72 lines
4.2 KiB
TypeScript
72 lines
4.2 KiB
TypeScript
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" };
|
|
}
|