import ExcelJS from "exceljs" import { MaterialPackValidationError, type MaterialDocument, type MaterialField } from "./types.js" export type DeclaredAttachment = { key: string; label: string; paths: string[] } export type Parsed = { document: MaterialDocument; laborNames: string[]; documentAttachments: DeclaredAttachment[]; expenseAttachments: Record; personAttachments: Record; } // ─── Attachment column helpers ─────────────────────────────────────────────── export function isAttachmentColumn(label: string): boolean { return label.startsWith("[附件]") } export function attachmentLabel(label: string): string { return label.startsWith("[附件]") ? label.slice(4) : label } export function attachmentKey(label: string): string { const stripped = attachmentLabel(label) return stripped.toLowerCase().replace(/\s+/g, "_") || "attachment" } export function parsePaths(raw: unknown): string[] { if (raw == null || raw === "") return [] return String(raw) .split(/[\n,;,;]/) .map((s) => s.trim()) .filter(Boolean) } export function collectRowAttachments( row: ExcelJS.Row, map: Map ): DeclaredAttachment[] { const groups: DeclaredAttachment[] = [] for (const [colLabel, colIdx] of map.entries()) { if (!isAttachmentColumn(colLabel)) continue const raw = row.getCell(colIdx).value const paths = parsePaths(raw) if (!paths.length) continue groups.push({ key: attachmentKey(colLabel), label: attachmentLabel(colLabel), paths, }) } return groups } // ─── Key deduplication ─────────────────────────────────────────────────────── function deduplicateKeys(groups: DeclaredAttachment[]): DeclaredAttachment[] { const seen = new Map() return groups.map((g) => { const count = (seen.get(g.key) ?? 0) + 1 seen.set(g.key, count) return count === 1 ? g : { ...g, key: `${g.key}-${count}` } }) } // ─── Field builders ────────────────────────────────────────────────────────── 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 { const map = new Map() sheet.getRow(1).eachCell((cell, index) => map.set(String(cell.value ?? "").trim(), index)) return map } function cell(row: ExcelJS.Row, map: Map, name: string): unknown { const index = map.get(name) return index ? row.getCell(index).value : undefined } function buildMainFields(row: ExcelJS.Row, map: Map): 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, 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"]] // ─── Main parser ───────────────────────────────────────────────────────────── export async function parseMaterialWorkbook(buffer: Uint8Array): Promise { 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 mainMap = headerMap(mainSheet) 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() 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 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 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, laborMap!, "姓名") ?? "").trim()) .filter(Boolean) // Collect attachment declarations from main sheet row const documentAttachments = deduplicateKeys(collectRowAttachments(row, mainMap)) // Collect expense attachment declarations per row index const expenseAttachments: Record = {} expenseRows.forEach((r, rowIdx) => { const groups = deduplicateKeys(collectRowAttachments(r, expenseMap!)) if (groups.length) expenseAttachments[rowIdx] = groups }) // Collect person attachment declarations per person name const personAttachments: Record = {} laborRows.forEach((r) => { const name = String(cell(r, laborMap!, "姓名") ?? "").trim() if (!name) return const groups = deduplicateKeys(collectRowAttachments(r, laborMap!)) if (groups.length) personAttachments[name] = groups }) 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, documentAttachments, expenseAttachments, personAttachments, document: { type: "document", documentId: id, documentSN: id, startTime: startTimeValue(apply), fields }, } }) return parsed }