/** * Pure helpers for the Stock Transfer Excel template / import (in-browser only, no upload). * Mirrors stockInWorkbook.ts; DOM work lives in the component. */ import * as XLSX from "xlsx"; import type { StockOnHandRow, TransferLineInput } from "@/app/lib/types"; import type { Translate } from "@/app/lib/i18n/t"; export const TRANSFER_HEADERS = [ "SKU Code", "SKU Name", "Variation", "On Hand", "Quantity", "Batch Number", "Expiry (YYYY-MM-DD)", "skuVariationId", ] as const; /** 0-based column index of the hidden skuVariationId column. */ const SKU_VARIATION_ID_COL = 7; const EXPIRY_COL = 6; /** A parsed line plus the readable fields the review table shows. */ export interface TransferImportLine extends TransferLineInput { skuCode: string; skuName: string; variation: string; } /** Template of the source warehouse's stock: only rows with stockOnHand > 0. */ export function buildTransferWorkbook(rows: StockOnHandRow[]): Uint8Array { const wb = XLSX.utils.book_new(); // skuVariationId is a string to avoid Snowflake precision loss. const ws = XLSX.utils.aoa_to_sheet([ [...TRANSFER_HEADERS], ...rows .filter(r => r.stockOnHand > 0) .map(r => [r.skuCode, r.skuName, r.variation ?? null, r.stockOnHand, null, null, null, String(r.skuVariationId)]), ]); // 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. const lastRow = rows.filter(r => r.stockOnHand > 0).length + 1; for (let r = 1; r < lastRow; r++) ws[XLSX.utils.encode_cell({ r, c: EXPIRY_COL })] = { t: "s", v: "", z: "@" }; // BABYBOO-50: a `{}` col opens at zero width in Excel, so every visible column gets a width. ws["!cols"] = TRANSFER_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 Transfer"); const instructions = [ ["Stock Transfer Import Instructions"], [""], ["1. Fill in Quantity (whole units) for the rows you are transferring. Leave other rows blank or set Quantity to 0."], ["2. Do not edit SKU Code, SKU Name, Variation, On Hand, or skuVariationId. On Hand is the source stock when this file was downloaded."], ["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 source and destination warehouses on the Transfer 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."], ]; XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(instructions), "Instructions"); // SheetJS may return an ArrayBuffer or a Uint8Array; always wrap into a fresh Uint8Array. const out = XLSX.write(wb, { type: "array", bookType: "xlsx" }); return out instanceof Uint8Array ? new Uint8Array(out) : new Uint8Array(out as ArrayBuffer); } const EXPIRY_RE = /^\d{4}-\d{2}-\d{2}$/; const text = (v: unknown): string => (v === undefined || v === null ? "" : String(v).trim()); const EXPIRY_HEADER = "Expiry (YYYY-MM-DD)"; /** * Parse sheet_to_json rows of the "Stock Transfer" sheet. Blank/zero/negative quantity is skipped; * a non-numeric or fractional quantity, missing id or bad expiry is an error naming the xlsx row * (header = 1, first data row = 2). Nothing is silently dropped. */ export function parseTransferWorkbook(rows: Record[], t: Translate): { lines: TransferImportLine[]; errors: string[]; } { const lines: TransferImportLine[] = []; const errors: string[] = []; rows.forEach((row, i) => { const xlsxRow = i + 2; const rawQty = row["Quantity"]; if (rawQty === undefined || rawQty === null || rawQty === "" || rawQty === 0) return; if (typeof rawQty !== "number" || !Number.isFinite(rawQty)) { errors.push(t("StockInRowQuantity", { row: xlsxRow })); return; } if (rawQty < 0) return; if (!Number.isInteger(rawQty)) { errors.push(t("StockXferRowQuantityWhole", { row: xlsxRow })); return; } const skuVariationId = text(row["skuVariationId"]); if (!skuVariationId) { errors.push(t("StockInRowMissingSku", { row: xlsxRow })); return; } const expiry = text(row[EXPIRY_HEADER]); if (expiry && !EXPIRY_RE.test(expiry)) { errors.push(t("StockInRowExpiry", { row: xlsxRow, value: expiry })); return; } const batchNumber = text(row["Batch Number"]); lines.push({ skuVariationId, quantity: rawQty, ...(batchNumber ? { batchNumber } : {}), ...(expiry ? { expiryDate: expiry } : {}), skuCode: text(row["SKU Code"]), skuName: text(row["SKU Name"]), variation: text(row["Variation"]), }); }); return { lines, errors }; } /** * Per skuVariationId, how many units the summed lines exceed raw on-hand by (missing id = 0 on hand). * Mirrors the StockTransferService check; ids that fit are absent from the result. */ export function transferShortfalls( lines: { skuVariationId: string; quantity: number }[], onHandById: Map, ): Map { const totals = new Map(); for (const l of lines) totals.set(l.skuVariationId, (totals.get(l.skuVariationId) ?? 0) + l.quantity); const short = new Map(); for (const [id, total] of totals) { const gap = total - (onHandById.get(id) ?? 0); if (gap > 0) short.set(id, gap); } return short; }