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:
@@ -22,8 +22,10 @@ import {
|
|||||||
} from '@/components/ui/select';
|
} from '@/components/ui/select';
|
||||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||||
import { OwnerPicker } from '@/components/shared/owner-picker';
|
import { OwnerPicker } from '@/components/shared/owner-picker';
|
||||||
|
import { CurrencySelect } from '@/components/shared/currency-select';
|
||||||
import { InvoiceLineItems } from '@/components/invoices/invoice-line-items';
|
import { InvoiceLineItems } from '@/components/invoices/invoice-line-items';
|
||||||
import { apiFetch } from '@/lib/api/client';
|
import { apiFetch } from '@/lib/api/client';
|
||||||
|
import { formatCurrency } from '@/lib/utils/currency';
|
||||||
import { createInvoiceSchema, type CreateInvoiceInput } from '@/lib/validators/invoices';
|
import { createInvoiceSchema, type CreateInvoiceInput } from '@/lib/validators/invoices';
|
||||||
|
|
||||||
const PAYMENT_TERMS = [
|
const PAYMENT_TERMS = [
|
||||||
@@ -324,11 +326,10 @@ export default function NewInvoicePage() {
|
|||||||
|
|
||||||
<div className="space-y-1">
|
<div className="space-y-1">
|
||||||
<Label>Currency</Label>
|
<Label>Currency</Label>
|
||||||
<Input
|
<CurrencySelect
|
||||||
{...register('currency')}
|
value={watchedValues.currency ?? 'USD'}
|
||||||
placeholder="USD"
|
onValueChange={(v) => setValue('currency', v, { shouldDirty: true })}
|
||||||
maxLength={3}
|
className="w-48"
|
||||||
className="uppercase w-24"
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -352,7 +353,7 @@ export default function NewInvoicePage() {
|
|||||||
<CardTitle className="text-base">Line Items</CardTitle>
|
<CardTitle className="text-base">Line Items</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<InvoiceLineItems name="lineItems" />
|
<InvoiceLineItems name="lineItems" currency={watchedValues.currency ?? 'USD'} />
|
||||||
{errors.lineItems && !Array.isArray(errors.lineItems) && (
|
{errors.lineItems && !Array.isArray(errors.lineItems) && (
|
||||||
<p className="text-xs text-destructive mt-2">
|
<p className="text-xs text-destructive mt-2">
|
||||||
{(errors.lineItems as { message?: string }).message}
|
{(errors.lineItems as { message?: string }).message}
|
||||||
@@ -415,8 +416,10 @@ export default function NewInvoicePage() {
|
|||||||
<div key={i} className="flex justify-between text-sm">
|
<div key={i} className="flex justify-between text-sm">
|
||||||
<span>{li.description}</span>
|
<span>{li.description}</span>
|
||||||
<span className="tabular-nums">
|
<span className="tabular-nums">
|
||||||
{(Number(li.quantity) * Number(li.unitPrice)).toFixed(2)}{' '}
|
{formatCurrency(
|
||||||
{watchedValues.currency}
|
Number(li.quantity) * Number(li.unitPrice),
|
||||||
|
watchedValues.currency,
|
||||||
|
)}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
@@ -427,21 +430,21 @@ export default function NewInvoicePage() {
|
|||||||
<div className="flex justify-between">
|
<div className="flex justify-between">
|
||||||
<span className="text-muted-foreground">Subtotal</span>
|
<span className="text-muted-foreground">Subtotal</span>
|
||||||
<span className="tabular-nums">
|
<span className="tabular-nums">
|
||||||
{subtotal.toFixed(2)} {watchedValues.currency}
|
{formatCurrency(subtotal, watchedValues.currency)}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
{isNet10 && (
|
{isNet10 && (
|
||||||
<div className="flex justify-between text-green-600">
|
<div className="flex justify-between text-green-600">
|
||||||
<span>Net 10 Discount (~2%)</span>
|
<span>Net 10 Discount (~2%)</span>
|
||||||
<span className="tabular-nums">
|
<span className="tabular-nums">
|
||||||
-{discountAmount.toFixed(2)} {watchedValues.currency}
|
-{formatCurrency(discountAmount, watchedValues.currency)}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<div className="flex justify-between font-semibold border-t pt-2 mt-1">
|
<div className="flex justify-between font-semibold border-t pt-2 mt-1">
|
||||||
<span>Total</span>
|
<span>Total</span>
|
||||||
<span className="tabular-nums">
|
<span className="tabular-nums">
|
||||||
{total.toFixed(2)} {watchedValues.currency}
|
{formatCurrency(total, watchedValues.currency)}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import type { Metadata } from 'next';
|
|||||||
import { getPortalSession } from '@/lib/portal/auth';
|
import { getPortalSession } from '@/lib/portal/auth';
|
||||||
import { getClientInvoices } from '@/lib/services/portal.service';
|
import { getClientInvoices } from '@/lib/services/portal.service';
|
||||||
import { Badge } from '@/components/ui/badge';
|
import { Badge } from '@/components/ui/badge';
|
||||||
|
import { formatCurrency } from '@/lib/utils/currency';
|
||||||
|
|
||||||
export const metadata: Metadata = { title: 'Invoices' };
|
export const metadata: Metadata = { title: 'Invoices' };
|
||||||
|
|
||||||
@@ -16,16 +17,6 @@ const STATUS_COLORS: Record<string, 'default' | 'secondary' | 'destructive' | 'o
|
|||||||
cancelled: 'destructive',
|
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() {
|
export default async function PortalInvoicesPage() {
|
||||||
const session = await getPortalSession();
|
const session = await getPortalSession();
|
||||||
if (!session) redirect('/portal/login');
|
if (!session) redirect('/portal/login');
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
import { TagBadge } from '@/components/shared/tag-badge';
|
import { TagBadge } from '@/components/shared/tag-badge';
|
||||||
import { ListCard, ListCardAvatar, ListCardMeta } from '@/components/shared/list-card';
|
import { ListCard, ListCardAvatar, ListCardMeta } from '@/components/shared/list-card';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
|
import { formatCurrency } from '@/lib/utils/currency';
|
||||||
import type { BerthRow } from './berth-columns';
|
import type { BerthRow } from './berth-columns';
|
||||||
import { mooringLetterDot } from './mooring-letter-tone';
|
import { mooringLetterDot } from './mooring-letter-tone';
|
||||||
|
|
||||||
@@ -28,18 +29,6 @@ const STATUS_LABELS: Record<string, string> = {
|
|||||||
sold: 'Sold',
|
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 {
|
interface BerthCardProps {
|
||||||
berth: BerthRow;
|
berth: BerthRow;
|
||||||
}
|
}
|
||||||
@@ -66,7 +55,10 @@ export function BerthCard({ berth }: BerthCardProps) {
|
|||||||
|
|
||||||
const metaParts: string[] = [];
|
const metaParts: string[] = [];
|
||||||
if (dimText) metaParts.push(dimText);
|
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 ?? [];
|
const tags = berth.tags ?? [];
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from '@/components/ui/dropdown-menu';
|
} from '@/components/ui/dropdown-menu';
|
||||||
import { TagBadge } from '@/components/shared/tag-badge';
|
import { TagBadge } from '@/components/shared/tag-badge';
|
||||||
|
import { formatCurrency } from '@/lib/utils/currency';
|
||||||
import { mooringLetterDot } from './mooring-letter-tone';
|
import { mooringLetterDot } from './mooring-letter-tone';
|
||||||
|
|
||||||
export type BerthRow = {
|
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 {
|
function formatMoney(amount: string | null, currency: string): string | null {
|
||||||
if (!amount) return null;
|
if (!amount) return null;
|
||||||
return new Intl.NumberFormat('en-US', {
|
return formatCurrency(amount, currency, { maxFractionDigits: 0 });
|
||||||
style: 'currency',
|
|
||||||
currency: currency || 'USD',
|
|
||||||
maximumFractionDigits: 0,
|
|
||||||
}).format(Number(amount));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const berthColumns: ColumnDef<BerthRow, unknown>[] = [
|
export const berthColumns: ColumnDef<BerthRow, unknown>[] = [
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetFooter } from '@/com
|
|||||||
import { Separator } from '@/components/ui/separator';
|
import { Separator } from '@/components/ui/separator';
|
||||||
import { Switch } from '@/components/ui/switch';
|
import { Switch } from '@/components/ui/switch';
|
||||||
import { TagPicker } from '@/components/shared/tag-picker';
|
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 { apiFetch } from '@/lib/api/client';
|
||||||
import { toastError } from '@/lib/api/toast-error';
|
import { toastError } from '@/lib/api/toast-error';
|
||||||
import { updateBerthSchema, type UpdateBerthInput } from '@/lib/validators/berths';
|
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="grid grid-cols-2 gap-4">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label>Price</Label>
|
<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>
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label>Currency</Label>
|
<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>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { apiFetch } from '@/lib/api/client';
|
|||||||
import { useUIStore } from '@/stores/ui-store';
|
import { useUIStore } from '@/stores/ui-store';
|
||||||
import { KPITile } from '@/components/ui/kpi-tile';
|
import { KPITile } from '@/components/ui/kpi-tile';
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
import { Skeleton } from '@/components/ui/skeleton';
|
||||||
|
import { formatCurrency } from '@/lib/utils/currency';
|
||||||
import { WidgetErrorBoundary } from './widget-error-boundary';
|
import { WidgetErrorBoundary } from './widget-error-boundary';
|
||||||
|
|
||||||
interface KpiData {
|
interface KpiData {
|
||||||
@@ -15,13 +16,7 @@ interface KpiData {
|
|||||||
occupancyRate: number;
|
occupancyRate: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatCurrency(value: number): string {
|
const formatUsd = (value: number) => formatCurrency(value, 'USD', { maxFractionDigits: 0 });
|
||||||
return new Intl.NumberFormat('en-US', {
|
|
||||||
style: 'currency',
|
|
||||||
currency: 'USD',
|
|
||||||
maximumFractionDigits: 0,
|
|
||||||
}).format(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatPercent(value: number): string {
|
function formatPercent(value: number): string {
|
||||||
return `${value.toFixed(1)}%`;
|
return `${value.toFixed(1)}%`;
|
||||||
@@ -81,7 +76,7 @@ export function KpiCards() {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: 'Pipeline Value',
|
label: 'Pipeline Value',
|
||||||
value: isError ? '-' : formatCurrency(data?.pipelineValueUsd ?? 0),
|
value: isError ? '-' : formatUsd(data?.pipelineValueUsd ?? 0),
|
||||||
accent: 'success',
|
accent: 'success',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
|||||||
import { Badge } from '@/components/ui/badge';
|
import { Badge } from '@/components/ui/badge';
|
||||||
import { CardSkeleton } from '@/components/shared/loading-skeleton';
|
import { CardSkeleton } from '@/components/shared/loading-skeleton';
|
||||||
import { stageLabel } from '@/lib/constants';
|
import { stageLabel } from '@/lib/constants';
|
||||||
|
import { formatCurrency } from '@/lib/utils/currency';
|
||||||
import { WidgetErrorBoundary } from './widget-error-boundary';
|
import { WidgetErrorBoundary } from './widget-error-boundary';
|
||||||
|
|
||||||
interface StageBreakdownRow {
|
interface StageBreakdownRow {
|
||||||
@@ -21,13 +22,7 @@ interface ForecastData {
|
|||||||
weightsSource: 'db' | 'default';
|
weightsSource: 'db' | 'default';
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatCurrency(value: number): string {
|
const formatUsd = (value: number) => formatCurrency(value, 'USD', { maxFractionDigits: 0 });
|
||||||
return new Intl.NumberFormat('en-US', {
|
|
||||||
style: 'currency',
|
|
||||||
currency: 'USD',
|
|
||||||
maximumFractionDigits: 0,
|
|
||||||
}).format(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
function RevenueForecastInner() {
|
function RevenueForecastInner() {
|
||||||
const { data, isLoading } = useQuery<ForecastData>({
|
const { data, isLoading } = useQuery<ForecastData>({
|
||||||
@@ -56,7 +51,7 @@ function RevenueForecastInner() {
|
|||||||
<CardContent className="space-y-4">
|
<CardContent className="space-y-4">
|
||||||
<div>
|
<div>
|
||||||
<p className="text-xs text-muted-foreground">Weighted Pipeline Value</p>
|
<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>
|
</div>
|
||||||
|
|
||||||
{activeStages.length > 0 && (
|
{activeStages.length > 0 && (
|
||||||
@@ -67,7 +62,7 @@ function RevenueForecastInner() {
|
|||||||
{stageLabel(s.stage)}
|
{stageLabel(s.stage)}
|
||||||
<span className="ml-1 text-xs">({s.count})</span>
|
<span className="ml-1 text-xs">({s.count})</span>
|
||||||
</span>
|
</span>
|
||||||
<span className="font-medium tabular-nums">{formatCurrency(s.weightedValue)}</span>
|
<span className="font-medium tabular-nums">{formatUsd(s.weightedValue)}</span>
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import {
|
|||||||
} from '@/components/ui/dropdown-menu';
|
} from '@/components/ui/dropdown-menu';
|
||||||
import { ListCard, ListCardAvatar, ListCardMeta } from '@/components/shared/list-card';
|
import { ListCard, ListCardAvatar, ListCardMeta } from '@/components/shared/list-card';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
|
import { formatCurrency } from '@/lib/utils/currency';
|
||||||
import type { ExpenseRow } from './expense-columns';
|
import type { ExpenseRow } from './expense-columns';
|
||||||
|
|
||||||
const PAYMENT_STATUS_COLORS: Record<string, string> = {
|
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 {
|
const formatAmount = (amount: string, currency: string) => formatCurrency(amount, currency);
|
||||||
try {
|
|
||||||
return new Intl.NumberFormat('en', { style: 'currency', currency }).format(Number(amount));
|
|
||||||
} catch {
|
|
||||||
return `${currency} ${amount}`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ExpenseCardProps {
|
interface ExpenseCardProps {
|
||||||
expense: ExpenseRow;
|
expense: ExpenseRow;
|
||||||
|
|||||||
@@ -19,6 +19,8 @@ import {
|
|||||||
SelectValue,
|
SelectValue,
|
||||||
} from '@/components/ui/select';
|
} from '@/components/ui/select';
|
||||||
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetFooter } from '@/components/ui/sheet';
|
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 { apiFetch } from '@/lib/api/client';
|
||||||
import { createExpenseSchema, type CreateExpenseInput } from '@/lib/validators/expenses';
|
import { createExpenseSchema, type CreateExpenseInput } from '@/lib/validators/expenses';
|
||||||
import { EXPENSE_CATEGORIES, PAYMENT_METHODS } from '@/lib/constants';
|
import { EXPENSE_CATEGORIES, PAYMENT_METHODS } from '@/lib/constants';
|
||||||
@@ -50,6 +52,7 @@ export function ExpenseFormDialog({ open, onOpenChange, expense }: ExpenseFormDi
|
|||||||
handleSubmit,
|
handleSubmit,
|
||||||
setValue,
|
setValue,
|
||||||
reset,
|
reset,
|
||||||
|
watch,
|
||||||
formState: { errors, isSubmitting },
|
formState: { errors, isSubmitting },
|
||||||
} = useForm<CreateExpenseInput>({
|
} = useForm<CreateExpenseInput>({
|
||||||
resolver: zodResolver(createExpenseSchema),
|
resolver: zodResolver(createExpenseSchema),
|
||||||
@@ -215,20 +218,26 @@ export function ExpenseFormDialog({ open, onOpenChange, expense }: ExpenseFormDi
|
|||||||
<div className="grid grid-cols-2 gap-3">
|
<div className="grid grid-cols-2 gap-3">
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="amount">Amount *</Label>
|
<Label htmlFor="amount">Amount *</Label>
|
||||||
<Input
|
<CurrencyInput
|
||||||
id="amount"
|
id="amount"
|
||||||
type="number"
|
value={watch('amount') ?? ''}
|
||||||
step="0.01"
|
currency={watch('currency') ?? 'USD'}
|
||||||
min="0"
|
onChange={(v) =>
|
||||||
placeholder="0.00"
|
setValue('amount', v ?? Number.NaN, { shouldDirty: true, shouldValidate: true })
|
||||||
{...register('amount', { valueAsNumber: true })}
|
}
|
||||||
/>
|
/>
|
||||||
{errors.amount && <p className="text-xs text-destructive">{errors.amount.message}</p>}
|
{errors.amount && <p className="text-xs text-destructive">{errors.amount.message}</p>}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="currency">Currency</Label>
|
<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 && (
|
{errors.currency && (
|
||||||
<p className="text-xs text-destructive">{errors.currency.message}</p>
|
<p className="text-xs text-destructive">{errors.currency.message}</p>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import {
|
|||||||
} from '@/components/ui/dropdown-menu';
|
} from '@/components/ui/dropdown-menu';
|
||||||
import { ListCard, ListCardAvatar, ListCardMeta } from '@/components/shared/list-card';
|
import { ListCard, ListCardAvatar, ListCardMeta } from '@/components/shared/list-card';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
|
import { formatCurrency } from '@/lib/utils/currency';
|
||||||
import type { InvoiceRow } from './invoice-columns';
|
import type { InvoiceRow } from './invoice-columns';
|
||||||
|
|
||||||
const STATUS_COLORS: Record<string, string> = {
|
const STATUS_COLORS: Record<string, string> = {
|
||||||
@@ -48,13 +49,7 @@ const STATUS_ACCENT: Record<string, string> = {
|
|||||||
cancelled: 'bg-slate-200',
|
cancelled: 'bg-slate-200',
|
||||||
};
|
};
|
||||||
|
|
||||||
function formatAmount(total: string, currency: string): string {
|
const formatAmount = (total: string, currency: string) => formatCurrency(total, currency);
|
||||||
try {
|
|
||||||
return new Intl.NumberFormat('en', { style: 'currency', currency }).format(Number(total));
|
|
||||||
} catch {
|
|
||||||
return `${currency} ${total}`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
interface InvoiceCardProps {
|
interface InvoiceCardProps {
|
||||||
invoice: InvoiceRow;
|
invoice: InvoiceRow;
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import { Plus, Trash2 } from 'lucide-react';
|
|||||||
|
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { CurrencyInput } from '@/components/shared/currency-input';
|
||||||
|
import { formatCurrency } from '@/lib/utils/currency';
|
||||||
|
|
||||||
interface LineItem {
|
interface LineItem {
|
||||||
description: string;
|
description: string;
|
||||||
@@ -14,10 +16,13 @@ interface LineItem {
|
|||||||
|
|
||||||
interface InvoiceLineItemsProps {
|
interface InvoiceLineItemsProps {
|
||||||
name?: string;
|
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) {
|
export function InvoiceLineItems({ name = 'lineItems', currency = 'USD' }: InvoiceLineItemsProps) {
|
||||||
const { register, watch } = useFormContext();
|
const { register, setValue, watch } = useFormContext();
|
||||||
const { fields, append, remove } = useFieldArray({ name });
|
const { fields, append, remove } = useFieldArray({ name });
|
||||||
|
|
||||||
const lineItems: LineItem[] = watch(name) ?? [];
|
const lineItems: LineItem[] = watch(name) ?? [];
|
||||||
@@ -66,22 +71,18 @@ export function InvoiceLineItems({ name = 'lineItems' }: InvoiceLineItemsProps)
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="col-span-2">
|
<div className="col-span-2">
|
||||||
<Input
|
<CurrencyInput
|
||||||
{...register(`${name}.${index}.unitPrice`, { valueAsNumber: true })}
|
value={lineItems[index]?.unitPrice ?? null}
|
||||||
type="number"
|
currency={currency}
|
||||||
min="0"
|
onChange={(v) =>
|
||||||
|
setValue(`${name}.${index}.unitPrice`, v ?? 0, { shouldDirty: true })
|
||||||
|
}
|
||||||
step="any"
|
step="any"
|
||||||
placeholder="0.00"
|
|
||||||
className="h-8 text-sm text-right"
|
className="h-8 text-sm text-right"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="col-span-1 flex items-center justify-end h-8">
|
<div className="col-span-1 flex items-center justify-end h-8">
|
||||||
<span className="text-sm tabular-nums">
|
<span className="text-sm tabular-nums">{formatCurrency(lineTotal, currency)}</span>
|
||||||
{lineTotal.toLocaleString('en-US', {
|
|
||||||
minimumFractionDigits: 2,
|
|
||||||
maximumFractionDigits: 2,
|
|
||||||
})}
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
<div className="col-span-1 flex items-center justify-end h-8">
|
<div className="col-span-1 flex items-center justify-end h-8">
|
||||||
<Button
|
<Button
|
||||||
@@ -120,13 +121,7 @@ export function InvoiceLineItems({ name = 'lineItems' }: InvoiceLineItemsProps)
|
|||||||
</Button>
|
</Button>
|
||||||
{fields.length > 0 && (
|
{fields.length > 0 && (
|
||||||
<div className="text-sm font-medium">
|
<div className="text-sm font-medium">
|
||||||
Subtotal:{' '}
|
Subtotal: <span className="tabular-nums">{formatCurrency(subtotal, currency)}</span>
|
||||||
<span className="tabular-nums">
|
|
||||||
{subtotal.toLocaleString('en-US', {
|
|
||||||
minimumFractionDigits: 2,
|
|
||||||
maximumFractionDigits: 2,
|
|
||||||
})}
|
|
||||||
</span>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
66
src/components/shared/currency-input.tsx
Normal file
66
src/components/shared/currency-input.tsx
Normal 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';
|
||||||
48
src/components/shared/currency-select.tsx
Normal file
48
src/components/shared/currency-select.tsx
Normal 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
71
src/lib/utils/currency.ts
Normal 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();
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user