feat: optimize datalink metadata display, fix field mapping schema, bill timeout and cli options

This commit is contained in:
gitea committed 2026-10-22 18:43:54 +08:00
1 parent fbdb38bfb2
commit a5f685045e
13 files changed
+254 -40

No files matched your search

+47 -20
View File
@@ -830,23 +830,39 @@ export async function getBillByCodeOrId(
}
}
// 2. 从 search 中匹配单号、flowCode、ID 或关联 LinkId
const searchRes = await searchRawBills(client, corpId, { start: 0, count: 50 });
const matched = searchRes.items.filter((item) => {
if (item.id === cleanQuery) return true;
if (item.code === cleanQuery) return true;
for (const [k, v] of Object.entries(item.form || {})) {
if (typeof v === "string" && v.trim() === cleanQuery) {
if (k.endsWith("_code") || k.endsWith("_flowCode") || k.endsWith("_linkId") || k.endsWith("_detailId")) {
return true;
// 1.1 如果是典型单据编号特征(如 B26010730、R2023...),优先走审批流通道检索,避免 invoice/search 接口慢超时
if (/^[A-Za-z][A-Za-z0-9_-]+$/.test(cleanQuery)) {
try {
const rawFlow = await getRawBillFlow(client, corpId, cleanQuery);
if (rawFlow) {
return [formatFlowAsBill(rawFlow, dictionary)];
}
} catch {
// 容错并继续回退到传统单据检索
}
}
// 2. 从 search 中匹配单号、flowCode、ID 或关联 LinkId(带 5s 超时与容错降级)
try {
const searchRes = await searchRawBills(client, corpId, { start: 0, count: 50, timeout: 5000 });
const matched = searchRes.items.filter((item) => {
if (item.id === cleanQuery) return true;
if (item.code === cleanQuery) return true;
for (const [k, v] of Object.entries(item.form || {})) {
if (typeof v === "string" && v.trim() === cleanQuery) {
if (k.endsWith("_code") || k.endsWith("_flowCode") || k.endsWith("_linkId") || k.endsWith("_detailId")) {
return true;
}
}
}
}
return false;
});
return false;
});
if (matched.length > 0) {
return matched.map((it) => formatSingleBill(it, dictionary));
if (matched.length > 0) {
return matched.map((it) => formatSingleBill(it, dictionary));
}
} catch {
// 忽略 invoice/search 超时或错误,平滑回退
}
// 3. 回退到审批流程/待办接口检索(支持申请单 Requisition、借款单、自由流待办)
@@ -1049,7 +1065,8 @@ function buildDiagnosticReport(
export async function traceBillFlowDetail(
client: KyInstance,
corpId: string,
targetQuery: string
targetQuery: string,
options?: { skipInvoices?: boolean }
): Promise<BillFlowTraceDiagnostic> {
const cleanTarget = targetQuery.trim();
if (!cleanTarget) {
@@ -1616,7 +1633,8 @@ export async function searchAndFormatBills(
export async function getTranslatorContext(
client: KyInstance,
corpId: string,
rawFlow?: Record<string, unknown>
rawFlow?: Record<string, unknown>,
options?: { skipInvoices?: boolean }
): Promise<TranslatorOptions> {
const [feeTypeTree, catalog, dimEntity, dimBiz, dimBool] = await Promise.allSettled([
getFeeTypeTree(client, corpId),
@@ -1667,10 +1685,19 @@ export async function getTranslatorContext(
}
}
const invoiceFetches = Array.from(invoiceIds).map(async (id) => {
const detail = await getInvoiceValidationDetail(client, corpId, id);
if (detail) invoiceDetailMap.set(id, detail);
});
const invoiceFetches = options?.skipInvoices
? []
: Array.from(invoiceIds).map(async (id) => {
try {
const detail = await Promise.race([
getInvoiceValidationDetail(client, corpId, id),
new Promise<null>((_, reject) => setTimeout(() => reject(new Error("Invoice timeout")), 3000)),
]);
if (detail) invoiceDetailMap.set(id, detail);
} catch {
// 单张发票详情超时或获取失败不阻断整体流程解析
}
});
// 2. 扫描数据连接/卡片 ID (例如供应商 ID01...,payeeId 等)
const cardCandidateIds = new Set<string>();
+6 -1
View File
@@ -3,6 +3,7 @@ import type { KyInstance } from "ky";
import {
DatalinkEntitySchema,
DatalinkPlatformDetailSchema,
enrichDatalinkField,
type DatalinkEntity,
type DatalinkField,
type DatalinkImportJob,
@@ -26,7 +27,11 @@ function numberOr(value: unknown, fallback: number): number {
}
function parseEntity(value: unknown): DatalinkEntity {
return DatalinkEntitySchema.parse(asRecord(value));
const entity = DatalinkEntitySchema.parse(asRecord(value));
return {
...entity,
fields: entity.fields.map(enrichDatalinkField),
};
}
function sanitizePlatformDetail(value: unknown): Record<string, unknown> {
+28
View File
@@ -20,9 +20,37 @@ export const DatalinkFieldSchema = z
unit: z.string().nullable().optional(),
index: z.boolean().nullable().optional(),
systemField: z.boolean().nullable().optional(),
fieldKey: z.string().optional(),
displayName: z.string().optional(),
role: z.enum(["title", "code", "system", "custom"]).optional(),
description: z.string().optional(),
})
.passthrough();
export function enrichDatalinkField<T extends DatalinkField>(field: T): T {
const name = field.name;
const label = field.label;
let role: "title" | "code" | "system" | "custom" = "custom";
let description = `业务自定义字段 (界面显示为「${label}」),API与工作流配置时使用此物理键`;
if (name.endsWith("_name")) {
role = "title";
description = `实体主名称/标题 (界面显示为「${label}」),系统基础字段`;
} else if (name.endsWith("_code")) {
role = "code";
description = `业务单号/流水号 (界面显示为「${label}」),通常由自动编号规则生成`;
} else if (field.systemField) {
role = "system";
description = `系统预置字段 (界面显示为「${label}」)`;
}
return {
...field,
fieldKey: field.fieldKey ?? name,
displayName: field.displayName ?? label,
role: field.role ?? role,
description: field.description ?? description,
};
}
export const DatalinkEntitySchema = z
.object({
id: z.string(),
+62
View File
@@ -0,0 +1,62 @@
import { describe, expect, it } from "bun:test";
import { FieldMappingSchema, EkuaibaoDatalinkCreateTaskSchema } from "./types.js";
describe("FieldMappingSchema 字段映射验证与序列化", () => {
it("正确解析仅含 key 的映射项", () => {
const raw = { key: "E_field_1" };
const parsed = FieldMappingSchema.parse(raw);
expect(parsed.key).toBe("E_field_1");
expect(parsed.value).toBeUndefined();
});
it("正确保留 value 表达式,不被剥离丢失 (防止 Piper 报错金额/必填字段为空)", () => {
const raw = {
key: "E_e716b9f4b67179b1fbc0_费用金额",
value: "control_stssrn.item.amortizationAmount",
};
const parsed = FieldMappingSchema.parse(raw);
expect(parsed.key).toBe("E_e716b9f4b67179b1fbc0_费用金额");
expect(parsed.value).toBe("control_stssrn.item.amortizationAmount");
});
it("正确保留复杂对象/数组或数字类型的 value 与扩展属性", () => {
const raw = {
key: "E_nested_field",
value: { subKey: "action_1.output", defaultVal: 100 },
type: "relateEntity",
required: true,
};
const parsed = FieldMappingSchema.parse(raw);
expect(parsed.key).toBe("E_nested_field");
expect(parsed.value).toEqual({ subKey: "action_1.output", defaultVal: 100 });
expect((parsed as any).type).toBe("relateEntity");
expect((parsed as any).required).toBe(true);
});
it("在 EkuaibaoDatalinkCreateTaskSchema 节点中完整保留所有字段映射的 key 与 value", () => {
const node = {
name: "action_create_test",
label: "创建摊销台账",
type: "ekuaibao-datalink-create",
groupName: "DEFAULT",
orderIndex: 1,
levelIndex: [1],
status: "NORMAL",
mode: "NORMAL",
entityId: "e716b9f4b67179b1fbc0",
combineFilters: { condition: "AND", filters: [] },
filters: [],
fields: [
{ key: "E_e716b9f4b67179b1fbc0_name", value: "control_stssrn.item.title" },
{ key: "E_e716b9f4b67179b1fbc0_费用金额", value: "control_stssrn.item.amortizationAmount" },
{ key: "E_e716b9f4b67179b1fbc0_摊销月份", value: "control_stssrn.item.amortizationMonth" },
],
};
const parsed = EkuaibaoDatalinkCreateTaskSchema.parse(node);
expect(parsed.fields).toHaveLength(3);
expect(parsed.fields[0].value).toBe("control_stssrn.item.title");
expect(parsed.fields[1].value).toBe("control_stssrn.item.amortizationAmount");
expect(parsed.fields[2].value).toBe("control_stssrn.item.amortizationMonth");
});
});
+5 -5
View File
@@ -64,11 +64,11 @@ export const FilterGroupSchema: z.ZodType<any> = z.lazy(() =>
})
);
// 字段映射条目的两种形态:只读 key 或 key-value 映射
export const FieldMappingSchema = z.union([
z.object({ key: z.string() }),
z.object({ key: z.string(), value: z.string() }),
]);
// 字段映射条目的两种形态:只读 key 或 key-value 映射(保留 value 及其余配置项)
export const FieldMappingSchema = z.object({
key: z.string(),
value: z.any().optional(),
}).passthrough();
// 错误处理配置
export const OnErrorSchema = z.object({
@@ -164,6 +164,27 @@ describe("workflow-script - 本地静态语法校验与沙箱仿真引擎", () =
expect(res.durationMs).toBeGreaterThanOrEqual(0);
});
it("supports accessing variables through inputs namespace as well as top-level globals", async () => {
const code = `
return {
direct: foo,
viaNamespace: inputs.foo,
nested: inputs.nested.value
};
`;
const inputs = {
foo: "bar",
nested: { value: 42 }
};
const res = await executeJavaScriptSandbox(code, inputs);
expect(res.success).toBe(true);
expect(res.returnValue).toEqual({
direct: "bar",
viaNamespace: "bar",
nested: 42
});
});
it("catches runtime errors and reports line number", async () => {
const code = `
const a = 10;
@@ -51,6 +51,11 @@ export async function executeJavaScriptSandbox(
const value = vm.getProp(parsed.value, key);
try { vm.setProp(vm.global, key, value); } finally { value.dispose(); }
}
// 同时挂载 inputs 命名空间,支持脚本直接通过 inputs.xxx 访问输入对象
if (!Object.hasOwn(inputs, "inputs")) {
const dup = parsed.value.dup();
try { vm.setProp(vm.global, "inputs", dup); } finally { dup.dispose(); }
}
} finally { parsed.value.dispose(); }
const recordLog = (args: Parameters<typeof vm.dump>) => {