feat(platform): 支持工作流单号本地缓存秒级定位与自建应用业务对象智能反查
- 数据库迁移与本地缓存:在 `core/db/migrations.ts` 新增 version 5 迁移 (`005_workflow_job_cache`),创建 `workflow_job_index` 缓存表及高效复合索引;实现 `core/db/workflow-job-cache.ts`,支持按企业+工作流+单号快速检索与幂等增量缓存; - 流式早停探查与业务编排:在 `domains/platform/workflow/execution/search-by-flow.ts` 实现 `searchWorkflowJobByFlowCode`,采用「本地 SQLite 缓存 0ms 直达 ➔ 远端流式探查早停熔断并自动建立本地索引」机制,彻底解决云端 Piper API 无单号索引导致的排查低效问题; - CLI 命令层升级: - `workflow logs <pipelineId> --flow=<单号>`:直接秒级定位单据关联 Job 实例; - `platform records <业务对象>`:支持单参数业务对象名称,自动在企业全量自建应用中全局反查与智能寻址,若跨应用重名则抛出精准候选; - 命令行元数据对齐:在 `command-metadata.ts` 为 `workflow` 补齐 `--max-pages`、`--maxPages` 与 `--page-limit` 选项注册,满足严格参数词汇表静态检查; - 测试与文档:新增并更新 `workflow-job-cache.test.ts`、`search-by-flow.test.ts`、`platform.test.ts` 与 `db.test.ts`,更新核心与域层文档,全量 1126 个测试与类型检查全部通过。
This commit is contained in:
1 parent
ea5eb22c51
commit
0c9eb27f85
16 files changed
+798
-19
No files matched your search
@@ -340,7 +340,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
|
||||
"outbound-message": "outbound"
|
||||
},
|
||||
|
||||
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 is-test 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 choose-serialization code code-file container count d data desc description display display-name displayName 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 json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs message-type n name node node-id nodeId nodes offset 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 seconds set size sleep-time sleepTime sn snapshot1 snapshot2 snapshotA snapshotB source start 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 is-test 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 choose-serialization code code-file container count d data desc description display display-name displayName 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 json-file keyword l label limit log logs mapping mapping-file max-jobs maxJobs max-pages maxPages message-type n name node node-id nodeId nodes offset output output-file outputFile p page page-limit 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 seconds set size sleep-time sleepTime sn snapshot1 snapshot2 snapshotA snapshotB source start 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": {
|
||||
|
||||
@@ -572,5 +572,85 @@ describe("CLI - platform 命令与 record 动作", () => {
|
||||
expect(jsRes.stdout).toContain('const ENTITY_ID = "E_contract";');
|
||||
expect(jsRes.stdout).toContain('"合同名称": FIELD_PREFIX + "name"');
|
||||
});
|
||||
|
||||
it("platform records 支持仅传单参数业务对象名称,全局反查其所属应用", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
// 按应用名称查未找到
|
||||
spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(undefined));
|
||||
// 列出所有平台
|
||||
spies.push(spyOn(servicesApplications, "listPlatforms").mockResolvedValue([
|
||||
{ id: "platform-lease", name: "租赁摊销业务" } as any,
|
||||
{ id: "platform-other", name: "其他应用" } as any,
|
||||
]));
|
||||
// 模拟应用详情与对象列表
|
||||
spies.push(spyOn(servicesApplications, "getPlatform").mockResolvedValue({
|
||||
id: "platform-lease",
|
||||
name: "租赁摊销业务",
|
||||
} as any));
|
||||
spies.push(spyOn(services, "listPlatformEntities").mockImplementation(async (_, __, platformId) => {
|
||||
if (platformId === "platform-lease") {
|
||||
return [
|
||||
{ id: "ent-track", name: "付款发票跟踪", code: "TRACK", fields: [{ name: "name", label: "名称", type: "text" }] } as any,
|
||||
];
|
||||
}
|
||||
return [];
|
||||
}));
|
||||
spies.push(spyOn(api, "searchEntityRecords").mockResolvedValue({
|
||||
total: 1,
|
||||
data: [
|
||||
{
|
||||
id: "rec-1",
|
||||
dataLink: { id: "rec-1", name: "记录1", code: "R1", active: true, updateTime: "2026-10-22" },
|
||||
},
|
||||
],
|
||||
actions: [],
|
||||
components: [],
|
||||
path: null,
|
||||
template: null,
|
||||
}));
|
||||
|
||||
const res = await handlePlatformCommand(
|
||||
{ area: "platform", action: "records", args: ["付款发票跟踪"], options: { count: 1 }, raw: [] },
|
||||
dummyRuntime
|
||||
);
|
||||
|
||||
expect(res.exitCode).toBe(0);
|
||||
expect(res.stdout).toContain("记录1");
|
||||
});
|
||||
|
||||
it("platform records 单参数业务对象在多个应用重名时抛出明确指导错误", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(undefined));
|
||||
spies.push(spyOn(servicesApplications, "listPlatforms").mockResolvedValue([
|
||||
{ id: "app-1", name: "应用一" } as any,
|
||||
{ id: "app-2", name: "应用二" } as any,
|
||||
]));
|
||||
spies.push(spyOn(services, "listPlatformEntities").mockImplementation(async (_, __, platformId) => {
|
||||
return [{ id: `ent-${platformId}`, name: "重名对象", code: "DUP" } as any];
|
||||
}));
|
||||
|
||||
await expect(
|
||||
handlePlatformCommand(
|
||||
{ area: "platform", action: "records", args: ["重名对象"], options: {}, raw: [] },
|
||||
dummyRuntime
|
||||
)
|
||||
).rejects.toThrow("在多个自建应用中找到同名业务对象 [重名对象],请显式指定应用名称");
|
||||
});
|
||||
|
||||
it("platform records 单参数既不是应用也不是业务对象时返回明确 NOT FOUND 错误", async () => {
|
||||
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ ekbClient: {} } as any));
|
||||
spies.push(spyOn(servicesApplications, "resolvePlatform").mockResolvedValue(undefined));
|
||||
spies.push(spyOn(servicesApplications, "listPlatforms").mockResolvedValue([
|
||||
{ id: "app-1", name: "应用一" } as any,
|
||||
]));
|
||||
spies.push(spyOn(services, "listPlatformEntities").mockResolvedValue([]));
|
||||
|
||||
await expect(
|
||||
handlePlatformCommand(
|
||||
{ area: "platform", action: "records", args: ["未知目标"], options: {}, raw: [] },
|
||||
dummyRuntime
|
||||
)
|
||||
).rejects.toThrow("[NOT FOUND] 当前企业下未找到名为 [未知目标] 的自建应用或业务对象");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -243,8 +243,8 @@ export async function handleRecords(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
};
|
||||
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: "", exitCode: 0 };
|
||||
|
||||
const nameField = resolved.entity.fields.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name"));
|
||||
const codeField = resolved.entity.fields.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code"));
|
||||
const nameField = resolved.entity.fields?.find((f) => f.label === "名称" || f.label.includes("名称") || f.name.endsWith("_name"));
|
||||
const codeField = resolved.entity.fields?.find((f) => f.label === "编码" || f.label.includes("编码") || f.name.endsWith("_code"));
|
||||
const rows = data.map((item, i): Array<string | number | boolean | null | undefined> => {
|
||||
const source = item.dataLink && typeof item.dataLink === "object" && !Array.isArray(item.dataLink) ? (item.dataLink as Record<string, unknown>) : item;
|
||||
const id = source.id ?? item.id;
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { resolveEntity } from "../../../domains/platform/datalink/services.js";
|
||||
import { resolvePlatform } from "../../../domains/platform/applications/services.js";
|
||||
import type { KyInstance } from "ky";
|
||||
import { listPlatformEntities, resolveEntity } from "../../../domains/platform/datalink/services.js";
|
||||
import { getPlatform, listPlatforms, resolvePlatform } from "../../../domains/platform/applications/services.js";
|
||||
import type { DatalinkEntity } from "../../../domains/platform/datalink/types.js";
|
||||
import type { DatalinkPlatformDetail } from "../../../domains/platform/applications/types.js";
|
||||
import { createClientsForCorp } from "../../helpers.js";
|
||||
import type { CliParsedArgs, CliRuntime } from "../../types.js";
|
||||
|
||||
@@ -19,16 +22,81 @@ export function cell(value: unknown): string {
|
||||
return String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 在企业全量自建应用中智能反查指定业务对象,避免强制用户/Agent 手动查询并记忆 platformId
|
||||
*/
|
||||
async function resolveEntityGlobally(
|
||||
client: KyInstance,
|
||||
corpId: string,
|
||||
target: string
|
||||
): Promise<{ platform: DatalinkPlatformDetail; entity: DatalinkEntity } | undefined> {
|
||||
const platforms = await listPlatforms(client, corpId);
|
||||
const matches: Array<{ platform: any; entity: DatalinkEntity }> = [];
|
||||
|
||||
const results = await Promise.allSettled(
|
||||
platforms.map(async (p) => {
|
||||
const entities = await listPlatformEntities(client, corpId, p.id);
|
||||
const found = entities.find((e) =>
|
||||
[e.id, e.name, e.code].some((val) => typeof val === "string" && val.toLowerCase() === target.toLowerCase())
|
||||
);
|
||||
if (found) {
|
||||
return { platform: p, entity: found };
|
||||
}
|
||||
return null;
|
||||
})
|
||||
);
|
||||
|
||||
for (const r of results) {
|
||||
if (r.status === "fulfilled" && r.value) {
|
||||
matches.push(r.value);
|
||||
}
|
||||
}
|
||||
|
||||
if (matches.length === 1) {
|
||||
const fullPlatform = await getPlatform(client, corpId, matches[0].platform.id);
|
||||
return { platform: fullPlatform || matches[0].platform, entity: matches[0].entity };
|
||||
}
|
||||
|
||||
if (matches.length > 1) {
|
||||
const names = matches.map((m) => `[${m.platform.name}] (${m.platform.id})`).join(", ");
|
||||
throw new Error(`在多个自建应用中找到同名业务对象 [${target}],请显式指定应用名称: ${names}`);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export async function resolveAppAndEntity(parsed: CliParsedArgs, runtime: CliRuntime, appIndex = 0, entityIndex = 1) {
|
||||
const appTarget = requiredTarget(parsed, appIndex, "hose-use platform <子命令> <应用 ID|名称>");
|
||||
const targetA = parsed.args[appIndex]?.trim();
|
||||
const targetB = parsed.args[entityIndex]?.trim();
|
||||
|
||||
if (!targetA) {
|
||||
throw new Error("请提供自建应用或业务对象参数: hose-use platform <子命令> [应用] <业务对象>");
|
||||
}
|
||||
|
||||
const clients = await createClientsForCorp(runtime.selectedCorp!);
|
||||
const corpId = runtime.selectedCorp!.credentials.corpId;
|
||||
const platform = await resolvePlatform(clients.ekbClient, corpId, appTarget);
|
||||
if (!platform) throw new Error(`[NOT FOUND] 当前企业下未找到自建应用: ${appTarget}`);
|
||||
|
||||
const entityTarget = parsed.args[entityIndex]?.trim();
|
||||
if (!entityTarget) return { clients, corpId, platform, entity: undefined };
|
||||
const entity = await resolveEntity(clients.ekbClient, corpId, platform, entityTarget);
|
||||
if (!entity) throw new Error(`[NOT FOUND] 应用 [${platform.name}] 下未找到业务对象: ${entityTarget}`);
|
||||
return { clients, corpId, platform, entity };
|
||||
// 1. 若提供了两个位置参数,严格按「应用 ➔ 对象」标准两级解析
|
||||
if (targetB) {
|
||||
const platform = await resolvePlatform(clients.ekbClient, corpId, targetA);
|
||||
if (!platform) throw new Error(`[NOT FOUND] 当前企业下未找到自建应用: ${targetA}`);
|
||||
const entity = await resolveEntity(clients.ekbClient, corpId, platform, targetB);
|
||||
if (!entity) throw new Error(`[NOT FOUND] 应用 [${platform.name}] 下未找到业务对象: ${targetB}`);
|
||||
return { clients, corpId, platform, entity };
|
||||
}
|
||||
|
||||
// 2. 若仅提供了一个位置参数:优先尝试按「应用」解析(兼容查看应用级信息,如 entities/audit 等)
|
||||
const platform = await resolvePlatform(clients.ekbClient, corpId, targetA);
|
||||
if (platform) {
|
||||
return { clients, corpId, platform, entity: undefined };
|
||||
}
|
||||
|
||||
// 3. 若按应用未找到,自动降维为「业务对象」在企业全量自建应用中智能反查 (Zero-Config Search)
|
||||
const globalMatch = await resolveEntityGlobally(clients.ekbClient, corpId, targetA);
|
||||
if (globalMatch) {
|
||||
return { clients, corpId, platform: globalMatch.platform, entity: globalMatch.entity };
|
||||
}
|
||||
|
||||
throw new Error(`[NOT FOUND] 当前企业下未找到名为 [${targetA}] 的自建应用或业务对象`);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getWorkflowDetail, listWorkflowLogs, listWorkflowSnapshots } from "../../../domains/platform/workflow/services.js";
|
||||
import { getWorkflowDetail, listWorkflowLogs, listWorkflowSnapshots, searchWorkflowJobByFlowCode } from "../../../domains/platform/workflow/services.js";
|
||||
import { stringOption, numberOption, booleanOption } from "../../parser.js";
|
||||
import { printJson, printTable, printKeyValue } from "../../printer.js";
|
||||
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
|
||||
@@ -28,8 +28,52 @@ export async function handleHistory(parsed: CliParsedArgs, runtime: CliRuntime):
|
||||
|
||||
export async function handleLogs(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
|
||||
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow logs <pipelineId> [--state=FAILED] [--has-error] [--start-time=YYYY-MM-DD] [--end-time=YYYY-MM-DD]\n", exitCode: 1 };
|
||||
if (!pipelineId) return { stdout: "", stderr: "用法: hose-use workflow logs <pipelineId> [--flow=<单号>] [--state=FAILED] [--has-error] [--start-time=YYYY-MM-DD] [--end-time=YYYY-MM-DD]\n", exitCode: 1 };
|
||||
const { client } = await createWorkflowDetailClient(parsed, runtime, pipelineId);
|
||||
|
||||
// 优先支持按单号精准定位 Job(本地 SQLite 缓存秒级直达 + 流式熔断探查)
|
||||
const flowFilter = stringOption(parsed.options, ["flow", "flowCode", "code"]);
|
||||
if (flowFilter) {
|
||||
const corpId = runtime.selectedCorp?.credentials.corpId || "";
|
||||
const searchResult = await searchWorkflowJobByFlowCode(client, corpId, pipelineId, flowFilter, {
|
||||
maxScanPages: numberOption(parsed.options, ["max-pages", "maxPages", "page-limit"]) ?? 10,
|
||||
});
|
||||
|
||||
if (runtime.jsonMode) {
|
||||
return {
|
||||
stdout: printJson(searchResult, runtime.outputOptions),
|
||||
stderr: "",
|
||||
exitCode: searchResult.found ? 0 : 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (!searchResult.found) {
|
||||
return {
|
||||
stdout: `未找到单号 [${flowFilter}] 对应的工作流执行记录 (已探查 ${searchResult.totalScanned || 0} 笔 Job)\n`,
|
||||
stderr: "",
|
||||
exitCode: 1,
|
||||
};
|
||||
}
|
||||
|
||||
const job = searchResult.job!;
|
||||
const hitInfo = searchResult.source === "cache" ? "⚡ 本地 SQLite 缓存秒级命中" : "🔍 远端流式探查并自动建立本地缓存";
|
||||
const out = [
|
||||
`====== 工作流单据定位成功 [${pipelineId}] ======`,
|
||||
printKeyValue({
|
||||
"定位来源": hitInfo,
|
||||
"触发单号": searchResult.flowCode || "-",
|
||||
"实例 ID (jobId)": job.id,
|
||||
"运行状态 (status)": job.status || "-",
|
||||
"提交人": job.inputs?.userInfo?.name || "-",
|
||||
"创建时间": job.createTime ? new Date(job.createTime).toLocaleString() : "-",
|
||||
}),
|
||||
"",
|
||||
`提示: 可执行 hose-use workflow job ${job.id} 查看该单据的完整节点执行树与代码运算日志。`,
|
||||
].join("\n");
|
||||
|
||||
return { stdout: `${out}\n`, stderr: "", exitCode: 0 };
|
||||
}
|
||||
|
||||
const rawResult = await listWorkflowLogs(client, pipelineId, {
|
||||
state: stringOption(parsed.options, ["state"]),
|
||||
page: numberOption(parsed.options, ["page"]),
|
||||
|
||||
Reference in new issue
Block a user