880 lines
32 KiB
TypeScript
880 lines
32 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, findReusableSimulationBatch, sealCapabilities } from "../capabilities.js";
|
|
import {
|
|
MaterialPackageSchema,
|
|
SimulationBatch,
|
|
SimulationBatchSchema,
|
|
SimulationIntegrationStatusSchema,
|
|
SimulationTemplateSchema
|
|
} from "../types.js";
|
|
|
|
type CapabilityHandler = (
|
|
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("findReusableSimulationBatch", () => {
|
|
const NOW = Date.parse("2026-09-28T08:00:00.000Z");
|
|
const WINDOW_MS = 5 * 60 * 1000;
|
|
const reusableBatch: SimulationBatch = SimulationBatchSchema.parse({
|
|
...hosecloudBatchFixture,
|
|
id: "01a0e699-existing",
|
|
status: "running",
|
|
createdAt: "2026-09-28T07:57:30.000Z"
|
|
});
|
|
|
|
test("reuses a batch with the same flow ids inside the window", () => {
|
|
const match = findReusableSimulationBatch([reusableBatch], { flowIds: ["B26017701"] }, WINDOW_MS, NOW);
|
|
expect(match?.id).toBe("01a0e699-existing");
|
|
});
|
|
|
|
test("matches regardless of flow id order or duplicates", () => {
|
|
const batch = { ...reusableBatch, params: { ...reusableBatch.params!, flowIds: ["B26028572", "B26022501"] } };
|
|
const match = findReusableSimulationBatch([batch], { flowIds: ["B26022501", "B26028572", "B26028572"] }, WINDOW_MS, NOW);
|
|
expect(match?.id).toBe("01a0e699-existing");
|
|
});
|
|
|
|
test("ignores batches created outside the reuse window", () => {
|
|
const old = { ...reusableBatch, createdAt: "2026-09-28T07:50:00.000Z" };
|
|
expect(findReusableSimulationBatch([old], { flowIds: ["B26017701"] }, WINDOW_MS, NOW)).toBeNull();
|
|
});
|
|
|
|
test("ignores failed and cancelled batches but reuses completed ones", () => {
|
|
const failed = { ...reusableBatch, status: "FAILED" };
|
|
const cancelled = { ...reusableBatch, status: "Cancelled" };
|
|
const completed = { ...reusableBatch, status: "COMPLETED" };
|
|
expect(findReusableSimulationBatch([failed], { flowIds: ["B26017701"] }, WINDOW_MS, NOW)).toBeNull();
|
|
expect(findReusableSimulationBatch([cancelled], { flowIds: ["B26017701"] }, WINDOW_MS, NOW)).toBeNull();
|
|
expect(findReusableSimulationBatch([completed], { flowIds: ["B26017701"] }, WINDOW_MS, NOW)?.status).toBe("COMPLETED");
|
|
});
|
|
|
|
test("ignores different flow ids, missing createdAt, and mismatched signKey", () => {
|
|
expect(findReusableSimulationBatch([reusableBatch], { flowIds: ["B99999999"] }, WINDOW_MS, NOW)).toBeNull();
|
|
const undated = { ...reusableBatch, createdAt: undefined };
|
|
expect(findReusableSimulationBatch([undated], { flowIds: ["B26017701"] }, WINDOW_MS, NOW)).toBeNull();
|
|
const otherSignKey = { ...reusableBatch, params: { ...reusableBatch.params!, signKey: "other-key" } };
|
|
expect(
|
|
findReusableSimulationBatch([otherSignKey], { flowIds: ["B26017701"], signKey: SIGN_KEY }, WINDOW_MS, NOW)
|
|
).toBeNull();
|
|
});
|
|
|
|
test("matches material pack batches by package ids", () => {
|
|
const packBatch = {
|
|
...reusableBatch,
|
|
params: { approvalCode: "material_pack", packageIds: ["pkg-1", "pkg-2"] }
|
|
};
|
|
const match = findReusableSimulationBatch([packBatch], { packageIds: ["pkg-2", "pkg-1"] }, WINDOW_MS, NOW);
|
|
expect(match?.id).toBe("01a0e699-existing");
|
|
expect(findReusableSimulationBatch([packBatch], { packageIds: ["pkg-9"] }, WINDOW_MS, NOW)).toBeNull();
|
|
});
|
|
|
|
test("accepts epoch millis createdAt", () => {
|
|
const batch = { ...reusableBatch, createdAt: NOW - 60_000 };
|
|
expect(findReusableSimulationBatch([batch], { flowIds: ["B26017701"] }, WINDOW_MS, NOW)?.id).toBe("01a0e699-existing");
|
|
});
|
|
|
|
test("returns null without an identity key", () => {
|
|
expect(findReusableSimulationBatch([reusableBatch], {}, WINDOW_MS, NOW)).toBeNull();
|
|
});
|
|
});
|
|
|
|
describe("simulation tool handlers", () => {
|
|
test("create tool resolves signKey automatically and posts the payload", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealSimulationBatchCreate");
|
|
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: "大黄蜂-测试" }]
|
|
})
|
|
};
|
|
}
|
|
if (url === "api/v1/simulation/batches") {
|
|
return { json: async () => ({ data: [] }) };
|
|
}
|
|
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 CapabilityHandler;
|
|
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 reuses a recent identical batch instead of creating a new one", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealSimulationBatchCreate");
|
|
expect(tool).toBeDefined();
|
|
|
|
let postCalls = 0;
|
|
const client = {
|
|
get: (url: string) => {
|
|
if (url === "api/v1/simulation/hosecloud-integrations") {
|
|
return { json: async () => ({ data: [{ signKey: SIGN_KEY, displayName: "大黄蜂-测试" }] }) };
|
|
}
|
|
if (url === "api/v1/simulation/batches") {
|
|
return {
|
|
json: async () => ({
|
|
data: [{
|
|
...hosecloudBatchFixture,
|
|
id: "01a0e699-existing",
|
|
status: "running",
|
|
createdAt: new Date(Date.now() - 90_000).toISOString()
|
|
}]
|
|
})
|
|
};
|
|
}
|
|
throw new Error(`unexpected url ${url}`);
|
|
},
|
|
post: () => {
|
|
postCalls += 1;
|
|
throw new Error("must not create a new batch when an identical one is reusable");
|
|
}
|
|
} as unknown as KyInstance;
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(client, {
|
|
mode: "hosecloud",
|
|
flowIds: ["B26017701"]
|
|
}, fakeContext()) as Record<string, unknown>;
|
|
|
|
expect(postCalls).toBe(0);
|
|
expect(result).toMatchObject({
|
|
batchId: "01a0e699-existing",
|
|
created: false,
|
|
reused: true,
|
|
asyncTicket: "01a0e699-existing"
|
|
});
|
|
expect(result.message).toContain("复用");
|
|
});
|
|
|
|
test("create tool force bypasses the reuse check", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealSimulationBatchCreate");
|
|
let posted = false;
|
|
const client = {
|
|
get: (url: string) => {
|
|
if (url === "api/v1/simulation/hosecloud-integrations") {
|
|
return { json: async () => ({ data: [{ signKey: SIGN_KEY, displayName: "大黄蜂-测试" }] }) };
|
|
}
|
|
if (url === "api/v1/simulation/batches") {
|
|
return {
|
|
json: async () => ({
|
|
data: [{
|
|
...hosecloudBatchFixture,
|
|
id: "01a0e699-existing",
|
|
status: "running",
|
|
createdAt: new Date(Date.now() - 90_000).toISOString()
|
|
}]
|
|
})
|
|
};
|
|
}
|
|
throw new Error(`unexpected url ${url}`);
|
|
},
|
|
post: (url: string) => {
|
|
posted = url === "api/v1/simulation/create-batch";
|
|
return { json: async () => ({ data: { batchId: "batch-new" } }) };
|
|
}
|
|
} as unknown as KyInstance;
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(client, {
|
|
mode: "hosecloud",
|
|
flowIds: ["B26017701"],
|
|
force: true
|
|
}, fakeContext()) as Record<string, unknown>;
|
|
|
|
expect(posted).toBe(true);
|
|
expect(result).toMatchObject({ batchId: "batch-new", created: true });
|
|
expect(result.reused).toBeUndefined();
|
|
});
|
|
|
|
test("create tool creates a new batch when the identical batch is outside the reuse window", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealSimulationBatchCreate");
|
|
let posted = false;
|
|
const client = {
|
|
get: (url: string) => {
|
|
if (url === "api/v1/simulation/hosecloud-integrations") {
|
|
return { json: async () => ({ data: [{ signKey: SIGN_KEY, displayName: "大黄蜂-测试" }] }) };
|
|
}
|
|
if (url === "api/v1/simulation/batches") {
|
|
return {
|
|
json: async () => ({
|
|
data: [{
|
|
...hosecloudBatchFixture,
|
|
id: "01a0e699-old",
|
|
status: "running",
|
|
createdAt: new Date(Date.now() - 10 * 60_000).toISOString()
|
|
}]
|
|
})
|
|
};
|
|
}
|
|
throw new Error(`unexpected url ${url}`);
|
|
},
|
|
post: (url: string) => {
|
|
posted = url === "api/v1/simulation/create-batch";
|
|
return { json: async () => ({ data: { batchId: "batch-new" } }) };
|
|
}
|
|
} as unknown as KyInstance;
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(client, {
|
|
mode: "hosecloud",
|
|
flowIds: ["B26017701"]
|
|
}, fakeContext()) as Record<string, unknown>;
|
|
|
|
expect(posted).toBe(true);
|
|
expect(result).toMatchObject({ batchId: "batch-new", created: true });
|
|
});
|
|
|
|
test("create tool surface exposes mode, flowIds, and rawParams", () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealSimulationBatchCreate");
|
|
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(sealCapabilities.find((item) => item.name === "sealSimulationBatchesList")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealSimulationBatchGet")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealSimulationBatchStatus")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealSimulationTemplatesGet")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealSimulationIntegrationsGet")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealSimulationBatchRecordsGet")).toBeDefined();
|
|
expect(sealCapabilities.find((item) => item.name === "sealSimulationMaterialPackageUpload")).toBeDefined();
|
|
});
|
|
|
|
test("status tool performs one non-blocking check and exposes the next action", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealSimulationBatchStatus");
|
|
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 CapabilityHandler;
|
|
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"
|
|
}
|
|
});
|
|
});
|
|
|
|
test("list tool scans pages and filters locally by UI name and time window", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealSimulationBatchesList");
|
|
expect(tool).toBeDefined();
|
|
|
|
const newer = {
|
|
...hosecloudBatchFixture,
|
|
id: "01a12488-a69d-74c4-88b1-118bfe1993e4",
|
|
createdAt: "2026-10-10T06:38:17.757Z"
|
|
};
|
|
const older = {
|
|
...hosecloudBatchFixture,
|
|
id: "01a123be-0742-743a-ac16-87f7c4e121c7",
|
|
createdAt: "2026-10-09T02:56:58.000Z"
|
|
};
|
|
const calls: string[] = [];
|
|
const client = {
|
|
get: (_url: string, options: { searchParams: Record<string, string> }) => {
|
|
const limit = Number(options.searchParams.limit);
|
|
const offset = Number(options.searchParams.offset ?? 0);
|
|
calls.push(`${limit}@${offset}`);
|
|
const all = [newer, older];
|
|
return { json: async () => ({ data: all.slice(offset, offset + limit) }) };
|
|
}
|
|
} as unknown as KyInstance;
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(
|
|
client,
|
|
{ query: "任务 fe1993e4", since: "2026-10-10", until: "2026-10-10" },
|
|
fakeContext()
|
|
) as Record<string, unknown>;
|
|
|
|
expect(calls).toEqual(["50@0"]);
|
|
expect(result).toMatchObject({
|
|
retrieval: { mode: "local_scan", serverSideSearch: false, scanned: 2 },
|
|
scanned: 2,
|
|
truncated: false,
|
|
count: 1,
|
|
filters: {
|
|
query: "任务 fe1993e4",
|
|
since: "2026-10-10T00:00:00+08:00",
|
|
until: "2026-10-10T23:59:59+08:00"
|
|
}
|
|
});
|
|
expect((result.batches as Array<{ id: string }>)[0]?.id).toBe(newer.id);
|
|
// 时间统一为北京时间秒级, 并附带 epoch 毫秒与单号标识, 便于核对界面任务
|
|
expect((result.batches as Array<Record<string, unknown>>)[0]).toMatchObject({
|
|
createdAt: "2026-10-10T14:38:17+08:00",
|
|
createdAtMs: Date.parse("2026-10-10T06:38:17.757Z"),
|
|
updatedAt: "2026-08-24T16:50:16+08:00",
|
|
flowIds: ["B26017701"],
|
|
packageIds: [],
|
|
templateId: null
|
|
});
|
|
});
|
|
|
|
test("list tool paginates when all=true is requested", async () => {
|
|
const tool = sealCapabilities.find((item) => item.name === "sealSimulationBatchesList");
|
|
const calls: string[] = [];
|
|
const client = {
|
|
get: (_url: string, options: { searchParams: Record<string, string> }) => {
|
|
const limit = Number(options.searchParams.limit);
|
|
const offset = Number(options.searchParams.offset ?? 0);
|
|
calls.push(`${limit}@${offset}`);
|
|
// Every page comes back full so the scanner keeps advancing until maxScan.
|
|
const data = Array.from({ length: limit }, (_, index) => ({
|
|
...hosecloudBatchFixture,
|
|
id: `batch-${offset + index}`
|
|
}));
|
|
return { json: async () => ({ data }) };
|
|
}
|
|
} as unknown as KyInstance;
|
|
|
|
const handler = tool!.handler as CapabilityHandler;
|
|
const result = await handler(client, { all: true, maxScan: 250 }, fakeContext()) as Record<string, unknown>;
|
|
|
|
expect(calls).toEqual(["100@0", "100@100", "50@200"]);
|
|
expect(result).toMatchObject({ scanned: 250, scanLimit: 250, truncated: true, count: 250 });
|
|
});
|
|
});
|
|
|
|
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("会议编号");
|
|
});
|
|
});
|