Files
seal-use/src/domains/seal/simulation.test.ts
T

607 lines
21 KiB
TypeScript

import { describe, expect, test } from "bun:test";
import { KyInstance } from "ky";
import { CorpConfig } from "../../core/config/types.js";
import {
createMaterialPackBatch,
createSimulationBatch,
getSimulationBatch,
getSimulationIntegrationStatus,
listSimulationBatches,
listSimulationHosecloudIntegrations,
listSimulationTemplates,
uploadMaterialPackage
} from "./api.js";
import { buildSimulationBatchParams, sealTools } from "./tools.js";
import {
MaterialPackageSchema,
SimulationBatchSchema,
SimulationIntegrationStatusSchema,
SimulationTemplateSchema
} from "./types.js";
type ToolHandler = (
client: KyInstance,
params: Record<string, unknown>,
context: { corp: CorpConfig }
) => Promise<unknown>;
// Fixtures captured from xiezihao staging console traffic (2026-08-24).
// Real tenant signKey is redacted; capture the value locally if needed.
const SIGN_KEY = "test-sign-key";
const hosecloudBatchFixture = {
id: "01a032f6-9798-7021-a632-f9fffb48f463",
tenantId: "019ef38b-b80a-732e-abb6-8bcb62a373a9",
approvalCode: "hosecloud",
nodeId: "hosecloud",
sourceSystem: "hosecloud",
status: "syncing",
totalCount: 0,
processedCount: 0,
successCount: 0,
failedCount: 0,
createdCount: 0,
createFailedCount: 0,
params: {
approvalCode: "hosecloud",
nodeId: "hosecloud",
startTime: 0,
endTime: 0,
limit: 1,
skipInvoiceGeneration: true,
skipExpenseExtraction: true,
disableAttachmentCache: false,
dataCollectionMode: "2",
flowIds: ["B26017701"],
signKey: SIGN_KEY,
rejectNodeName: null,
thinkingDepthOverride: "medium"
},
requestSummary: {
mode: "指定单号",
conditions: [
{ label: "取数模式", value: "指定单号" },
{ label: "指定单号数量", value: "1" }
]
},
resultSummary: null,
createdAt: "2026-08-24T08:50:16.600Z",
updatedAt: "2026-08-24T08:50:16.606Z"
};
const templateFixture = {
id: "019ef84b-1065-71f8-b916-c6592d869fd3",
tenantId: "019ef38b-b80a-732e-abb6-8bcb62a373a9",
name: "ack11",
description: "find",
approvalSystem: "hosecloud",
hosecloudConfig: {
dataCollectionMode: "2",
flowIds: ["B26022501", "B26028572"],
rejectNodeName: null,
skipInvoiceGeneration: false,
skipExpenseExtraction: true
},
createdAt: "2026-06-24T06:22:09.507Z",
updatedAt: "2026-06-24T06:22:09.507Z"
};
const integrationStatusFixture = {
hasFeishu: false,
hasHosecloud: true,
hasWeaver: false,
hasHelios: false,
hasMaycur: false,
hasMaycurStandard: false
};
const materialPackageUploadFixture = {
id: "019fcae7-21f5-73fc-8bf1-cfff0a464607",
tenantId: "019ef38b-b80a-732e-abb6-8bcb62a373a9",
name: "测试材料包",
templateId: "conference_reimbursement_v1",
originalFileName: "测试材料包.zip",
status: "ready",
documentCount: 2,
attachmentCount: 18,
uploadedBy: "019ef38b-b850-768e-bbbf-bee26b81416a",
schemaConfig: {
id: "conference_reimbursement_v1",
listSheets: [
{
columns: [
{ key: "code", type: "AMOUNT", label: "费类code", column: "费类code" },
{ key: "feiyongleixing", type: "TEXT", label: "费用类型", column: "费用类型" },
{ key: "jine", type: "AMOUNT", label: "金额", column: "金额" }
],
fieldKey: "sheet1_list",
keyColumn: "会议编号",
sheetName: "Sheet1",
fieldLabel: "Sheet1列表"
}
],
mainColumns: [
{ key: "huiyibianhao", type: "TEXT", label: "会议编号", column: "会议编号" },
{ key: "tijiaoren", type: "TEXT", label: "提交人", column: "提交人" },
{ key: "shifouyiwancheng", type: "TEXT", label: "是否已完成", column: "是否已完成" },
{ key: "jine", type: "AMOUNT", label: "金额", column: "金额" }
],
workbookName: "信息表.xlsx",
mainKeyColumn: "会议编号",
mainSheetName: "会议",
attachmentFieldKey: "supporting_files",
attachmentFieldLabel: "支撑材料"
},
createdAt: "2026-08-04T03:52:52.979Z",
updatedAt: "2026-08-04T04:07:12.368Z"
};
function fakeContext(): { corp: CorpConfig } {
return {
corp: {
id: "xiezihao",
name: "谢子豪的测试环境",
seal: {
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
},
source: {
type: "seal",
token: "token",
sealUrl: "https://xiezihao.staging.sealai.cc",
expiresIn: 3600,
staffId: "test"
}
} as CorpConfig
};
}
describe("buildSimulationBatchParams", () => {
test("builds hosecloud request payload matching the captured create-batch body", () => {
const params = buildSimulationBatchParams({
mode: "hosecloud",
flowIds: ["B26017701"],
skipInvoiceGeneration: true,
skipExpenseExtraction: true,
disableAttachmentCache: false,
rejectNodeName: null,
thinkingDepthOverride: "default",
signKey: SIGN_KEY
});
expect(params).toEqual({
dataCollectionMode: "2",
rejectNodeName: null,
skipInvoiceGeneration: true,
skipExpenseExtraction: true,
disableAttachmentCache: false,
thinkingDepthOverride: "default",
sourceSystem: "hosecloud",
flowIds: ["B26017701"],
signKey: SIGN_KEY
});
// approvalCode/nodeId/limit/startTime/endTime 由服务端从请求推导,不进请求体
expect(params).not.toHaveProperty("approvalCode");
expect(params).not.toHaveProperty("nodeId");
expect(params).not.toHaveProperty("limit");
expect(params).not.toHaveProperty("startTime");
expect(params).not.toHaveProperty("endTime");
});
test("supports node override and deep thinking depth", () => {
const params = buildSimulationBatchParams({
mode: "hosecloud",
flowIds: ["B26010080", "B25011446"],
skipExpenseExtraction: false,
disableAttachmentCache: true,
rejectNodeName: "财务",
thinkingDepthOverride: "high",
signKey: SIGN_KEY
});
expect(params).toMatchObject({
flowIds: ["B26010080", "B25011446"],
skipInvoiceGeneration: true,
skipExpenseExtraction: false,
disableAttachmentCache: true,
rejectNodeName: "财务",
thinkingDepthOverride: "high"
});
expect(params).not.toHaveProperty("limit");
});
test("builds material_pack payload with the confirmed schema config", () => {
const params = buildSimulationBatchParams({
mode: "material_pack",
packageIds: ["019fd15c-13a6-748f-8cdd-73e2da60252a"],
templateId: "conference_reimbursement_v1",
skipInvoiceGeneration: true,
skipExpenseExtraction: true,
schemaConfig: {
id: "conference_reimbursement_v1",
mainColumns: [
{ key: "huiyibianhao", type: "TEXT", label: "会议编号", column: "会议编号" }
],
listSheets: [],
workbookName: "信息表.xlsx",
mainKeyColumn: "会议编号",
mainSheetName: "Sheet1",
attachmentFieldKey: "supporting_files",
attachmentFieldLabel: "支撑材料"
}
});
expect(params).toMatchObject({
templateId: "conference_reimbursement_v1",
packageIds: ["019fd15c-13a6-748f-8cdd-73e2da60252a"],
approvalCode: "material_pack",
nodeId: "material_pack",
runMode: "import_and_simulate",
skipInvoiceGeneration: true,
skipExpenseExtraction: true,
disableAttachmentCache: false,
thinkingDepthOverride: "default",
schemaConfig: {
id: "conference_reimbursement_v1",
mainKeyColumn: "会议编号",
attachmentFieldKey: "supporting_files"
}
});
// 材料包走独立端点, 请求体不带合思专属字段和服务端推导字段
expect(params).not.toHaveProperty("sourceSystem");
expect(params).not.toHaveProperty("flowIds");
expect(params).not.toHaveProperty("dataCollectionMode");
expect(params).not.toHaveProperty("rejectNodeName");
expect(params).not.toHaveProperty("limit");
expect(params).not.toHaveProperty("packageLabel");
});
test("derives templateId from schemaConfig.id when omitted", () => {
const params = buildSimulationBatchParams({
mode: "material_pack",
packageIds: ["019fd15c-13a6-748f-8cdd-73e2da60252a"],
schemaConfig: { id: "conference_reimbursement_v1", mainSheetName: "Sheet1" }
});
expect(params).toMatchObject({
templateId: "conference_reimbursement_v1",
packageIds: ["019fd15c-13a6-748f-8cdd-73e2da60252a"],
approvalCode: "material_pack"
});
});
test("rawParams can introduce reserved time-range fields", () => {
const params = buildSimulationBatchParams({
mode: "hosecloud",
flowIds: ["B26017701"],
signKey: SIGN_KEY,
rawParams: { startTime: 1786000000000, endTime: 1787000000000 }
});
expect(params).toMatchObject({
startTime: 1786000000000,
endTime: 1787000000000
});
});
test("supports weaver platform params", () => {
const params = buildSimulationBatchParams({
sourceSystem: "weaver",
workflowTypeId: "wf-1",
requestIds: ["req-101", "req-102"],
rejectNodeName: "财务审核"
});
expect(params).toMatchObject({
sourceSystem: "weaver",
workflowTypeId: "wf-1",
requestIds: ["req-101", "req-102"],
rejectNodeName: "财务审核"
});
});
test("supports helios platform params", () => {
const params = buildSimulationBatchParams({
sourceSystem: "helios",
documentType: "EXPENSE_REPORT",
businessCodes: ["HLY001", "HLY002"]
});
expect(params).toMatchObject({
sourceSystem: "helios",
documentType: "EXPENSE_REPORT",
businessCodes: ["HLY001", "HLY002"]
});
});
test("supports maycur platform params", () => {
const params = buildSimulationBatchParams({
sourceSystem: "maycur",
formCodes: ["MC001"],
signKey: SIGN_KEY
});
expect(params).toMatchObject({
sourceSystem: "maycur",
formCodes: ["MC001"],
signKey: SIGN_KEY
});
});
test("rejects hosecloud mode without flowIds", () => {
expect(() => buildSimulationBatchParams({ mode: "hosecloud", signKey: SIGN_KEY }))
.toThrow("hosecloud 模式需要提供 flowIds");
});
test("rejects material_pack mode without packageIds", () => {
expect(() => buildSimulationBatchParams({ mode: "material_pack" }))
.toThrow("material_pack 模式需要提供 packageIds");
});
});
describe("simulation API client", () => {
test("creates a batch by POSTing to create-batch", async () => {
let postedUrl = "";
let postedBody: Record<string, unknown> | undefined;
const client = {
post: (url: string, options: { json: Record<string, unknown> }) => {
postedUrl = url;
postedBody = options.json;
return { json: async () => ({ data: { batchId: "01a032f6-9798-7021-a632-f9fffb48f463" } }) };
}
} as unknown as KyInstance;
const result = await createSimulationBatch(client, { approvalCode: "hosecloud" });
expect(postedUrl).toBe("api/v1/simulation/create-batch");
expect(postedBody).toEqual({ approvalCode: "hosecloud" });
expect(result.batchId).toBe("01a032f6-9798-7021-a632-f9fffb48f463");
});
test("creates a material pack batch via its own endpoint", async () => {
let postedUrl = "";
const client = {
post: (url: string, options: { json: Record<string, unknown> }) => {
postedUrl = url;
expect(options.json).toMatchObject({ templateId: "conference_reimbursement_v1" });
return { json: async () => ({ data: { batchId: "material-batch-1" } }) };
}
} as unknown as KyInstance;
const result = await createMaterialPackBatch(client, { templateId: "conference_reimbursement_v1" });
expect(postedUrl).toBe("api/v1/simulation/create-material-pack-batch");
expect(result.batchId).toBe("material-batch-1");
});
test("lists batches with a limit query", async () => {
let requestedUrl = "";
let requestedParams: Record<string, string> | undefined;
const client = {
get: (url: string, options?: { searchParams?: Record<string, string> }) => {
requestedUrl = url;
requestedParams = options?.searchParams;
return { json: async () => ({ data: [hosecloudBatchFixture] }) };
}
} as unknown as KyInstance;
const result = await listSimulationBatches(client, { limit: 10 });
expect(requestedUrl).toBe("api/v1/simulation/batches");
expect(requestedParams).toEqual({ limit: "10" });
expect(result).toHaveLength(1);
expect(result[0]!.id).toBe("01a032f6-9798-7021-a632-f9fffb48f463");
});
test("gets batch detail and templates", async () => {
const client = {
get: (url: string) => {
if (url === "api/v1/simulation/batch/01a032f6-9798-7021-a632-f9fffb48f463") {
return { json: async () => ({ data: hosecloudBatchFixture }) };
}
if (url === "api/v1/simulation/templates") {
return { json: async () => ({ data: [templateFixture] }) };
}
throw new Error(`unexpected url ${url}`);
}
} as unknown as KyInstance;
const batch = await getSimulationBatch(client, "01a032f6-9798-7021-a632-f9fffb48f463");
expect(batch.params?.flowIds).toEqual(["B26017701"]);
expect(batch.requestSummary?.mode).toBe("指定单号");
const templates = await listSimulationTemplates(client);
expect(templates).toHaveLength(1);
expect(templates[0]!.name).toBe("ack11");
});
test("uploads a material package as multipart with the file field", async () => {
let postedUrl = "";
let postedBody: unknown;
const client = {
post: (url: string, options: { body: unknown }) => {
postedUrl = url;
postedBody = options.body;
return { json: async () => ({ data: materialPackageUploadFixture }) };
}
} as unknown as KyInstance;
const result = await uploadMaterialPackage(client, {
fileName: "测试材料包.zip",
fileBuffer: new Uint8Array([1, 2, 3])
});
expect(postedUrl).toBe("api/v1/material-packages/upload");
expect(postedBody).toBeInstanceOf(FormData);
const entry = (postedBody as FormData).get("file");
expect(entry).toBeInstanceOf(File);
expect((entry as File).name).toBe("测试材料包.zip");
expect(result.id).toBe("019fcae7-21f5-73fc-8bf1-cfff0a464607");
expect(result.schemaConfig?.mainKeyColumn).toBe("会议编号");
});
test("gets integration status and hosecloud integrations", async () => {
const client = {
get: (url: string) => {
if (url === "api/v1/simulation/integration-status") {
return { json: async () => ({ data: integrationStatusFixture }) };
}
if (url === "api/v1/simulation/hosecloud-integrations") {
return {
json: async () => ({
data: [{ signKey: SIGN_KEY, displayName: "大黄蜂-测试-不要配置到审批流", corporationId: "ID01Nl1kQVYbKL" }]
})
};
}
throw new Error(`unexpected url ${url}`);
}
} as unknown as KyInstance;
const status = await getSimulationIntegrationStatus(client);
expect(status.hasHosecloud).toBe(true);
expect(status.hasFeishu).toBe(false);
const integrations = await listSimulationHosecloudIntegrations(client);
expect(integrations[0]!.signKey).toBe(SIGN_KEY);
});
});
describe("simulation tool handlers", () => {
test("create tool resolves signKey automatically and posts the payload", async () => {
const tool = sealTools.find((item) => item.name === "seal_simulation_batch_create");
expect(tool).toBeDefined();
let postedBody: Record<string, unknown> | undefined;
let assertPosted = false;
const client = {
get: (url: string) => {
if (url === "api/v1/simulation/hosecloud-integrations") {
return {
json: async () => ({
data: [{ signKey: SIGN_KEY, displayName: "大黄蜂-测试" }]
})
};
}
throw new Error(`unexpected url ${url}`);
},
post: (url: string, options: { json: Record<string, unknown> }) => {
assertPosted = url === "api/v1/simulation/create-batch";
postedBody = options.json;
return { json: async () => ({ data: { batchId: "batch-1" } }) };
}
} as unknown as KyInstance;
const handler = tool!.handler as ToolHandler;
const result = await handler(client, {
mode: "hosecloud",
flowIds: ["B26017701"],
thinkingDepthOverride: "default"
}, fakeContext());
expect(assertPosted).toBe(true);
expect(postedBody).toMatchObject({
flowIds: ["B26017701"],
signKey: SIGN_KEY,
thinkingDepthOverride: "default",
sourceSystem: "hosecloud"
});
expect(postedBody).not.toHaveProperty("limit");
expect(result).toMatchObject({
batchId: "batch-1",
created: true,
noWait: true,
asyncTicket: "batch-1"
});
});
test("create tool surface exposes mode, flowIds, and rawParams", () => {
const tool = sealTools.find((item) => item.name === "seal_simulation_batch_create");
const { z } = require("zod") as typeof import("zod");
const schema = z.toJSONSchema(tool!.parameters) as { properties?: Record<string, unknown> };
expect(Object.keys(schema.properties ?? {})).toEqual(
expect.arrayContaining(["mode", "flowIds", "rawParams", "schemaConfig", "packageIds", "noWait"])
);
});
test("includes the simulation management tool set", () => {
expect(sealTools.find((item) => item.name === "seal_simulation_batches_list")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_simulation_batch_get")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_simulation_batch_status")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_simulation_templates_get")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_simulation_integrations_get")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_simulation_batch_records_get")).toBeDefined();
expect(sealTools.find((item) => item.name === "seal_simulation_material_package_upload")).toBeDefined();
});
test("status tool performs one non-blocking check and exposes the next action", async () => {
const tool = sealTools.find((item) => item.name === "seal_simulation_batch_status");
expect(tool).toBeDefined();
const client = {
get: (url: string) => {
expect(url).toBe("api/v1/simulation/batch/batch-1");
return { json: async () => ({ data: { ...hosecloudBatchFixture, id: "batch-1" } }) };
}
} as unknown as KyInstance;
const handler = tool!.handler as ToolHandler;
const result = await handler(client, { batchId: "batch-1" }, fakeContext()) as Record<string, unknown>;
expect(result).toMatchObject({
batchId: "batch-1",
status: "SYNCING",
terminal: false,
next: {
status: "seal-use simulation status batch-1",
wait: "seal-use simulation wait batch-1"
}
});
});
});
describe("simulation response schemas", () => {
test("parses the captured batch detail including echoed params", () => {
const parsed = SimulationBatchSchema.parse(hosecloudBatchFixture);
expect(parsed.status).toBe("syncing");
expect(parsed.params?.thinkingDepthOverride).toBe("medium");
expect(parsed.requestSummary?.conditions).toHaveLength(2);
});
test("tolerates legacy batches without requestSummary", () => {
const legacy = {
...hosecloudBatchFixture,
id: "019f3556-9c4e-7599-b13a-9df52c18f8a2",
requestSummary: null,
params: {
approvalCode: "hosecloud",
nodeId: "hosecloud",
startTime: 0,
endTime: 0,
limit: 2,
skipInvoiceGeneration: true,
skipExpenseExtraction: true,
dataCollectionMode: "2",
flowIds: ["B26022501", "B26028572"],
signKey: SIGN_KEY,
rejectNodeName: null
}
};
const parsed = SimulationBatchSchema.parse(legacy);
expect(parsed.id).toBe("019f3556-9c4e-7599-b13a-9df52c18f8a2");
expect(parsed.requestSummary).toBeNull();
});
test("parses the captured template with hosecloudConfig", () => {
const parsed = SimulationTemplateSchema.parse(templateFixture);
expect(parsed.name).toBe("ack11");
expect(parsed.hosecloudConfig?.flowIds).toContain("B26022501");
});
test("parses the captured integration status", () => {
const parsed = SimulationIntegrationStatusSchema.parse(integrationStatusFixture);
expect(parsed.hasHosecloud).toBe(true);
});
test("parses the captured material package upload response", () => {
const parsed = MaterialPackageSchema.parse(materialPackageUploadFixture);
expect(parsed.templateId).toBe("conference_reimbursement_v1");
expect(parsed.schemaConfig?.mainColumns).toHaveLength(4);
expect(parsed.schemaConfig?.listSheets[0]?.keyColumn).toBe("会议编号");
});
});