fix: 修复审核记录导出进度与后台等待机制

为审核记录导出增加可复用的本地后台任务及 status/wait/list,等待超时或观察进程退出后任务继续执行。
统一实时脱敏诊断输出,保留 stdout 单一 JSON;补齐高级参数、预览和筛选配置摘要。
默认保留合思未找到单据,分别统计单据与审核记录,并显式报告部分补取失败。
补充 CLI/Skill 版本诊断、技能路由及回归测试,修复企业列表加载开销和源码更新测试隔离。
This commit is contained in:
gitea committed 2026-10-27 15:59:04 +08:00
1 parent 477cc630b4
commit db5a3f7139
24 files changed
+1239 -174

No files matched your search

+1
View File
@@ -151,6 +151,7 @@ seal-use langfuse observation <traceId> <observationId> # 最后才取焦点
| 配置、同步或排查发布到 HoseCloud | `references/hose-enterprise-deploy.md` | 涉及生产/测试配对或模拟时,再读 `staging-simulation-workflow.md` |
| 生产草稿、测试同步、模拟、回归、发布 | `references/staging-simulation-workflow.md` | 需要客诉证据定界时,再读 `customer-feedback-rule-remediation.md` |
| 按单号、SN、record ID 查审批、结论、引用规则或直达链接 | `references/approval-run-lightweight.md` | 明确涉及附件/OCR/发票争议时,转读 `approval-attachment-trace.md` |
| 导出审核记录 Excel、额外人工审批流、高级筛选或导出任务等待 | `references/approval-run-export.md` | 只查命令语法时读 `cli.md`;报告与复核台账走 `report-templates.md` |
| 单号对应费用是否入库、数据管理费用明细、费用库检索或记录关联 | `references/expense-data.md` | 明确要求审批结论时,再读 `approval-run-lightweight.md` |
| CLI 参数、退出码或命令语法 | `references/cli.md` | 只查业务流程时不要加载本文件 |
| Webhook 资源包(ZIP/Excel 结构、附件校验、策略配置) | `references/webhook-resource-pack.md` | 只查命令语法时读 `cli.md`,不要加载本文件 |
@@ -0,0 +1,71 @@
# 审核记录 Excel 导出
用户说「导出审核记录」「导出 AI 审核明细」「额外拉人工审批记录」时,使用 `approval-runs export`。
`report ledger` 是报告编制与复核裁决台账,不能代替审核记录导出。沿用旧 Excel 时先核对旧文件;不要声称当前标准格式必然与旧文件完全相同。
## 导出前确认业务口径
确认企业、北京时间起止日期,以及是否额外拉取合思人工审批流。用户已经明确的参数不重复询问。
| 参数 | 默认与含义 |
| --- | --- |
| `--with-flow` / `--no-flow` | 默认关闭。开启后从合思原生审批流补充「E人工行为」「E人工意见」。关闭时仍保留 Seal 已存的「人工审核」「人工驳回原因」 |
| `--include-deleted` / `--exclude-deleted` | **默认保留**合思未找到的单据并标记。只有显式排除才删除对应记录行;排除必须同时开启 `--with-flow`。未找到可能是删除或作废,不等于已证明删除;请求失败另行统计 |
| `--include-simulation` | 生产企业默认排除模拟任务;测试企业默认包含。指定 `--task-mode simulation` 也会包含 |
| `--task-mode` | `assisted`(辅助审核)、`automatic`(自动审批)或 `simulation`(模拟);默认不限制真实任务模式 |
| `--source-system` | 来源系统筛选。合思来源企业仍只保留合思业务来源 |
| `--completed-only` | 只保留 AI 任务已完成记录,不代表人工审批已结束;默认不限制 |
| `--status` / `--manual-status` | 分别筛选 AI 任务状态和人工审批状态,默认不限制 |
| `--limit` | 默认自动分页,最多选取 100,000 条审核记录;可设置 1–100,000 的整数上限,同单多轮审核分别保留 |
| `--flow-concurrency` | 合思单据审批流并发,1–5,默认 3;取数和审批流请求耗时随规模变化,不承诺固定秒数 |
| `--out` / `--downloads` | 指定 Excel 路径;CLI 未指定路径时默认下载目录。业务文件不得落在源码仓库 |
日期包含首尾整天,时区为北京时间。按单号 `--sn` 定向导出且不提供日期时,检索该单号历史记录,不套用默认日期窗口。
互相矛盾的正反开关会返回退出码 2;不会静默选择其中一个。
执行前可核对归一化配置,不访问企业 API、不创建任务或输出目录:
```bash
seal-use approval-runs export --corp <corpId> --start-date 2026-10-19 --end-date 2026-10-25 --with-flow --include-deleted --downloads --dry-run
```
## 长任务:凭据、状态、有界等待
沿用模拟审核的哲学:**任务独立执行,wait 只观察;等待超时不代表任务失败。** 模拟审核在服务端运行,导出由本机独立后台进程执行。
Agent 推荐先创建后台任务,再用短时等待查询:
```bash
seal-use approval-runs export --corp <corpId> --start-date 2026-10-19 --end-date 2026-10-25 --with-flow --include-deleted --downloads --no-wait
seal-use approval-runs export status <taskId>
seal-use approval-runs export wait <taskId> --timeout 30s --poll-interval 2s
seal-use approval-runs export list --corp <corpId>
```
- `--no-wait` 返回任务凭据,不等待网络提数完成。相同企业、有效参数、工作目录、配置来源和构建版本的在途任务会复用,返回 `reused: true`;完成后的任务不自动复用,以便重新获取最新审批意见。
- 自动文件名附带任务短标识,避免同一分钟的不同导出互相覆盖。同一个显式 `--out` 路径已有其他在途任务时拒绝启动,需等待或改用不同文件名。
- `status` 只读本地状态;`wait` 默认最多等待 10 分钟,每 2 秒查一次,可指定 `--timeout` 与 `--poll-interval`。
- 超时返回 `completed: false`、`timedOut: true`、当前阶段和 `next` 命令。继续等待同一个任务,不重发导出。
- 创建调用或 wait 被聊天消息、终端中断后,先用 `list` 找任务,再执行 `status/wait`。没有终端输出不能证明卡住,不要仅据此 kill 或重跑。
- 任务阶段为 `queued → auth → rules → records → flow → write`,最终为 `completed` 或 `failed`。阶段进度不是全流程完成百分比,最近更新时间由后台心跳维护。
- 等待进程退出不会取消后台工作;机器休眠、关机、缓存清理或后台工作进程被终止可能导致任务无法继续。`status` 会识别失效进程,明确报错;本轮不提供跨机器续传或逐阶段断点恢复。
- 不指定等待开关仍保留历史阻塞行为,直到文件生成;`--wait` 或 `--timeout` 启用有界等待。终端诊断实时写入 `stderr`,`stdout` 始终是一次 JSON。
任务元信息和脱敏诊断在 `~/.cache/seal-use/exports/tasks/`,文件权限仅属主可读,不保存企业配置或认证密钥。状态回执包含 `logFile`。文件仍按用户指定位置交付;只在 Excel 保存成功后标记任务完成。
## 交付与计数核对
旧字段 `filePath`、`recordCount`、`excludedDeletedCount`、`excludedSimulationCount` 保留。新增字段包括:
- `filters`:实际日期与筛选口径。
- `counts`:扫描/选取记录数、导出单据数、各类排除数,以及未找到单据的保留单据数和保留审核记录数。
- `flow`:请求、找到、未找到及请求失败的单据数。按单据数统计,不与审核记录数混用。
- `partial` / `warnings`:规则字典、审核详情或原生审批流补取失败时显式说明。不把生成了文件写成数据全部完整。
例如 2,907 条中排除 3 条模拟任务,则导出 2,904 条。362 个未找到单据可能对应 364 条审核记录;默认保留时,这两个数量都会明确返回,不需要靠读取 Excel 推算。
明确终止失败的任务保留错误及退出码;查询 `status` 本身成功不等于导出成功,必须检查 `status/completed/partial`。
## 版本就绪核对
`seal-use version`、`seal-use skill status` 和本地 `seal-use doctor` 会报告 CLI 与已安装技能版本。开发构建后缀不被当成发布代际差异。
技能较新时更新 CLI;CLI 较新时同步技能。版本不一致是诊断信号,不能据此认定业务请求已经失败,也不自动用旧 CLI 内嵌技能覆盖较新的技能。
+8 -1
View File
@@ -96,7 +96,10 @@ seal-use webhook replay --limit <n> [--status <status>] [--source-corp <corpId>]
seal-use approval-runs summary [--date <YYYY-MM-DD>] [--timezone Asia/Shanghai] [--corp <corpId>]
seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id] [--corp <corpId>]
seal-use approval-runs count [--status APPROVED] [--start-date <YYYY-MM-DD|ms>] [--end-date <YYYY-MM-DD|ms>] [--corp <corpId>]
seal-use approval-runs export [--sn <SN1,SN2>] [--start-date <YYYY-MM-DD|ms>] [--end-date <YYYY-MM-DD|ms>] [--force] [--status <status>] [--manual-status <status>] [--completed-only] [--limit <n>] [--downloads] [--with-flow] [--out <file>] [--corp <corpId>]
seal-use approval-runs export [--sn <SN1,SN2>] [--start-date <YYYY-MM-DD|ms>] [--end-date <YYYY-MM-DD|ms>] [--force] [--status <status>] [--manual-status <status>] [--completed-only] [--limit <n>] [--downloads] [--with-flow] [--include-deleted|--exclude-deleted] [--include-simulation] [--task-mode <mode>] [--source-system <source>] [--flow-concurrency <n>] [--no-wait|--wait] [--timeout 10m] [--poll-interval 2s] [--dry-run] [--out <file>] [--corp <corpId>]
seal-use approval-runs export status <taskId> [--corp <corpId>]
seal-use approval-runs export wait <taskId> [--timeout 10m] [--poll-interval 2s] [--corp <corpId>]
seal-use approval-runs export list [--limit <n>] [--corp <corpId>]
seal-use approval-runs hose-flow <recordId|SN> [--corp <corpId>]
seal-use approval-runs list|search [--query text] [--human-result 驳回] [--manual-approval-status TERMINATED] [--start-date <ms>] [--end-date <ms>] [--has-extra-risk] [--limit 20] [--include-bridge] [--corp <corpId>]
seal-use approval-runs pick --sn <documentSN> [--batch <batchId>] [--latest] [--fields recordId,status,aiDecision] [--corp <corpId>]
@@ -247,6 +250,10 @@ seal-use test regression [--corp <corpId>] [--samples <N>] [--dry-run] [--fail-o
```bash
# --sn / --sns: 定向筛选单据编号(支持逗号/分号/空格分隔,跳过全量分页,秒级定向导出特定单据)
# --with-flow: 启用合思原生审批流对齐,输出 E人工行为 / E人工意见 两列(含样式 2-B 三行展开式驳回目标与重审规则、中途修改置顶事实且保留时序、动作 Emoji,默认关闭以节省合思 API 调用)
# --include-deleted(默认)/ --exclude-deleted: 保留并标记合思未找到单据,或显式排除;排除需同时启用 --with-flow,网络请求失败不会当作删除。
# --include-simulation / --task-mode / --source-system / --flow-concurrency: 控制模拟任务、模式、来源和审批流并发(1–5,默认 3)。
# --no-wait: 返回后台导出凭据;export status / export wait / export list 查询同一任务,wait 超时不终止任务。
# --dry-run: 只预览实际配置,无网络请求或文件输出。详细口径、恢复与统计见 approval-run-export.md。
# 导出文件名自动追加精确到分钟的 _YYYYMMDD_HHmm 时间戳后缀防止文件覆盖,格式:${企业名称}_审核记录_${时间区间}_${条数}_${导出时间戳}.xlsx
# 生成审批详情链接:seal-use approval-runs link <recordId>
```
+41 -3
View File
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, test } from "bun:test";
import { spawnSync } from "node:child_process";
import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
import { chmodSync, copyFileSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { VERSION } from "./version.js";
@@ -9,7 +9,7 @@ const CLI_PATH = join(import.meta.dirname, "cli.ts");
const tempDirs: string[] = [];
function runCli(args: string[], env: Record<string, string> = {}) {
return spawnSync("bun", [CLI_PATH, ...args], {
return spawnSync(process.execPath, [CLI_PATH, ...args], {
encoding: "utf-8",
env: { ...process.env, ...env }
});
@@ -153,12 +153,50 @@ describe("CLI version & help handling", () => {
});
test("update command runs in source mode when executed from bun", () => {
const result = runCli(["update"]);
// Exercise the CLI's source-update control flow without fetching Git refs,
// installing packages, or running hooks in the developer's working tree.
// Native shims work with spawnSync on Windows as well as POSIX (no shell).
const dir = mkdtempSync(join(tmpdir(), "cli-source-update-"));
tempDirs.push(dir);
const source = join(dir, "tool-shim.ts");
const suffix = process.platform === "win32" ? ".exe" : "";
const executable = join(dir, `shim${suffix}`);
const log = join(dir, "commands.jsonl");
const realGit = Bun.which("git");
expect(realGit).not.toBeNull();
writeFileSync(source, `
import { basename } from "node:path";
import { appendFileSync } from "node:fs";
import { spawnSync } from "node:child_process";
const command = basename(process.execPath).replace(/\\.exe$/, "");
const args = process.argv.slice(2);
if (command === "git" && !args.includes("pull")) {
const result = spawnSync(${JSON.stringify(realGit)}, args, { encoding: "utf8" });
if (result.stdout) process.stdout.write(result.stdout);
if (result.stderr) process.stderr.write(result.stderr);
process.exitCode = result.status ?? 1;
} else {
appendFileSync(${JSON.stringify(log)}, JSON.stringify({ command, args }) + "\\n");
}
`);
const build = spawnSync(process.execPath, ["build", "--compile", source, "--outfile", executable], { encoding: "utf8" });
expect(build.status).toBe(0);
for (const name of ["git", "bun"]) {
const path = join(dir, `${name}${suffix}`);
copyFileSync(executable, path);
chmodSync(path, 0o755);
}
const result = runCli(["update"], { PATH: `${dir}${process.platform === "win32" ? ";" : ":"}${process.env.PATH ?? ""}` });
expect(result.status).toBe(0);
const parsed = JSON.parse(result.stdout.trim());
expect(parsed.updated).toBe(true);
expect(parsed.mode).toBe("source");
expect(parsed.version).toBe(VERSION);
const calls = readFileSync(log, "utf8").trim().split("\n").map(line => JSON.parse(line));
expect(calls).toEqual([
{ command: "git", args: ["-C", join(import.meta.dirname, ".."), "pull", "--ff-only"] },
{ command: "bun", args: ["install"] }
]);
}, 20000);
test("mcp-config outputs valid mcp configuration json", () => {
+2 -7
View File
@@ -21,7 +21,8 @@ const launcher = resolveDefaultLauncher(entryFile, isCompiled);
const result = await runCli(Bun.argv.slice(2), {
appRoot,
entryFile,
launcher
launcher,
onStderr: (text) => process.stderr.write(text)
});
try {
@@ -30,10 +31,4 @@ try {
if (err?.code !== "EPIPE") throw err;
}
try {
if (result.stderr) process.stderr.write(`${result.stderr}${result.stderr.endsWith("\n") ? "" : "\n"}`);
} catch (err: any) {
if (err?.code !== "EPIPE") throw err;
}
process.exitCode = result.exitCode;
@@ -0,0 +1,191 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { fileURLToPath } from "node:url"
import { join } from "node:path"
import ExcelJS from "exceljs"
import { parseArgs } from "../parser.js"
import { runCli } from "../runner.js"
import { isReadOnlyCliCommand } from "../read-only.js"
import { getExportTask, startExportTask, waitForExportTask, writeExportTask } from "../../domains/seal/approval-runs/export-task.js"
import { resolveExportOptions } from "./approval-runs-export.js"
import type { CorpConfig } from "../../core/config/types.js"
const keys = ["SEAL_USE_ENTERPRISES_DIR", "SEAL_USE_CONFIG_FILE", "SEAL_USE_TOKEN_STORE", "SEAL_USE_USAGE_FILE", "SEAL_USE_EXPORT_TASKS_DIR", "SEAL_DISABLE_BG_UPDATE"] as const
const previous = Object.fromEntries(keys.map(key => [key, process.env[key]]))
let dir: string
const corp = { id: "export-fixture", name: "导出测试", environment: "production", source: { type: "hose" } } as CorpConfig
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "seal-export-cli-"))
const enterprises = join(dir, "enterprises")
mkdirSync(enterprises)
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises
process.env.SEAL_USE_CONFIG_FILE = join(dir, "config.json")
process.env.SEAL_USE_TOKEN_STORE = join(dir, "tokens.json")
process.env.SEAL_USE_USAGE_FILE = join(dir, "usage.json")
process.env.SEAL_USE_EXPORT_TASKS_DIR = join(dir, "tasks")
process.env.SEAL_DISABLE_BG_UPDATE = "1"
writeFileSync(join(enterprises, "export-fixture.json"), JSON.stringify({
...corp, source: { type: "seal", token: "fixture-token", sealUrl: "http://127.0.0.1:1", staffId: "fixture" }
}))
})
afterEach(() => {
for (const key of keys) {
if (previous[key] === undefined) delete process.env[key]
else process.env[key] = previous[key]
}
rmSync(dir, { recursive: true, force: true })
})
describe("audit export options and observation", () => {
test("normalizes business defaults and explicit overrides without side effects", () => {
const args = parseArgs(["approval-runs", "export", "--with-flow", "--include-deleted", "--start-date", "2026-10-19", "--end-date", "2026-10-25"])
expect(resolveExportOptions(args, corp)).toMatchObject({
startDate: "2026-10-19", endDate: "2026-10-25", withFlow: true,
excludeDeleted: false, includeSimulation: false, includeCompletedOnly: false, flowConcurrency: 3, toDownloads: true
})
const targeted = resolveExportOptions(parseArgs(["approval-runs", "export", "--sn", "B2,B1,B1"]), corp)
expect(targeted.sns).toEqual(["B1", "B2"])
expect(targeted.startDate).toBeUndefined()
expect(resolveExportOptions(parseArgs(["approval-runs", "export", "--task-mode", "simulation"]), corp).includeSimulation).toBe(true)
expect(resolveExportOptions(parseArgs(["approval-runs", "export", "--no-flow=false", "--include-deleted=false"]), corp)).toMatchObject({ withFlow: true, excludeDeleted: true })
expect(resolveExportOptions(parseArgs(["approval-runs", "export", "--include-simulation=false"]), { ...corp, environment: "test" }).includeSimulation).toBe(false)
expect(existsSync(join(dir, "tasks"))).toBe(false)
})
test("rejects conflicting flags, out-of-range controls and ineffective deletion filtering", () => {
for (const flags of [
["--with-flow", "--no-flow"], ["--exclude-deleted", "--include-deleted"], ["--wait", "--no-wait"],
["--flow-concurrency", "0"], ["--flow-concurrency", "6"], ["--flow-concurrency", "1.5"],
["--limit", "0"], ["--limit", "100001"], ["--exclude-deleted"], ["--task-mode", "invalid"]
]) expect(() => resolveExportOptions(parseArgs(["approval-runs", "export", ...flags]), corp)).toThrow()
expect(isReadOnlyCliCommand(["approval-runs", "export", "status", "id"])).toBe(true)
expect(isReadOnlyCliCommand(["approval-runs", "export-worker", "id"])).toBe(false)
})
test("dry-run and local list/status never authenticate or create an output directory", async () => {
const output = join(dir, "not-created", "audit.xlsx")
const result = await runCli(["approval-runs", "export", "--corp", corp.id, "--dry-run", "--out", output])
expect(result.exitCode).toBe(0)
expect(JSON.parse(result.stdout)).toMatchObject({ preview: true, options: { outputFile: output, excludeDeleted: false } })
expect(existsSync(join(dir, "not-created"))).toBe(false)
expect(existsSync(join(dir, "tasks"))).toBe(false)
expect(JSON.parse((await runCli(["approval-runs", "export", "list"])).stdout)).toMatchObject({ count: 0 })
expect((await runCli(["approval-runs", "export", "status", "../bad"])).exitCode).toBe(13)
})
test("wait preserves failed-worker authentication exit codes and a structured receipt", async () => {
const options = resolveExportOptions(parseArgs(["approval-runs", "export"]), corp)
const { task } = startExportTask({ corpId: corp.id, corpName: corp.name, options, launcher: { command: process.execPath } }, task => {
task.status = "failed"
task.error = "session invalid"
task.exitCode = 11
writeExportTask(task)
return process.pid
})
const status = await runCli(["approval-runs", "export", "status", task.id])
expect(status.exitCode).toBe(0)
expect(JSON.parse(status.stdout)).toMatchObject({ status: "failed", completed: false, terminal: true })
const result = await runCli(["approval-runs", "export", "wait", task.id])
expect(result.exitCode).toBe(11)
expect(JSON.parse(result.stdout)).toMatchObject({ status: "failed", completed: false, error: "session invalid" })
})
test("simulation wait streams redacted diagnostics before the operation finishes", async () => {
const received = Promise.withResolvers<void>()
const release = Promise.withResolvers<void>()
const server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: async () => {
received.resolve()
await release.promise
return Response.json({ data: { id: "fixture", status: "completed", totalCount: 1, processedCount: 1,
successCount: 1, failedCount: 0, createdAt: "2026-10-20T10:00:00+08:00", updatedAt: "2026-10-20T10:00:01+08:00" } })
} })
const origin = `http://127.0.0.1:${server.port}`
writeFileSync(join(process.env.SEAL_USE_ENTERPRISES_DIR!, "export-fixture.json"), JSON.stringify({
...corp, source: { type: "seal", token: "fixture-token", sealUrl: origin, staffId: "fixture" }, seal: { url: origin }
}))
const lines: string[] = []
let settled = false
const pending = runCli(["simulation", "wait", "Bearer fixture-sensitive", "--corp", corp.id], {
onStderr: text => lines.push(text)
}).then(result => { settled = true; return result })
try {
await received.promise
expect(settled).toBe(false)
expect(lines.join("")).toContain("正在轮询等待结果")
expect(lines.join("")).not.toContain("fixture-sensitive")
release.resolve()
const result = await pending
expect(result.exitCode).toBe(0)
expect(JSON.parse(result.stdout)).toMatchObject({ completed: true })
expect(lines.join("")).toBe(result.stderr)
} finally { release.resolve(); await pending; server.stop(true) }
})
test("detached worker survives its submitting CLI and a bounded wait, then exports a valid workbook", async () => {
const gate = Promise.withResolvers<void>()
let taskId: string | undefined
const server = Bun.serve({
hostname: "127.0.0.1", port: 0,
fetch: async request => {
const url = new URL(request.url)
if (url.pathname === "/api/v1/rules") return Response.json({ rules: [] })
if (url.pathname === "/api/v1/approvals") {
await gate.promise
return Response.json({ data: { total: 1, records: [{
id: "run-fixture", sourceDocumentSN: "B-FIXTURE", status: "completed", taskMode: "assisted",
createdAt: Date.parse("2026-10-20T10:00:00+08:00"), result: { decision: "APPROVE", rulesResult: [] }
}] } })
}
return Response.json({ error: "unexpected request" }, { status: 404 })
}
})
const origin = `http://127.0.0.1:${server.port}`
writeFileSync(join(process.env.SEAL_USE_ENTERPRISES_DIR!, "export-fixture.json"), JSON.stringify({
...corp, source: { type: "seal", token: "fixture-token", sealUrl: origin, staffId: "fixture" }, seal: { url: origin }
}))
const output = join(dir, "audit.xlsx")
try {
const entry = fileURLToPath(new URL("../../cli.ts", import.meta.url))
const child = Bun.spawn([process.execPath, entry, "approval-runs", "export", "--corp", corp.id,
"--start-date", "2026-10-19", "--end-date", "2026-10-25", "--out", output, "--no-wait"],
{ stdout: "pipe", stderr: "pipe", env: { ...process.env } })
const [stdout, stderr, exit] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited])
expect(exit).toBe(0)
const ticket = JSON.parse(stdout)
taskId = ticket.taskId
expect(taskId).toBeString()
expect(stderr).toContain("[导出配置]")
expect(existsSync(output)).toBe(false)
const pending = await runCli(["approval-runs", "export", "wait", taskId!, "--timeout", "20ms", "--poll-interval", "5ms"])
expect(pending.exitCode).toBe(0)
expect(JSON.parse(pending.stdout)).toMatchObject({ completed: false, timedOut: true })
const watcher = Bun.spawn([process.execPath, entry, "approval-runs", "export", "wait", taskId!, "--timeout", "10m"],
{ stdout: "pipe", stderr: "pipe", env: { ...process.env } })
const reader = watcher.stderr.getReader()
try { await reader.read() } finally { reader.releaseLock() }
watcher.kill("SIGTERM")
await watcher.exited
expect(getExportTask(taskId!).status).not.toBe("failed")
const again = await runCli(["approval-runs", "export", "--corp", corp.id,
"--start-date", "2026-10-19", "--end-date", "2026-10-25", "--out", output, "--no-wait"])
expect(JSON.parse(again.stdout)).toMatchObject({ taskId, reused: true })
gate.resolve()
const final = await waitForExportTask(taskId!, { timeoutMs: 5000, pollIntervalMs: 20 })
expect(final.task.status).toBe("completed")
expect(final.task.result).toMatchObject({ filePath: output, recordCount: 1, excludedDeletedCount: 0, partial: false })
const workbook = new ExcelJS.Workbook()
await workbook.xlsx.readFile(output)
expect(workbook.worksheets[0]!.rowCount).toBe(2)
expect(readFileSync(join(dir, "tasks", `${taskId}.log`), "utf8")).toContain("Excel 文件已成功落地")
} finally {
gate.resolve()
if (taskId) {
const { task } = await waitForExportTask(taskId, { timeoutMs: 5000, pollIntervalMs: 20 })
if (task.status === "running" && task.pid) process.kill(task.pid, "SIGTERM")
getExportTask(taskId)
}
server.stop(true)
}
}, 15000)
})
+158
View File
@@ -0,0 +1,158 @@
import { appendFileSync, rmSync, writeFileSync } from "node:fs"
import { extname, join, resolve } from "node:path"
import { durationSeconds, tokenizeDuration } from "../../core/duration.js"
import { classifyCliError, CliError, usageError } from "../../core/errors.js"
import { formatBeijingIso } from "../../core/config/timestamps.js"
import { resolveDefaultLauncher } from "../../core/runtime.js"
import { createSealClient } from "../../core/http/factory.js"
import { exportApprovalRunsToExcel, normalizeManualApprovalStatus, resolveExportDateRange } from "../../domains/seal/approval-runs/export.js"
import {
exportTaskOptionsSchema, exportTasksDir, getExportTask, listExportTasks,
presentExportTask, readExportTask, startExportTask, waitForExportTask, writeExportTask,
type ExportTaskOptions
} from "../../domains/seal/approval-runs/export-task.js"
import { selectCorp } from "../helpers.js"
import { booleanOption, dryRunOption, numberOption, stringOption } from "../parser.js"
import { formatConsoleOutput, printJson, redactSensitiveText } from "../printer.js"
import type { CliRuntime, ParsedArgs } from "../types.js"
import { approvalRunsExportOptions } from "./approval-runs.js"
import type { CorpConfig } from "../../core/config/types.js"
export function resolveExportOptions(args: ParsedArgs, corp: CorpConfig): ExportTaskOptions {
const raw = approvalRunsExportOptions(args)
for (const [positive, negative] of [["with-flow", "no-flow"], ["exclude-deleted", "include-deleted"], ["wait", "no-wait"]]) {
const a = booleanOption(args.options[positive!])
const b = booleanOption(args.options[negative!])
if (a !== undefined && b !== undefined && a === b) throw usageError(`Conflicting options: --${positive} / --${negative}`)
}
if (raw.withFlow && corp.source.type !== "hose") throw usageError("--with-flow requires a Hose enterprise")
if (raw.excludeDeleted && !raw.withFlow) throw usageError("--exclude-deleted requires --with-flow")
if (raw.taskMode && !["assisted", "automatic", "simulation"].includes(raw.taskMode)) throw usageError("Invalid --task-mode: use assisted, automatic or simulation")
const sns = raw.sns?.length ? [...new Set(raw.sns)].sort() : undefined
const dateRange = resolveExportDateRange({ startDate: raw.startDate, endDate: raw.endDate, force: raw.force, silent: true })
const datesSpecified = Boolean(raw.startDate || raw.endDate) || !sns
let outputFile = raw.outputFile ? resolve(raw.outputFile) : undefined
if (outputFile && extname(outputFile) && extname(outputFile).toLowerCase() !== ".xlsx") throw usageError("--out requires an .xlsx file")
if (outputFile && !extname(outputFile)) outputFile += ".xlsx"
const resolved = exportTaskOptionsSchema.safeParse({
startDate: datesSpecified ? dateRange.startDateStr : undefined,
endDate: datesSpecified ? dateRange.endDateStr : undefined,
limit: raw.limit ?? 100000, status: raw.status,
manualApprovalStatus: normalizeManualApprovalStatus(raw.manualApprovalStatus),
includeCompletedOnly: raw.includeCompletedOnly ?? false,
outputFile, toDownloads: raw.toDownloads ?? !outputFile,
force: raw.force ?? false, withFlow: raw.withFlow ?? false,
flowConcurrency: raw.flowConcurrency ?? 3, excludeDeleted: raw.excludeDeleted ?? false,
taskMode: raw.taskMode, sourceSystem: raw.sourceSystem, sns,
includeSimulation: raw.taskMode === "simulation" || (raw.includeSimulation ?? corp.environment === "test")
})
if (!resolved.success) throw usageError(`Invalid export options: ${resolved.error.issues.map(issue => `${issue.path.join(".")}: ${issue.message}`).join("; ")}`)
return resolved.data
}
function durationOption(args: ParsedArgs, key: string, fallback: string): number {
const value = stringOption(args.options[key]) ?? (key === "poll-interval" ? stringOption(args.options.pollInterval) : undefined) ?? fallback
const token = tokenizeDuration(value)
const ms = token ? durationSeconds(token, "s") * 1000 : NaN
if (!Number.isFinite(ms) || ms <= 0 || ms > 2147483647) throw usageError(`Invalid --${key}: use a positive duration such as 30s or 10m`)
return Math.ceil(ms)
}
async function runExportWorker(id: string) {
const task = readExportTask(id)
if (task.status === "completed" || task.status === "failed") return
const claim = join(exportTasksDir(), `${id}.worker`)
try { writeFileSync(claim, String(process.pid), { flag: "wx", mode: 0o600 }) } catch { return }
const originalError = console.error
console.error = (...values: unknown[]) => {
appendFileSync(join(exportTasksDir(), `${id}.log`), `${redactSensitiveText(formatConsoleOutput(values))}\n`, { mode: 0o600 })
originalError(...values)
}
const save = () => { task.updatedAt = formatBeijingIso(); writeExportTask(task) }
task.status = "running"
task.pid = process.pid
task.progress = { phase: "auth", processed: 0, total: null }
save()
const heartbeat = setInterval(save, 5000)
heartbeat.unref()
try {
const corp = selectCorp(task.corpId)
const client = await createSealClient(corp)
const result = await exportApprovalRunsToExcel(client, corp, {
...task.options, outputTag: task.id.slice(0, 8), onProgress: progress => { task.progress = progress; save() }
})
task.result = { ...result }
task.status = "completed"
} catch (error) {
task.status = "failed"
task.error = redactSensitiveText(error instanceof Error ? error.message : String(error))
task.exitCode = classifyCliError(error).exitCode
console.error(task.error)
} finally {
clearInterval(heartbeat)
save()
console.error = originalError
rmSync(claim, { force: true })
}
}
export async function handleApprovalRunsExportCommand(args: ParsedArgs, runtime: CliRuntime) {
const action = args.command[2]
if (args.command[1] === "export-worker") {
if (!action) throw usageError("Missing export worker task ID")
await runExportWorker(action)
return
}
if (action === "list") {
const limit = numberOption(args.options.limit) ?? 20
if (!Number.isInteger(limit) || limit < 1 || limit > 1000) throw usageError("--limit must be an integer in 1..1000")
const selector = stringOption(args.options.corp)
const tasks = listExportTasks(selector ? selectCorp(selector).id : undefined)
printJson({ count: tasks.length, tasks: tasks.slice(0, limit).map(task => presentExportTask(task)) })
return
}
if (action === "status" || action === "wait") {
const id = args.command[3]
if (!id) throw usageError(`Usage: seal-use approval-runs export ${action} <taskId>`)
const selector = stringOption(args.options.corp)
if (selector && getExportTask(id).corpId !== selectCorp(selector).id) throw usageError("Export task belongs to a different enterprise")
if (action === "status") { printJson(presentExportTask(getExportTask(id))); return }
const { task, timedOut } = await waitForExportTask(id, {
timeoutMs: durationOption(args, "timeout", "10m"),
pollIntervalMs: durationOption(args, "poll-interval", "2s"),
onChange: task => console.error(`[导出进度] ${task.status} / ${task.progress.phase}: ${task.progress.processed}/${task.progress.total ?? "待确定"}; 最近更新 ${task.updatedAt}`)
})
printJson(presentExportTask(task, timedOut))
if (task.status === "failed") throw new CliError(task.error ?? "Export failed", task.exitCode ?? 1)
return
}
if (action) throw usageError(`Unknown approval-runs export command: ${action}`)
const corp = selectCorp(stringOption(args.options.corp))
const options = resolveExportOptions(args, corp)
const noWait = booleanOption(args.options["no-wait"]) ?? booleanOption(args.options.noWait) ?? false
const boundedWait = booleanOption(args.options.wait) === true || args.options.timeout !== undefined
const timeoutMs = boundedWait ? durationOption(args, "timeout", "10m") : Infinity
const pollIntervalMs = durationOption(args, "poll-interval", "2s")
if (noWait && boundedWait) throw usageError("--no-wait cannot be combined with --wait or --timeout")
if (dryRunOption(args)) { printJson({ preview: true, corpName: corp.name, options }); return }
console.error(`[导出配置] 企业: ${corp.name}; 北京时间: ${options.startDate ?? "按单号、不限日期"} 至 ${options.endDate ?? "不限日期"}; 人工审批流: ${options.withFlow ? "开启" : "关闭"}; 未找到单据: ${options.excludeDeleted ? "排除(需开启审批流)" : "保留并标记"}; 模拟任务: ${options.includeSimulation ? "包含" : "排除"}; 仅AI已完成: ${options.includeCompletedOnly}; AI状态: ${options.status ?? "不限"}; 人工状态: ${options.manualApprovalStatus?.join(",") ?? "不限"}; 模式: ${options.taskMode ?? "不限"}; 来源: ${options.sourceSystem ?? "企业业务来源"}; 上限: ${options.limit}; 审批流并发: ${options.flowConcurrency}; 输出: ${options.outputFile ?? "下载目录"}`)
const { task: created, reused } = startExportTask({
corpId: corp.id, corpName: corp.name, options,
launcher: runtime.launcher ?? resolveDefaultLauncher(runtime.entryFile)
})
console.error(`[导出任务] ${created.id}${reused ? "(复用在途任务)" : ""}`)
console.error(`👉 Next action: seal-use approval-runs export wait ${created.id} --timeout 30s`)
if (noWait) { printJson({ ...presentExportTask(created), reused }); return }
const { task, timedOut } = await waitForExportTask(created.id, {
timeoutMs, pollIntervalMs,
onChange: task => console.error(`[导出进度] ${task.status} / ${task.progress.phase}: ${task.progress.processed}/${task.progress.total ?? "待确定"}; 最近更新 ${task.updatedAt}`)
})
if (task.status === "completed") {
printJson({ ...task.result, taskId: task.id, reused })
console.error(`导出完成: ${String(task.result?.filePath)}`)
if (task.result?.partial) console.error(`⚠️ 部分数据补取失败,请检查结果中的 warnings 和任务日志。`)
} else {
printJson({ ...presentExportTask(task, timedOut), reused })
if (task.status === "failed") throw new CliError(task.error ?? "Export failed", task.exitCode ?? 1)
}
}
+68 -69
View File
@@ -2,7 +2,7 @@ import { usageError } from "../../core/errors.js";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import * as api from "../../domains/seal/api.js";
import { exportApprovalRunsToExcel, normalizeTimestamp } from "../../domains/seal/approval-runs/export.js";
import { type ApprovalRunsExportOptions, normalizeTimestamp } from "../../domains/seal/approval-runs/export.js";
import {
downloadApprovalRunAttachments,
extractApprovalRunAttachments
@@ -403,73 +403,72 @@ export async function handleApprovalRunsCommand(
return;
}
if (action === "export") {
const rawSn =
stringOption(args.options.sn) ??
stringOption(args.options.sns) ??
stringOption(args.options.sourceDocumentSN);
const snList = rawSn
? rawSn
.split(/[,;\s]+/)
.map((s) => s.trim())
.filter(Boolean)
: undefined;
const result = await exportApprovalRunsToExcel(client, corp, {
sns: snList,
limit: numberOption(args.options.limit),
startDate:
stringOption(args.options["start-date"]) ??
stringOption(args.options.startDate) ??
stringOption(args.options.start) ??
stringOption(args.options.since),
endDate:
stringOption(args.options["end-date"]) ??
stringOption(args.options.endDate) ??
stringOption(args.options.end) ??
stringOption(args.options.until),
status: stringOption(args.options.status),
manualApprovalStatus:
stringOption(args.options["manual-status"]) ??
stringOption(args.options.manualStatus) ??
stringOption(args.options["manual-approval-status"]) ??
stringOption(args.options.manualApprovalStatus),
includeCompletedOnly:
booleanOption(args.options["completed-only"]) ?? booleanOption(args.options.completedOnly),
outputFile:
stringOption(args.options.out) ??
stringOption(args.options["output-file"]) ??
stringOption(args.options.output) ??
stringOption(args.options.outputFile) ??
stringOption(args.options.file),
toDownloads:
booleanOption(args.options["to-downloads"]) ??
booleanOption(args.options.downloads) ??
booleanOption(args.options.download),
force: booleanOption(args.options.force),
withFlow:
booleanOption(args.options["with-flow"]) ??
(booleanOption(args.options["no-flow"]) ? false : undefined),
flowConcurrency:
numberOption(args.options["flow-concurrency"]) ??
numberOption(args.options.concurrency),
excludeDeleted:
booleanOption(args.options["exclude-deleted"]) ??
(booleanOption(args.options["include-deleted"]) ? false : undefined),
taskMode: stringOption(args.options.taskMode) ?? stringOption(args.options["task-mode"]),
sourceSystem: stringOption(args.options.sourceSystem) ?? stringOption(args.options["source-system"]),
includeSimulation:
booleanOption(args.options["include-simulation"]) ??
booleanOption(args.options.includeSimulation) ??
booleanOption(args.options["simulation"])
});
console.error(`👉 查看导出文件: open "${result.filePath}"`);
if (!args.options["with-flow"] && corp.source.type === "hose") {
console.error(`👉 提示: 追加 --with-flow 可额外拉取合思原生审批流,输出 E人工行为 / E人工意见。`);
}
printJson(result, outputOptions(args.options));
return;
}
throw usageError(`Unknown approval-runs command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
export function approvalRunsExportOptions(args: ParsedArgs): ApprovalRunsExportOptions {
const inverseBoolean = (value: string | boolean | undefined) => {
const parsed = booleanOption(value);
return parsed === undefined ? undefined : !parsed;
};
const rawSn =
stringOption(args.options.sn) ??
stringOption(args.options.sns) ??
stringOption(args.options.sourceDocumentSN);
const snList = rawSn
? rawSn
.split(/[,;\s]+/)
.map((s) => s.trim())
.filter(Boolean)
: undefined;
return {
sns: snList,
limit: numberOption(args.options.limit),
startDate:
stringOption(args.options["start-date"]) ??
stringOption(args.options.startDate) ??
stringOption(args.options.start) ??
stringOption(args.options.since),
endDate:
stringOption(args.options["end-date"]) ??
stringOption(args.options.endDate) ??
stringOption(args.options.end) ??
stringOption(args.options.until),
status: stringOption(args.options.status),
manualApprovalStatus:
stringOption(args.options["manual-status"]) ??
stringOption(args.options.manualStatus) ??
stringOption(args.options["manual-approval-status"]) ??
stringOption(args.options.manualApprovalStatus),
includeCompletedOnly:
booleanOption(args.options["completed-only"]) ?? booleanOption(args.options.completedOnly),
outputFile:
stringOption(args.options.out) ??
stringOption(args.options["output-file"]) ??
stringOption(args.options.output) ??
stringOption(args.options.outputFile) ??
stringOption(args.options.file),
toDownloads:
booleanOption(args.options["to-downloads"]) ??
booleanOption(args.options.toDownloads) ??
booleanOption(args.options.downloads) ??
booleanOption(args.options.download),
force: booleanOption(args.options.force),
withFlow:
booleanOption(args.options["with-flow"]) ??
inverseBoolean(args.options["no-flow"]),
flowConcurrency:
numberOption(args.options["flow-concurrency"]) ??
numberOption(args.options.concurrency),
excludeDeleted:
booleanOption(args.options["exclude-deleted"]) ??
inverseBoolean(args.options["include-deleted"]),
taskMode: stringOption(args.options.taskMode) ?? stringOption(args.options["task-mode"]),
sourceSystem: stringOption(args.options.sourceSystem) ?? stringOption(args.options["source-system"]),
includeSimulation:
booleanOption(args.options["include-simulation"]) ??
booleanOption(args.options.includeSimulation) ??
booleanOption(args.options["simulation"])
};
}
+3 -3
View File
@@ -5,18 +5,15 @@ import {
saveGlobalConfig,
updateCorpConfig
} from "../../../core/config/loader.js";
import { filterCorpsFuzzy } from "../../../core/corp-search/rank.js";
import {
getRecentCorpUsageScores,
sortCorpsByUsageAndRecency
} from "../../../core/stats/usage-tracker.js";
import type { CorpEnvironment } from "../../../core/config/types.js";
import { selectCorp } from "../../helpers.js";
import { confirmationRequired, usageError } from "../../../core/errors.js";
import { booleanOption, dryRunOption, numberOption, stringOption } from "../../parser.js";
import { printJson } from "../../printer.js";
import type { ParsedArgs } from "../../types.js";
import { formatSafeSourceDetail, resolveCorpSealUrl } from "./shared.js";
export async function handleCorpOverview(
action: string | undefined,
@@ -51,6 +48,7 @@ export async function handleCorpOverview(
filtered = filtered.filter((item) => (item.environment ?? "production").toLowerCase() === envFilter);
}
if (rawQuery) {
const { filterCorpsFuzzy } = await import("../../../core/corp-search/rank.js");
// Equal-relevance results are ordered by recent usage so frequent corps
// surface on ties without ever beating a better match.
const usageScores = getRecentCorpUsageScores(filtered.map((item) => item.id));
@@ -101,7 +99,9 @@ export async function handleCorpOverview(
return true;
}
const { selectCorp } = await import("../../helpers.js");
if (action === "get" || action === "show") {
const { formatSafeSourceDetail, resolveCorpSealUrl } = await import("./shared.js");
const targetCorpId = maybeName ?? stringOption(args.options.corp);
if (!targetCorpId) {
throw usageError("Usage: seal-use corps get <corpId>");
+4 -3
View File
@@ -1,5 +1,4 @@
import { usageError } from "../../core/errors.js";
import { existsSync } from "node:fs";
import { join } from "node:path";
import {
getAllLinkableHostsStatus,
@@ -15,6 +14,8 @@ import {
import { booleanOption, stringOption } from "../parser.js";
import { printJson } from "../printer.js";
import type { ParsedArgs } from "../types.js";
import { getSkillVersionStatus } from "../../core/skill-version.js";
import { VERSION } from "../../version.js";
export function handleSkillCommand(action: string | undefined, maybeName: string | undefined, args: ParsedArgs) {
if (action === "dump" || action === "cat" || action === "show") {
@@ -55,11 +56,11 @@ export function handleSkillCommand(action: string | undefined, maybeName: string
printJson({
global: {
dir: globalDir,
installed: existsSync(join(globalDir, "SKILL.md"))
...getSkillVersionStatus(VERSION, join(globalDir, "SKILL.md"))
},
local: {
dir: localDir,
installed: existsSync(join(localDir, "SKILL.md"))
...getSkillVersionStatus(VERSION, join(localDir, "SKILL.md"))
},
antigravity,
hosts
+24 -7
View File
@@ -491,19 +491,36 @@ export const HELP_REGISTRY: AreaHelp[] = [
},
{
name: "export",
summary: "Export approval run audit records to Excel workbook. Add --with-flow to include E人工行为 / E人工意见 columns (requires Hose Open API; adds ~30s for large batches).",
usage: ["seal-use approval-runs export [--sn <SN1,SN2>] [--start-date <YYYY-MM-DD|ms>] [--end-date <YYYY-MM-DD|ms>] [--force] [--status <status>] [--manual-status <status>] [--completed-only] [--limit <n>] [--downloads] [--with-flow] [--out <file>] [--corp <corpId>]"],
summary: "Export approval run audit records to Excel. Background tasks support status/wait; missing Hose documents are retained by default.",
usage: [
"seal-use approval-runs export [--sn <SN1,SN2>] [--start-date <YYYY-MM-DD|ms>] [--end-date <YYYY-MM-DD|ms>] [--force] [--status <status>] [--manual-status <status>] [--completed-only] [--limit <n>] [--downloads] [--with-flow] [--include-deleted|--exclude-deleted] [--include-simulation] [--task-mode <mode>] [--source-system <source>] [--flow-concurrency <n>] [--no-wait|--wait] [--timeout 10m] [--poll-interval 2s] [--dry-run] [--out <file>] [--corp <corpId>]",
"seal-use approval-runs export status <taskId> [--corp <corpId>]",
"seal-use approval-runs export wait <taskId> [--timeout 10m] [--poll-interval 2s] [--corp <corpId>]",
"seal-use approval-runs export list [--limit <n>] [--corp <corpId>]"
],
options: [
{ flag: "--sn, --sns <SNs>", description: "Target specific document SNs (comma-separated, e.g. B26002307,B26002144); fast indexed search bypassing full pagination" },
{ flag: "--with-flow", description: "Enrich export with Hose human actions and opinions in E人工行为 / E人工意见 columns (rejection 2-B, mid-flow modifications, action emojis)" },
{ flag: "--sn <SNs>", description: "Target document SNs (comma-separated); without dates, search their history" },
{ flag: "--with-flow", description: "Fetch Hose native human actions/opinions into E人工行为 / E人工意见 (default off). Additional requests scale with unique documents; large exports can take minutes" },
{ flag: "--no-flow", description: "Explicitly disable additional Hose flow requests; existing Seal human result columns remain" },
{ flag: "--include-deleted", description: "Retain and mark documents not found in Hose (default); not-found does not prove deletion" },
{ flag: "--exclude-deleted", description: "Exclude records whose native Hose flow is not found; requires --with-flow" },
{ flag: "--include-simulation", description: "Include simulation runs (default off in production, on in test enterprises)" },
{ flag: "--task-mode <mode>", description: "Filter assisted, automatic or simulation; simulation explicitly includes test runs" },
{ flag: "--source-system <source>", description: "Filter source system; Hose exports retain Hose business sources" },
{ flag: "--flow-concurrency <n>", description: "Native Hose flow request concurrency, integer 1..5 (default 3)" },
{ flag: "--start-date <date>", description: "Filter records by start date (YYYY-MM-DD or ms timestamp)" },
{ flag: "--end-date <date>", description: "Filter records by end date (YYYY-MM-DD or ms timestamp)" },
{ flag: "--force", description: "Force export when time range exceeds 180 days" },
{ flag: "--status <status>", description: "Filter by system status (e.g. completed, processing)" },
{ flag: "--manual-status <status>", description: "Filter by manual approval status (e.g. APPROVED, TERMINATED)" },
{ flag: "--completed-only", description: "Only export completed approval runs" },
{ flag: "--limit <n>", description: "Maximum number of records to export" },
{ flag: "--downloads", description: "Save exported workbook directly to user's ~/Downloads directory" },
{ flag: "--completed-only", description: "Only completed AI runs; does not require human approval to have finished (default no status restriction)" },
{ flag: "--limit <n>", description: "Maximum selected approval runs, integer 1..100000 (default 100000 safety cap)" },
{ flag: "--downloads", description: "Save workbook in ~/Downloads (default when --out is omitted)" },
{ flag: "--no-wait", description: "Immediately return a local task ticket; worker continues independently. Matching in-flight tasks are reused" },
{ flag: "--wait", description: "Wait with a time limit (default 10m); without waiting flags the existing blocking behavior is retained" },
{ flag: "--timeout <duration>", description: "Bound waiting; timeout returns completed:false/timedOut:true and does not stop the worker" },
{ flag: "--poll-interval <duration>", description: "Local status polling interval (default 2s)" },
{ flag: "--dry-run", description: "Preview effective export options without network requests, task creation or output files" },
{ flag: "--out <file>", description: "Custom output file path" }
]
},
+22 -3
View File
@@ -15,6 +15,7 @@ import {
} from "./parser.js";
import { extractHelpRequest } from "./help.js";
import { isNewerVersion } from "../core/semver.js";
import { getSkillVersionStatus } from "../core/skill-version.js";
import {
formatConsoleOutput,
joinOutput,
@@ -48,6 +49,11 @@ const LOCAL_COMMANDS: Record<string, LocalCommand> = {
changelog: dispatchUpdate,
corps: async (args) => {
const action = args.command[1];
// Local discovery must not initialize onboarding, sync or the capability registry.
if (!action || ["list", "search", "find"].includes(action)) {
await (await import("./commands/corps/overview.js")).handleCorpOverview(action, args.command[2], args);
return;
}
if (action === "regression" || action === "test-regression") {
await (await import("./commands/test.js")).handleTestCommand("regression", args.command[2], args);
return;
@@ -130,7 +136,9 @@ async function runCliOnce(argv: string[], options: CliRunOptions): Promise<CliRe
stdout.push(formatConsoleOutput(values));
};
console.error = (...values: unknown[]) => {
stderr.push(formatConsoleOutput(values));
const line = redactSensitiveText(formatConsoleOutput(values));
stderr.push(line);
options.onStderr?.(`${line}\n`);
};
try {
@@ -144,9 +152,9 @@ async function runCliOnce(argv: string[], options: CliRunOptions): Promise<CliRe
} catch (error) {
const message = redactSensitiveText(error instanceof Error ? error.message : String(error));
const classification = classifyCliError(error);
stderr.push(message);
console.error(message);
if (classification.nextAction && !message.includes("Next action:")) {
stderr.push(`👉 Next action: ${classification.nextAction}`);
console.error(`👉 Next action: ${classification.nextAction}`);
}
return {
stdout: joinOutput(stdout),
@@ -218,6 +226,7 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
const payload = {
...VERSION_INFO,
skill: getSkillVersionStatus(VERSION_INFO.version),
...(cache?.latestVersion
? {
latestVersion: cache.latestVersion,
@@ -231,6 +240,10 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
console.error(`💡 发现新版本可用: v${VERSION_INFO.version} -> v${cache.latestVersion}`);
console.error(`👉 Next action: seal-use update\n`);
}
if (["skill_newer", "cli_newer", "unknown"].includes(payload.skill.status)) {
console.error(`技能版本与 CLI 需要核对: CLI ${payload.skill.cliVersion}, Skill ${payload.skill.installedVersion ?? "无法识别"}`);
console.error(`👉 Next action: ${payload.skill.nextAction}`);
}
printJson(payload);
@@ -315,6 +328,12 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
// Local task observation and previews must not authenticate or contact a tenant.
if (area === "approval-runs" && (action === "export" || action === "export-worker")) {
await (await import("./commands/approval-runs-export.js")).handleApprovalRunsExportCommand(args, runtime);
return;
}
const corp = (await import("./helpers.js")).selectCorp(stringOption(args.options.corp));
const corpCommand = CORP_COMMANDS[area];
+2
View File
@@ -22,6 +22,8 @@ export type CliRunOptions = {
appRoot?: string;
entryFile?: string;
launcher?: LauncherConfig;
/** Receives redacted diagnostics immediately; stdout remains a single payload. */
onStderr?: (text: string) => void;
};
export type CliRuntime = {
+7 -4
View File
@@ -5,7 +5,7 @@ import { PRIMARY_LINTERS_DIR, OFFICIAL_LINTERS_DIR } from "../paths.js";
import { VERSION } from "../../version.js";
import { getLastCorpConfigLoadIssues, getLastGlobalConfigIssue, loadCorpConfigs, loadGlobalConfig } from "../config/loader.js";
import { formatBeijingIso } from "../config/timestamps.js";
import { getDefaultGlobalSkillDir } from "../embedded-skill.js";
import { getDefaultGlobalSkillDir, getSkillVersionStatus } from "../skill-version.js";
import { resolveUsageFilePath } from "../stats/usage-tracker.js";
import {
EMBEDDED_DIRECTORY_SPECS,
@@ -38,6 +38,7 @@ export interface DoctorDiagnosis {
platform: string;
engine: string;
};
skill: ReturnType<typeof getSkillVersionStatus>;
directories: Record<string, DirectoryHealth>;
enterprises: {
total: number;
@@ -273,19 +274,20 @@ export function diagnoseSystem(): DoctorDiagnosis {
}
// Check 4: Agent Skill
const skill = getSkillVersionStatus(VERSION);
if (directories.agentSkillDir?.exists) {
checks.push({
id: "agent_skill",
title: "AI Agent 技能",
status: "ok",
message: `已就绪于 ${agentSkillDir}`
status: skill.status === "matched" ? "ok" : "warn",
message: skill.status === "matched" ? `已就绪于 ${agentSkillDir} (版本 ${skill.installedVersion})` : `CLI ${VERSION}; Skill ${skill.installedVersion ?? "无法识别版本"}; ${skill.nextAction}`
});
} else {
checks.push({
id: "agent_skill",
title: "AI Agent 技能",
status: "warn",
message: `未在 ${agentSkillDir} 检测到技能,可运行 'seal-use skill sync' 安装`
message: `未在 ${agentSkillDir} 检测到技能,可运行 'seal-use skill install' 安装`
});
}
@@ -360,6 +362,7 @@ export function diagnoseSystem(): DoctorDiagnosis {
platform: `${process.platform} (${process.arch})`,
engine
},
skill,
directories,
enterprises: {
total: corps.length,
+35 -32
View File
@@ -10,44 +10,46 @@ import file6 from "../../skills/seal-use/assets/hose-open-platform-credentials.p
import file7 from "../../skills/seal-use/assets/hose-open-platform-product-config.png" with { type: "file" };
import file8 from "../../skills/seal-use/references/approval-attachment-trace.md" with { type: "text" };
import file9 from "../../skills/seal-use/references/approval-bad-cases.md" with { type: "text" };
import file10 from "../../skills/seal-use/references/approval-run-lightweight.md" with { type: "text" };
import file11 from "../../skills/seal-use/references/cli.md" with { type: "text" };
import file12 from "../../skills/seal-use/references/customer-feedback-rule-remediation.md" with { type: "text" };
import file13 from "../../skills/seal-use/references/documents.md" with { type: "text" };
import file14 from "../../skills/seal-use/references/enterprise-onboarding.md" with { type: "text" };
import file15 from "../../skills/seal-use/references/expense-data.md" with { type: "text" };
import file16 from "../../skills/seal-use/references/first-time-user.md" with { type: "text" };
import file17 from "../../skills/seal-use/references/hose-enterprise-auth.md" with { type: "text" };
import file18 from "../../skills/seal-use/references/hose-enterprise-deploy.md" with { type: "text" };
import file19 from "../../skills/seal-use/references/hose-enterprise-init.md" with { type: "text" };
import file20 from "../../skills/seal-use/references/langfuse-trace.md" with { type: "text" };
import file21 from "../../skills/seal-use/references/report-templates.md" with { type: "text" };
import file22 from "../../skills/seal-use/references/rule-lightweight.md" with { type: "text" };
import file23 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" };
import file24 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
import file25 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
import file10 from "../../skills/seal-use/references/approval-run-export.md" with { type: "text" };
import file11 from "../../skills/seal-use/references/approval-run-lightweight.md" with { type: "text" };
import file12 from "../../skills/seal-use/references/cli.md" with { type: "text" };
import file13 from "../../skills/seal-use/references/customer-feedback-rule-remediation.md" with { type: "text" };
import file14 from "../../skills/seal-use/references/documents.md" with { type: "text" };
import file15 from "../../skills/seal-use/references/enterprise-onboarding.md" with { type: "text" };
import file16 from "../../skills/seal-use/references/expense-data.md" with { type: "text" };
import file17 from "../../skills/seal-use/references/first-time-user.md" with { type: "text" };
import file18 from "../../skills/seal-use/references/hose-enterprise-auth.md" with { type: "text" };
import file19 from "../../skills/seal-use/references/hose-enterprise-deploy.md" with { type: "text" };
import file20 from "../../skills/seal-use/references/hose-enterprise-init.md" with { type: "text" };
import file21 from "../../skills/seal-use/references/langfuse-trace.md" with { type: "text" };
import file22 from "../../skills/seal-use/references/report-templates.md" with { type: "text" };
import file23 from "../../skills/seal-use/references/rule-lightweight.md" with { type: "text" };
import file24 from "../../skills/seal-use/references/rule-lint.md" with { type: "text" };
import file25 from "../../skills/seal-use/references/staging-simulation-workflow.md" with { type: "text" };
import file26 from "../../skills/seal-use/references/webhook-resource-pack.md" with { type: "text" };
export const EMBEDDED_SKILL_TEXT_FILES: Record<string, string> = {
"SKILL.md": file0,
"agents/openai.yaml": file1,
"references/approval-attachment-trace.md": file8,
"references/approval-bad-cases.md": file9,
"references/approval-run-lightweight.md": file10,
"references/cli.md": file11,
"references/customer-feedback-rule-remediation.md": file12,
"references/documents.md": file13,
"references/enterprise-onboarding.md": file14,
"references/expense-data.md": file15,
"references/first-time-user.md": file16,
"references/hose-enterprise-auth.md": file17,
"references/hose-enterprise-deploy.md": file18,
"references/hose-enterprise-init.md": file19,
"references/langfuse-trace.md": file20,
"references/report-templates.md": file21,
"references/rule-lightweight.md": file22,
"references/rule-lint.md": file23,
"references/staging-simulation-workflow.md": file24,
"references/webhook-resource-pack.md": file25,
"references/approval-run-export.md": file10,
"references/approval-run-lightweight.md": file11,
"references/cli.md": file12,
"references/customer-feedback-rule-remediation.md": file13,
"references/documents.md": file14,
"references/enterprise-onboarding.md": file15,
"references/expense-data.md": file16,
"references/first-time-user.md": file17,
"references/hose-enterprise-auth.md": file18,
"references/hose-enterprise-deploy.md": file19,
"references/hose-enterprise-init.md": file20,
"references/langfuse-trace.md": file21,
"references/report-templates.md": file22,
"references/rule-lightweight.md": file23,
"references/rule-lint.md": file24,
"references/staging-simulation-workflow.md": file25,
"references/webhook-resource-pack.md": file26,
};
export const EMBEDDED_SKILL_ASSET_PATHS: Record<string, string> = {
@@ -70,6 +72,7 @@ export const EMBEDDED_SKILL_ALL_PATHS = [
"assets/hose-open-platform-product-config.png",
"references/approval-attachment-trace.md",
"references/approval-bad-cases.md",
"references/approval-run-export.md",
"references/approval-run-lightweight.md",
"references/cli.md",
"references/customer-feedback-rule-remediation.md",
+4 -15
View File
@@ -1,6 +1,8 @@
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { getDefaultGlobalSkillDir, parseSkillVersion } from "./skill-version.js";
export { getDefaultGlobalSkillDir } from "./skill-version.js";
import {
EMBEDDED_SKILL_ASSET_PATHS,
@@ -33,27 +35,14 @@ export function getSkillContent(): string {
* success either way, so the version is the only signal that says *which generation* of the
* document actually landed on disk.
*/
export function parseSkillVersion(markdown: string): string | undefined {
return markdown.match(/^\s*version:\s*(\S+)\s*$/m)?.[1];
}
export { parseSkillVersion } from "./skill-version.js";
/** Reads the version of an installed SKILL.md, or `undefined` when it is missing or unreadable. */
export function readInstalledSkillVersion(
skillFile: string = join(getDefaultGlobalSkillDir(), "SKILL.md")
): string | undefined {
try {
return parseSkillVersion(readFileSync(skillFile, "utf8"));
} catch {
return undefined;
}
}
export { readInstalledSkillVersion } from "./skill-version.js";
/** The version of the skill compiled into this build, used to assert what an install wrote. */
export const EMBEDDED_SKILL_VERSION = parseSkillVersion(getSkillContent());
export function getDefaultGlobalSkillDir(): string {
return join(homedir(), ".agents", "skills", "seal-use");
}
function getLegacyGlobalSkillDir(): string {
return join(homedir(), ".agents", "skills", "seal-home");
+24
View File
@@ -0,0 +1,24 @@
import { describe, expect, test } from "bun:test"
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { getSkillVersionStatus, parseSkillVersion } from "./skill-version.js"
describe("lightweight Skill version inspection", () => {
test("compares release generations without mistaking a development suffix for drift", () => {
const dir = mkdtempSync(join(tmpdir(), "seal-skill-version-"))
const file = join(dir, "SKILL.md")
try {
expect(getSkillVersionStatus("1.2.3", file).status).toBe("missing")
const content = "---\nname: seal-use\nmetadata:\n version: \"1.2.3\"\n---\n"
writeFileSync(file, content)
expect(getSkillVersionStatus("1.2.3-dev.6+abc.dirty", file)).toMatchObject({ status: "matched", installedVersion: "1.2.3", nextAction: null })
expect(getSkillVersionStatus("1.2.2", file)).toMatchObject({ status: "skill_newer", nextAction: "seal-use update" })
expect(getSkillVersionStatus("1.2.4", file)).toMatchObject({ status: "cli_newer", nextAction: "seal-use skill install" })
expect(readFileSync(file, "utf8")).toBe(content)
writeFileSync(file, "# invalid metadata\nversion: 1.2.3\n")
expect(getSkillVersionStatus("1.2.3", file).status).toBe("unknown")
expect(parseSkillVersion("---\r\nmetadata:\r\n version: '2.0.0'\r\n---\r\n")).toBe("2.0.0")
} finally { rmSync(dir, { recursive: true, force: true }) }
})
})
+28
View File
@@ -0,0 +1,28 @@
import { existsSync, readFileSync } from "node:fs"
import { homedir } from "node:os"
import { join } from "node:path"
import { compareSemVer } from "./semver.js"
// Keep local version inspection independent of the embedded Skill asset graph.
export function getDefaultGlobalSkillDir(): string {
return join(homedir(), ".agents", "skills", "seal-use")
}
export function parseSkillVersion(markdown: string): string | undefined {
const frontMatter = markdown.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)?.[1]
return frontMatter?.match(/^\s*version:\s*["']?(\d+\.\d+\.\d+(?:[-+][\w.+-]+)?)["']?\s*$/m)?.[1]
}
export function readInstalledSkillVersion(skillFile = join(getDefaultGlobalSkillDir(), "SKILL.md")): string | undefined {
try { return parseSkillVersion(readFileSync(skillFile, "utf8")) } catch { return undefined }
}
export function getSkillVersionStatus(cliVersion: string, skillFile = join(getDefaultGlobalSkillDir(), "SKILL.md")) {
const installed = existsSync(skillFile)
const installedVersion = readInstalledSkillVersion(skillFile) ?? null
const cliBaseVersion = cliVersion.match(/^v?(\d+\.\d+\.\d+)/)?.[1] ?? cliVersion
const comparison = installedVersion ? compareSemVer(installedVersion, cliBaseVersion) : null
const status = !installed ? "missing" : comparison === null ? "unknown" : comparison > 0 ? "skill_newer" : comparison < 0 ? "cli_newer" : "matched"
const nextAction = status === "skill_newer" ? "seal-use update" : status === "cli_newer" || status === "missing" || status === "unknown" ? "seal-use skill install" : null
return { cliVersion, cliBaseVersion, installedVersion, installed, status, nextAction }
}
@@ -0,0 +1,87 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
import { mkdtempSync, rmSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import ky from "ky"
import ExcelJS from "exceljs"
import { exportApprovalRunsToExcel, type ApprovalRunsExportProgress } from "./export.js"
import type { CorpConfig } from "../../../core/config/types.js"
const oldFetch = globalThis.fetch
const oldTokens = process.env.SEAL_USE_TOKEN_STORE
let dir: string
const runs = [
{ id: "missing-a1", sourceDocumentId: "missing-a", sourceDocumentSN: "SN-SHARED" },
{ id: "missing-a2", sourceDocumentId: "missing-a", sourceDocumentSN: "SN-SHARED" },
{ id: "missing-b1", sourceDocumentId: "missing-b", sourceDocumentSN: "SN-OTHER" },
{ id: "broken1", sourceDocumentId: "broken", sourceDocumentSN: "SN-BROKEN" },
{ id: "good1", sourceDocumentId: "good", sourceDocumentSN: "SN-SHARED" },
{ id: "simulation", sourceDocumentId: "sim", taskMode: "simulation" },
{ id: "other", sourceDocumentId: "other", sourceSystem: "other" }
].map(run => ({
status: "completed", taskMode: "assisted", sourceSystem: "hosecloud",
createdAt: Date.parse("2026-10-20T10:00:00+08:00"),
result: { decision: "APPROVE", rulesResult: [] }, ...run
}))
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "seal-export-observe-"))
process.env.SEAL_USE_TOKEN_STORE = join(dir, "tokens.json")
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const request = new Request(input, init)
const url = new URL(request.url)
if (url.pathname.endsWith("/auth/getAccessToken")) return Response.json({ value: { accessToken: "fixture-open-token" } })
if (url.pathname === "/api/v1/rules") return Response.json({ rules: [] })
if (url.pathname === "/api/v1/approvals") return Response.json({ data: { total: runs.length, records: runs } })
if (url.pathname.endsWith("/flowDetails")) {
const id = url.searchParams.get("flowId")
if (id === "broken") return Response.json({ error: "fixture upstream failure" }, { status: 400 })
return Response.json({ value: id === "good" ? { id, state: "PAID", logs: [] } : null })
}
if (url.pathname.endsWith("/allLogs") || url.pathname.endsWith("/versioned")) return Response.json({ items: [] })
throw new Error(`Unexpected fixture request: ${url.pathname}`)
}) as typeof fetch
})
afterEach(() => {
globalThis.fetch = oldFetch
if (oldTokens === undefined) delete process.env.SEAL_USE_TOKEN_STORE
else process.env.SEAL_USE_TOKEN_STORE = oldTokens
rmSync(dir, { recursive: true, force: true })
})
const corp = {
id: "export-observe-fixture", name: "测试企业", environment: "production",
source: { type: "hose", domain: "https://hose.example.test", corpId: "fixture", appKey: "fixture-key", appSecurity: "fixture-secret", staffId: "fixture" },
seal: {}, auth: { refreshTtl: 300 }
} as CorpConfig
describe("export accounting and partial results", () => {
for (const excludeDeleted of [false, true]) {
test(`counts documents separately from runs and ${excludeDeleted ? "excludes only missing run identities" : "retains missing documents by default"}`, async () => {
const progress: ApprovalRunsExportProgress[] = []
const file = join(dir, "audit.xlsx")
const result = await exportApprovalRunsToExcel(ky.create({ prefix: "https://seal.example.test", retry: 0 }), corp, {
startDate: "2026-10-19", endDate: "2026-10-25", outputFile: file,
withFlow: true, ...(excludeDeleted ? { excludeDeleted: true } : {}),
pageDelayMs: 0, flowBatchDelayMs: 0, onProgress: value => progress.push(value)
})
expect(result.flow).toEqual({ requestedDocumentCount: 4, foundDocumentCount: 1, missingDocumentCount: 2, failedDocumentCount: 1 })
expect(result.counts).toMatchObject({ scannedRecordCount: 7, selectedRecordCount: 5, excludedOtherSourceCount: 1,
retainedMissingFlowDocumentCount: excludeDeleted ? 0 : 2,
retainedMissingFlowRecordCount: excludeDeleted ? 0 : 3,
excludedMissingFlowDocumentCount: excludeDeleted ? 2 : 0 })
expect(result.recordCount).toBe(excludeDeleted ? 2 : 5)
expect(result.excludedDeletedCount).toBe(excludeDeleted ? 3 : 0)
expect(result.excludedSimulationCount).toBe(1)
expect(result.partial).toBe(true)
expect(result.warnings).toContain("1 个单据的合思审批流请求失败,已使用降级对齐")
expect(progress.map(item => item.phase)).toEqual(expect.arrayContaining(["rules", "records", "flow", "write"]))
expect(progress.at(-1)).toEqual({ phase: "write", processed: 5, total: 5 })
const workbook = new ExcelJS.Workbook()
await workbook.xlsx.readFile(file)
const sheet = workbook.worksheets[0]!
expect(sheet.rowCount - 1).toBe(result.recordCount)
expect(sheet.getColumn(1).values).toContain("SN-SHARED")
const actions = sheet.getColumn(11).values.map(String)
expect(actions.filter(action => action.includes("可能已删除"))).toHaveLength(excludeDeleted ? 0 : 3)
})
}
})
@@ -0,0 +1,108 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test"
import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import {
exportTaskOptionsSchema, getExportTask, listExportTasks, presentExportTask,
readExportTask, startExportTask, waitForExportTask, writeExportTask,
type ExportTask
} from "./export-task.js"
const previous = process.env.SEAL_USE_EXPORT_TASKS_DIR
let dir: string
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "seal-export-task-"))
process.env.SEAL_USE_EXPORT_TASKS_DIR = dir
})
afterEach(() => {
if (previous === undefined) delete process.env.SEAL_USE_EXPORT_TASKS_DIR
else process.env.SEAL_USE_EXPORT_TASKS_DIR = previous
rmSync(dir, { recursive: true, force: true })
})
const options = exportTaskOptionsSchema.parse({
startDate: "2026-10-19", endDate: "2026-10-25", limit: 100000,
includeCompletedOnly: false, toDownloads: true, force: false,
withFlow: true, flowConcurrency: 3, excludeDeleted: false, includeSimulation: false
})
const input = { corpId: "fixture", corpName: "测试企业", options, launcher: { command: process.execPath } }
function launch(task: ExportTask): number {
task.status = "running"
task.pid = process.pid
writeExportTask(task)
return process.pid
}
describe("local export lifecycle", () => {
test("reuses an in-flight task but creates a fresh task after completion or changed controls", () => {
const first = startExportTask(input, launch)
expect(first.reused).toBe(false)
expect(startExportTask(input, launch)).toMatchObject({ reused: true, task: { id: first.task.id } })
const other = startExportTask({ ...input, options: { ...options, excludeDeleted: true } }, launch)
expect(other.task.id).not.toBe(first.task.id)
const completed = readExportTask(first.task.id)
completed.status = "completed"
completed.result = { filePath: "/tmp/fixture.xlsx" }
writeExportTask(completed)
expect(startExportTask(input, launch).task.id).not.toBe(first.task.id)
expect(listExportTasks("fixture")).toHaveLength(3)
expect(listExportTasks("another")).toEqual([])
if (process.platform !== "win32") expect(statSync(join(dir, `${first.task.id}.json`)).mode & 0o777).toBe(0o600)
expect(readFileSync(join(dir, `${first.task.id}.json`), "utf8")).not.toContain("appSecurity")
})
test("timeout returns a ticket without stopping execution and can be waited again", async () => {
const { task } = startExportTask(input, launch)
const pending = await waitForExportTask(task.id, { timeoutMs: 5, pollIntervalMs: 2 })
expect(pending.timedOut).toBe(true)
expect(getExportTask(task.id).status).toBe("running")
expect(presentExportTask(pending.task, true)).toMatchObject({ completed: false, terminal: false, timedOut: true })
const complete = readExportTask(task.id)
complete.status = "completed"
complete.result = { recordCount: 2 }
writeExportTask(complete)
const result = await waitForExportTask(task.id, { timeoutMs: 50, pollIntervalMs: 2 })
expect(result).toMatchObject({ timedOut: false, task: { status: "completed", result: { recordCount: 2 } } })
})
test("reports dead workers, expired startup and pre-reboot tasks as failures", () => {
for (const mode of ["dead", "startup", "reboot"]) {
const { task } = startExportTask({ ...input, corpId: mode }, launch)
if (mode === "dead") task.pid = 2147483647
if (mode === "startup") { task.pid = null; task.createdAt = new Date(Date.now() - 60000).toISOString() }
if (mode === "reboot") task.createdAt = "2000-01-01T00:00:00+08:00"
writeExportTask(task)
expect(getExportTask(task.id)).toMatchObject({ status: "failed", exitCode: 1 })
expect(presentExportTask(getExportTask(task.id))).toMatchObject({ terminal: true, completed: false })
}
})
test("rejects unsafe IDs and corrupt states while keeping healthy entries visible", () => {
expect(() => readExportTask("../secrets")).toThrow("无效")
const { task } = startExportTask(input, launch)
writeFileSync(join(dir, "broken.json"), "not json")
expect(listExportTasks()).toHaveLength(1)
writeFileSync(join(dir, `${task.id}.json`), "{}")
expect(() => getExportTask(task.id)).toThrow("无效")
})
test("records launch failure and recovers an abandoned reservation", () => {
const lock = join(dir, ".start-lock")
mkdirSync(lock)
writeFileSync(join(lock, "owner"), "2147483647")
expect(() => startExportTask(input, () => { throw Error("launch failed") })).toThrow("launch failed")
expect(listExportTasks()[0]).toMatchObject({ status: "failed", error: "launch failed" })
expect(startExportTask(input, launch).reused).toBe(false)
})
test("prevents different in-flight exports from overwriting the same explicit destination", () => {
const withPath = { ...input, options: { ...options, outputFile: join(dir, "audit.xlsx") } }
const first = startExportTask(withPath, launch)
expect(startExportTask(withPath, launch).reused).toBe(true)
expect(() => startExportTask({ ...withPath, options: { ...withPath.options, limit: 10 } }, launch)).toThrow("同一 --out")
const task = readExportTask(first.task.id)
task.status = "completed"
task.result = { filePath: withPath.options.outputFile }
writeExportTask(task)
expect(startExportTask({ ...withPath, options: { ...withPath.options, limit: 10 } }, launch).reused).toBe(false)
})
})
@@ -0,0 +1,208 @@
import { createHash, randomUUID } from "node:crypto"
import { spawn } from "node:child_process"
import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"
import { homedir, uptime } from "node:os"
import { join } from "node:path"
import { z } from "zod"
import { formatBeijingIso } from "../../../core/config/timestamps.js"
import { validationError } from "../../../core/errors.js"
import type { LauncherConfig } from "../../../core/runtime.js"
import { VERSION } from "../../../version.js"
import { redactSensitiveText } from "../../../core/redact.js"
// Persist only export controls, never the enterprise configuration or session.
export const exportTaskOptionsSchema = z.object({
startDate: z.string().optional(), endDate: z.string().optional(),
limit: z.number().int().min(1).max(100000),
status: z.string().optional(), manualApprovalStatus: z.array(z.string()).optional(),
includeCompletedOnly: z.boolean(), outputFile: z.string().optional(),
toDownloads: z.boolean(), force: z.boolean(), withFlow: z.boolean(),
flowConcurrency: z.number().int().min(1).max(5), excludeDeleted: z.boolean(),
taskMode: z.string().optional(), sourceSystem: z.string().optional(),
sns: z.array(z.string()).optional(), includeSimulation: z.boolean()
})
export type ExportTaskOptions = z.infer<typeof exportTaskOptionsSchema>
const progressSchema = z.object({
phase: z.enum(["queued", "auth", "rules", "records", "flow", "write"]),
processed: z.number().nonnegative(), total: z.number().nonnegative().nullable()
})
const taskSchema = z.object({
id: z.string().uuid(), fingerprint: z.string(), corpId: z.string(), corpName: z.string(),
options: exportTaskOptionsSchema, cwd: z.string(),
status: z.enum(["queued", "running", "completed", "failed"]),
createdAt: z.iso.datetime({ offset: true }), updatedAt: z.iso.datetime({ offset: true }), pid: z.number().int().positive().nullable(),
progress: progressSchema,
result: z.record(z.string(), z.unknown()).optional(),
error: z.string().optional(),
exitCode: z.union([z.literal(1), z.literal(2), z.literal(10), z.literal(11), z.literal(12), z.literal(13), z.literal(14)]).optional()
})
export type ExportTask = z.infer<typeof taskSchema>
export function exportTasksDir(): string {
return process.env.SEAL_USE_EXPORT_TASKS_DIR || join(homedir(), ".cache", "seal-use", "exports", "tasks")
}
function taskPath(id: string): string {
if (!z.string().uuid().safeParse(id).success) throw validationError("无效的导出任务 ID")
return join(exportTasksDir(), `${id}.json`)
}
export function writeExportTask(task: ExportTask): void {
const path = taskPath(task.id)
mkdirSync(exportTasksDir(), { recursive: true, mode: 0o700 })
const temp = `${path}.${process.pid}.${randomUUID()}.tmp`
try {
writeFileSync(temp, JSON.stringify(taskSchema.parse(task)), { mode: 0o600 })
renameSync(temp, path)
} finally {
rmSync(temp, { force: true })
}
}
export function readExportTask(id: string): ExportTask {
const path = taskPath(id)
if (!existsSync(path)) throw validationError("导出任务不存在或缓存已清理,请先执行 approval-runs export list")
const parsed = taskSchema.safeParse(JSON.parse(readFileSync(path, "utf8")))
if (!parsed.success) throw validationError("导出任务状态文件无效")
const task = parsed.data
if (task.id !== id) throw validationError("导出任务状态文件身份不匹配")
return task
}
function isAlive(pid: number): boolean {
try { process.kill(pid, 0); return true } catch (error) {
return error instanceof Error && "code" in error && error.code === "EPERM"
}
}
export function getExportTask(id: string): ExportTask {
const task = readExportTask(id)
if (["completed", "failed"].includes(task.status)) return task
const beforeBoot = Date.parse(task.createdAt) < Date.now() - uptime() * 1000 - 5000
const startExpired = !task.pid && Date.now() - Date.parse(task.createdAt) > 30000
if (beforeBoot || startExpired || (task.pid && !isAlive(task.pid))) {
// A worker may have persisted its terminal result between our read and the PID check.
const latest = readExportTask(id)
if (latest.status !== task.status || latest.pid !== task.pid || latest.updatedAt !== task.updatedAt) return latest
task.status = "failed"
task.error = "导出工作进程已退出或未能启动;请检查任务日志后重新创建任务"
task.exitCode = 1
task.updatedAt = formatBeijingIso()
writeExportTask(task)
}
return task
}
export function listExportTasks(corpId?: string): ExportTask[] {
if (!existsSync(exportTasksDir())) return []
const tasks: ExportTask[] = []
for (const file of readdirSync(exportTasksDir())) {
if (!file.endsWith(".json")) continue
try {
const task = getExportTask(file.slice(0, -5))
if (!corpId || task.corpId === corpId) tasks.push(task)
} catch { /* A corrupt cache entry must not hide healthy tasks. */ }
}
return tasks.sort((a, b) => b.createdAt.localeCompare(a.createdAt))
}
export function presentExportTask(task: ExportTask, timedOut = false) {
return {
taskId: task.id, corpName: task.corpName, status: task.status,
terminal: task.status === "completed" || task.status === "failed",
completed: task.status === "completed", timedOut,
createdAt: task.createdAt, updatedAt: task.updatedAt, progress: task.progress,
options: task.options, result: task.result, error: task.error,
logFile: join(exportTasksDir(), `${task.id}.log`),
next: {
status: `seal-use approval-runs export status ${task.id}`,
wait: `seal-use approval-runs export wait ${task.id} --timeout 30s`,
list: "seal-use approval-runs export list"
}
}
}
export async function waitForExportTask(
id: string,
options: { timeoutMs: number; pollIntervalMs: number; onChange?: (task: ExportTask) => void }
) {
const start = Date.now()
let revision = ""
let lastNotice = 0
while (true) {
const task = getExportTask(id)
const current = JSON.stringify([task.status, task.progress])
if (current !== revision || Date.now() - lastNotice >= 15000) {
options.onChange?.(task)
revision = current
lastNotice = Date.now()
}
if (task.status === "completed" || task.status === "failed") return { task, timedOut: false }
const remaining = options.timeoutMs - (Date.now() - start)
if (remaining <= 0) return { task, timedOut: true }
await new Promise(resolve => setTimeout(resolve, Math.min(options.pollIntervalMs, remaining)))
}
}
export function startExportTask(input: {
corpId: string; corpName: string; options: ExportTaskOptions; launcher: LauncherConfig
}, launch?: (task: ExportTask) => number) {
const root = exportTasksDir()
mkdirSync(root, { recursive: true, mode: 0o700 })
// Exclusive reservation prevents simultaneous callers from starting duplicate workers.
const lock = join(root, ".start-lock")
if (existsSync(lock)) {
let abandoned = false
try {
const owner = Number(readFileSync(join(lock, "owner"), "utf8"))
abandoned = !Number.isInteger(owner) || owner <= 0 || !isAlive(owner) || statSync(lock).mtimeMs < Date.now() - uptime() * 1000 - 5000
} catch {
abandoned = Date.now() - statSync(lock).mtimeMs > 30000
}
if (abandoned) rmSync(lock, { recursive: true, force: true })
}
try { mkdirSync(lock, { mode: 0o700 }) } catch {
throw validationError("另一个导出正在创建任务,请稍后重试;已有任务可通过 export list 查询")
}
try {
writeFileSync(join(lock, "owner"), String(process.pid), { mode: 0o600 })
const fingerprint = createHash("sha256").update(JSON.stringify({
corpId: input.corpId, options: input.options, cwd: process.cwd(), version: VERSION,
enterprises: process.env.SEAL_USE_ENTERPRISES_DIR, config: process.env.SEAL_USE_CONFIG_FILE
})).digest("hex")
const active = listExportTasks().filter(task => ["queued", "running"].includes(task.status))
const reused = active.find(task => task.fingerprint === fingerprint)
if (reused) return { task: reused, reused: true }
if (input.options.outputFile && active.some(task => task.options.outputFile === input.options.outputFile)) {
throw validationError("另一个导出任务正在写入同一 --out 路径,请等待该任务结束或选择不同文件")
}
const task: ExportTask = {
id: randomUUID(), fingerprint, corpId: input.corpId, corpName: input.corpName,
options: input.options, cwd: process.cwd(), status: "queued", pid: null,
createdAt: formatBeijingIso(), updatedAt: formatBeijingIso(),
progress: { phase: "queued", processed: 0, total: null }
}
writeExportTask(task)
try {
let pid: number | undefined
if (launch) pid = launch(task)
else {
const child = spawn(input.launcher.command, [...(input.launcher.args ?? []), "approval-runs", "export-worker", task.id], {
cwd: task.cwd, detached: true, stdio: "ignore", env: { ...process.env, SEAL_DISABLE_BG_UPDATE: "1" }
})
child.on("error", () => { /* Missing PID is handled below; a dead worker is detected by status. */ })
pid = child.pid
child.unref()
}
if (!pid) throw new Error("无法启动导出后台进程")
return { task: readExportTask(task.id), reused: false }
} catch (error) {
task.status = "failed"
task.error = redactSensitiveText(error instanceof Error ? error.message : "无法启动导出后台进程")
task.exitCode = 1
writeExportTask(task)
throw error
}
} finally { rmSync(lock, { recursive: true, force: true }) }
}
+17 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, test } from "bun:test";
import { existsSync, rmSync } from "node:fs";
import { existsSync, mkdtempSync, rmSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import ExcelJS from "exceljs";
@@ -104,6 +104,22 @@ describe("approval-runs-export helpers", () => {
expect(formatExportMinuteTag(fixedTime)).toBe("20260915_1026");
});
test("automatic filenames distinguish background tasks started within one minute", () => {
const dir = mkdtempSync(join(tmpdir(), "seal-export-names-"));
const cwd = process.cwd();
try {
process.chdir(dir);
const options = { corpName: "测试", dateTag: "2026-10-19至2026-10-25", recordCount: 1, exportTime: new Date("2026-10-27T13:00:00+08:00") };
const first = resolveOutputFilePath({ ...options, outputTag: "task-a" });
const second = resolveOutputFilePath({ ...options, outputTag: "task-b" });
expect(first).not.toBe(second);
expect(first).toEndWith("_20261027_1300_task-a.xlsx");
} finally {
process.chdir(cwd);
rmSync(dir, { recursive: true, force: true });
}
});
test("formatDate formats dates, epoch timestamps, and strings cleanly in Asia/Shanghai", () => {
expect(formatDate("2026-08-07")).toBe("2026-08-07");
expect(formatDate("2026-08-07T12:00:00Z")).toBe("2026-08-07");
+124 -24
View File
@@ -37,6 +37,14 @@ export interface ApprovalRunsExportOptions {
sns?: string[];
includeSimulation?: boolean;
exportTime?: Date;
outputTag?: string;
onProgress?: (progress: ApprovalRunsExportProgress) => void;
}
export interface ApprovalRunsExportProgress {
phase: "rules" | "records" | "flow" | "write";
processed: number;
total: number | null;
}
export interface ApprovalRunsExportResult {
@@ -51,6 +59,38 @@ export interface ApprovalRunsExportResult {
exportedAt: string;
excludedDeletedCount?: number;
excludedSimulationCount?: number;
filters: {
startDate: string | null;
endDate: string | null;
withFlow: boolean;
excludeDeleted: boolean;
includeSimulation: boolean;
completedOnly: boolean;
limit: number;
status: string | null;
manualStatus: string[] | null;
taskMode: string | null;
sourceSystem: string | null;
};
counts: {
scannedRecordCount: number;
selectedRecordCount: number;
exportedDocumentCount: number;
excludedOtherSourceCount: number;
excludedTaskModeCount: number;
excludedIncompleteCount: number;
retainedMissingFlowDocumentCount: number;
retainedMissingFlowRecordCount: number;
excludedMissingFlowDocumentCount: number;
};
flow: {
requestedDocumentCount: number;
foundDocumentCount: number;
missingDocumentCount: number;
failedDocumentCount: number;
};
partial: boolean;
warnings: string[];
}
export function normalizeTimestamp(val?: string | number, endOfDay = false): string | undefined {
@@ -291,6 +331,7 @@ export function resolveOutputFilePath(options: {
dateTag?: string;
recordCount: number;
exportTime?: Date;
outputTag?: string;
}): string {
if (options.outputFile) {
let p = resolve(options.outputFile);
@@ -312,7 +353,8 @@ export function resolveOutputFilePath(options: {
const dateTag = options.dateTag || getBeijingDate(0);
const countTag = options.recordCount > 0 ? `${options.recordCount}条` : "空数据";
const timeTag = formatExportMinuteTag(options.exportTime || new Date());
const fileName = `${safeCorpName}_审核记录_${dateTag}_${countTag}_${timeTag}.xlsx`;
const suffix = options.outputTag ? `_${options.outputTag.replace(/[^a-zA-Z0-9_-]/g, "_")}` : "";
const fileName = `${safeCorpName}_审核记录_${dateTag}_${countTag}_${timeTag}${suffix}.xlsx`;
let targetDir: string;
if (options.toDownloads) {
@@ -354,9 +396,22 @@ export async function exportApprovalRunsToExcel(
const { startDateTs, endDateTs } = dateRange;
let dateTag = dateRange.dateTag;
const manualStatusFilter = normalizeManualApprovalStatus(options.manualApprovalStatus);
const withFlow = options.withFlow === true && corp.source.type === "hose";
const excludeDeleted = options.excludeDeleted ?? false;
const includeSimulation = options.taskMode === "simulation" || (options.includeSimulation ?? corp.environment === "test");
const progress = (phase: ApprovalRunsExportProgress["phase"], processed: number, total: number | null) =>
options.onProgress?.({ phase, processed, total });
const warnings: string[] = [];
let rulesFailed = false;
let detailFailureCount = 0;
let scannedRecordCount = 0;
let excludedTaskModeCount = 0;
let excludedIncompleteCount = 0;
const flowCounts = { requestedDocumentCount: 0, foundDocumentCount: 0, missingDocumentCount: 0, failedDocumentCount: 0 };
// 1. 动态加载企业规则集,生成列定义
console.error(`正在加载企业「${corpName}」审核规则集...`);
progress("rules", 0, null);
const ruleMap = new Map<string, { id: string; code: string; title: string; desc: string }>();
try {
@@ -372,6 +427,7 @@ export async function exportApprovalRunsToExcel(
});
});
} catch (err: any) {
rulesFailed = true;
console.error(`⚠️ 加载规则字典失败: ${err.message},将仅导出基础信息列。`);
}
@@ -382,9 +438,10 @@ export async function exportApprovalRunsToExcel(
});
console.error(`已就绪 ${sortedRuleKeys.length} 个规则列。开始拉取单据...`);
progress("records", 0, null);
// 1.5 如果是合思企业且显式启用 withFlow,先探测单据规模并做耗时与频控提示
if (options.withFlow === true && corp.source.type === "hose") {
if (withFlow) {
if (hasTargetSns) {
console.error(
`🎯 [单据筛选] 已指定定向筛选单号: [${targetSns.join(", ")}] (共 ${targetSns.length} 个)。`
@@ -435,26 +492,30 @@ export async function exportApprovalRunsToExcel(
});
const matched = (batch.records || []).filter((r) => r.sourceDocumentSN === sn);
for (const r of matched) {
const allowSimulation =
options.taskMode === "simulation" ||
options.includeSimulation === true ||
corp.environment === "test";
if (!allowSimulation && r.taskMode === "simulation") {
scannedRecordCount++;
if (!includeSimulation && r.taskMode === "simulation") {
excludedSimulationCount++;
continue;
}
if (options.taskMode && r.taskMode !== options.taskMode) continue;
if (options.taskMode && r.taskMode !== options.taskMode) {
excludedTaskModeCount++;
continue;
}
if (corp.source.type === "hose" && r.sourceSystem && !["hose", "hosecloud"].includes(r.sourceSystem)) {
excludedOtherSourceCount++;
continue;
}
if (options.includeCompletedOnly && r.status !== "completed") continue;
if (options.includeCompletedOnly && r.status !== "completed") {
excludedIncompleteCount++;
continue;
}
if (r.status === "completed" && (!r.result || !(r.result as any).rulesResult)) {
try {
const full = await api.getApprovalRun(client, r.id);
fetchedRecords.push(full);
} catch {
detailFailureCount++;
fetchedRecords.push(r);
}
} else {
@@ -463,8 +524,10 @@ export async function exportApprovalRunsToExcel(
if (fetchedRecords.length >= limit) break;
}
} catch (e: any) {
warnings.push(`定向检索失败: ${sn}`);
console.error(`⚠️ 定向检索单号 [${sn}] 失败: ${e.message}`);
}
progress("records", scannedRecordCount, null);
if (fetchedRecords.length >= limit) break;
}
console.error(`定向检索完成,成功匹配 ${fetchedRecords.length} 条记录。`);
@@ -501,21 +564,19 @@ export async function exportApprovalRunsToExcel(
totalAvailable = batch.total ?? totalAvailable;
for (const r of batch.records) {
scannedRecordCount++;
if (hasTargetSns && (!r.sourceDocumentSN || !targetSnsSet.has(r.sourceDocumentSN))) {
continue;
}
// 过滤测试任务(默认仅保留真实审批任务;测试环境或显式指定时放行)
const allowSimulation =
options.taskMode === "simulation" ||
options.includeSimulation === true ||
corp.environment === "test";
if (!allowSimulation && r.taskMode === "simulation") {
if (!includeSimulation && r.taskMode === "simulation") {
excludedSimulationCount++;
continue;
}
if (options.taskMode && r.taskMode !== options.taskMode) {
excludedTaskModeCount++;
continue;
}
@@ -526,6 +587,7 @@ export async function exportApprovalRunsToExcel(
}
if (options.includeCompletedOnly && r.status !== "completed") {
excludedIncompleteCount++;
continue;
}
@@ -535,6 +597,7 @@ export async function exportApprovalRunsToExcel(
const full = await api.getApprovalRun(client, r.id);
fetchedRecords.push(full);
} catch {
detailFailureCount++;
fetchedRecords.push(r);
}
} else {
@@ -545,6 +608,7 @@ export async function exportApprovalRunsToExcel(
}
offset += batch.records.length;
progress("records", scannedRecordCount, totalAvailable || null);
const currentProgress = totalAvailable > 0 ? ((offset / totalAvailable) * 100).toFixed(1) : "-";
if (offset % 500 === 0 || offset >= totalAvailable || fetchedRecords.length >= limit) {
console.error(
@@ -596,8 +660,6 @@ export async function exportApprovalRunsToExcel(
views: [{ state: "frozen", ySplit: 1, xSplit: 2 }]
});
const withFlow = options.withFlow === true && corp.source.type === "hose";
const baseColumns: Array<{ header: string; key: string; width: number }> = [
{ header: "单据编号", key: "sn", width: 16 },
{ header: "单据模板名称", key: "templateName", width: 26 },
@@ -662,9 +724,9 @@ export async function exportApprovalRunsToExcel(
// 3.5 如果是合思租户且显式启用 withFlow(--with-flow),获取原生审批流并对齐 E人工行为 / E人工意见
const alignmentsByRecordId = new Map<string, HoseRunAlignment>();
const deletedSNs = new Set<string>();
const excludeDeleted = options.excludeDeleted ?? true;
const missingFlowRunIds = new Set<string>();
if (options.withFlow === true && corp.source.type === "hose") {
if (withFlow) {
try {
const runsByDocKey = new Map<string, ApprovalRun[]>();
for (const record of fetchedRecords) {
@@ -677,6 +739,8 @@ export async function exportApprovalRunsToExcel(
}
const uniqueDocKeys = Array.from(runsByDocKey.keys());
flowCounts.requestedDocumentCount = uniqueDocKeys.length;
progress("flow", 0, uniqueDocKeys.length);
if (uniqueDocKeys.length > 0) {
const concurrency = Math.max(1, Math.min(options.flowConcurrency ?? 3, 5));
const batchDelayMs = options.flowBatchDelayMs ?? 150;
@@ -696,20 +760,24 @@ export async function exportApprovalRunsToExcel(
try {
const flow = await getHoseOpenFlow(openClient, docKey, staffCache);
if (!flow) {
flowCounts.missingDocumentCount++;
deletedSNs.add(displaySN);
const aligned = alignApprovalRunsWithHoseFlow(runsForDoc, undefined);
for (const [recordId, align] of aligned.entries()) {
align.eHumanAction = "单据已删除";
missingFlowRunIds.add(recordId);
align.eHumanAction = "单据未找到(可能已删除)";
align.eHumanComment = "合思系统中未找到该单据流转记录(可能已在合思端删除或作废)";
alignmentsByRecordId.set(recordId, align);
}
return;
}
const aligned = alignApprovalRunsWithHoseFlow(runsForDoc, flow);
flowCounts.foundDocumentCount++;
for (const [recordId, align] of aligned.entries()) {
alignmentsByRecordId.set(recordId, align);
}
} catch (err: any) {
flowCounts.failedDocumentCount++;
console.error(`⚠️ 拉取单据 ${displaySN} 审批流失败: ${err.message},使用降级对齐。`);
const aligned = alignApprovalRunsWithHoseFlow(runsForDoc, undefined);
for (const [recordId, align] of aligned.entries()) {
@@ -718,6 +786,7 @@ export async function exportApprovalRunsToExcel(
}
})
);
progress("flow", Math.min(i + batchKeys.length, uniqueDocKeys.length), uniqueDocKeys.length);
if (batchDelayMs > 0 && i + concurrency < uniqueDocKeys.length) {
await new Promise((r) => setTimeout(r, batchDelayMs));
@@ -731,13 +800,15 @@ export async function exportApprovalRunsToExcel(
}
}
} catch (err: any) {
flowCounts.failedDocumentCount = flowCounts.requestedDocumentCount - flowCounts.foundDocumentCount - flowCounts.missingDocumentCount;
warnings.push("合思审批流初始化或对齐失败,人工审批流信息不完整");
console.error(`⚠️ 对齐合思审批流失败: ${err.message},E人工行为与意见将使用默认值。`);
}
if (deletedSNs.size > 0) {
console.error(
`ℹ️ 检测到 ${deletedSNs.size} 个单据在合思端已删除或不存在(如: ${Array.from(deletedSNs).slice(0, 3).join(", ")}...)${
excludeDeleted ? ",已按要求自动排除。" : ",已在报表中标记为「单据已删除」。"
`ℹ️ 检测到 ${flowCounts.missingDocumentCount} 个单据在合思端未找到(可能已删除或作废,如: ${Array.from(deletedSNs).slice(0, 3).join(", ")}...)${
excludeDeleted ? ",已按要求自动排除。" : ",已保留并标记为「单据未找到(可能已删除)」。"
}`
);
}
@@ -745,14 +816,19 @@ export async function exportApprovalRunsToExcel(
let exportedRecordCount = 0;
let excludedDeletedCount = 0;
let retainedMissingFlowRecordCount = 0;
const exportedDocuments = new Set<string>();
progress("write", 0, fetchedRecords.length);
// 填充数据行
for (const record of fetchedRecords) {
const sn = record.sourceDocumentSN || record.sourceDocumentId;
if (excludeDeleted && sn && deletedSNs.has(sn)) {
if (excludeDeleted && missingFlowRunIds.has(record.id)) {
excludedDeletedCount++;
continue;
}
if (missingFlowRunIds.has(record.id)) retainedMissingFlowRecordCount++;
if (sn) exportedDocuments.add(record.sourceDocumentId || sn);
exportedRecordCount++;
const res = (record.result as any) || {};
const doc = (record.document as any) || {};
@@ -1035,7 +1111,8 @@ export async function exportApprovalRunsToExcel(
corpName,
dateTag,
recordCount: exportedRecordCount,
exportTime: options.exportTime
exportTime: options.exportTime,
outputTag: options.outputTag
});
await workbook.xlsx.writeFile(targetPath);
@@ -1043,6 +1120,10 @@ export async function exportApprovalRunsToExcel(
const stat = statSync(targetPath);
if (rulesFailed) warnings.push("规则字典加载失败,规则列不完整");
if (detailFailureCount) warnings.push(`${detailFailureCount} 条审核详情补取失败,已保留列表信息`);
if (flowCounts.failedDocumentCount) warnings.push(`${flowCounts.failedDocumentCount} 个单据的合思审批流请求失败,已使用降级对齐`);
progress("write", fetchedRecords.length, fetchedRecords.length);
return {
filePath: targetPath,
corpId: corp.id,
@@ -1054,6 +1135,25 @@ export async function exportApprovalRunsToExcel(
fileSizeBytes: stat.size,
exportedAt: formatBeijingIso(),
excludedDeletedCount,
excludedSimulationCount
excludedSimulationCount,
filters: {
startDate: hasExplicitDate || !hasTargetSns ? dateRange.startDateStr : null,
endDate: hasExplicitDate || !hasTargetSns ? dateRange.endDateStr : null,
withFlow, excludeDeleted, includeSimulation,
completedOnly: options.includeCompletedOnly ?? false, limit,
status: options.status ?? null, manualStatus: manualStatusFilter ?? null,
taskMode: options.taskMode ?? null, sourceSystem: options.sourceSystem ?? null
},
counts: {
scannedRecordCount, selectedRecordCount: fetchedRecords.length,
exportedDocumentCount: exportedDocuments.size,
excludedOtherSourceCount, excludedTaskModeCount, excludedIncompleteCount,
retainedMissingFlowDocumentCount: excludeDeleted ? 0 : flowCounts.missingDocumentCount,
retainedMissingFlowRecordCount,
excludedMissingFlowDocumentCount: excludeDeleted ? flowCounts.missingDocumentCount : 0
},
flow: flowCounts,
partial: warnings.length > 0,
warnings
};
}
+2 -2
View File
@@ -200,10 +200,10 @@ async function runEmbeddedCli() {
const result = await runCli(process.argv.slice(3), {
appRoot: pluginRoot,
entryFile: cliEntryFile,
launcher: resolveServerCliLauncher()
launcher: resolveServerCliLauncher(),
onStderr: (text) => process.stderr.write(text)
});
if (result.stdout) process.stdout.write(result.stdout);
if (result.stderr) process.stderr.write(`${result.stderr}${result.stderr.endsWith("\n") ? "" : "\n"}`);
process.exitCode = result.exitCode;
}