Add Webhook material pack import
This commit is contained in:
1 parent
1299d70777
commit
77ae7d4dca
17 files changed
+667
-4
No files matched your search
@@ -1,6 +1,10 @@
|
||||
import type { CorpConfig } from "../../core/config/types.js";
|
||||
import type { createSealClient } from "../../core/http/factory.js";
|
||||
import { existsSync } from "node:fs";
|
||||
import { runTool } from "../helpers.js";
|
||||
import * as api from "../../domains/seal/api.js";
|
||||
import { findWebhookIntegration } from "../../domains/seal/api.js";
|
||||
import { previewMaterialPack, pushMaterialPack, readMaterialPackFile } from "../../domains/seal/material-pack/index.js";
|
||||
import {
|
||||
booleanOption,
|
||||
parseWebhookMode,
|
||||
@@ -11,6 +15,12 @@ import {
|
||||
import { outputOptions } from "../printer.js";
|
||||
import type { ParsedArgs } from "../types.js";
|
||||
|
||||
export async function handleWebhookMaterialPackPreview(filePath: string) {
|
||||
if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`);
|
||||
const input = readMaterialPackFile(filePath);
|
||||
console.log(JSON.stringify(await previewMaterialPack(input.fileBuffer, input.fileName), null, 2));
|
||||
}
|
||||
|
||||
export async function handleWebhookCommand(
|
||||
action: string | undefined,
|
||||
maybeName: string | undefined,
|
||||
@@ -18,6 +28,29 @@ export async function handleWebhookCommand(
|
||||
corp: CorpConfig,
|
||||
args: ParsedArgs
|
||||
) {
|
||||
if (action === "material-pack" || action === "material-pack-push") {
|
||||
const operation = action === "material-pack-push" ? "push" : maybeName;
|
||||
const filePath = action === "material-pack-push"
|
||||
? stringOption(args.options.file) ?? stringOption(args.options.input)
|
||||
: args.command[3] ?? stringOption(args.options.file) ?? stringOption(args.options.input);
|
||||
if (!filePath) throw new Error("Usage: seal-use webhook material-pack <preview|push> <材料包.zip>");
|
||||
if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`);
|
||||
const input = readMaterialPackFile(filePath);
|
||||
if (operation === "preview") {
|
||||
console.log(JSON.stringify(await previewMaterialPack(input.fileBuffer, input.fileName), null, 2));
|
||||
return;
|
||||
}
|
||||
if (operation !== "push") throw new Error("Usage: seal-use webhook material-pack <preview|push> <材料包.zip>");
|
||||
const selector = stringOption(args.options.webhook) ?? stringOption(args.options.selector);
|
||||
if (!selector) throw new Error("Push requires --webhook <idOrName>");
|
||||
const integration = findWebhookIntegration(await api.listWebhookIntegrations(client), selector);
|
||||
const result = await pushMaterialPack(input.fileBuffer, input.fileName, {
|
||||
webhookUrl: integration.incomingDocumentWebhook.url,
|
||||
secret: integration.secret
|
||||
});
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
return;
|
||||
}
|
||||
if (action === "list") {
|
||||
await runTool(
|
||||
"seal_webhook_list",
|
||||
|
||||
@@ -121,6 +121,8 @@ Usage:
|
||||
seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--corp <corpId>]
|
||||
seal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--corp <corpId>]
|
||||
seal-use webhook delete <idOrName> --yes [--corp <corpId>]
|
||||
seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> [--corp <corpId>]
|
||||
seal-use webhook material-pack push <材料包.zip|信息表.xlsx> --webhook <idOrName> [--corp <corpId>]
|
||||
seal-use deploy hosecloud requirements [--corp <corpId>]
|
||||
seal-use deploy hosecloud list [--corp <corpId>]
|
||||
seal-use deploy hosecloud get <sign-key> [--corp <corpId>]
|
||||
|
||||
+8
-1
@@ -28,7 +28,7 @@ import { handleToolCommand } from "./commands/tool.js";
|
||||
import { handleToolsListCommand } from "./commands/tools.js";
|
||||
import { handleUpdateCommand } from "./commands/update.js";
|
||||
import { handleUsersCommand } from "./commands/users.js";
|
||||
import { handleWebhookCommand } from "./commands/webhook.js";
|
||||
import { handleWebhookCommand, handleWebhookMaterialPackPreview } from "./commands/webhook.js";
|
||||
import { selectCorp } from "./helpers.js";
|
||||
import { booleanOption, numberOption, parseArgs, stringOption } from "./parser.js";
|
||||
import {
|
||||
@@ -155,6 +155,13 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
|
||||
throw new Error(`Unknown command: ${args.command.join(" ")}. Run 'seal-use help' for available commands.`);
|
||||
}
|
||||
|
||||
if (area === "webhook" && action === "material-pack" && maybeName === "preview") {
|
||||
const filePath = args.command[3] ?? stringOption(args.options.file) ?? stringOption(args.options.input);
|
||||
if (!filePath) throw new Error("Usage: seal-use webhook material-pack preview <材料包.zip>");
|
||||
await handleWebhookMaterialPackPreview(filePath);
|
||||
return;
|
||||
}
|
||||
|
||||
if (area === "openapi") {
|
||||
handleOpenApiCommand(args);
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { pinyin } from "pinyin-pro";
|
||||
import type { MaterialAttachmentPlan, MaterialDocument, MaterialField } from "./types.js";
|
||||
import type { ZipEntry } from "./validate.js";
|
||||
|
||||
function keyFromLabel(value: string): string {
|
||||
const label = value.replace(/^\d+[\s.\-_—]*/, "").trim();
|
||||
const parts = pinyin(label, { toneType: "none", type: "all", nonZh: "consecutive" })
|
||||
.map((item: any) => item.pinyin ? item.pinyin : String(item.origin).toLowerCase().replace(/[^a-z0-9]+/g, ""))
|
||||
.filter(Boolean);
|
||||
return parts.join("") || "attachments";
|
||||
}
|
||||
|
||||
export function buildAttachmentPlans(entries: ZipEntry[], documents: Array<{ document: MaterialDocument; laborNames: string[] }>): MaterialAttachmentPlan[] {
|
||||
return documents.map(({ document, laborNames }) => {
|
||||
const plan: MaterialAttachmentPlan = { documentId: document.documentId, categoryFields: [], personAttachments: {} };
|
||||
for (const entry of entries) {
|
||||
if (entry.fileName === "信息表.xlsx") continue;
|
||||
const segments = entry.fileName.split("/");
|
||||
if (segments[0] !== document.documentId || segments.length < 2) continue;
|
||||
const add = (list: Array<{ key: string; label: string; entries: any[] }>, label: string) => {
|
||||
const clean = label.replace(/^\d+[\s.\-_—]*/, "");
|
||||
const item = list.find((value) => value.label === clean) ?? { key: clean === "附件" ? "attachments" : keyFromLabel(clean), label: clean, entries: [] };
|
||||
if (!list.includes(item)) list.push(item);
|
||||
item.entries.push({ fileName: entry.fileName, path: entry.fileName, size: entry.uncompressedSize });
|
||||
};
|
||||
if (segments.length === 2) add(plan.categoryFields, "附件");
|
||||
else if (laborNames.includes(segments[1]!)) {
|
||||
const list = plan.personAttachments[segments[1]!] ?? (plan.personAttachments[segments[1]!] = []);
|
||||
add(list, segments.length === 3 ? "附件" : segments[2]!);
|
||||
} else add(plan.categoryFields, segments[1]!);
|
||||
}
|
||||
return plan;
|
||||
});
|
||||
}
|
||||
|
||||
export function injectAttachmentPlan(document: MaterialDocument, plan: MaterialAttachmentPlan, uploaded: Map<string, unknown[]>): MaterialDocument {
|
||||
const clone = structuredClone(document);
|
||||
const lookup = (path: string) => uploaded.get(path) ?? [];
|
||||
for (const category of plan.categoryFields) {
|
||||
const value = category.entries.flatMap((entry) => lookup(entry.path));
|
||||
clone.fields.push({ key: category.key, label: category.label, type: "ATTACHMENT", value });
|
||||
}
|
||||
const list = clone.fields.find((item) => item.key === "daoshi_list" && item.type === "LIST");
|
||||
if (list && Array.isArray(list.value)) {
|
||||
for (const row of list.value as MaterialField[][]) {
|
||||
const name = row.find((item) => item.key === "name")?.value;
|
||||
for (const category of plan.personAttachments[String(name)] ?? []) row.push({ key: category.key, label: category.label, type: "ATTACHMENT", value: category.entries.flatMap((entry) => lookup(entry.path)) });
|
||||
}
|
||||
}
|
||||
return clone;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
export * from "./types.js";
|
||||
export * from "./signature.js";
|
||||
export * from "./validate.js";
|
||||
export * from "./parse.js";
|
||||
export * from "./attachments.js";
|
||||
export * from "./service.js";
|
||||
@@ -0,0 +1,29 @@
|
||||
import ExcelJS from "exceljs";
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { previewMaterialPack } from "./service.js";
|
||||
import { signWebhookPayload } from "./signature.js";
|
||||
|
||||
async function workbookBuffer() {
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
const main = workbook.addWorksheet("会议");
|
||||
main.addRow(["会议编号", "会议名称", "总金额", "申请日期"]);
|
||||
main.addRow(["DOC-001", "测试单据", 100, "2026-09-03 12:00:00"]);
|
||||
const labor = workbook.addWorksheet("劳务明细");
|
||||
labor.addRow(["会议编号", "姓名", "劳务费用"]);
|
||||
labor.addRow(["DOC-001", "张三", 100]);
|
||||
return Buffer.from(await workbook.xlsx.writeBuffer());
|
||||
}
|
||||
|
||||
describe("Webhook material pack", () => {
|
||||
test("previews official workbook shape without network access", async () => {
|
||||
const result = await previewMaterialPack(await workbookBuffer(), "材料包.xlsx");
|
||||
expect(result.documents).toHaveLength(1);
|
||||
expect(result.documents[0]).toMatchObject({ documentId: "DOC-001", documentSN: "DOC-001" });
|
||||
expect(result.documents[0]?.fields).toContainEqual(expect.objectContaining({ key: "daoshi_list", type: "LIST" }));
|
||||
});
|
||||
|
||||
test("uses the confirmed timestamp.nonce.payload HMAC contract", () => {
|
||||
expect(signWebhookPayload(1700000000, "nonce", { webhookId: "wh-1", value: 1 }, "secret"))
|
||||
.toBe("d65d858afb6adc33dc640ebc6b259861c2b73ef0e6f0995ff822b41465fbfdf1");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,99 @@
|
||||
import ExcelJS from "exceljs";
|
||||
import { MaterialPackValidationError, type MaterialDocument, type MaterialField } from "./types.js";
|
||||
|
||||
type Parsed = { document: MaterialDocument; laborNames: string[] };
|
||||
|
||||
function field(key: string, label: string, type: string, value: unknown): MaterialField {
|
||||
return { key, label, type, value };
|
||||
}
|
||||
|
||||
function text(key: string, label: string, value: unknown) {
|
||||
return field(key, label, "TEXT", value == null ? "" : String(value));
|
||||
}
|
||||
|
||||
function amount(key: string, label: string, value: unknown) {
|
||||
return field(key, label, "AMOUNT", typeof value === "number" ? { amount: value, currency: "CNY" } : null);
|
||||
}
|
||||
|
||||
function dateValue(value: unknown): string | null {
|
||||
if (value instanceof Date) return value.toISOString();
|
||||
if (typeof value === "string" && value.trim()) return value.trim();
|
||||
return null;
|
||||
}
|
||||
|
||||
function startTimeValue(value: unknown): number | null {
|
||||
if (value instanceof Date) return Math.floor(value.getTime() / 1000);
|
||||
if (typeof value === "string" && value.trim()) {
|
||||
const timestamp = Date.parse(value.trim().replace(" ", "T"));
|
||||
if (Number.isFinite(timestamp)) return Math.floor(timestamp / 1000);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function headerMap(sheet: ExcelJS.Worksheet): Map<string, number> {
|
||||
const map = new Map<string, number>();
|
||||
sheet.getRow(1).eachCell((cell, index) => map.set(String(cell.value ?? "").trim(), index));
|
||||
return map;
|
||||
}
|
||||
|
||||
function cell(row: ExcelJS.Row, map: Map<string, number>, name: string): unknown {
|
||||
const index = map.get(name);
|
||||
return index ? row.getCell(index).value : undefined;
|
||||
}
|
||||
|
||||
function buildMainFields(row: ExcelJS.Row, map: Map<string, number>): MaterialField[] {
|
||||
const specs: Array<[string, string, string]> = [
|
||||
["会议编号", "meeting_id", "TEXT"], ["会议名称", "meeting_name", "TEXT"], ["状态", "status", "TEXT"],
|
||||
["总金额", "total_amount", "AMOUNT"], ["税前劳务总额", "pretax_labor_total", "AMOUNT"],
|
||||
["报销事由", "reimbursement_reason", "TEXT"], ["po码", "po_code", "TEXT"], ["快递单号", "tracking_number", "TEXT"],
|
||||
["申请日期", "application_date", "DATE"], ["更新日期", "updated_date", "DATE"]
|
||||
];
|
||||
return specs.flatMap(([label, key, type]) => {
|
||||
const value = cell(row, map, label);
|
||||
if (value == null || value === "") return [];
|
||||
return [type === "TEXT" ? text(key, label, value) : type === "AMOUNT" ? amount(key, label, value) : field(key, label, type, dateValue(value))];
|
||||
});
|
||||
}
|
||||
|
||||
function buildDetailFields(row: ExcelJS.Row, map: Map<string, number>, specs: Array<[string, string, string]>): MaterialField[] {
|
||||
return specs.flatMap(([label, key, type]) => {
|
||||
const value = cell(row, map, label);
|
||||
if (value == null || value === "") return [];
|
||||
return [type === "TEXT" ? text(key, label, value) : type === "AMOUNT" ? amount(key, label, value) : field(key, label, type, dateValue(value))];
|
||||
});
|
||||
}
|
||||
|
||||
const laborSpecs: Array<[string, string, string]> = [["姓名", "name", "TEXT"], ["身份证号码", "id_number", "TEXT"], ["手机号", "phone", "TEXT"], ["劳务费用", "labor_fee", "AMOUNT"], ["税前费用", "pretax_fee", "AMOUNT"], ["开户行", "bank", "TEXT"], ["支行名称", "branch_name", "TEXT"], ["联行号", "bank_code", "TEXT"], ["银行卡号", "bank_card_number", "TEXT"]];
|
||||
const expenseSpecs: Array<[string, string, string]> = [["报销金额", "reimbursement_amount", "AMOUNT"], ["费用类型", "expense_type", "TEXT"], ["发生时间", "occurrence_time", "DATE"], ["收款人", "payee", "TEXT"], ["开户行", "bank", "TEXT"], ["支行名称", "branch_name", "TEXT"], ["支行行号", "branch_code", "TEXT"], ["银行卡号", "bank_card_number", "TEXT"], ["费用说明", "expense_description", "TEXT"]];
|
||||
|
||||
export async function parseMaterialWorkbook(buffer: Uint8Array): Promise<Parsed[]> {
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
await workbook.xlsx.load(Buffer.from(buffer) as any);
|
||||
if (!workbook.worksheets.length) throw new MaterialPackValidationError(["信息表没有任何 Sheet"]);
|
||||
const sheets = workbook.worksheets;
|
||||
const mainSheet = sheets[0]!;
|
||||
const maps = sheets.map(headerMap);
|
||||
const mainMap = maps[0]!;
|
||||
const idColumn = mainMap.get("会议编号") ?? 1;
|
||||
const mainRows = (mainSheet.getRows(2, mainSheet.rowCount) ?? []).filter((row) => row.getCell(idColumn).value != null && row.getCell(idColumn).value !== "");
|
||||
const ids = new Set<string>();
|
||||
const parsed: Parsed[] = mainRows.map((row) => {
|
||||
const id = String(row.getCell(idColumn).value).trim();
|
||||
if (!id) throw new MaterialPackValidationError(["主表会议编号不能为空"]);
|
||||
if (ids.has(id)) throw new MaterialPackValidationError([`主表会议编号重复: ${id}`]);
|
||||
ids.add(id);
|
||||
const apply = cell(row, mainMap, "申请日期");
|
||||
const laborSheet = sheets.find((sheet, index) => index > 0 && headerMap(sheet).has("姓名"));
|
||||
const expenseSheet = sheets.find((sheet, index) => index > 0 && headerMap(sheet).has("报销金额"));
|
||||
const laborMap = laborSheet ? headerMap(laborSheet) : undefined;
|
||||
const expenseMap = expenseSheet ? headerMap(expenseSheet) : undefined;
|
||||
const laborRows = (laborSheet?.getRows(2, laborSheet.rowCount) ?? []).filter((r) => String(cell(r, laborMap!, "会议编号") ?? "").trim() === id);
|
||||
const expenseRows = (expenseSheet?.getRows(2, expenseSheet.rowCount) ?? []).filter((r) => String(cell(r, expenseMap!, "会议编号") ?? "").trim() === id);
|
||||
const laborNames = laborRows.map((r) => String(cell(r, headerMap(laborSheet!), "姓名") ?? "").trim()).filter(Boolean);
|
||||
const fields = buildMainFields(row, mainMap);
|
||||
if (laborRows.length) fields.push({ key: "daoshi_list", label: "导师列表", type: "LIST", value: laborRows.map((r) => buildDetailFields(r, laborMap!, laborSpecs)) });
|
||||
if (expenseRows.length) fields.push({ key: "mingxi_list", label: "明细列表", type: "LIST", value: expenseRows.map((r) => buildDetailFields(r, expenseMap!, expenseSpecs)) });
|
||||
return { laborNames, document: { type: "document", documentId: id, documentSN: id, startTime: startTimeValue(apply), fields } };
|
||||
});
|
||||
return parsed;
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { webhookHeaders } from "./signature.js";
|
||||
import { buildAttachmentPlans, injectAttachmentPlan } from "./attachments.js";
|
||||
import { parseMaterialWorkbook } from "./parse.js";
|
||||
import { extractZipEntry, readZipEntries, validatePackEntries, type ZipEntry } from "./validate.js";
|
||||
import type { MaterialPackPreview, MaterialPackPushResult } from "./types.js";
|
||||
|
||||
function webhookInfo(url: string): { baseUrl: string; webhookId: string } {
|
||||
const parsed = new URL(url);
|
||||
const match = parsed.pathname.match(/\/webhook\/([^/]+)/);
|
||||
if (!match) throw new Error("Webhook URL 必须包含 /webhook/{webhookId}/document");
|
||||
return { baseUrl: `${parsed.protocol}//${parsed.host}`, webhookId: match[1]! };
|
||||
}
|
||||
|
||||
function isZip(buffer: Uint8Array, fileName: string): boolean {
|
||||
return fileName.toLowerCase().endsWith(".zip") || (buffer[0] === 0x50 && buffer[1] === 0x4b && !fileName.toLowerCase().endsWith(".xlsx"));
|
||||
}
|
||||
|
||||
async function prepare(fileBuffer: Uint8Array, fileName: string) {
|
||||
let entries: ZipEntry[] = [];
|
||||
let workbook = fileBuffer;
|
||||
if (isZip(fileBuffer, fileName)) {
|
||||
entries = await readZipEntries(fileBuffer);
|
||||
validatePackEntries(entries);
|
||||
const info = entries.find((entry) => entry.fileName === "信息表.xlsx");
|
||||
if (!info) throw new Error("ZIP 根目录缺少信息表.xlsx");
|
||||
workbook = await extractZipEntry(fileBuffer, info);
|
||||
}
|
||||
const parsed = await parseMaterialWorkbook(workbook);
|
||||
const plans = buildAttachmentPlans(entries, parsed);
|
||||
const documents = parsed.map((item) => item.document);
|
||||
return { entries, parsed, plans, documents, fileBuffer };
|
||||
}
|
||||
|
||||
export async function previewMaterialPack(fileBuffer: Uint8Array, fileName: string): Promise<MaterialPackPreview> {
|
||||
const prepared = await prepare(fileBuffer, fileName);
|
||||
return { warnings: [], documents: prepared.documents, attachmentPlan: prepared.plans };
|
||||
}
|
||||
|
||||
export async function pushMaterialPack(fileBuffer: Uint8Array, fileName: string, config: { webhookUrl: string; secret: string }): Promise<MaterialPackPushResult> {
|
||||
const prepared = await prepare(fileBuffer, fileName);
|
||||
const { baseUrl, webhookId } = webhookInfo(config.webhookUrl);
|
||||
const results: MaterialPackPushResult["results"] = [];
|
||||
for (let index = 0; index < prepared.parsed.length; index += 1) {
|
||||
const item = prepared.parsed[index]!;
|
||||
const plan = prepared.plans[index]!;
|
||||
const uploaded = new Map<string, unknown[]>();
|
||||
for (const category of [...plan.categoryFields, ...Object.values(plan.personAttachments).flat()]) {
|
||||
for (const entry of category.entries) {
|
||||
const zipEntry = prepared.entries.find((candidate) => candidate.fileName === entry.path);
|
||||
if (!zipEntry) continue;
|
||||
const body = new FormData();
|
||||
const attachment = await extractZipEntry(prepared.fileBuffer, zipEntry);
|
||||
body.append("files", new File([new Uint8Array(attachment)], entry.fileName));
|
||||
const response = await fetch(`${baseUrl}/api/v1/integrations/webhook/${encodeURIComponent(webhookId)}/attachments`, { method: "POST", headers: webhookHeaders({}, config.secret), body });
|
||||
if (!response.ok) throw new Error(`附件上传失败 ${response.status}: ${await response.text()}`);
|
||||
const json = await response.json() as { data?: unknown; attachments?: Array<{ data: unknown }> };
|
||||
uploaded.set(entry.path, json.attachments?.map((value) => value.data) ?? (json.data === undefined ? [] : [json.data]));
|
||||
}
|
||||
}
|
||||
const document = injectAttachmentPlan(item.document, plan, uploaded);
|
||||
const response = await fetch(`${baseUrl}/api/v1/integrations/webhook/${encodeURIComponent(webhookId)}/document`, { method: "POST", headers: { "Content-Type": "application/json", ...webhookHeaders({ webhookId, ...document }, config.secret) }, body: JSON.stringify(document) });
|
||||
if (!response.ok) throw new Error(`Webhook 单据推送失败 ${response.status}: ${await response.text()}`);
|
||||
results.push({ documentId: document.documentId, document, pushResult: await response.json() });
|
||||
}
|
||||
return { warnings: [], results };
|
||||
}
|
||||
|
||||
export function readMaterialPackFile(filePath: string): { fileBuffer: Buffer; fileName: string } {
|
||||
return { fileBuffer: readFileSync(filePath), fileName: filePath.split(/[\\/]/).pop() ?? "material-pack.zip" };
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { createHmac, randomBytes } from "node:crypto";
|
||||
|
||||
export function signWebhookPayload(timestamp: number, nonce: string, payload: unknown, secret: string): string {
|
||||
return createHmac("sha256", secret)
|
||||
.update(`${timestamp}.${nonce}.${JSON.stringify(payload)}`)
|
||||
.digest("hex");
|
||||
}
|
||||
|
||||
export function webhookHeaders(payload: unknown, secret: string): Record<string, string> {
|
||||
const timestamp = Math.floor(Date.now() / 1000);
|
||||
const nonce = randomBytes(16).toString("hex");
|
||||
return {
|
||||
Authorization: `Bearer ${secret}`,
|
||||
"x-webhook-signature": signWebhookPayload(timestamp, nonce, payload, secret),
|
||||
"x-webhook-timestamp": String(timestamp),
|
||||
"x-webhook-nonce": nonce
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
export type MaterialField = {
|
||||
key: string;
|
||||
label: string;
|
||||
type: string;
|
||||
value: unknown;
|
||||
};
|
||||
|
||||
export type MaterialDocument = {
|
||||
type: "document";
|
||||
documentId: string;
|
||||
documentSN: string;
|
||||
startTime: number | null;
|
||||
fields: MaterialField[];
|
||||
};
|
||||
|
||||
export type MaterialAttachmentEntry = {
|
||||
fileName: string;
|
||||
size: number;
|
||||
path: string;
|
||||
};
|
||||
|
||||
export type MaterialAttachmentPlan = {
|
||||
documentId: string;
|
||||
categoryFields: Array<{ key: string; label: string; entries: MaterialAttachmentEntry[] }>;
|
||||
personAttachments: Record<string, Array<{ key: string; label: string; entries: MaterialAttachmentEntry[] }>>;
|
||||
};
|
||||
|
||||
export type MaterialPackPreview = {
|
||||
warnings: string[];
|
||||
documents: MaterialDocument[];
|
||||
attachmentPlan: MaterialAttachmentPlan[];
|
||||
};
|
||||
|
||||
export type MaterialPackPushResult = {
|
||||
warnings: string[];
|
||||
results: Array<{ documentId: string; document: MaterialDocument; pushResult: unknown }>;
|
||||
};
|
||||
|
||||
export class MaterialPackValidationError extends Error {
|
||||
constructor(public readonly errors: string[], public readonly warnings: string[] = []) {
|
||||
super(`材料包校验失败:${errors.length} 个错误`);
|
||||
this.name = "MaterialPackValidationError";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import yauzl from "yauzl";
|
||||
import iconv from "iconv-lite";
|
||||
import { MaterialPackValidationError } from "./types.js";
|
||||
|
||||
export const MATERIAL_PACK_LIMITS = { maxEntries: 1000, maxTotalSize: 500 * 1024 * 1024, maxCompressionRatio: 150 };
|
||||
|
||||
export type ZipEntry = { fileName: string; uncompressedSize: number; compressedSize: number; raw: unknown };
|
||||
|
||||
export async function readZipEntries(buffer: Uint8Array): Promise<ZipEntry[]> {
|
||||
return new Promise((resolve, reject) => {
|
||||
yauzl.fromBuffer(Buffer.from(buffer), { lazyEntries: true, autoClose: true }, (openError: Error | null, zipFile: any) => {
|
||||
if (openError || !zipFile) return reject(openError ?? new Error("无法打开 ZIP"));
|
||||
const entries: ZipEntry[] = [];
|
||||
zipFile.readEntry();
|
||||
zipFile.on("entry", (entry: any) => {
|
||||
const fileName = decodeZipEntryName(entry);
|
||||
if (!fileName.endsWith("/") && !isJunk(fileName)) {
|
||||
entries.push({ fileName, uncompressedSize: entry.uncompressedSize, compressedSize: entry.compressedSize, raw: entry });
|
||||
}
|
||||
zipFile.readEntry();
|
||||
});
|
||||
zipFile.on("end", () => resolve(entries));
|
||||
zipFile.on("error", reject);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function decodeZipEntryName(entry: any): string {
|
||||
if (entry.fileNameUTF8 || (entry.generalPurposeBitFlag & 0x800)) return entry.fileNameUTF8 ?? entry.fileName;
|
||||
const raw = Buffer.from(String(entry.fileName), "binary");
|
||||
const utf8 = raw.toString("utf8");
|
||||
if (utf8.includes("\uFFFD") || /[\u0080-\u00FF]/.test(utf8)) {
|
||||
const gbk = iconv.decode(raw, "gbk");
|
||||
if (!gbk.includes("\uFFFD")) return gbk;
|
||||
}
|
||||
return utf8;
|
||||
}
|
||||
|
||||
export function isJunk(name: string): boolean {
|
||||
const base = name.split("/").pop() ?? "";
|
||||
return name.split("/").includes("__MACOSX") || base === ".DS_Store" || base.startsWith("._") || base.startsWith(".~") || base.startsWith("~$");
|
||||
}
|
||||
|
||||
export function validatePackEntries(entries: ZipEntry[]): void {
|
||||
const errors: string[] = [];
|
||||
if (entries.length > MATERIAL_PACK_LIMITS.maxEntries) errors.push(`文件数超过 ${MATERIAL_PACK_LIMITS.maxEntries}`);
|
||||
const total = entries.reduce((sum, entry) => sum + entry.uncompressedSize, 0);
|
||||
if (total > MATERIAL_PACK_LIMITS.maxTotalSize) errors.push("解压后总大小超过 500MB");
|
||||
for (const entry of entries) {
|
||||
if (entry.fileName.startsWith("/") || entry.fileName.split("/").includes("..")) errors.push(`存在不安全路径: ${entry.fileName}`);
|
||||
if (entry.compressedSize > 0 && entry.uncompressedSize / entry.compressedSize > MATERIAL_PACK_LIMITS.maxCompressionRatio) errors.push(`压缩比超过 150: ${entry.fileName}`);
|
||||
}
|
||||
const info = entries.find((entry) => entry.fileName === "信息表.xlsx");
|
||||
if (!info) errors.push("ZIP 根目录缺少精确名为「信息表.xlsx」的文件");
|
||||
if (entries.some((entry) => entry.fileName.toLowerCase().endsWith(".zip"))) errors.push("不允许嵌套 ZIP");
|
||||
if (errors.length) throw new MaterialPackValidationError(errors);
|
||||
}
|
||||
|
||||
export function extractZipEntry(buffer: Uint8Array, target: ZipEntry): Promise<Buffer> {
|
||||
return new Promise((resolve, reject) => {
|
||||
yauzl.fromBuffer(Buffer.from(buffer), { lazyEntries: true, autoClose: true }, (openError: Error | null, zipFile: any) => {
|
||||
if (openError || !zipFile) return reject(openError ?? new Error("无法打开 ZIP"));
|
||||
zipFile.readEntry();
|
||||
zipFile.on("entry", (entry: any) => {
|
||||
if (decodeZipEntryName(entry) !== target.fileName) return zipFile.readEntry();
|
||||
zipFile.openReadStream(entry, (error: Error | null, stream: any) => {
|
||||
if (error || !stream) return reject(error ?? new Error(`无法读取 ${target.fileName}`));
|
||||
const chunks: Buffer[] = [];
|
||||
stream.on("data", (chunk: Buffer) => chunks.push(chunk));
|
||||
stream.on("end", () => resolve(Buffer.concat(chunks)));
|
||||
stream.on("error", reject);
|
||||
});
|
||||
});
|
||||
zipFile.on("error", reject);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -235,6 +235,7 @@ describe("sealTools", () => {
|
||||
"seal_whoami",
|
||||
"seal_approval_search",
|
||||
"seal_approval_context_get",
|
||||
"seal_webhook_material_pack",
|
||||
"seal_runs_search",
|
||||
"seal_action"
|
||||
]);
|
||||
@@ -1034,4 +1035,3 @@ function fakeDeployClient(): KyInstance {
|
||||
}
|
||||
} as unknown as KyInstance;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import { loadGlobalConfig } from "../../core/config/loader.js";
|
||||
import { createSealClientForToken } from "../../core/http/factory.js";
|
||||
import { searchApprovalContent } from "./search.js";
|
||||
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "./linter/index.js";
|
||||
import { previewMaterialPack, pushMaterialPack, readMaterialPackFile } from "./material-pack/index.js";
|
||||
import {
|
||||
ThinkingPolicySchema,
|
||||
type ApprovalRule,
|
||||
@@ -1361,6 +1362,25 @@ export const sealTools = [
|
||||
};
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_webhook_material_pack",
|
||||
description: "将官方材料包格式本地校验、解析并通过 Seal 入站 Webhook 触发 AI 审批;preview 模式不联网",
|
||||
parameters: z.object({
|
||||
filePath: z.string().describe("材料包 ZIP 或 信息表.xlsx 文件路径"),
|
||||
mode: z.enum(["preview", "push"]).default("preview"),
|
||||
webhook: z.string().optional().describe("Webhook ID 或名称,push 模式必填")
|
||||
}),
|
||||
handler: async (client: KyInstance, params: { filePath: string; mode?: "preview" | "push"; webhook?: string }) => {
|
||||
const input = readMaterialPackFile(params.filePath);
|
||||
if (params.mode !== "push") return previewMaterialPack(input.fileBuffer, input.fileName);
|
||||
if (!params.webhook) throw new Error("push 模式需要 webhook");
|
||||
const integration = api.findWebhookIntegration(await api.listWebhookIntegrations(client), params.webhook);
|
||||
return pushMaterialPack(input.fileBuffer, input.fileName, {
|
||||
webhookUrl: integration.incomingDocumentWebhook.url,
|
||||
secret: integration.secret
|
||||
});
|
||||
}
|
||||
},
|
||||
{
|
||||
name: "seal_approval_run_langfuse_bridge_get",
|
||||
description: "从 Seal approval run 中抽取 Langfuse 定位信息;优先返回 _langfuseTraceId,没有时给出 hosecloud-{sourceDocumentSN} session 回退",
|
||||
@@ -1842,7 +1862,8 @@ const sealToolByName = new Map<string, SealTool>(
|
||||
const mcpDirectToolNames = [
|
||||
"seal_whoami",
|
||||
"seal_approval_search",
|
||||
"seal_approval_context_get"
|
||||
"seal_approval_context_get",
|
||||
"seal_webhook_material_pack"
|
||||
] as const;
|
||||
|
||||
const sealActionNames = [
|
||||
|
||||
Reference in new issue
Block a user