Merge pull request #150 from yunyingk/fix/workflow-filter-validation
fix: 完善协助平台字段映射与工作流筛选静态门禁
This commit is contained in:
7 files changed
+377
-261
No files matched your search
Vendored
+243
-243
File diff suppressed because it is too large.
Load diff
@@ -19,12 +19,14 @@
|
||||
|
||||
## 关键 API
|
||||
|
||||
- `searchCorporations`: 全量企业库检索(按关键词/企业 ID)
|
||||
- `searchCorporations`: 全量企业库检索(企业 ID 精确匹配、企业名称忽略大小写包含匹配;服务端过滤并分页)
|
||||
- `getCorporationDetail`: 查询企业详细画像与开通版本
|
||||
- `listAssistTickets`: 查询企业生效中的协助工单(包含 ticketId、原因、有效期、申请人)
|
||||
- `searchStaffList`: 查询企业内部员工名单(用于指定代客身份时的 staffId 定位)
|
||||
- `getAssistToken`: 换取免密代客登录链接与临时 JWT凭证
|
||||
|
||||
企业检索的关键词和状态通过 JSON 字符串字面量转义后构造过滤表达式,支持中文、引号及反斜线。协助工单在保留既有字段优先级的基础上,将平台原始字段 `userId`、`responsibleUserName`、`responsibleUserId`、`applyMessage` 分别映射为 `applicantId`、`principal`、`principalId`、`matter`;`assistTime` 从毫秒换算为小时 `duration`,仅在缺少旧字段 `duration` / `hours` 时使用。空申请事由保留为空字符串。
|
||||
|
||||
## 会话生成、导入与身份完整度
|
||||
|
||||
- `assist-platform enter <corpId> --dry-run` 在换票、身份查询和落盘前返回预览;无论是否带 `--save` / `--switch`,均不需要协助平台登录,也不会发出网络请求。
|
||||
|
||||
@@ -38,12 +38,12 @@ export async function searchCorporationsApi(
|
||||
|
||||
const conditions: string[] = [];
|
||||
if (params.keyword?.trim()) {
|
||||
const kw = params.keyword.trim().replace(/"/g, '\\"');
|
||||
conditions.push(`(id == "${kw}" || name == "${kw}")`);
|
||||
const kw = JSON.stringify(params.keyword.trim());
|
||||
conditions.push(`(id == ${kw} || name.containsIgnoreCase(${kw}))`);
|
||||
}
|
||||
if (params.state?.trim()) {
|
||||
const st = params.state.trim().replace(/"/g, '\\"');
|
||||
conditions.push(`state == "${st}"`);
|
||||
const st = JSON.stringify(params.state.trim());
|
||||
conditions.push(`state == ${st}`);
|
||||
}
|
||||
if (conditions.length > 0) {
|
||||
requestBody.filterBy = conditions.join(" && ");
|
||||
@@ -127,20 +127,27 @@ export async function searchAssistTicketsApi(
|
||||
|
||||
const rawStatus = item.state ?? item.status;
|
||||
const stateStr = rawStatus !== undefined && rawStatus !== null ? String(rawStatus) : "未知状态";
|
||||
const applicantId = item.applicantId || item.userId;
|
||||
const principal = item.principal || item.operationUserName || item.responsibleUserName;
|
||||
const principalId = item.principalId || item.responsibleUserId;
|
||||
const matter = item.matter ?? item.applyMessage;
|
||||
|
||||
return {
|
||||
id: String(item.id || item.ticketId || ""),
|
||||
ticketId: String(item.ticketId || item.id || item.authCode || ""),
|
||||
applicant: String(item.applicant || item.applyUserName || item.userName || "未知申请人"),
|
||||
applicantId: item.applicantId ? String(item.applicantId) : undefined,
|
||||
principal: item.principal ? String(item.principal) : (item.operationUserName ? String(item.operationUserName) : undefined),
|
||||
principalId: item.principalId ? String(item.principalId) : undefined,
|
||||
applicantId: applicantId ? String(applicantId) : undefined,
|
||||
principal: principal ? String(principal) : undefined,
|
||||
principalId: principalId ? String(principalId) : undefined,
|
||||
state: stateStr,
|
||||
duration: typeof item.duration === "number" ? item.duration : (typeof item.hours === "number" ? item.hours : undefined),
|
||||
duration: typeof item.duration === "number" ? item.duration : (typeof item.hours === "number" ? item.hours : (
|
||||
typeof item.assistTime === "number" && Number.isFinite(item.assistTime) && item.assistTime >= 0
|
||||
? item.assistTime / 3600000 : undefined
|
||||
)),
|
||||
startTime,
|
||||
endTime,
|
||||
usePeriodDesc,
|
||||
matter: item.matter ? String(item.matter) : undefined,
|
||||
matter: matter !== undefined && matter !== null ? String(matter) : undefined,
|
||||
createTime: typeof item.createTime === "number" ? item.createTime : undefined,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -38,7 +38,7 @@ describe("domains/assist-platform - 协助平台业务编排", () => {
|
||||
expect(req.url).toContain("corporation/search");
|
||||
const body = (await req.json()) as any;
|
||||
expect(body.limit.count).toBe(10);
|
||||
expect(body.filterBy).toContain('name == "CSM"');
|
||||
expect(body.filterBy).toBe('(id == "CSM" || name.containsIgnoreCase("CSM"))');
|
||||
return Response.json({
|
||||
count: 1,
|
||||
items: [
|
||||
@@ -63,6 +63,20 @@ describe("domains/assist-platform - 协助平台业务编排", () => {
|
||||
expect(res.items[0].name).toBe("CSM");
|
||||
});
|
||||
|
||||
it("searchCorporations 转义关键词和状态并保留分页条件", async () => {
|
||||
const keyword = ' 齐齐"哈\\尔 ';
|
||||
const state = ' 可"用\\ ';
|
||||
const client = createMockClient(async (req) => {
|
||||
const body = await req.json() as any;
|
||||
const kw = JSON.stringify(keyword.trim());
|
||||
expect(body.filterBy).toBe(`(id == ${kw} || name.containsIgnoreCase(${kw})) && state == ${JSON.stringify(state.trim())}`);
|
||||
expect(body.limit).toEqual({ start: 3, count: 5 });
|
||||
return Response.json({ count: 0, items: [] });
|
||||
});
|
||||
expect(await searchCorporations(client, { keyword, state, limit: { start: 3, count: 5 } }))
|
||||
.toEqual({ count: 0, items: [] });
|
||||
});
|
||||
|
||||
it("getCorporationDetail 返回企业详细配置", async () => {
|
||||
const client = createMockClient(async (req) => {
|
||||
expect(req.url).toContain("corporation/$Cxa3oOtQi2eS$g/getCorporationDetail");
|
||||
@@ -108,6 +122,31 @@ describe("domains/assist-platform - 协助平台业务编排", () => {
|
||||
expect(tickets[0].usePeriodDesc).toContain("至");
|
||||
});
|
||||
|
||||
it("listAssistTickets 映射平台原始字段并保留旧字段优先级", async () => {
|
||||
const raw = {
|
||||
id: "ticket-raw", userName: "申请人", userId: "applicant-raw",
|
||||
responsibleUserName: "负责人", responsibleUserId: "principal-raw",
|
||||
status: 1, assistTime: 86400000, applyMessage: "",
|
||||
};
|
||||
const client = createMockClient(() => Response.json({ items: [
|
||||
raw,
|
||||
{ ...raw, applicant: "旧申请人", applicantId: "applicant-old", principal: "旧负责人",
|
||||
principalId: "principal-old", operationUserName: "旧经办人", state: "已提供",
|
||||
duration: 12, hours: 48, matter: "旧事由" },
|
||||
{ ...raw, operationUserName: "旧经办人", hours: 6 },
|
||||
] }));
|
||||
const tickets = await listAssistTickets(client, "corp-test");
|
||||
expect(tickets[0]).toMatchObject({
|
||||
ticketId: "ticket-raw", applicant: "申请人", applicantId: "applicant-raw",
|
||||
principal: "负责人", principalId: "principal-raw", state: "1", duration: 24, matter: "",
|
||||
});
|
||||
expect(tickets[1]).toMatchObject({
|
||||
applicant: "旧申请人", applicantId: "applicant-old", principal: "旧负责人",
|
||||
principalId: "principal-old", state: "已提供", duration: 12, matter: "旧事由",
|
||||
});
|
||||
expect(tickets[2]).toMatchObject({ principal: "旧经办人", duration: 6 });
|
||||
});
|
||||
|
||||
it("findStaff 正确检索企业员工工号与角色", async () => {
|
||||
const client = createMockClient(async (req) => {
|
||||
expect(req.url).toContain("assistPlatform/getStaff");
|
||||
|
||||
@@ -165,7 +165,9 @@ MVEL 本地仿真支持的是转译子集:零参 `HashMap` / `ArrayList` 及 `
|
||||
|
||||
## 工具链静态门禁与防御性保障 (Toolchain Defense & Linting)
|
||||
|
||||
字段引用检查覆盖 `inputs`、`fields`、`mapping`、直接 `form` 及其嵌套对象/数组,不扫描脚本和说明文本。`choose` 支持 JSON 描述符、引号路径和裸路径:明确节点键或标准节点前缀缺失时产生 `BROKEN_CHOOSE_REFERENCE`,旧循环 `$item` 路径产生 `BROKEN_LOOP_ITEM_REFERENCE`;`trigger_1` 也必须实际存在。`body` 等上下文根不按节点处理,来源无法静态确定或无法解析的表达式给出软提示,不据此声称已验证可用。此检查不等同于完整的上游作用域或字段类型校验。
|
||||
字段引用检查覆盖 `inputs`、`fields`、`mapping`、直接 `form`、`combineFilters`、`filters`、`conditions`、`flowCode`、`list`、`details` 及其嵌套对象/数组,不扫描脚本和说明文本。`choose` 支持 JSON 描述符、引号路径和裸路径:明确节点键或标准节点前缀缺失时产生 `BROKEN_CHOOSE_REFERENCE`,旧循环 `$item` 路径产生 `BROKEN_LOOP_ITEM_REFERENCE`;`trigger_1` 也必须实际存在。明确为 JSON 描述符但 JSON 损坏(例如多余 `}`)或缺少有效节点 key 时产生 `INVALID_CHOOSE_DESCRIPTOR` 硬门禁。`body` 等上下文根不按节点处理,来源无法静态确定或使用不支持的表达式时仍给出软提示,不据此声称已验证可用。此检查不等同于完整的上游作用域或字段类型校验。
|
||||
|
||||
业务对象查询的 `gte/lte` 会产生 `DATALINK_FILTER_COMPARISON_COMPATIBILITY` 软提示:本地条件解释器支持通用比较符,不代表真实设计器的日期字段支持同一枚举。分析器不会自动改为 `gt/lt`,因为这会改变端点是否包含的业务语义;采用严格比较时需同时核对月初、下月月初等毫秒边界。保存成功及静态门禁通过均不等于前端配置校验或租户实际运行通过。
|
||||
|
||||
1. **文档站点域名拦截 (`DOCS_DOMAIN_USED`)**:静态分析会阻断在 HTTP 任务节点配置 `docs.ekuaibao.com` 的行为(错误复制开放平台文档地址),指导修正为 `app.ekuaibao.com`;
|
||||
2. **应用权限代码交叉核验 (`UNLICENSED_POWER_CODE`)**:扫描 HTTP 任务 URL 中的 `powerCode` 参数(如 `TICKET_AUDIT_switch`),与当前企业已开通应用交叉核验,未开通时产生硬门禁阻断;参数包含无效 URL 百分号转义时产生 `INVALID_POWER_CODE_ENCODING` 硬门禁诊断,避免权限探测异常中断其他节点分析;
|
||||
|
||||
@@ -58,6 +58,7 @@ interface ChooseReference {
|
||||
key?: string;
|
||||
descriptor?: boolean;
|
||||
problem?: string;
|
||||
invalidDescriptor?: boolean;
|
||||
}
|
||||
|
||||
/** 只解析 choose 参数,不执行表达式;引号内的括号不参与标签边界匹配。 */
|
||||
@@ -90,6 +91,7 @@ function extractChooseTags(val: unknown): ChooseReference[] {
|
||||
marker.lastIndex = end + 1 + close[0].length;
|
||||
const raw = val.slice(match.index, marker.lastIndex);
|
||||
const argument = val.slice(from, end).trim();
|
||||
let isDescriptor = false;
|
||||
try {
|
||||
let value = argument;
|
||||
if (argument.startsWith('"')) value = JSON.parse(argument);
|
||||
@@ -100,6 +102,7 @@ function extractChooseTags(val: unknown): ChooseReference[] {
|
||||
}
|
||||
if (typeof value !== "string") throw new Error("参数应为节点描述或路径");
|
||||
if (value.trim().startsWith("{")) {
|
||||
isDescriptor = true;
|
||||
const descriptor: unknown = JSON.parse(value);
|
||||
if (!descriptor || typeof descriptor !== "object" || Array.isArray(descriptor) || typeof (descriptor as Record<string, unknown>).key !== "string" || !(descriptor as { key: string }).key.trim()) throw new Error("节点描述缺少 key");
|
||||
results.push({ raw, key: (descriptor as { key: string }).key.trim(), descriptor: true });
|
||||
@@ -107,7 +110,8 @@ function extractChooseTags(val: unknown): ChooseReference[] {
|
||||
results.push({ raw, key: value.trim(), descriptor: false });
|
||||
} else throw new Error("参数不是可静态识别的节点路径");
|
||||
} catch {
|
||||
results.push({ raw, problem: "choose 参数不是可静态识别的节点描述或路径" });
|
||||
results.push({ raw, invalidDescriptor: isDescriptor,
|
||||
problem: isDescriptor ? "choose 节点描述不是有效 JSON 对象或缺少有效 key" : "choose 参数不是可静态识别的节点描述或路径" });
|
||||
}
|
||||
}
|
||||
return results;
|
||||
@@ -245,6 +249,7 @@ interface LeafFilterItem {
|
||||
}
|
||||
|
||||
function extractLeafFilters(filterGroup: unknown): LeafFilterItem[] {
|
||||
if (Array.isArray(filterGroup)) return filterGroup.flatMap(extractLeafFilters);
|
||||
if (!filterGroup || typeof filterGroup !== "object") return [];
|
||||
const items: LeafFilterItem[] = [];
|
||||
const rec = filterGroup as Record<string, unknown>;
|
||||
@@ -496,6 +501,19 @@ export function analyzeWorkflow(
|
||||
// 诊断:DataLink 字段误填表单公式硬校验
|
||||
checkMisplacedFormulasInDatalink(task, path, diagnostics);
|
||||
|
||||
// 本地条件解释器支持的通用比较符,不等于真实设计器对应字段的枚举。
|
||||
if (task.type === "ekuaibao-datalink-filter") {
|
||||
const raw = task as Record<string, unknown>;
|
||||
for (const filter of extractLeafFilters(raw.combineFilters ?? raw.filters)) {
|
||||
if (filter.compare === "gte" || filter.compare === "lte") {
|
||||
addDiagnostic(diagnostics, {
|
||||
severity: "warning", code: "DATALINK_FILTER_COMPARISON_COMPATIBILITY", path,
|
||||
message: `业务对象筛选字段 [${String(filter.key || "未知")}] 使用通用比较符 '${filter.compare}'。合思前端日期字段可能不识别该枚举,请在设计器核对支持的比较符;直接替换为 gt/lt 会改变等号边界,月份范围需同时核对月初及下月月初时间戳。`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 诊断 2: every 循环内 flow-create-task (SKIP) 后跟无状态守卫的 ekuaibao-datalink-edit
|
||||
if (insideEvery && task.type === "flow-create-task") {
|
||||
const onError = (task as Record<string, unknown>).onError as
|
||||
@@ -753,7 +771,7 @@ export function analyzeWorkflow(
|
||||
// 诊断 5: 字段变量引用失效校验 (BROKEN_CHOOSE_REFERENCE / BROKEN_LOOP_ITEM_REFERENCE)
|
||||
const inspectFields: Array<{ key: string; value: string }> = [];
|
||||
const rawTask = task as Record<string, unknown>;
|
||||
for (const key of ["inputs", "fields", "mapping", "form"]) collectExpressionValues(rawTask[key], key, inspectFields);
|
||||
for (const key of ["inputs", "fields", "mapping", "form", "combineFilters", "filters", "conditions", "flowCode", "list", "details"]) collectExpressionValues(rawTask[key], key, inspectFields);
|
||||
|
||||
for (const field of inspectFields) {
|
||||
if (typeof field.value === "string") {
|
||||
@@ -762,8 +780,11 @@ export function analyzeWorkflow(
|
||||
const chooseKey = item.key;
|
||||
if (!chooseKey) {
|
||||
addDiagnostic(diagnostics, {
|
||||
severity: "warning", category: "soft_advice", code: "UNRESOLVED_CHOOSE_REFERENCE", path,
|
||||
message: `字段 [${field.key}] 的引用无法静态检查:${item.problem}。请在真实流程设计器中确认。`,
|
||||
severity: item.invalidDescriptor ? "error" : "warning",
|
||||
code: item.invalidDescriptor ? "INVALID_CHOOSE_DESCRIPTOR" : "UNRESOLVED_CHOOSE_REFERENCE", path,
|
||||
message: item.invalidDescriptor
|
||||
? `字段 [${field.key}] 的 choose 节点描述损坏:${item.problem}。请检查多余括号、JSON 转义和节点 key。`
|
||||
: `字段 [${field.key}] 的引用无法静态检查:${item.problem}。请在真实流程设计器中确认。`,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -70,8 +70,8 @@ describe("choose reference containers and source classification", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("warns for unknown bare roots and unsupported or malformed expressions without blocking", () => {
|
||||
for (const tag of ["@{choose(missing_node.data)}", "@{choose('missing_node.data')}", "@{choose(action_x.data + 1)}", "@{choose('action_missing.data')", "@{choose('{bad json}')}"]) {
|
||||
test("warns for unknown bare roots and unsupported or incomplete expressions without blocking", () => {
|
||||
for (const tag of ["@{choose(missing_node.data)}", "@{choose('missing_node.data')}", "@{choose(action_x.data + 1)}", "@{choose('action_missing.data')"]) {
|
||||
const result = analyze({ form: { title: tag } });
|
||||
expect(result.summary.passed).toBe(true);
|
||||
expect(result.diagnostics.map(item => item.code)).toContain("UNRESOLVED_CHOOSE_REFERENCE");
|
||||
@@ -79,6 +79,51 @@ describe("choose reference containers and source classification", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test.each([
|
||||
"@{choose('{bad json}')}",
|
||||
`@{choose('${JSON.stringify({ key: "trigger_actual", properties: [{ key: "startTime", type: "NUMBER" }] })}}')}`,
|
||||
`@{choose('${JSON.stringify({ properties: [] })}')}`,
|
||||
])("blocks an explicitly damaged JSON descriptor in %s", tag => {
|
||||
const result = analyze({ combineFilters: { condition: "and", filters: [{ key: "日期", compare: "gt", value: tag }] } });
|
||||
expect(result.summary.passed).toBe(false);
|
||||
expect(result.diagnostics).toMatchObject([{ code: "INVALID_CHOOSE_DESCRIPTOR", category: "hard_block", severity: "error" }]);
|
||||
expect(result.diagnostics[0].message).toContain("日期");
|
||||
});
|
||||
|
||||
test("checks runtime expressions in filters, lookup codes, loops and nested details", () => {
|
||||
const missing = descriptor("action_missing");
|
||||
for (const config of [
|
||||
{ combineFilters: { filters: [{ filters: [{ key: "日期", value: missing, compare: "gt" }], condition: "and" }], condition: "or" } },
|
||||
{ filters: [{ key: "日期", value: missing }] },
|
||||
{ conditions: { value: missing } },
|
||||
{ flowCode: missing },
|
||||
{ list: missing },
|
||||
{ details: { fixed: [{ amount: missing }] } },
|
||||
]) {
|
||||
const result = analyze(config);
|
||||
expect(result.diagnostics.map(item => item.code)).toContain("BROKEN_CHOOSE_REFERENCE");
|
||||
expect(result.summary.passed).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test("warns about DataLink inclusive comparison compatibility without rewriting boundaries", () => {
|
||||
const config = { type: "ekuaibao-datalink-filter", combineFilters: { filters: [
|
||||
{ key: "日期", compare: "gte", value: descriptor("trigger_actual") },
|
||||
{ key: "日期", compare: "lte", value: descriptor("trigger_actual") },
|
||||
] } };
|
||||
const original = JSON.stringify(config);
|
||||
const result = analyze(config);
|
||||
expect(result.diagnostics).toHaveLength(2);
|
||||
expect(result.diagnostics.every(item => item.code === "DATALINK_FILTER_COMPARISON_COMPATIBILITY" && item.category === "soft_advice")).toBe(true);
|
||||
expect(result.diagnostics[0].message).toContain("边界");
|
||||
expect(JSON.stringify(config)).toBe(original);
|
||||
expect(analyze({ type: "ekuaibao-datalink-filter", filters: config.combineFilters.filters }).diagnostics).toHaveLength(2);
|
||||
for (const compare of ["gt", "lt"]) {
|
||||
expect(analyze({ ...config, combineFilters: { filters: [{ key: "日期", compare, value: descriptor("trigger_actual") }] } }).diagnostics).toEqual([]);
|
||||
}
|
||||
expect(analyze({ ...config, type: "condition", tasks: [{ name: "child", type: "http" }] }).diagnostics).toEqual([]);
|
||||
});
|
||||
|
||||
test.each(["@{choose(control_loop.$item)}", "@{choose('control_loop.$item.data')}", descriptor("control_loop.$item")])("blocks old loop item paths in %s", tag => {
|
||||
const result = analyze({ fields: [{ key: "value", value: tag }] });
|
||||
expect(result.summary.passed).toBe(false);
|
||||
|
||||
Reference in new issue
Block a user