Merge pull request #139 from yunyingk/feat/cli-dx-and-metadata-fixes
CI / validate (push) Has been cancelled

feat: optimize datalink metadata display, fix field mapping schema, bill timeout and cli options
This commit is contained in:
yunyingk authored and GitHub committed 2026-10-22 18:45:27 +08:00
commit 1c2e97486b
13 files changed
+254 -40

No files matched your search

+4 -4
View File
@@ -272,7 +272,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
"dictionary": "enum",
"dict": "enum"
},
flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c code code-file container count d data desc description end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId keyword l label log logs max-jobs maxJobs n name node node-id nodeId nodes output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId set size snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") }
flags: { ...flagList("all allow-prod allow-production auto-publish autoPublish compare detail diff empty errors f fail fail-on-alert failOnAlert failed failed-only failedOnly follow force force-write forceWrite full has-error hasError in-place inPlace includeDetail json none once publish snapshot v value-json valueJson verbose with-tasks withTasks timeline progress steps", "boolean"), ...flagList("a admin-key adminKey after app app-id appId b bill body c code code-file container count d data desc description end-time endTime entity execution-logs field file filter flow flow-code flowCode from i id input input-file insert-after interval job job-id job1 job2 jobA jobB jobId keyword l label limit log logs max-jobs maxJobs n name node node-id nodeId nodes output output-file outputFile p page page-size pageSize parent parent-id parentId password path payload pipeline pipeline-id pipelineId platform platform-id platformId pwd q query record s sample sample-id sampleId set size snapshot1 snapshot2 snapshotA snapshotB source start-time startTime state state-file stateFile t target targetName targetPlatformId task taskType third-id thirdId timeout timeout-ms timeoutMs to trigger type types value workflowId", "value") }
},
"bill": {
"summary": "单据检索、表单规格诊断与审批动作",
@@ -339,7 +339,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
"url": "link",
"specification": "spec"
},
flags: { ...flagList("audit confirm distinct force-write keep-it-secret mine my private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") }
flags: { ...flagList("audit basic confirm distinct force-write keep-it-secret mine my no-invoice noInvoice private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") }
},
"flow": {
"summary": "审批流全域透视与穿透诊断",
@@ -368,7 +368,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
"show": "get",
"find": "get"
},
flags: { ...flagList("audit confirm distinct force-write keep-it-secret mine my private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") }
flags: { ...flagList("audit basic confirm distinct force-write keep-it-secret mine my no-invoice noInvoice private remind reminder risk secret self with-risk y yes", "boolean"), ...flagList("add-node-type addNodeType approver approver-id approverIds c code comment count d days dir direction end end-date endDate fields file file-id filter filter-by filterBy flowId from id k keyword limit message mode n opinion order output-dir participant participants q query reject-to rejectTo resubmit-method resubmitMethod s search-field search-fields searchFields select sf since sort spec specification specification-id specificationId staff staff-id stage start start-date startDate state target to", "value") }
},
"contact": {
"summary": "企业通讯录与人员检索",
@@ -819,7 +819,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
},
flags: {
...flagList("token t user name u hose-token jwt ticket ticket-id auth-code staff alias corp-name count limit n start offset state status corpid id keyword query q message msg reason matter hours hour duration days day to recipient target remarks comment corp", "value"),
...flagList("logout admin save import persist switch current overwrite candidates list-candidates", "boolean")
...flagList("all a logout admin save import persist switch current overwrite candidates list-candidates", "boolean")
}
}
};
+4 -3
View File
@@ -1,5 +1,5 @@
import { listAssistTickets } from "../../../domains/assist-platform/services.js";
import { stringOption } from "../../parser.js";
import { booleanOption, stringOption } from "../../parser.js";
import { printJson, printTable } from "../../printer.js";
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { resolveAssistClient } from "./common.js";
@@ -9,6 +9,7 @@ export async function handleTickets(
runtime: CliRuntime
): Promise<CliResult> {
const client = resolveAssistClient(parsed, runtime);
const isAll = booleanOption(parsed.options, ["all", "a"], false);
const corpId =
parsed.args[0] ||
stringOption(parsed.options, ["corp", "corpid", "id"]) ||
@@ -17,7 +18,7 @@ export async function handleTickets(
if (!corpId) {
return {
stdout: "",
stderr: "用法: hose-use assist-platform tickets <企业ID>\n示例: hose-use assist-platform tickets Cxa3oOtQi2eS$g\n",
stderr: "用法: hose-use assist-platform tickets <企业ID> [--all]\n示例: hose-use assist-platform tickets Cxa3oOtQi2eS$g\n",
exitCode: 1,
};
}
@@ -26,7 +27,7 @@ export async function handleTickets(
if (runtime.jsonMode) {
return {
stdout: printJson({ corporationId: corpId, count: tickets.length, tickets }, runtime.outputOptions),
stdout: printJson({ corporationId: corpId, count: tickets.length, all: isAll, tickets }, runtime.outputOptions),
stderr: "",
exitCode: 0,
};
+2 -1
View File
@@ -207,7 +207,8 @@ export async function handleTrace(ctx: BillActionContext): Promise<CliResult> {
}
const client = await ctx.getClient();
const report = await traceBillFlowDetail(client, corpId, target);
const skipInvoices = booleanOption(parsed.options, ["no-invoice", "noInvoice", "basic"]);
const report = await traceBillFlowDetail(client, corpId, target, { skipInvoices });
if (!report.found) {
if (runtime.jsonMode) {
+48 -3
View File
@@ -50,10 +50,55 @@ export async function handleSchema(parsed: CliParsedArgs, runtime: CliRuntime):
const resolved = await resolveAppAndEntity(parsed, runtime);
const entities = resolved.entity ? [resolved.entity] : await listPlatformEntities(resolved.clients.ekbClient, resolved.corpId, resolved.platform.id);
const fieldKeyword = stringOption(parsed.options, ["keyword", "field", "name"])?.toLowerCase();
const output = entities.map((entity) => ({ ...entity, fields: fieldKeyword ? entity.fields.filter((field) => [field.name, field.label, field.type].some((value) => value.toLowerCase().includes(fieldKeyword))) : entity.fields }));
const output = entities.map((entity) => ({
...entity,
fields: fieldKeyword
? entity.fields.filter((field) =>
[field.name, field.label, field.type, field.fieldKey, field.displayName].some(
(value) => typeof value === "string" && value.toLowerCase().includes(fieldKeyword)
)
)
: entity.fields,
}));
if (runtime.jsonMode) return { stdout: printJson({ platform: resolved.platform, count: output.length, entities: output }, runtime.outputOptions), stderr: "", exitCode: 0 };
const rows = output.flatMap((entity) => entity.fields.map((field): Array<string | number | boolean | null | undefined> => [entity.name, field.name, field.label, field.type, field.optional === false ? "必填" : "可选", cell(field.entity)]));
return { stdout: `====== 应用 [${resolved.platform.name}] 字段定义 ======\n${printTable(["业务对象", "字段名", "显示名", "类型", "必填性", "引用对象"], rows)}\n`, stderr: "", exitCode: 0 };
const rows = output.flatMap((entity) =>
entity.fields.map((field): Array<string | number | boolean | null | undefined> => {
const roleTag =
field.role === "title"
? "⭐ 主标题 (_name)"
: field.role === "code"
? "🔢 业务编码 (_code)"
: field.role === "system"
? "⚙️ 系统字段"
: "📝 业务字段";
return [
entity.name,
field.name,
field.label,
field.type,
roleTag,
field.optional === false ? "必填" : "可选",
cell(field.entity),
];
})
);
const table = printTable(
["业务对象", "物理字段键 (fieldKey / 接口参数名)", "界面名称 (label)", "类型", "角色说明", "必填性", "引用对象"],
rows
);
const tips = [
"",
"💡 字段命名与工作流配置避坑提示:",
" 1. 物理字段键 (fieldKey / 接口参数名): 在工作流节点映射 (如 ekuaibao-datalink-create) 和 API 请求中,必须使用此键 (例如 E_..._费用金额),切勿使用中文显示名。",
" 2. 结尾 _name: 代表实体的业务主名称/标题 (界面通常显示为单据/计划名称);",
" 3. 结尾 _code: 代表业务编号/单号 (界面通常显示为单据/计划编码);若设置了 autoNumber 规则,创建时会自动生成流水号。",
"",
].join("\n");
return {
stdout: `====== 应用 [${resolved.platform.name}] 字段定义 (共 ${rows.length} 个字段) ======\n${table}\n${tips}`,
stderr: "",
exitCode: 0,
};
}
export async function handlePermissions(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
+1 -1
View File
@@ -33,7 +33,7 @@ export async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Pr
const rawResult = await listWorkflowLogs(client, pipelineId, {
state: stringOption(parsed.options, ["state"]),
page: numberOption(parsed.options, ["page"]),
pageSize: numberOption(parsed.options, ["page-size", "pageSize", "size"]),
pageSize: numberOption(parsed.options, ["page-size", "pageSize", "size", "limit", "count", "n"]),
startTime: stringOption(parsed.options, ["start-time", "startTime"]),
endTime: stringOption(parsed.options, ["end-time", "endTime"]),
});
+21 -2
View File
@@ -58,9 +58,28 @@ export async function handleWorkflowTest(
if (isProductionCorp) {
warnings.push(`⚠️ 当前企业 [${runtime.selectedCorp?.name || runtime.selectedCorp?.id}] 为正式生产环境 (env: prod)!正式执行时需显式追加 --force 参数。`);
}
const confirmExecution = () => requireMutationConfirmation(parsed, runtime, "执行工作流调试", `hose-use workflow test ${pipelineId} --yes`);
const nextActionCmd = isProductionCorp
? `hose-use workflow test ${pipelineId} --yes --force`
: `hose-use workflow test ${pipelineId} --yes`;
const confirmExecution = () => requireMutationConfirmation(parsed, runtime, "执行工作流调试", nextActionCmd);
if (isDryRun(parsed, runtime)) {
return mutationPreview(parsed, runtime, "执行工作流调试", pipelineId, { flowCodeOrId, rawBody, filePath, empty: isEmpty, autoPublish, timeoutMs, warnings });
const previewResult = mutationPreview(parsed, runtime, "执行工作流调试", pipelineId, { flowCodeOrId, rawBody, filePath, empty: isEmpty, autoPublish, timeoutMs, warnings });
if (isProductionCorp) {
if (runtime.jsonMode) {
try {
const parsedJson = JSON.parse(previewResult.stdout);
if (parsedJson.nextAction && !parsedJson.nextAction.includes("--force")) {
parsedJson.nextAction = `${parsedJson.nextAction} --force`;
previewResult.stdout = `${JSON.stringify(parsedJson, null, 2)}\n`;
}
} catch {
// ignore
}
} else {
previewResult.stdout = previewResult.stdout.replace(/--yes/g, "--yes --force");
}
}
return previewResult;
}
if (flowCodeOrId || rawBody || filePath || isEmpty) confirmExecution();
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
+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>) => {