import { afterEach, describe, expect, it, spyOn } from "bun:test"; import { mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import * as services from "../../domains/platform/services.js"; import * as billApi from "../../domains/bill/api.js"; import * as cache from "../../core/cache/index.js"; import * as session from "../../core/http/session-client.js"; import * as helpers from "../helpers.js"; import * as workflowShared from "./workflow/shared.js"; import * as platformShared from "./platform/shared.js"; import { parseArgs } from "../parser.js"; import { runCli } from "../runner.js"; import { commandFlags } from "../command-metadata.js"; import { renderScopedHelp } from "../help.js"; import type { CliRuntime } from "../types.js"; import { handleNodeCommand } from "./workflow/node.js"; import { handleLogs } from "./workflow/history.js"; import { handleJob } from "./workflow/job.js"; import { handleSchema } from "./platform/app-info.js"; import { handleBillCommand } from "./bill/index.js"; import { handleFlowCommand } from "./flow.js"; const runtime = { selectedCorp: { id: "fixture-corp", name: "离线测试企业", credentials: { corpId: "fixture-corp" } }, jsonMode: true, } as CliRuntime; const spies: Array<{ mockRestore(): void }> = []; const directories: string[] = []; afterEach(async () => { for (const spy of spies.splice(0).reverse()) spy.mockRestore(); await Promise.all(directories.splice(0).map((path) => rm(path, { recursive: true, force: true }))); }); describe("review CLI compatibility regressions", () => { it("keeps real trace-shaped boolean flags valid through runner redaction", async () => { const raw = { id: "bill", state: "DRAFT", flowId: { id: "flow", state: "DRAFT", form: { code: "B-FIXTURE", keepItSecret: false, appSecurity: "fixture-credential" }, plan: { nodes: [] } } }; spies.push(spyOn(helpers, "initCorpRuntime").mockReturnValue(runtime as any)); spies.push(spyOn(session, "createSessionClient").mockResolvedValue({} as any)); spies.push(spyOn(billApi, "getRawBillFlow").mockResolvedValue(raw)); const result = await runCli(["bill", "trace", "B-FIXTURE", "--basic", "--json"]); expect(result.exitCode).toBe(0); const data = JSON.parse(result.stdout); expect(data.raw.flowId.form.keepItSecret).toBe(false); expect(data.raw.flowId.form.appSecurity).toBe(""); expect(result.stdout).not.toContain("fixture-credential"); expect(result.stderr).toContain("旧版兼容参数"); }); it("documents legacy trace flags without dropping them from the parser vocabulary", () => { for (const [area, action] of [["bill", "trace"], ["flow", "get"], ["trace", "get"]]) { const help = renderScopedHelp([area!, action!]); expect(help).toContain("兼容空操作"); expect(help).toContain("不补充加载发票详情"); const documented = help.split("支持选项:\n")[1]!.split("\n\n提示:")[0]!.trim().split("\n").map((line) => line.trim().match(/^--([^=[\s]+)/)?.[1]); expect(documented).toEqual(Object.keys(commandFlags(area, action))); for (const flag of ["no-invoice", "noInvoice", "basic"]) { expect(commandFlags(area, action)[flag]).toBe("boolean"); } } }); it("restores edit --file as code while explicit mapping and map --file still work", async () => { const dir = await mkdtemp(join(tmpdir(), "hose-node-options-")); directories.push(dir); const codeFile = join(dir, "script.js"); const mappingFile = join(dir, "mapping.json"); const code = "// Keep exact bytes.\nreturn 7;\n"; await writeFile(codeFile, code); await writeFile(mappingFile, JSON.stringify({ label: "mapped" })); const detail = { id: "wf", state: 0, tasks: [{ name: "action_js", type: "code-js2", label: "original", code: "return 0;" }] }; spies.push(spyOn(workflowShared, "createWorkflowDetailClient").mockResolvedValue({ client: {} } as any)); spies.push(spyOn(services, "getWorkflowDetail").mockResolvedValue(detail as any)); const save = spyOn(services, "updateWorkflow").mockImplementation(async (_client, workflow) => workflow); spies.push(save); for (const flag of ["file", "code-file"]) { const result = await handleNodeCommand(parseArgs(["workflow", "node", "edit", "wf", "action_js", `--${flag}=${codeFile}`, "--dry-run"]), runtime); expect(result.exitCode).toBe(0); expect(JSON.parse(result.stdout).changes.updatedFields.code).toContain(`${code.length} 字符`); } for (const [action, flag] of [["edit", "mapping-file"], ["edit", "mapping"], ["edit", "json-file"], ["map", "file"]]) { const result = await handleNodeCommand(parseArgs(["workflow", "node", action!, "wf", "action_js", `--${flag}=${mappingFile}`, "--dry-run"]), runtime); expect(result.exitCode).toBe(0); expect(JSON.parse(result.stdout).changes.changedKeys).toContain("label"); } expect(save).not.toHaveBeenCalled(); const result = await handleNodeCommand(parseArgs(["workflow", "node", "edit", "wf", "action_js", `--file=${codeFile}`, "--yes"]), runtime); expect(result.exitCode).toBe(0); expect(save).toHaveBeenCalledTimes(1); expect(JSON.parse(result.stdout).editedTask.code).toBe(code); expect((save.mock.calls[0]?.[1]?.tasks?.[0] as any).code).toBe(code); }); for (const fallback of [false, true]) { it(`keeps legacy trace invoice flags as explicit no-ops (${fallback ? "search fallback" : "direct flow"})`, async () => { const target = fallback ? "流水中文" : "B-FIXTURE"; const raw = { id: "bill", state: "DRAFT", flowId: { id: "flow", state: "DRAFT", form: { code: target, details: [{ feeTypeForm: { invoices: [{ invoiceId: "invoice" }] } }] }, plan: { nodes: [] } } }; spies.push(spyOn(session, "createSessionClient").mockResolvedValue({} as any)); spies.push(spyOn(billApi, "getRawBillFlow").mockImplementation(async (_client, _corp, query) => fallback && query !== "bill" ? undefined : raw)); spies.push(spyOn(cache, "getGlobalCache").mockReturnValue({ withCache: async (_key: unknown, loader: () => Promise) => loader() } as any)); spies.push(spyOn(billApi, "listEntitySchemas").mockResolvedValue([])); const search = spyOn(billApi, "searchRawBills").mockResolvedValue({ items: [{ id: "bill", code: target, form: {} }], total: 1 } as any); spies.push(search); const invoice = spyOn(billApi, "getInvoiceValidationDetail").mockRejectedValue(new Error("must not supplement invoices")); spies.push(invoice); const baseline = await handleBillCommand(parseArgs(["bill", "trace", target]), runtime); expect(baseline.stderr).toBe(""); expect(baseline.exitCode).toBe(0); for (const [area, action] of [["bill", "trace"], ["bill", "inspect"], ["flow", "get"], ["flow", "trace"], ["flow", "diagnose"]]) { for (const flag of ["no-invoice", "noInvoice", "basic"]) { for (const value of ["true", "false"]) { const parsed = parseArgs([area!, action!, target, `--${flag}=${value}`]); expect(parsed.options[flag]).toBe(value === "true"); const result = await (area === "bill" ? handleBillCommand : handleFlowCommand)(parsed, runtime); expect(result.exitCode).toBe(baseline.exitCode); expect(JSON.parse(result.stdout)).toEqual(JSON.parse(baseline.stdout)); expect(result.stderr).toContain("仅为旧版兼容参数"); } } } const text = await handleBillCommand(parseArgs(["bill", "trace", target, "--basic"]), { ...runtime, jsonMode: false }); expect(text.stdout).toContain("单据全域穿透诊断"); expect(text.stderr).toContain("不会改变结果"); expect(invoice).not.toHaveBeenCalled(); if (fallback) expect(search).toHaveBeenCalled(); else expect(search).not.toHaveBeenCalled(); }); } it("preserves not-found trace output and status with compatibility notices", async () => { spies.push(spyOn(session, "createSessionClient").mockResolvedValue({} as any)); spies.push(spyOn(billApi, "getRawBillFlow").mockResolvedValue(undefined)); spies.push(spyOn(cache, "getGlobalCache").mockReturnValue({ withCache: async (_key: unknown, loader: () => Promise) => loader() } as any)); spies.push(spyOn(billApi, "listEntitySchemas").mockResolvedValue([])); spies.push(spyOn(billApi, "searchRawBills").mockResolvedValue({ items: [], total: 0 } as any)); for (const jsonMode of [false, true]) { const result = await handleBillCommand(parseArgs(["bill", "trace", "missing", "--basic=false"]), { ...runtime, jsonMode }); expect(result.exitCode).toBe(1); expect(result.stderr).toContain("旧版兼容参数"); if (jsonMode) expect(JSON.parse(result.stdout).found).toBe(false); else expect(result.stderr).toContain("[NOT FOUND]"); } }); it("shows actual physical schema keys, preserves JSON and falls back to name", async () => { const fields = [{ name: "alias_name", fieldKey: "E_REAL_KEY", label: "字段", type: "text" }, { name: "fallback_key", label: "旧字段", type: "text" }]; spies.push(spyOn(platformShared, "resolveAppAndEntity").mockResolvedValue({ clients: {}, corpId: "corp", platform: { id: "app", name: "应用" }, entity: { id: "entity", name: "对象", fields } } as any)); const args = ["platform", "schema", "app", "entity"]; const text = await handleSchema(parseArgs(args), { ...runtime, jsonMode: false }); expect(text.stdout).toContain("E_REAL_KEY"); expect(text.stdout).toContain("fallback_key"); expect(text.stdout).not.toContain("alias_name"); const json = JSON.parse((await handleSchema(parseArgs(args), runtime)).stdout); expect(json.entities[0].fields).toEqual(fields); const filtered = JSON.parse((await handleSchema(parseArgs([...args, "--keyword=E_REAL_KEY"]), runtime)).stdout); expect(filtered.entities[0].fields).toEqual([fields[0]]); }); it("finds in-flight errors without expanding the existing terminal state filters", async () => { const jobs = [ { id: "running-boolean", status: "RUNNING", hasError: true }, { id: "started-string", status: "STARTED", hasError: "true" }, { id: "running-localized", status: "RUNNING", hasError: "存在" }, { id: "started-count", status: "STARTED", errorTaskCount: 1 }, { id: "running-normal", status: "RUNNING", hasError: false, errorTaskCount: 0 }, { id: "started-normal", status: "STARTED", hasError: "不存在" }, { id: "completed-normal", status: "COMPLETED", hasError: "false" }, { id: "completed-skip", status: "COMPLETED", errorTaskCount: 1 }, { id: "failed", status: "FAILED" }, ]; const page = { executeCount: 9, successCount: 2, errorCount: 1, totalItems: 9, jobList: jobs }; spies.push(spyOn(workflowShared, "createWorkflowDetailClient").mockResolvedValue({ client: {} } as any)); const logs = spyOn(services, "listWorkflowLogs").mockResolvedValue(page as any); spies.push(logs, spyOn(services, "getWorkflowDetail").mockRejectedValue(new Error("offline unavailable"))); const read = async (flags: string[]) => JSON.parse((await handleLogs(parseArgs(["workflow", "logs", "wf", ...flags]), runtime)).stdout); const errors = await read(["--has-error"]); const expected = ["running-boolean", "started-string", "running-localized", "started-count", "completed-skip", "failed"]; expect(errors.jobList.map((j: any) => j.id)).toEqual(expected); expect(errors.totalItems).toBe(9); expect(errors.inProgressCount).toBe(6); expect((await read([])).jobList).toEqual(jobs); expect((await read(["--state=FAILED"])).jobList.map((j: any) => j.id)).toEqual(["completed-skip", "failed"]); expect((await read(["--state=COMPLETED"])).jobList.map((j: any) => j.id)).toEqual(["completed-normal"]); expect((await read(["--state=RUNNING"])).jobList).toEqual(jobs.slice(0, 6)); expect((await read(["--state=RUNNING", "--has-error"])).jobList.map((j: any) => j.id)).toEqual(expected); expect(logs.mock.calls.at(-1)?.[2]?.state).toBe("RUNNING"); const text = await handleLogs(parseArgs(["workflow", "logs", "wf"]), { ...runtime, jsonMode: false }); expect(text.stdout.split("\n").find((line) => line.includes("running-boolean"))).toContain("⚠️ 包含错误"); expect(text.stdout.split("\n").find((line) => line.includes("running-normal"))).toContain("⏳ 执行中"); }); for (const state of [undefined, 0, 1, 2]) { it(`reports workflow state truthfully when detail state is ${state ?? "unavailable"}`, async () => { spies.push(spyOn(helpers, "createPiperClientForCorp").mockResolvedValue({} as any)); spies.push(spyOn(services, "getJob").mockResolvedValue({ id: "job", pipelineId: "wf", status: "RUNNING" } as any)); spies.push(spyOn(services, "getJobExecutionTree").mockResolvedValue([])); spies.push(spyOn(services, "getJobFailedExecutions").mockResolvedValue({ items: [] } as any)); const detail = spyOn(services, "getWorkflowDetail"); spies.push(detail); if (state === undefined) detail.mockRejectedValue(new Error("offline detail unavailable")); else detail.mockResolvedValue({ id: "wf", state, tasks: [{ name: "trigger", type: "clock" }] } as any); const expected = state === undefined ? "未知(无法读取工作流详情)" : state === 0 ? "⚪ 已停用" : state === 1 ? "🟢 启用中" : "未知"; for (const mode of [[], ["--timeline"]]) { const parsed = parseArgs(["workflow", "job", "job", "--platform=p", ...mode]); const text = await handleJob(parsed, { ...runtime, jsonMode: false }); expect(text.exitCode).toBe(0); expect(text.stdout).toContain(expected); if (state !== 0) expect(text.stdout).not.toContain("已停用"); const json = JSON.parse((await handleJob(parsed, runtime)).stdout); if (state === undefined) { expect(json.workflow).toBeUndefined(); expect(json.job.id).toBe("job"); } else if (mode.length) expect(json.workflowState).toBe(expected); else expect(json.workflow.stateLabel).toBe(expected); } }); } });