import * as XLSX from "xlsx"; import type { XlsxColumn } from "@/app/lib/xlsx"; import type { RateRow } from "@/app/lib/services/adminShipping"; import type { Translate } from "@/app/lib/i18n/t"; import { MAX_FEE, rowErrors, withDerivedFrom } from "./rateRows"; // Rate card xlsx layout and checks (add-shipping-rates). One sheet: Zone code | Type | Up to kg | Max L cm | Max W cm | Max H cm | Step kg | Fee RM. // BRACKET rows use Up to and the box (From is derived from the row above); OVERFLOW rows use Step (fee per step). The browser checks the whole file before anything is // sent; the server checks it again and applies it all or nothing. export const RATE_COLUMNS: XlsxColumn[] = [ { key: "zoneCode", title: "Zone code" }, { key: "type", title: "Type" }, { key: "toKg", title: "Up to kg" }, { key: "maxLengthCm", title: "Max L cm" }, { key: "maxWidthCm", title: "Max W cm" }, { key: "maxHeightCm", title: "Max H cm" }, { key: "stepKg", title: "Step kg" }, { key: "fee", title: "Fee RM" }, ]; const MAX_KG = 1_000_000; /** One BRACKET (up to 1 kg, box 20×15×10 cm) and one OVERFLOW (per 1 kg) example row per zone, fees 0. */ export function templateRows(zoneCodes: string[]): Record[] { return zoneCodes.flatMap((z) => [ { zoneCode: z, type: "BRACKET", toKg: 1, maxLengthCm: 20, maxWidthCm: 15, maxHeightCm: 10, stepKg: null, fee: 0 }, { zoneCode: z, type: "OVERFLOW", toKg: null, maxLengthCm: null, maxWidthCm: null, maxHeightCm: null, stepKg: 1, fee: 0 }, ]); } const grams = (kg: number) => Math.round(kg * 1000); /** The server's rules, so the admin sees every error before uploading. `rowNumbers[i]` is rows[i]'s sheet row. */ export function validateRates(rows: RateRow[], rowNumbers: number[], zoneCodes: string[], t: Translate): string[] { const errors: string[] = []; const known = new Set(zoneCodes); const brackets = new Set(); const overflow = new Set(); const checked: RateRow[] = []; const checkedNumbers: number[] = []; rows.forEach((r, i) => { if (!r.zoneCode) { errors.push(t("ShipRateErrZoneRequired", { row: rowNumbers[i] })); return; } if (!known.has(r.zoneCode)) { errors.push(t("ShipRateErrUnknownZone", { row: rowNumbers[i], zone: r.zoneCode })); return; } if ([r.fromKg, r.toKg, r.stepKg].some((v) => v != null && v > MAX_KG)) { errors.push(t("ShipRateErrWeightMax", { row: rowNumbers[i], max: MAX_KG })); return; } if (r.type !== "BRACKET" && r.type !== "OVERFLOW") { // rowErrors checks the fee of BRACKET and OVERFLOW rows; an unknown type still gets its fee checked here. if (r.fee == null || Number.isNaN(r.fee) || r.fee < 0) errors.push(t("ShipRateErrFeeMin", { row: rowNumbers[i] })); else if (r.fee > MAX_FEE) errors.push(t("ShipRateErrFeeMax", { row: rowNumbers[i], max: MAX_FEE })); } if (r.type === "BRACKET") { brackets.add(r.zoneCode); checked.push(r); checkedNumbers.push(rowNumbers[i]); } else if (r.type === "OVERFLOW") { checked.push(r); checkedNumbers.push(rowNumbers[i]); // rowErrors reports a missing or non-positive step; such a line does not count as the zone's overflow. if (r.stepKg != null && grams(r.stepKg) > 0) { if (overflow.has(r.zoneCode)) errors.push(t("ShipRateErrDuplicateOverflow", { row: rowNumbers[i], zone: r.zoneCode })); else overflow.add(r.zoneCode); } } else { errors.push(t("ShipRateErrType", { row: rowNumbers[i] })); } }); for (const msgs of rowErrors(checked, checkedNumbers, t).values()) errors.push(...msgs); for (const zone of brackets) { if (!overflow.has(zone)) errors.push(t("ShipRateErrNeedOverflow", { zone })); } for (const zone of overflow) { if (!brackets.has(zone)) errors.push(t("ShipRateErrNeedBracket", { zone })); } return errors; } /** Reads the Rates sheet: every formula or formula-like text is refused, then the server's rules are applied. */ export function parseRateSheet(sheet: XLSX.WorkSheet, zoneCodes: string[], t: Translate): { rows: RateRow[]; errors: string[] } { const errors: string[] = []; const rows: RateRow[] = []; const rowNumbers: number[] = []; const range = XLSX.utils.decode_range(sheet["!ref"] ?? "A1:A1"); const cell = (r: number, c: number) => sheet[XLSX.utils.encode_cell({ r, c })] as XLSX.CellObject | undefined; const header = RATE_COLUMNS.map((_, c) => String(cell(range.s.r, c)?.v ?? "").trim().toLowerCase()); if (header.join("|") !== RATE_COLUMNS.map((c) => c.title.toLowerCase()).join("|")) { return { rows: [], errors: [t("ShipRateErrColumns", { columns: RATE_COLUMNS.map((c) => c.title).join(", ") })] }; } for (let r = range.s.r + 1; r <= range.e.r; r++) { const n = r + 1; const cells = RATE_COLUMNS.map((_, c) => cell(r, c)); if (cells.every((x) => x == null || x.v == null || String(x.v).trim() === "")) continue; if (cells.some((x) => x?.f != null || (x?.t === "s" && /^[=+\-@]/.test(String(x.v))))) { errors.push(t("ShipRateErrFormula", { row: n })); continue; } const text = (x: XLSX.CellObject | undefined) => (x?.v == null ? "" : String(x.v).trim()); const num = (x: XLSX.CellObject | undefined, title: string): number | null | undefined => { if (x?.v == null || String(x.v).trim() === "") return null; const v = typeof x.v === "number" ? x.v : Number(String(x.v).trim()); if (Number.isNaN(v)) { errors.push(t("ShipRateErrNumber", { row: n, title })); return undefined; } return v; }; const toKg = num(cells[2], "Up to kg"); const maxLengthCm = num(cells[3], "Max L cm"); const maxWidthCm = num(cells[4], "Max W cm"); const maxHeightCm = num(cells[5], "Max H cm"); const stepKg = num(cells[6], "Step kg"); const fee = num(cells[7], "Fee RM"); if ([toKg, maxLengthCm, maxWidthCm, maxHeightCm, stepKg, fee].includes(undefined)) continue; rows.push({ zoneCode: text(cells[0]), type: text(cells[1]).toUpperCase() as RateRow["type"], fromKg: null, toKg: toKg ?? null, stepKg: stepKg ?? null, fee: fee ?? Number.NaN, maxLengthCm: maxLengthCm ?? null, maxWidthCm: maxWidthCm ?? null, maxHeightCm: maxHeightCm ?? null, }); rowNumbers.push(n); } errors.push(...validateRates(rows, rowNumbers, zoneCodes, t)); return { rows: withDerivedFrom(rows), errors }; } export type RateDiff = { added: number; removed: number; changed: number }; const keyOf = (r: RateRow) => (r.type === "OVERFLOW" ? `${r.zoneCode}|OVERFLOW` : `${r.zoneCode}|${r.toKg}`); const valueOf = (r: RateRow) => (r.type === "OVERFLOW" ? `${r.stepKg}|${r.fee}` : `${r.fee}|${r.maxLengthCm}|${r.maxWidthCm}|${r.maxHeightCm}`); /** What an import would change, in total and per zone. */ export function diffRates(current: RateRow[], next: RateRow[]): RateDiff & { byZone: Record } { const total: RateDiff = { added: 0, removed: 0, changed: 0 }; const byZone: Record = {}; const bump = (zone: string, k: keyof RateDiff) => { byZone[zone] ??= { added: 0, removed: 0, changed: 0 }; byZone[zone][k]++; total[k]++; }; const before = new Map(current.map((r) => [keyOf(r), r])); const after = new Map(next.map((r) => [keyOf(r), r])); for (const [k, r] of after) { const old = before.get(k); if (!old) bump(r.zoneCode, "added"); else if (valueOf(old) !== valueOf(r)) bump(r.zoneCode, "changed"); } for (const [k, r] of before) if (!after.has(k)) bump(r.zoneCode, "removed"); return { ...total, byZone }; }