Files
Crussell/frontend/src/lib/utils/format.ts
T
popertots 3866cc5963 fix: round-2 loop-A fresh review (503c326 baseline) — B1 replay cap, A6 discount record, 2FA reissue+cooldown, notification flood, lockout saturation, VAT/refund-status consolidation
Round 2 Loop A fresh money/security/dup-mod review. 23 findings fixed:

MONEY:
- CRITICAL: B1 duplicate auto-refund gains an attempt cap (b1_attempts col, cap 3) —
  a rejected auto-refund no longer re-replays the expired key every sweep run
  (which minted a stacking unauthorized charge each time); FAILED-webhook
  demotion respects the cap; never re-replay a key whose B1 refund failed
- HIGH: A6 deposit_covered_by_discount skip path now APPLIES the eligible
  campaign discount rows immediately (capped) instead of skipping with no
  discount recorded — no more promised-discount-not-recorded overcharge
- MEDIUM: 2FA code burned by the SAVE gate is re-issued on failed
  new-card+save_card charges (re-issue guard now covers req.SaveCard)
- LOW: GetBookingPaymentSummary excludes tip rows from paidAmount (remaining
  now matches the authoritative tip-excluded balance)

SECURITY:
- MEDIUM: unacknowledged CRITICAL admin-notification flood capped (global cap
  on critical_payment_log + refresh_token_reuse rows)
- MEDIUM: 2FA reissue no longer bypasses the mint cooldown (Check no longer
  clears LastMintAt on gate-verify; cleared on terminal charge success)
- MEDIUM: twofa.StateFor map-saturation returns a shared permanently-locked
  state instead of a fresh 5-guess budget per request
- MEDIUM: ProgressiveRateLimit rejects 429 past maxProgressiveSleepDelayMs
  instead of sleeping unboundedly; login bcrypt concurrency semaphore added
- LOW: loginInProgress 409->429; webhook key-set/URL-unset startup check;
  email-verification per-user attempt counter

DUP/MOD:
- formatCurrency single source (frontend format.ts, 7 files consolidated);
  SquareRefundStatusToLocal single source (errors.go, all sites); admin
  audit-log helper dedup; SCA retry model unified (proactive on all 6
  surfaces); buyDailyTotal/daily-cap mirror via backend; lock TTL from
  backend; generateUUID at all card-form sites; magic numbers named
  (defaultPostgresHost, epsilon, fee constants); admin CASH + gift-card
  terminal charges now audited; DAV_SKIP_INIT documented in manuals

Verified: 26/26 dev + 24/24 prod (GO_TESTING=1, the CI condition), both vet
tags, frontend tests+build, env-docs 42/42.
2026-08-22 00:34:50 +01:00

120 lines
3.4 KiB
TypeScript

/**
* Shared formatting utilities for consistent display across the app.
*/
/**
* Convert minutes to a human-readable duration string.
*
* Examples:
* 45 → "45m"
* 60 → "1h"
* 90 → "1h 30m"
* 120 → "2h"
* 150 → "2h 30m"
*/
export function formatDuration(minutes: number): string {
const hours = Math.floor(minutes / 60);
const mins = minutes % 60;
if (hours === 0) return `${mins}m`;
if (mins === 0) return `${hours}h`;
return `${hours}h ${mins}m`;
}
/**
* Format a date/time to "Weekday, Month Day at HH:MM AM/PM".
*
* Examples:
* "2026-05-29T10:00:00Z" → "Friday, May 29 at 10:00 AM"
* "2026-06-05T14:30:00Z" → "Friday, Jun 5 at 2:30 PM"
*/
export function formatDateTime(date: Date | string): string {
const d = typeof date === 'string' ? new Date(date) : date;
const dateStr = d.toLocaleDateString('en-US', {
weekday: 'long',
month: 'short',
day: 'numeric',
timeZone: 'Europe/London'
});
const timeStr = d.toLocaleTimeString('en-US', {
hour: 'numeric',
minute: '2-digit',
hour12: true,
timeZone: 'Europe/London'
});
return `${dateStr} at ${timeStr}`;
}
/**
* Format a Date to ISO date string "YYYY-MM-DD".
*
* Example: new Date(2026, 4, 29) → "2026-05-29"
*/
export function formatDateISO(d: Date, timeZone = 'Europe/London'): string {
return d.toLocaleDateString('en-CA', { timeZone });
}
/**
* Calculate age from a date-of-birth string.
* Returns the number of full years, or null if DOB is invalid.
*/
export function calculateAge(dateOfBirth: string | undefined | null): number | null {
if (!dateOfBirth) return null;
const dob = new Date(dateOfBirth);
if (isNaN(dob.getTime())) return null;
const today = new Date();
// Get London date components to ensure correct DST-safe age calculation
const [dobY, dobM, dobD] = dob
.toLocaleDateString('en-CA', { timeZone: 'Europe/London' })
.split('-')
.map(Number);
const [todayY, todayM, todayD] = today
.toLocaleDateString('en-CA', { timeZone: 'Europe/London' })
.split('-')
.map(Number);
let age = todayY - dobY;
const monthDiff = todayM - dobM;
if (monthDiff < 0 || (monthDiff === 0 && todayD < dobD)) {
age--;
}
return age;
}
// Single cached GBP formatter shared by every `formatCurrency` call — one
// `Intl.NumberFormat` instance instead of a fresh allocation per call, since
// currency formatting runs on the app's hottest rendering paths. The explicit
// `minimumFractionDigits: 2` guarantees whole pounds render as "£5.00", never
// "£5". `formatCurrency` takes the amount in POUNDS (not pence).
const gbpFormatter = new Intl.NumberFormat('en-GB', {
style: 'currency',
currency: 'GBP',
minimumFractionDigits: 2
});
/**
* Format a monetary amount as GBP, e.g. 19.5 → "£19.50".
*
* The amount must be in POUNDS (e.g. `booking.total_amount`, `subtotal`).
* For pence values, divide by 100 at the call site: `formatCurrency(pence / 100)`.
*/
export function formatCurrency(amount: number): string {
return gbpFormatter.format(amount);
}
/**
* Create an array of numbers from 0 to n-1.
*
* Useful for iterating a fixed number of times in Svelte templates:
*
* {#each range(3) as i}
* <div>{i}</div>
* {/each}
*
* Replaces the `{#each Array(3) as _, i (i)}{__}{/each}` workaround pattern
* that was needed to suppress eslint unused-variable warnings.
*/
export function range(n: number): number[] {
return Array.from({ length: n }, (_, i) => i);
}