Files
parking_solution/apps/web/src/lib/format.ts
T
julian a9ccf9e20c feat(carwash): Car Wash v1 + per-till shifts + site-level pay-at + till access by module permission
Car Wash — the pilot venue module (wiki/decisions/venue-modules.md):
- Master data (categories × services price matrix) at /setup/carwash; the desk at /wash
  (ticket lookup → order; open queue oldest-first: Done / Paid cash / Paid card / Void;
  Finished list). Orders freeze names + price; their life is signed (carwash_order,
  carwash_payment). Migration 0027.
- Where money is taken is a SITE setting (carwash_config.pay_at, migration 0028, signed
  config_change on a flip) — no per-order radio; a stale client is refused (409).
- Core seams: PayStation charge providers (a booth-paid wash rides the parking payment as
  chargeLines) + applyValidation() shared with the merchant route. A bay-paid, done wash
  signs the $0 parking payment so the exit reader releases the car.
- "Parking discount" modes for the wash: free while the wash runs (+ tolerance) and wash
  price off the fee (floored at 0), resolved at done and anchored at the order's intake
  (the entry-anchored version comped a 74-day stay); typed-amount and percent hidden for
  the wash. Long durations render y/d/h/m.

Tills — a shift belongs to a till, not the site (wiki/concepts/shift.md §Tills):
- TillId booth|carwash; every money event names its till (absent = booth, so the chain
  re-folds identically). ShiftService is per till: single-open, folds, X/Z-reports,
  vouchers, carry-forward. A bay payment needs the carwash shift.
- Working a till needs that till's module permission (manifest tillPermission; 403
  till_forbidden); /api/shift/tills lists only the role's tills.
- Web: ShiftButton per till (header = booth, wash desk = carwash); shift hub lists every
  open shift with till badges + filter; drawer hub switches tills.

Modules: landing per module (index route resolves booth → module landing → shifts →
profile); guards bounce to "/", /booth needs session:read.

Tests: carwash e2e suite (settings, intake, booth/bay paths, modes, void, gate, pay-at
policy, till permissions), 6 per-till shift tests; suite green (1 pre-existing flaky
backup test under the parallel run).

Claude-Session: https://claude.ai/code/session_01FWncR69HgGPuei1dLrW3cU
2026-09-05 13:23:09 +02:00

153 lines
6.8 KiB
TypeScript

// Small formatting helpers for the booth. Money is integer MINOR units (never a
// float — matches the tariff/ledger model); duration is whole minutes.
/** Format integer minor units + ISO-4217 currency as a major-unit string. */
export function formatMoney(amountMinor: number, currency: string): string {
const major = amountMinor / 100;
try {
return new Intl.NumberFormat(undefined, { style: "currency", currency }).format(major);
} catch {
// Unknown/garbled currency code — fall back to a plain number + the code.
return `${major.toFixed(2)} ${currency}`;
}
}
/** Human duration between two ISO times, e.g. "2h 14m" / "47m" / "0m". */
export function formatDuration(fromIso: string, toIso: string): string {
const ms = Date.parse(toIso) - Date.parse(fromIso);
if (!Number.isFinite(ms) || ms < 0) return "—";
return formatMinutesLong(Math.floor(ms / 60_000));
}
/** "Xy Xd Xh Xm" with the leading zero units dropped — a stay of 1797h reads as
* "74d 21h 23m", not a wall of hours (a stale/forgotten ticket is a real case on a
* booth; the number should still be readable at a glance). Years only past 365 days. */
export function formatMinutesLong(totalMinutes: number): string {
const mins = Math.max(0, Math.floor(totalMinutes));
const y = Math.floor(mins / (365 * 24 * 60));
const d = Math.floor((mins % (365 * 24 * 60)) / (24 * 60));
const h = Math.floor((mins % (24 * 60)) / 60);
const m = mins % 60;
const parts: string[] = [];
if (y > 0) parts.push(`${y}y`);
if (y > 0 || d > 0) parts.push(`${d}d`);
if (y > 0 || d > 0 || h > 0) parts.push(`${h}h`);
parts.push(`${m}m`);
return parts.join(" ");
}
/** Remaining time until `untilIso`, as a live countdown: "M:SS" (or "H:MM:SS" past an
* hour). Returns null once expired (or for a bad/empty input) so callers can drop the
* badge. Pass `nowMs` (a ticking clock) to make it update each second. */
export function formatCountdown(untilIso: string | null, nowMs: number = Date.now()): string | null {
if (!untilIso) return null;
const ms = Date.parse(untilIso) - nowMs;
if (!Number.isFinite(ms) || ms <= 0) return null;
const total = Math.ceil(ms / 1000);
const h = Math.floor(total / 3600);
const m = Math.floor((total % 3600) / 60);
const s = total % 60;
const ss = String(s).padStart(2, "0");
if (h > 0) return `${h}:${String(m).padStart(2, "0")}:${ss}`;
return `${m}:${ss}`;
}
/** Human duration from whole minutes, e.g. 134 → "2h 14m", 47 → "47m", 0 → "0m". */
export function formatMinutes(mins: number): string {
if (!Number.isFinite(mins) || mins < 0) return "—";
return formatMinutesLong(Math.round(mins));
}
/** Calendar-day difference (local) between two dates: 0 = same day, 1 = d is one day
* before ref, etc. Compares date parts only (ignores time-of-day). */
function dayDiff(d: Date, ref: Date): number {
const a = new Date(d.getFullYear(), d.getMonth(), d.getDate());
const b = new Date(ref.getFullYear(), ref.getMonth(), ref.getDate());
return Math.round((b.getTime() - a.getTime()) / 86_400_000);
}
/** HH:MM (local, 24h) for the relative-day labels; ":ss" appended when `seconds`. */
function hhmm(d: Date, seconds = false): string {
const p = (n: number) => String(n).padStart(2, "0");
const base = `${p(d.getHours())}:${p(d.getMinutes())}`;
return seconds ? `${base}:${p(d.getSeconds())}` : base;
}
/** Minimal shape of i18next's `t` that we rely on: a string lookup, plus the
* `returnObjects` overload used to fetch the month-name array. */
export interface TFn {
(key: string): string;
(key: string, opts: { returnObjects: true }): unknown;
}
/** Localized month name (index 0 = January) from the i18n catalog. Browser ICU on
* the appliance may lack Albanian data, so we DON'T use Intl — the catalog is the
* source of truth. Falls back to a numeric month if the array is missing. */
function monthName(d: Date, t: TFn): string {
const months = t("common.months", { returnObjects: true });
if (Array.isArray(months) && typeof months[d.getMonth()] === "string") {
return months[d.getMonth()] as string;
}
return String(d.getMonth() + 1);
}
/** Short month ("Qer", "Korr") from the catalog — the UI-wide date standard
* (2026-07-06): every visible date reads "25 Qer" / "7 Korr 2025", never the
* browser-locale "7/6/2026". Falls back to the full name, then the number. */
function monthShort(d: Date, t: TFn): string {
const months = t("common.monthsShort", { returnObjects: true });
if (Array.isArray(months) && typeof months[d.getMonth()] === "string") {
return months[d.getMonth()] as string;
}
return monthName(d, t);
}
/** "HH:mm" (local, 24h) — the unified time-of-day everywhere ("—" for bad input). */
export function formatClock(iso: string | null): string {
if (!iso) return "—";
const d = new Date(iso);
return Number.isNaN(d.getTime()) ? "—" : hhmm(d);
}
/** "25 Qer" (current year) / "25 Qer 2025" (other years) — the unified DATE. */
export function formatDate(iso: string | null, t: TFn): string {
if (!iso) return "—";
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return "—";
const base = `${d.getDate()} ${monthShort(d, t)}`;
return d.getFullYear() === new Date().getFullYear() ? base : `${base} ${d.getFullYear()}`;
}
/** "25 Qer 14:30" (+ ":ss" when `seconds`) — the unified absolute DATE+TIME. Use
* formatRelativeDateTime instead where "Sot/Dje" reads better (feeds, history). */
export function formatDateTime(iso: string | null, t: TFn, opts?: { seconds?: boolean }): string {
if (!iso) return "—";
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return "—";
return `${formatDate(iso, t)} ${hhmm(d, opts?.seconds)}`;
}
/**
* Human, day-relative date+time for sessions/logs/history. An event from earlier
* today reads "Sot 10:48", yesterday "Dje 17:33", and anything older a localized
* "17 Qershor 10:48" (month name from the active catalog). Keeps time-of-day on
* every variant — operators care about it within a shift.
*
* `t` supplies the today/yesterday words AND the month names (the appliance browser
* may lack Albanian Intl data, so month names come from the catalog, not Intl).
*
* `seconds` appends ":ss" — use it where a timestamp sits next to another that shows
* seconds (e.g. the booth pay modal's entry vs. exit rows), so the two read alike.
*/
export function formatRelativeDateTime(iso: string | null, t: TFn, opts?: { seconds?: boolean }): string {
if (!iso) return "—";
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return "—";
const time = hhmm(d, opts?.seconds);
const diff = dayDiff(d, new Date());
if (diff === 0) return `${t("common.today")} ${time}`;
if (diff === 1) return `${t("common.yesterday")} ${time}`;
// Older (or future): "17 Qer 10:48" — the short-month standard, year only if it differs.
return `${formatDate(iso, t)} ${time}`;
}