Add simulation test batch creation and material package upload

Support the release loop against Seal simulation batches:
- simulation create (hosecloud specified single-number and material_pack
  modes; other collection modes reserved via rawParams passthrough)
- simulation list/get/templates/integrations/package-upload
- schema modeling from captured staging traffic, mode-scoped request params
- new MCP tools and OpenAPI paths; bump version to 0.6.0

Tests: bun run check, bun test (114 pass).
This commit is contained in:
gitea committed 2026-08-24 18:10:05 +08:00
1 parent 39de757042
commit 0e52a295ba
13 files changed
+1883 -17

No files matched your search

+75 -1
View File
@@ -48,7 +48,19 @@ import {
BillingStatusDataSchema,
WebhookIntegration,
WebhookIntegrationSchema,
WebhookMode
WebhookMode,
SimulationBatch,
SimulationBatchSchema,
SimulationCreateResult,
SimulationCreateResultSchema,
SimulationTemplate,
SimulationTemplateSchema,
SimulationIntegrationStatus,
SimulationIntegrationStatusSchema,
SimulationHosecloudIntegration,
SimulationHosecloudIntegrationSchema,
MaterialPackage,
MaterialPackageSchema
} from "./types.js";
const SuccessResponseSchema = z.object({ success: z.boolean().optional() }).passthrough();
@@ -577,6 +589,68 @@ export async function listSimulationBatchRecords(
return parsed.records;
}
export async function createSimulationBatch(
client: KyInstance,
params: Record<string, unknown>
): Promise<SimulationCreateResult> {
return unwrap(
await client.post("api/v1/simulation/create-batch", { json: params }),
SimulationCreateResultSchema
);
}
export async function listSimulationBatches(
client: KyInstance,
opts: { limit?: number } = {}
): Promise<SimulationBatch[]> {
const json = (await client
.get("api/v1/simulation/batches", {
searchParams: { limit: String(opts.limit ?? 50) }
})
.json()) as { data?: unknown };
const data = json.data ?? json;
return z.array(SimulationBatchSchema).parse(data);
}
export async function getSimulationBatch(
client: KyInstance,
batchId: string
): Promise<SimulationBatch> {
return unwrap(await client.get(`api/v1/simulation/batch/${batchId}`), SimulationBatchSchema);
}
export async function listSimulationTemplates(client: KyInstance): Promise<SimulationTemplate[]> {
const json = (await client.get("api/v1/simulation/templates").json()) as { data?: unknown };
const data = json.data ?? json;
return z.array(SimulationTemplateSchema).parse(data);
}
export async function getSimulationIntegrationStatus(
client: KyInstance
): Promise<SimulationIntegrationStatus> {
return unwrap(await client.get("api/v1/simulation/integration-status"), SimulationIntegrationStatusSchema);
}
export async function listSimulationHosecloudIntegrations(
client: KyInstance
): Promise<SimulationHosecloudIntegration[]> {
const json = (await client.get("api/v1/simulation/hosecloud-integrations").json()) as { data?: unknown };
const data = json.data ?? json;
return z.array(SimulationHosecloudIntegrationSchema).parse(data);
}
export async function uploadMaterialPackage(
client: KyInstance,
params: { fileName: string; fileBuffer: Uint8Array }
): Promise<MaterialPackage> {
const form = new FormData();
form.append("file", new Blob([new Uint8Array(params.fileBuffer)]), params.fileName);
return unwrap(
await client.post("api/v1/material-packages/upload", { body: form }),
MaterialPackageSchema
);
}
function setOptional(searchParams: URLSearchParams, key: string, value?: string) {
if (value) {
searchParams.set(key, value);
+497
View File
@@ -0,0 +1,497 @@
import { describe, expect, test } from "bun:test";
import { KyInstance } from "ky";
import { CorpConfig } from "../../core/config/types.js";
import {
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 without mode-irrelevant fields", () => {
const params = buildSimulationBatchParams({
mode: "hosecloud",
flowIds: ["B26017701"],
skipInvoiceGeneration: true,
skipExpenseExtraction: true,
disableAttachmentCache: false,
rejectNodeName: null,
thinkingDepthOverride: "medium",
signKey: SIGN_KEY
});
expect(params).toEqual({
approvalCode: "hosecloud",
nodeId: "hosecloud",
skipInvoiceGeneration: true,
skipExpenseExtraction: true,
flowIds: ["B26017701"],
limit: 1,
dataCollectionMode: "2",
disableAttachmentCache: false,
rejectNodeName: null,
signKey: SIGN_KEY,
thinkingDepthOverride: "medium"
});
// 时间范围字段只在对应取数模式下发送
expect(params).not.toHaveProperty("startTime");
expect(params).not.toHaveProperty("endTime");
});
test("defaults limit to flowIds length and supports node override", () => {
const params = buildSimulationBatchParams({
mode: "hosecloud",
flowIds: ["B26010080", "B25011446"],
skipExpenseExtraction: false,
disableAttachmentCache: true,
rejectNodeName: "财务",
signKey: SIGN_KEY
});
expect(params).toMatchObject({
flowIds: ["B26010080", "B25011446"],
limit: 2,
skipInvoiceGeneration: true,
skipExpenseExtraction: false,
disableAttachmentCache: true,
rejectNodeName: "财务"
});
expect(params.thinkingDepthOverride).toBeUndefined();
});
test("builds material_pack payload with the confirmed schema config", () => {
const params = buildSimulationBatchParams({
mode: "material_pack",
packageIds: ["019fd15c-13a6-748f-8cdd-73e2da60252a"],
packageLabel: "Hilton测试材料包3-ready-v2-20260805-c6fcc0db",
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({
approvalCode: "material_pack",
nodeId: "material_pack",
packageIds: ["019fd15c-13a6-748f-8cdd-73e2da60252a"],
packageLabel: "Hilton测试材料包3-ready-v2-20260805-c6fcc0db",
templateId: "conference_reimbursement_v1",
runMode: "import_and_simulate",
schemaConfig: {
id: "conference_reimbursement_v1",
mainKeyColumn: "会议编号",
attachmentFieldKey: "supporting_files"
}
});
// 合思专属字段不随材料包模式发送
expect(params).not.toHaveProperty("disableAttachmentCache");
expect(params).not.toHaveProperty("flowIds");
expect(params).not.toHaveProperty("startTime");
});
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("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("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"],
limit: 1,
thinkingDepthOverride: "medium"
}, fakeContext());
expect(assertPosted).toBe(true);
expect(postedBody).toMatchObject({
flowIds: ["B26017701"],
limit: 1,
signKey: SIGN_KEY,
thinkingDepthOverride: "medium"
});
expect(result).toMatchObject({ batchId: "batch-1", created: true });
});
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"])
);
});
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_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();
});
});
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("会议编号");
});
});
+256 -1
View File
@@ -1,11 +1,12 @@
import { z } from "zod";
import { KyInstance } from "ky";
import { readFileSync } from "node:fs";
import * as api from "./api.js";
import { defaultSealUrl, getHoseEnterpriseUrl } from "../../core/auth/hose.js";
import { CorpConfig } from "../../core/config/types.js";
import { createSealClientForToken } from "../../core/http/factory.js";
import { searchApprovalContent } from "./search.js";
import type { ApprovalRule, ApprovalRun, RuleSetVersion, WebhookIntegration, WebhookMode } from "./types.js";
import type { ApprovalRule, ApprovalRun, RuleSetVersion, SimulationBatch, WebhookIntegration, WebhookMode } from "./types.js";
type ToolContext = {
corp: CorpConfig;
@@ -1067,6 +1068,175 @@ export const sealTools = [
};
}
},
{
name: "seal_simulation_batch_create",
description: "创建 Seal 模拟测试批次。支持合思指定单号(hosecloud)与材料包导入(material_pack)两种模式;其他取数模式通过 rawParams 预留透传。",
parameters: z.object({
mode: z.enum(["hosecloud", "material_pack"]).default("hosecloud").describe("来源模式: hosecloud=合思指定单号; material_pack=材料包导入"),
flowIds: z.array(z.string()).max(100).optional().describe("合思模式: 单据流水号列表"),
limit: z.number().int().positive().max(100).optional().describe("指定单号数量, 默认取 flowIds 个数"),
rejectNodeName: z.string().nullable().optional().describe("仅关注特定节点: 节点名称, 不传为 null 表示不限制"),
thinkingDepthOverride: z.enum(["medium", "high"]).nullable().optional().describe("思考深度: medium=标准, high=深度推理, 不传=按偏好设置"),
skipInvoiceGeneration: z.boolean().optional().describe("跳过发票生成, 默认 true"),
skipExpenseExtraction: z.boolean().optional().describe("跳过费用提取, 默认 true"),
disableAttachmentCache: z.boolean().optional().describe("不使用附件缓存, 默认 false"),
signKey: z.string().optional().describe("合思集成标识; 缺省时自动取第一个合思集成"),
packageIds: z.array(z.string()).optional().describe("材料包模式: 材料包 id 列表(来自 material-packages upload 响应)"),
packageLabel: z.string().optional().describe("材料包标签, 展示用"),
templateId: z.string().optional().describe("材料包模板 id, 例如 conference_reimbursement_v1"),
schemaConfig: z.record(z.string(), z.unknown()).optional().describe("材料包字段映射(确认参数), 建议使用 material-packages upload 返回的 schemaConfig"),
rawParams: z.record(z.string(), z.unknown()).optional().describe("预留: 其他取数模式(如时间范围 startTime/endTime)透传参数, 覆盖上述构建结果")
}),
handler: async (
client: KyInstance,
params: {
mode?: "hosecloud" | "material_pack";
flowIds?: string[];
limit?: number;
rejectNodeName?: string | null;
thinkingDepthOverride?: "medium" | "high" | null;
skipInvoiceGeneration?: boolean;
skipExpenseExtraction?: boolean;
disableAttachmentCache?: boolean;
signKey?: string;
packageIds?: string[];
packageLabel?: string;
templateId?: string;
schemaConfig?: Record<string, unknown>;
rawParams?: Record<string, unknown>;
}
) => {
const mode = params.mode ?? "hosecloud";
let signKey = params.signKey;
if (mode === "hosecloud" && !signKey) {
const integrations = await api.listSimulationHosecloudIntegrations(client);
signKey = integrations.find((item) => item.signKey)?.signKey;
if (!signKey) {
throw new Error("未找到合思集成 signKey, 请通过 signKey 参数提供");
}
}
const payload = buildSimulationBatchParams({
mode,
flowIds: params.flowIds,
limit: params.limit,
rejectNodeName: params.rejectNodeName,
thinkingDepthOverride: params.thinkingDepthOverride ?? undefined,
skipInvoiceGeneration: params.skipInvoiceGeneration,
skipExpenseExtraction: params.skipExpenseExtraction,
disableAttachmentCache: params.disableAttachmentCache,
signKey,
packageIds: params.packageIds,
packageLabel: params.packageLabel,
templateId: params.templateId,
schemaConfig: params.schemaConfig,
rawParams: params.rawParams
});
const result = await api.createSimulationBatch(client, payload);
return {
...result,
created: true,
next: {
getBatch: "seal-home simulation get <batchId>",
getRecords: "seal-home simulation batch-records <batchId>",
listBatches: "seal-home simulation list"
}
};
}
},
{
name: "seal_simulation_batches_list",
description: "列出 Seal 模拟测试批次摘要(含状态、统计计数与展示摘要)",
parameters: z.object({
limit: z.number().int().positive().max(100).optional().describe("最多返回批次数量, 默认 50")
}),
handler: async (client: KyInstance, params: { limit?: number }) => {
const batches = await api.listSimulationBatches(client, { limit: params.limit ?? 50 });
return {
count: batches.length,
batches: batches.map(summarizeSimulationBatch),
next: {
getBatch: "seal-home simulation get <batchId>",
getRecords: "seal-home simulation batch-records <batchId>"
}
};
}
},
{
name: "seal_simulation_batch_get",
description: "获取某一次 Seal 模拟测试批次的详情,包含服务端回显的创建参数、展示摘要和任务统计",
parameters: z.object({
batchId: z.string().describe("simulation batch ID")
}),
handler: async (client: KyInstance, params: { batchId: string }) => {
const batch = await api.getSimulationBatch(client, params.batchId);
return {
batch,
next: {
getRecords: "seal-home simulation batch-records <batchId>"
}
};
}
},
{
name: "seal_simulation_templates_get",
description: "列出 Seal 模拟测试模板(我的模板,保存常用配置快速复用)",
parameters: z.object({}),
handler: async (client: KyInstance) => {
const templates = await api.listSimulationTemplates(client);
return {
count: templates.length,
templates: templates.map((template) => ({
id: template.id,
name: template.name,
description: template.description,
approvalSystem: template.approvalSystem,
hosecloudConfig: template.hosecloudConfig,
updatedAt: template.updatedAt
})),
next: {
createBatch: "seal-home simulation create --mode hosecloud --flow-ids ..."
}
};
}
},
{
name: "seal_simulation_integrations_get",
description: "查询模拟测试可用的来源集成状态与合思集成选项(signKey 等)",
parameters: z.object({}),
handler: async (client: KyInstance) => {
const [status, hosecloudIntegrations] = await Promise.all([
api.getSimulationIntegrationStatus(client),
api.listSimulationHosecloudIntegrations(client)
]);
return { status, hosecloudIntegrations };
}
},
{
name: "seal_simulation_material_package_upload",
description: "上传材料包 ZIP 到 Seal 模拟测试;服务端解析 Excel/AI 推断配置并返回材料包 id 与 schemaConfig(字段映射确认后用于创建模拟批次)",
parameters: z.object({
filePath: z.string().describe("材料包 ZIP 文件路径(含 信息表.xlsx 与附件)")
}),
handler: async (client: KyInstance, params: { filePath?: string }) => {
if (!params.filePath) {
throw new Error("filePath is required");
}
const fileBuffer = readFileSync(params.filePath);
const fileName = params.filePath.split(/[\\/]/).pop() ?? "material-pack.zip";
const materialPackage = await api.uploadMaterialPackage(client, {
fileName,
fileBuffer
});
return {
materialPackage,
next: {
createBatch: `seal-home simulation create --mode material_pack --package-ids ${materialPackage.id} --schema-config schema.json`
}
};
}
},
{
name: "seal_approval_run_langfuse_bridge_get",
description: "从 Seal approval run 中抽取 Langfuse 定位信息;优先返回 _langfuseTraceId,没有时给出 hosecloud-{sourceDocumentSN} session 回退",
@@ -1156,6 +1326,12 @@ const sealActionNames = [
"seal_approval_run_url_get",
"seal_approval_run_pick",
"seal_simulation_batch_records_get",
"seal_simulation_batch_create",
"seal_simulation_batches_list",
"seal_simulation_batch_get",
"seal_simulation_templates_get",
"seal_simulation_integrations_get",
"seal_simulation_material_package_upload",
"seal_approval_run_langfuse_bridge_get"
] as const;
@@ -1190,6 +1366,12 @@ const sealActionAliases: Record<string, (typeof sealActionNames)[number]> = {
"runs.url": "seal_approval_run_url_get",
"runs.pick": "seal_approval_run_pick",
"batch.records.get": "seal_simulation_batch_records_get",
"batch.create": "seal_simulation_batch_create",
"batch.list": "seal_simulation_batches_list",
"batch.get": "seal_simulation_batch_get",
"batch.templates.list": "seal_simulation_templates_get",
"batch.integrations.get": "seal_simulation_integrations_get",
"batch.materialPackageUpload": "seal_simulation_material_package_upload",
"langfuse.bridge.get": "seal_approval_run_langfuse_bridge_get"
};
@@ -1363,6 +1545,79 @@ function pickRuleFields(rule: ApprovalRule, fields: readonly RuleField[]) {
return output;
}
export type SimulationBatchCreateInput = {
mode: "hosecloud" | "material_pack";
flowIds?: string[];
limit?: number;
rejectNodeName?: string | null;
thinkingDepthOverride?: "medium" | "high";
skipInvoiceGeneration?: boolean;
skipExpenseExtraction?: boolean;
disableAttachmentCache?: boolean;
signKey?: string;
packageIds?: string[];
packageLabel?: string;
templateId?: string;
schemaConfig?: Record<string, unknown>;
// 预留:其他取数模式(如合思时间范围)透传参数,覆盖构建结果
rawParams?: Record<string, unknown>;
};
export function buildSimulationBatchParams(input: SimulationBatchCreateInput): Record<string, unknown> {
const params: Record<string, unknown> = {
approvalCode: input.mode,
nodeId: input.mode,
skipInvoiceGeneration: input.skipInvoiceGeneration ?? true,
skipExpenseExtraction: input.skipExpenseExtraction ?? true
};
if (input.mode === "hosecloud") {
if (!input.flowIds?.length) {
throw new Error("hosecloud 模式需要提供 flowIds(单号列表)");
}
Object.assign(params, {
flowIds: input.flowIds,
limit: input.limit ?? input.flowIds.length,
dataCollectionMode: "2",
disableAttachmentCache: input.disableAttachmentCache ?? false
});
if (input.signKey) params.signKey = input.signKey;
if (input.rejectNodeName !== undefined) params.rejectNodeName = input.rejectNodeName;
} else {
if (!input.packageIds?.length) {
throw new Error("material_pack 模式需要提供 packageIds(材料包 id)");
}
Object.assign(params, {
packageIds: input.packageIds,
runMode: "import_and_simulate"
});
if (input.templateId) params.templateId = input.templateId;
if (input.packageLabel) params.packageLabel = input.packageLabel;
if (input.schemaConfig !== undefined) params.schemaConfig = input.schemaConfig;
}
if (input.thinkingDepthOverride) params.thinkingDepthOverride = input.thinkingDepthOverride;
if (input.rawParams) Object.assign(params, input.rawParams);
return params;
}
function summarizeSimulationBatch(batch: SimulationBatch) {
return {
id: batch.id,
status: batch.status,
approvalCode: batch.approvalCode,
sourceSystem: batch.sourceSystem,
totalCount: batch.totalCount,
processedCount: batch.processedCount,
successCount: batch.successCount,
failedCount: batch.failedCount,
createdCount: batch.createdCount,
createFailedCount: batch.createFailedCount,
requestSummary: batch.requestSummary,
resultSummary: batch.resultSummary,
createdAt: batch.createdAt
};
}
function summarizeApprovalRun(record: ApprovalRun): ApprovalRunSummary {
const sourceDocumentSN = record.sourceDocumentSN;
const humanResult = extractHumanResult(record);
+153
View File
@@ -316,6 +316,149 @@ export const BillingStatusDataSchema = z.object({
features: z.array(z.record(z.string(), z.unknown())).default([])
}).passthrough();
export const SimulationColumnSchema = z.object({
key: z.string(),
type: z.string(),
label: z.string(),
column: z.string(),
mask: z.string().optional()
}).passthrough();
export const SimulationListSheetSchema = z.object({
columns: z.array(SimulationColumnSchema).default([]),
fieldKey: z.string().optional(),
keyColumn: z.string().optional(),
sheetName: z.string().optional(),
fieldLabel: z.string().optional()
}).passthrough();
export const SimulationSchemaConfigSchema = z.object({
id: z.string().optional(),
listSheets: z.array(SimulationListSheetSchema).default([]),
mainColumns: z.array(SimulationColumnSchema).default([]),
workbookName: z.string().optional(),
mainKeyColumn: z.string().optional(),
mainSheetName: z.string().optional(),
titleColumn: z.string().optional(),
statusColumn: z.string().optional(),
applicationDateColumn: z.string().optional(),
updatedDateColumn: z.string().optional(),
attachmentFieldKey: z.string().optional(),
attachmentFieldLabel: z.string().optional()
}).passthrough();
export const SimulationBatchParamsSchema = z.object({
approvalCode: z.string(),
nodeId: z.string().optional(),
// 合思指定单号模式
flowIds: z.array(z.string()).max(100).optional(),
limit: z.number().int().positive().max(100).optional(),
dataCollectionMode: z.string().optional(),
signKey: z.string().optional(),
rejectNodeName: z.string().nullable().optional(),
skipInvoiceGeneration: z.boolean().optional(),
skipExpenseExtraction: z.boolean().optional(),
disableAttachmentCache: z.boolean().optional(),
thinkingDepthOverride: z.enum(["medium", "high"]).optional(),
// 预留:合思时间范围等其他取数模式
startTime: z.number().optional(),
endTime: z.number().optional(),
// 材料包导入模式
templateId: z.string().optional(),
packageIds: z.array(z.string()).optional(),
packageLabel: z.string().optional(),
runMode: z.string().optional(),
schemaConfig: SimulationSchemaConfigSchema.optional()
}).passthrough();
export const SimulationRequestSummarySchema = z.object({
mode: z.string().optional(),
conditions: z.array(z.object({
label: z.string(),
value: z.string()
}).passthrough()).default([])
}).passthrough();
export const SimulationResultSummarySchema = z.object({
kind: z.string().optional(),
stage: z.string().optional(),
code: z.string().optional(),
message: z.string().optional()
}).passthrough();
export const SimulationBatchSchema = z.object({
id: z.string(),
tenantId: z.string().optional(),
approvalCode: z.string().optional(),
nodeId: z.string().optional(),
sourceSystem: z.string().optional(),
status: z.string().optional(),
totalCount: z.number().default(0),
processedCount: z.number().default(0),
successCount: z.number().default(0),
failedCount: z.number().default(0),
createdCount: z.number().default(0),
createFailedCount: z.number().default(0),
params: SimulationBatchParamsSchema.optional(),
requestSummary: SimulationRequestSummarySchema.nullable().optional(),
resultSummary: SimulationResultSummarySchema.nullable().optional(),
createdAt: z.union([z.string(), z.number()]).optional(),
updatedAt: z.union([z.string(), z.number()]).optional()
}).passthrough();
export const SimulationCreateResultSchema = z.object({
batchId: z.string()
}).passthrough();
export const SimulationHosecloudConfigSchema = z.object({
dataCollectionMode: z.string().optional(),
flowIds: z.array(z.string()).max(100).optional(),
rejectNodeName: z.string().nullable().optional(),
skipInvoiceGeneration: z.boolean().optional(),
skipExpenseExtraction: z.boolean().optional()
}).passthrough();
export const SimulationTemplateSchema = z.object({
id: z.string(),
tenantId: z.string().optional(),
name: z.string().optional(),
description: z.string().optional(),
approvalSystem: z.string().optional(),
hosecloudConfig: SimulationHosecloudConfigSchema.optional(),
createdAt: z.union([z.string(), z.number()]).optional(),
updatedAt: z.union([z.string(), z.number()]).optional()
}).passthrough();
export const SimulationIntegrationStatusSchema = z.object({
hasFeishu: z.boolean().default(false),
hasHosecloud: z.boolean().default(false),
hasWeaver: z.boolean().default(false),
hasHelios: z.boolean().default(false),
hasMaycur: z.boolean().default(false),
hasMaycurStandard: z.boolean().default(false)
}).passthrough();
export const SimulationHosecloudIntegrationSchema = z.object({
signKey: z.string().optional(),
displayName: z.string().optional(),
corporationId: z.string().optional()
}).passthrough();
export const MaterialPackageSchema = z.object({
id: z.string(),
tenantId: z.string().optional(),
name: z.string().optional(),
templateId: z.string().optional(),
originalFileName: z.string().optional(),
status: z.string().optional(),
documentCount: z.number().optional(),
attachmentCount: z.number().optional(),
uploadedBy: z.string().optional(),
schemaConfig: SimulationSchemaConfigSchema.nullable().optional(),
createdAt: z.union([z.string(), z.number()]).optional(),
updatedAt: z.union([z.string(), z.number()]).optional()
}).passthrough();
export type MeData = z.infer<typeof MeDataSchema>;
export type SealSessionData = z.infer<typeof SealSessionDataSchema>;
export type ApprovalRule = z.infer<typeof ApprovalRuleSchema>;
@@ -342,5 +485,15 @@ export type LlmProvider = z.infer<typeof LlmProviderSchema>;
export type AvailablePermissionsData = z.infer<typeof AvailablePermissionsDataSchema>;
export type PermissionConfigsData = z.infer<typeof PermissionConfigsDataSchema>;
export type BillingStatusData = z.infer<typeof BillingStatusDataSchema>;
export type SimulationColumn = z.infer<typeof SimulationColumnSchema>;
export type SimulationListSheet = z.infer<typeof SimulationListSheetSchema>;
export type SimulationSchemaConfig = z.infer<typeof SimulationSchemaConfigSchema>;
export type SimulationBatchParams = z.infer<typeof SimulationBatchParamsSchema>;
export type SimulationBatch = z.infer<typeof SimulationBatchSchema>;
export type SimulationCreateResult = z.infer<typeof SimulationCreateResultSchema>;
export type SimulationTemplate = z.infer<typeof SimulationTemplateSchema>;
export type SimulationIntegrationStatus = z.infer<typeof SimulationIntegrationStatusSchema>;
export type SimulationHosecloudIntegration = z.infer<typeof SimulationHosecloudIntegrationSchema>;
export type MaterialPackage = z.infer<typeof MaterialPackageSchema>;