import { describe, it, expect, vi, beforeEach } from "vitest"; import { render, screen, fireEvent, waitFor, within } from "@testing-library/react"; import * as XLSX from "xlsx"; import { ApiError } from "@/app/lib/clientApi"; const ship = vi.hoisted(() => ({ getRateCard: vi.fn(), listZones: vi.fn(), saveRates: vi.fn(), activateRateCard: vi.fn(), deactivateRateCard: vi.fn(), })); vi.mock("@/app/lib/services/adminShipping", () => ship); const xl = vi.hoisted(() => ({ toXlsx: vi.fn(), downloadXlsx: vi.fn() })); vi.mock("@/app/lib/xlsx", () => xl); import { RateCardEditor } from "./RateCardEditor"; const BOX = { maxLengthCm: 20, maxWidthCm: 15, maxHeightCm: 10 }; const NO_BOX = { maxLengthCm: null, maxWidthCm: null, maxHeightCm: null }; const ROWS = [ { zoneCode: "WM", type: "BRACKET", fromKg: 0, toKg: 1, stepKg: null, fee: 8, ...BOX }, { zoneCode: "WM", type: "OVERFLOW", fromKg: null, toKg: null, stepKg: 1, fee: 3, ...NO_BOX }, ]; const cardWith = (rows: unknown[]) => ({ id: 3, name: "2026 rates", effectiveFrom: "2026-11-01T00:00:00", status: "DRAFT", rows }); const rowOf = (label: string) => screen.getByLabelText(label).closest("tbody") as HTMLElement; const type = (label: string, value: string | number) => fireEvent.change(screen.getByLabelText(label), { target: { value: String(value) } }); const fillRow = (zone: string, row: number, upTo: number, box: [number, number, number], fee: number) => { type(`${zone} row ${row} up to kg`, upTo); type(`${zone} row ${row} max length`, box[0]); type(`${zone} row ${row} max width`, box[1]); type(`${zone} row ${row} max height`, box[2]); type(`${zone} row ${row} fee`, fee); }; function xlsxFile(aoa: unknown[][]): File { const wb = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(wb, XLSX.utils.aoa_to_sheet(aoa), "Rates"); const bytes = XLSX.write(wb, { type: "array", bookType: "xlsx" }) as ArrayBuffer; const file = new File([bytes], "rates.xlsx"); Object.defineProperty(file, "arrayBuffer", { value: () => Promise.resolve(bytes) }); return file; } const HEADER = ["Zone code", "Type", "Up to kg", "Max L cm", "Max W cm", "Max H cm", "Step kg", "Fee RM"]; beforeEach(() => { ship.getRateCard.mockReset().mockResolvedValue(cardWith(ROWS)); ship.listZones.mockReset().mockResolvedValue([ { id: 1, code: "WM", name: "West", status: "Y", geoLocationIds: [50] }, { id: 2, code: "EM", name: "East", status: "Y", geoLocationIds: [60] }, ]); ship.saveRates.mockReset().mockImplementation(async (_id: number, rows: unknown[]) => ({ id: 3, rows })); ship.activateRateCard.mockReset(); ship.deactivateRateCard.mockReset(); xl.toXlsx.mockReset().mockResolvedValue(new Uint8Array([1])); xl.downloadXlsx.mockReset(); }); describe("RateCardEditor (shipping-rate-rows-with-dimensions)", () => { it("addsRowsOneByOne: rows are added one at a time and From follows the row above", async () => { ship.getRateCard.mockResolvedValue(cardWith([])); render(); fireEvent.click(await screen.findByRole("button", { name: "Add row" })); fillRow("WM", 1, 1, [20, 15, 10], 8); fireEvent.click(screen.getByRole("button", { name: "Add row" })); type("WM row 2 up to kg", 3); expect(within(rowOf("WM row 2 up to kg")).getAllByRole("cell")[0]).toHaveTextContent("1"); fillRow("WM", 2, 3, [40, 30, 20], 12); fireEvent.click(screen.getByRole("button", { name: "Save rates" })); await waitFor(() => expect(ship.saveRates).toHaveBeenCalled()); expect(ship.saveRates.mock.calls[0][1]).toEqual([ { zoneCode: "WM", type: "BRACKET", fromKg: 0, toKg: 1, stepKg: null, fee: 8, maxLengthCm: 20, maxWidthCm: 15, maxHeightCm: 10 }, { zoneCode: "WM", type: "BRACKET", fromKg: 1, toKg: 3, stepKg: null, fee: 12, maxLengthCm: 40, maxWidthCm: 30, maxHeightCm: 20 }, ]); expect(await screen.findByText("Rates saved")).toBeInTheDocument(); expect(screen.getByLabelText("WM row 1 up to kg")).toHaveValue(1); expect(screen.getByLabelText("WM row 2 up to kg")).toHaveValue(3); }); it("deletingARowReDerivesFrom: deleting the 3 kg row makes the last row start at 1 kg", async () => { ship.getRateCard.mockResolvedValue(cardWith([ { zoneCode: "WM", type: "BRACKET", fromKg: 0, toKg: 1, stepKg: null, fee: 8, ...BOX }, { zoneCode: "WM", type: "BRACKET", fromKg: 1, toKg: 3, stepKg: null, fee: 12, ...BOX }, { zoneCode: "WM", type: "BRACKET", fromKg: 3, toKg: 5, stepKg: null, fee: 14, ...BOX }, ])); render(); await screen.findByLabelText("WM row 3 up to kg"); expect(within(rowOf("WM row 3 up to kg")).getAllByRole("cell")[0]).toHaveTextContent("3"); fireEvent.click(screen.getByRole("button", { name: "Delete row 2" })); expect(screen.queryByLabelText("WM row 3 up to kg")).toBeNull(); expect(screen.getByLabelText("WM row 2 up to kg")).toHaveValue(5); expect(within(rowOf("WM row 2 up to kg")).getAllByRole("cell")[0]).toHaveTextContent("1"); }); it("rowWithoutBoxShowsErrorAndSendsNothing: the error sits on that row", async () => { ship.getRateCard.mockResolvedValue(cardWith([ ...ROWS, { zoneCode: "WM", type: "BRACKET", fromKg: 1, toKg: 3, stepKg: null, fee: 12, maxLengthCm: 40, maxWidthCm: 30, maxHeightCm: 20 }, ])); render(); await screen.findByLabelText("WM row 2 max height"); type("WM row 2 max height", ""); fireEvent.click(screen.getByRole("button", { name: "Save rates" })); expect(await within(rowOf("WM row 2 up to kg")).findByText("Row 2: Max L, W and H must each be greater than 0")).toBeInTheDocument(); expect(within(rowOf("WM row 1 up to kg")).queryByText(/must each be greater than 0/)).toBeNull(); expect(ship.saveRates).not.toHaveBeenCalled(); }); it("blankFeeShowsErrorOnTheRowAndSendsNothing", async () => { ship.getRateCard.mockResolvedValue(cardWith([ ...ROWS, { zoneCode: "WM", type: "BRACKET", fromKg: 1, toKg: 3, stepKg: null, fee: 12, maxLengthCm: 40, maxWidthCm: 30, maxHeightCm: 20 }, ])); render(); await screen.findByLabelText("WM row 2 fee"); type("WM row 2 fee", ""); fireEvent.click(screen.getByRole("button", { name: "Save rates" })); expect(await within(rowOf("WM row 2 up to kg")).findByText("Row 2: Fee must be 0 or more")).toBeInTheDocument(); expect(within(rowOf("WM row 1 up to kg")).queryByText(/Fee must be/)).toBeNull(); expect(ship.saveRates).not.toHaveBeenCalled(); }); it("overflowStepWithoutFeeShowsErrorByTheOverflowLineAndSendsNothing", async () => { render(); await screen.findByLabelText("Fee per additional step (RM)"); type("Fee per additional step (RM)", ""); fireEvent.click(screen.getByRole("button", { name: "Save rates" })); const alert = await screen.findByText("Row 2: Fee must be 0 or more"); expect(screen.getByLabelText("Fee per additional step (RM)").closest("div[class*=border]")).toContainElement(alert); expect(ship.saveRates).not.toHaveBeenCalled(); }); it("an error in another zone selects that zone on Save", async () => { ship.getRateCard.mockResolvedValue(cardWith([ ...ROWS, { zoneCode: "EM", type: "BRACKET", fromKg: 0, toKg: 1, stepKg: null, fee: 9, ...NO_BOX }, ])); render(); await screen.findByLabelText("WM row 1 up to kg"); fireEvent.click(screen.getByRole("button", { name: "Save rates" })); expect(await within(rowOf("EM row 1 up to kg")).findByText("Row 1: Max L, W and H must each be greater than 0")).toBeInTheDocument(); expect(screen.queryByLabelText("WM row 1 up to kg")).toBeNull(); expect(ship.saveRates).not.toHaveBeenCalled(); }); it("quickCheckUsesUnsavedRows: prices a parcel from the rows being edited", async () => { ship.getRateCard.mockResolvedValue(cardWith([])); render(); fireEvent.click(await screen.findByRole("button", { name: "Add row" })); fillRow("WM", 1, 1, [20, 15, 10], 8); fireEvent.click(screen.getByRole("button", { name: "Add row" })); fillRow("WM", 2, 3, [40, 30, 20], 12); type("Weight (kg)", 0.5); type("Length (cm)", 35); type("Width (cm)", 25); type("Height (cm)", 15); expect(screen.getByText("RM12 (row 2)")).toBeInTheDocument(); expect(ship.saveRates).not.toHaveBeenCalled(); }); it("legacyRowShowsNeedsSize: a saved row without a box asks for box sizes on that row", async () => { ship.getRateCard.mockResolvedValue(cardWith([{ ...ROWS[0], ...NO_BOX }, ROWS[1]])); render(); await screen.findByLabelText("WM row 1 up to kg"); expect(within(rowOf("WM row 1 up to kg")).getByText("Add box sizes")).toBeInTheDocument(); expect(screen.getByLabelText("WM row 1 max length")).toHaveValue(null); }); it("copyFromZoneReplacesAfterConfirm: EM gets copies of WM's rows and overflow", async () => { render(); await screen.findByLabelText("WM row 1 up to kg"); fireEvent.click(screen.getByRole("button", { name: /^EM/ })); expect(screen.queryByLabelText("EM row 1 up to kg")).toBeNull(); fireEvent.change(screen.getByLabelText("Copy from zone"), { target: { value: "WM" } }); const dialog = await screen.findByRole("dialog"); expect(within(dialog).getByText("Replace EM's rates?")).toBeInTheDocument(); expect(within(dialog).getByText("EM's rows and overflow rule will be replaced with WM's.")).toBeInTheDocument(); expect(screen.queryByLabelText("EM row 1 up to kg")).toBeNull(); fireEvent.click(within(dialog).getByRole("button", { name: "Confirm" })); expect(await screen.findByLabelText("EM row 1 up to kg")).toHaveValue(1); expect(screen.getByLabelText("EM row 1 max length")).toHaveValue(20); fireEvent.click(screen.getByRole("button", { name: "Save rates" })); await waitFor(() => expect(ship.saveRates).toHaveBeenCalled()); expect(ship.saveRates.mock.calls[0][1]).toEqual(expect.arrayContaining([ { zoneCode: "EM", type: "BRACKET", fromKg: 0, toKg: 1, stepKg: null, fee: 8, ...BOX }, { zoneCode: "EM", type: "OVERFLOW", fromKg: null, toKg: null, stepKg: 1, fee: 3, ...NO_BOX }, { zoneCode: "WM", type: "BRACKET", fromKg: 0, toKg: 1, stepKg: null, fee: 8, ...BOX }, ])); expect(ship.saveRates.mock.calls[0][1]).toHaveLength(4); }); it("backWhileDirtyAsks: Back with unsaved changes asks first, and only then leaves", async () => { const onBack = vi.fn(); render(); await screen.findByLabelText("WM row 1 fee"); type("WM row 1 fee", 9); const unload = new Event("beforeunload", { cancelable: true }); window.dispatchEvent(unload); expect(unload.defaultPrevented).toBe(true); fireEvent.click(screen.getByRole("button", { name: "Back" })); const dialog = await screen.findByRole("dialog"); expect(within(dialog).getByText("You have unsaved changes. Leave anyway?")).toBeInTheDocument(); expect(onBack).not.toHaveBeenCalled(); fireEvent.click(within(dialog).getByRole("button", { name: "Back" })); expect(onBack).toHaveBeenCalledTimes(1); }); it("Back without changes, or after a successful save, leaves straight away", async () => { const onBack = vi.fn(); render(); await screen.findByLabelText("WM row 1 fee"); type("WM row 1 fee", 9); fireEvent.click(screen.getByRole("button", { name: "Save rates" })); await screen.findByText("Rates saved"); // The unload guard is removed by an effect that runs after the notice renders; on a busy CI CPU // findByText can resolve in between, so wait for the guard to go rather than checking once. await waitFor(() => { const unload = new Event("beforeunload", { cancelable: true }); window.dispatchEvent(unload); expect(unload.defaultPrevented).toBe(false); }); fireEvent.click(screen.getByRole("button", { name: "Back" })); expect(onBack).toHaveBeenCalledTimes(1); expect(screen.queryByRole("dialog")).toBeNull(); }); it("zoneListMarksIncompleteZones: complete, needs rates, or needs box sizes", async () => { ship.listZones.mockResolvedValue([ { id: 1, code: "WM", name: "West", status: "Y", geoLocationIds: [50] }, { id: 2, code: "EM", name: "East", status: "Y", geoLocationIds: [60] }, { id: 3, code: "SB", name: "Sabah", status: "Y", geoLocationIds: [70] }, { id: 4, code: "OLD", name: "Old", status: "N", geoLocationIds: [] }, ]); ship.getRateCard.mockResolvedValue(cardWith([ ...ROWS, { zoneCode: "SB", type: "BRACKET", fromKg: 0, toKg: 1, stepKg: null, fee: 20, ...NO_BOX }, { zoneCode: "SB", type: "OVERFLOW", fromKg: null, toKg: null, stepKg: 1, fee: 5, ...NO_BOX }, ])); render(); const wm = await screen.findByRole("button", { name: /^WM/ }); expect(within(wm).getByText("Complete")).toBeInTheDocument(); expect(wm).toHaveAttribute("aria-pressed", "true"); expect(within(screen.getByRole("button", { name: /^EM/ })).getByText("Needs rates")).toBeInTheDocument(); expect(within(screen.getByRole("button", { name: /^SB/ })).getByText("Add box sizes")).toBeInTheDocument(); expect(screen.queryByRole("button", { name: /^OLD/ })).toBeNull(); }); it("lists every error the server returns", async () => { ship.saveRates.mockRejectedValue(new ApiError("Rates not saved", 400, { error: "Rates not saved", errors: ["Zone EM: add an overflow row", "Row 3: gap after 1 kg"] })); render(); await screen.findByLabelText("WM row 1 up to kg"); fireEvent.click(screen.getByRole("button", { name: "Save rates" })); const alert = await screen.findByRole("alert"); expect(within(alert).getByText("Zone EM: add an overflow row")).toBeInTheDocument(); expect(within(alert).getByText("Row 3: gap after 1 kg")).toBeInTheDocument(); }); it("an import with errors lists them and sends nothing", async () => { render(); await screen.findByLabelText("WM row 1 up to kg"); fireEvent.change(screen.getByLabelText("Import rates"), { target: { files: [xlsxFile([HEADER, ["XX", "BRACKET", 1, 20, 15, 10, null, 8]])] } }); expect(await screen.findByText("Row 2: unknown zone XX")).toBeInTheDocument(); expect(ship.saveRates).not.toHaveBeenCalled(); }); it("a valid import shows the change per zone and saves only on Confirm", async () => { render(); await screen.findByLabelText("WM row 1 up to kg"); fireEvent.change(screen.getByLabelText("Import rates"), { target: { files: [xlsxFile([HEADER, ["WM", "BRACKET", 1, 20, 15, 10, null, 9], ["WM", "OVERFLOW", null, null, null, null, 1, 3]])] }, }); expect(await screen.findByText("WM: 0 added, 1 changed, 0 removed")).toBeInTheDocument(); expect(ship.saveRates).not.toHaveBeenCalled(); fireEvent.click(screen.getByRole("button", { name: "Confirm" })); await waitFor(() => expect(ship.saveRates).toHaveBeenCalledTimes(1)); }); it("clearing an overflow fee leaves it blank, never a free RM0 overflow", async () => { render(); const fee = await screen.findByLabelText("Fee per additional step (RM)"); fireEvent.change(fee, { target: { value: "" } }); expect(screen.getByLabelText("Fee per additional step (RM)")).toHaveValue(null); fireEvent.click(screen.getByRole("button", { name: "Save rates" })); // The blank fee is refused in the editor, so no free RM0 overflow is ever sent. expect(await screen.findByText("Row 2: Fee must be 0 or more")).toBeInTheDocument(); expect(ship.saveRates).not.toHaveBeenCalled(); }); it("a file that is not a readable workbook shows an error and sends nothing", async () => { render(); await screen.findByLabelText("WM row 1 up to kg"); const bytes = new Uint8Array([0x50, 0x4b, 3, 4, 1, 2, 3, 4, 5, 6, 7, 8]).buffer; const file = new File([bytes], "rates.xlsx"); Object.defineProperty(file, "arrayBuffer", { value: () => Promise.resolve(bytes) }); fireEvent.change(screen.getByLabelText("Import rates"), { target: { files: [file] } }); expect(await screen.findByText("Couldn't read this file. Use the .xlsx template.")).toBeInTheDocument(); expect(ship.saveRates).not.toHaveBeenCalled(); }); it("imports through a labelled Import rates button, not a bare file box", async () => { render(); await screen.findByLabelText("WM row 1 up to kg"); const input = screen.getByLabelText("Import rates") as HTMLInputElement; const click = vi.spyOn(input, "click"); expect(input).not.toBeVisible(); fireEvent.click(screen.getByRole("button", { name: "Import rates" })); expect(click).toHaveBeenCalled(); }); it("labels the overflow step and the overflow fee rows", async () => { render(); await screen.findByLabelText("WM row 1 up to kg"); expect(screen.getByText("Each additional (kg)")).toBeInTheDocument(); expect(screen.getByText("Fee per additional step (RM)")).toBeInTheDocument(); }); it("downloads a template with a row pair per active zone", async () => { render(); await screen.findByLabelText("WM row 1 up to kg"); fireEvent.click(screen.getByRole("button", { name: "Download template" })); await waitFor(() => expect(xl.downloadXlsx).toHaveBeenCalledWith("2026 rates-template.xlsx", expect.any(Uint8Array))); expect(xl.toXlsx.mock.calls[0][0]).toHaveLength(4); }); it("shows why activation was refused", async () => { ship.activateRateCard.mockRejectedValue(new ApiError("Add rates for: EM", 400, { error: "Add rates for: EM" })); render(); await screen.findByLabelText("WM row 1 up to kg"); fireEvent.click(screen.getByRole("button", { name: "Activate" })); fireEvent.click(within(await screen.findByRole("dialog")).getByRole("button", { name: "Activate" })); expect(await screen.findByText("Add rates for: EM")).toBeInTheDocument(); }); });