Files
co-lite/solvway-admin-portal/app/components/shipping/RateCardEditor.tsx
T
ngqileandClaude Opus 5.5 5ee51d1913 chore: copy kept Tastefully modules and portals into Co-Lite
Backend modules from tastefully 8bd93d15: core-libs, core-session,
api-gateway, mobile-api, services-auth, services-system,
services-counter, services-member, services-log, services-email.
solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal
from tastefully 8bd93d15. Copied as tracked files only.

Literal secrets replaced with environment placeholders:
- services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY,
  MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default)
- services-system: JUMIO_TOKEN, JUMIO_SECRET (optional)
- services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed
- core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default
  removed, ipgeolocation key read from IPGEOLOCATION_API_KEY
- services-system EkycAppConfig: commented Jumio credentials removed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-26 15:55:45 +08:00

306 lines
13 KiB
TypeScript

"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import * as XLSX from "xlsx";
import { Button } from "@/app/components/ui/button";
import { ConfirmDialog } from "@/app/components/ui/confirm-dialog";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/app/components/ui/dialog";
import { ApiError } from "@/app/lib/clientApi";
import { downloadXlsx, toXlsx } from "@/app/lib/xlsx";
import { RATE_COLUMNS, diffRates, parseRateSheet, templateRows, type RateDiff } from "@/app/lib/shipping/rateCardWorkbook";
import { rowErrors, withDerivedFrom } from "@/app/lib/shipping/rateRows";
import {
activateRateCard,
deactivateRateCard,
getRateCard,
listZones,
saveRates,
type RateCard,
type RateRow,
type ShippingZone,
} from "@/app/lib/services/adminShipping";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { ZoneRatesTable } from "./ZoneRatesTable";
const errorsOf = (e: unknown, t: (code: string) => string): string[] => {
const listed = e instanceof ApiError ? (e.data as { errors?: unknown } | undefined)?.errors : undefined;
if (Array.isArray(listed) && listed.length > 0) return listed.map(String);
return [e instanceof Error ? e.message : t("ShipRateErrGeneric")];
};
const hasBox = (r: RateRow) => r.maxLengthCm != null && r.maxWidthCm != null && r.maxHeightCm != null;
/** This zone's BRACKET rows in table order, then its OVERFLOW row. */
const zoneRowsOf = (rows: RateRow[], zone: string) => [
...rows.filter((r) => r.zoneCode === zone && r.type === "BRACKET"),
...rows.filter((r) => r.zoneCode === zone && r.type === "OVERFLOW"),
];
/** Groups rows by zone (first appearance), each zone's BRACKET rows by Up to then its OVERFLOW row: the table order. */
function tableOrder(rows: RateRow[]): RateRow[] {
const zones = [...new Set(rows.map((r) => r.zoneCode))];
return zones.flatMap((z) => {
const [brackets, others] = [rows.filter((r) => r.zoneCode === z && r.type === "BRACKET"), rows.filter((r) => r.zoneCode === z && r.type !== "BRACKET")];
return [...brackets.sort((a, b) => (a.toKg ?? Infinity) - (b.toKg ?? Infinity)), ...others];
});
}
/** Display row number of each row: its 1-based position among its zone's BRACKET rows (the OVERFLOW line comes next). */
function rowNumbersOf(rows: RateRow[]): number[] {
const seen = new Map<string, number>();
return rows.map((r) => {
// The OVERFLOW line is numbered after its zone's BRACKET rows.
const n = (seen.get(r.zoneCode) ?? 0) + 1;
if (r.type === "BRACKET") seen.set(r.zoneCode, n);
return n;
});
}
// Rate card editor (shipping-rate-rows-with-dimensions): a zone list, the selected zone's rows edited one by one with
// a box per row, and the whole card (every zone) saved at once. Leaving with unsaved changes asks first.
export function RateCardEditor({ cardId, onBack }: { cardId: number; onBack: () => void }) {
const t = useT();
const [card, setCard] = useState<RateCard | null>(null);
const [zones, setZones] = useState<ShippingZone[]>([]);
const [rows, setRows] = useState<RateRow[]>([]);
const [selected, setSelected] = useState<string | null>(null);
const [checked, setChecked] = useState(false);
const [dirty, setDirty] = useState(false);
const [leaving, setLeaving] = useState(false);
const [copyFrom, setCopyFrom] = useState<string | null>(null);
const [errors, setErrors] = useState<string[]>([]);
const [notice, setNotice] = useState<string | null>(null);
const [pending, setPending] = useState<{ rows: RateRow[]; diff: RateDiff & { byZone: Record<string, RateDiff> } } | null>(null);
const [confirm, setConfirm] = useState<"activate" | "deactivate" | null>(null);
const fileRef = useRef<HTMLInputElement>(null);
const load = useCallback(() => {
Promise.all([getRateCard(cardId), listZones()])
.then(([c, z]) => { setCard(c); setRows(tableOrder(c.rows ?? [])); setZones(z); })
.catch((e: unknown) => setErrors([e instanceof Error ? e.message : "ShipRateErrGeneric"]));
}, [cardId]);
useEffect(load, [load]);
useEffect(() => {
if (!dirty) return;
const warn = (e: BeforeUnloadEvent) => {
e.preventDefault();
e.returnValue = "";
};
window.addEventListener("beforeunload", warn);
return () => window.removeEventListener("beforeunload", warn);
}, [dirty]);
const zoneCodes = useMemo(() => {
const codes = zones.filter((z) => z.status === "Y").map((z) => z.code);
for (const r of rows) if (!codes.includes(r.zoneCode)) codes.push(r.zoneCode);
return codes;
}, [zones, rows]);
const zone = selected ?? zoneCodes[0] ?? null;
// Row errors appear once a save was attempted, and then follow the edits live until the rows are valid.
const rowErrs = useMemo(() => (checked ? rowErrors(rows, rowNumbersOf(rows), t) : new Map<number, string[]>()), [checked, rows, t]);
const zoneRows = zone ? zoneRowsOf(rows, zone) : [];
const zoneErrs = new Map<number, string[]>();
zoneRows.forEach((r, i) => {
const errs = rowErrs.get(rows.indexOf(r));
if (errs) zoneErrs.set(i, errs);
});
const zoneStatus = (code: string) => {
const mine = rows.filter((r) => r.zoneCode === code);
const brackets = mine.filter((r) => r.type === "BRACKET");
if (brackets.length === 0 || !mine.some((r) => r.type === "OVERFLOW")) return "incomplete";
return brackets.every(hasBox) ? "complete" : "needsSize";
};
const edit = (next: RateRow[]) => { setRows(next); setDirty(true); setNotice(null); };
const replaceZone = (code: string, next: RateRow[]) => edit([...rows.filter((r) => r.zoneCode !== code), ...next]);
const persist = async (toSave: RateRow[]) => {
setErrors([]);
setNotice(null);
const found = rowErrors(toSave, rowNumbersOf(toSave), t);
if (found.size > 0) {
setChecked(true);
const failing = new Set([...found.keys()].map((i) => toSave[i].zoneCode));
setSelected(zoneCodes.find((z) => failing.has(z)) ?? null);
return;
}
try {
const saved = await saveRates(cardId, withDerivedFrom(toSave));
setRows(tableOrder(saved.rows ?? toSave));
setChecked(false);
setDirty(false);
setNotice("ShipRateSaved");
} catch (e) {
setErrors(errorsOf(e, t));
}
};
const download = async (name: string, data: Record<string, unknown>[]) =>
downloadXlsx(name, await toXlsx(data, RATE_COLUMNS, "Rates"));
const importFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
e.target.value = "";
if (!file) return;
setErrors([]);
setNotice(null);
let wb: XLSX.WorkBook;
try {
wb = XLSX.read(new Uint8Array(await file.arrayBuffer()), { type: "array" });
} catch {
setErrors([t("ShipRateReadFailed")]);
return;
}
const parsed = parseRateSheet(wb.Sheets[wb.SheetNames[0]], zones.map((z) => z.code), t);
if (parsed.errors.length > 0) { setErrors(parsed.errors); return; }
setPending({ rows: parsed.rows, diff: diffRates(rows, parsed.rows) });
};
const changeStatus = async (action: "activate" | "deactivate") => {
setErrors([]);
try {
setCard(action === "activate" ? await activateRateCard(cardId) : await deactivateRateCard(cardId));
} catch (e) {
setErrors(errorsOf(e, t));
}
};
if (!card) {
return errors.length > 0 ? <p role="alert" className="text-sm text-destructive">{t(errors[0])}</p> : <p className="text-sm text-muted-foreground">{t("Loading")}</p>;
}
const back = () => (dirty ? setLeaving(true) : onBack());
const copyRows = (from: string, to: string) =>
zoneRowsOf(rows, from).map((r) => ({ ...r, zoneCode: to }));
return (
<div className="space-y-4">
<div className="flex flex-wrap items-center gap-2">
<Button variant="outline" onClick={back}>{t("Back")}</Button>
<h2 className="text-lg font-semibold">{card.name}</h2>
<span className="text-sm text-muted-foreground">{card.status}</span>
<div className="ml-auto flex flex-wrap gap-2">
<Button variant="outline" onClick={() => download(`${card.name}-template.xlsx`, templateRows(zoneCodes))}>{t("CatDownloadTemplate")}</Button>
<Button variant="outline" onClick={() => download(`${card.name}.xlsx`, rows as unknown as Record<string, unknown>[])}>{t("Export")}</Button>
<Button variant="outline" onClick={() => fileRef.current?.click()}>{t("ShipRateImport")}</Button>
<input ref={fileRef} type="file" accept=".xlsx" aria-label={t("ShipRateImport")} hidden onChange={importFile} />
{card.status === "ACTIVE"
? <Button variant="outline" onClick={() => setConfirm("deactivate")}>{t("CatDeactivate")}</Button>
: <Button onClick={() => setConfirm("activate")}>{t("CatActivate")}</Button>}
</div>
</div>
<div className="flex flex-col gap-4 md:flex-row">
<nav aria-label={t("ShipRateZones")} className="md:w-48 md:shrink-0">
<h3 className="mb-2 text-sm font-semibold">{t("ShipRateZones")}</h3>
<ul className="flex flex-wrap gap-1 md:flex-col">
{zoneCodes.map((code) => {
const status = zoneStatus(code);
return (
<li key={code}>
<Button variant={code === zone ? "secondary" : "ghost"} aria-pressed={code === zone}
className="w-full justify-between gap-3" onClick={() => setSelected(code)}>
<span>{code}</span>
{status === "complete" ? (
<span className="text-primary">
<span aria-hidden="true">✓</span>
<span className="sr-only">{t("ShipRateZoneComplete")}</span>
</span>
) : (
<span className="text-xs font-normal text-muted-foreground">
{status === "needsSize" ? t("ShipRateNeedsSize") : t("ShipRateZoneIncomplete")}
</span>
)}
</Button>
</li>
);
})}
</ul>
</nav>
{zone && (
<section className="min-w-0 flex-1 space-y-3">
<div className="flex flex-wrap items-center gap-2">
<h3 className="text-base font-semibold">{zone}</h3>
{zoneCodes.length > 1 && (
<select aria-label={t("ShipRateCopyFrom")} value="" onChange={(e) => { if (e.target.value) setCopyFrom(e.target.value); }}
className="ml-auto h-9 rounded-md border border-input bg-transparent px-3 text-sm shadow-sm dark:bg-input/30">
<option value="">{t("ShipRateCopyFrom")}</option>
{zoneCodes.filter((c) => c !== zone).map((c) => <option key={c} value={c}>{c}</option>)}
</select>
)}
</div>
<ZoneRatesTable key={zone} zone={zone} rows={zoneRows} errors={zoneErrs} onChange={(next) => replaceZone(zone, next)} />
</section>
)}
</div>
<div className="flex justify-end">
<Button onClick={() => persist(rows)}>{t("ShipRateSave")}</Button>
</div>
{notice && <p className="text-sm text-muted-foreground">{t(notice)}</p>}
{errors.length > 0 && (
<ul role="alert" className="list-disc space-y-1 pl-5 text-sm text-destructive">
{errors.map((e) => <li key={e}>{t(e)}</li>)}
</ul>
)}
<Dialog open={pending !== null} onOpenChange={(o) => { if (!o) setPending(null); }}>
<DialogContent>
<DialogHeader><DialogTitle>{t("ShipRateReplaceTitle")}</DialogTitle></DialogHeader>
{pending && (
<ul className="space-y-1 text-sm">
{Object.entries(pending.diff.byZone).map(([z, d]) => (
<li key={z}>{t("ShipRateDiff", { zone: z, added: d.added, changed: d.changed, removed: d.removed })}</li>
))}
</ul>
)}
<DialogFooter>
<Button variant="outline" onClick={() => setPending(null)}>{t("Cancel")}</Button>
<Button onClick={() => {
const next = tableOrder(pending?.rows ?? []);
setPending(null);
edit(next);
void persist(next);
}}>{t("Confirm")}</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<ConfirmDialog
open={copyFrom !== null}
onOpenChange={(o) => { if (!o) setCopyFrom(null); }}
title={t("ShipRateCopyTitle", { zone: zone ?? "" })}
description={t("ShipRateCopyDesc", { zone: zone ?? "", from: copyFrom ?? "" })}
confirmLabel={t("Confirm")}
onConfirm={() => { if (zone && copyFrom) replaceZone(zone, copyRows(copyFrom, zone)); setCopyFrom(null); }}
/>
<ConfirmDialog
open={leaving}
onOpenChange={setLeaving}
title={t("ShipRateUnsaved")}
description=""
confirmLabel={t("Back")}
onConfirm={onBack}
/>
<ConfirmDialog
open={confirm !== null}
onOpenChange={(o) => { if (!o) setConfirm(null); }}
title={confirm === "deactivate" ? t("ShipRateDeactivateTitle") : t("ShipRateActivateTitle")}
description={confirm === "deactivate"
? t("ShipRateDeactivateDesc")
: t("ShipRateActivateDesc")}
confirmLabel={confirm === "deactivate" ? t("CatDeactivate") : t("CatActivate")}
onConfirm={() => { const a = confirm; setConfirm(null); if (a) void changeStatus(a); }}
/>
</div>
);
}