Files
co-lite/solvway-admin-portal/app/components/shipping/ZoneRatesTable.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

181 lines
9.7 KiB
TypeScript

"use client";
import { useState } from "react";
import { Trash2 } from "lucide-react";
import { Button } from "@/app/components/ui/button";
import { Input } from "@/app/components/ui/input";
import { Label } from "@/app/components/ui/label";
import { Table, TableCell, TableHead, TableHeader, TableRow } from "@/app/components/ui/table";
import type { RateRow } from "@/app/lib/services/adminShipping";
import { priceParcel, withDerivedFrom, type ParcelPrice } from "@/app/lib/shipping/rateRows";
import { useT } from "@/app/lib/i18n/MessagesProvider";
type BoxSide = "maxLengthCm" | "maxWidthCm" | "maxHeightCm";
type RowField = "toKg" | BoxSide | "fee";
const NO_BOX = { maxLengthCm: null, maxWidthCm: null, maxHeightCm: null };
const numberOrNull = (value: string) => (value.trim() === "" ? null : Number(value));
const shown = (v: number | null | undefined) => v ?? "";
const kgText = (kg: number) => String(Number(kg.toFixed(3)));
const feeText = (fee: number) => (Number.isInteger(fee) ? String(fee) : fee.toFixed(2));
const sortedBox = (r: RateRow) =>
r.maxLengthCm == null || r.maxWidthCm == null || r.maxHeightCm == null
? null
: [r.maxLengthCm, r.maxWidthCm, r.maxHeightCm].sort((a, b) => b - a);
/** True when every side of this row's box is smaller than the matching side of the box above (sides compared largest to largest). */
function smallerThanAbove(row: RateRow, above: RateRow | undefined): boolean {
const mine = sortedBox(row);
const theirs = above ? sortedBox(above) : null;
return !!mine && !!theirs && mine.every((s, i) => s < theirs[i]);
}
// One zone's rate rows (shipping-rate-rows-with-dimensions): the BRACKET rows in table order, the overflow rule as one
// line and a quick check priced in the browser from these unsaved rows. `rows` holds this zone's BRACKET rows then its
// OVERFLOW row; `errors` is keyed by index into `rows`.
export function ZoneRatesTable({ zone, rows, errors, onChange }: {
zone: string;
rows: RateRow[];
errors: Map<number, string[]>;
onChange: (rows: RateRow[]) => void;
}) {
const t = useT();
const [check, setCheck] = useState({ weightKg: "", lengthCm: "", widthCm: "", heightCm: "" });
const brackets = rows.map((r, i) => ({ row: r, index: i })).filter((x) => x.row.type === "BRACKET");
const overflowIndex = rows.findIndex((r) => r.type === "OVERFLOW");
const overflow = overflowIndex >= 0 ? rows[overflowIndex] : undefined;
const overflowErrs = overflowIndex >= 0 ? errors.get(overflowIndex) ?? [] : [];
const derived = withDerivedFrom(rows);
const lastUpTo = [...brackets].reverse().find((b) => b.row.toKg != null)?.row.toKg ?? 0;
const setField = (index: number, field: RowField, value: string) =>
onChange(rows.map((r, i) => (i === index ? { ...r, [field]: numberOrNull(value) } : r)));
const addRow = () => {
const blank: RateRow = { zoneCode: zone, type: "BRACKET", fromKg: null, toKg: null, stepKg: null, fee: null, ...NO_BOX };
const at = overflowIndex >= 0 ? overflowIndex : rows.length;
onChange([...rows.slice(0, at), blank, ...rows.slice(at)]);
};
const deleteRow = (index: number) => onChange(rows.filter((_, i) => i !== index));
const setOverflow = (field: "stepKg" | "fee", value: string) => {
const current: RateRow = overflow ?? { zoneCode: zone, type: "OVERFLOW", fromKg: null, toKg: null, stepKg: null, fee: null, ...NO_BOX };
const next: RateRow = { ...current, [field]: numberOrNull(value) };
const others = rows.filter((_, i) => i !== overflowIndex);
// Both fields blank removes the overflow row; otherwise it stays, even with a blank fee (never a silent RM0).
onChange(next.stepKg == null && next.fee == null ? others : [...others, next]);
};
const parcel = {
weightKg: Number(check.weightKg), lengthCm: Number(check.lengthCm), widthCm: Number(check.widthCm), heightCm: Number(check.heightCm),
};
const checkReady = Object.values(check).every((v) => v.trim() !== "") && Object.values(parcel).every((v) => Number.isFinite(v) && v > 0);
const price: ParcelPrice | null = checkReady ? priceParcel(rows, parcel.weightKg, [{ ...parcel, qty: 1 }]) : null;
const sideInput = (index: number, rowNumber: number, side: BoxSide, aria: string, placeholder: string, invalid: boolean) => (
<TableCell className="p-1">
<Input type="number" min="0" step="0.1" className="w-24" aria-label={t(aria, { zone, row: rowNumber })} placeholder={t(placeholder)}
aria-invalid={invalid || undefined} value={shown(rows[index][side])} onChange={(e) => setField(index, side, e.target.value)} />
</TableCell>
);
const checkField = (key: keyof typeof check, label: string) => (
<div className="space-y-1">
<Label htmlFor={`quick-${zone}-${key}`}>{label}</Label>
<Input id={`quick-${zone}-${key}`} type="number" min="0" step="0.01" className="w-28" value={check[key]}
onChange={(e) => setCheck({ ...check, [key]: e.target.value })} />
</div>
);
return (
<div className="space-y-4">
<Table>
<TableHeader>
<TableRow>
<TableHead>{t("ShipRateFromKgCol")}</TableHead>
<TableHead>{t("ShipRateUpToKg")}</TableHead>
<TableHead colSpan={3}>{t("ShipRateMaxBox")}</TableHead>
<TableHead>{t("ShipRateFeeRm")}</TableHead>
<TableHead />
</TableRow>
</TableHeader>
{brackets.map(({ row, index }, n) => {
const rowNumber = n + 1;
const rowErrs = errors.get(index) ?? [];
const invalid = rowErrs.length > 0;
const needsSize = sortedBox(row) == null;
const smaller = smallerThanAbove(row, brackets[n - 1]?.row);
return (
<tbody key={index} className="border-b">
<TableRow className="border-0">
<TableCell className="p-2 tabular-nums text-muted-foreground">{kgText(derived[index].fromKg ?? 0)}</TableCell>
<TableCell className="p-1">
<Input type="number" min="0" step="0.001" className="w-24" aria-label={t("ShipRateUpToAria", { zone, row: rowNumber })}
aria-invalid={invalid || undefined} value={shown(row.toKg)} onChange={(e) => setField(index, "toKg", e.target.value)} />
</TableCell>
{sideInput(index, rowNumber, "maxLengthCm", "ShipRateLengthAria", "ShipRateLengthCm", invalid)}
{sideInput(index, rowNumber, "maxWidthCm", "ShipRateWidthAria", "ShipRateWidthCm", invalid)}
{sideInput(index, rowNumber, "maxHeightCm", "ShipRateHeightAria", "ShipRateHeightCm", invalid)}
<TableCell className="p-1">
<Input type="number" min="0" step="0.01" className="w-24" aria-label={t("ShipRateRowFeeAria", { zone, row: rowNumber })}
value={shown(row.fee)} onChange={(e) => setField(index, "fee", e.target.value)} />
</TableCell>
<TableCell className="p-1 text-right">
<Button variant="ghost" size="icon-sm" aria-label={t("ShipRateDeleteRowAria", { row: rowNumber })} onClick={() => deleteRow(index)}>
<Trash2 aria-hidden="true" />
</Button>
</TableCell>
</TableRow>
{(invalid || needsSize || smaller) && (
<TableRow className="border-0 hover:bg-transparent">
<TableCell colSpan={7} className="px-2 pt-0 pb-2 whitespace-normal">
{rowErrs.map((e) => <p key={e} role="alert" className="text-sm text-destructive">{e}</p>)}
{needsSize && !invalid && <p className="text-sm text-warning">{t("ShipRateNeedsSize")}</p>}
{smaller && <p className="text-sm text-muted-foreground">{t("ShipRateBoxSmallerHint")}</p>}
</TableCell>
</TableRow>
)}
</tbody>
);
})}
</Table>
<Button variant="outline" onClick={addRow}>{t("ShipRateAddRow")}</Button>
<div className="flex flex-wrap items-end gap-3 rounded-md border p-3">
<span className="pb-2 text-sm font-medium">{t("ShipRateAboveKg", { kg: kgText(lastUpTo) })}</span>
<div className="space-y-1">
<Label htmlFor={`overflow-${zone}-step`}>{t("ShipRateEachAdditional")}</Label>
<Input id={`overflow-${zone}-step`} type="number" min="0" step="0.001" className="w-28"
aria-invalid={overflowErrs.length > 0 || undefined} value={shown(overflow?.stepKg)} onChange={(e) => setOverflow("stepKg", e.target.value)} />
</div>
<div className="space-y-1">
<Label htmlFor={`overflow-${zone}-fee`}>{t("ShipRateFeePerStep")}</Label>
<Input id={`overflow-${zone}-fee`} type="number" min="0" step="0.01" className="w-28"
aria-invalid={overflowErrs.length > 0 || undefined} value={shown(overflow?.fee)} onChange={(e) => setOverflow("fee", e.target.value)} />
</div>
{overflowErrs.length > 0 && (
<div className="basis-full">
{overflowErrs.map((e) => <p key={e} role="alert" className="text-sm text-destructive">{e}</p>)}
</div>
)}
</div>
<div className="space-y-2 rounded-md border p-3">
<h3 className="text-sm font-semibold">{t("ShipRateQuickCheck")}</h3>
<div className="flex flex-wrap items-end gap-3">
{checkField("weightKg", t("SkuWeightKg"))}
{checkField("lengthCm", t("SkuLengthCm"))}
{checkField("widthCm", t("SkuWidthCm"))}
{checkField("heightCm", t("SkuHeightCm"))}
</div>
{price && (
<p role="status" className="text-sm">
{"fee" in price
? t("ShipRateQuickResult", { fee: feeText(price.fee), row: price.row })
: "tooLarge" in price ? t("ShipRateQuickTooLarge") : t("ShipRateQuickNoRate")}
</p>
)}
</div>
</div>
);
}