Merge feat/process-modeler 阶段2: 表达式codec+EIP4侧板+存草稿闭环
Some checks failed
ci / build-test (push) Has been cancelled
Some checks failed
ci / build-test (push) Has been cancelled
- 办理人/会签表达式 codec(与 BasePropertiesConverter 逐字对齐+stringToJson引号映射防截断JUEL; 全库4794真实表达式往返实证零破坏) - EIP4 侧板五控件(办理人meta透传/会签保真读回isSequential+elementVariable+自定义完成条件/ formKey过滤/扩展属性/监听器field保留;切换节点无串台) - 存草稿闭环(三路径保eip4IdMap+首存回填modelId防刷新重复+草稿列表/删除/formKey过滤输入) - 全量 vitest 198+tsc+build 绿;live 验收总包合同交底存草稿→重开侧板忠实回显 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -95,6 +95,134 @@ interface RawOption {
|
|||||||
key?: unknown;
|
key?: unknown;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* formKey picker 的一条选项。数据源 `GET /api/workflow/wftemplates`(T2.2 网关端点),
|
||||||
|
* 契约 `{templates:[{id,name}],degraded?}`。id=view_wftemplate_id 裸 UUID(即 activiti:formKey
|
||||||
|
* 值,无前缀)。**T2.2 实证**:view_wftemplate 无名称列,网关按 entityid→sys_entity.name 解析,
|
||||||
|
* 1016 活动模板仅 ~339 有中文名,其余 name 回落为 id(uuid)——前端下拉需过滤 + 未命名展示。
|
||||||
|
*/
|
||||||
|
export interface WfTemplateOption {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** wftemplates 结果:degraded=数据源读库异常(网关返 {templates:[],degraded:true})。 */
|
||||||
|
export interface WfTemplateResult {
|
||||||
|
templates: WfTemplateOption[];
|
||||||
|
degraded: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** GET /api/workflow/wftemplates —— 取表单模板列表供 formKey 下拉(防御性;透传 degraded)。 */
|
||||||
|
export async function fetchWfTemplates(): Promise<WfTemplateResult> {
|
||||||
|
const { data } = await http.get<{ templates?: unknown[]; degraded?: boolean }>(
|
||||||
|
'/api/workflow/wftemplates',
|
||||||
|
);
|
||||||
|
const degraded = data?.degraded === true;
|
||||||
|
const raw = data?.templates ?? [];
|
||||||
|
if (!Array.isArray(raw)) return { templates: [], degraded };
|
||||||
|
const templates = 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 !== '');
|
||||||
|
return { templates, degraded };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 流程草稿(act_re_model)CRUD(T2.1 后端 + T2.2 网关,全走超管门;前端已登录 admin) ────
|
||||||
|
|
||||||
|
/** GET /api/workflow/models 列表项。 */
|
||||||
|
export interface ModelSummary {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
key: string;
|
||||||
|
lastUpdateTime?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** GET /api/workflow/models/{id} 单条草稿(含编辑源 XML 与 metaInfo JSON 串)。 */
|
||||||
|
export interface DraftModel {
|
||||||
|
found: boolean;
|
||||||
|
id?: string;
|
||||||
|
name?: string;
|
||||||
|
key?: string;
|
||||||
|
bpmnXml?: string;
|
||||||
|
/** metaInfo JSON 串,含 eip4IdMap/sourceProcDefId/originalKey(from-procdef 建的草稿有)。 */
|
||||||
|
metaInfo?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 新建草稿请求体。metaInfo 必带 eip4IdMap 以便发布还原中文 key(存量改造场景)。 */
|
||||||
|
export interface CreateDraftBody {
|
||||||
|
name: string;
|
||||||
|
key: string;
|
||||||
|
bpmnXml: string;
|
||||||
|
metaInfo?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** GET /api/workflow/models —— 草稿列表(防御性返回数组)。 */
|
||||||
|
export async function listModels(): Promise<ModelSummary[]> {
|
||||||
|
const { data } = await http.get<{ models?: unknown[] }>('/api/workflow/models');
|
||||||
|
const raw = data?.models ?? [];
|
||||||
|
if (!Array.isArray(raw)) return [];
|
||||||
|
return raw
|
||||||
|
.map((m) => {
|
||||||
|
const o = (m ?? {}) as { id?: unknown; name?: unknown; key?: unknown; lastUpdateTime?: unknown };
|
||||||
|
return {
|
||||||
|
id: o.id != null ? String(o.id) : '',
|
||||||
|
name: o.name != null ? String(o.name) : '',
|
||||||
|
key: o.key != null ? String(o.key) : '',
|
||||||
|
lastUpdateTime: o.lastUpdateTime != null ? String(o.lastUpdateTime) : undefined,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.filter((m) => m.id !== '');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** GET /api/workflow/models/{id} —— 取单条草稿(防御性 found:false)。 */
|
||||||
|
export async function getModel(id: string): Promise<DraftModel> {
|
||||||
|
const { data } = await http.get<DraftModel>(`/api/workflow/models/${encodeURIComponent(id)}`);
|
||||||
|
if (!data?.found) return { found: false };
|
||||||
|
return {
|
||||||
|
found: true,
|
||||||
|
id: data.id != null ? String(data.id) : undefined,
|
||||||
|
name: data.name != null ? String(data.name) : undefined,
|
||||||
|
key: data.key != null ? String(data.key) : undefined,
|
||||||
|
bpmnXml: data.bpmnXml ?? undefined,
|
||||||
|
metaInfo: data.metaInfo ?? undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** POST /api/workflow/models —— 新建草稿,返回 modelId。 */
|
||||||
|
export async function createDraft(body: CreateDraftBody): Promise<string> {
|
||||||
|
const { data } = await http.post<{ modelId?: unknown }>('/api/workflow/models', body);
|
||||||
|
return data?.modelId != null ? String(data.modelId) : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PUT /api/workflow/models/{id} —— 保存草稿(更新 name/编辑源)。
|
||||||
|
* ⚠️ 刻意不传 metaInfo 键:后端 T2.1「不带 metaInfo 不覆盖」保住 from-procdef/create 时写入的
|
||||||
|
* eip4IdMap,避免二次保存打掉发布还原所需的映射。
|
||||||
|
*/
|
||||||
|
export async function saveDraft(id: string, body: { name?: string; bpmnXml: string }): Promise<void> {
|
||||||
|
await http.put(`/api/workflow/models/${encodeURIComponent(id)}`, body);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** POST /api/workflow/models/from-procdef —— 由 procDefId 建草稿(后端净化+写 metaInfo),返回 modelId。 */
|
||||||
|
export async function draftFromProcDef(procDefId: string): Promise<string> {
|
||||||
|
const { data } = await http.post<{ modelId?: unknown }>('/api/workflow/models/from-procdef', {
|
||||||
|
procDefId,
|
||||||
|
});
|
||||||
|
return data?.modelId != null ? String(data.modelId) : '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* DELETE /api/workflow/models/{id} —— 删除草稿。
|
||||||
|
* 后端已实现(flowable-service DELETE /api/flow/models/{id} + 网关同超管门转发,f0d704d)。
|
||||||
|
*/
|
||||||
|
export async function deleteDraft(id: string): Promise<void> {
|
||||||
|
await http.delete(`/api/workflow/models/${encodeURIComponent(id)}`);
|
||||||
|
}
|
||||||
|
|
||||||
/** GET /api/process-select/options —— 取存量流程选项(解 amis 信封,防御性返回数组)。 */
|
/** GET /api/process-select/options —— 取存量流程选项(解 amis 信封,防御性返回数组)。 */
|
||||||
export async function fetchProcessOptions(q?: string): Promise<ProcessOption[]> {
|
export async function fetchProcessOptions(q?: string): Promise<ProcessOption[]> {
|
||||||
const { data } = await http.get<ProcessSelectEnvelope>('/api/process-select/options', {
|
const { data } = await http.get<ProcessSelectEnvelope>('/api/process-select/options', {
|
||||||
|
|||||||
629
src/modeler/Eip4Panel.test.tsx
Normal file
629
src/modeler/Eip4Panel.test.tsx
Normal file
@@ -0,0 +1,629 @@
|
|||||||
|
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,
|
||||||
|
buildCandidateExpression,
|
||||||
|
type UserPropertyItem,
|
||||||
|
} from './candidateExpression';
|
||||||
|
|
||||||
|
// formKey 下拉数据源:mock,其中一个 id 对齐 fixture 的 formKey 值;第三项 name===id(未命名)。
|
||||||
|
vi.mock('../api/processModeler', () => ({
|
||||||
|
fetchWfTemplates: vi.fn(() =>
|
||||||
|
Promise.resolve({
|
||||||
|
templates: [
|
||||||
|
{ id: '2098ce21-400b-4425-9c22-63e350974b98', name: '合同交底表单' },
|
||||||
|
{ id: 'aaaa-bbbb', name: '另一个表单' },
|
||||||
|
{ id: 'deadbeef-1111-2222', name: 'deadbeef-1111-2222' }, // 未命名(name 回落为 id)
|
||||||
|
],
|
||||||
|
degraded: false,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { Eip4Panel } from './Eip4Panel';
|
||||||
|
import { fetchWfTemplates } from '../api/processModeler';
|
||||||
|
const mWfTemplates = vi.mocked(fetchWfTemplates);
|
||||||
|
|
||||||
|
// ── 真实办理人形态锚定(同 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 selHandler: ((e: unknown) => void) | null = null;
|
||||||
|
let cmdHandler: (() => void) | null = null;
|
||||||
|
const updateProperties = vi.fn();
|
||||||
|
const created: Array<Record<string, unknown>> = [];
|
||||||
|
const moddle = {
|
||||||
|
create: vi.fn((type: string, props: Record<string, unknown> = {}) => {
|
||||||
|
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') selHandler = cb;
|
||||||
|
if (ev === 'commandStack.changed') cmdHandler = cb as () => void;
|
||||||
|
});
|
||||||
|
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 () => {
|
||||||
|
selHandler?.({ newSelection: element ? [element] : [] });
|
||||||
|
await Promise.resolve();
|
||||||
|
await Promise.resolve();
|
||||||
|
});
|
||||||
|
// 模拟外部 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<typeof vi.spyOn>;
|
||||||
|
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=原始扩展属性袋。 */
|
||||||
|
function userTask(map: Record<string, unknown> = {}, $attrs?: Record<string, string>) {
|
||||||
|
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<string, unknown>) {
|
||||||
|
return { $type: type, ...props, get: (n: string) => props[n] };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 取最后一次 updateProperties 载荷。 */
|
||||||
|
function lastPayload(updateProperties: ReturnType<typeof vi.fn>): Record<string, unknown> {
|
||||||
|
const calls = updateProperties.mock.calls;
|
||||||
|
return calls[calls.length - 1][1] as Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Eip4Panel — 选择状态', () => {
|
||||||
|
it('未选中任何节点时提示选择', async () => {
|
||||||
|
const { modeler } = makeModeler();
|
||||||
|
render(<Eip4Panel modeler={modeler} />);
|
||||||
|
expect(screen.getByText(/请选择/)).toBeInTheDocument();
|
||||||
|
// flush 挂载期 fetchWfTemplates 的 setState(避免 act 告警)
|
||||||
|
await act(async () => {
|
||||||
|
await Promise.resolve();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('选中非 userTask 显示简短提示,不渲染办理人控件', async () => {
|
||||||
|
const { modeler, select } = makeModeler();
|
||||||
|
render(<Eip4Panel modeler={modeler} />);
|
||||||
|
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(<Eip4Panel modeler={modeler} />);
|
||||||
|
await select(userTask());
|
||||||
|
expect(screen.getByText(/引擎以本控件为准/)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('set:改 content 写回 activiti:candidateUsers(可被 codec 解析)', async () => {
|
||||||
|
const { modeler, updateProperties, select } = makeModeler();
|
||||||
|
render(<Eip4Panel modeler={modeler} />);
|
||||||
|
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(<Eip4Panel modeler={modeler} />);
|
||||||
|
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('清空最后一行(meta 为空):无 confirm,直接写回 undefined', async () => {
|
||||||
|
const { modeler, updateProperties, select } = makeModeler();
|
||||||
|
render(<Eip4Panel modeler={modeler} />);
|
||||||
|
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(<Eip4Panel modeler={modeler} />);
|
||||||
|
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();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('I-3 清空含非空业务 meta:confirm=取消 → 不写回、行仍在', async () => {
|
||||||
|
const { modeler, updateProperties, select } = makeModeler();
|
||||||
|
confirmSpy.mockReturnValue(false);
|
||||||
|
render(<Eip4Panel modeler={modeler} />);
|
||||||
|
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(<Eip4Panel modeler={modeler} />);
|
||||||
|
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(<Eip4Panel modeler={modeler} />);
|
||||||
|
await select(userTask({ 'activiti:candidateUsers': '${someOtherExpr(execution)}' }));
|
||||||
|
expect(screen.getByTestId('eip4-candidate-nonstandard')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('增行:改 type 下拉写回对应 type', async () => {
|
||||||
|
const { modeler, updateProperties, select } = makeModeler();
|
||||||
|
render(<Eip4Panel modeler={modeler} />);
|
||||||
|
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}' });
|
||||||
|
});
|
||||||
|
|
||||||
|
// codec build 对叶子值应用引擎 stringToJson 转义(' → ‘、" → “),防用户输入含撇号/双引号
|
||||||
|
// 截断外层 JUEL 单引号字面量或内层 JSON。侧板消费 codec 即受保护——断言写回载荷的内容段
|
||||||
|
// (剥离 JUEL 前后缀定界引号后)无裸 ASCII 撇号、有全角‘。
|
||||||
|
it("content 含撇号 O'Brien:写回载荷转义为‘、内容段无裸单引号(防截断 JUEL 字面量)", async () => {
|
||||||
|
const { modeler, updateProperties, select } = makeModeler();
|
||||||
|
render(<Eip4Panel modeler={modeler} />);
|
||||||
|
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)', () => {
|
||||||
|
it('开:载荷含 loopCharacteristics(collection multiInstance 前缀+elementVariable+completionCondition 全票预设)', async () => {
|
||||||
|
const { modeler, updateProperties, select } = makeModeler();
|
||||||
|
render(<Eip4Panel modeler={modeler} />);
|
||||||
|
await select(userTask());
|
||||||
|
fireEvent.click(screen.getByTestId('eip4-cosign-toggle'));
|
||||||
|
const loop = lastPayload(updateProperties).loopCharacteristics as Record<string, unknown>;
|
||||||
|
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(<Eip4Panel modeler={modeler} />);
|
||||||
|
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(<Eip4Panel modeler={modeler} />);
|
||||||
|
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<string, unknown>;
|
||||||
|
expect((loop.completionCondition as { body: string }).body).toBe(
|
||||||
|
'${nrOfCompletedInstances>=3}',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('过半预设:body 为 >0.5', async () => {
|
||||||
|
const { modeler, updateProperties, select } = makeModeler();
|
||||||
|
render(<Eip4Panel modeler={modeler} />);
|
||||||
|
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<string, unknown>;
|
||||||
|
expect((loop.completionCondition as { body: string }).body).toBe(
|
||||||
|
'${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(<Eip4Panel modeler={modeler} />);
|
||||||
|
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<string, unknown>;
|
||||||
|
expect(loop.isSequential).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('I-1 elementVariable=assign 往返保 assign(不被强写 assignee)', async () => {
|
||||||
|
const { modeler, updateProperties, select } = makeModeler();
|
||||||
|
render(<Eip4Panel modeler={modeler} />);
|
||||||
|
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<string, unknown>;
|
||||||
|
expect(loop['activiti:elementVariable']).toBe('assign');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('I-1 非预设完成条件 >0.6 不被归一为全票(自定义态保留原 body)', async () => {
|
||||||
|
const { modeler, updateProperties, select } = makeModeler();
|
||||||
|
render(<Eip4Panel modeler={modeler} />);
|
||||||
|
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<string, unknown>;
|
||||||
|
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(<Eip4Panel modeler={modeler} />);
|
||||||
|
await select(userTask({ loopCharacteristics: loop }));
|
||||||
|
fireEvent.change(screen.getByTestId('eip4-cosign-content-0'), { target: { value: 'x' } });
|
||||||
|
const written = lastPayload(updateProperties).loopCharacteristics as Record<string, unknown>;
|
||||||
|
expect('activiti:elementVariable' in written).toBe(false); // 缺省态不写
|
||||||
|
expect('completionCondition' in written).toBe(false); // 原本无完成条件不发出
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Eip4Panel — formKey', () => {
|
||||||
|
it('选择模板 → 写回 activiti:formKey=裸 UUID', async () => {
|
||||||
|
const { modeler, updateProperties, select } = makeModeler();
|
||||||
|
render(<Eip4Panel modeler={modeler} />);
|
||||||
|
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(<Eip4Panel modeler={modeler} />);
|
||||||
|
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();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('过滤输入实时 filter 选项(名称匹配)', async () => {
|
||||||
|
const { modeler, select } = makeModeler();
|
||||||
|
render(<Eip4Panel modeler={modeler} />);
|
||||||
|
await select(userTask());
|
||||||
|
const sel = await screen.findByTestId('eip4-formkey-select');
|
||||||
|
await waitFor(() => expect(sel.querySelectorAll('option').length).toBeGreaterThan(3)); // (无)+3
|
||||||
|
fireEvent.change(screen.getByTestId('eip4-formkey-filter'), { target: { value: '合同' } });
|
||||||
|
const opts = Array.from(sel.querySelectorAll('option')).map((o) => o.textContent);
|
||||||
|
expect(opts).toContain('合同交底表单');
|
||||||
|
expect(opts).not.toContain('另一个表单');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('未命名项(name===id)显示「<uuid前8>…(未命名)」', async () => {
|
||||||
|
const { modeler, select } = makeModeler();
|
||||||
|
render(<Eip4Panel modeler={modeler} />);
|
||||||
|
await select(userTask());
|
||||||
|
const sel = await screen.findByTestId('eip4-formkey-select');
|
||||||
|
await waitFor(() => expect(sel.querySelectorAll('option').length).toBeGreaterThan(3));
|
||||||
|
const opts = Array.from(sel.querySelectorAll('option')).map((o) => o.textContent);
|
||||||
|
expect(opts).toContain('deadbeef…(未命名)');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('degraded:显示「模板列表暂不可用」提示', async () => {
|
||||||
|
mWfTemplates.mockResolvedValueOnce({ templates: [], degraded: true });
|
||||||
|
const { modeler, select } = makeModeler();
|
||||||
|
render(<Eip4Panel modeler={modeler} />);
|
||||||
|
await select(userTask());
|
||||||
|
expect(await screen.findByTestId('eip4-formkey-degraded')).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('过滤掉当前值后 select 仍保留该值(占位「(当前)」防丢值)', async () => {
|
||||||
|
const { modeler, select } = makeModeler();
|
||||||
|
render(<Eip4Panel modeler={modeler} />);
|
||||||
|
await select(userTask({ 'activiti:formKey': 'aaaa-bbbb' })); // 当前值=另一个表单
|
||||||
|
const sel = (await screen.findByTestId('eip4-formkey-select')) as HTMLSelectElement;
|
||||||
|
await waitFor(() => expect(sel.querySelectorAll('option').length).toBeGreaterThan(3));
|
||||||
|
// 过滤到「合同」→ aaaa-bbbb(另一个表单)被过滤掉
|
||||||
|
fireEvent.change(screen.getByTestId('eip4-formkey-filter'), { target: { value: '合同' } });
|
||||||
|
expect(sel.value).toBe('aaaa-bbbb'); // 值未丢
|
||||||
|
const cur = Array.from(sel.querySelectorAll('option')).find(
|
||||||
|
(o) => (o as HTMLOptionElement).value === 'aaaa-bbbb',
|
||||||
|
);
|
||||||
|
expect(cur).toBeTruthy();
|
||||||
|
expect(cur!.textContent).toContain('(当前)');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Eip4Panel — 扩展属性(长尾 $attrs)', () => {
|
||||||
|
it('增:填 key/value 后写回命名空间键', async () => {
|
||||||
|
const { modeler, updateProperties, select } = makeModeler();
|
||||||
|
render(<Eip4Panel modeler={modeler} />);
|
||||||
|
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(<Eip4Panel modeler={modeler} />);
|
||||||
|
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(<Eip4Panel modeler={modeler} />);
|
||||||
|
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();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('顺手:无 activiti:/flowable: 前缀的新键被拒(不写回)', async () => {
|
||||||
|
const { modeler, updateProperties, select } = makeModeler();
|
||||||
|
render(<Eip4Panel modeler={modeler} />);
|
||||||
|
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(<Eip4Panel modeler={modeler} />);
|
||||||
|
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)', () => {
|
||||||
|
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(<Eip4Panel modeler={modeler} />);
|
||||||
|
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<Record<string, unknown>> };
|
||||||
|
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(<Eip4Panel modeler={modeler} />);
|
||||||
|
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<Record<string, unknown>> };
|
||||||
|
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(<Eip4Panel modeler={modeler} />);
|
||||||
|
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(<Eip4Panel modeler={modeler} />);
|
||||||
|
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<Record<string, unknown>> };
|
||||||
|
const listener = ext.values.find((v) => v.$type === 'activiti:taskListener')!;
|
||||||
|
expect(listener.delegateExpression).toBe('${bean}');
|
||||||
|
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(<Eip4Panel modeler={modeler} />);
|
||||||
|
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<string, unknown> = {
|
||||||
|
'activiti:candidateUsers': buildCandidateExpression([item('X')], 'candidate', {}),
|
||||||
|
};
|
||||||
|
const el = {
|
||||||
|
id: 't1',
|
||||||
|
type: 'bpmn:UserTask',
|
||||||
|
businessObject: { $type: 'bpmn:UserTask', get: (n: string) => map[n] },
|
||||||
|
};
|
||||||
|
render(<Eip4Panel modeler={modeler} />);
|
||||||
|
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');
|
||||||
|
});
|
||||||
|
});
|
||||||
802
src/modeler/Eip4Panel.tsx
Normal file
802
src/modeler/Eip4Panel.tsx
Normal file
@@ -0,0 +1,802 @@
|
|||||||
|
// EIP4 定制侧板:选中 userTask 时叠加办理人/会签/formKey/扩展属性/任务监听器五控件。
|
||||||
|
//
|
||||||
|
// 设计要点(计划 T2.4 + §0.5 P5 + 评审收口):
|
||||||
|
// - 全部写操作经 bpmn-js `modeling.updateProperties(element,{...})`,undo/redo 天然生效。
|
||||||
|
// - 办理人/会签共用 items 编辑器(ItemsEditor),表达式编解码走 candidateExpression codec。
|
||||||
|
// - 🔴 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,
|
||||||
|
parseCandidateExpression,
|
||||||
|
type CandidateVariant,
|
||||||
|
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';
|
||||||
|
|
||||||
|
// ── bpmn-js 服务契约(最小) ───────────────────────────────────────────────────
|
||||||
|
interface Modeling {
|
||||||
|
updateProperties(element: BpmnElement, props: Record<string, unknown>): void;
|
||||||
|
}
|
||||||
|
interface Moddle {
|
||||||
|
create(type: string, props?: Record<string, unknown>): Record<string, unknown>;
|
||||||
|
}
|
||||||
|
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'];
|
||||||
|
|
||||||
|
// 有专用控件的属性,禁止再从「扩展属性」兜底编辑器写入(去重、防冲突)。
|
||||||
|
const RESERVED_EXT_LOCALNAMES = new Set(['candidateUsers', 'formKey', 'collection', 'elementVariable']);
|
||||||
|
|
||||||
|
// ── 会签完成条件预设 ─────────────────────────────────────────────────────────
|
||||||
|
type CompletionType = 'all' | 'majority' | 'count' | 'custom';
|
||||||
|
const COMPLETION_ALL = '${nrOfCompletedInstances/nrOfInstances==1}';
|
||||||
|
const COMPLETION_MAJORITY = '${nrOfCompletedInstances/nrOfInstances>0.5}';
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
// 精确匹配预设串(不用子串,否则 >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) 与直读属性) ──────────────────────────────────
|
||||||
|
function mget(obj: unknown, name: string): unknown {
|
||||||
|
if (!obj || typeof obj !== 'object') return undefined;
|
||||||
|
const o = obj as Record<string, unknown> & { get?: (n: string) => unknown };
|
||||||
|
if (typeof o.get === 'function') return o.get(name);
|
||||||
|
return o[name];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 非空业务 meta → 只读徽标/确认文案(用于「删光办理人会一并移除 X」)。
|
||||||
|
function notableMeta(meta: Record<string, unknown>): 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// formKey 下拉展示名:网关无名称时 name 回落为 id(uuid),未命名项显示「<uuid前8>…(未命名)」。
|
||||||
|
function wfTemplateLabel(t: WfTemplateOption): string {
|
||||||
|
if (t.name && t.name !== t.id) return t.name;
|
||||||
|
return (t.id.length > 8 ? t.id.slice(0, 8) : t.id) + '…(未命名)';
|
||||||
|
}
|
||||||
|
|
||||||
|
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[];
|
||||||
|
/** 保真:串行/并行,读回原值(真实库有 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,
|
||||||
|
items,
|
||||||
|
onChange,
|
||||||
|
}: {
|
||||||
|
idPrefix: string;
|
||||||
|
items: UserPropertyItem[];
|
||||||
|
onChange: (next: UserPropertyItem[]) => void;
|
||||||
|
}) {
|
||||||
|
const patch = (i: number, p: Partial<UserPropertyItem>) =>
|
||||||
|
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 (
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
|
||||||
|
{items.map((it, i) => (
|
||||||
|
<div
|
||||||
|
key={i}
|
||||||
|
style={{
|
||||||
|
border: '1px solid var(--line)',
|
||||||
|
borderRadius: 4,
|
||||||
|
padding: 6,
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
gap: 4,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div style={{ display: 'flex', gap: 4 }}>
|
||||||
|
<select
|
||||||
|
data-testid={`${idPrefix}-type-${i}`}
|
||||||
|
value={it.type}
|
||||||
|
onChange={(e) => patch(i, { type: e.target.value })}
|
||||||
|
style={{ flex: '0 0 120px' }}
|
||||||
|
>
|
||||||
|
{CANDIDATE_TYPES.map((t) => (
|
||||||
|
<option key={t.value} value={t.value}>
|
||||||
|
{t.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<input
|
||||||
|
data-testid={`${idPrefix}-content-${i}`}
|
||||||
|
value={it.content}
|
||||||
|
placeholder="人员/部门/岗位 id 或表达式"
|
||||||
|
onChange={(e) => patch(i, { content: e.target.value })}
|
||||||
|
style={{ flex: 1, minWidth: 0 }}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
className="btn btn-sm"
|
||||||
|
data-testid={`${idPrefix}-remove-${i}`}
|
||||||
|
onClick={() => remove(i)}
|
||||||
|
title="删除该行"
|
||||||
|
>
|
||||||
|
删
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', fontSize: 12 }}>
|
||||||
|
<label>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
data-testid={`${idPrefix}-iscandidate-${i}`}
|
||||||
|
checked={!!it.isCandidate}
|
||||||
|
onChange={(e) => patch(i, { isCandidate: e.target.checked })}
|
||||||
|
/>{' '}
|
||||||
|
候选
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
data-testid={`${idPrefix}-mail-${i}`}
|
||||||
|
checked={!!it.isSendMail}
|
||||||
|
onChange={(e) => patch(i, { isSendMail: e.target.checked })}
|
||||||
|
/>{' '}
|
||||||
|
邮件
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
data-testid={`${idPrefix}-phone-${i}`}
|
||||||
|
checked={!!it.isSendPhone}
|
||||||
|
onChange={(e) => patch(i, { isSendPhone: e.target.checked })}
|
||||||
|
/>{' '}
|
||||||
|
短信
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
data-testid={`${idPrefix}-msg-${i}`}
|
||||||
|
checked={!!it.isSendMessage}
|
||||||
|
onChange={(e) => patch(i, { isSendMessage: e.target.checked })}
|
||||||
|
/>{' '}
|
||||||
|
站内
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<button className="btn btn-sm" data-testid={`${idPrefix}-add`} onClick={add}>
|
||||||
|
+ 添加办理人
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Section({ title, children }: { title: string; children: React.ReactNode }) {
|
||||||
|
return (
|
||||||
|
<div style={{ borderBottom: '1px solid var(--line)', padding: '10px 12px' }}>
|
||||||
|
<div style={{ fontWeight: 600, fontSize: 13, marginBottom: 8 }}>{title}</div>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
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';
|
||||||
|
|
||||||
|
// ── 本地编辑态(选中变更 / undo-redo 时从 businessObject 重新初始化) ─────────
|
||||||
|
const [candidateItems, setCandidateItems] = useState<UserPropertyItem[]>([]);
|
||||||
|
const [candidateMeta, setCandidateMeta] = useState<Record<string, unknown>>({});
|
||||||
|
const [candidateNonStandard, setCandidateNonStandard] = useState(false);
|
||||||
|
const [cosign, setCosign] = useState<CosignState>(FRESH_COSIGN);
|
||||||
|
const [cosignMeta, setCosignMeta] = useState<Record<string, unknown>>({});
|
||||||
|
const [formKey, setFormKey] = useState('');
|
||||||
|
const [extAttrs, setExtAttrs] = useState<Array<{ key: string; value: string }>>([]);
|
||||||
|
const [newAttr, setNewAttr] = useState<{ key: string; value: string }>({ key: '', value: '' });
|
||||||
|
const [listeners, setListeners] = useState<ListenerRow[]>([]);
|
||||||
|
const [templates, setTemplates] = useState<WfTemplateOption[]>([]);
|
||||||
|
const [templatesDegraded, setTemplatesDegraded] = useState(false);
|
||||||
|
const [formKeyFilter, setFormKeyFilter] = useState('');
|
||||||
|
// undo/redo 重灌计数:commandStack.changed(非自身写入)时自增,触发 init 重跑。
|
||||||
|
const [syncTick, setSyncTick] = useState(0);
|
||||||
|
|
||||||
|
// 非 taskListener 的扩展元素(formProperty 等)原样保留(引用不动)。
|
||||||
|
const otherExtRef = useRef<unknown[]>([]);
|
||||||
|
// 自身写入标记:updateProperties 会触发 commandStack.changed,借此跳过自触发重灌。
|
||||||
|
const selfWriteRef = useRef(false);
|
||||||
|
|
||||||
|
// formKey 数据源加载一次(透传 degraded;1016 项靠过滤输入,不裸滚动)。
|
||||||
|
useEffect(() => {
|
||||||
|
let alive = true;
|
||||||
|
Promise.resolve(fetchWfTemplates())
|
||||||
|
.then((r) => {
|
||||||
|
if (!alive) return;
|
||||||
|
setTemplates(Array.isArray(r?.templates) ? r.templates : []);
|
||||||
|
setTemplatesDegraded(!!r?.degraded);
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
if (!alive) return;
|
||||||
|
setTemplates([]);
|
||||||
|
setTemplatesDegraded(true);
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
alive = false;
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// 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([]);
|
||||||
|
setCandidateMeta({});
|
||||||
|
setCandidateNonStandard(false);
|
||||||
|
setCosign(FRESH_COSIGN);
|
||||||
|
setCosignMeta({});
|
||||||
|
setFormKey('');
|
||||||
|
setExtAttrs([]);
|
||||||
|
setNewAttr({ key: '', value: '' });
|
||||||
|
setListeners([]);
|
||||||
|
otherExtRef.current = [];
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const bo = element.businessObject;
|
||||||
|
|
||||||
|
// 办理人
|
||||||
|
const rawCand = bo.get('activiti:candidateUsers') as string | undefined;
|
||||||
|
const cand = parseCandidateExpression(rawCand);
|
||||||
|
setCandidateItems(cand?.items ?? []);
|
||||||
|
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,
|
||||||
|
);
|
||||||
|
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,
|
||||||
|
});
|
||||||
|
setCosignMeta(parsed?.meta ?? {});
|
||||||
|
} else {
|
||||||
|
setCosign(FRESH_COSIGN);
|
||||||
|
setCosignMeta({});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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, syncTick]);
|
||||||
|
|
||||||
|
function update(props: Record<string, unknown>) {
|
||||||
|
if (element && modeling) {
|
||||||
|
selfWriteRef.current = true;
|
||||||
|
modeling.updateProperties(element, props);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 办理人写回 ─────────────────────────────────────────────────────────────
|
||||||
|
function writeCandidate(items: UserPropertyItem[]) {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
setCandidateItems(items);
|
||||||
|
update({ 'activiti:candidateUsers': buildCandidateExpression(items, 'candidate', candidateMeta) });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 会签写回 ───────────────────────────────────────────────────────────────
|
||||||
|
function writeCosign(next: CosignState) {
|
||||||
|
setCosign(next);
|
||||||
|
if (!next.enabled) {
|
||||||
|
update({ loopCharacteristics: undefined });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!moddle) return;
|
||||||
|
const collection = buildCandidateExpression(
|
||||||
|
next.items,
|
||||||
|
'multiInstance' as CandidateVariant,
|
||||||
|
cosignMeta,
|
||||||
|
);
|
||||||
|
const props: Record<string, unknown> = {
|
||||||
|
isSequential: next.isSequential,
|
||||||
|
'activiti:collection': collection,
|
||||||
|
};
|
||||||
|
// 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 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── formKey 写回 ───────────────────────────────────────────────────────────
|
||||||
|
function writeFormKey(value: string) {
|
||||||
|
setFormKey(value);
|
||||||
|
update({ 'activiti:formKey': value === '' ? undefined : value });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 扩展属性写回 ───────────────────────────────────────────────────────────
|
||||||
|
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 }];
|
||||||
|
});
|
||||||
|
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<string, unknown> = { 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<ListenerRow>) {
|
||||||
|
writeListeners(listeners.map((l, idx) => (idx === i ? { ...l, ...p } : l)));
|
||||||
|
}
|
||||||
|
function removeListener(i: number) {
|
||||||
|
writeListeners(listeners.filter((_, idx) => idx !== i));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 渲染 ───────────────────────────────────────────────────────────────────
|
||||||
|
if (!element) {
|
||||||
|
return (
|
||||||
|
<div data-testid="process-modeler-eip4-panel" style={hintStyle}>
|
||||||
|
请选择一个用户任务节点以编辑 EIP4 属性。
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!isUserTask) {
|
||||||
|
return (
|
||||||
|
<div data-testid="process-modeler-eip4-panel" style={hintStyle}>
|
||||||
|
选中的不是用户任务节点。EIP4 定制控件仅对用户任务(办理人 / 会签 / formKey)可用。
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const candidateBadges = notableMeta(candidateMeta);
|
||||||
|
const formKeyQuery = formKeyFilter.trim().toLowerCase();
|
||||||
|
const filteredTemplates = formKeyQuery
|
||||||
|
? templates.filter(
|
||||||
|
(t) => t.name.toLowerCase().includes(formKeyQuery) || t.id.toLowerCase().includes(formKeyQuery),
|
||||||
|
)
|
||||||
|
: templates;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-testid="process-modeler-eip4-panel"
|
||||||
|
style={{ overflow: 'auto', maxHeight: '55%', borderBottom: '1px solid var(--line)' }}
|
||||||
|
>
|
||||||
|
<div style={{ padding: '8px 12px', fontSize: 12, color: 'var(--text-3)', background: 'var(--surface-2, #fafafa)' }}>
|
||||||
|
EIP4 引擎以本控件为准,下方标准面板原生字段仅供高级调试。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Section title="办理人">
|
||||||
|
{candidateBadges.length > 0 ? (
|
||||||
|
<div
|
||||||
|
data-testid="eip4-candidate-meta-badge"
|
||||||
|
style={{ fontSize: 12, color: 'var(--text-2)', marginBottom: 8, lineHeight: 1.6 }}
|
||||||
|
>
|
||||||
|
含业务配置:{candidateBadges.join('、')}(清空办理人会一并移除)
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
{candidateNonStandard ? (
|
||||||
|
<div
|
||||||
|
data-testid="eip4-candidate-nonstandard"
|
||||||
|
style={{ fontSize: 12, color: 'var(--warn, #d48806)', marginBottom: 8 }}
|
||||||
|
>
|
||||||
|
当前为非标准办理人表达式,编辑将覆盖原表达式。
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
<ItemsEditor idPrefix="eip4-candidate" items={candidateItems} onChange={writeCandidate} />
|
||||||
|
</Section>
|
||||||
|
|
||||||
|
<Section title="会签(多实例)">
|
||||||
|
<label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, marginBottom: 8 }}>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
data-testid="eip4-cosign-toggle"
|
||||||
|
checked={cosign.enabled}
|
||||||
|
onChange={(e) => writeCosign({ ...cosign, enabled: e.target.checked })}
|
||||||
|
/>
|
||||||
|
启用会签
|
||||||
|
</label>
|
||||||
|
{cosign.enabled ? (
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
|
||||||
|
<label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13 }}>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
data-testid="eip4-cosign-sequential"
|
||||||
|
checked={cosign.isSequential}
|
||||||
|
onChange={(e) => writeCosign({ ...cosign, isSequential: e.target.checked })}
|
||||||
|
/>
|
||||||
|
串行(顺序会签)
|
||||||
|
</label>
|
||||||
|
<label style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13 }}>
|
||||||
|
<span style={{ flex: '0 0 auto' }}>循环变量</span>
|
||||||
|
<input
|
||||||
|
data-testid="eip4-cosign-element-variable"
|
||||||
|
value={cosign.elementVariable}
|
||||||
|
placeholder="assignee"
|
||||||
|
onChange={(e) => writeCosign({ ...cosign, elementVariable: e.target.value })}
|
||||||
|
style={{ flex: 1, minWidth: 0 }}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<ItemsEditor
|
||||||
|
idPrefix="eip4-cosign"
|
||||||
|
items={cosign.items}
|
||||||
|
onChange={(items) => writeCosign({ ...cosign, items })}
|
||||||
|
/>
|
||||||
|
<div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, flexWrap: 'wrap' }}>
|
||||||
|
<span>完成条件</span>
|
||||||
|
<select
|
||||||
|
data-testid="eip4-cosign-completion-type"
|
||||||
|
value={cosign.completionType}
|
||||||
|
onChange={(e) =>
|
||||||
|
writeCosign({ ...cosign, completionType: e.target.value as CompletionType })
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{/* 自定义(保留)仅在当前为自定义态时可选中——presets 不提供切到自定义,防误清 */}
|
||||||
|
{cosign.completionType === 'custom' ? (
|
||||||
|
<option value="custom">自定义(保留)</option>
|
||||||
|
) : null}
|
||||||
|
<option value="all">全票通过</option>
|
||||||
|
<option value="majority">过半通过</option>
|
||||||
|
<option value="count">指定数</option>
|
||||||
|
</select>
|
||||||
|
{cosign.completionType === 'count' ? (
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min={1}
|
||||||
|
data-testid="eip4-cosign-completion-n"
|
||||||
|
value={cosign.completionN}
|
||||||
|
onChange={(e) =>
|
||||||
|
writeCosign({ ...cosign, completionN: Number(e.target.value) || 1 })
|
||||||
|
}
|
||||||
|
style={{ width: 64 }}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
{cosign.completionType === 'custom' ? (
|
||||||
|
<span
|
||||||
|
data-testid="eip4-cosign-completion-custom"
|
||||||
|
style={{ fontSize: 12, color: 'var(--text-3)' }}
|
||||||
|
>
|
||||||
|
当前条件:<code>{cosign.completionCustomBody || '(无)'}</code>
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</Section>
|
||||||
|
|
||||||
|
<Section title="表单(formKey)">
|
||||||
|
{templatesDegraded ? (
|
||||||
|
<div
|
||||||
|
data-testid="eip4-formkey-degraded"
|
||||||
|
style={{ fontSize: 12, color: 'var(--warn, #d48806)', marginBottom: 6 }}
|
||||||
|
>
|
||||||
|
模板列表暂不可用(数据源异常);可保留当前值或稍后重试。
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
<input
|
||||||
|
data-testid="eip4-formkey-filter"
|
||||||
|
placeholder={`筛选表单(名称或 id,共 ${templates.length} 项)`}
|
||||||
|
value={formKeyFilter}
|
||||||
|
onChange={(e) => setFormKeyFilter(e.target.value)}
|
||||||
|
style={{ width: '100%', marginBottom: 6 }}
|
||||||
|
/>
|
||||||
|
<select
|
||||||
|
data-testid="eip4-formkey-select"
|
||||||
|
value={formKey}
|
||||||
|
onChange={(e) => writeFormKey(e.target.value)}
|
||||||
|
style={{ width: '100%' }}
|
||||||
|
>
|
||||||
|
<option value="">(无)</option>
|
||||||
|
{/* 当前值不在(过滤后的)模板列表时,补一条占位以免下拉丢值 */}
|
||||||
|
{formKey && !filteredTemplates.some((t) => t.id === formKey) ? (
|
||||||
|
<option value={formKey}>
|
||||||
|
{(() => {
|
||||||
|
const cur = templates.find((t) => t.id === formKey);
|
||||||
|
return (cur ? wfTemplateLabel(cur) : formKey) + '(当前)';
|
||||||
|
})()}
|
||||||
|
</option>
|
||||||
|
) : null}
|
||||||
|
{filteredTemplates.map((t) => (
|
||||||
|
<option key={t.id} value={t.id}>
|
||||||
|
{wfTemplateLabel(t)}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</Section>
|
||||||
|
|
||||||
|
<Section title="扩展属性(activiti/flowable)">
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
|
||||||
|
{extAttrs.map((a, i) => (
|
||||||
|
<div key={a.key} style={{ display: 'flex', gap: 4 }}>
|
||||||
|
<input
|
||||||
|
data-testid={`eip4-extattr-key-${i}`}
|
||||||
|
value={a.key}
|
||||||
|
readOnly
|
||||||
|
style={{ flex: '0 0 130px', minWidth: 0 }}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
data-testid={`eip4-extattr-value-${i}`}
|
||||||
|
value={a.value}
|
||||||
|
onChange={(e) => editExtAttr(a.key, e.target.value)}
|
||||||
|
style={{ flex: 1, minWidth: 0 }}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
className="btn btn-sm"
|
||||||
|
data-testid={`eip4-extattr-remove-${i}`}
|
||||||
|
onClick={() => removeExtAttr(a.key)}
|
||||||
|
>
|
||||||
|
删
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<div style={{ display: 'flex', gap: 4 }}>
|
||||||
|
<input
|
||||||
|
data-testid="eip4-extattr-new-key"
|
||||||
|
placeholder="activiti:key"
|
||||||
|
value={newAttr.key}
|
||||||
|
onChange={(e) => setNewAttr((s) => ({ ...s, key: e.target.value }))}
|
||||||
|
style={{ flex: '0 0 130px', minWidth: 0 }}
|
||||||
|
/>
|
||||||
|
<input
|
||||||
|
data-testid="eip4-extattr-new-value"
|
||||||
|
placeholder="value"
|
||||||
|
value={newAttr.value}
|
||||||
|
onChange={(e) => setNewAttr((s) => ({ ...s, value: e.target.value }))}
|
||||||
|
style={{ flex: 1, minWidth: 0 }}
|
||||||
|
/>
|
||||||
|
<button className="btn btn-sm" data-testid="eip4-extattr-add" onClick={addExtAttr}>
|
||||||
|
+ 增
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Section>
|
||||||
|
|
||||||
|
<Section title="任务监听器(taskListener)">
|
||||||
|
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
|
||||||
|
{listeners.map((l, i) => (
|
||||||
|
<div
|
||||||
|
key={i}
|
||||||
|
style={{ border: '1px solid var(--line)', borderRadius: 4, padding: 6, display: 'flex', flexDirection: 'column', gap: 4 }}
|
||||||
|
>
|
||||||
|
<div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
|
||||||
|
<select
|
||||||
|
data-testid={`eip4-listener-event-${i}`}
|
||||||
|
value={l.event}
|
||||||
|
onChange={(e) => patchListener(i, { event: e.target.value })}
|
||||||
|
style={{ flex: '0 0 110px' }}
|
||||||
|
>
|
||||||
|
{LISTENER_EVENTS.map((ev) => (
|
||||||
|
<option key={ev} value={ev}>
|
||||||
|
{ev}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<select
|
||||||
|
data-testid={`eip4-listener-mode-${i}`}
|
||||||
|
value={l.mode}
|
||||||
|
onChange={(e) =>
|
||||||
|
patchListener(i, { mode: e.target.value as ListenerRow['mode'] })
|
||||||
|
}
|
||||||
|
style={{ flex: '0 0 130px' }}
|
||||||
|
>
|
||||||
|
<option value="class">class</option>
|
||||||
|
<option value="delegateExpression">delegateExpression</option>
|
||||||
|
</select>
|
||||||
|
<button
|
||||||
|
className="btn btn-sm"
|
||||||
|
data-testid={`eip4-listener-remove-${i}`}
|
||||||
|
onClick={() => removeListener(i)}
|
||||||
|
>
|
||||||
|
删
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<input
|
||||||
|
data-testid={`eip4-listener-value-${i}`}
|
||||||
|
value={l.value}
|
||||||
|
placeholder={l.mode === 'class' ? '全限定类名' : '${bean}'}
|
||||||
|
onChange={(e) => patchListener(i, { value: e.target.value })}
|
||||||
|
/>
|
||||||
|
{l.fields && l.fields.length ? (
|
||||||
|
<span style={{ fontSize: 11, color: 'var(--text-3)' }}>
|
||||||
|
含 field 配置({l.fields.length})· 编辑时原样保留
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
<button className="btn btn-sm" data-testid="eip4-listener-add" onClick={addListener}>
|
||||||
|
+ 添加监听器
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</Section>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const hintStyle: React.CSSProperties = {
|
||||||
|
padding: 12,
|
||||||
|
color: 'var(--text-3)',
|
||||||
|
fontSize: 12,
|
||||||
|
borderBottom: '1px solid var(--line)',
|
||||||
|
};
|
||||||
305
src/modeler/candidateExpression.test.ts
Normal file
305
src/modeler/candidateExpression.test.ts
Normal file
@@ -0,0 +1,305 @@
|
|||||||
|
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();
|
||||||
|
});
|
||||||
|
|
||||||
|
// 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<string, unknown>).futureFlag).toBe(true);
|
||||||
|
expect(buildCandidateExpression(r.items, r.variant, r.meta)).toBe(WITH_UNKNOWN);
|
||||||
|
});
|
||||||
|
});
|
||||||
152
src/modeler/candidateExpression.ts
Normal file
152
src/modeler/candidateExpression.ts
Normal file
@@ -0,0 +1,152 @@
|
|||||||
|
// 办理人 / 会签(多实例)办理人表达式的编解码器(纯函数)。
|
||||||
|
//
|
||||||
|
// 处理的是 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"}(语料实测 meta 键集有多种子集)。
|
||||||
|
// 引擎运行期候选人解析(convertToUserProperties)只读 items,但 taskSuccessService 等是
|
||||||
|
// 任务后置服务钩子等运行期业务字段——侧板只改 items 时必须原样带回(meta),否则重新部署
|
||||||
|
// 会打掉这些字段。
|
||||||
|
// - 字符串叶子值(content/messageTemplate 等)的转义逐字对齐原版 stringToJson
|
||||||
|
// (BasePropertiesConverter.java:235-280):`'`→‘(U+2018)、`"`→“(U+201C)、
|
||||||
|
// `{`→【、`}`→】,反斜杠与控制字符走标准 JSON 转义。build 对新值应用此契约,防用户输入
|
||||||
|
// 含 `'`(截断外层 JUEL 单引号字面量)或 `"`(截断内层 JSON)导致部署后表达式解析即断。
|
||||||
|
//
|
||||||
|
// 逐字往返口径(全量 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,'";
|
||||||
|
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<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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('}');
|
||||||
|
}
|
||||||
|
|
||||||
|
function halfToFull(s: string): string {
|
||||||
|
return s.split('{').join('【').split('}').join('】');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 字符串叶子值转义,逐字对齐原版 stringToJson 里 JSON.stringify **未覆盖**的两处值级映射:
|
||||||
|
* `'`→‘、`"`→“。(反斜杠/控制字符由 JSON.stringify 覆盖;`{`/`}`→【/】由 halfToFull 覆盖。)
|
||||||
|
* 对合法存量叶子值(不含裸 ' / ")为 no-op,故不破坏逐字往返;仅对面板新输入生效。
|
||||||
|
*/
|
||||||
|
function escapeLeaf(v: string): string {
|
||||||
|
return v.split("'").join('‘').split('"').join('“');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 按规范键序重建 item:已知键在前(存在才输出,不凭空增删),未知键按原序透传。 */
|
||||||
|
function reorderItem(src: Record<string, unknown>): Record<string, unknown> {
|
||||||
|
const o: Record<string, unknown> = {};
|
||||||
|
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 数组、items 元素非对象或 type 非字符串、
|
||||||
|
* 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<string, unknown>;
|
||||||
|
if (!Array.isArray(record.items)) return null;
|
||||||
|
|
||||||
|
// 形状守卫:元素必须是普通对象且 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<string, unknown>).type !== 'string') return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const items = (record.items as Record<string, unknown>[]).map(
|
||||||
|
reorderItem,
|
||||||
|
) as unknown as UserPropertyItem[];
|
||||||
|
const meta: Record<string, unknown> = { ...record };
|
||||||
|
delete meta.items;
|
||||||
|
|
||||||
|
return { items, variant, meta };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建办理人/会签表达式:重建外层对象 {items, ...meta} → JSON.stringify(紧凑无空白,replacer
|
||||||
|
* 对字符串叶子应用 stringToJson 引号映射)→ 结构性 {} 换成全角【】(方括号保持半角)→ 套前后缀。
|
||||||
|
* round-trip 与真实表达式逐字一致(半角 content 变体除外,见文件头运行期等价说明)。
|
||||||
|
*/
|
||||||
|
export function buildCandidateExpression(
|
||||||
|
items: UserPropertyItem[],
|
||||||
|
variant: CandidateVariant,
|
||||||
|
meta?: Record<string, unknown>,
|
||||||
|
): string {
|
||||||
|
const prefix = variant === 'multiInstance' ? MULTI_PREFIX : CANDIDATE_PREFIX;
|
||||||
|
const outer = {
|
||||||
|
items: items.map((it) => reorderItem(it as unknown as Record<string, unknown>)),
|
||||||
|
...(meta ?? {}),
|
||||||
|
};
|
||||||
|
const json = JSON.stringify(outer, (_key, value) =>
|
||||||
|
typeof value === 'string' ? escapeLeaf(value) : value,
|
||||||
|
);
|
||||||
|
return prefix + halfToFull(json) + SUFFIX;
|
||||||
|
}
|
||||||
55
src/modeler/useSelectedElement.test.tsx
Normal file
55
src/modeler/useSelectedElement.test.tsx
Normal file
@@ -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();
|
||||||
|
});
|
||||||
|
});
|
||||||
56
src/modeler/useSelectedElement.ts
Normal file
56
src/modeler/useSelectedElement.ts
Normal file
@@ -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<string, string>;
|
||||||
|
/** 读取声明属性(如 '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<BpmnElement | null>(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;
|
||||||
|
}
|
||||||
@@ -1,11 +1,12 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
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 { MemoryRouter } from 'react-router-dom';
|
||||||
import { SYNTHETIC_BPMN } from '../modeler/moddle/fixtures/synthetic-full-surface.bpmn';
|
import { SYNTHETIC_BPMN } from '../modeler/moddle/fixtures/synthetic-full-surface.bpmn';
|
||||||
|
|
||||||
// bpmn-js Modeler:jsdom 跑不动真渲染,stub 成类(可断言 importXML/destroy 调用)。
|
// bpmn-js Modeler:jsdom 跑不动真渲染,stub 成类(可断言 importXML/saveXML/destroy 调用)。
|
||||||
const { importXMLMock, destroyMock, getMock, onMock, attachToMock, ModelerCtor } = vi.hoisted(() => {
|
const { importXMLMock, saveXMLMock, destroyMock, getMock, onMock, attachToMock, ModelerCtor } = vi.hoisted(() => {
|
||||||
const importXMLMock = vi.fn();
|
const importXMLMock = vi.fn();
|
||||||
|
const saveXMLMock = vi.fn();
|
||||||
const destroyMock = vi.fn();
|
const destroyMock = vi.fn();
|
||||||
const attachToMock = vi.fn();
|
const attachToMock = vi.fn();
|
||||||
const getMock = vi.fn((service: string) => {
|
const getMock = vi.fn((service: string) => {
|
||||||
@@ -16,11 +17,12 @@ const { importXMLMock, destroyMock, getMock, onMock, attachToMock, ModelerCtor }
|
|||||||
const onMock = vi.fn();
|
const onMock = vi.fn();
|
||||||
const ModelerCtor = vi.fn().mockImplementation(() => ({
|
const ModelerCtor = vi.fn().mockImplementation(() => ({
|
||||||
importXML: importXMLMock,
|
importXML: importXMLMock,
|
||||||
|
saveXML: saveXMLMock,
|
||||||
destroy: destroyMock,
|
destroy: destroyMock,
|
||||||
get: getMock,
|
get: getMock,
|
||||||
on: onMock,
|
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 }));
|
vi.mock('bpmn-js/lib/Modeler', () => ({ default: ModelerCtor }));
|
||||||
// 标准属性面板模块只作为 additionalModules 配置项传入被 mock 的 Modeler,永不真正执行。
|
// 标准属性面板模块只作为 additionalModules 配置项传入被 mock 的 Modeler,永不真正执行。
|
||||||
@@ -32,6 +34,14 @@ vi.mock('../api/processModeler', () => ({
|
|||||||
fetchProcDefSource: vi.fn(),
|
fetchProcDefSource: vi.fn(),
|
||||||
fetchProcDefSourceByKey: vi.fn(),
|
fetchProcDefSourceByKey: vi.fn(),
|
||||||
fetchProcessOptions: vi.fn(),
|
fetchProcessOptions: vi.fn(),
|
||||||
|
// Eip4Panel(右栏叠板)挂载时拉 formKey 数据源——mock 成空列表避免真请求。
|
||||||
|
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) => ({
|
vi.mock('../auth/token', async (importOriginal) => ({
|
||||||
...(await importOriginal<typeof import('../auth/token')>()),
|
...(await importOriginal<typeof import('../auth/token')>()),
|
||||||
@@ -39,12 +49,28 @@ vi.mock('../auth/token', async (importOriginal) => ({
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
import { ProcessModelerPage } from './ProcessModelerPage';
|
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';
|
import { getProfile } from '../auth/token';
|
||||||
|
|
||||||
const mSource = vi.mocked(fetchProcDefSource);
|
const mSource = vi.mocked(fetchProcDefSource);
|
||||||
const mSourceByKey = vi.mocked(fetchProcDefSourceByKey);
|
const mSourceByKey = vi.mocked(fetchProcDefSourceByKey);
|
||||||
const mOptions = vi.mocked(fetchProcessOptions);
|
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);
|
const mProfile = vi.mocked(getProfile);
|
||||||
|
|
||||||
function renderPage(initialPath = '/process-modeler') {
|
function renderPage(initialPath = '/process-modeler') {
|
||||||
@@ -57,6 +83,7 @@ function renderPage(initialPath = '/process-modeler') {
|
|||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
importXMLMock.mockReset().mockResolvedValue(undefined);
|
importXMLMock.mockReset().mockResolvedValue(undefined);
|
||||||
|
saveXMLMock.mockReset().mockResolvedValue({ xml: '<edited/>' });
|
||||||
destroyMock.mockReset();
|
destroyMock.mockReset();
|
||||||
attachToMock.mockReset();
|
attachToMock.mockReset();
|
||||||
getMock.mockClear();
|
getMock.mockClear();
|
||||||
@@ -65,14 +92,29 @@ beforeEach(() => {
|
|||||||
mSource.mockReset().mockResolvedValue({ found: true, bpmnXml: SYNTHETIC_BPMN, idMap: { '总包合同交底': 'Proc_zbht' } });
|
mSource.mockReset().mockResolvedValue({ found: true, bpmnXml: SYNTHETIC_BPMN, idMap: { '总包合同交底': 'Proc_zbht' } });
|
||||||
mSourceByKey.mockReset().mockResolvedValue({ found: true, bpmnXml: SYNTHETIC_BPMN, idMap: { '总包合同交底': 'Proc_zbht' } });
|
mSourceByKey.mockReset().mockResolvedValue({ found: true, bpmnXml: SYNTHETIC_BPMN, idMap: { '总包合同交底': 'Proc_zbht' } });
|
||||||
mOptions.mockReset().mockResolvedValue([]);
|
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: [] });
|
mProfile.mockReset().mockReturnValue({ userId: 'ADMIN', account: 'admin', name: '管理员', roles: [] });
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('ProcessModelerPage', () => {
|
describe('ProcessModelerPage', () => {
|
||||||
it('admin 渲染画布容器与标准属性面板容器', () => {
|
it('admin 渲染画布容器与标准属性面板容器', async () => {
|
||||||
renderPage();
|
renderPage();
|
||||||
expect(screen.getByTestId('process-modeler-canvas')).toBeInTheDocument();
|
expect(screen.getByTestId('process-modeler-canvas')).toBeInTheDocument();
|
||||||
expect(screen.getByTestId('process-modeler-props')).toBeInTheDocument();
|
expect(screen.getByTestId('process-modeler-props')).toBeInTheDocument();
|
||||||
|
// flush Eip4Panel 挂载期 fetchWfTemplates 的 setState(避免 act 告警)
|
||||||
|
await act(async () => {
|
||||||
|
await Promise.resolve();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
it('非 admin 降级为「仅管理员可用」文案,不渲染画布', () => {
|
it('非 admin 降级为「仅管理员可用」文案,不渲染画布', () => {
|
||||||
@@ -138,4 +180,116 @@ describe('ProcessModelerPage', () => {
|
|||||||
await waitFor(() => expect(mSource).toHaveBeenCalledWith('部署流程:3:uuid'));
|
await waitFor(() => expect(mSource).toHaveBeenCalledWith('部署流程:3:uuid'));
|
||||||
expect(mSourceByKey).not.toHaveBeenCalled();
|
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<string, unknown>;
|
||||||
|
additionalModules: unknown[];
|
||||||
|
};
|
||||||
|
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('<edited/>');
|
||||||
|
expect(JSON.parse(body.metaInfo!).eip4IdMap).toEqual({ '总包合同交底': 'Proc_zbht' });
|
||||||
|
expect(JSON.parse(body.metaInfo!)).toHaveProperty('sourceProcDefId'); // 结构对齐 from-procdef
|
||||||
|
expect(mFromProcDef).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('I-2 首存后回填 ?modelId=(令刷新幂等):触发按 modelId 重载', 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());
|
||||||
|
// 回填 ?modelId=NEW-1 → 载入效果按 modelId 重载(getModel)——证明 setParams 已写入。
|
||||||
|
await waitFor(() => expect(mGetModel).toHaveBeenCalledWith('NEW-1'));
|
||||||
|
});
|
||||||
|
|
||||||
|
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: '<edited/>' }));
|
||||||
|
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 → 回填 ?modelId= → 重载
|
||||||
|
await waitFor(() => expect(mCreateDraft).toHaveBeenCalled());
|
||||||
|
await waitFor(() => expect(mGetModel).toHaveBeenCalledWith('NEW-1')); // 回填后重载完成
|
||||||
|
await waitFor(() => expect(saveBtn()).not.toBeDisabled()); // saving 复位 + 重载就绪
|
||||||
|
fireEvent.click(saveBtn()); // 二次:PUT NEW-1(modelId 已在)
|
||||||
|
await waitFor(() => expect(mSaveDraft).toHaveBeenCalledWith('NEW-1', { bpmnXml: '<edited/>' }));
|
||||||
|
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();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
// 在线流程 Modeler(B3)——可编辑 BPMN 设计器页骨架。
|
// 在线流程 Modeler(B3)——可编辑 BPMN 设计器页。
|
||||||
// 本阶段(T1.5)只做:admin 门 + 三栏布局 + bpmn-js Modeler 挂载 + 存量流程只读载入。
|
// T1.5 骨架:admin 门 + 三栏布局 + bpmn-js Modeler + 存量只读载入。
|
||||||
// EIP4 定制侧板(办理人/会签/formKey…)是 T2.4,本页右上只放占位容器;
|
// T2.4:右栏叠 EIP4 定制侧板(办理人/会签/formKey…)。
|
||||||
// 「保存草稿」「发布」是 T2.5/T3.3,本页顶栏先放 disabled 占位按钮。
|
// T2.5:顶栏「保存草稿」可用(saveXML→create/from-procdef→PUT,metaInfo 带 eip4IdMap);
|
||||||
|
// 打开器加「草稿」tab(listModels→?modelId=→getModel→importXML)+ 草稿删除。
|
||||||
import { useEffect, useRef, useState } from 'react';
|
import { useEffect, useRef, useState } from 'react';
|
||||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||||
import Modeler from 'bpmn-js/lib/Modeler';
|
import Modeler from 'bpmn-js/lib/Modeler';
|
||||||
@@ -16,13 +17,23 @@ import {
|
|||||||
fetchProcDefSource,
|
fetchProcDefSource,
|
||||||
fetchProcDefSourceByKey,
|
fetchProcDefSourceByKey,
|
||||||
fetchProcessOptions,
|
fetchProcessOptions,
|
||||||
|
listModels,
|
||||||
|
getModel,
|
||||||
|
createDraft,
|
||||||
|
saveDraft,
|
||||||
|
draftFromProcDef,
|
||||||
|
deleteDraft,
|
||||||
type ProcessOption,
|
type ProcessOption,
|
||||||
|
type ModelSummary,
|
||||||
} from '../api/processModeler';
|
} from '../api/processModeler';
|
||||||
|
import { Eip4Panel, type PanelModeler } from '../modeler/Eip4Panel';
|
||||||
|
import { toast } from '../components/ui';
|
||||||
|
|
||||||
// bpmn-js/lib/Modeler 自带类型,但选项对象里的标准面板模块(本项目无类型)与 moddle JSON
|
// bpmn-js/lib/Modeler 自带类型,但选项对象里的标准面板模块(本项目无类型)与 moddle JSON
|
||||||
// 会与官方选项类型产生摩擦;照 ProcessDiagram 惯例把构造器收窄为本页用到的最小契约再实例化。
|
// 会与官方选项类型产生摩擦;照 ProcessDiagram 惯例把构造器收窄为本页用到的最小契约再实例化。
|
||||||
interface ModelerLike {
|
interface ModelerLike {
|
||||||
importXML(xml: string): Promise<unknown>;
|
importXML(xml: string): Promise<unknown>;
|
||||||
|
saveXML(opts?: { format?: boolean }): Promise<{ xml: string }>;
|
||||||
destroy(): void;
|
destroy(): void;
|
||||||
get(service: string): unknown;
|
get(service: string): unknown;
|
||||||
on(event: string, cb: (e: unknown) => void): void;
|
on(event: string, cb: (e: unknown) => void): void;
|
||||||
@@ -31,31 +42,56 @@ const ModelerCtor = Modeler as unknown as new (options: Record<string, unknown>)
|
|||||||
|
|
||||||
type LoadState = 'idle' | 'loading' | 'ready' | 'error';
|
type LoadState = 'idle' | 'loading' | 'ready' | 'error';
|
||||||
|
|
||||||
|
/** 从草稿 metaInfo JSON 串取 eip4IdMap(发布还原用;防御性)。 */
|
||||||
|
function parseMetaIdMap(metaInfo?: string): Record<string, string> {
|
||||||
|
if (!metaInfo) return {};
|
||||||
|
try {
|
||||||
|
const o = JSON.parse(metaInfo) as { eip4IdMap?: unknown };
|
||||||
|
return o && typeof o.eip4IdMap === 'object' && o.eip4IdMap
|
||||||
|
? (o.eip4IdMap as Record<string, string>)
|
||||||
|
: {};
|
||||||
|
} catch {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function ProcessModelerPage() {
|
export function ProcessModelerPage() {
|
||||||
const profile = getProfile();
|
const profile = getProfile();
|
||||||
const isAdmin = isAdminProfile(profile);
|
const isAdmin = isAdminProfile(profile);
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const [params, setParams] = useSearchParams();
|
const [params, setParams] = useSearchParams();
|
||||||
// 打开存量流程两条路:?procDefId=(source=processDefinition,id 即 procDefId)
|
// 打开三条路:?procDefId=(source=processDefinition)/ ?procKey=(存量按 key)/ ?modelId=(草稿)。
|
||||||
// 或 ?procKey=(source=model/history,按流程 key 载入最新版)。
|
|
||||||
const procDefId = params.get('procDefId') ?? '';
|
const procDefId = params.get('procDefId') ?? '';
|
||||||
const procKey = params.get('procKey') ?? '';
|
const procKey = params.get('procKey') ?? '';
|
||||||
const hasTarget = !!procDefId || !!procKey;
|
const modelIdParam = params.get('modelId') ?? '';
|
||||||
|
const hasTarget = !!procDefId || !!procKey || !!modelIdParam;
|
||||||
|
|
||||||
const canvasRef = useRef<HTMLDivElement>(null);
|
const canvasRef = useRef<HTMLDivElement>(null);
|
||||||
const panelRef = useRef<HTMLDivElement>(null);
|
const panelRef = useRef<HTMLDivElement>(null);
|
||||||
const modelerRef = useRef<ModelerLike | null>(null);
|
const modelerRef = useRef<ModelerLike | null>(null);
|
||||||
// 净化映射 原id→净化id:本阶段仅暂存,发布还原(T3.x)时用。
|
// Modeler 实例入 state 以驱动 Eip4Panel 重渲染(selection.changed 订阅需要真实例)。
|
||||||
|
const [modelerReady, setModelerReady] = useState<ModelerLike | null>(null);
|
||||||
|
// 净化映射 原id→净化id:存量载入时暂存,保存草稿写进 metaInfo、发布还原(T3.x)时用。
|
||||||
const idMapRef = useRef<Record<string, string>>({});
|
const idMapRef = useRef<Record<string, string>>({});
|
||||||
|
// 当前草稿 modelId(打开草稿或首次保存后写入);空=尚未落草稿。
|
||||||
|
const modelIdRef = useRef<string>('');
|
||||||
|
// 当前载入流程的 key(存量 procDefKey / 草稿 key)——新建草稿的 name/key 源。
|
||||||
|
const loadedKeyRef = useRef<string>('');
|
||||||
|
|
||||||
const [loadState, setLoadState] = useState<LoadState>('idle');
|
const [loadState, setLoadState] = useState<LoadState>('idle');
|
||||||
const [loadError, setLoadError] = useState('');
|
const [loadError, setLoadError] = useState('');
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
const [options, setOptions] = useState<ProcessOption[]>([]);
|
const [options, setOptions] = useState<ProcessOption[]>([]);
|
||||||
const [optionsError, setOptionsError] = useState('');
|
const [optionsError, setOptionsError] = useState('');
|
||||||
|
// 打开器 tab:存量流程 / 草稿。
|
||||||
|
const [openTab, setOpenTab] = useState<'existing' | 'draft'>('existing');
|
||||||
|
const [drafts, setDrafts] = useState<ModelSummary[]>([]);
|
||||||
|
const [draftsError, setDraftsError] = useState('');
|
||||||
|
const [draftsReload, setDraftsReload] = useState(0);
|
||||||
|
|
||||||
// 未打开任何流程时拉存量流程选项(数据源复用旧 ProcessSelectDialog 端点)。
|
// 未打开任何流程 + 存量 tab 时拉存量流程选项(复用旧 ProcessSelectDialog 端点)。
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isAdmin || hasTarget) return;
|
if (!isAdmin || hasTarget || openTab !== 'existing') return;
|
||||||
let alive = true;
|
let alive = true;
|
||||||
fetchProcessOptions()
|
fetchProcessOptions()
|
||||||
.then((opts) => alive && setOptions(opts))
|
.then((opts) => alive && setOptions(opts))
|
||||||
@@ -63,9 +99,22 @@ export function ProcessModelerPage() {
|
|||||||
return () => {
|
return () => {
|
||||||
alive = false;
|
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(() => {
|
useEffect(() => {
|
||||||
if (!isAdmin || !hasTarget) return;
|
if (!isAdmin || !hasTarget) return;
|
||||||
let alive = true;
|
let alive = true;
|
||||||
@@ -75,10 +124,18 @@ export function ProcessModelerPage() {
|
|||||||
|
|
||||||
(async () => {
|
(async () => {
|
||||||
try {
|
try {
|
||||||
// procDefId 优先(source=processDefinition);否则按 key(source=model/history)。
|
// 三条路统一成 {found,bpmnXml,idMap,key}。
|
||||||
const src = procDefId
|
let src: { found: boolean; bpmnXml?: string; idMap?: Record<string, string>; key?: string };
|
||||||
? await fetchProcDefSource(procDefId)
|
if (modelIdParam) {
|
||||||
: await fetchProcDefSourceByKey(procKey);
|
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 (!alive) return;
|
||||||
if (!src.found || !src.bpmnXml) {
|
if (!src.found || !src.bpmnXml) {
|
||||||
setLoadError('未找到该流程的 BPMN 源(可能未部署或无布局信息)');
|
setLoadError('未找到该流程的 BPMN 源(可能未部署或无布局信息)');
|
||||||
@@ -102,9 +159,7 @@ export function ProcessModelerPage() {
|
|||||||
// 扩展属性冲突静默丢弃 userTask;单载 activiti 时 flowable 文档经 moddle lax 往返零丢失。
|
// 扩展属性冲突静默丢弃 userTask;单载 activiti 时 flowable 文档经 moddle lax 往返零丢失。
|
||||||
moddleExtensions: { activiti: activitiModdle },
|
moddleExtensions: { activiti: activitiModdle },
|
||||||
});
|
});
|
||||||
// ⚠️ 显式 attachTo:live 实证——只靠构造参数 propertiesPanel.parent,面板从不挂载
|
// ⚠️ 显式 attachTo:live 实证——只靠构造参数 propertiesPanel.parent,面板从不挂载。
|
||||||
// (.bio-properties-panel 在 document 中为 0;构造时 ref 时序/传对象非 element 皆可致此)。
|
|
||||||
// attachTo 容器 DOM 是 bpmn-js-properties-panel 的规范补救。放在 importXML 前,alive 内。
|
|
||||||
if (panelRef.current) {
|
if (panelRef.current) {
|
||||||
try {
|
try {
|
||||||
(modeler.get('propertiesPanel') as { attachTo(el: HTMLElement): void }).attachTo(panelRef.current);
|
(modeler.get('propertiesPanel') as { attachTo(el: HTMLElement): void }).attachTo(panelRef.current);
|
||||||
@@ -113,9 +168,13 @@ export function ProcessModelerPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
idMapRef.current = src.idMap ?? {};
|
idMapRef.current = src.idMap ?? {};
|
||||||
|
loadedKeyRef.current = src.key ?? '';
|
||||||
|
// 草稿路:记住 modelId(后续保存走 PUT);存量路:清空(首次保存新建草稿)。
|
||||||
|
modelIdRef.current = modelIdParam || '';
|
||||||
await modeler.importXML(src.bpmnXml);
|
await modeler.importXML(src.bpmnXml);
|
||||||
if (!alive) return;
|
if (!alive) return;
|
||||||
modelerRef.current = modeler;
|
modelerRef.current = modeler;
|
||||||
|
setModelerReady(modeler);
|
||||||
try {
|
try {
|
||||||
const canvas = modeler.get('canvas') as { zoom(mode: string, point?: string): void };
|
const canvas = modeler.get('canvas') as { zoom(mode: string, point?: string): void };
|
||||||
canvas.zoom('fit-viewport', 'auto');
|
canvas.zoom('fit-viewport', 'auto');
|
||||||
@@ -141,8 +200,48 @@ export function ProcessModelerPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
modelerRef.current = null;
|
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;
|
||||||
|
// I-2:首存回填 ?modelId=,令刷新幂等(不再重复建草稿)、二次保存恒走 PUT。
|
||||||
|
setParams({ modelId }, { replace: true });
|
||||||
|
} else {
|
||||||
|
const key = loadedKeyRef.current || procKey || 'new_process';
|
||||||
|
// metaInfo 结构与 from-procdef 对齐(sourceProcDefId 便于 T3.x 影响摘要/审计,
|
||||||
|
// 虽 restore 只读 eip4IdMap)。
|
||||||
|
const metaInfo = JSON.stringify({
|
||||||
|
eip4IdMap: idMapRef.current,
|
||||||
|
sourceProcDefId: procDefId || '',
|
||||||
|
originalKey: key,
|
||||||
|
});
|
||||||
|
modelId = await createDraft({ name: key, key, bpmnXml: xml, metaInfo });
|
||||||
|
modelIdRef.current = modelId;
|
||||||
|
setParams({ modelId }, { replace: true });
|
||||||
|
}
|
||||||
|
toast('已保存草稿', 'ok');
|
||||||
|
} catch {
|
||||||
|
toast('保存草稿失败', 'err');
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (!isAdmin) {
|
if (!isAdmin) {
|
||||||
return <div style={{ padding: 24, color: 'var(--text-3)' }}>流程设计器仅管理员可用。</div>;
|
return <div style={{ padding: 24, color: 'var(--text-3)' }}>流程设计器仅管理员可用。</div>;
|
||||||
@@ -154,7 +253,6 @@ export function ProcessModelerPage() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
// 选择器按 source 分派:processDefinition→?procDefId=<id>;其余→?procKey=<key>。
|
// 选择器按 source 分派:processDefinition→?procDefId=<id>;其余→?procKey=<key>。
|
||||||
// 用索引取回选项对象(避免把 id/key 直接塞进 <option value> 造成路由二义)。
|
|
||||||
function openSelected(indexValue: string) {
|
function openSelected(indexValue: string) {
|
||||||
if (indexValue === '') return;
|
if (indexValue === '') return;
|
||||||
const opt = loadableOptions[Number(indexValue)];
|
const opt = loadableOptions[Number(indexValue)];
|
||||||
@@ -166,6 +264,23 @@ export function ProcessModelerPage() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function openDraft(id: string) {
|
||||||
|
setParams({ modelId: id });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onDeleteDraft(d: ModelSummary) {
|
||||||
|
if (typeof window !== 'undefined' && !window.confirm(`删除草稿「${d.name || d.key || d.id}」?`)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await deleteDraft(d.id);
|
||||||
|
toast('草稿已删除', 'ok');
|
||||||
|
setDraftsReload((x) => x + 1);
|
||||||
|
} catch {
|
||||||
|
toast('删除草稿失败', 'err');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
data-testid="process-modeler-root"
|
data-testid="process-modeler-root"
|
||||||
@@ -185,10 +300,18 @@ export function ProcessModelerPage() {
|
|||||||
>
|
>
|
||||||
<span style={{ fontWeight: 600, fontSize: 15 }}>流程设计器</span>
|
<span style={{ fontWeight: 600, fontSize: 15 }}>流程设计器</span>
|
||||||
<span className="muted" style={{ fontSize: 12, flex: 1 }}>
|
<span className="muted" style={{ fontSize: 12, flex: 1 }}>
|
||||||
{hasTarget ? `已打开:${procDefId || procKey}` : '在线编辑 BPMN 流程定义(可编辑存量 / 新建)'}
|
{hasTarget
|
||||||
|
? `已打开:${modelIdParam ? '草稿 ' + modelIdParam : procDefId || procKey}`
|
||||||
|
: '在线编辑 BPMN 流程定义(可编辑存量 / 草稿)'}
|
||||||
</span>
|
</span>
|
||||||
<button className="btn btn-sm" data-testid="process-modeler-save-draft" disabled title="保存草稿(下阶段)">
|
<button
|
||||||
保存草稿
|
className="btn btn-sm"
|
||||||
|
data-testid="process-modeler-save-draft"
|
||||||
|
disabled={!modelerReady || saving}
|
||||||
|
onClick={handleSaveDraft}
|
||||||
|
title="保存为草稿(act_re_model)"
|
||||||
|
>
|
||||||
|
{saving ? '保存中…' : '保存草稿'}
|
||||||
</button>
|
</button>
|
||||||
<button className="btn btn-sm btn-primary" data-testid="process-modeler-publish" disabled title="发布(下阶段)">
|
<button className="btn btn-sm btn-primary" data-testid="process-modeler-publish" disabled title="发布(下阶段)">
|
||||||
发布
|
发布
|
||||||
@@ -198,12 +321,12 @@ export function ProcessModelerPage() {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* 主体:左画布 + 右栏(上=EIP4 侧板占位 / 下=标准属性面板) */}
|
{/* 主体:左画布 + 右栏(上=EIP4 侧板 / 下=标准属性面板) */}
|
||||||
<div style={{ flex: 1, display: 'flex', minHeight: 0 }}>
|
<div style={{ flex: 1, display: 'flex', minHeight: 0 }}>
|
||||||
<div style={{ flex: 1, position: 'relative', minWidth: 0, background: '#fff' }}>
|
<div style={{ flex: 1, position: 'relative', minWidth: 0, background: '#fff' }}>
|
||||||
<div ref={canvasRef} data-testid="process-modeler-canvas" style={{ width: '100%', height: '100%' }} />
|
<div ref={canvasRef} data-testid="process-modeler-canvas" style={{ width: '100%', height: '100%' }} />
|
||||||
|
|
||||||
{/* 未打开任何流程:叠加「打开存量流程」选择器 + 新建占位 */}
|
{/* 未打开任何流程:叠加打开器(存量流程 / 草稿 两 tab) */}
|
||||||
{!hasTarget ? (
|
{!hasTarget ? (
|
||||||
<div
|
<div
|
||||||
style={{
|
style={{
|
||||||
@@ -217,6 +340,25 @@ export function ProcessModelerPage() {
|
|||||||
background: 'var(--surface, #fff)',
|
background: 'var(--surface, #fff)',
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
|
<div style={{ display: 'flex', gap: 8 }}>
|
||||||
|
<button
|
||||||
|
className={openTab === 'existing' ? 'btn btn-sm btn-primary' : 'btn btn-sm'}
|
||||||
|
data-testid="process-modeler-tab-existing"
|
||||||
|
onClick={() => setOpenTab('existing')}
|
||||||
|
>
|
||||||
|
存量流程
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className={openTab === 'draft' ? 'btn btn-sm btn-primary' : 'btn btn-sm'}
|
||||||
|
data-testid="process-modeler-tab-draft"
|
||||||
|
onClick={() => setOpenTab('draft')}
|
||||||
|
>
|
||||||
|
草稿
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{openTab === 'existing' ? (
|
||||||
|
<>
|
||||||
<div style={{ color: 'var(--text-3)', fontSize: 13 }}>选择一个存量流程开始编辑</div>
|
<div style={{ color: 'var(--text-3)', fontSize: 13 }}>选择一个存量流程开始编辑</div>
|
||||||
<select
|
<select
|
||||||
data-testid="process-modeler-open-select"
|
data-testid="process-modeler-open-select"
|
||||||
@@ -237,6 +379,59 @@ export function ProcessModelerPage() {
|
|||||||
<button className="btn btn-sm" data-testid="process-modeler-new" disabled title="新建流程(下阶段)">
|
<button className="btn btn-sm" data-testid="process-modeler-new" disabled title="新建流程(下阶段)">
|
||||||
+ 新建流程
|
+ 新建流程
|
||||||
</button>
|
</button>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<div
|
||||||
|
data-testid="process-modeler-draft-list"
|
||||||
|
style={{
|
||||||
|
minWidth: 320,
|
||||||
|
maxHeight: 320,
|
||||||
|
overflow: 'auto',
|
||||||
|
display: 'flex',
|
||||||
|
flexDirection: 'column',
|
||||||
|
gap: 4,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{drafts.length === 0 ? (
|
||||||
|
<div style={{ color: 'var(--text-3)', fontSize: 13, textAlign: 'center' }}>暂无草稿</div>
|
||||||
|
) : (
|
||||||
|
drafts.map((d, i) => (
|
||||||
|
<div
|
||||||
|
key={d.id}
|
||||||
|
style={{
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
gap: 8,
|
||||||
|
padding: '4px 6px',
|
||||||
|
border: '1px solid var(--line)',
|
||||||
|
borderRadius: 4,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span style={{ flex: 1, minWidth: 0, fontSize: 13, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
|
||||||
|
{d.name || d.key || d.id}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
className="btn btn-sm"
|
||||||
|
data-testid={`process-modeler-draft-open-${i}`}
|
||||||
|
onClick={() => openDraft(d.id)}
|
||||||
|
>
|
||||||
|
打开
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="btn btn-sm"
|
||||||
|
data-testid={`process-modeler-draft-delete-${i}`}
|
||||||
|
onClick={() => onDeleteDraft(d)}
|
||||||
|
>
|
||||||
|
删除
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
{draftsError ? (
|
||||||
|
<div style={{ color: 'var(--err)', fontSize: 12 }}>{draftsError}</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
@@ -263,13 +458,8 @@ export function ProcessModelerPage() {
|
|||||||
minHeight: 0,
|
minHeight: 0,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{/* EIP4 定制侧板占位(办理人/会签/formKey…由 T2.4 接入) */}
|
{/* EIP4 定制侧板(办理人/会签/formKey/扩展属性/监听器)——选中 userTask 时叠加 */}
|
||||||
<div
|
<Eip4Panel modeler={modelerReady as unknown as PanelModeler | null} />
|
||||||
data-testid="process-modeler-eip4-panel"
|
|
||||||
style={{ padding: 12, borderBottom: '1px solid var(--line)', color: 'var(--text-3)', fontSize: 12 }}
|
|
||||||
>
|
|
||||||
EIP4 定制控件(办理人 / 会签 / formKey)将在此叠加,下阶段接入。
|
|
||||||
</div>
|
|
||||||
{/* 标准属性面板宿主(bpmn-js-properties-panel attachTo 进此容器) */}
|
{/* 标准属性面板宿主(bpmn-js-properties-panel attachTo 进此容器) */}
|
||||||
<div ref={panelRef} data-testid="process-modeler-props" style={{ flex: 1, overflow: 'auto', minHeight: 0 }} />
|
<div ref={panelRef} data-testid="process-modeler-props" style={{ flex: 1, overflow: 'auto', minHeight: 0 }} />
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
178
tools/codec-corpus-sweep.mjs
Normal file
178
tools/codec-corpus-sweep.mjs
Normal file
@@ -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);
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user