Files
co-lite/solvway-admin-portal/app/lib/shipping/rateRows.ts
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

97 lines
5.1 KiB
TypeScript

import type { RateRow } from "@/app/lib/services/adminShipping";
import type { Translate } from "@/app/lib/i18n/t";
// The shared rate row rule (shipping-rate-rows-with-dimensions): how a parcel is priced from one zone's rows, how
// "from" is derived, and the row-level checks. The pricing must stay identical to the Java rule in services-inventory.
export type ParcelItem = { weightKg: number; lengthCm: number; widthCm: number; heightCm: number; qty: number };
export type ParcelPrice = { fee: number; row: number } | { tooLarge: true } | { noRate: true };
export const MAX_BOX_CM = 100000;
export const MAX_FEE = 99_999_999.99;
// A side is stored with 2 decimals, so anything below 0.005 cm becomes 0.00 and fits nothing.
const MIN_SIDE_CM = 0.005;
const EPS = 1e-9;
const kgText = (kg: number) => String(Number(kg.toFixed(3)));
const gramsOf = (kg: number) => Math.round(kg * 1000);
const boxOf = (row: RateRow): [number, number, number] | null =>
row.maxLengthCm == null || row.maxWidthCm == null || row.maxHeightCm == null ? null : [row.maxLengthCm, row.maxWidthCm, row.maxHeightCm];
/** Each item's sides, sorted descending, fit the box's pairwise, and the items' total volume fits the box's. A row with any null side fits anything. */
export function fitsBox(items: ParcelItem[], row: RateRow): boolean {
const box = boxOf(row);
if (!box) return true;
const sortedBox = [...box].sort((a, b) => b - a);
let volume = 0;
for (const it of items) {
const sides = [it.lengthCm, it.widthCm, it.heightCm].sort((a, b) => b - a);
if (sides.some((s, i) => s > sortedBox[i] + EPS)) return false;
volume += it.lengthCm * it.widthCm * it.heightCm * it.qty;
}
return volume <= box[0] * box[1] * box[2] + EPS;
}
/** Prices a parcel from one zone's BRACKET and OVERFLOW rows. `row` is the 1-based position among BRACKET rows sorted by up to. */
export function priceParcel(rows: RateRow[], weightKg: number, items: ParcelItem[]): ParcelPrice {
const brackets = rows.filter((r) => r.type === "BRACKET" && r.toKg != null).sort((a, b) => gramsOf(a.toKg!) - gramsOf(b.toKg!));
if (brackets.length === 0) return { noRate: true };
const totalKg = items.length > 0 ? items.reduce((s, it) => s + it.weightKg * it.qty, 0) : weightKg;
const grams = Math.max(1, Math.ceil(totalKg * 1000 - 1e-6));
for (let i = 0; i < brackets.length; i++) {
if (grams <= gramsOf(brackets[i].toKg!) && fitsBox(items, brackets[i])) return brackets[i].fee == null ? { noRate: true } : { fee: brackets[i].fee!, row: i + 1 };
}
const last = brackets[brackets.length - 1];
const lastG = gramsOf(last.toKg!);
if (grams > lastG && fitsBox(items, last)) {
const over = rows.find((r) => r.type === "OVERFLOW");
if (!over || over.stepKg == null || gramsOf(over.stepKg) <= 0 || over.fee == null || last.fee == null) return { noRate: true };
const steps = Math.ceil((grams - lastG) / gramsOf(over.stepKg));
return { fee: Math.round((last.fee + steps * over.fee) * 100) / 100, row: brackets.length };
}
return { tooLarge: true };
}
/** Sets each BRACKET row's fromKg to the previous BRACKET toKg of the same zone, in array order (0 for the first). */
export function withDerivedFrom(rows: RateRow[]): RateRow[] {
const prev = new Map<string, number>();
return rows.map((r) => {
if (r.type !== "BRACKET") return r;
const from = prev.get(r.zoneCode) ?? 0;
if (r.toKg != null) prev.set(r.zoneCode, r.toKg);
return { ...r, fromKg: from };
});
}
/** Row-level checks (BRACKET: up to, box, fee; OVERFLOW: step, fee), keyed by index into `rows`. `rowNumbers[i]` is rows[i]'s display row. */
export function rowErrors(rows: RateRow[], rowNumbers: number[], t: Translate): Map<number, string[]> {
const errors = new Map<number, string[]>();
const add = (i: number, msg: string) => errors.set(i, [...(errors.get(i) ?? []), msg]);
const prevTo = new Map<string, number>();
const feeError = (r: RateRow, i: number) => {
if (r.fee == null || Number.isNaN(r.fee) || r.fee < 0) add(i, t("ShipRateErrFeeMin", { row: rowNumbers[i] }));
else if (r.fee > MAX_FEE) add(i, t("ShipRateErrFeeMax", { row: rowNumbers[i], max: MAX_FEE }));
};
rows.forEach((r, i) => {
const row = rowNumbers[i];
if (r.type === "OVERFLOW") {
if (r.stepKg == null || Number.isNaN(r.stepKg) || gramsOf(r.stepKg) <= 0) add(i, t("ShipRateErrStepPositive", { row }));
feeError(r, i);
return;
}
if (r.type !== "BRACKET") return;
if (r.toKg == null || Number.isNaN(r.toKg) || gramsOf(r.toKg) <= 0) {
add(i, t("ShipRateErrUpToPositive", { row }));
} else {
const prev = prevTo.get(r.zoneCode);
if (prev != null && gramsOf(r.toKg) <= gramsOf(prev)) add(i, t("ShipRateErrUpTo", { row, kg: kgText(prev) }));
else prevTo.set(r.zoneCode, r.toKg);
}
const sides = [r.maxLengthCm, r.maxWidthCm, r.maxHeightCm];
if (sides.some((s) => s == null || Number.isNaN(s) || s < MIN_SIDE_CM)) add(i, t("ShipRateErrBox", { row }));
else if (sides.some((s) => (s as number) > MAX_BOX_CM)) add(i, t("ShipRateErrBoxMax", { row, max: MAX_BOX_CM }));
feeError(r, i);
});
return errors;
}