/** * Pure-function unit tests for stockInWorkbook.ts. * Uses a real in-memory xlsx workbook — no DOM required. * Run: ./node_modules/.bin/vitest run app/lib/inventory */ import { describe, it, expect } from "vitest"; import { tEn } from "@/test/i18nCatalog"; import * as XLSX from "xlsx"; import { buildStockInWorkbook, parseStockInWorkbook } from "./stockInWorkbook"; import { readSheetRows } from "./workbookRows"; import type { SkuCatalogRow } from "@/app/lib/types"; const CATALOG: SkuCatalogRow[] = [ { skuVariationId: "100001", skuCode: "BB-001", skuName: "Baby Milk", variation: "100g" }, { skuVariationId: "100002", skuCode: "BB-001", skuName: "Baby Milk", variation: "250g" }, { skuVariationId: "100003", skuCode: "BB-002", skuName: "Baby Lotion", variation: "200ml" }, ]; // ─── buildStockInWorkbook ───────────────────────────────────────────────────── describe("buildStockInWorkbook", () => { it("creates a workbook with 'Stock In' and 'Instructions' sheets", () => { const bytes = buildStockInWorkbook(CATALOG); const wb = XLSX.read(bytes, { type: "array" }); expect(wb.SheetNames).toContain("Stock In"); expect(wb.SheetNames).toContain("Instructions"); }); it("has the required header columns in the correct order", () => { const bytes = buildStockInWorkbook(CATALOG); const wb = XLSX.read(bytes, { type: "array" }); // header:1 returns arrays; first element is the header row. const rows = XLSX.utils.sheet_to_json(wb.Sheets["Stock In"], { header: 1 }); expect(rows[0]).toEqual([ "SKU Code", "SKU Name", "Variation", "Quantity", "Batch Number", "Expiry (YYYY-MM-DD)", "skuVariationId", ]); }); it("pre-fills SKU Code, SKU Name, Variation, and skuVariationId from the catalog", () => { const bytes = buildStockInWorkbook(CATALOG); const wb = XLSX.read(bytes, { type: "array" }); const rows = XLSX.utils.sheet_to_json>(wb.Sheets["Stock In"]); expect(rows).toHaveLength(CATALOG.length); expect(rows[0]).toMatchObject({ "SKU Code": "BB-001", "SKU Name": "Baby Milk", Variation: "100g", skuVariationId: "100001", }); expect(rows[1]).toMatchObject({ skuVariationId: "100002" }); expect(rows[2]).toMatchObject({ skuVariationId: "100003" }); }); it("leaves Quantity, Batch Number, and Expiry blank in all data rows", () => { const bytes = buildStockInWorkbook(CATALOG); const wb = XLSX.read(bytes, { type: "array" }); const rows = XLSX.utils.sheet_to_json>(wb.Sheets["Stock In"]); for (const row of rows) { expect(row["Quantity"]).toBeUndefined(); expect(row["Batch Number"]).toBeUndefined(); // The text-formatted template cell reads back as "" (blank), not absent. expect(row["Expiry (YYYY-MM-DD)"]).toBe(""); } }); it("marks the skuVariationId column (index 6) as hidden", () => { const bytes = buildStockInWorkbook(CATALOG); // cellStyles: true is required to round-trip !cols hidden flags through XLSX.read. const wb = XLSX.read(bytes, { type: "array", cellStyles: true }); const sheet = wb.Sheets["Stock In"]; const cols = sheet["!cols"] ?? []; expect(cols[6]?.hidden).toBe(true); }); // BABYBOO-50: a width-less column opened at zero width in Excel, so column A was missing. it("gives every visible column a width and keeps only skuVariationId hidden", () => { const bytes = buildStockInWorkbook(CATALOG); const wb = XLSX.read(bytes, { type: "array", cellStyles: true }); const cols = wb.Sheets["Stock In"]["!cols"] ?? []; for (let i = 0; i < 6; i++) { expect(cols[i]?.hidden, `column ${i}`).toBeFalsy(); expect(cols[i]?.wch ?? 0, `column ${i}`).toBeGreaterThanOrEqual(14); } expect(cols[6]?.hidden).toBe(true); }); it("returns empty data rows (only headers) when catalog is empty", () => { const bytes = buildStockInWorkbook([]); const wb = XLSX.read(bytes, { type: "array" }); const rows = XLSX.utils.sheet_to_json>(wb.Sheets["Stock In"]); expect(rows).toHaveLength(0); }); it("Instructions sheet warns against unhiding/editing the hidden id column and round-tripping through Google Sheets", () => { const bytes = buildStockInWorkbook(CATALOG); const wb = XLSX.read(bytes, { type: "array" }); const rows = XLSX.utils.sheet_to_json(wb.Sheets["Instructions"], { header: 1 }); const text = rows.flat().join("\n"); // Warning 1: do not unhide or edit the hidden skuVariationId column expect(text).toMatch(/unhide/i); // Warning 2: do not round-trip through Google Sheets (corrupts long IDs) expect(text).toMatch(/Google Sheets/); }); // Regression: the download byte path. SheetJS 0.18.5 returns an ArrayBuffer for // type:"array" (not a Uint8Array); reading `.buffer` off it yielded undefined and // `new Blob([undefined])` produced a 9-byte "undefined" file. buildStockInWorkbook // must return a real Uint8Array that makes a full-size Blob. it("returns a Uint8Array that forms a valid, non-empty Blob (download byte path)", () => { const bytes = buildStockInWorkbook(CATALOG); expect(bytes).toBeInstanceOf(Uint8Array); expect(bytes.byteLength).toBeGreaterThan(100); // a real .xlsx zip, not 9-byte junk const blob = new Blob([bytes], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", }); expect(blob.size).toBe(bytes.byteLength); expect(blob.size).toBeGreaterThan(9); // the exact bug: "undefined" was 9 bytes }); }); // ─── parseStockInWorkbook ───────────────────────────────────────────────────── describe("parseStockInWorkbook", () => { it("returns empty lines and no errors for an empty rows array", () => { const { lines, errors } = parseStockInWorkbook([], tEn); expect(lines).toHaveLength(0); expect(errors).toHaveLength(0); }); it("keeps only rows with quantity > 0 and resolves skuVariationId and quantity", () => { const rows = [ { "SKU Code": "BB-001", Quantity: 5, skuVariationId: "100001" }, { "SKU Code": "BB-001", Quantity: 0, skuVariationId: "100002" }, { "SKU Code": "BB-002", Quantity: 3, skuVariationId: "100003" }, ]; const { lines, errors } = parseStockInWorkbook(rows, tEn); expect(errors).toHaveLength(0); expect(lines).toHaveLength(2); expect(lines[0]).toMatchObject({ skuVariationId: "100001", quantity: 5 }); expect(lines[1]).toMatchObject({ skuVariationId: "100003", quantity: 3 }); }); it("silently ignores rows with blank/absent quantity — not an error", () => { const rows = [{ "SKU Code": "BB-001", skuVariationId: "100001" }]; const { lines, errors } = parseStockInWorkbook(rows, tEn); expect(lines).toHaveLength(0); expect(errors).toHaveLength(0); }); it("silently ignores rows with quantity === 0", () => { const rows = [{ Quantity: 0, skuVariationId: "100001" }]; const { lines, errors } = parseStockInWorkbook(rows, tEn); expect(lines).toHaveLength(0); expect(errors).toHaveLength(0); }); it("reports an error (NOT a silent drop) for a kept row with missing skuVariationId", () => { const rows = [{ "SKU Code": "BB-001", Quantity: 2 }]; // no skuVariationId key const { lines, errors } = parseStockInWorkbook(rows, tEn); expect(lines).toHaveLength(0); expect(errors).toHaveLength(1); // Row 2 — header is row 1, first data row is row 2. expect(errors[0]).toMatch(/row 2/i); expect(errors[0]).toMatch(/sku id/i); }); it("reports an error for a kept row with a blank skuVariationId string", () => { const rows = [{ Quantity: 2, skuVariationId: " " }]; const { lines, errors } = parseStockInWorkbook(rows, tEn); expect(lines).toHaveLength(0); expect(errors).toHaveLength(1); expect(errors[0]).toMatch(/row 2/i); expect(errors[0]).toMatch(/sku id/i); }); it("reports an error for a kept row with a malformed expiry date", () => { const rows = [ { Quantity: 2, skuVariationId: "100001", "Expiry (YYYY-MM-DD)": "31/12/2027" }, ]; const { lines, errors } = parseStockInWorkbook(rows, tEn); expect(lines).toHaveLength(0); expect(errors).toHaveLength(1); expect(errors[0]).toMatch(/row 2/i); expect(errors[0]).toMatch(/expiry/i); }); it("includes batchNumber and expiryDate when correctly provided", () => { const rows = [ { Quantity: 10, skuVariationId: "100001", "Batch Number": "LOT-001", "Expiry (YYYY-MM-DD)": "2027-12-31", }, ]; const { lines, errors } = parseStockInWorkbook(rows, tEn); expect(errors).toHaveLength(0); expect(lines).toHaveLength(1); expect(lines[0]).toMatchObject({ batchNumber: "LOT-001", expiryDate: "2027-12-31" }); }); it("omits batchNumber and expiryDate when not provided", () => { const rows = [{ Quantity: 1, skuVariationId: "100001" }]; const { lines } = parseStockInWorkbook(rows, tEn); expect(lines[0].batchNumber).toBeUndefined(); expect(lines[0].expiryDate).toBeUndefined(); }); it("accumulates errors for multiple bad rows and still returns valid lines", () => { const rows = [ { Quantity: 5, skuVariationId: "100001" }, // good — row 2 { Quantity: 3 }, // bad (missing id) — row 3 { Quantity: 7, skuVariationId: "100003" }, // good — row 4 { Quantity: 2, skuVariationId: "100004", "Expiry (YYYY-MM-DD)": "bad-date" }, // bad expiry — row 5 ]; const { lines, errors } = parseStockInWorkbook(rows, tEn); expect(lines).toHaveLength(2); expect(errors).toHaveLength(2); expect(errors[0]).toMatch(/row 3/i); expect(errors[1]).toMatch(/row 5/i); }); // Integration: build a real workbook, read it back, set quantities, then parse. it("reads skuVariationId from the hidden column in a real round-trip workbook", () => { const bytes = buildStockInWorkbook(CATALOG); const wb = XLSX.read(bytes, { type: "array" }); const sheet = wb.Sheets["Stock In"]; const rows = XLSX.utils.sheet_to_json>(sheet); // Simulate admin filling quantity for only the first row. const filledRows = rows.map((r, i) => (i === 0 ? { ...r, Quantity: 7 } : r)); const { lines, errors } = parseStockInWorkbook(filledRows, tEn); expect(errors).toHaveLength(0); expect(lines).toHaveLength(1); expect(lines[0]).toMatchObject({ skuVariationId: "100001", quantity: 7 }); }); }); describe("Stock-In date cells", () => { // Round trip like StockInForm: write cells, read with cellNF, readSheetRows, parse. function importExpiry(cell: XLSX.CellObject) { const wb = XLSX.read(buildStockInWorkbook(CATALOG), { type: "array" }); const ws = wb.Sheets["Stock In"]; ws["D2"] = { t: "n", v: 5 }; ws["F2"] = cell; const back = XLSX.read(new Uint8Array(XLSX.write(wb, { type: "array", bookType: "xlsx" })), { type: "array", cellNF: true }); return parseStockInWorkbook(readSheetRows(back.Sheets["Stock In"], "Expiry (YYYY-MM-DD)"), tEn); } it("imports an Excel date cell as YYYY-MM-DD", () => { const { lines, errors } = importExpiry({ t: "n", v: 46752, z: "yyyy-mm-dd" }); expect(errors).toEqual([]); expect(lines[0].expiryDate).toBe("2027-12-31"); }); it("rejects a General-format number with its Excel row number", () => { const { lines, errors } = importExpiry({ t: "n", v: 5 }); expect(lines).toEqual([]); expect(errors).toHaveLength(1); expect(errors[0]).toContain("Row 2: expiry must be YYYY-MM-DD"); }); it("keeps a date-formatted Batch Number as its raw cell value, not a Date string", () => { const wb = XLSX.read(buildStockInWorkbook(CATALOG), { type: "array" }); const ws = wb.Sheets["Stock In"]; ws["D2"] = { t: "n", v: 5 }; ws["E2"] = { t: "n", v: 46752, z: "yyyy-mm-dd" }; const back = XLSX.read(new Uint8Array(XLSX.write(wb, { type: "array", bookType: "xlsx" })), { type: "array", cellNF: true }); const { lines, errors } = parseStockInWorkbook(readSheetRows(back.Sheets["Stock In"], "Expiry (YYYY-MM-DD)"), tEn); expect(errors).toEqual([]); expect(lines[0].batchNumber).toBe("46752"); }); it("template Expiry cells have text format", () => { const ws = XLSX.read(buildStockInWorkbook(CATALOG), { type: "array", cellNF: true }).Sheets["Stock In"]; for (let r = 1; r <= CATALOG.length; r++) expect(ws[XLSX.utils.encode_cell({ r, c: 5 })]?.z).toBe("@"); }); });