import { describe, it, expect } from "vitest"; import * as XLSX from "xlsx"; import { readSheetRows } from "./workbookRows"; const COL = "Expiry (YYYY-MM-DD)"; /** Write the sheet to xlsx and read it back with cellNF, like the import forms do. */ function roundTrip(aoa: unknown[][], cells: Record = {}) { const ws = XLSX.utils.aoa_to_sheet(aoa); Object.assign(ws, cells); const wb = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(wb, ws, "S"); const back = XLSX.read(new Uint8Array(XLSX.write(wb, { type: "array", bookType: "xlsx" })), { type: "array", cellNF: true }); return back.Sheets["S"]; } describe("readSheetRows", () => { it("turns a date-formatted cell into YYYY-MM-DD", () => { const sheet = roundTrip([["Qty", COL], [1, null]], { B2: { t: "n", v: 46752, z: "yyyy-mm-dd" } }); expect(readSheetRows(sheet, COL)[0][COL]).toBe("2027-12-31"); }); it("leaves a General-format number as a number", () => { const sheet = roundTrip([["Qty", COL], [1, 5]]); expect(readSheetRows(sheet, COL)[0][COL]).toBe(5); }); it("passes text through unchanged", () => { const sheet = roundTrip([["Qty", COL], [1, "2027-12-31"]]); expect(readSheetRows(sheet, COL)[0][COL]).toBe("2027-12-31"); }); it("returns the sheet_to_json rows unchanged when the date header is absent", () => { const sheet = roundTrip([["Qty", "Other"], [1, 46752]], { B2: { t: "n", v: 46752, z: "yyyy-mm-dd" } }); expect(readSheetRows(sheet, COL)).toEqual([{ Qty: 1, Other: 46752 }]); }); it("keeps a date-formatted cell in another column as its raw number (SheetJS 0.20 would make a Date)", () => { const sheet = roundTrip([["Batch Number", COL], [null, null]], { A2: { t: "n", v: 46752, z: "yyyy-mm-dd" }, B2: { t: "n", v: 46752, z: "yyyy-mm-dd" }, }); const [row] = readSheetRows(sheet, COL); expect(row["Batch Number"]).toBe(46752); expect(row[COL]).toBe("2027-12-31"); }); it("keeps text cells with a date format as their string, in a Batch column and in the date column", () => { const sheet = roundTrip([["Batch Number", COL], [null, null]], { A2: { t: "s", v: "B-001", z: "yyyy-mm-dd" }, B2: { t: "s", v: "2027-12-31", z: "yyyy-mm-dd" }, }); expect(readSheetRows(sheet, COL)).toEqual([{ "Batch Number": "B-001", [COL]: "2027-12-31" }]); }); it("keeps a boolean cell with a date format as a boolean", () => { const sheet = roundTrip([["Flag", COL], [null, null]], { A2: { t: "b", v: true, z: "yyyy-mm-dd" } }); expect(readSheetRows(sheet, COL)[0]["Flag"]).toBe(true); }); it("keeps later rows aligned across a blank row", () => { const sheet = roundTrip([["Qty", COL], [1, null], [], [3, null]], { B2: { t: "n", v: 46752, z: "yyyy-mm-dd" }, B4: { t: "n", v: 46753, z: "yyyy-mm-dd" }, }); const rows = readSheetRows(sheet, COL); expect(rows).toHaveLength(3); expect(rows[0][COL]).toBe("2027-12-31"); expect(rows[2]).toMatchObject({ Qty: 3, [COL]: "2028-01-01" }); }); });