feat(currency): centralise money formatting + curated currency picker

New `src/lib/utils/currency.ts` is the single source of truth for
display formatting (`formatCurrency`) and the supported-currency
catalog (`SUPPORTED_CURRENCIES`, 10 codes covering the marina market).

New shared components:
- `<CurrencyInput>` — number input with leading symbol prefix and
  decimal inputMode, raw number value out via onChange.
- `<CurrencySelect>` — Select dropdown over `SUPPORTED_CURRENCIES`
  with symbol + code + label per row, replaces the free-text 3-letter
  inputs that let reps type "EURO" or "$$$" into a 3-char ISO column.

Threaded through every money input + display:
- Forms: berth (price/currency), expense (amount/currency), invoice
  (currency Select + line-items unit-price + step-3 review totals).
- Reads: berth-card / berth-columns / invoice-card / expense-card /
  dashboard KPIs / dashboard revenue-forecast / portal-invoices page.
  Each had its own ad-hoc `Intl.NumberFormat` wrapper with slightly
  different fallbacks; collapsed onto the shared helper.

`InvoiceLineItems` gained a `currency` prop so the unit-price input
prefix and the subtotal use the parent invoice's currency rather than
hard-coded `en-US` formatting.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-09 04:24:46 +02:00
parent 72ab7180cf
commit ee2da8f67e
14 changed files with 264 additions and 99 deletions

View File

@@ -22,8 +22,10 @@ import {
} from '@/components/ui/select';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { OwnerPicker } from '@/components/shared/owner-picker';
import { CurrencySelect } from '@/components/shared/currency-select';
import { InvoiceLineItems } from '@/components/invoices/invoice-line-items';
import { apiFetch } from '@/lib/api/client';
import { formatCurrency } from '@/lib/utils/currency';
import { createInvoiceSchema, type CreateInvoiceInput } from '@/lib/validators/invoices';
const PAYMENT_TERMS = [
@@ -324,11 +326,10 @@ export default function NewInvoicePage() {
<div className="space-y-1">
<Label>Currency</Label>
<Input
{...register('currency')}
placeholder="USD"
maxLength={3}
className="uppercase w-24"
<CurrencySelect
value={watchedValues.currency ?? 'USD'}
onValueChange={(v) => setValue('currency', v, { shouldDirty: true })}
className="w-48"
/>
</div>
@@ -352,7 +353,7 @@ export default function NewInvoicePage() {
<CardTitle className="text-base">Line Items</CardTitle>
</CardHeader>
<CardContent>
<InvoiceLineItems name="lineItems" />
<InvoiceLineItems name="lineItems" currency={watchedValues.currency ?? 'USD'} />
{errors.lineItems && !Array.isArray(errors.lineItems) && (
<p className="text-xs text-destructive mt-2">
{(errors.lineItems as { message?: string }).message}
@@ -415,8 +416,10 @@ export default function NewInvoicePage() {
<div key={i} className="flex justify-between text-sm">
<span>{li.description}</span>
<span className="tabular-nums">
{(Number(li.quantity) * Number(li.unitPrice)).toFixed(2)}{' '}
{watchedValues.currency}
{formatCurrency(
Number(li.quantity) * Number(li.unitPrice),
watchedValues.currency,
)}
</span>
</div>
))}
@@ -427,21 +430,21 @@ export default function NewInvoicePage() {
<div className="flex justify-between">
<span className="text-muted-foreground">Subtotal</span>
<span className="tabular-nums">
{subtotal.toFixed(2)} {watchedValues.currency}
{formatCurrency(subtotal, watchedValues.currency)}
</span>
</div>
{isNet10 && (
<div className="flex justify-between text-green-600">
<span>Net 10 Discount (~2%)</span>
<span className="tabular-nums">
-{discountAmount.toFixed(2)} {watchedValues.currency}
-{formatCurrency(discountAmount, watchedValues.currency)}
</span>
</div>
)}
<div className="flex justify-between font-semibold border-t pt-2 mt-1">
<span>Total</span>
<span className="tabular-nums">
{total.toFixed(2)} {watchedValues.currency}
{formatCurrency(total, watchedValues.currency)}
</span>
</div>
</div>

View File

@@ -5,6 +5,7 @@ import type { Metadata } from 'next';
import { getPortalSession } from '@/lib/portal/auth';
import { getClientInvoices } from '@/lib/services/portal.service';
import { Badge } from '@/components/ui/badge';
import { formatCurrency } from '@/lib/utils/currency';
export const metadata: Metadata = { title: 'Invoices' };
@@ -16,16 +17,6 @@ const STATUS_COLORS: Record<string, 'default' | 'secondary' | 'destructive' | 'o
cancelled: 'destructive',
};
function formatCurrency(amount: string, currency: string): string {
const num = parseFloat(amount);
if (isNaN(num)) return `${currency} ${amount}`;
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency,
minimumFractionDigits: 2,
}).format(num);
}
export default async function PortalInvoicesPage() {
const session = await getPortalSession();
if (!session) redirect('/portal/login');

View File

@@ -13,6 +13,7 @@ import {
import { TagBadge } from '@/components/shared/tag-badge';
import { ListCard, ListCardAvatar, ListCardMeta } from '@/components/shared/list-card';
import { cn } from '@/lib/utils';
import { formatCurrency } from '@/lib/utils/currency';
import type { BerthRow } from './berth-columns';
import { mooringLetterDot } from './mooring-letter-tone';
@@ -28,18 +29,6 @@ const STATUS_LABELS: Record<string, string> = {
sold: 'Sold',
};
function formatPrice(price: string, currency: string): string {
try {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: currency || 'USD',
maximumFractionDigits: 0,
}).format(Number(price));
} catch {
return `${currency} ${price}`;
}
}
interface BerthCardProps {
berth: BerthRow;
}
@@ -66,7 +55,10 @@ export function BerthCard({ berth }: BerthCardProps) {
const metaParts: string[] = [];
if (dimText) metaParts.push(dimText);
if (berth.price) metaParts.push(formatPrice(berth.price, berth.priceCurrency));
if (berth.price)
metaParts.push(
formatCurrency(berth.price, berth.priceCurrency, { maxFractionDigits: 0 }),
);
const tags = berth.tags ?? [];

View File

@@ -12,6 +12,7 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { TagBadge } from '@/components/shared/tag-badge';
import { formatCurrency } from '@/lib/utils/currency';
import { mooringLetterDot } from './mooring-letter-tone';
export type BerthRow = {
@@ -176,11 +177,7 @@ function joinNonNull(parts: Array<string | null | undefined>, sep = ' · '): str
function formatMoney(amount: string | null, currency: string): string | null {
if (!amount) return null;
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: currency || 'USD',
maximumFractionDigits: 0,
}).format(Number(amount));
return formatCurrency(amount, currency, { maxFractionDigits: 0 });
}
export const berthColumns: ColumnDef<BerthRow, unknown>[] = [

View File

@@ -20,6 +20,8 @@ import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetFooter } from '@/com
import { Separator } from '@/components/ui/separator';
import { Switch } from '@/components/ui/switch';
import { TagPicker } from '@/components/shared/tag-picker';
import { CurrencyInput } from '@/components/shared/currency-input';
import { CurrencySelect } from '@/components/shared/currency-select';
import { apiFetch } from '@/lib/api/client';
import { toastError } from '@/lib/api/toast-error';
import { updateBerthSchema, type UpdateBerthInput } from '@/lib/validators/berths';
@@ -400,11 +402,22 @@ export function BerthForm({ berth, open, onOpenChange }: BerthFormProps) {
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Price</Label>
<Input type="number" step="0.01" {...register('price')} />
<CurrencyInput
value={watch('price') ?? ''}
currency={watch('priceCurrency') ?? 'USD'}
onChange={(v) =>
setValue('price', v ?? undefined, { shouldDirty: true })
}
/>
</div>
<div className="space-y-2">
<Label>Currency</Label>
<Input {...register('priceCurrency')} placeholder="USD" maxLength={3} />
<CurrencySelect
value={watch('priceCurrency') ?? 'USD'}
onValueChange={(v) =>
setValue('priceCurrency', v, { shouldDirty: true })
}
/>
</div>
</div>
</div>

View File

@@ -6,6 +6,7 @@ import { apiFetch } from '@/lib/api/client';
import { useUIStore } from '@/stores/ui-store';
import { KPITile } from '@/components/ui/kpi-tile';
import { Skeleton } from '@/components/ui/skeleton';
import { formatCurrency } from '@/lib/utils/currency';
import { WidgetErrorBoundary } from './widget-error-boundary';
interface KpiData {
@@ -15,13 +16,7 @@ interface KpiData {
occupancyRate: number;
}
function formatCurrency(value: number): string {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
maximumFractionDigits: 0,
}).format(value);
}
const formatUsd = (value: number) => formatCurrency(value, 'USD', { maxFractionDigits: 0 });
function formatPercent(value: number): string {
return `${value.toFixed(1)}%`;
@@ -81,7 +76,7 @@ export function KpiCards() {
},
{
label: 'Pipeline Value',
value: isError ? '-' : formatCurrency(data?.pipelineValueUsd ?? 0),
value: isError ? '-' : formatUsd(data?.pipelineValueUsd ?? 0),
accent: 'success',
},
{

View File

@@ -7,6 +7,7 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { CardSkeleton } from '@/components/shared/loading-skeleton';
import { stageLabel } from '@/lib/constants';
import { formatCurrency } from '@/lib/utils/currency';
import { WidgetErrorBoundary } from './widget-error-boundary';
interface StageBreakdownRow {
@@ -21,13 +22,7 @@ interface ForecastData {
weightsSource: 'db' | 'default';
}
function formatCurrency(value: number): string {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
maximumFractionDigits: 0,
}).format(value);
}
const formatUsd = (value: number) => formatCurrency(value, 'USD', { maxFractionDigits: 0 });
function RevenueForecastInner() {
const { data, isLoading } = useQuery<ForecastData>({
@@ -56,7 +51,7 @@ function RevenueForecastInner() {
<CardContent className="space-y-4">
<div>
<p className="text-xs text-muted-foreground">Weighted Pipeline Value</p>
<p className="text-2xl font-bold">{formatCurrency(data?.totalWeightedValue ?? 0)}</p>
<p className="text-2xl font-bold">{formatUsd(data?.totalWeightedValue ?? 0)}</p>
</div>
{activeStages.length > 0 && (
@@ -67,7 +62,7 @@ function RevenueForecastInner() {
{stageLabel(s.stage)}
<span className="ml-1 text-xs">({s.count})</span>
</span>
<span className="font-medium tabular-nums">{formatCurrency(s.weightedValue)}</span>
<span className="font-medium tabular-nums">{formatUsd(s.weightedValue)}</span>
</div>
))}
</div>

View File

@@ -13,6 +13,7 @@ import {
} from '@/components/ui/dropdown-menu';
import { ListCard, ListCardAvatar, ListCardMeta } from '@/components/shared/list-card';
import { cn } from '@/lib/utils';
import { formatCurrency } from '@/lib/utils/currency';
import type { ExpenseRow } from './expense-columns';
const PAYMENT_STATUS_COLORS: Record<string, string> = {
@@ -47,13 +48,7 @@ function deriveAccent(status: string | null, duplicateOf: string | null): string
}
}
function formatAmount(amount: string, currency: string): string {
try {
return new Intl.NumberFormat('en', { style: 'currency', currency }).format(Number(amount));
} catch {
return `${currency} ${amount}`;
}
}
const formatAmount = (amount: string, currency: string) => formatCurrency(amount, currency);
interface ExpenseCardProps {
expense: ExpenseRow;

View File

@@ -19,6 +19,8 @@ import {
SelectValue,
} from '@/components/ui/select';
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetFooter } from '@/components/ui/sheet';
import { CurrencyInput } from '@/components/shared/currency-input';
import { CurrencySelect } from '@/components/shared/currency-select';
import { apiFetch } from '@/lib/api/client';
import { createExpenseSchema, type CreateExpenseInput } from '@/lib/validators/expenses';
import { EXPENSE_CATEGORIES, PAYMENT_METHODS } from '@/lib/constants';
@@ -50,6 +52,7 @@ export function ExpenseFormDialog({ open, onOpenChange, expense }: ExpenseFormDi
handleSubmit,
setValue,
reset,
watch,
formState: { errors, isSubmitting },
} = useForm<CreateExpenseInput>({
resolver: zodResolver(createExpenseSchema),
@@ -215,20 +218,26 @@ export function ExpenseFormDialog({ open, onOpenChange, expense }: ExpenseFormDi
<div className="grid grid-cols-2 gap-3">
<div className="space-y-2">
<Label htmlFor="amount">Amount *</Label>
<Input
<CurrencyInput
id="amount"
type="number"
step="0.01"
min="0"
placeholder="0.00"
{...register('amount', { valueAsNumber: true })}
value={watch('amount') ?? ''}
currency={watch('currency') ?? 'USD'}
onChange={(v) =>
setValue('amount', v ?? Number.NaN, { shouldDirty: true, shouldValidate: true })
}
/>
{errors.amount && <p className="text-xs text-destructive">{errors.amount.message}</p>}
</div>
<div className="space-y-2">
<Label htmlFor="currency">Currency</Label>
<Input id="currency" placeholder="USD" maxLength={3} {...register('currency')} />
<CurrencySelect
id="currency"
value={watch('currency') ?? 'USD'}
onValueChange={(v) =>
setValue('currency', v, { shouldDirty: true })
}
/>
{errors.currency && (
<p className="text-xs text-destructive">{errors.currency.message}</p>
)}

View File

@@ -22,6 +22,7 @@ import {
} from '@/components/ui/dropdown-menu';
import { ListCard, ListCardAvatar, ListCardMeta } from '@/components/shared/list-card';
import { cn } from '@/lib/utils';
import { formatCurrency } from '@/lib/utils/currency';
import type { InvoiceRow } from './invoice-columns';
const STATUS_COLORS: Record<string, string> = {
@@ -48,13 +49,7 @@ const STATUS_ACCENT: Record<string, string> = {
cancelled: 'bg-slate-200',
};
function formatAmount(total: string, currency: string): string {
try {
return new Intl.NumberFormat('en', { style: 'currency', currency }).format(Number(total));
} catch {
return `${currency} ${total}`;
}
}
const formatAmount = (total: string, currency: string) => formatCurrency(total, currency);
interface InvoiceCardProps {
invoice: InvoiceRow;

View File

@@ -5,6 +5,8 @@ import { Plus, Trash2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { CurrencyInput } from '@/components/shared/currency-input';
import { formatCurrency } from '@/lib/utils/currency';
interface LineItem {
description: string;
@@ -14,10 +16,13 @@ interface LineItem {
interface InvoiceLineItemsProps {
name?: string;
/** Currency code from the parent invoice form (drives both the
* unit-price input symbol and the subtotal formatting). */
currency?: string;
}
export function InvoiceLineItems({ name = 'lineItems' }: InvoiceLineItemsProps) {
const { register, watch } = useFormContext();
export function InvoiceLineItems({ name = 'lineItems', currency = 'USD' }: InvoiceLineItemsProps) {
const { register, setValue, watch } = useFormContext();
const { fields, append, remove } = useFieldArray({ name });
const lineItems: LineItem[] = watch(name) ?? [];
@@ -66,22 +71,18 @@ export function InvoiceLineItems({ name = 'lineItems' }: InvoiceLineItemsProps)
/>
</div>
<div className="col-span-2">
<Input
{...register(`${name}.${index}.unitPrice`, { valueAsNumber: true })}
type="number"
min="0"
<CurrencyInput
value={lineItems[index]?.unitPrice ?? null}
currency={currency}
onChange={(v) =>
setValue(`${name}.${index}.unitPrice`, v ?? 0, { shouldDirty: true })
}
step="any"
placeholder="0.00"
className="h-8 text-sm text-right"
/>
</div>
<div className="col-span-1 flex items-center justify-end h-8">
<span className="text-sm tabular-nums">
{lineTotal.toLocaleString('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})}
</span>
<span className="text-sm tabular-nums">{formatCurrency(lineTotal, currency)}</span>
</div>
<div className="col-span-1 flex items-center justify-end h-8">
<Button
@@ -120,13 +121,7 @@ export function InvoiceLineItems({ name = 'lineItems' }: InvoiceLineItemsProps)
</Button>
{fields.length > 0 && (
<div className="text-sm font-medium">
Subtotal:{' '}
<span className="tabular-nums">
{subtotal.toLocaleString('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})}
</span>
Subtotal: <span className="tabular-nums">{formatCurrency(subtotal, currency)}</span>
</div>
)}
</div>

View File

@@ -0,0 +1,66 @@
'use client';
import * as React from 'react';
import { Input } from '@/components/ui/input';
import { cn } from '@/lib/utils';
import { currencySymbol } from '@/lib/utils/currency';
interface CurrencyInputProps
extends Omit<React.ComponentProps<'input'>, 'value' | 'onChange' | 'type'> {
/** Controlled raw numeric value. `null` / `undefined` render empty. */
value: number | string | null | undefined;
/** Fires with a raw number (or `null` if cleared). */
onChange: (value: number | null) => void;
/** ISO currency code; renders as a leading symbol prefix. */
currency?: string;
className?: string;
}
/**
* Numeric input pre-decorated with a currency symbol. The display
* value is the raw number the user typed (we don't fight the keystroke
* cadence by re-formatting on every key) — formatted display lives in
* read-only contexts via `formatCurrency()`. This keeps form behaviour
* predictable while still scoping the input to a money field via the
* symbol prefix and the `decimal` inputMode.
*/
export const CurrencyInput = React.forwardRef<HTMLInputElement, CurrencyInputProps>(
({ value, onChange, currency = 'USD', className, ...props }, ref) => {
const symbol = currencySymbol(currency);
const display =
value === null || value === undefined || value === '' ? '' : String(value);
return (
<div className="relative">
<span
className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-sm text-muted-foreground"
aria-hidden
>
{symbol}
</span>
<Input
ref={ref}
type="number"
inputMode="decimal"
step="0.01"
min="0"
value={display}
onChange={(e) => {
const raw = e.target.value;
if (raw === '') {
onChange(null);
return;
}
const n = Number(raw);
onChange(Number.isFinite(n) ? n : null);
}}
className={cn('pl-9 tabular-nums', className)}
{...props}
/>
</div>
);
},
);
CurrencyInput.displayName = 'CurrencyInput';

View File

@@ -0,0 +1,48 @@
'use client';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { SUPPORTED_CURRENCIES } from '@/lib/utils/currency';
interface CurrencySelectProps {
value: string | undefined;
onValueChange: (value: string) => void;
disabled?: boolean;
id?: string;
className?: string;
}
/**
* Select dropdown over the curated `SUPPORTED_CURRENCIES` list. Replaces
* the free-text `<Input maxLength={3}>` price-currency spots so reps
* can't typo "EURO" or "$$$" into a 3-letter ISO column.
*/
export function CurrencySelect({
value,
onValueChange,
disabled,
id,
className,
}: CurrencySelectProps) {
return (
<Select value={value} onValueChange={onValueChange} disabled={disabled}>
<SelectTrigger id={id} className={className}>
<SelectValue placeholder="Select currency" />
</SelectTrigger>
<SelectContent>
{SUPPORTED_CURRENCIES.map((c) => (
<SelectItem key={c.code} value={c.code}>
<span className="tabular-nums mr-2">{c.symbol}</span>
<span className="font-medium">{c.code}</span>
<span className="text-muted-foreground ml-2 text-xs">{c.label}</span>
</SelectItem>
))}
</SelectContent>
</Select>
);
}

71
src/lib/utils/currency.ts Normal file
View File

@@ -0,0 +1,71 @@
/**
* Single source of truth for money formatting + the supported-currency
* dropdown list. Everywhere in the CRM that renders an amount should
* call `formatCurrency()` rather than spinning up its own
* `Intl.NumberFormat`, and every form that captures an amount should
* use the curated `SUPPORTED_CURRENCIES` list rather than a free-text
* 3-letter input.
*/
export const SUPPORTED_CURRENCIES = [
{ code: 'USD', symbol: '$', label: 'US Dollar' },
{ code: 'EUR', symbol: '€', label: 'Euro' },
{ code: 'GBP', symbol: '£', label: 'British Pound' },
{ code: 'CAD', symbol: 'CA$', label: 'Canadian Dollar' },
{ code: 'AUD', symbol: 'A$', label: 'Australian Dollar' },
{ code: 'CHF', symbol: 'CHF', label: 'Swiss Franc' },
{ code: 'JPY', symbol: '¥', label: 'Japanese Yen' },
{ code: 'AED', symbol: 'د.إ', label: 'UAE Dirham' },
{ code: 'SGD', symbol: 'S$', label: 'Singapore Dollar' },
{ code: 'HKD', symbol: 'HK$', label: 'Hong Kong Dollar' },
] as const;
export type SupportedCurrencyCode = (typeof SUPPORTED_CURRENCIES)[number]['code'];
const SUPPORTED_SET: ReadonlySet<string> = new Set(SUPPORTED_CURRENCIES.map((c) => c.code));
/**
* Format an amount for display. Accepts numbers, numeric strings, and
* null/undefined (returns the empty string for the latter so callers
* can short-circuit display logic).
*
* Defaults to `en-US` locale because the CRM is single-locale today;
* pass `locale` explicitly when rendering for portal users in the
* future. Unknown ISO codes fall through to Intl unchanged so the
* function never throws on legacy data.
*/
export function formatCurrency(
amount: number | string | null | undefined,
currency: string | null | undefined = 'USD',
options: { locale?: string; minFractionDigits?: number; maxFractionDigits?: number } = {},
): string {
if (amount === null || amount === undefined || amount === '') return '';
const value = typeof amount === 'number' ? amount : Number(amount);
if (!Number.isFinite(value)) return '';
const code = (currency ?? 'USD').toUpperCase();
const { locale = 'en-US', minFractionDigits = 2, maxFractionDigits = 2 } = options;
try {
return new Intl.NumberFormat(locale, {
style: 'currency',
currency: code,
minimumFractionDigits: minFractionDigits,
maximumFractionDigits: maxFractionDigits,
}).format(value);
} catch {
// Unknown currency code — degrade to a bare number with the code
// appended rather than throwing. Keeps display robust against any
// legacy NocoDB rows that smuggled non-ISO strings into the column.
return `${value.toFixed(maxFractionDigits)} ${code}`;
}
}
/** Whether a 3-letter code is in the curated supported list. */
export function isSupportedCurrency(code: string): boolean {
return SUPPORTED_SET.has(code.toUpperCase());
}
/** Symbol for a given currency code, falling back to the code itself. */
export function currencySymbol(code: string): string {
const match = SUPPORTED_CURRENCIES.find((c) => c.code === code.toUpperCase());
return match?.symbol ?? code.toUpperCase();
}