Release v0.10.32: Semantic approval-runs link redesign, auth link standardization, and export defense
This commit is contained in:
1 parent
9060a28d8b
commit
972eff1436
31 files changed
+976
-288
No files matched your search
@@ -302,20 +302,35 @@ export async function handleApprovalRunsCommand(
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "url") {
|
||||
const sso = booleanOption(args.options.sso) ?? false;
|
||||
if (action === "link" || action === "url") {
|
||||
const autoLogin =
|
||||
booleanOption(args.options["auto-login"]) ??
|
||||
booleanOption(args.options.autoLogin) ??
|
||||
booleanOption(args.options["hose-sso"]) ??
|
||||
booleanOption(args.options.hoseSso) ??
|
||||
booleanOption(args.options.sso) ??
|
||||
false;
|
||||
const type = stringOption(args.options.type);
|
||||
const expiresIn = numberOption(args.options.expire) ?? numberOption(args.options.expiresIn) ?? 7200;
|
||||
const recordId = maybeName ?? stringOption(args.options.id) ?? stringOption(args.options.recordId);
|
||||
const sn = stringOption(args.options.sn) ?? stringOption(args.options.sourceDocumentSN);
|
||||
const sourceDocumentId = stringOption(args.options.sourceDocumentId);
|
||||
|
||||
if (!recordId && !sn && !sourceDocumentId) {
|
||||
throw new Error("Usage: seal-use approval-runs link <recordId> [--sn <sn>] [--type seal-result|hose-document] [--auto-login] [--corp <corpId>]");
|
||||
}
|
||||
|
||||
await runTool(
|
||||
"seal_approval_run_url_get",
|
||||
client,
|
||||
corp,
|
||||
{
|
||||
recordId: maybeName ?? stringOption(args.options.id) ?? stringOption(args.options.recordId),
|
||||
recordId,
|
||||
sourceDocumentSN: sn,
|
||||
sourceDocumentId: stringOption(args.options.sourceDocumentId),
|
||||
sso,
|
||||
sourceDocumentId,
|
||||
type,
|
||||
autoLogin,
|
||||
sso: autoLogin,
|
||||
expiresIn
|
||||
},
|
||||
outputOptions(args.options)
|
||||
@@ -395,7 +410,11 @@ export async function handleApprovalRunsCommand(
|
||||
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"])
|
||||
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") {
|
||||
|
||||
@@ -7,6 +7,7 @@ import { getMe } from "../../domains/seal/api.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../parser.js";
|
||||
import { printJson, redactSensitiveText } from "../printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
import { runToolResult } from "../helpers.js";
|
||||
import { extractKeysFromLinkAction, showCorpKeysAction } from "./corps.js";
|
||||
|
||||
export async function handleAuthExtractKeysCommand(maybeName: string | undefined, args: ParsedArgs) {
|
||||
@@ -38,6 +39,22 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "seal-link" || action === "link" || (action === "hose-link" && corp.source.type === "seal")) {
|
||||
const client = await createSealClient(corp);
|
||||
const note = stringOption(args.options.note) ?? "CLI generated provisional access link";
|
||||
const delegation = await runToolResult(
|
||||
"seal_delegation_create",
|
||||
client,
|
||||
corp,
|
||||
{ note }
|
||||
);
|
||||
if (action === "hose-link") {
|
||||
console.error(`👉 提示: 企业「${corp.name}」源类型为 Seal 原生测试环境,已自动为您生成委托免登直达链接。`);
|
||||
}
|
||||
printJson(delegation);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "hose-link") {
|
||||
const rawExpire = args.options.expire;
|
||||
const expiresIn = rawExpire !== undefined ? numberOption(rawExpire) : 7200;
|
||||
|
||||
@@ -842,6 +842,45 @@ describe("Hose OpenAPI key extraction from assistance link", () => {
|
||||
expect(authResult.stderr).toContain("合思子域专享能力");
|
||||
});
|
||||
|
||||
test("corps rename updates enterprise name successfully", async () => {
|
||||
const enterprises = setupConfigEnv();
|
||||
mkdirSync(enterprises, { recursive: true });
|
||||
writeFileSync(
|
||||
join(enterprises, "corp-rename.json"),
|
||||
JSON.stringify({
|
||||
id: "corp-rename",
|
||||
name: "待识别企业",
|
||||
environment: "production",
|
||||
seal: { url: "https://seal.example.com" },
|
||||
source: {
|
||||
type: "seal",
|
||||
sealUrl: "https://seal.example.com",
|
||||
token: "token-123"
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
const result = await runCli(["corps", "rename", "corp-rename", "--name", "已识别真实企业"]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
const parsed = JSON.parse(result.stdout);
|
||||
expect(parsed).toEqual({
|
||||
id: "corp-rename",
|
||||
previousName: "待识别企业",
|
||||
name: "已识别真实企业",
|
||||
success: true
|
||||
});
|
||||
|
||||
const updated = JSON.parse(readFileSync(join(enterprises, "corp-rename.json"), "utf-8"));
|
||||
expect(updated.name).toBe("已识别真实企业");
|
||||
});
|
||||
|
||||
test("corps rename rejects missing --name parameter", async () => {
|
||||
setupConfigEnv();
|
||||
const result = await runCli(["corps", "rename", "some-corp"]);
|
||||
expect(result.exitCode).toBe(2);
|
||||
expect(result.stderr).toContain("Usage: seal-use corps rename <corpId> --name <newName>");
|
||||
});
|
||||
|
||||
test("maskCellphone masks standard 11-digit mobile and non-standard phones safely", async () => {
|
||||
const { maskCellphone } = await import("./corps.js");
|
||||
expect(maskCellphone("13812345678")).toBe("138****5678");
|
||||
|
||||
@@ -270,6 +270,31 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "rename") {
|
||||
const targetCorpId =
|
||||
maybeName ??
|
||||
stringOption(args.options.corp) ??
|
||||
stringOption(args.options.id);
|
||||
const newName =
|
||||
stringOption(args.options.name) ??
|
||||
stringOption(args.options.to) ??
|
||||
(args.command[3] && !args.command[3].startsWith("-") ? args.command[3] : undefined);
|
||||
|
||||
if (!targetCorpId || !newName) {
|
||||
throw new Error("Usage: seal-use corps rename <corpId> --name <newName>");
|
||||
}
|
||||
|
||||
const corp = selectCorp(targetCorpId);
|
||||
const updated = updateCorpConfig(corp.id, { name: newName });
|
||||
printJson({
|
||||
success: true,
|
||||
id: updated.id,
|
||||
name: updated.name,
|
||||
previousName: corp.name
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "bind-test") {
|
||||
let prodId: string | undefined;
|
||||
let testId: string | undefined;
|
||||
@@ -954,12 +979,40 @@ export async function handleCorpsCommand(action: string | undefined, maybeName:
|
||||
}
|
||||
|
||||
if (action === "add-hose") {
|
||||
await addHoseCorp(jsonObject(args.json));
|
||||
const jsonPayload = jsonObject(args.json);
|
||||
const merged = {
|
||||
...jsonPayload,
|
||||
...(args.options.staffName ? { staffName: stringOption(args.options.staffName) } : {}),
|
||||
...(args.options["staff-name"] ? { staffName: stringOption(args.options["staff-name"]) } : {}),
|
||||
...(args.options.staffPhone ? { staffPhone: stringOption(args.options.staffPhone) } : {}),
|
||||
...(args.options["staff-phone"] ? { staffPhone: stringOption(args.options["staff-phone"]) } : {}),
|
||||
...(args.options.name ? { name: stringOption(args.options.name) } : {}),
|
||||
...(args.options.domain ? { domain: stringOption(args.options.domain) } : {}),
|
||||
...(args.options.corpId ? { corpId: stringOption(args.options.corpId) } : {}),
|
||||
...(args.options["corp-id"] ? { corpId: stringOption(args.options["corp-id"]) } : {}),
|
||||
...(args.options.appKey ? { appKey: stringOption(args.options.appKey) } : {}),
|
||||
...(args.options["app-key"] ? { appKey: stringOption(args.options["app-key"]) } : {}),
|
||||
...(args.options.appSecurity ? { appSecurity: stringOption(args.options.appSecurity) } : {}),
|
||||
...(args.options["app-security"] ? { appSecurity: stringOption(args.options["app-security"]) } : {}),
|
||||
...(args.options.force !== undefined ? { force: booleanOption(args.options.force) } : {}),
|
||||
...(args.options.overwrite !== undefined ? { overwrite: booleanOption(args.options.overwrite) } : {})
|
||||
};
|
||||
await addHoseCorp(merged);
|
||||
return;
|
||||
}
|
||||
|
||||
if (action === "add-seal") {
|
||||
await addSealCorp(jsonObject(args.json));
|
||||
const jsonPayload = jsonObject(args.json);
|
||||
const merged = {
|
||||
...jsonPayload,
|
||||
...(args.options.name ? { name: stringOption(args.options.name) } : {}),
|
||||
...(args.options.token ? { token: stringOption(args.options.token) } : {}),
|
||||
...(args.options.sealUrl ? { sealUrl: stringOption(args.options.sealUrl) } : {}),
|
||||
...(args.options.url ? { sealUrl: stringOption(args.options.url) } : {}),
|
||||
...(args.options.force !== undefined ? { force: booleanOption(args.options.force) } : {}),
|
||||
...(args.options.overwrite !== undefined ? { overwrite: booleanOption(args.options.overwrite) } : {})
|
||||
};
|
||||
await addSealCorp(merged);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1410,7 +1463,9 @@ async function addHoseCorp(input: Record<string, unknown>) {
|
||||
mkdirSync(enterprisesDir, { recursive: true, mode: 0o700 });
|
||||
const file = join(enterprisesDir, `${safeFileName(id)}.json`);
|
||||
if (existsSync(file) && input.overwrite !== true) {
|
||||
throw new Error(`Enterprise config already exists: ${file}. Pass "overwrite": true to replace it.`);
|
||||
throw new Error(
|
||||
`Enterprise config already exists: ${file}。如需覆盖已有配置,请在命令行追加 --overwrite 或在 JSON 参数中添加 "overwrite": true。`
|
||||
);
|
||||
}
|
||||
|
||||
writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
|
||||
|
||||
@@ -228,4 +228,26 @@ describe("seal-use test regression CLI", () => {
|
||||
expect(payload.verdict).toBe("DRY_RUN");
|
||||
expect(payload.targetCorp.id).toBe("corp-test");
|
||||
});
|
||||
|
||||
test("test regression accepts --webhook option and succeeds in dry-run", async () => {
|
||||
setupTestEnv();
|
||||
mockApiFetch();
|
||||
|
||||
const result = await runCli([
|
||||
"test",
|
||||
"regression",
|
||||
"--corp",
|
||||
"corp-test",
|
||||
"--samples",
|
||||
"2",
|
||||
"--dry-run",
|
||||
"--webhook",
|
||||
"自定义通道"
|
||||
]);
|
||||
expect(result.exitCode).toBe(0);
|
||||
|
||||
const payload = JSON.parse(result.stdout);
|
||||
expect(payload.verdict).toBe("DRY_RUN");
|
||||
expect(payload.targetCorp.id).toBe("corp-test");
|
||||
});
|
||||
});
|
||||
@@ -74,6 +74,7 @@ export async function handleTestCommand(
|
||||
const pollIntervalMs = numberOption(args.options["poll-interval"]) ?? 2000;
|
||||
const timeoutMs = numberOption(args.options.timeout) ?? 45000;
|
||||
const snPrefix = stringOption(args.options["sn-prefix"]) ?? "REG_";
|
||||
const webhookSelector = stringOption(args.options.webhook) ?? stringOption(args.options.selector);
|
||||
|
||||
const result = await runRegressionTest({
|
||||
sourceCorp,
|
||||
@@ -85,7 +86,8 @@ export async function handleTestCommand(
|
||||
pollIntervalMs,
|
||||
timeoutMs,
|
||||
snPrefix,
|
||||
failOnFlips
|
||||
failOnFlips,
|
||||
webhookSelector
|
||||
});
|
||||
|
||||
const isQuiet = booleanOption(args.options.quiet) || booleanOption(args.options.silent);
|
||||
|
||||
+43
-8
@@ -77,6 +77,15 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
],
|
||||
description: "Explicitly updates an enterprise's environment tag. Requires --confirm to prevent accidental changes."
|
||||
},
|
||||
{
|
||||
name: "rename",
|
||||
summary: "Rename an enterprise display name",
|
||||
usage: ["seal-use corps rename <corpId> --name <newName>"],
|
||||
options: [
|
||||
{ flag: "--name <newName>", description: "New human-readable enterprise name (required)" }
|
||||
],
|
||||
description: "Safely updates the display name of a configured enterprise without modifying underlying files manually."
|
||||
},
|
||||
{
|
||||
name: "bind-test",
|
||||
summary: "Bind a production enterprise to a test enterprise (1-to-1 association)",
|
||||
@@ -449,13 +458,28 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
usage: ["seal-use approval-runs result <recordId> [--summary] [--corp <corpId>]"]
|
||||
},
|
||||
{
|
||||
name: "url",
|
||||
summary: "Get web console URL for approval run (default deep link, or --sso for auto-login link)",
|
||||
name: "link",
|
||||
aliases: ["url"],
|
||||
summary: "Get web console link for an approval run (Seal AI audit result or Hose original document)",
|
||||
usage: [
|
||||
"seal-use approval-runs url <recordId> [--corp <corpId>]",
|
||||
"seal-use approval-runs url <recordId> --sso [--expire 7200] [--corp <corpId>]",
|
||||
"seal-use approval-runs url --sn <documentSN> [--sso] [--corp <corpId>]",
|
||||
"seal-use approval-runs url [--corp <corpId>]"
|
||||
"seal-use approval-runs link <recordId> [--corp <corpId>]",
|
||||
"seal-use approval-runs link <recordId> --auto-login [--expire 7200] [--corp <corpId>]",
|
||||
"seal-use approval-runs link <recordId> --type hose-document [--corp <corpId>]",
|
||||
"seal-use approval-runs link --sn <documentSN> [--auto-login] [--corp <corpId>]"
|
||||
],
|
||||
options: [
|
||||
{
|
||||
flag: "--type <seal-result|hose-document>",
|
||||
description: "Link type: 'seal-result' (Seal AI audit result page, default) or 'hose-document' (Hose original form)"
|
||||
},
|
||||
{
|
||||
flag: "--auto-login",
|
||||
description: "Generate auto-login ticketed link (for seal-result type, valid for --expire seconds)"
|
||||
},
|
||||
{
|
||||
flag: "--expire <seconds>",
|
||||
description: "Auto-login ticket expiration in seconds (default: 7200)"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -674,16 +698,27 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
summary: "Diagnose auth session and platform connectivity",
|
||||
usage: ["seal-use auth diagnose [--corp <corpId>]"]
|
||||
},
|
||||
{
|
||||
name: "link",
|
||||
aliases: ["seal-link"],
|
||||
summary: "【Seal 审核后台】生成免密登录/委托访问直达链接",
|
||||
usage: ["seal-use auth link [--note <note>] [--corp <corpId>]"],
|
||||
options: [
|
||||
{ flag: "--note <note>", description: "委托授权备注说明(如:演示测试、外部审计)" }
|
||||
],
|
||||
description:
|
||||
"生成访问当前企业 Seal AI 智能审核后台 (https://<tenant>.sealai.cc/delegate) 的免密直达链接。主体作用于 Seal 审核台,等价于快捷生成 delegation 委托访问链接。"
|
||||
},
|
||||
{
|
||||
name: "hose-link",
|
||||
summary: "【合思主站】生成免密登录/第三方协助入口链接",
|
||||
summary: "【合思外部主站】生成免密登录/第三方协助入口链接",
|
||||
usage: ["seal-use auth hose-link [--corp <corpId>] [--expire 7200] [--force]"],
|
||||
options: [
|
||||
{ flag: "--expire <seconds>", description: "链接有效时间(秒),默认 7200,支持如 86400(1天)" },
|
||||
{ flag: "--force, --refresh, -f", description: "强制向合思 OpenAPI 申请全新临时凭证" }
|
||||
],
|
||||
description:
|
||||
"专用于合思 (Hose) 来源企业。向合思申请临时 ticket,生成直达合思/易快报主站 (https://app.ekuaibao.com/web/thirdparty.html) 的免密登录链接。凭证独立生成,不读取亦不污染 CLI 内部会话。注意:此链接不可通过 'seal-use delegation list' 查询(后者仅管理 Seal 审核后台的委托令牌)。"
|
||||
"专用于合思 (Hose) 来源企业。向合思申请临时 ticket,生成直达外部合思/易快报主站 (https://app.ekuaibao.com/web/thirdparty.html) 的免密登录链接。若需生成 Seal 自身的审核后台访问链接,请使用 'seal-use auth link'。"
|
||||
},
|
||||
{
|
||||
name: "extract-keys",
|
||||
|
||||
@@ -23,7 +23,12 @@ describe("CLI read-only classification", () => {
|
||||
const ACTIONS_WITHOUT_REGISTRY_ENTRY = new Set(["approval-runs search"]);
|
||||
|
||||
test("every allow-listed command exists in the help registry", () => {
|
||||
const byArea = new Map(HELP_REGISTRY.map((area) => [area.area, area.commands.map((c) => c.name)]));
|
||||
const byArea = new Map(
|
||||
HELP_REGISTRY.map((area) => [
|
||||
area.area,
|
||||
area.commands.flatMap((c) => [c.name, ...(c.aliases ?? [])])
|
||||
])
|
||||
);
|
||||
|
||||
for (const { area, action } of listReadOnlyCommands()) {
|
||||
if (ACTIONS_WITHOUT_REGISTRY_ENTRY.has(`${area} ${action}`)) continue;
|
||||
|
||||
@@ -46,6 +46,7 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
|
||||
"document-summary",
|
||||
"attachments",
|
||||
"result",
|
||||
"link",
|
||||
"url"
|
||||
],
|
||||
simulation: [
|
||||
|
||||
@@ -141,8 +141,8 @@ export const EMBEDDED_DOMAIN_CAPABILITIES: DomainCapabilitySpec[] = [
|
||||
},
|
||||
{
|
||||
domain: "approval-runs (审核大盘)",
|
||||
summary: "AI 审核单据检索、统计分析、引证规则查看、附件全链路追踪、Excel 报表导出、免登 SSO 深度链接",
|
||||
primaryCommands: ["approval-runs list", "approval-runs stats", "approval-runs get", "approval-runs export", "approval-runs url"]
|
||||
summary: "AI 审核单据检索、统计分析、引证规则查看、附件全链路追踪、Excel 报表导出、单据直达链接与免登",
|
||||
primaryCommands: ["approval-runs list", "approval-runs stats", "approval-runs get", "approval-runs export", "approval-runs link"]
|
||||
},
|
||||
{
|
||||
domain: "rules (规则治理)",
|
||||
|
||||
@@ -65,6 +65,21 @@ describe("approval-runs-export helpers", () => {
|
||||
});
|
||||
expect(custom).toBe("/tmp/custom-export.xlsx");
|
||||
|
||||
expect(() =>
|
||||
resolveOutputFilePath({
|
||||
outputFile: "/tmp/custom-export.csv",
|
||||
corpName: "TestCorp",
|
||||
recordCount: 10
|
||||
})
|
||||
).toThrow("本命令仅支持导出 Excel 工作簿,文件扩展名必须为 .xlsx");
|
||||
|
||||
const noExtPath = resolveOutputFilePath({
|
||||
outputFile: "/tmp/custom-export",
|
||||
corpName: "TestCorp",
|
||||
recordCount: 10
|
||||
});
|
||||
expect(noExtPath).toBe("/tmp/custom-export.xlsx");
|
||||
|
||||
const fixedTime = new Date("2026-09-15T10:26:00+08:00");
|
||||
const dl = resolveOutputFilePath({
|
||||
toDownloads: true,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { existsSync, mkdirSync, statSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { dirname, extname, resolve } from "node:path";
|
||||
import ExcelJS from "exceljs";
|
||||
import type { KyInstance } from "ky";
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
@@ -33,6 +33,7 @@ export interface ApprovalRunsExportOptions {
|
||||
taskMode?: string;
|
||||
sourceSystem?: string;
|
||||
sns?: string[];
|
||||
includeSimulation?: boolean;
|
||||
exportTime?: Date;
|
||||
}
|
||||
|
||||
@@ -294,7 +295,16 @@ export function resolveOutputFilePath(options: {
|
||||
exportTime?: Date;
|
||||
}): string {
|
||||
if (options.outputFile) {
|
||||
const p = resolve(options.outputFile);
|
||||
let p = resolve(options.outputFile);
|
||||
const ext = extname(p).toLowerCase();
|
||||
if (ext && ext !== ".xlsx") {
|
||||
throw new Error(
|
||||
`导出路径错误: 本命令仅支持导出 Excel 工作簿,文件扩展名必须为 .xlsx(当前指定为 "${ext}")。请使用 .xlsx 后缀,例如: ${p.slice(0, -ext.length)}.xlsx`
|
||||
);
|
||||
}
|
||||
if (!ext) {
|
||||
p = `${p}.xlsx`;
|
||||
}
|
||||
const dir = dirname(p);
|
||||
if (!existsSync(dir)) {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
@@ -429,7 +439,11 @@ export async function exportApprovalRunsToExcel(
|
||||
});
|
||||
const matched = (batch.records || []).filter((r) => r.sourceDocumentSN === sn);
|
||||
for (const r of matched) {
|
||||
if (r.taskMode === "simulation") {
|
||||
const allowSimulation =
|
||||
options.taskMode === "simulation" ||
|
||||
options.includeSimulation === true ||
|
||||
corp.environment === "test";
|
||||
if (!allowSimulation && r.taskMode === "simulation") {
|
||||
excludedSimulationCount++;
|
||||
continue;
|
||||
}
|
||||
@@ -495,8 +509,12 @@ export async function exportApprovalRunsToExcel(
|
||||
continue;
|
||||
}
|
||||
|
||||
// 过滤测试任务(仅保留真实审批任务)
|
||||
if (r.taskMode === "simulation") {
|
||||
// 过滤测试任务(默认仅保留真实审批任务;测试环境或显式指定时放行)
|
||||
const allowSimulation =
|
||||
options.taskMode === "simulation" ||
|
||||
options.includeSimulation === true ||
|
||||
corp.environment === "test";
|
||||
if (!allowSimulation && r.taskMode === "simulation") {
|
||||
excludedSimulationCount++;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ export interface RegressionTestOptions {
|
||||
timeoutMs?: number;
|
||||
snPrefix?: string;
|
||||
failOnFlips?: boolean;
|
||||
webhookSelector?: string;
|
||||
fetchFn?: typeof fetch;
|
||||
}
|
||||
|
||||
@@ -191,7 +192,7 @@ export async function runRegressionTest(
|
||||
}
|
||||
|
||||
// 4. Resolve Target Webhook Channel in Test Corp
|
||||
const targetWebhook = await ensureTestWebhookIntegration(targetClient, targetCorp);
|
||||
const targetWebhook = await ensureTestWebhookIntegration(targetClient, targetCorp, options.webhookSelector);
|
||||
|
||||
// 5. Execute Batch Replay & HTTPS Run Polling
|
||||
const records: RegressionSampleRecord[] = [];
|
||||
|
||||
@@ -194,7 +194,7 @@ describe("sealTools", () => {
|
||||
expect(result.rules).toEqual([
|
||||
{
|
||||
id: "rule-1",
|
||||
code: 29,
|
||||
code: "#0029",
|
||||
status: "active",
|
||||
strictness: "MUST_FOLLOW",
|
||||
scope: "travel"
|
||||
@@ -645,10 +645,9 @@ describe("sealTools", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("approval run url returns Hose enterprise and document links by recordId", async () => {
|
||||
test("approval run url returns Seal result and Hose document links by recordId", async () => {
|
||||
const tool = sealTools.find((item) => item.name === "seal_approval_run_url_get");
|
||||
expect(tool).toBeDefined();
|
||||
primeHoseEnterpriseUrl("corp-a", "https://app.ekuaibao.com/web/home.html?accessToken=close-token");
|
||||
|
||||
const handler = tool!.handler as ToolHandler;
|
||||
const result = await handler(
|
||||
@@ -656,50 +655,74 @@ describe("sealTools", () => {
|
||||
{ recordId: "run-1" },
|
||||
fakeHoseContext()
|
||||
) as {
|
||||
enterpriseAssistUrl?: string;
|
||||
enterpriseUrl?: string;
|
||||
url?: string;
|
||||
sealResultUrl?: string;
|
||||
type?: string;
|
||||
mode?: string;
|
||||
hoseDomain?: string;
|
||||
documentUrl?: string;
|
||||
hoseDocumentUrl?: string;
|
||||
recordId?: string;
|
||||
sourceDocumentSN?: string;
|
||||
enterpriseAssistUrl?: string;
|
||||
enterpriseUrl?: string;
|
||||
hoseEnterpriseUrl?: string;
|
||||
};
|
||||
|
||||
expect(result).toMatchObject({
|
||||
url: "https://hose-corp-a.sealai.cc/approval-result/run-1",
|
||||
sealResultUrl: "https://hose-corp-a.sealai.cc/approval-result/run-1",
|
||||
type: "deep_link",
|
||||
enterpriseAssistUrl: "https://app.ekuaibao.com/web/home.html?accessToken=close-token",
|
||||
enterpriseUrl: "https://app.ekuaibao.com/web/home.html?accessToken=close-token",
|
||||
type: "seal_result",
|
||||
mode: "direct",
|
||||
hoseDomain: "https://app.ekuaibao.com",
|
||||
documentUrl: "https://app.ekuaibao.com/web/thirdparty.html",
|
||||
hoseDocumentUrl: "https://app.ekuaibao.com/web/thirdparty.html",
|
||||
recordId: "run-1",
|
||||
sourceDocumentSN: "B26001965"
|
||||
});
|
||||
expect(result.enterpriseAssistUrl).toBeUndefined();
|
||||
expect(result.enterpriseUrl).toBeUndefined();
|
||||
expect(result.hoseEnterpriseUrl).toBeUndefined();
|
||||
});
|
||||
|
||||
test("approval run url returns enterprise assist link without a document lookup", async () => {
|
||||
test("approval run url supports type=hose-document", async () => {
|
||||
const tool = sealTools.find((item) => item.name === "seal_approval_run_url_get");
|
||||
expect(tool).toBeDefined();
|
||||
|
||||
const handler = tool!.handler as ToolHandler;
|
||||
const result = await handler(
|
||||
fakeApprovalRunsClient(),
|
||||
{ recordId: "run-1", type: "hose-document" },
|
||||
fakeHoseContext()
|
||||
) as {
|
||||
url?: string;
|
||||
sealResultUrl?: string;
|
||||
hoseDocumentUrl?: string;
|
||||
type?: string;
|
||||
mode?: string;
|
||||
};
|
||||
|
||||
expect(result.type).toBe("hose_document");
|
||||
expect(result.mode).toBe("direct");
|
||||
expect(result.url).toBe("https://app.ekuaibao.com/web/thirdparty.html");
|
||||
expect(result.hoseDocumentUrl).toBe("https://app.ekuaibao.com/web/thirdparty.html");
|
||||
expect(result.sealResultUrl).toBe("https://hose-corp-a.sealai.cc/approval-result/run-1");
|
||||
});
|
||||
|
||||
test("approval run url throws error without a document lookup", async () => {
|
||||
const tool = sealTools.find((item) => item.name === "seal_approval_run_url_get");
|
||||
expect(tool).toBeDefined();
|
||||
primeHoseEnterpriseUrl("corp-a", "https://app.ekuaibao.com/web/home.html?accessToken=close-token");
|
||||
|
||||
const requests: string[] = [];
|
||||
const handler = tool!.handler as ToolHandler;
|
||||
const result = await handler(
|
||||
fakeApprovalRunsClient(requests),
|
||||
{},
|
||||
fakeHoseContext()
|
||||
) as {
|
||||
enterpriseAssistUrl?: string;
|
||||
enterpriseUrl?: string;
|
||||
documentUrl?: string;
|
||||
};
|
||||
|
||||
await expect(
|
||||
handler(
|
||||
fakeApprovalRunsClient(requests),
|
||||
{},
|
||||
fakeHoseContext()
|
||||
)
|
||||
).rejects.toThrow("recordId, sourceDocumentSN, or sourceDocumentId is required");
|
||||
expect(requests).toEqual([]);
|
||||
expect(result).toMatchObject({
|
||||
enterpriseAssistUrl: "https://app.ekuaibao.com/web/home.html?accessToken=close-token",
|
||||
enterpriseUrl: "https://app.ekuaibao.com/web/home.html?accessToken=close-token"
|
||||
});
|
||||
expect(result.documentUrl).toBeUndefined();
|
||||
});
|
||||
|
||||
test("approval run url can resolve by sourceDocumentSN", async () => {
|
||||
@@ -713,16 +736,17 @@ describe("sealTools", () => {
|
||||
fakeApprovalRunsClient(requests),
|
||||
{ sourceDocumentSN: "B26001965" },
|
||||
fakeHoseContext()
|
||||
) as { documentUrl?: string; url?: string; type?: string };
|
||||
) as { documentUrl?: string; url?: string; type?: string; mode?: string };
|
||||
|
||||
expect(requests[0]).toContain("search=B26001965");
|
||||
expect(requests[1]).toBe("api/v1/approvals/run-1");
|
||||
expect(result.documentUrl).toBe("https://app.ekuaibao.com/web/thirdparty.html");
|
||||
expect(result.type).toBe("deep_link");
|
||||
expect(result.type).toBe("seal_result");
|
||||
expect(result.mode).toBe("direct");
|
||||
expect(result.url).toBe("https://hose-corp-a.sealai.cc/approval-result/run-1");
|
||||
});
|
||||
|
||||
test("approval run url returns SSO link with identity, expiration, and warning when sso=true", async () => {
|
||||
test("approval run url returns auto_login link with identity, expiration, and warning when autoLogin=true", async () => {
|
||||
const tool = sealTools.find((item) => item.name === "seal_approval_run_url_get");
|
||||
expect(tool).toBeDefined();
|
||||
primeHoseEnterpriseUrl("corp-a", "https://app.ekuaibao.com/web/home.html?accessToken=close-token");
|
||||
@@ -730,18 +754,20 @@ describe("sealTools", () => {
|
||||
const handler = tool!.handler as ToolHandler;
|
||||
const result = (await handler(
|
||||
fakeApprovalRunsClient(),
|
||||
{ recordId: "run-1", sso: true, expiresIn: 3600 },
|
||||
{ recordId: "run-1", autoLogin: true, expiresIn: 3600 },
|
||||
fakeHoseContext()
|
||||
)) as {
|
||||
url?: string;
|
||||
ssoUrl?: string;
|
||||
type?: string;
|
||||
mode?: string;
|
||||
expiresIn?: number;
|
||||
warning?: string;
|
||||
identity?: { staffId?: string };
|
||||
};
|
||||
|
||||
expect(result.type).toBe("sso_link");
|
||||
expect(result.type).toBe("seal_result");
|
||||
expect(result.mode).toBe("auto_login");
|
||||
expect(result.expiresIn).toBe(3600);
|
||||
expect(result.url).toContain("/api/auth/oauth2/session/oem-hosecloud?token=close-token");
|
||||
expect(result.url).toContain("path=%2Fapproval-result%2Frun-1");
|
||||
@@ -749,6 +775,31 @@ describe("sealTools", () => {
|
||||
expect(result.identity?.staffId).toBe("staff-a");
|
||||
});
|
||||
|
||||
test("approval run url supports legacy hoseSso=true with explicit hose attribute naming", async () => {
|
||||
const tool = sealTools.find((item) => item.name === "seal_approval_run_url_get");
|
||||
expect(tool).toBeDefined();
|
||||
primeHoseEnterpriseUrl("corp-a", "https://app.ekuaibao.com/web/home.html?accessToken=close-token");
|
||||
|
||||
const handler = tool!.handler as ToolHandler;
|
||||
const result = (await handler(
|
||||
fakeApprovalRunsClient(),
|
||||
{ recordId: "run-1", hoseSso: true },
|
||||
fakeHoseContext()
|
||||
)) as {
|
||||
type?: string;
|
||||
mode?: string;
|
||||
url?: string;
|
||||
hoseDocumentUrl?: string;
|
||||
hoseEnterpriseUrl?: string;
|
||||
};
|
||||
|
||||
expect(result.type).toBe("seal_result");
|
||||
expect(result.mode).toBe("auto_login");
|
||||
expect(result.url).toContain("/api/auth/oauth2/session/oem-hosecloud?token=close-token");
|
||||
expect(result.hoseDocumentUrl).toBe("https://app.ekuaibao.com/web/thirdparty.html");
|
||||
expect(result.hoseEnterpriseUrl).toBeUndefined();
|
||||
});
|
||||
|
||||
test("approval run url throws clear error when sso=true is used on non-hose enterprise", async () => {
|
||||
const tool = sealTools.find((item) => item.name === "seal_approval_run_url_get");
|
||||
expect(tool).toBeDefined();
|
||||
@@ -760,7 +811,7 @@ describe("sealTools", () => {
|
||||
{ recordId: "run-1", sso: true },
|
||||
fakeContext()
|
||||
)
|
||||
).rejects.toThrow("SSO direct links currently support Hose-integrated enterprises");
|
||||
).rejects.toThrow("direct links currently support Hose-integrated enterprises");
|
||||
});
|
||||
|
||||
test("approval run summary filters by local date and returns compact aggregates", async () => {
|
||||
|
||||
+60
-31
@@ -3,7 +3,7 @@ import { KyInstance } from "ky";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import * as api from "./api.js";
|
||||
import { defaultSealUrl, ensureHoseCloseApiToken, getHoseEnterpriseUrl, getHoseProvisionalAuthLink, probeHoseDomain } from "../../core/auth/hose.js";
|
||||
import { defaultSealUrl, ensureHoseCloseApiToken, getHoseProvisionalAuthLink, probeHoseDomain } from "../../core/auth/hose.js";
|
||||
import { CorpConfig } from "../../core/config/types.js";
|
||||
import { loadGlobalConfig, loadCorpConfigs, getEnterprisesDirCandidates } from "../../core/config/loader.js";
|
||||
import { resolveCorpConfig } from "../../core/config/manager.js";
|
||||
@@ -834,7 +834,7 @@ export const sealTools = [
|
||||
await api.deleteApprovalRule(client, rule.id);
|
||||
}
|
||||
|
||||
const created: Array<{ id: string; description: string; code?: number }> = [];
|
||||
const created: Array<{ id: string; description: string; code?: string | number }> = [];
|
||||
for (const rule of plan.created) {
|
||||
const newRule = await api.createApprovalRule(client, {
|
||||
description: rule.description,
|
||||
@@ -1739,13 +1739,16 @@ export const sealTools = [
|
||||
},
|
||||
{
|
||||
name: "seal_approval_run_url_get",
|
||||
description: "获取审批单的 Web 控制台直达链接或合思企业协助链接,支持纯深度链接与带安全警告的免密 SSO 链接",
|
||||
description: "获取审批单的 Web 链接(支持 seal-result 审核页与 hose-document 原单据页,支持 --auto-login 免密直达)",
|
||||
parameters: z.object({
|
||||
recordId: z.string().optional().describe("Seal approval run record ID"),
|
||||
sourceDocumentSN: z.string().optional().describe("合思/易快报单号"),
|
||||
sourceDocumentId: z.string().optional().describe("合思/易快报源单据 ID"),
|
||||
sso: z.boolean().optional().describe("是否生成带临时认证凭证的免密直达链接 (SSO link)"),
|
||||
expiresIn: z.number().optional().describe("SSO 免密凭证有效秒数,默认 7200 (2小时)")
|
||||
type: z.string().optional().describe("链接类型:'seal-result' (Seal AI 审核页,默认) 或 'hose-document' (合思原单据页)"),
|
||||
autoLogin: z.boolean().optional().describe("是否生成带临时认证凭证的免密直达链接"),
|
||||
sso: z.boolean().optional().describe("是否生成带临时认证凭证的免密直达链接 (兼容别名)"),
|
||||
hoseSso: z.boolean().optional().describe("通过合思 OEM 换票生成直达该单据审核详情的免密直达链接 (兼容别名)"),
|
||||
expiresIn: z.number().optional().describe("免密凭证有效秒数,默认 7200 (2小时)")
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
@@ -1753,32 +1756,43 @@ export const sealTools = [
|
||||
recordId?: string;
|
||||
sourceDocumentSN?: string;
|
||||
sourceDocumentId?: string;
|
||||
type?: string;
|
||||
autoLogin?: boolean;
|
||||
sso?: boolean;
|
||||
hoseSso?: boolean;
|
||||
expiresIn?: number;
|
||||
},
|
||||
context: ToolContext
|
||||
) => {
|
||||
const hasDocumentLookup = Boolean(params.recordId || params.sourceDocumentSN || params.sourceDocumentId);
|
||||
const record = hasDocumentLookup ? await resolveApprovalRunForUrl(client, params) : undefined;
|
||||
if (!hasDocumentLookup) {
|
||||
throw new Error("recordId, sourceDocumentSN, or sourceDocumentId is required to generate approval run link");
|
||||
}
|
||||
const record = await resolveApprovalRunForUrl(client, params);
|
||||
const source = context.corp.source;
|
||||
const enterpriseAssistUrl = source.type === "hose" ? await getHoseEnterpriseUrl(context.corp) : undefined;
|
||||
const documentUrl = stringFromUnknown(record?.sourceExtendData?.hosecloudViewUrl);
|
||||
const hoseDocumentUrl = stringFromUnknown(record?.sourceExtendData?.hosecloudViewUrl);
|
||||
|
||||
const sealBaseUrl = resolveSealBaseUrl(context.corp);
|
||||
const sealResultUrl = record?.id ? `${sealBaseUrl}/approval-result/${record.id}` : undefined;
|
||||
const sealResultUrl = `${sealBaseUrl}/approval-result/${record.id}`;
|
||||
|
||||
const rawType = (params.type ?? "seal-result").toLowerCase().replace(/_/g, "-");
|
||||
const isHoseDoc = rawType === "hose-document" || rawType === "source-document" || rawType === "hose";
|
||||
const linkType = isHoseDoc ? "hose_document" : "seal_result";
|
||||
|
||||
const useAutoLogin = Boolean(params.autoLogin ?? params.hoseSso ?? params.sso);
|
||||
const expiresIn = params.expiresIn ?? 7200;
|
||||
|
||||
let ssoUrl: string | undefined;
|
||||
let identity: { name?: string; staffId?: string; isAdmin?: boolean; providerUserId?: string } | undefined;
|
||||
let warning: string | undefined;
|
||||
const expiresIn = params.expiresIn ?? 7200;
|
||||
|
||||
if (params.sso) {
|
||||
if (!record?.id) {
|
||||
throw new Error("recordId or sourceDocumentSN is required to generate an SSO approval result URL");
|
||||
if (useAutoLogin) {
|
||||
if (isHoseDoc) {
|
||||
throw new Error("Auto-login (--auto-login) is only supported for Seal AI audit link (type: seal-result)");
|
||||
}
|
||||
if (source.type !== "hose") {
|
||||
throw new Error(
|
||||
`SSO direct links currently support Hose-integrated enterprises (corp '${context.corp.id}' uses '${source.type}'). For Seal-native enterprises, use 'seal-use delegation create' for authorized access.`
|
||||
`Auto-login direct links currently support Hose-integrated enterprises (corp '${context.corp.id}' uses '${source.type}'). For Seal-native enterprises, use 'seal-use auth link' for authorized access.`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1810,7 +1824,7 @@ export const sealTools = [
|
||||
warning = `⚠️ 安全警示:该链接使用 [${userName}${roleLabel}] 身份签发,在 Seal AI 拥有全站操作权限。链接具备 ${Math.round(expiresIn / 3600 * 10) / 10} 小时时效,仅供受信任人员排查使用,请勿在外部公开分享。`;
|
||||
|
||||
console.error(
|
||||
`⚠️ 安全警示 (SSO 强化免密链接):\n` +
|
||||
`⚠️ 安全警示 (免密直达链接):\n` +
|
||||
`• 身份主体:${userName}${roleLabel}\n` +
|
||||
`• 权限范围:持有该链接者在 Seal AI 中拥有该用户的完整操作权限(含系统设置与规则编辑)\n` +
|
||||
`• 时效性:换票凭证有效时间 ${expiresIn} 秒(${Math.round(expiresIn / 60)} 分钟),在浏览器打开后将保留 30 天会话\n` +
|
||||
@@ -1818,25 +1832,28 @@ export const sealTools = [
|
||||
);
|
||||
}
|
||||
|
||||
const activeUrl = isHoseDoc ? hoseDocumentUrl : (useAutoLogin ? ssoUrl : sealResultUrl);
|
||||
const activeMode = useAutoLogin ? "auto_login" : "direct";
|
||||
|
||||
return {
|
||||
url: params.sso ? ssoUrl : sealResultUrl,
|
||||
url: activeUrl,
|
||||
type: linkType,
|
||||
mode: activeMode,
|
||||
sealResultUrl,
|
||||
hoseDocumentUrl,
|
||||
// Legacy compatibility fields
|
||||
documentUrl: hoseDocumentUrl,
|
||||
ssoUrl,
|
||||
type: params.sso ? "sso_link" : "deep_link",
|
||||
expiresIn: params.sso ? expiresIn : undefined,
|
||||
expiresIn: useAutoLogin ? expiresIn : undefined,
|
||||
identity,
|
||||
warning,
|
||||
enterpriseAssistUrl,
|
||||
enterpriseUrl: enterpriseAssistUrl,
|
||||
hoseDomain: source.type === "hose" ? normalizeUrl(source.domain) : undefined,
|
||||
documentUrl,
|
||||
recordId: record?.id,
|
||||
sourceDocumentSN: record?.sourceDocumentSN,
|
||||
sourceDocumentId: record?.sourceDocumentId,
|
||||
sourceSystem: record?.sourceSystem,
|
||||
recordId: record.id,
|
||||
sourceDocumentSN: record.sourceDocumentSN,
|
||||
sourceDocumentId: record.sourceDocumentId,
|
||||
sourceSystem: record.sourceSystem,
|
||||
missing: {
|
||||
enterpriseAssistUrl: enterpriseAssistUrl ? undefined : "Current enterprise source is not Hose, so no Hose enterprise assist URL is configured.",
|
||||
documentUrl: hasDocumentLookup && !documentUrl ? "sourceExtendData.hosecloudViewUrl is absent from the approval run detail." : undefined
|
||||
hoseDocumentUrl: !hoseDocumentUrl ? "sourceExtendData.hosecloudViewUrl is absent from the approval run detail." : undefined
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -1999,9 +2016,9 @@ export const sealTools = [
|
||||
next: {
|
||||
status: `seal-use simulation status ${result.batchId}`,
|
||||
wait: `seal-use simulation wait ${result.batchId}`,
|
||||
getBatch: "seal-home simulation get <batchId>",
|
||||
getRecords: "seal-home simulation batch-records <batchId>",
|
||||
listBatches: "seal-home simulation list"
|
||||
getBatch: `seal-use simulation get ${result.batchId}`,
|
||||
getRecords: `seal-use simulation batch-records ${result.batchId}`,
|
||||
listBatches: "seal-use simulation list"
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -2892,7 +2909,19 @@ function pickRuleFields(rule: ApprovalRule, fields: readonly RuleField[]) {
|
||||
const output: Partial<ApprovalRule> = {};
|
||||
for (const field of fields) {
|
||||
if (rule[field] !== undefined) {
|
||||
output[field] = rule[field] as never;
|
||||
if (field === "code") {
|
||||
const val = rule.code;
|
||||
if (typeof val === "number") {
|
||||
output.code = formatRuleCode(val) as never;
|
||||
} else if (typeof val === "string") {
|
||||
const digits = val.match(/\d+/)?.[0];
|
||||
output.code = (digits ? formatRuleCode(Number(digits)) : val) as never;
|
||||
} else {
|
||||
output.code = val as never;
|
||||
}
|
||||
} else {
|
||||
output[field] = rule[field] as never;
|
||||
}
|
||||
}
|
||||
}
|
||||
return output;
|
||||
|
||||
@@ -74,7 +74,7 @@ export const SealSessionDataSchema = z.object({
|
||||
export const ApprovalRuleSchema = z.object({
|
||||
id: z.string(),
|
||||
tenantId: z.string().optional(),
|
||||
code: z.number().optional(),
|
||||
code: z.union([z.number(), z.string()]).optional(),
|
||||
description: z.string(),
|
||||
scope: z.string(),
|
||||
strictness: z.string(),
|
||||
|
||||
@@ -360,4 +360,120 @@ describe("webhook-replay domain", () => {
|
||||
expect(savedIntegration.name).toBe("(Seal测-回放通道)");
|
||||
});
|
||||
});
|
||||
|
||||
describe("executeApprovalRunsReplay sn matching", () => {
|
||||
test("matches exact sourceDocumentSN even if search returns multiple candidates", async () => {
|
||||
const sourceCorp = {
|
||||
id: "source-corp",
|
||||
name: "源企业",
|
||||
environment: "production",
|
||||
seal: { url: "https://source.sealai.cc" },
|
||||
source: { type: "seal", sealUrl: "https://source.sealai.cc", token: "tok", expiresIn: 3600 }
|
||||
} as unknown as CorpConfig;
|
||||
|
||||
const targetCorp = {
|
||||
id: "target-corp",
|
||||
name: "目标测试企业",
|
||||
environment: "test",
|
||||
seal: { url: "https://target.sealai.cc" },
|
||||
source: { type: "seal", sealUrl: "https://target.sealai.cc", token: "tok", expiresIn: 3600 }
|
||||
} as unknown as CorpConfig;
|
||||
|
||||
const mockSourceClient: any = {
|
||||
get: (url: string) => {
|
||||
if (url.includes("api/v1/approvals")) {
|
||||
return {
|
||||
json: async () => ({
|
||||
data: {
|
||||
records: [
|
||||
{
|
||||
id: "run-001",
|
||||
sourceDocumentSN: "SN12345-OTHER",
|
||||
sourceDocumentId: "DOC-OTHER",
|
||||
status: "APPROVED"
|
||||
},
|
||||
{
|
||||
id: "run-002",
|
||||
sourceDocumentSN: "SN12345",
|
||||
sourceDocumentId: "DOC-EXACT",
|
||||
status: "TERMINATED"
|
||||
}
|
||||
]
|
||||
}
|
||||
})
|
||||
};
|
||||
}
|
||||
return { json: async () => ({ data: {} }) };
|
||||
}
|
||||
};
|
||||
|
||||
const mockTargetClient: any = {
|
||||
get: () => ({
|
||||
json: async () => ({ data: { integrations: [mockWebhookIntegration] } })
|
||||
})
|
||||
};
|
||||
|
||||
const result = await executeApprovalRunsReplay({
|
||||
sourceClient: mockSourceClient,
|
||||
targetClient: mockTargetClient,
|
||||
sourceCorp,
|
||||
targetCorp,
|
||||
query: { sn: "SN12345" },
|
||||
dryRun: true
|
||||
});
|
||||
|
||||
expect(result.totalCount).toBe(1);
|
||||
expect(result.records[0]?.originalRecord.id).toBe("run-002");
|
||||
expect(result.records[0]?.originalRecord.sourceDocumentSN).toBe("SN12345");
|
||||
});
|
||||
|
||||
test("throws clear error when sn is not found in search results", async () => {
|
||||
const sourceCorp = {
|
||||
id: "source-corp",
|
||||
name: "源企业",
|
||||
environment: "production",
|
||||
source: { type: "seal", sealUrl: "https://source.sealai.cc", token: "tok", expiresIn: 3600 }
|
||||
} as unknown as CorpConfig;
|
||||
|
||||
const targetCorp = {
|
||||
id: "target-corp",
|
||||
name: "目标测试企业",
|
||||
environment: "test",
|
||||
source: { type: "seal", sealUrl: "https://target.sealai.cc", token: "tok", expiresIn: 3600 }
|
||||
} as unknown as CorpConfig;
|
||||
|
||||
const mockSourceClient: any = {
|
||||
get: () => ({
|
||||
json: async () => ({
|
||||
data: {
|
||||
records: [
|
||||
{
|
||||
id: "run-001",
|
||||
sourceDocumentSN: "SN99999",
|
||||
status: "APPROVED"
|
||||
}
|
||||
]
|
||||
}
|
||||
})
|
||||
})
|
||||
};
|
||||
|
||||
const mockTargetClient: any = {
|
||||
get: () => ({
|
||||
json: async () => ({ data: { integrations: [mockWebhookIntegration] } })
|
||||
})
|
||||
};
|
||||
|
||||
expect(
|
||||
executeApprovalRunsReplay({
|
||||
sourceClient: mockSourceClient,
|
||||
targetClient: mockTargetClient,
|
||||
sourceCorp,
|
||||
targetCorp,
|
||||
query: { sn: "SN-NOT-FOUND" },
|
||||
dryRun: true
|
||||
})
|
||||
).rejects.toThrow("在企业「源企业」中未找到单据编号为「SN-NOT-FOUND」的审批记录。");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -423,18 +423,40 @@ export async function executeApprovalRunsReplay(
|
||||
runs.push(await api.getApprovalRun(sourceClient, id));
|
||||
}
|
||||
} else if (query.sn) {
|
||||
const search = await api.listApprovalRuns(sourceClient, { sourceDocumentSN: query.sn, limit: 1 });
|
||||
if (!search.records.length) {
|
||||
const search = await api.listApprovalRuns(sourceClient, {
|
||||
search: query.sn,
|
||||
sourceDocumentSN: query.sn,
|
||||
limit: 20
|
||||
});
|
||||
const matched = search.records.find(
|
||||
(r) =>
|
||||
r.sourceDocumentSN === query.sn ||
|
||||
r.sourceDocumentId === query.sn ||
|
||||
(r.document as any)?.sourceDocumentSN === query.sn ||
|
||||
(r.document as any)?.sn === query.sn
|
||||
);
|
||||
if (!matched) {
|
||||
throw new Error(`在企业「${sourceCorp.name}」中未找到单据编号为「${query.sn}」的审批记录。`);
|
||||
}
|
||||
runs.push(search.records[0]!);
|
||||
runs.push(matched);
|
||||
} else if (query.sns && query.sns.length > 0) {
|
||||
for (const sn of query.sns) {
|
||||
const search = await api.listApprovalRuns(sourceClient, { sourceDocumentSN: sn, limit: 1 });
|
||||
if (!search.records.length) {
|
||||
const search = await api.listApprovalRuns(sourceClient, {
|
||||
search: sn,
|
||||
sourceDocumentSN: sn,
|
||||
limit: 20
|
||||
});
|
||||
const matched = search.records.find(
|
||||
(r) =>
|
||||
r.sourceDocumentSN === sn ||
|
||||
r.sourceDocumentId === sn ||
|
||||
(r.document as any)?.sourceDocumentSN === sn ||
|
||||
(r.document as any)?.sn === sn
|
||||
);
|
||||
if (!matched) {
|
||||
throw new Error(`在企业「${sourceCorp.name}」中未找到单据编号为「${sn}」的审批记录。`);
|
||||
}
|
||||
runs.push(search.records[0]!);
|
||||
runs.push(matched);
|
||||
}
|
||||
} else if (query.limit !== undefined) {
|
||||
const search = await api.listApprovalRuns(sourceClient, {
|
||||
|
||||
Reference in new issue
Block a user