feat(platform,datalink,bill): add workflow job drilldown, safe record batch-edit, audit, and spec linkage diagnostics (v0.8.11)
This commit is contained in:
1 parent
2ec08033e0
commit
a0ec7f95a7
37 files changed
+3958
-674
No files matched your search
@@ -4,9 +4,11 @@ import {
|
||||
RawBillSearchResponseSchema,
|
||||
RawBillBatchGetResponseSchema,
|
||||
EntityListResponseSchema,
|
||||
FormSpecificationSchema,
|
||||
type RawBillSearchResponse,
|
||||
type RawBillItem,
|
||||
type EntityMeta,
|
||||
type FormSpecification,
|
||||
} from "./types.js";
|
||||
|
||||
function quoted(value: string): string {
|
||||
@@ -472,3 +474,31 @@ export async function getDatalinkCard(
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
// ── 单据模板规格定义 API(GET api/form/v2/specifications/[{specificationId}])──
|
||||
|
||||
export async function getFormSpecification(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
specificationId: string
|
||||
): Promise<FormSpecification | undefined> {
|
||||
const cleanId = specificationId.replace(/^\[|\]$/g, "").trim();
|
||||
if (!cleanId) return undefined;
|
||||
const response = await client.get(
|
||||
`api/form/v2/specifications/[${encodeURIComponent(cleanId)}]`,
|
||||
{
|
||||
searchParams: { corpId },
|
||||
}
|
||||
);
|
||||
const json = (await response.json()) as {
|
||||
items?: unknown[];
|
||||
value?: unknown;
|
||||
id?: string;
|
||||
};
|
||||
const raw = Array.isArray(json.items)
|
||||
? json.items[0]
|
||||
: json.value ?? (typeof json.id === "string" ? json : undefined);
|
||||
if (!raw || typeof raw !== "object") return undefined;
|
||||
return FormSpecificationSchema.parse(raw);
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
commentBillAction,
|
||||
getInvoiceValidationDetail,
|
||||
getDatalinkCard,
|
||||
getFormSpecification,
|
||||
type BillActionOptions,
|
||||
type BillActionTarget,
|
||||
} from "./api.js";
|
||||
@@ -48,6 +49,9 @@ import {
|
||||
type BillRelationsReport,
|
||||
type BillAttachment,
|
||||
type BillAttachmentReport,
|
||||
type FormSpecification,
|
||||
type FormSpecificationComponent,
|
||||
type FormPriorityItem,
|
||||
} from "./types.js";
|
||||
import { CorpContext } from "../../core/config/manager.js";
|
||||
import { createSessionClient } from "../../core/http/session-client.js";
|
||||
@@ -1596,6 +1600,73 @@ export async function getTranslatorContext(
|
||||
};
|
||||
}
|
||||
|
||||
export function formatFormPriorityList(priorityList: FormPriorityItem[] | undefined): string {
|
||||
if (!Array.isArray(priorityList) || priorityList.length === 0) return "-";
|
||||
const sorted = [...priorityList].sort((a, b) => b.priority - a.priority);
|
||||
return sorted.map((p) => `${p.type}(${p.priority})`).join(" > ");
|
||||
}
|
||||
|
||||
export function hasLinkageOverridePriority(priorityList: FormPriorityItem[] | undefined): boolean {
|
||||
if (!Array.isArray(priorityList) || priorityList.length === 0) return false;
|
||||
const linkage = priorityList.find((p) => p.type === "LINKAGE_ASSIGNMENT");
|
||||
const manual = priorityList.find((p) => p.type === "MANUALLY_FILL_IN");
|
||||
if (!linkage || !manual) return false;
|
||||
return linkage.priority > manual.priority;
|
||||
}
|
||||
|
||||
export interface FormSpecificationInspection {
|
||||
specification: FormSpecification;
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
export async function inspectFormSpecification(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
specificationId: string
|
||||
): Promise<FormSpecificationInspection | undefined> {
|
||||
const spec = await getFormSpecification(client, corpId, specificationId);
|
||||
if (!spec) return undefined;
|
||||
|
||||
const warnings: string[] = [];
|
||||
const linkageSources = spec.components.filter(
|
||||
(c) => c.isLinkageAssignment === true || Boolean(c.assignmentRule)
|
||||
);
|
||||
const overrideTargets = spec.components.filter((c) =>
|
||||
hasLinkageOverridePriority(c.priorityList)
|
||||
);
|
||||
|
||||
for (const src of linkageSources) {
|
||||
if (src.isLinkageAssignment) {
|
||||
warnings.push(
|
||||
`字段 [${src.label || src.name}] (${src.name}, type=${src.type}) 开启了联动赋值 (isLinkageAssignment=true, assignmentRule=${src.assignmentRule || "-"})`
|
||||
);
|
||||
} else if (src.assignmentRule) {
|
||||
warnings.push(
|
||||
`字段 [${src.label || src.name}] (${src.name}, type=${src.type}) 配置了联动规则 (assignmentRule=${src.assignmentRule}, 当前 isLinkageAssignment=false)`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (linkageSources.length > 0 && overrideTargets.length > 0) {
|
||||
const targetNames = overrideTargets.map((t) => `${t.label || t.name}(${t.name})`).join("、");
|
||||
warnings.push(
|
||||
`优先级覆盖风险: 字段 [${targetNames}] 的赋值优先级中 LINKAGE_ASSIGNMENT 高于 MANUALLY_FILL_IN(如 LINKAGE_ASSIGNMENT(10) > MANUALLY_FILL_IN(5)),当关联业务对象触发联动赋值时,手动填写或工作流 API 显式传入的值将被联动值覆盖!`
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
specification: spec,
|
||||
warnings,
|
||||
};
|
||||
}
|
||||
|
||||
export {
|
||||
getFormSpecification,
|
||||
type FormSpecification,
|
||||
type FormSpecificationComponent,
|
||||
type FormPriorityItem,
|
||||
};
|
||||
|
||||
export {
|
||||
translateBillFlowToMarkdown,
|
||||
formatBillFlowOperator,
|
||||
@@ -1612,3 +1683,4 @@ export {
|
||||
formatDynamicField,
|
||||
type TranslatorOptions,
|
||||
} from "./translator.js";
|
||||
|
||||
@@ -26,6 +26,60 @@ export const EntityListResponseSchema = z.object({
|
||||
items: z.array(EntitySchema).default([]),
|
||||
});
|
||||
|
||||
export const FormPriorityItemSchema = z
|
||||
.object({
|
||||
type: z.string(),
|
||||
label: z.string().optional().default(""),
|
||||
priority: z.number().optional(),
|
||||
value: z.number().optional(),
|
||||
})
|
||||
.passthrough()
|
||||
.transform((item) => ({
|
||||
...item,
|
||||
priority: item.priority ?? item.value ?? 0,
|
||||
}));
|
||||
|
||||
export const FormSpecificationComponentSchema = z
|
||||
.object({
|
||||
id: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
field: z.string().optional(),
|
||||
label: z.string().optional().default(""),
|
||||
type: z.string().default("text"),
|
||||
optional: z.boolean().optional().default(true),
|
||||
editable: z.boolean().optional().default(true),
|
||||
hidden: z.boolean().optional().default(false),
|
||||
isLinkageAssignment: z.boolean().optional().default(false),
|
||||
assignmentRule: z.string().nullable().optional(),
|
||||
priorityList: z.array(FormPriorityItemSchema).nullable().optional(),
|
||||
priority: z.array(FormPriorityItemSchema).nullable().optional(),
|
||||
entityId: z.string().nullable().optional(),
|
||||
referenceData: z.string().nullable().optional(),
|
||||
dimensionId: z.string().nullable().optional(),
|
||||
})
|
||||
.passthrough()
|
||||
.transform((comp) => ({
|
||||
...comp,
|
||||
name: comp.name || comp.field || comp.label || "",
|
||||
priorityList: comp.priorityList ?? comp.priority ?? [],
|
||||
entityId: comp.entityId ?? comp.referenceData ?? null,
|
||||
}));
|
||||
|
||||
export const FormSpecificationSchema = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
name: z.string().optional().default(""),
|
||||
type: z.string().optional().default(""),
|
||||
active: z.boolean().optional().default(true),
|
||||
configs: z.unknown().optional(),
|
||||
components: z.array(FormSpecificationComponentSchema).optional().default([]),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export type FormPriorityItem = z.infer<typeof FormPriorityItemSchema>;
|
||||
export type FormSpecificationComponent = z.infer<typeof FormSpecificationComponentSchema>;
|
||||
export type FormSpecification = z.infer<typeof FormSpecificationSchema>;
|
||||
|
||||
// ── 原始单据条目(Raw Bill Item from /api/v2/invoice/search)─────────────────────
|
||||
|
||||
export const RawBillMoneySchema = z.object({
|
||||
|
||||
@@ -30,15 +30,20 @@ hose-use platform list
|
||||
hose-use platform get <应用 ID|名称>
|
||||
hose-use platform entities <应用 ID|名称>
|
||||
hose-use platform schema <应用 ID|名称> [对象 ID|名称] [--keyword <字段关键词>]
|
||||
hose-use platform records <应用 ID|名称> <对象 ID|名称> [--keyword <关键词>] [--filter <表达式>] [--fields <字段列表>]
|
||||
hose-use platform record get <应用> <业务对象> <记录ID>
|
||||
hose-use platform records <应用 ID|名称> <对象 ID|名称> [--all] [--keyword <关键词>] [--filter <表达式>] [--fields <字段列表>]
|
||||
hose-use platform record get [<应用> <业务对象>] <记录ID>
|
||||
hose-use platform record toggle <应用> <业务对象> <记录ID> [--state=true|false] [--dry-run|--yes]
|
||||
hose-use platform record edit <应用> <业务对象> <记录ID> --data='{"field": "val"}' [--dry-run|--yes]
|
||||
hose-use platform record edit <应用> <业务对象> <记录ID> --data='{"field": "val"}' [--raw] [--dry-run|--yes]
|
||||
hose-use platform record batch-edit <应用> <业务对象> [--ids=id1,id2|--filter=...] --data='{"field": "val"}' [--concurrency=8] [--dry-run|--yes]
|
||||
hose-use platform record recompute <应用> <业务对象> <记录ID> [--dry-run|--yes]
|
||||
hose-use platform audit <应用 ID|名称> <对象 ID|名称> [--check-fields=字段1,字段2] [--active-only]
|
||||
hose-use platform permissions <应用 ID|名称> [对象 ID|名称]
|
||||
hose-use platform imports <应用 ID|名称> <对象 ID|名称>
|
||||
```
|
||||
|
||||
也可以使用 `datalink` / `data-link` 作为同义命令域。
|
||||
|
||||
单条业务对象记录支持通过 `record get`(详情)、`record toggle`(启停用)、`record edit`(字段编辑更新)以及 `record recompute`(台账重算)进行维护。Excel 批量上传与流程引擎触发暂不在本域开放。
|
||||
- `record get` 支持直传 `<记录ID>` 免传应用与业务对象。
|
||||
- `record edit` 与 `record batch-edit` 默认启用 **Read-Modify-Write 安全全量合并**(保留全部 `E_<entityId>_*` 字段、将嵌套引用对象归一化为字符串 ID、保留 `active` 与 `visibility` 结构,支持字段短名/中文标签映射);仅当显式传入 `--raw` 时才直接透传原始补丁。
|
||||
- `records --all` 自动按 `500` 条/页循环拉取全量台账记录。
|
||||
- `audit` 一键巡检必填/指定字段缺失、引用已停用档案以及跨台账同名字段同步差异,并输出 `suggestedPatches`。
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
DatalinkEntitySchema,
|
||||
DatalinkPlatformDetailSchema,
|
||||
type DatalinkEntity,
|
||||
type DatalinkField,
|
||||
type DatalinkImportJob,
|
||||
type DatalinkPlatformDetail,
|
||||
type DatalinkRecord,
|
||||
@@ -266,6 +267,248 @@ export async function editRecord(
|
||||
return (json.value ?? json.data ?? json) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
const REFERENCE_FIELD_TYPES = new Set([
|
||||
"dimension",
|
||||
"dataLink",
|
||||
"staff",
|
||||
"department",
|
||||
"role",
|
||||
"reference",
|
||||
]);
|
||||
|
||||
const SYSTEM_RECORD_KEYS = new Set([
|
||||
"id",
|
||||
"entityId",
|
||||
"active",
|
||||
"visibility",
|
||||
"createTime",
|
||||
"updateTime",
|
||||
"corporationId",
|
||||
"platformId",
|
||||
"ownerId",
|
||||
"creatorId",
|
||||
"form",
|
||||
"fieldAuth",
|
||||
"actions",
|
||||
"source",
|
||||
"sourceId",
|
||||
]);
|
||||
|
||||
function extractReferenceId(value: unknown): string | undefined {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
||||
const obj = value as Record<string, unknown>;
|
||||
if ("standard" in obj) return undefined;
|
||||
if (typeof obj.id === "string" && obj.id) return obj.id;
|
||||
if (obj.dataLink && typeof obj.dataLink === "object" && !Array.isArray(obj.dataLink)) {
|
||||
const dl = obj.dataLink as Record<string, unknown>;
|
||||
if (typeof dl.id === "string" && dl.id) return dl.id;
|
||||
}
|
||||
if (obj.data && typeof obj.data === "object" && !Array.isArray(obj.data)) {
|
||||
const dataObj = obj.data as Record<string, unknown>;
|
||||
if (typeof dataObj.id === "string" && dataObj.id) return dataObj.id;
|
||||
if (dataObj.dataLink && typeof dataObj.dataLink === "object" && !Array.isArray(dataObj.dataLink)) {
|
||||
const dl = dataObj.dataLink as Record<string, unknown>;
|
||||
if (typeof dl.id === "string" && dl.id) return dl.id;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function normalizeRecordFieldValue(
|
||||
value: unknown,
|
||||
fieldDef?: DatalinkField
|
||||
): unknown {
|
||||
if (value === undefined) return undefined;
|
||||
if (value === null) return "";
|
||||
const isRefType = fieldDef ? REFERENCE_FIELD_TYPES.has(fieldDef.type) : false;
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((item) => {
|
||||
const refId = extractReferenceId(item);
|
||||
if (refId && (isRefType || refId)) {
|
||||
return refId;
|
||||
}
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
if (typeof value === "object" && "standard" in (value as Record<string, unknown>)) {
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
const refId = extractReferenceId(value);
|
||||
if (refId && (isRefType || refId)) {
|
||||
return refId;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
export function resolveEntityFieldKey(
|
||||
inputKey: string,
|
||||
entityId: string,
|
||||
fields: DatalinkField[] = [],
|
||||
existingForm: Record<string, unknown> = {}
|
||||
): { key: string; fieldDef?: DatalinkField } {
|
||||
const bareEntityId = entityId.startsWith("$") ? entityId.slice(1) : entityId;
|
||||
const exactByName = fields.find((f) => f.name === inputKey);
|
||||
if (exactByName) {
|
||||
return { key: exactByName.name, fieldDef: exactByName };
|
||||
}
|
||||
const prefixedKey = `E_${bareEntityId}_${inputKey}`;
|
||||
const byPrefixedName = fields.find((f) => f.name === prefixedKey);
|
||||
if (byPrefixedName) {
|
||||
return { key: byPrefixedName.name, fieldDef: byPrefixedName };
|
||||
}
|
||||
const byLabel = fields.find((f) => f.label === inputKey);
|
||||
if (byLabel && byLabel.name) {
|
||||
return { key: byLabel.name, fieldDef: byLabel };
|
||||
}
|
||||
if (inputKey.startsWith(`E_${bareEntityId}_`)) {
|
||||
return { key: inputKey };
|
||||
}
|
||||
if (prefixedKey in existingForm) {
|
||||
return { key: prefixedKey };
|
||||
}
|
||||
if (fields.some((f) => f.name.startsWith(`E_${bareEntityId}_`)) && !(inputKey in existingForm)) {
|
||||
return { key: prefixedKey };
|
||||
}
|
||||
return { key: inputKey };
|
||||
}
|
||||
|
||||
export interface SafeRecordEditOptions {
|
||||
entityId: string;
|
||||
recordId: string;
|
||||
detail?: DatalinkRecordDetail | Record<string, unknown>;
|
||||
fields?: DatalinkField[];
|
||||
patchForm: Record<string, unknown>;
|
||||
active?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建安全的业务对象记录 Read-Modify-Write 编辑 Payload:
|
||||
* 1. 自动提取并保留原记录全部 E_<entityId>_* 及已有业务字段;
|
||||
* 2. 自动将 dimension / dataLink / staff / department 等引用对象 { id: "ID01..." } 归一化为字符串 ID;
|
||||
* 3. 自动保留 active 与 visibility(将 staff/role/department 映射为 staffs/roles/departments);
|
||||
* 4. 支持按完整字段名(E_<entityId>_xxx)或简写字段显示名/后缀(我方签约主体、name、code)合并变更。
|
||||
*/
|
||||
export function buildSafeRecordEditPayload(
|
||||
options: SafeRecordEditOptions
|
||||
): DatalinkRecordEditPayload {
|
||||
const bareEntityId = options.entityId.startsWith("$")
|
||||
? options.entityId.slice(1)
|
||||
: options.entityId;
|
||||
const bareRecordId = options.recordId.startsWith("$")
|
||||
? options.recordId.slice(1)
|
||||
: options.recordId;
|
||||
const fields = options.fields ?? [];
|
||||
const detailObj = asRecord(options.detail);
|
||||
const nestedData = asRecord(detailObj.data);
|
||||
const record = asRecord(
|
||||
detailObj.dataLink ?? nestedData.dataLink ?? detailObj
|
||||
);
|
||||
|
||||
const mergedForm: Record<string, unknown> = {};
|
||||
const fieldByName = new Map<string, DatalinkField>();
|
||||
for (const f of fields) {
|
||||
if (f.name) fieldByName.set(f.name, f);
|
||||
}
|
||||
|
||||
// 1. 提取 record.form 中的字段(兼容测试与部分特殊实体结构)
|
||||
if (record.form && typeof record.form === "object" && !Array.isArray(record.form)) {
|
||||
for (const [k, v] of Object.entries(record.form as Record<string, unknown>)) {
|
||||
const fDef = fieldByName.get(k);
|
||||
mergedForm[k] = normalizeRecordFieldValue(v, fDef);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 提取原记录中的 E_<entityId>_* 字段与 schema 中定义的业务字段
|
||||
const entityPrefix = `E_${bareEntityId}_`;
|
||||
for (const [k, v] of Object.entries(record)) {
|
||||
if (SYSTEM_RECORD_KEYS.has(k)) continue;
|
||||
const fDef = fieldByName.get(k);
|
||||
if (k.startsWith(entityPrefix) || k.startsWith("E_") || fDef) {
|
||||
mergedForm[k] = normalizeRecordFieldValue(v, fDef);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 合并用户传入的 patchForm(支持字段名、中文显示名或后缀简写)
|
||||
for (const [rawKey, rawVal] of Object.entries(options.patchForm)) {
|
||||
const { key, fieldDef } = resolveEntityFieldKey(
|
||||
rawKey,
|
||||
bareEntityId,
|
||||
fields,
|
||||
mergedForm
|
||||
);
|
||||
mergedForm[key] = normalizeRecordFieldValue(rawVal, fieldDef);
|
||||
}
|
||||
|
||||
// 4. 保留 active 与 visibility
|
||||
const resolvedActive =
|
||||
options.active !== undefined
|
||||
? options.active
|
||||
: typeof record.active === "boolean"
|
||||
? record.active
|
||||
: true;
|
||||
|
||||
const rawVis = asRecord(record.visibility);
|
||||
const normalizeRefIdList = (list: unknown): string[] => {
|
||||
if (!Array.isArray(list)) return [];
|
||||
return list
|
||||
.map((item) =>
|
||||
typeof item === "string"
|
||||
? item
|
||||
: item && typeof item === "object" && typeof (item as Record<string, unknown>).id === "string"
|
||||
? String((item as Record<string, unknown>).id)
|
||||
: undefined
|
||||
)
|
||||
.filter((item): item is string => Boolean(item));
|
||||
};
|
||||
|
||||
const visibility = {
|
||||
fullVisible:
|
||||
typeof rawVis.fullVisible === "boolean" ? rawVis.fullVisible : true,
|
||||
staffs: normalizeRefIdList(rawVis.staffs ?? rawVis.staff),
|
||||
roles: normalizeRefIdList(rawVis.roles ?? rawVis.role),
|
||||
departments: normalizeRefIdList(rawVis.departments ?? rawVis.department),
|
||||
departmentsIncludeChildren:
|
||||
typeof rawVis.departmentsIncludeChildren === "boolean"
|
||||
? rawVis.departmentsIncludeChildren
|
||||
: false,
|
||||
};
|
||||
|
||||
return {
|
||||
dataLinkEntityId: bareEntityId,
|
||||
dataLinkId: bareRecordId,
|
||||
active: resolvedActive,
|
||||
form: mergedForm,
|
||||
visibility,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全编辑单条业务对象记录(Read-Modify-Write 模式)。
|
||||
*/
|
||||
export async function safeEditRecord(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
options: Omit<SafeRecordEditOptions, "detail"> & {
|
||||
detail?: DatalinkRecordDetail | Record<string, unknown>;
|
||||
}
|
||||
): Promise<{
|
||||
payload: DatalinkRecordEditPayload;
|
||||
result: Record<string, unknown>;
|
||||
}> {
|
||||
const detail =
|
||||
options.detail ?? (await getRecordDetail(client, corpId, options.recordId));
|
||||
const payload = buildSafeRecordEditPayload({
|
||||
...options,
|
||||
detail,
|
||||
});
|
||||
const result = await editRecord(client, corpId, payload);
|
||||
return { payload, result };
|
||||
}
|
||||
|
||||
/** 重算业务对象记录下的台账信息。 */
|
||||
export async function recomputeRecordLedger(
|
||||
client: KyInstance,
|
||||
@@ -278,3 +521,4 @@ export async function recomputeRecordLedger(
|
||||
});
|
||||
return asRecord(await response.json());
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import {
|
||||
buildSafeRecordEditPayload,
|
||||
editRecord,
|
||||
getPlatform,
|
||||
getRecordDetail,
|
||||
@@ -9,7 +10,13 @@ import {
|
||||
searchEntityRecords,
|
||||
toggleRecordState,
|
||||
} from "./api.js";
|
||||
import { buildKeywordFilter, selectRecordFields } from "./services.js";
|
||||
import {
|
||||
auditEntityRecords,
|
||||
batchSafeEditRecords,
|
||||
buildKeywordFilter,
|
||||
fetchAllEntityRecords,
|
||||
selectRecordFields,
|
||||
} from "./services.js";
|
||||
|
||||
const platform = {
|
||||
id: "platform-1",
|
||||
@@ -167,5 +174,217 @@ describe("DataLink Domain - 应用、业务对象与记录查询", () => {
|
||||
const result = await recomputeRecordLedger(client, "corp-1", "record-1");
|
||||
expect(result.id).toBe("ok");
|
||||
});
|
||||
|
||||
test("buildSafeRecordEditPayload 执行 Read-Modify-Write 安全合并并归一化嵌套引用 ID 与 visibility", async () => {
|
||||
const fields = [
|
||||
{ name: "E_e1_name", label: "合同名称", type: "text" },
|
||||
{ name: "E_e1_company", label: "我方签约主体", type: "dimension" },
|
||||
{ name: "E_e1_supplier", label: "供应商", type: "supplier" },
|
||||
{ name: "E_e1_amount", label: "合同金额", type: "money" },
|
||||
];
|
||||
const detail = {
|
||||
dataLink: {
|
||||
id: "ID01VSau4VJWSH",
|
||||
active: true,
|
||||
E_e1_name: "年度采购合同",
|
||||
E_e1_company: null,
|
||||
E_e1_supplier: { id: "ID01SUP123", name: "测试供应商" },
|
||||
E_e1_amount: { standard: "1000.00", standardUnit: "元", standardScale: 2 },
|
||||
visibility: {
|
||||
fullVisible: false,
|
||||
staff: [{ id: "staff-1" }],
|
||||
role: ["role-1"],
|
||||
department: [],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const payload = buildSafeRecordEditPayload({
|
||||
entityId: "e1",
|
||||
recordId: "ID01VSau4VJWSH",
|
||||
detail,
|
||||
fields: fields as any,
|
||||
patchForm: {
|
||||
我方签约主体: "ID01RnG3b79daL",
|
||||
},
|
||||
});
|
||||
|
||||
expect(payload.dataLinkEntityId).toBe("e1");
|
||||
expect(payload.dataLinkId).toBe("ID01VSau4VJWSH");
|
||||
expect(payload.active).toBe(true);
|
||||
expect(payload.form.E_e1_name).toBe("年度采购合同");
|
||||
expect(payload.form.E_e1_company).toBe("ID01RnG3b79daL");
|
||||
expect(payload.form.E_e1_supplier).toBe("ID01SUP123");
|
||||
expect(payload.form.E_e1_amount).toBe(
|
||||
JSON.stringify({
|
||||
standard: "1000.00",
|
||||
standardUnit: "元",
|
||||
standardScale: 2,
|
||||
})
|
||||
);
|
||||
expect(payload.visibility).toEqual({
|
||||
fullVisible: false,
|
||||
staffs: ["staff-1"],
|
||||
roles: ["role-1"],
|
||||
departments: [],
|
||||
departmentsIncludeChildren: false,
|
||||
});
|
||||
|
||||
let postUrl = "";
|
||||
let postBody: any = null;
|
||||
const client = {
|
||||
post: async (url: string, options: any) => {
|
||||
postUrl = url;
|
||||
postBody = options.json;
|
||||
return { json: async () => ({ value: { id: "ID01VSau4VJWSH" } }) };
|
||||
},
|
||||
} as any;
|
||||
|
||||
await editRecord(client, "corp-1", payload);
|
||||
expect(postUrl).toBe("api/v2/datalink/entityEdit/edit");
|
||||
expect(postBody.form.E_e1_company).toBe("ID01RnG3b79daL");
|
||||
expect(postBody.visibility.staffs).toEqual(["staff-1"]);
|
||||
});
|
||||
|
||||
test("fetchAllEntityRecords 自动分页拉取全量记录", async () => {
|
||||
const calls: Array<{ start: number; count: number }> = [];
|
||||
const client = {
|
||||
post: async (_url: string, options: any) => {
|
||||
const limit = options.json.query.limit;
|
||||
calls.push(limit);
|
||||
if (limit.start === 0) {
|
||||
return {
|
||||
json: async () => ({
|
||||
items: {
|
||||
total: 3,
|
||||
data: [
|
||||
{ id: "r-1", dataLink: { id: "r-1" } },
|
||||
{ id: "r-2", dataLink: { id: "r-2" } },
|
||||
],
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
return {
|
||||
json: async () => ({
|
||||
items: {
|
||||
total: 3,
|
||||
data: [{ id: "r-3", dataLink: { id: "r-3" } }],
|
||||
},
|
||||
}),
|
||||
};
|
||||
},
|
||||
} as any;
|
||||
|
||||
const result = await fetchAllEntityRecords(client, "corp-1", "entity-1", { pageSize: 2 });
|
||||
expect(calls).toEqual([
|
||||
{ start: 0, count: 2 },
|
||||
{ start: 2, count: 2 },
|
||||
]);
|
||||
expect(result.data).toHaveLength(3);
|
||||
});
|
||||
|
||||
test("auditEntityRecords 巡检必填缺失、停用引用与跨台账同名字段同步差异", () => {
|
||||
const childEntity = {
|
||||
id: "e_plan",
|
||||
name: "支付计划表",
|
||||
fields: [
|
||||
{ name: "E_e_plan_code", label: "编码", type: "text", optional: true },
|
||||
{ name: "E_e_plan_company", label: "我方签约主体", type: "dimension", optional: false },
|
||||
{
|
||||
name: "E_e_plan_contract",
|
||||
label: "关联合同流程",
|
||||
type: "dataLink",
|
||||
optional: true,
|
||||
entityId: "e_contract",
|
||||
},
|
||||
],
|
||||
actions: [],
|
||||
importMethod: [],
|
||||
};
|
||||
|
||||
const records = [
|
||||
{
|
||||
id: "plan-1",
|
||||
dataLink: {
|
||||
id: "plan-1",
|
||||
code: "PL-001",
|
||||
name: "第一期付款",
|
||||
active: true,
|
||||
E_e_plan_company: null,
|
||||
E_e_plan_contract: {
|
||||
id: "contract-1",
|
||||
name: "测试合同",
|
||||
active: false,
|
||||
data: {
|
||||
dataLink: {
|
||||
id: "contract-1",
|
||||
code: "HT-001",
|
||||
active: false,
|
||||
E_e_contract_company: {
|
||||
id: "ID01RnG3b79daL",
|
||||
name: "北京转转精神科技有限责任公司",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const report = auditEntityRecords(records as any, childEntity as any, {
|
||||
checkFields: ["我方签约主体"],
|
||||
});
|
||||
|
||||
expect(report.totalRecords).toBe(1);
|
||||
expect(report.summary.missingFieldCount).toBe(1);
|
||||
expect(report.summary.disabledReferenceCount).toBe(1);
|
||||
expect(report.summary.crossLedgerMissingSyncCount).toBe(1);
|
||||
expect(report.suggestedPatches).toEqual([
|
||||
{
|
||||
id: "plan-1",
|
||||
code: "PL-001",
|
||||
name: "第一期付款",
|
||||
form: {
|
||||
E_e_plan_company: "ID01RnG3b79daL",
|
||||
},
|
||||
reason: "我方签约主体 <- 北京转转精神科技有限责任公司 (ID01RnG3b79daL)",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("batchSafeEditRecords 支持 dryRun 预览与并发安全合并", async () => {
|
||||
const entity = {
|
||||
id: "e1",
|
||||
name: "合同流程",
|
||||
fields: [{ name: "E_e1_company", label: "我方签约主体", type: "dimension" }],
|
||||
actions: [],
|
||||
importMethod: [],
|
||||
};
|
||||
const client = {
|
||||
get: async () => ({
|
||||
json: async () => ({
|
||||
value: {
|
||||
dataLink: {
|
||||
id: "r-1",
|
||||
active: true,
|
||||
E_e1_company: null,
|
||||
},
|
||||
},
|
||||
}),
|
||||
}),
|
||||
} as any;
|
||||
|
||||
const results = await batchSafeEditRecords(
|
||||
client,
|
||||
"corp-1",
|
||||
entity as any,
|
||||
[{ recordId: "r-1", patchForm: { 我方签约主体: "ID01RnG3b79daL" } }],
|
||||
{ dryRun: true }
|
||||
);
|
||||
expect(results).toHaveLength(1);
|
||||
expect(results[0]?.status).toBe("preview");
|
||||
expect(results[0]?.payload?.form.E_e1_company).toBe("ID01RnG3b79daL");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
import type { KyInstance } from "ky";
|
||||
import * as api from "./api.js";
|
||||
import type { DatalinkEntity, DatalinkField, DatalinkPlatformDetail } from "./types.js";
|
||||
import type {
|
||||
DatalinkEntity,
|
||||
DatalinkField,
|
||||
DatalinkPlatformDetail,
|
||||
DatalinkRecord,
|
||||
DatalinkRecordEditPayload,
|
||||
DatalinkRecordPage,
|
||||
} from "./types.js";
|
||||
|
||||
function matches(value: unknown, target: string): boolean {
|
||||
return typeof value === "string" && value.toLowerCase() === target.toLowerCase();
|
||||
@@ -35,14 +42,21 @@ export function buildKeywordFilter(keyword: string): string {
|
||||
return `(name.containsIgnoreCase("${escaped}")||code.containsIgnoreCase("${escaped}"))&&(active.in(true,false))`;
|
||||
}
|
||||
|
||||
export function selectRecordFields(record: Record<string, unknown>, fields: string[], definitions: DatalinkField[] = []): Record<string, unknown> {
|
||||
export function selectRecordFields(
|
||||
record: Record<string, unknown>,
|
||||
fields: string[],
|
||||
definitions: DatalinkField[] = []
|
||||
): Record<string, unknown> {
|
||||
if (fields.length === 0) return record;
|
||||
const dataLink = record.dataLink && typeof record.dataLink === "object" && !Array.isArray(record.dataLink)
|
||||
? (record.dataLink as Record<string, unknown>)
|
||||
: record;
|
||||
const dataLink =
|
||||
record.dataLink && typeof record.dataLink === "object" && !Array.isArray(record.dataLink)
|
||||
? (record.dataLink as Record<string, unknown>)
|
||||
: record;
|
||||
const selected: Record<string, unknown> = {};
|
||||
for (const selector of fields) {
|
||||
const definition = definitions.find((field) => field.name === selector || field.label === selector);
|
||||
const definition = definitions.find(
|
||||
(field) => field.name === selector || field.label === selector
|
||||
);
|
||||
const sourceName = definition?.name ?? selector;
|
||||
if (sourceName in dataLink) selected[definition?.label || selector] = dataLink[sourceName];
|
||||
}
|
||||
@@ -50,3 +64,493 @@ export function selectRecordFields(record: Record<string, unknown>, fields: stri
|
||||
? { ...record, dataLink: selected }
|
||||
: selected;
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动分页全量拉取指定业务对象的全部记录(默认每页 500 条循环直到底)。
|
||||
*/
|
||||
export async function fetchAllEntityRecords(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
entityId: string,
|
||||
options: { filterBy?: string; pageSize?: number; orderBy?: unknown } = {}
|
||||
): Promise<DatalinkRecordPage> {
|
||||
const pageSize = Math.max(1, Math.min(options.pageSize ?? 500, 1000));
|
||||
let start = 0;
|
||||
let total = 0;
|
||||
const allData: DatalinkRecord[] = [];
|
||||
let firstPage: DatalinkRecordPage | undefined;
|
||||
|
||||
while (true) {
|
||||
const page = await api.searchEntityRecords(client, corpId, entityId, {
|
||||
start,
|
||||
count: pageSize,
|
||||
filterBy: options.filterBy,
|
||||
orderBy: options.orderBy,
|
||||
});
|
||||
firstPage ??= page;
|
||||
total = page.total;
|
||||
if (page.data.length === 0) break;
|
||||
allData.push(...page.data);
|
||||
start += page.data.length;
|
||||
if (allData.length >= total || page.data.length < pageSize) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
total: Math.max(total, allData.length),
|
||||
data: allData,
|
||||
actions: firstPage?.actions ?? [],
|
||||
components: firstPage?.components ?? [],
|
||||
path: firstPage?.path,
|
||||
template: firstPage?.template,
|
||||
};
|
||||
}
|
||||
|
||||
export interface DatalinkAuditIssue {
|
||||
recordId: string;
|
||||
recordCode: string;
|
||||
recordName: string;
|
||||
active: boolean;
|
||||
type:
|
||||
| "MISSING_FIELD"
|
||||
| "DISABLED_REFERENCE"
|
||||
| "CROSS_LEDGER_MISSING_SYNC"
|
||||
| "CROSS_LEDGER_MISMATCH";
|
||||
field: string;
|
||||
fieldLabel: string;
|
||||
message: string;
|
||||
linkedField?: string;
|
||||
linkedFieldLabel?: string;
|
||||
linkedRecordId?: string;
|
||||
actualId?: string;
|
||||
actualName?: string;
|
||||
expectedId?: string;
|
||||
expectedName?: string;
|
||||
}
|
||||
|
||||
export interface DatalinkAuditReport {
|
||||
entityId: string;
|
||||
entityName: string;
|
||||
totalRecords: number;
|
||||
auditedRecords: number;
|
||||
healthyRecords: number;
|
||||
affectedRecordCount: number;
|
||||
issueCount: number;
|
||||
summary: {
|
||||
missingFieldCount: number;
|
||||
disabledReferenceCount: number;
|
||||
crossLedgerMissingSyncCount: number;
|
||||
crossLedgerMismatchCount: number;
|
||||
};
|
||||
issues: DatalinkAuditIssue[];
|
||||
suggestedPatches: Array<{
|
||||
id: string;
|
||||
code: string;
|
||||
name: string;
|
||||
form: Record<string, string>;
|
||||
reason: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
function isEmptyFieldValue(value: unknown): boolean {
|
||||
if (value === undefined || value === null || value === "") return true;
|
||||
if (Array.isArray(value)) return value.length === 0;
|
||||
if (typeof value === "object") {
|
||||
const obj = value as Record<string, unknown>;
|
||||
if ("id" in obj) {
|
||||
return obj.id === undefined || obj.id === null || obj.id === "";
|
||||
}
|
||||
if ("standard" in obj) {
|
||||
return obj.standard === undefined || obj.standard === null || obj.standard === "";
|
||||
}
|
||||
return Object.keys(obj).length === 0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function extractRefIdAndName(value: unknown): {
|
||||
id?: string;
|
||||
name?: string;
|
||||
active?: boolean;
|
||||
} {
|
||||
if (typeof value === "string" && value.trim()) {
|
||||
return { id: value.trim() };
|
||||
}
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||
return {};
|
||||
}
|
||||
const obj = value as Record<string, unknown>;
|
||||
const nestedData =
|
||||
obj.data && typeof obj.data === "object"
|
||||
? (obj.data as Record<string, unknown>)
|
||||
: undefined;
|
||||
const nestedDl =
|
||||
nestedData?.dataLink && typeof nestedData.dataLink === "object"
|
||||
? (nestedData.dataLink as Record<string, unknown>)
|
||||
: obj.dataLink && typeof obj.dataLink === "object"
|
||||
? (obj.dataLink as Record<string, unknown>)
|
||||
: undefined;
|
||||
const id =
|
||||
typeof obj.id === "string" && obj.id.trim()
|
||||
? obj.id.trim()
|
||||
: typeof nestedDl?.id === "string" && nestedDl.id.trim()
|
||||
? nestedDl.id.trim()
|
||||
: undefined;
|
||||
const name =
|
||||
typeof obj.name === "string" && obj.name.trim()
|
||||
? obj.name.trim()
|
||||
: typeof nestedDl?.name === "string" && nestedDl.name.trim()
|
||||
? nestedDl.name.trim()
|
||||
: undefined;
|
||||
const active =
|
||||
typeof obj.active === "boolean"
|
||||
? obj.active
|
||||
: typeof nestedDl?.active === "boolean"
|
||||
? nestedDl.active
|
||||
: undefined;
|
||||
return { id, name, active };
|
||||
}
|
||||
|
||||
/**
|
||||
* 对业务对象记录集合执行数据健康度体检:
|
||||
* 1. 必填/关键字段缺失检查 (MISSING_FIELD)
|
||||
* 2. 关联对象/档案停用检查 (DISABLED_REFERENCE)
|
||||
* 3. 跨表关联同名维度一致性检查 (CROSS_LEDGER_MISSING_SYNC / CROSS_LEDGER_MISMATCH)
|
||||
*/
|
||||
export function auditEntityRecords(
|
||||
records: DatalinkRecord[],
|
||||
entity: DatalinkEntity,
|
||||
options: { checkFields?: string[]; activeOnly?: boolean; total?: number } = {}
|
||||
): DatalinkAuditReport {
|
||||
const bareEntityId = entity.id.startsWith("$") ? entity.id.slice(1) : entity.id;
|
||||
const nameField = entity.fields.find(
|
||||
(f) => f.label === "名称" || f.label === "标题" || f.name === `E_${bareEntityId}_name` || f.name.endsWith("_name")
|
||||
);
|
||||
const codeField = entity.fields.find(
|
||||
(f) => f.label === "编码" || f.name === `E_${bareEntityId}_code` || f.name.endsWith("_code")
|
||||
);
|
||||
|
||||
// 解析需要检查缺失的字段集合
|
||||
const explicitSelectors = (options.checkFields ?? []).map((s) => s.trim()).filter(Boolean);
|
||||
const fieldsToCheck: DatalinkField[] =
|
||||
explicitSelectors.length > 0
|
||||
? explicitSelectors.map((selector) => {
|
||||
const found = entity.fields.find(
|
||||
(f) =>
|
||||
f.name === selector ||
|
||||
f.label === selector ||
|
||||
f.name === `E_${bareEntityId}_${selector}`
|
||||
);
|
||||
return (
|
||||
found ?? {
|
||||
name: selector.startsWith("E_") ? selector : `E_${bareEntityId}_${selector}`,
|
||||
label: selector,
|
||||
type: "text",
|
||||
}
|
||||
);
|
||||
})
|
||||
: entity.fields.filter(
|
||||
(f) =>
|
||||
f.optional === false ||
|
||||
f.type === "dimension" ||
|
||||
f.type === "dataLink"
|
||||
);
|
||||
|
||||
const dataLinkFields = entity.fields.filter((f) => f.type === "dataLink");
|
||||
const dimensionFields = entity.fields.filter((f) => f.type === "dimension");
|
||||
|
||||
const issues: DatalinkAuditIssue[] = [];
|
||||
const suggestedPatchesMap = new Map<
|
||||
string,
|
||||
{ id: string; code: string; name: string; form: Record<string, string>; reasons: string[] }
|
||||
>();
|
||||
const affectedRecordIds = new Set<string>();
|
||||
let auditedRecords = 0;
|
||||
|
||||
let missingFieldCount = 0;
|
||||
let disabledReferenceCount = 0;
|
||||
let crossLedgerMissingSyncCount = 0;
|
||||
let crossLedgerMismatchCount = 0;
|
||||
|
||||
for (const rawRecord of records) {
|
||||
const dl =
|
||||
rawRecord.dataLink &&
|
||||
typeof rawRecord.dataLink === "object" &&
|
||||
!Array.isArray(rawRecord.dataLink)
|
||||
? (rawRecord.dataLink as Record<string, unknown>)
|
||||
: (rawRecord as Record<string, unknown>);
|
||||
const recordId = String(dl.id ?? rawRecord.id ?? "");
|
||||
const active = (dl.active ?? rawRecord.active) !== false;
|
||||
if (options.activeOnly && !active) continue;
|
||||
|
||||
auditedRecords++;
|
||||
const recordName = String(
|
||||
dl.name ??
|
||||
dl["名称"] ??
|
||||
(nameField ? dl[nameField.name] : undefined) ??
|
||||
dl[`E_${bareEntityId}_name`] ??
|
||||
""
|
||||
);
|
||||
const recordCode = String(
|
||||
dl.code ??
|
||||
dl["编码"] ??
|
||||
(codeField ? dl[codeField.name] : undefined) ??
|
||||
dl[`E_${bareEntityId}_code`] ??
|
||||
""
|
||||
);
|
||||
|
||||
const getFieldVal = (field: DatalinkField): unknown =>
|
||||
dl[field.name] ??
|
||||
dl[`E_${bareEntityId}_${field.name}`] ??
|
||||
(dl.form && typeof dl.form === "object"
|
||||
? (dl.form as Record<string, unknown>)[field.name]
|
||||
: undefined) ??
|
||||
dl[field.label];
|
||||
|
||||
// 1. 必填/关键字段缺失检查
|
||||
for (const field of fieldsToCheck) {
|
||||
const val = getFieldVal(field);
|
||||
if (isEmptyFieldValue(val)) {
|
||||
missingFieldCount++;
|
||||
affectedRecordIds.add(recordId);
|
||||
issues.push({
|
||||
recordId,
|
||||
recordCode,
|
||||
recordName,
|
||||
active,
|
||||
type: "MISSING_FIELD",
|
||||
field: field.name,
|
||||
fieldLabel: field.label || field.name,
|
||||
message: `字段 [${field.label || field.name}] (${field.name}) 为空`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 关联对象/档案停用检查
|
||||
for (const field of entity.fields) {
|
||||
if (field.type !== "dimension" && field.type !== "dataLink") continue;
|
||||
const val = getFieldVal(field);
|
||||
const items = Array.isArray(val) ? val : val ? [val] : [];
|
||||
for (const item of items) {
|
||||
const refInfo = extractRefIdAndName(item);
|
||||
if (refInfo.active === false) {
|
||||
disabledReferenceCount++;
|
||||
affectedRecordIds.add(recordId);
|
||||
issues.push({
|
||||
recordId,
|
||||
recordCode,
|
||||
recordName,
|
||||
active,
|
||||
type: "DISABLED_REFERENCE",
|
||||
field: field.name,
|
||||
fieldLabel: field.label || field.name,
|
||||
actualId: refInfo.id,
|
||||
actualName: refInfo.name,
|
||||
message: `字段 [${field.label || field.name}] 引用的${
|
||||
field.type === "dataLink" ? "业务对象记录" : "维度档案"
|
||||
} [${refInfo.name || refInfo.id || "-"}] (${refInfo.id || "-"}) 已停用 (active=false)`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 跨表关联同名维度一致性检查
|
||||
for (const linkField of dataLinkFields) {
|
||||
const linkVal = getFieldVal(linkField);
|
||||
if (!linkVal || typeof linkVal !== "object" || Array.isArray(linkVal)) continue;
|
||||
const linkObj = linkVal as Record<string, unknown>;
|
||||
const parentDl =
|
||||
linkObj.data &&
|
||||
typeof linkObj.data === "object" &&
|
||||
(linkObj.data as Record<string, unknown>).dataLink &&
|
||||
typeof (linkObj.data as Record<string, unknown>).dataLink === "object"
|
||||
? ((linkObj.data as Record<string, unknown>).dataLink as Record<string, unknown>)
|
||||
: linkObj.dataLink && typeof linkObj.dataLink === "object"
|
||||
? (linkObj.dataLink as Record<string, unknown>)
|
||||
: linkObj;
|
||||
const linkedRecordId = String(parentDl.id ?? linkObj.id ?? "");
|
||||
|
||||
for (const dimField of dimensionFields) {
|
||||
const entityPrefix = `E_${bareEntityId}_`;
|
||||
const suffix = dimField.name.startsWith(entityPrefix)
|
||||
? dimField.name.slice(entityPrefix.length)
|
||||
: dimField.name.replace(/^E_[^_]+_/, "");
|
||||
const parentKey = Object.keys(parentDl).find(
|
||||
(k) =>
|
||||
k === dimField.label ||
|
||||
k === suffix ||
|
||||
k.endsWith(`_${suffix}`) ||
|
||||
(Boolean(dimField.label) && k.endsWith(`_${dimField.label}`))
|
||||
);
|
||||
if (!parentKey) continue;
|
||||
|
||||
const parentRef = extractRefIdAndName(parentDl[parentKey]);
|
||||
if (!parentRef.id) continue;
|
||||
|
||||
const childRef = extractRefIdAndName(getFieldVal(dimField));
|
||||
if (!childRef.id) {
|
||||
crossLedgerMissingSyncCount++;
|
||||
affectedRecordIds.add(recordId);
|
||||
const reason = `子表字段 [${dimField.label || dimField.name}] 为空,但关联 [${
|
||||
linkField.label || linkField.name
|
||||
}] (${linkedRecordId}) 中同名字段有值 [${parentRef.name || parentRef.id}] (${
|
||||
parentRef.id
|
||||
}),建议回填修复`;
|
||||
issues.push({
|
||||
recordId,
|
||||
recordCode,
|
||||
recordName,
|
||||
active,
|
||||
type: "CROSS_LEDGER_MISSING_SYNC",
|
||||
field: dimField.name,
|
||||
fieldLabel: dimField.label || dimField.name,
|
||||
linkedField: linkField.name,
|
||||
linkedFieldLabel: linkField.label || linkField.name,
|
||||
linkedRecordId,
|
||||
expectedId: parentRef.id,
|
||||
expectedName: parentRef.name,
|
||||
message: reason,
|
||||
});
|
||||
|
||||
const existingPatch = suggestedPatchesMap.get(recordId) ?? {
|
||||
id: recordId,
|
||||
code: recordCode,
|
||||
name: recordName,
|
||||
form: {},
|
||||
reasons: [],
|
||||
};
|
||||
existingPatch.form[dimField.name] = parentRef.id;
|
||||
existingPatch.reasons.push(
|
||||
`${dimField.label || dimField.name} <- ${parentRef.name || parentRef.id} (${parentRef.id})`
|
||||
);
|
||||
suggestedPatchesMap.set(recordId, existingPatch);
|
||||
} else if (childRef.id !== parentRef.id) {
|
||||
crossLedgerMismatchCount++;
|
||||
affectedRecordIds.add(recordId);
|
||||
issues.push({
|
||||
recordId,
|
||||
recordCode,
|
||||
recordName,
|
||||
active,
|
||||
type: "CROSS_LEDGER_MISMATCH",
|
||||
field: dimField.name,
|
||||
fieldLabel: dimField.label || dimField.name,
|
||||
linkedField: linkField.name,
|
||||
linkedFieldLabel: linkField.label || linkField.name,
|
||||
linkedRecordId,
|
||||
actualId: childRef.id,
|
||||
actualName: childRef.name,
|
||||
expectedId: parentRef.id,
|
||||
expectedName: parentRef.name,
|
||||
message: `子表字段 [${dimField.label || dimField.name}] 当前值 [${
|
||||
childRef.name || childRef.id
|
||||
}] (${childRef.id}) 与关联 [${
|
||||
linkField.label || linkField.name
|
||||
}] (${linkedRecordId}) 中的值 [${parentRef.name || parentRef.id}] (${
|
||||
parentRef.id
|
||||
}) 不一致`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const suggestedPatches = [...suggestedPatchesMap.values()].map((item) => ({
|
||||
id: item.id,
|
||||
code: item.code,
|
||||
name: item.name,
|
||||
form: item.form,
|
||||
reason: item.reasons.join("; "),
|
||||
}));
|
||||
|
||||
return {
|
||||
entityId: entity.id,
|
||||
entityName: entity.name,
|
||||
totalRecords: options.total ?? records.length,
|
||||
auditedRecords,
|
||||
healthyRecords: Math.max(0, auditedRecords - affectedRecordIds.size),
|
||||
affectedRecordCount: affectedRecordIds.size,
|
||||
issueCount: issues.length,
|
||||
summary: {
|
||||
missingFieldCount,
|
||||
disabledReferenceCount,
|
||||
crossLedgerMissingSyncCount,
|
||||
crossLedgerMismatchCount,
|
||||
},
|
||||
issues,
|
||||
suggestedPatches,
|
||||
};
|
||||
}
|
||||
|
||||
export interface BatchEditTargetItem {
|
||||
recordId: string;
|
||||
patchForm: Record<string, unknown>;
|
||||
active?: boolean;
|
||||
}
|
||||
|
||||
export interface BatchEditItemResult {
|
||||
recordId: string;
|
||||
status: "preview" | "updated" | "failed";
|
||||
payload?: DatalinkRecordEditPayload;
|
||||
result?: Record<string, unknown>;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export async function batchSafeEditRecords(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
entity: DatalinkEntity,
|
||||
targets: BatchEditTargetItem[],
|
||||
options: { concurrency?: number; dryRun?: boolean } = {}
|
||||
): Promise<BatchEditItemResult[]> {
|
||||
const concurrency = Math.max(1, Math.min(options.concurrency ?? 8, 32));
|
||||
const results: BatchEditItemResult[] = new Array(targets.length);
|
||||
let cursor = 0;
|
||||
|
||||
const worker = async () => {
|
||||
while (true) {
|
||||
const idx = cursor++;
|
||||
if (idx >= targets.length) break;
|
||||
const target = targets[idx];
|
||||
try {
|
||||
const detail = await api.getRecordDetail(client, corpId, target.recordId);
|
||||
const payload = api.buildSafeRecordEditPayload({
|
||||
entityId: entity.id,
|
||||
recordId: target.recordId,
|
||||
detail,
|
||||
fields: entity.fields,
|
||||
patchForm: target.patchForm,
|
||||
active: target.active,
|
||||
});
|
||||
if (options.dryRun) {
|
||||
results[idx] = {
|
||||
recordId: target.recordId,
|
||||
status: "preview",
|
||||
payload,
|
||||
};
|
||||
} else {
|
||||
const res = await api.editRecord(client, corpId, payload);
|
||||
results[idx] = {
|
||||
recordId: target.recordId,
|
||||
status: "updated",
|
||||
payload,
|
||||
result: res,
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
results[idx] = {
|
||||
recordId: target.recordId,
|
||||
status: "failed",
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
await Promise.all(
|
||||
Array.from({ length: Math.min(concurrency, targets.length) }, () => worker())
|
||||
);
|
||||
return results;
|
||||
}
|
||||
|
||||
@@ -6,9 +6,20 @@ Platform 域负责工作流(EASO/Piper)以及自建应用容器的兼容能
|
||||
|
||||
```text
|
||||
src/domains/platform/
|
||||
├── types.ts # Zod schema 与类型定义
|
||||
├── api.ts # HTTP 传输层
|
||||
└── tools.ts # MCP tool 注册 + 服务层聚合函数
|
||||
├── types.ts # Zod schema 与类型定义(含 Job 执行树、失败节点、节点日志)
|
||||
├── api.ts # HTTP 传输层(含 unwrap 空安全校验与 Piper Job 5 大诊断端点)
|
||||
├── analysis.ts # 工作流静态分析(禁用状态、SKIP 无状态守卫、单据联动覆盖诊断)
|
||||
└── tools.ts # MCP tool 注册 + 服务层聚合函数
|
||||
```
|
||||
|
||||
## CLI 常用命令
|
||||
|
||||
```bash
|
||||
hose-use workflow list [--platform-id=<id>|--app-id=<id>]
|
||||
hose-use workflow get <pipelineId>
|
||||
hose-use workflow analyze <pipelineId> [--json]
|
||||
hose-use workflow logs <pipelineId> [--has-error] [--state=FAILED]
|
||||
hose-use workflow job <jobId> [--failed] [--parent=<executionId>] [--logs=<executionId>]
|
||||
```
|
||||
|
||||
## 详细文档
|
||||
|
||||
@@ -13,8 +13,102 @@ describe("Workflow static analysis", () => {
|
||||
const result = analyzeWorkflow({ id: "wf-1", label: "审批", state: 1, version: "3", tasks: [{ name: "条件", type: "condition", label: "条件", groupName: "", orderIndex: 0, levelIndex: [0], status: "", tasks: [{ name: "脚本", type: "code-js2", label: "脚本", groupName: "", orderIndex: 1, levelIndex: [0, 0], status: "", code: "return {{bill.amount}} + ctx.user.id;" }] }] } as any);
|
||||
expect(result.ast[0]?.children[0]?.path).toBe("0.0"); expect(result.dependencies[0]?.references).toEqual(["bill.amount", "user.id"]); expect(result.diagnostics).toHaveLength(0);
|
||||
});
|
||||
it("reports empty scripts and branches", () => {
|
||||
it("reports empty scripts, branches, and disabled workflow state", () => {
|
||||
const result = analyzeWorkflow({ id: "wf-2", label: "异常", state: 0, version: "", tasks: [{ name: "脚本", type: "code", label: "", groupName: "", orderIndex: 0, levelIndex: [0], status: "", code: "" }, { name: "条件", type: "condition", label: "", groupName: "", orderIndex: 1, levelIndex: [1], status: "", tasks: [] }] } as any);
|
||||
expect(result.diagnostics.map((item) => item.code)).toEqual(["EMPTY_CODE", "EMPTY_BRANCH"]);
|
||||
expect(result.diagnostics.map((item) => item.code)).toEqual(["WORKFLOW_DISABLED", "EMPTY_CODE", "EMPTY_BRANCH"]);
|
||||
});
|
||||
|
||||
it("detects UNSAFE_SKIP_WITHOUT_STATUS_GUARD and LINKAGE_PRIORITY_OVERRIDE", () => {
|
||||
const wf = {
|
||||
id: "886351399301758976",
|
||||
label: "【生产】每30分钟创建采购申请单",
|
||||
state: 1,
|
||||
version: "10",
|
||||
tasks: [
|
||||
{
|
||||
name: "every_0",
|
||||
type: "every",
|
||||
label: "循环每条支付计划",
|
||||
groupName: "control",
|
||||
orderIndex: 1,
|
||||
levelIndex: [0],
|
||||
status: "",
|
||||
tasks: [
|
||||
{
|
||||
name: "ekuaibao_flow_create_task_0",
|
||||
type: "flow-create-task",
|
||||
label: "创建预付申请单",
|
||||
groupName: "ekuaibao",
|
||||
orderIndex: 0,
|
||||
levelIndex: [0, 0],
|
||||
status: "",
|
||||
onError: { defaultAction: "SKIP" },
|
||||
inputs: {
|
||||
specificationId: "ID01TxgE3fhD6n",
|
||||
form: {
|
||||
u_关联合同流程: "{{every_0.item.E_contract}}",
|
||||
u_我方签约主体: "{{every_0.item.E_company}}",
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "ekuaibao_datalink_edit_0",
|
||||
type: "ekuaibao-datalink-edit",
|
||||
label: "更新支付计划状态为创建成功",
|
||||
groupName: "ekuaibao",
|
||||
orderIndex: 1,
|
||||
levelIndex: [0, 1],
|
||||
status: "",
|
||||
inputs: {
|
||||
dataLinkId: "{{every_0.item.id}}",
|
||||
form: {
|
||||
状态: "创建成功",
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const specifications = {
|
||||
ID01TxgE3fhD6n: {
|
||||
id: "ID01TxgE3fhD6n",
|
||||
name: "预付申请单",
|
||||
form: [
|
||||
{
|
||||
id: "f1",
|
||||
name: "u_关联合同流程",
|
||||
label: "关联合同流程",
|
||||
type: "dataLink",
|
||||
optional: false,
|
||||
entityId: "e23d0d5451b1ccabfd7a",
|
||||
assignmentRule: "ID01TRWvYFAulh",
|
||||
isLinkageAssignment: false,
|
||||
priorityList: [
|
||||
{ type: "LINKAGE_ASSIGNMENT", priority: 10 },
|
||||
{ type: "MANUALLY_FILL_IN", priority: 5 },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "f2",
|
||||
name: "u_我方签约主体",
|
||||
label: "我方签约主体",
|
||||
type: "dimension",
|
||||
optional: false,
|
||||
isLinkageAssignment: true,
|
||||
priorityList: [
|
||||
{ type: "LINKAGE_ASSIGNMENT", priority: 10 },
|
||||
{ type: "MANUALLY_FILL_IN", priority: 5 },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const result = analyzeWorkflow(wf as any, { specifications: specifications as any });
|
||||
const codes = result.diagnostics.map((d) => d.code);
|
||||
expect(codes).toContain("UNSAFE_SKIP_WITHOUT_STATUS_GUARD");
|
||||
expect(codes).toContain("LINKAGE_PRIORITY_OVERRIDE");
|
||||
});
|
||||
});
|
||||
@@ -1,19 +1,400 @@
|
||||
import type { WorkflowDetail, WorkflowTask } from "./types.js";
|
||||
|
||||
export interface WorkflowAstNode { type: string; name: string; label: string; path: string; orderIndex: number; levelIndex: number[]; children: WorkflowAstNode[]; }
|
||||
export interface WorkflowDependency { path: string; taskType: string; references: string[]; }
|
||||
export interface WorkflowDiagnostic { severity: "warning" | "error"; code: string; path: string; message: string; }
|
||||
export interface WorkflowAnalysis { workflow: { id: string; label: string; state: number; version: string }; ast: WorkflowAstNode[]; dependencies: WorkflowDependency[]; diagnostics: WorkflowDiagnostic[]; }
|
||||
export interface WorkflowAstNode {
|
||||
type: string;
|
||||
name: string;
|
||||
label: string;
|
||||
path: string;
|
||||
orderIndex: number;
|
||||
levelIndex: number[];
|
||||
children: WorkflowAstNode[];
|
||||
}
|
||||
|
||||
export interface WorkflowDependency {
|
||||
path: string;
|
||||
taskType: string;
|
||||
references: string[];
|
||||
}
|
||||
|
||||
export interface WorkflowDiagnostic {
|
||||
severity: "warning" | "error";
|
||||
code: string;
|
||||
path: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface WorkflowAnalysis {
|
||||
workflow: { id: string; label: string; state: number; version: string };
|
||||
ast: WorkflowAstNode[];
|
||||
dependencies: WorkflowDependency[];
|
||||
diagnostics: WorkflowDiagnostic[];
|
||||
}
|
||||
|
||||
export interface WorkflowFormSpecComponentLike {
|
||||
name?: string;
|
||||
field?: string;
|
||||
label?: string;
|
||||
type?: string;
|
||||
isLinkageAssignment?: boolean;
|
||||
assignmentRule?: string | null;
|
||||
priorityList?: Array<{ type: string; label?: string; priority?: number; value?: number }>;
|
||||
priority?: Array<{ type: string; label?: string; priority?: number; value?: number }> | null;
|
||||
}
|
||||
|
||||
export interface WorkflowFormSpecLike {
|
||||
id: string;
|
||||
name?: string;
|
||||
components?: WorkflowFormSpecComponentLike[];
|
||||
}
|
||||
|
||||
export interface AnalyzeWorkflowOptions {
|
||||
specifications?: Record<string, WorkflowFormSpecLike | undefined>;
|
||||
}
|
||||
|
||||
const KNOWN_TYPES = new Set([
|
||||
"webhook",
|
||||
"crontab",
|
||||
"clock",
|
||||
"condition",
|
||||
"every",
|
||||
"stop",
|
||||
"http",
|
||||
"flow-detail",
|
||||
"code",
|
||||
"code-js2",
|
||||
"ekuaibao-datalink-filter",
|
||||
"ekuaibao-datalink-create",
|
||||
"ekuaibao-datalink-edit",
|
||||
"ekuaibao-datalink-delete",
|
||||
"data-convert",
|
||||
"flow-create-task",
|
||||
]);
|
||||
|
||||
const KNOWN_TYPES = new Set(["webhook", "condition", "every", "stop", "http", "flow-detail", "code", "code-js2", "ekuaibao-datalink-filter", "ekuaibao-datalink-create", "data-convert", "flow-create-task"]);
|
||||
function referencesFromTask(task: WorkflowTask): string[] {
|
||||
const code = typeof task.code === "string" ? task.code : "";
|
||||
const values = [...code.matchAll(/\{\{\s*([^{}]+?)\s*\}\}|\b(?:ctx|input|output|context)\.([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)/g)].map((match) => (match[1] || match[2] || "").trim()).filter(Boolean);
|
||||
const values = [
|
||||
...code.matchAll(
|
||||
/\{\{\s*([^{}]+?)\s*\}\}|\b(?:ctx|input|output|context)\.([A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*)/g
|
||||
),
|
||||
]
|
||||
.map((match) => (match[1] || match[2] || "").trim())
|
||||
.filter(Boolean);
|
||||
return [...new Set(values)];
|
||||
}
|
||||
function toAst(tasks: WorkflowTask[], parentPath = ""): WorkflowAstNode[] { return tasks.map((task, index) => { const path = parentPath ? `${parentPath}.${index}` : String(index); return { type: task.type, name: task.name, label: task.label || task.displayName || "", path, orderIndex: task.orderIndex, levelIndex: task.levelIndex, children: toAst(task.tasks || [], path) }; }); }
|
||||
export function analyzeWorkflow(detail: WorkflowDetail): WorkflowAnalysis {
|
||||
const ast = toAst(detail.tasks); const dependencies: WorkflowDependency[] = []; const diagnostics: WorkflowDiagnostic[] = [];
|
||||
const visit = (tasks: WorkflowTask[], parentPath = "") => tasks.forEach((task, index) => { const path = parentPath ? `${parentPath}.${index}` : String(index); const refs = referencesFromTask(task); if (refs.length) dependencies.push({ path, taskType: task.type, references: refs }); if ((task.type === "code" || task.type === "code-js2") && !String(task.code || "").trim()) diagnostics.push({ severity: "error", code: "EMPTY_CODE", path, message: "代码节点没有可执行脚本" }); if ((task.type === "condition" || task.type === "every") && !(task.tasks || []).length) diagnostics.push({ severity: "warning", code: "EMPTY_BRANCH", path, message: `${task.type} 控制节点没有子节点` }); if (!KNOWN_TYPES.has(task.type)) diagnostics.push({ severity: "warning", code: "UNKNOWN_TASK_TYPE", path, message: `未收录的节点类型: ${task.type}` }); visit(task.tasks || [], path); });
|
||||
visit(detail.tasks); return { workflow: { id: detail.id, label: detail.label, state: detail.state, version: detail.version }, ast, dependencies, diagnostics };
|
||||
|
||||
function toAst(tasks: WorkflowTask[], parentPath = ""): WorkflowAstNode[] {
|
||||
return tasks.map((task, index) => {
|
||||
const path = parentPath ? `${parentPath}.${index}` : String(index);
|
||||
return {
|
||||
type: task.type,
|
||||
name: task.name,
|
||||
label: task.label || task.displayName || "",
|
||||
path,
|
||||
orderIndex: task.orderIndex,
|
||||
levelIndex: task.levelIndex,
|
||||
children: toAst(task.tasks || [], path),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function getTaskSpecificationId(task: WorkflowTask): string | undefined {
|
||||
const raw = task as Record<string, unknown>;
|
||||
if (typeof raw.specificationId === "string" && raw.specificationId.trim()) {
|
||||
return raw.specificationId.trim();
|
||||
}
|
||||
if (Array.isArray(task.inputs)) {
|
||||
const found = task.inputs.find((item) => item.key === "specificationId");
|
||||
if (found && typeof found.value === "string" && found.value.trim()) {
|
||||
return found.value.trim();
|
||||
}
|
||||
} else if (raw.inputs && typeof raw.inputs === "object") {
|
||||
const specId = (raw.inputs as Record<string, unknown>).specificationId;
|
||||
if (typeof specId === "string" && specId.trim()) {
|
||||
return specId.trim();
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function getTaskFormEntries(
|
||||
task: WorkflowTask
|
||||
): Array<{ key?: string; label?: string; type?: string; value?: unknown }> {
|
||||
const raw = task as Record<string, unknown>;
|
||||
if (Array.isArray(raw.form)) {
|
||||
return raw.form.filter(
|
||||
(item): item is { key?: string; label?: string; type?: string; value?: unknown } =>
|
||||
Boolean(item && typeof item === "object")
|
||||
);
|
||||
}
|
||||
if (raw.form && typeof raw.form === "object") {
|
||||
return Object.entries(raw.form as Record<string, unknown>).map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
}));
|
||||
}
|
||||
if (Array.isArray(task.inputs)) {
|
||||
const formInput = task.inputs.find((item) => item.key === "form");
|
||||
if (formInput && Array.isArray(formInput.value)) {
|
||||
return formInput.value.filter(
|
||||
(item: unknown): item is { key?: string; label?: string; type?: string; value?: unknown } =>
|
||||
Boolean(item && typeof item === "object")
|
||||
);
|
||||
}
|
||||
if (formInput && formInput.value && typeof formInput.value === "object") {
|
||||
return Object.entries(formInput.value as Record<string, unknown>).map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
}));
|
||||
}
|
||||
} else if (raw.inputs && typeof raw.inputs === "object") {
|
||||
const formVal = (raw.inputs as Record<string, unknown>).form;
|
||||
if (Array.isArray(formVal)) {
|
||||
return formVal.filter(
|
||||
(item): item is { key?: string; label?: string; type?: string; value?: unknown } =>
|
||||
Boolean(item && typeof item === "object")
|
||||
);
|
||||
}
|
||||
if (formVal && typeof formVal === "object") {
|
||||
return Object.entries(formVal as Record<string, unknown>).map(([key, value]) => ({
|
||||
key,
|
||||
value,
|
||||
}));
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export function extractWorkflowSpecificationIds(detail: WorkflowDetail): string[] {
|
||||
const ids = new Set<string>();
|
||||
const walk = (tasks: WorkflowTask[]) => {
|
||||
for (const task of tasks) {
|
||||
if (task.type === "flow-create-task") {
|
||||
const specId = getTaskSpecificationId(task);
|
||||
if (specId) ids.add(specId);
|
||||
}
|
||||
if (Array.isArray(task.tasks) && task.tasks.length > 0) {
|
||||
walk(task.tasks);
|
||||
}
|
||||
}
|
||||
};
|
||||
walk(detail.tasks || []);
|
||||
return [...ids];
|
||||
}
|
||||
|
||||
function taskGuardsStatusOf(task: WorkflowTask, targetTaskName: string): boolean {
|
||||
if (task.type !== "condition") return false;
|
||||
const raw = task as Record<string, unknown>;
|
||||
const filterSource = raw.combineFilters ?? raw.filters ?? task.inputs ?? raw.conditions ?? {};
|
||||
const serialized = JSON.stringify(filterSource);
|
||||
if (
|
||||
serialized.includes(`${targetTaskName}.$status`) ||
|
||||
serialized.includes(`${targetTaskName}.status`) ||
|
||||
serialized.includes(`${targetTaskName}.result`) ||
|
||||
serialized.includes(`${targetTaskName}.data`)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return (
|
||||
serialized.includes(targetTaskName) &&
|
||||
(serialized.includes("$status") || serialized.includes("是否运行成功"))
|
||||
);
|
||||
}
|
||||
|
||||
function findUnguardedDatalinkEdits(
|
||||
tasks: WorkflowTask[],
|
||||
basePath: string,
|
||||
createTaskName: string
|
||||
): Array<{ task: WorkflowTask; path: string }> {
|
||||
const found: Array<{ task: WorkflowTask; path: string }> = [];
|
||||
tasks.forEach((task, idx) => {
|
||||
const path = `${basePath}.${idx}`;
|
||||
if (task.type === "ekuaibao-datalink-edit") {
|
||||
found.push({ task, path });
|
||||
return;
|
||||
}
|
||||
if (taskGuardsStatusOf(task, createTaskName)) {
|
||||
return;
|
||||
}
|
||||
if (Array.isArray(task.tasks) && task.tasks.length > 0) {
|
||||
found.push(...findUnguardedDatalinkEdits(task.tasks, path, createTaskName));
|
||||
}
|
||||
});
|
||||
return found;
|
||||
}
|
||||
|
||||
export function analyzeWorkflow(
|
||||
detail: WorkflowDetail,
|
||||
options: AnalyzeWorkflowOptions = {}
|
||||
): WorkflowAnalysis {
|
||||
const ast = toAst(detail.tasks);
|
||||
const dependencies: WorkflowDependency[] = [];
|
||||
const diagnostics: WorkflowDiagnostic[] = [];
|
||||
|
||||
if (detail.state === 0) {
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "WORKFLOW_DISABLED",
|
||||
path: "workflow",
|
||||
message:
|
||||
"工作流当前处于未启用/草稿状态 (state=0),修改或排障后需 publish/toggle --state=1 方可生效",
|
||||
});
|
||||
}
|
||||
|
||||
const visit = (tasks: WorkflowTask[], parentPath = "", insideEvery = false) => {
|
||||
tasks.forEach((task, index) => {
|
||||
const path = parentPath ? `${parentPath}.${index}` : String(index);
|
||||
const refs = referencesFromTask(task);
|
||||
if (refs.length) {
|
||||
dependencies.push({ path, taskType: task.type, references: refs });
|
||||
}
|
||||
if ((task.type === "code" || task.type === "code-js2") && !String(task.code || "").trim()) {
|
||||
diagnostics.push({
|
||||
severity: "error",
|
||||
code: "EMPTY_CODE",
|
||||
path,
|
||||
message: "代码节点没有可执行脚本",
|
||||
});
|
||||
}
|
||||
if ((task.type === "condition" || task.type === "every") && !(task.tasks || []).length) {
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "EMPTY_BRANCH",
|
||||
path,
|
||||
message: `${task.type} 控制节点没有子节点`,
|
||||
});
|
||||
}
|
||||
if (!KNOWN_TYPES.has(task.type)) {
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "UNKNOWN_TASK_TYPE",
|
||||
path,
|
||||
message: `未收录的节点类型: ${task.type}`,
|
||||
});
|
||||
}
|
||||
|
||||
// 诊断 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
|
||||
| { defaultAction?: string }
|
||||
| undefined;
|
||||
if (onError?.defaultAction === "SKIP") {
|
||||
const subsequentSiblings = tasks.slice(index + 1);
|
||||
const unguardedEdits: Array<{ task: WorkflowTask; path: string }> = [];
|
||||
subsequentSiblings.forEach((sibling, relIdx) => {
|
||||
const siblingIndex = index + 1 + relIdx;
|
||||
const siblingPath = parentPath ? `${parentPath}.${siblingIndex}` : String(siblingIndex);
|
||||
if (sibling.type === "ekuaibao-datalink-edit") {
|
||||
unguardedEdits.push({ task: sibling, path: siblingPath });
|
||||
} else if (!taskGuardsStatusOf(sibling, task.name) && sibling.tasks?.length) {
|
||||
unguardedEdits.push(
|
||||
...findUnguardedDatalinkEdits(sibling.tasks, siblingPath, task.name)
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
for (const edit of unguardedEdits) {
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "UNSAFE_SKIP_WITHOUT_STATUS_GUARD",
|
||||
path: edit.path,
|
||||
message: `节点 [${task.label || task.name}] (${task.name}) 配置了报错跳过(SKIP),但后续台账更新节点 [${edit.task.label || edit.task.name}] (${edit.task.name}) 未校验其执行状态(如 ${task.name}.$status),前序建单失败时仍会误改台账状态!`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 诊断 3: flow-create-task 表单字段联动覆盖告警 (LINKAGE_ASSIGNMENT > MANUALLY_FILL_IN)
|
||||
if (task.type === "flow-create-task") {
|
||||
const specId = getTaskSpecificationId(task);
|
||||
const spec = specId ? options.specifications?.[specId] : undefined;
|
||||
const formEntries = getTaskFormEntries(task).filter(
|
||||
(entry) =>
|
||||
entry.value !== undefined &&
|
||||
entry.value !== null &&
|
||||
String(entry.value).trim() !== ""
|
||||
);
|
||||
|
||||
const specComponents =
|
||||
spec?.components ??
|
||||
(Array.isArray((spec as unknown as Record<string, unknown> | undefined)?.form)
|
||||
? ((spec as unknown as Record<string, unknown>).form as WorkflowFormSpecComponentLike[])
|
||||
: []);
|
||||
|
||||
if (spec && specComponents.length && formEntries.length > 0) {
|
||||
const matchedComponents = specComponents.filter((comp) => {
|
||||
const compKey = comp.name || comp.field || "";
|
||||
return formEntries.some(
|
||||
(entry) =>
|
||||
(Boolean(compKey) && entry.key === compKey) ||
|
||||
(Boolean(entry.label) && Boolean(comp.label) && entry.label === comp.label)
|
||||
);
|
||||
});
|
||||
|
||||
const linkageSources = matchedComponents.filter(
|
||||
(comp) =>
|
||||
Boolean(comp.assignmentRule) ||
|
||||
(comp.type === "dataLink" && comp.isLinkageAssignment === true)
|
||||
);
|
||||
|
||||
for (const src of linkageSources) {
|
||||
const srcKey = src.name || src.field || src.label || "";
|
||||
const overrideTargets = matchedComponents
|
||||
.filter((comp) => (comp.name || comp.field || comp.label || "") !== srcKey)
|
||||
.map((comp) => {
|
||||
const list = comp.priorityList || comp.priority || [];
|
||||
const linkage = list.find((p) => p.type === "LINKAGE_ASSIGNMENT");
|
||||
const manual = list.find((p) => p.type === "MANUALLY_FILL_IN");
|
||||
const linkagePriority = linkage?.priority ?? linkage?.value;
|
||||
const manualPriority = manual?.priority ?? manual?.value;
|
||||
if (
|
||||
linkagePriority !== undefined &&
|
||||
manualPriority !== undefined &&
|
||||
linkagePriority > manualPriority
|
||||
) {
|
||||
return {
|
||||
comp,
|
||||
compKey: comp.name || comp.field || comp.label || "",
|
||||
linkagePriority,
|
||||
manualPriority,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
})
|
||||
.filter((item): item is NonNullable<typeof item> => Boolean(item));
|
||||
|
||||
if (overrideTargets.length > 0) {
|
||||
const affectedDesc = overrideTargets
|
||||
.map(
|
||||
(t) =>
|
||||
`${t.comp.label || t.compKey}(${t.compKey}: LINKAGE_ASSIGNMENT(${t.linkagePriority}) > MANUALLY_FILL_IN(${t.manualPriority}))`
|
||||
)
|
||||
.join("、");
|
||||
diagnostics.push({
|
||||
severity: "warning",
|
||||
code: "LINKAGE_PRIORITY_OVERRIDE",
|
||||
path,
|
||||
message: `表单模板 [${spec.name || spec.id}] 中字段 [${src.label || srcKey}] (${srcKey}) 存在业务对象联动配置 (isLinkageAssignment=${Boolean(src.isLinkageAssignment)}, assignmentRule=${src.assignmentRule || "-"}),且当前节点同时传入了 [${affectedDesc}],联动赋值优先级高于手动/API 传入,显式传入的值可能被关联对象中的字段值覆盖!`,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
visit(task.tasks || [], path, insideEvery || task.type === "every");
|
||||
});
|
||||
};
|
||||
|
||||
visit(detail.tasks);
|
||||
return {
|
||||
workflow: {
|
||||
id: detail.id,
|
||||
label: detail.label,
|
||||
state: detail.state,
|
||||
version: detail.version,
|
||||
},
|
||||
ast,
|
||||
dependencies,
|
||||
diagnostics,
|
||||
};
|
||||
}
|
||||
|
||||
+113
-5
@@ -1,5 +1,6 @@
|
||||
import { z } from "zod";
|
||||
import { KyInstance } from "ky";
|
||||
import { AuthenticationError, EkbApiError } from "../../core/errors.js";
|
||||
import {
|
||||
PlatformSchema,
|
||||
WorkflowPageSchema,
|
||||
@@ -9,6 +10,10 @@ import {
|
||||
WorkflowSnapshotPageSchema,
|
||||
WorkflowLogPageSchema,
|
||||
WorkflowJobSchema,
|
||||
WorkflowJobDetailSchema,
|
||||
WorkflowTaskExecutionSchema,
|
||||
WorkflowExecutionPageSchema,
|
||||
WorkflowExecutionLogSchema,
|
||||
WorkflowDslSchema,
|
||||
StaffSchema,
|
||||
WebhookInfoSchema,
|
||||
@@ -16,10 +21,35 @@ import {
|
||||
} from "./types.js";
|
||||
import type { WorkflowState } from "./types.js";
|
||||
|
||||
// Helper to unwrap { data: T } response
|
||||
async function unwrap<T>(response: Response, schema: z.ZodType<T>): Promise<T> {
|
||||
const json = (await response.json()) as { data: unknown };
|
||||
return schema.parse(json.data);
|
||||
// Helper to unwrap { data: T } / { value: T } response with null/error defense
|
||||
export async function unwrap<T>(response: Response, schema: z.ZodType<T>): Promise<T> {
|
||||
const raw = await response.json();
|
||||
const record =
|
||||
raw !== null && typeof raw === "object" && !Array.isArray(raw)
|
||||
? (raw as Record<string, unknown>)
|
||||
: undefined;
|
||||
|
||||
const code = record?.code;
|
||||
const hasCodeError = code !== undefined && code !== null && Number(code) !== 200;
|
||||
const hasWrapper = Boolean(record && ("data" in record || "value" in record));
|
||||
const payload = hasWrapper ? (record!.data ?? record!.value) : raw;
|
||||
|
||||
if (hasCodeError || payload === null || payload === undefined) {
|
||||
const status = typeof code === "number" ? code : response.status || 500;
|
||||
const urlInfo = response.url ? ` [${response.url}]` : "";
|
||||
const reason =
|
||||
(typeof record?.msg === "string" && record.msg.trim()) ||
|
||||
(typeof record?.errorMessage === "string" && record.errorMessage.trim()) ||
|
||||
(typeof record?.message === "string" && record.message.trim()) ||
|
||||
"服务端返回空数据 (可能凭证已过期或无该自建应用权限)";
|
||||
const fullMsg = `EASO/Piper API 请求失败 (HTTP ${response.status || status}${urlInfo}): ${reason}`;
|
||||
if (status === 401 || status === 403 || Number(code) === 401 || Number(code) === 403) {
|
||||
throw new AuthenticationError(fullMsg);
|
||||
}
|
||||
throw new EkbApiError(fullMsg, "EASO_API_ERROR", status);
|
||||
}
|
||||
|
||||
return schema.parse(payload);
|
||||
}
|
||||
|
||||
// Helper for simple success responses
|
||||
@@ -146,7 +176,7 @@ export async function toggleWorkflow(
|
||||
return ok(response);
|
||||
}
|
||||
|
||||
// ── 运行中的任务(Piper)──────────────────────────────────────────────────────
|
||||
// ── 运行中的任务与单次 Job 执行详情(Piper)────────────────────────────────────
|
||||
|
||||
export async function listRunningJobs(
|
||||
client: KyInstance,
|
||||
@@ -159,6 +189,83 @@ export async function listRunningJobs(
|
||||
return unwrap(response, z.array(WorkflowJobSchema));
|
||||
}
|
||||
|
||||
export async function getJob(
|
||||
client: KyInstance,
|
||||
jobId: string
|
||||
): Promise<import("./types.js").WorkflowJobDetail> {
|
||||
const response = await client.get(`api/easo/jobs/${jobId}`);
|
||||
return unwrap(response, WorkflowJobDetailSchema);
|
||||
}
|
||||
|
||||
export async function getJobExecutionTree(
|
||||
client: KyInstance,
|
||||
jobId: string,
|
||||
options: { page?: number; pageSize?: number } = {}
|
||||
): Promise<import("./types.js").WorkflowTaskExecution[]> {
|
||||
const response = await client.get(`api/easo/jobs/${jobId}/execution`, {
|
||||
searchParams: {
|
||||
number: String(options.page ?? 1),
|
||||
pageSize: String(options.pageSize ?? 100),
|
||||
},
|
||||
});
|
||||
const parsed = await unwrap(
|
||||
response,
|
||||
z.union([z.array(WorkflowTaskExecutionSchema), WorkflowExecutionPageSchema])
|
||||
);
|
||||
return Array.isArray(parsed) ? parsed : parsed.items;
|
||||
}
|
||||
|
||||
export async function getJobFailedExecutions(
|
||||
client: KyInstance,
|
||||
jobId: string
|
||||
): Promise<import("./types.js").WorkflowExecutionPage> {
|
||||
const response = await client.get(`api/easo/jobs/${jobId}/execution/level/failed`);
|
||||
const parsed = await unwrap(
|
||||
response,
|
||||
z.union([WorkflowExecutionPageSchema, z.array(WorkflowTaskExecutionSchema)])
|
||||
);
|
||||
if (Array.isArray(parsed)) {
|
||||
return {
|
||||
number: 1,
|
||||
size: parsed.length,
|
||||
totalPages: 1,
|
||||
totalItems: parsed.length,
|
||||
items: parsed,
|
||||
};
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
export async function getJobExecutionLevel(
|
||||
client: KyInstance,
|
||||
jobId: string,
|
||||
options: { parentId: string; page?: number; pageSize?: number }
|
||||
): Promise<import("./types.js").WorkflowExecutionPage> {
|
||||
const response = await client.get(`api/easo/jobs/${jobId}/execution/level`, {
|
||||
searchParams: {
|
||||
parentId: options.parentId,
|
||||
number: String(options.page ?? 1),
|
||||
pageSize: String(options.pageSize ?? 20),
|
||||
},
|
||||
});
|
||||
return unwrap(response, WorkflowExecutionPageSchema);
|
||||
}
|
||||
|
||||
export async function getExecutionLogs(
|
||||
client: KyInstance,
|
||||
executionId: string
|
||||
): Promise<import("./types.js").WorkflowExecutionLog[]> {
|
||||
const response = await client.get(`api/easo/executions/${executionId}/logs`);
|
||||
const parsed = await unwrap(
|
||||
response,
|
||||
z.union([
|
||||
z.array(WorkflowExecutionLogSchema),
|
||||
z.object({ items: z.array(WorkflowExecutionLogSchema).default([]) }).passthrough(),
|
||||
])
|
||||
);
|
||||
return Array.isArray(parsed) ? parsed : parsed.items;
|
||||
}
|
||||
|
||||
// ── DSL 配置(Piper)──────────────────────────────────────────────────────────
|
||||
|
||||
export async function listDsl(
|
||||
@@ -199,3 +306,4 @@ export async function sampleWorkflowData(
|
||||
const response = await client.post(`api/easo/pipelines/${pipelineId}/sampleData`);
|
||||
return WorkflowSampleDataSchema.parse(await response.json());
|
||||
}
|
||||
|
||||
@@ -338,17 +338,87 @@ export const WorkflowChargeSchema = z.object({
|
||||
remaining: z.number().default(0),
|
||||
});
|
||||
|
||||
// ── 运行中的任务 ──────────────────────────────────────────────────────────────
|
||||
// ── 运行中的任务与单次 Job 执行详情 ──────────────────────────────────────────
|
||||
|
||||
export const WorkflowJobSchema = z.object({
|
||||
id: z.string(),
|
||||
pipelineId: z.string(),
|
||||
status: z.string().default(""),
|
||||
startTime: z.string().optional(),
|
||||
endTime: z.string().optional(),
|
||||
startTime: z.union([z.string(), z.number()]).optional(),
|
||||
endTime: z.union([z.string(), z.number()]).optional(),
|
||||
triggerType: z.string().default(""),
|
||||
});
|
||||
|
||||
export const WorkflowJobDetailSchema = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
pipelineId: z.string().default(""),
|
||||
label: z.string().default(""),
|
||||
status: z.string().default(""),
|
||||
runType: z.string().default(""),
|
||||
startTime: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
endTime: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
createTime: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
inputs: z.any().optional(),
|
||||
outputs: z.any().optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const WorkflowExecutionErrorSchema = z
|
||||
.object({
|
||||
message: z.string().default(""),
|
||||
stackTrace: z.array(z.string()).nullish().transform((v) => v ?? []),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const WorkflowExecutionLogSchema = z
|
||||
.object({
|
||||
id: z.union([z.string(), z.number()]).optional(),
|
||||
level: z.string().default("INFO"),
|
||||
message: z.string().default(""),
|
||||
createAt: z.union([z.string(), z.number()]).optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const WorkflowTaskExecutionSchema = z
|
||||
.object({
|
||||
id: z.string(),
|
||||
parentId: z.string().nullable().optional(),
|
||||
jobId: z.string().optional(),
|
||||
pipelineId: z.string().optional(),
|
||||
name: z.string().optional(),
|
||||
displayName: z.string().nullable().optional(),
|
||||
label: z.string().nullable().optional(),
|
||||
type: z.string().default(""),
|
||||
orderIndex: z.number().optional(),
|
||||
levelIndex: z.array(z.number()).optional(),
|
||||
status: z.string().default(""),
|
||||
executionTime: z.number().optional(),
|
||||
startTime: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
endTime: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
createTime: z.union([z.number(), z.string()]).nullable().optional(),
|
||||
currentLoopPath: z.string().nullable().optional(),
|
||||
error: WorkflowExecutionErrorSchema.nullable().optional(),
|
||||
output: z.any().optional(),
|
||||
form: z.record(z.string(), z.any()).nullable().optional(),
|
||||
details: z.record(z.string(), z.any()).nullable().optional(),
|
||||
executionLogs: z.array(z.any()).optional(),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
export const WorkflowExecutionPageSchema = z
|
||||
.object({
|
||||
number: z.number().default(1),
|
||||
size: z.number().default(20),
|
||||
totalPages: z.number().default(0),
|
||||
totalItems: z.number().default(0),
|
||||
items: z
|
||||
.array(z.union([WorkflowTaskExecutionSchema, z.array(WorkflowTaskExecutionSchema)]))
|
||||
.default([])
|
||||
.transform((arr) => arr.flat()),
|
||||
})
|
||||
.passthrough();
|
||||
|
||||
// ── DSL 配置 ─────────────────────────────────────────────────────────────────
|
||||
|
||||
export const WorkflowDslSchema = z.object({
|
||||
@@ -423,6 +493,11 @@ export type WorkflowLogItem = z.infer<typeof WorkflowLogItemSchema>;
|
||||
export type WorkflowLogPage = z.infer<typeof WorkflowLogPageSchema>;
|
||||
export type WorkflowCharge = z.infer<typeof WorkflowChargeSchema>;
|
||||
export type WorkflowJob = z.infer<typeof WorkflowJobSchema>;
|
||||
export type WorkflowJobDetail = z.infer<typeof WorkflowJobDetailSchema>;
|
||||
export type WorkflowExecutionError = z.infer<typeof WorkflowExecutionErrorSchema>;
|
||||
export type WorkflowExecutionLog = z.infer<typeof WorkflowExecutionLogSchema>;
|
||||
export type WorkflowTaskExecution = z.infer<typeof WorkflowTaskExecutionSchema>;
|
||||
export type WorkflowExecutionPage = z.infer<typeof WorkflowExecutionPageSchema>;
|
||||
export type WorkflowDsl = z.infer<typeof WorkflowDslSchema>;
|
||||
export type Staff = z.infer<typeof StaffSchema>;
|
||||
export type WebhookInfo = z.infer<typeof WebhookInfoSchema>;
|
||||
@@ -431,3 +506,4 @@ export type WorkflowSummary = z.infer<typeof WorkflowSummarySchema>;
|
||||
export type WorkflowListAllError = z.infer<typeof WorkflowListAllErrorSchema>;
|
||||
export type TaskMatch = z.infer<typeof TaskMatchSchema>;
|
||||
export type WorkflowWithMatches = z.infer<typeof WorkflowWithMatchesSchema>;
|
||||
|
||||
@@ -10,7 +10,19 @@ import {
|
||||
} from "./workflow-state.js";
|
||||
import { WorkflowDetailSchema } from "./types.js";
|
||||
import type { WorkflowDetail } from "./types.js";
|
||||
import { listWorkflowSnapshots, listWorkflowLogs, toggleWorkflow, updateWorkflow } from "./api.js";
|
||||
import {
|
||||
getExecutionLogs,
|
||||
getJob,
|
||||
getJobExecutionLevel,
|
||||
getJobExecutionTree,
|
||||
getJobFailedExecutions,
|
||||
getWorkflowDetail,
|
||||
listWorkflowSnapshots,
|
||||
listWorkflowLogs,
|
||||
toggleWorkflow,
|
||||
updateWorkflow,
|
||||
} from "./api.js";
|
||||
import { AuthenticationError, EkbApiError } from "../../core/errors.js";
|
||||
import { WorkflowAlertStore } from "./workflow-alert-store.js";
|
||||
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
@@ -150,4 +162,144 @@ describe("workflow draft state machine", () => {
|
||||
expect(failed.status).toBe("failed");
|
||||
expect(failed.error).toBe("网络错误");
|
||||
});
|
||||
|
||||
it("throws structured AuthenticationError or EkbApiError when Piper unwrap receives null data or non-200 code", async () => {
|
||||
const unauthorizedClient = {
|
||||
get: async () =>
|
||||
new Response(JSON.stringify({ code: 401, message: "登录已过期", data: null }), {
|
||||
status: 200,
|
||||
}),
|
||||
} as any;
|
||||
await expect(getWorkflowDetail(unauthorizedClient, "wf-1")).rejects.toBeInstanceOf(AuthenticationError);
|
||||
|
||||
const nullDataClient = {
|
||||
get: async () =>
|
||||
new Response(JSON.stringify({ code: 200, msg: "pipeline not found", data: null }), {
|
||||
status: 200,
|
||||
}),
|
||||
} as any;
|
||||
await expect(getWorkflowDetail(nullDataClient, "wf-1")).rejects.toBeInstanceOf(EkbApiError);
|
||||
});
|
||||
|
||||
it("calls the 5 Piper Job diagnostic endpoints and parses execution trees, failed nodes, child levels, and logs", async () => {
|
||||
const client = {
|
||||
get: async (url: string, options?: any) => {
|
||||
if (url === "api/easo/jobs/892809886382563347") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: {
|
||||
id: "892809886382563347",
|
||||
pipelineId: "886351399301758976",
|
||||
label: "每30分钟创建采购申请单",
|
||||
state: "COMPLETED",
|
||||
successTaskCount: 5,
|
||||
errorTaskCount: 1,
|
||||
hasError: true,
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
if (url === "api/easo/jobs/892809886382563347/execution") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: [
|
||||
{
|
||||
id: "892809893789696012",
|
||||
jobId: "892809886382563347",
|
||||
name: "every_0",
|
||||
label: "循环",
|
||||
type: "every",
|
||||
state: "COMPLETED",
|
||||
levelIndex: [0],
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
}
|
||||
if (url === "api/easo/jobs/892809886382563347/execution/level/failed") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: [
|
||||
{
|
||||
id: "892809900000000001",
|
||||
jobId: "892809886382563347",
|
||||
parentId: "892809893789696012",
|
||||
name: "ekuaibao_flow_create_task_0",
|
||||
label: "创建预付申请单",
|
||||
type: "flow-create-task",
|
||||
state: "FAILED",
|
||||
inputs: { form: { u_关联合同流程: "ID01VSau4VJWSH" } },
|
||||
outputs: { error: "我方签约主体未填写" },
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
}
|
||||
if (url === "api/easo/jobs/892809886382563347/execution/level") {
|
||||
expect(options?.searchParams).toEqual({
|
||||
parentId: "892809893789696012",
|
||||
number: "1",
|
||||
pageSize: "20",
|
||||
});
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: {
|
||||
number: 1,
|
||||
size: 20,
|
||||
totalPages: 1,
|
||||
totalItems: 1,
|
||||
items: [
|
||||
[
|
||||
{
|
||||
id: "892809900000000001",
|
||||
name: "ekuaibao_flow_create_task_0",
|
||||
state: "FAILED",
|
||||
inputs: { form: { u_关联合同流程: "ID01VSau4VJWSH" } },
|
||||
outputs: { error: "我方签约主体未填写" },
|
||||
},
|
||||
],
|
||||
],
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
if (url === "api/easo/executions/892809893789696012/logs") {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
code: 200,
|
||||
data: {
|
||||
total: 1,
|
||||
items: [{ id: "log-1", message: "MVEL script executed", level: "INFO" }],
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
throw new Error(`Unexpected URL: ${url}`);
|
||||
},
|
||||
} as any;
|
||||
|
||||
const job = await getJob(client, "892809886382563347");
|
||||
expect(job.hasError).toBe(true);
|
||||
expect(job.errorTaskCount).toBe(1);
|
||||
|
||||
const tree = await getJobExecutionTree(client, "892809886382563347");
|
||||
expect(tree).toHaveLength(1);
|
||||
expect(tree[0]?.name).toBe("every_0");
|
||||
|
||||
const failed = await getJobFailedExecutions(client, "892809886382563347");
|
||||
expect(failed.items).toHaveLength(1);
|
||||
expect((failed.items[0]?.outputs as any)?.error).toBe("我方签约主体未填写");
|
||||
|
||||
const level = await getJobExecutionLevel(client, "892809886382563347", {
|
||||
parentId: "892809893789696012",
|
||||
});
|
||||
expect(level.items).toHaveLength(1);
|
||||
|
||||
const logs = await getExecutionLogs(client, "892809893789696012");
|
||||
expect(logs[0]?.message).toBe("MVEL script executed");
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user