/** * Pure helper functions for the Stock-In Excel import/export feature. * * These functions have no DOM dependencies and are fully unit-testable * against a real in-memory xlsx workbook. All DOM-specific work (file input, * download trigger, FileReader/arrayBuffer) lives in the component. * * NO file upload, NO drive-service call — everything is in-browser only. */ import * as XLSX from "xlsx"; import type { SkuCatalogRow, StockInLineInput } from "@/app/lib/types"; import type { Translate } from "@/app/lib/i18n/t"; // ─── Column layout ──────────────────────────────────────────────────────────── /** Column headers, in order. The visible columns come first; skuVariationId is last (hidden). */ export const STOCK_IN_HEADERS = [ "SKU Code", "SKU Name", "Variation", "Quantity", "Batch Number", "Expiry (YYYY-MM-DD)", "skuVariationId", ] as const; /** 0-based column index of the hidden skuVariationId column. */ const SKU_VARIATION_ID_COL = 6; const EXPIRY_COL = 5; // ─── Template builder ───────────────────────────────────────────────────────── /** * Build a pre-filled Stock-In template workbook from the SKU catalog. * Returns raw bytes (Uint8Array) suitable for a browser Blob / download. * * Sheet "Stock In": * - Header row with the canonical column names. * - One row per catalog entry, pre-filled with SKU Code / SKU Name / Variation / * skuVariationId. Quantity / Batch Number / Expiry are left blank. * - The skuVariationId column (index 6) is marked hidden via `!cols`. * * Sheet "Instructions": usage guidance for the admin. */ export function buildStockInWorkbook(catalog: SkuCatalogRow[]): Uint8Array { const wb = XLSX.utils.book_new(); // ─── Sheet 1: Stock In ──────────────────────────────────────────────────── // aoa_to_sheet: first row = headers; subsequent rows = one per catalog entry. // null cells (Quantity/Batch/Expiry) are written as empty — they don't appear // in sheet_to_json output (key is absent), which parseStockInWorkbook treats as // "blank → skip". skuVariationId is a string to avoid Snowflake precision loss. const wsData: (string | null)[][] = [ [...STOCK_IN_HEADERS], ...catalog.map(row => [ row.skuCode, row.skuName, row.variation, null, // Quantity — admin fills in null, // Batch Number null, // Expiry (YYYY-MM-DD) row.skuVariationId, ]), ]; const ws = XLSX.utils.aoa_to_sheet(wsData); // Text format on Expiry so a typed 2027-12-31 stays text where Excel honours it. Every data row gets a // cell (aoa_to_sheet skips nulls), so typing into an empty row is formatted too. for (let r = 1; r <= catalog.length; r++) ws[XLSX.utils.encode_cell({ r, c: EXPIRY_COL })] = { t: "s", v: "", z: "@" }; // Mark the skuVariationId column as hidden. SheetJS community build supports // the `hidden` flag on column descriptors (full sheet protection is not // reliably available in the community build and is not required by spec). // BABYBOO-50: a `{}` entry is written as a width-less , which Excel opens at zero width, so // column A was missing. Every visible column gets a width: the header plus padding, at least 14. ws["!cols"] = STOCK_IN_HEADERS.map((header, i) => i === SKU_VARIATION_ID_COL ? { hidden: true } : { wch: Math.max(14, header.length + 4) }, ); XLSX.utils.book_append_sheet(wb, ws, "Stock In"); // ─── Sheet 2: Instructions ───────────────────────────────────────────────── const instructionData = [ ["Stock-In Import Instructions"], [""], ["1. Fill in Quantity for the rows you are booking in. Leave other rows blank or set Quantity to 0."], ["2. Do not edit SKU Code, SKU Name, Variation, or skuVariationId — these are pre-filled from the catalog."], ["3. Batch Number is optional."], ["4. Expiry date must be in YYYY-MM-DD format (e.g. 2027-12-31). Leave blank if not applicable."], ["5. Pick the destination warehouse in the Stock-In page before importing."], ["6. Click 'Import' to load the filled rows into the form for review, then click Submit."], ["7. Do NOT unhide or edit the hidden skuVariationId column — editing it will cause the row to be rejected on import."], ["8. Do NOT round-trip this file through Google Sheets — it can corrupt the long internal IDs. Use Excel or LibreOffice instead."], ]; const wsInstructions = XLSX.utils.aoa_to_sheet(instructionData); XLSX.utils.book_append_sheet(wb, wsInstructions, "Instructions"); // SheetJS 0.18.5 returns an ArrayBuffer for type:"array" (NOT a Uint8Array), // whose `.buffer` is undefined — reading it broke the download (a 9-byte // "undefined" file). Normalize to a Uint8Array so callers get a valid, // version-stable BlobPart regardless of what this SheetJS build returns. const out = XLSX.write(wb, { type: "array", bookType: "xlsx" }); // Always wrap into a fresh Uint8Array: guarantees a valid BlobPart // (its .buffer is a plain ArrayBuffer, never SharedArrayBuffer) regardless of // whether this SheetJS build returned an ArrayBuffer or a Uint8Array. return out instanceof Uint8Array ? new Uint8Array(out) : new Uint8Array(out as ArrayBuffer); } // ─── Workbook parser ────────────────────────────────────────────────────────── /** Regex for YYYY-MM-DD expiry validation. */ const EXPIRY_RE = /^\d{4}-\d{2}-\d{2}$/; /** * Parse rows from the "Stock In" sheet — the output of * `XLSX.utils.sheet_to_json(sheet)` (header row already consumed; rows are * objects keyed by column name). * * Rules: * - Row with blank/absent or zero Quantity → silently ignored (no error). * - Row with Quantity > 0: * - Missing/blank `skuVariationId` → pushed to `errors` (NOT dropped silently). * - Present `Expiry (YYYY-MM-DD)` that does not match YYYY-MM-DD → error. * - Otherwise → added to `lines`. * * Row numbers in error messages are 1-based xlsx rows (header = 1, data = 2+). * * @param rows - Direct output of XLSX.utils.sheet_to_json for the "Stock In" sheet. * @param t - Translation function. * @returns { lines, errors } — lines ready for the multi-line editor; errors for display. */ export function parseStockInWorkbook(rows: Record[], t: Translate): { lines: StockInLineInput[]; errors: string[]; } { const lines: StockInLineInput[] = []; const errors: string[] = []; for (let i = 0; i < rows.length; i++) { const row = rows[i]; // xlsx row number: header is 1, first data row is 2. const xlsxRow = i + 2; const rawQty = row["Quantity"]; // Blank / absent / zero quantity → the admin left the row empty. Silently skip. if (rawQty === undefined || rawQty === null || rawQty === "") continue; if (rawQty === 0) continue; // Non-numeric quantity (e.g. someone typed "five") → error. if (typeof rawQty !== "number" || !Number.isFinite(rawQty)) { errors.push(t("StockInRowQuantity", { row: xlsxRow })); continue; } // Negative quantity → treat as blank (not intended to book stock). if (rawQty <= 0) continue; // skuVariationId is required for the backend to resolve the SKU. const rawId = row["skuVariationId"]; const skuVariationId = rawId !== undefined && rawId !== null ? String(rawId).trim() : ""; if (!skuVariationId) { errors.push(t("StockInRowMissingSku", { row: xlsxRow })); continue; } // Expiry — optional. If present it must match YYYY-MM-DD. const rawExpiry = row["Expiry (YYYY-MM-DD)"]; let expiryDate: string | undefined; if (rawExpiry !== undefined && rawExpiry !== null && rawExpiry !== "") { const s = String(rawExpiry).trim(); if (!EXPIRY_RE.test(s)) { errors.push( t("StockInRowExpiry", { row: xlsxRow, value: s }), ); continue; } expiryDate = s; } // Batch number — optional. const rawBatch = row["Batch Number"]; const batchNumber = rawBatch !== undefined && rawBatch !== null && rawBatch !== "" ? String(rawBatch).trim() : undefined; const line: StockInLineInput = { skuVariationId, quantity: rawQty, ...(batchNumber !== undefined ? { batchNumber } : {}), ...(expiryDate !== undefined ? { expiryDate } : {}), }; lines.push(line); } return { lines, errors }; }