feat(uat-b1): ship Wave A-E of Bucket 1 audit findings

Wave A (Interest+EOI form quick wins):
- Auto-select yacht after inline-create from interest form
- EOI generate dialog: "View EOI" action toast
- Interest form berth picker: formatBerthRange compact label
- Remove "Generate EOI" button from Documents tab (clean removal)
- Interest auto-assign: only sales_agent/sales_manager auto-claim
  ownership on create (explicit role check via user_port_roles join)
- LinkedBerthRowItem dims: drop "D" suffix + "L × W" format
- ExternalEoiUploadDialog: prefillSignatories prop threaded from
  active EOI signers
- EOI signature progress on Overview milestone card footer

Wave B (a11y + i18n sweeps):
- aria-live on supplemental-info error state
- text-[10px] -> text-xs in client-pipeline-summary
- Currency formatter: locale default removed (Intl uses runtime)
- en-US/en-GB hardcoded toLocaleString swept across 13 components

Wave C (Primary berth always in EOI bundle):
- Service guard strengthened on update path
- Migration 0083 backfills historical primary rows

Wave D (Onboarding super_admin discoverability):
- /api/v1/admin/onboarding/status endpoint + shared service
- Topbar OnboardingBanner (super_admin, session-dismissible)
- OnboardingTile dashboard widget (rail group, self-hides at 100%)
- Celebration toast + invalidate of shared status on last tick

Wave E (Branded post-completion email idempotency):
- Verified handleDocumentCompleted already owns the email fan-out
- Added regression test for the polling path + idempotency

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-25 03:40:37 +02:00
parent 41737fa950
commit 14ae41d0fa
40 changed files with 835 additions and 70 deletions

View File

@@ -129,7 +129,7 @@ export function TemplateList() {
accessorKey: 'updatedAt',
header: 'Last Updated',
cell: ({ row }) =>
new Date(row.original.updatedAt).toLocaleDateString('en-GB', {
new Date(row.original.updatedAt).toLocaleDateString(undefined, {
day: '2-digit',
month: 'short',
year: 'numeric',
@@ -221,7 +221,7 @@ export function TemplateList() {
<span aria-hidden>·</span>
<span>
Updated{' '}
{new Date(original.updatedAt).toLocaleDateString('en-GB', {
{new Date(original.updatedAt).toLocaleDateString(undefined, {
day: '2-digit',
month: 'short',
year: 'numeric',

View File

@@ -0,0 +1,95 @@
'use client';
import { useState } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { X, Sparkles, ChevronRight } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { usePermissions } from '@/hooks/use-permissions';
import { useOnboardingStatus } from '@/hooks/use-onboarding-status';
import { cn } from '@/lib/utils';
const DISMISS_STORAGE_KEY = 'pn-crm.onboarding-banner-dismissed';
function getInitialDismissed(): boolean {
if (typeof window === 'undefined') return false;
return sessionStorage.getItem(DISMISS_STORAGE_KEY) === '1';
}
/**
* Topbar banner nudging super_admins to finish onboarding while the
* checklist is incomplete. Renders nothing for non-super-admin roles and
* disappears for everyone once the checklist hits 100%.
*
* Dismissible per browser session — flag stored in sessionStorage so it
* comes back on next sign-in (we want it visible until they actually
* finish, not just clicked-away forever).
*/
export function OnboardingBanner() {
const params = useParams<{ portSlug: string }>();
const portSlug = params?.portSlug ?? '';
const { isSuperAdmin } = usePermissions();
const { data, isLoading } = useOnboardingStatus({ enabled: isSuperAdmin });
const [dismissed, setDismissed] = useState(getInitialDismissed);
if (!isSuperAdmin || isLoading || !data) return null;
if (data.isComplete) return null;
if (dismissed) return null;
if (!portSlug) return null;
const next = data.nextStep;
return (
<div
className={cn(
'flex items-center justify-between gap-3 border-b border-amber-200 bg-amber-50 px-4 py-2 text-sm text-amber-900',
'dark:border-amber-900/40 dark:bg-amber-950/30 dark:text-amber-100',
)}
role="status"
>
<div className="flex min-w-0 items-center gap-2">
<Sparkles className="size-4 shrink-0" aria-hidden />
<span className="truncate">
<strong>Setup is {data.percent}% complete</strong>. {data.completed} of {data.total} steps
done.{' '}
{next ? (
<>
Next:{' '}
<Link
// eslint-disable-next-line @typescript-eslint/no-explicit-any
href={`/${portSlug}/admin/${next.href}` as any}
className="font-medium underline-offset-2 hover:underline"
>
{next.label}
</Link>
</>
) : null}
</span>
</div>
<div className="flex shrink-0 items-center gap-1">
<Button asChild size="sm" variant="ghost" className="h-7 px-2 text-xs">
<Link
// eslint-disable-next-line @typescript-eslint/no-explicit-any
href={`/${portSlug}/admin/onboarding` as any}
>
View checklist
<ChevronRight className="ml-0.5 size-3" aria-hidden />
</Link>
</Button>
<Button
type="button"
size="icon"
variant="ghost"
className="h-7 w-7"
aria-label="Dismiss onboarding banner"
onClick={() => {
sessionStorage.setItem(DISMISS_STORAGE_KEY, '1');
setDismissed(true);
}}
>
<X className="size-3.5" aria-hidden />
</Button>
</div>
</div>
);
}

View File

@@ -1,9 +1,11 @@
'use client';
import { useEffect, useState } from 'react';
import { useEffect, useRef, useState } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { Check, Circle, Loader2, ExternalLink } from 'lucide-react';
import { toast } from 'sonner';
import { useQueryClient } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
@@ -251,6 +253,25 @@ export function OnboardingChecklist() {
const completed = STEPS.filter((s) => stepDone(s.id)).length;
const percent = Math.round((completed / STEPS.length) * 100);
// Fire a celebration toast exactly once when the last item ticks. Both
// auto- and manual-driven completions trigger it. Guarded against
// refetch noise so reloading the page when already 100% doesn't re-fire.
const queryClient = useQueryClient();
const prevCompletedRef = useRef<number | null>(null);
useEffect(() => {
if (loading) return;
const prev = prevCompletedRef.current;
if (prev !== null && prev < STEPS.length && completed === STEPS.length) {
toast.success('🎉 Setup complete — every onboarding step is checked off.', {
duration: 6000,
});
// Invalidate the shared status query so the banner + tile collapse
// immediately instead of waiting for the 60s cache to expire.
queryClient.invalidateQueries({ queryKey: ['admin', 'onboarding-status'] });
}
prevCompletedRef.current = completed;
}, [completed, loading, queryClient]);
return (
<div className="mt-6 space-y-6">
<Card>

View File

@@ -96,7 +96,7 @@ export function StageStepper({
see the ladder ahead. The `xs` size variant hides this row to
keep the cramped table-cell footprint intact. */}
{size !== 'xs' ? (
<div className="flex w-full text-[10px] font-medium uppercase tracking-wide">
<div className="flex w-full text-xs font-medium uppercase tracking-wide">
{PIPELINE_STAGES.map((stage, i) => {
const isReached = i <= idx;
return (
@@ -104,7 +104,7 @@ export function StageStepper({
key={stage}
className={cn(
'flex-1 truncate text-center',
isReached ? 'text-foreground' : 'text-muted-foreground/60',
isReached ? 'text-foreground' : 'text-muted-foreground',
)}
>
{STAGE_SHORT_LABELS[stage]}
@@ -193,13 +193,11 @@ function HeroVariant({ clientId, portSlug }: { clientId: string; portSlug: strin
return (
<div className="space-y-2">
<div className="flex items-center gap-2 flex-wrap">
<span className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
<span className="text-xs font-semibold uppercase tracking-wide text-muted-foreground">
Sales pipeline
</span>
{activeCount > 1 ? (
<span className="text-[10px] font-medium text-muted-foreground">
· {activeCount} active
</span>
<span className="text-xs font-medium text-muted-foreground">· {activeCount} active</span>
) : null}
</div>

View File

@@ -30,8 +30,8 @@ function rangeLabel(range: DateRange): string {
year: 'numeric',
timeZone: 'UTC',
};
const from = new Date(`${range.from}T00:00:00.000Z`).toLocaleDateString('en-US', fmt);
const to = new Date(`${range.to}T00:00:00.000Z`).toLocaleDateString('en-US', fmt);
const from = new Date(`${range.from}T00:00:00.000Z`).toLocaleDateString(undefined, fmt);
const to = new Date(`${range.to}T00:00:00.000Z`).toLocaleDateString(undefined, fmt);
return `${from} ${to}`;
}
return PRESET_LABELS[range];

View File

@@ -32,7 +32,7 @@ function formatCustom(range: { from: string; to: string }): string {
const fmt: Intl.DateTimeFormatOptions = sameYear
? { month: 'short', day: 'numeric', timeZone: 'UTC' }
: { month: 'short', day: 'numeric', year: 'numeric', timeZone: 'UTC' };
return `${from.toLocaleDateString('en-US', fmt)} ${to.toLocaleDateString('en-US', fmt)}`;
return `${from.toLocaleDateString(undefined, fmt)} ${to.toLocaleDateString(undefined, fmt)}`;
}
/**

View File

@@ -0,0 +1,83 @@
'use client';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { ChevronRight, Sparkles } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Progress } from '@/components/ui/progress';
import { usePermissions } from '@/hooks/use-permissions';
import { useOnboardingStatus } from '@/hooks/use-onboarding-status';
/**
* Compact dashboard tile that surfaces onboarding progress for super_admins
* while the checklist is incomplete. Collapses (returns null) once setup is
* 100% complete so the dashboard doesn't stay cluttered after the org is
* past the initial onboarding phase. Non-super-admin users never see it.
*/
export function OnboardingTile() {
const params = useParams<{ portSlug: string }>();
const portSlug = params?.portSlug ?? '';
const { isSuperAdmin } = usePermissions();
const { data, isLoading } = useOnboardingStatus({ enabled: isSuperAdmin });
if (!isSuperAdmin) return null;
if (isLoading) {
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-sm">
<Sparkles className="size-4 text-brand-600" aria-hidden />
Setup checklist
</CardTitle>
</CardHeader>
<CardContent>
<Progress value={0} className="h-2" />
</CardContent>
</Card>
);
}
if (!data || data.isComplete) return null;
return (
<Card className="border-brand-200 bg-brand-50/30">
<CardHeader className="pb-2">
<CardTitle className="flex items-center gap-2 text-sm">
<Sparkles className="size-4 text-brand-600" aria-hidden />
Setup checklist
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<div className="space-y-1">
<Progress value={data.percent} className="h-2" />
<p className="text-xs text-muted-foreground">
{data.completed} of {data.total} steps complete ({data.percent}%)
</p>
</div>
{data.nextStep ? (
<div className="rounded-md border border-dashed border-brand-200 bg-white/60 p-2">
<p className="text-[10px] font-semibold uppercase tracking-wide text-brand-700">
Next step
</p>
<p className="mt-0.5 text-xs text-foreground">{data.nextStep.label}</p>
</div>
) : null}
{portSlug ? (
<Button asChild size="sm" variant="outline" className="w-full">
<Link
href={
(data.nextStep
? `/${portSlug}/admin/${data.nextStep.href}`
: `/${portSlug}/admin/onboarding`) as never
}
>
{data.nextStep ? 'Continue setup' : 'Open checklist'}
<ChevronRight className="ml-1 size-3" aria-hidden />
</Link>
</Button>
) : null}
</CardContent>
</Card>
);
}

View File

@@ -15,6 +15,7 @@ import dynamic from 'next/dynamic';
import { ActiveDealsTile } from './active-deals-tile';
import { ActivityFeed } from './activity-feed';
import { OnboardingTile } from './onboarding-tile';
import { BerthHeatWidget } from './berth-heat-widget';
import { ClientsByCountryWidget } from './clients-by-country-widget';
import { HotDealsCard } from './hot-deals-card';
@@ -105,6 +106,19 @@ export interface DashboardWidget {
}
export const DASHBOARD_WIDGETS: readonly DashboardWidget[] = [
// ── Onboarding (rail, super_admin-only) ─────────────────────────────
// Self-collapses when the checklist hits 100% and self-hides for
// non-super-admin users so most reps never see this tile at all.
{
id: 'onboarding_checklist',
label: 'Setup checklist',
description:
'Progress + next-step nudge while the org is still going through Documenso / branding / users setup. Hidden once 100% complete.',
render: () => <OnboardingTile />,
group: 'rail',
defaultVisible: true,
},
// ── KPI tiles (rail) ────────────────────────────────────────────────
// Off by default - keep the existing dashboard layout unchanged for
// users on first paint after the upgrade; reps can flip them on from

View File

@@ -277,7 +277,7 @@ export function DocumentDetail({ documentId, portSlug }: DocumentDetailProps) {
<PageHeader
eyebrow={doc.documentType.replace(/_/g, ' ')}
title={doc.title}
description={`Created ${new Date(doc.createdAt).toLocaleDateString('en-GB')}`}
description={`Created ${new Date(doc.createdAt).toLocaleDateString(undefined)}`}
kpiLine={
<>
<StatusPill status={STATUS_PILL_MAP[doc.status] ?? 'pending'} withDot>

View File

@@ -109,7 +109,7 @@ function DocRow({ doc, onDelete, onSend, onPreview }: DocRowProps) {
</td>
<td className="px-4 py-3 text-muted-foreground">{signerProgress}</td>
<td className="px-4 py-3 text-muted-foreground">
{new Date(doc.createdAt).toLocaleDateString('en-GB')}
{new Date(doc.createdAt).toLocaleDateString(undefined)}
</td>
<td className="px-4 py-3 text-right">
<DropdownMenu>

View File

@@ -389,7 +389,7 @@ function FlatFolderListing({
{totalSigners > 0 ? `${signedCount}/${totalSigners} signed` : '-'}
</span>
<span className="text-xs text-muted-foreground">
{new Date(doc.createdAt).toLocaleDateString('en-GB')}
{new Date(doc.createdAt).toLocaleDateString(undefined)}
</span>
</div>
{expanded && doc.signers && doc.signers.length > 0 ? (

View File

@@ -116,7 +116,7 @@ export function EntityFolderView({ portSlug, entityType, entityId }: Props) {
) : null}
</button>
<div className="flex items-center gap-2 text-xs text-muted-foreground tabular-nums shrink-0">
<span>{new Date(f.createdAt).toLocaleDateString('en-GB')}</span>
<span>{new Date(f.createdAt).toLocaleDateString(undefined)}</span>
{signedFromDocumentId ? (
<Button
variant="ghost"

View File

@@ -2,6 +2,7 @@
import { useEffect, useMemo, useState } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { AlertTriangle, ExternalLink, FileSignature, Pencil } from 'lucide-react';
@@ -174,6 +175,7 @@ export function EoiGenerateDialog({
}: EoiGenerateDialogProps) {
const queryClient = useQueryClient();
const portSlug = useUIStore((s) => s.currentPortSlug);
const router = useRouter();
const [isGenerating, setIsGenerating] = useState(false);
const [error, setError] = useState<string | null>(null);
const [selectedTemplate, setSelectedTemplate] = useState<string>(DOCUMENSO_TEMPLATE_VALUE);
@@ -579,6 +581,14 @@ export function EoiGenerateDialog({
]);
toast.success(
isDocumenso ? 'EOI generated and sent for signature.' : 'EOI generated. Ready to send.',
portSlug && interestId
? {
action: {
label: 'View EOI',
onClick: () => router.push(`/${portSlug}/interests/${interestId}?tab=eoi` as never),
},
}
: undefined,
);
onOpenChange(false);
} catch (err) {

View File

@@ -107,7 +107,7 @@ export function HubRootView({ portSlug }: Props) {
{f.filename}
</button>
<span className="text-xs text-muted-foreground tabular-nums">
{new Date(f.createdAt).toLocaleDateString('en-GB')}
{new Date(f.createdAt).toLocaleDateString(undefined)}
</span>
</li>
))}

View File

@@ -100,7 +100,7 @@ export function SigningDetailsDialog({ documentId, open, onOpenChange }: Props)
<div className="flex items-center gap-2">
{s.signedAt ? (
<span className="tabular-nums text-muted-foreground">
{new Date(s.signedAt).toLocaleDateString('en-GB')}
{new Date(s.signedAt).toLocaleDateString(undefined)}
</span>
) : null}
<StatusPill status={mapSignerStatus(s.status)}>{s.status}</StatusPill>

View File

@@ -84,7 +84,7 @@ export function getExpenseColumns({
enableSorting: false,
cell: ({ row }) => (
<span className="font-medium tabular-nums">
{Number(row.original.amount).toLocaleString('en-US', {
{Number(row.original.amount).toLocaleString(undefined, {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})}{' '}
@@ -100,7 +100,7 @@ export function getExpenseColumns({
row.original.amountUsd ? (
<span className="text-sm text-muted-foreground tabular-nums">
$
{Number(row.original.amountUsd).toLocaleString('en-US', {
{Number(row.original.amountUsd).toLocaleString(undefined, {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})}

View File

@@ -188,7 +188,7 @@ export function ExpenseDetail({ expenseId, onEdit, onArchived }: ExpenseDetailPr
</CardHeader>
<CardContent>
<p className="text-2xl font-bold tabular-nums">
{Number(expense.amount).toLocaleString('en-US', {
{Number(expense.amount).toLocaleString(undefined, {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})}{' '}
@@ -197,7 +197,7 @@ export function ExpenseDetail({ expenseId, onEdit, onArchived }: ExpenseDetailPr
{expense.amountUsd && expense.currency !== 'USD' && (
<p className="text-sm text-muted-foreground mt-1">
$
{Number(expense.amountUsd).toLocaleString('en-US', {
{Number(expense.amountUsd).toLocaleString(undefined, {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})}{' '}

View File

@@ -51,9 +51,19 @@ interface Props {
onOpenChange: (next: boolean) => void;
interestId: string;
onSuccess?: () => void;
/** When supplied, used as the initial signatory seed (typically derived
* from the active Documenso EOI's signers). Falls through to the
* client-only seed when omitted or empty. */
prefillSignatories?: SignatoryRow[];
}
export function ExternalEoiUploadDialog({ open, onOpenChange, interestId, onSuccess }: Props) {
export function ExternalEoiUploadDialog({
open,
onOpenChange,
interestId,
onSuccess,
prefillSignatories,
}: Props) {
const qc = useQueryClient();
const [file, setFile] = useState<File | null>(null);
const [title, setTitle] = useState('');
@@ -88,6 +98,7 @@ export function ExternalEoiUploadDialog({ open, onOpenChange, interestId, onSucc
// explicit override takes over.
const signatories: SignatoryRow[] = useMemo(() => {
if (signatoriesOverride !== null) return signatoriesOverride;
if (prefillSignatories && prefillSignatories.length > 0) return prefillSignatories;
if (!interestData?.data) return [];
return [
{
@@ -96,7 +107,7 @@ export function ExternalEoiUploadDialog({ open, onOpenChange, interestId, onSucc
role: 'client' as const,
},
];
}, [signatoriesOverride, interestData]);
}, [signatoriesOverride, prefillSignatories, interestData]);
const { data: berthsData } = useQuery<{ data: Array<{ mooringNumber: string | null }> }>({
queryKey: ['interests', interestId, 'berths'],
queryFn: () =>

View File

@@ -4,9 +4,7 @@ import { useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { FileSignature } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { DocumentList } from '@/components/documents/document-list';
import { EoiGenerateDialog } from '@/components/documents/eoi-generate-dialog';
import { FileGrid, type FileRow } from '@/components/files/file-grid';
import { FileUploadZone } from '@/components/files/file-upload-zone';
import { FilePreviewDialog } from '@/components/files/file-preview-dialog';
@@ -35,7 +33,6 @@ interface InterestData {
*/
export function InterestDocumentsTab({ interestId }: InterestDocumentsTabProps) {
const queryClient = useQueryClient();
const [eoiDialogOpen, setEoiDialogOpen] = useState(false);
const [previewFile, setPreviewFile] = useState<FileRow | null>(null);
const { confirm, dialog: confirmDialog } = useConfirmation();
@@ -111,9 +108,6 @@ export function InterestDocumentsTab({ interestId }: InterestDocumentsTabProps)
<section className="space-y-4">
<div className="flex items-center justify-between">
<h3 className="text-sm font-medium text-muted-foreground">Signature documents</h3>
<Button size="sm" variant="outline" onClick={() => setEoiDialogOpen(true)}>
Generate EOI
</Button>
</div>
<DocumentList
@@ -126,12 +120,9 @@ export function InterestDocumentsTab({ interestId }: InterestDocumentsTabProps)
<div className="space-y-1">
<p className="text-sm font-medium text-foreground">No documents yet</p>
<p className="text-xs text-muted-foreground">
Generate the EOI to send it for signing in one click.
Generate the EOI from the Overview tab to send it for signing in one click.
</p>
</div>
<Button size="sm" onClick={() => setEoiDialogOpen(true)}>
Generate EOI
</Button>
</div>
}
/>
@@ -202,13 +193,6 @@ export function InterestDocumentsTab({ interestId }: InterestDocumentsTabProps)
)}
</section>
<EoiGenerateDialog
interestId={interestId}
clientId={interest?.clientId ?? null}
open={eoiDialogOpen}
onOpenChange={setEoiDialogOpen}
/>
<FilePreviewDialog
open={!!previewFile}
onOpenChange={(open) => !open && setPreviewFile(null)}

View File

@@ -126,6 +126,37 @@ export function InterestEoiTab({ interestId, clientId }: InterestEoiTabProps) {
const activeDoc = useMemo(() => docs.find((d) => ACTIVE_STATUSES.has(d.status)) ?? null, [docs]);
const completedDocs = useMemo(() => docs.filter((d) => !ACTIVE_STATUSES.has(d.status)), [docs]);
// Pulled at the parent so we can thread the active EOI's signers into the
// ExternalEoiUploadDialog as a prefill seed. ActiveEoiCard hits the same
// query key — react-query dedupes the actual fetch.
const { data: activeSignersRes } = useQuery<{ data: DocumentSigner[] }>({
queryKey: ['documents', activeDoc?.id, 'signers'],
queryFn: () =>
apiFetch<{ data: DocumentSigner[] }>(`/api/v1/documents/${activeDoc!.id}/signers`),
enabled: !!activeDoc,
staleTime: 30_000,
});
const externalUploadPrefill = useMemo(() => {
const rows = activeSignersRes?.data ?? [];
if (rows.length === 0) return undefined;
const ROLE_MAP: Record<string, 'client' | 'developer' | 'rep' | 'witness' | 'cc'> = {
client: 'client',
developer: 'developer',
approver: 'developer',
rep: 'rep',
witness: 'witness',
cc: 'cc',
viewer: 'cc',
other: 'witness',
};
return rows.map((s) => ({
name: s.signerName,
email: s.signerEmail,
role: ROLE_MAP[(s.signerRole ?? '').toLowerCase()] ?? ('witness' as const),
}));
}, [activeSignersRes]);
return (
<div className="space-y-5">
{docsLoading ? (
@@ -201,6 +232,7 @@ export function InterestEoiTab({ interestId, clientId }: InterestEoiTabProps) {
open={uploadSignedOpen}
onOpenChange={setUploadSignedOpen}
interestId={interestId}
prefillSignatories={externalUploadPrefill}
/>
{/* Phase 4 parity - same upload-PDF + place-fields wizard as

View File

@@ -47,6 +47,7 @@ import { YachtForm } from '@/components/yachts/yacht-form';
import { YachtPicker } from '@/components/yachts/yacht-picker';
import { apiFetch } from '@/lib/api/client';
import { useEntityOptions } from '@/hooks/use-entity-options';
import { formatBerthRange } from '@/lib/templates/berth-range';
import type { z } from 'zod';
import { createInterestSchema, type CreateInterestInput } from '@/lib/validators/interests';
import { PIPELINE_STAGES, STAGE_LABELS, LEAD_CATEGORIES, SOURCES } from '@/lib/constants';
@@ -438,11 +439,24 @@ export function InterestForm({ open, onOpenChange, defaultClientId, interest }:
>
<span className="truncate">
{selectedBerthId
? `${selectedBerth?.label ?? interest?.berthMooringNumber ?? selectedBerthId}${
additionalBerthIds.length > 0
? ` + ${additionalBerthIds.length} more`
: ''
}`
? (() => {
const primaryLabel =
selectedBerth?.label ??
interest?.berthMooringNumber ??
selectedBerthId;
const additionalLabels = additionalBerthIds
.map((id) => berthOptions.find((b) => b.value === id)?.label)
.filter((label): label is string => Boolean(label));
const allLabels = [primaryLabel, ...additionalLabels];
const range = formatBerthRange(allLabels);
// Cap at 5 segments after range collapse so "A1-A3, B5, C2, D7, E4 +N more"
// doesn't overflow the trigger.
const segments = range ? range.split(', ') : [];
if (segments.length <= 5) return range || primaryLabel;
const head = segments.slice(0, 5).join(', ');
const overflow = segments.length - 5;
return `${head} +${overflow} more`;
})()
: 'Select berths…'}
</span>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" aria-hidden />
@@ -791,6 +805,7 @@ export function InterestForm({ open, onOpenChange, defaultClientId, interest }:
open={createYachtOpen}
onOpenChange={setCreateYachtOpen}
initialOwner={{ type: 'client', id: selectedClientId }}
onCreated={(y) => setValue('yachtId', y.id, { shouldDirty: true })}
/>
)}
</Sheet>

View File

@@ -3,7 +3,7 @@
import Link from 'next/link';
import { useParams } from 'next/navigation';
import { format, formatDistanceToNowStrict } from 'date-fns';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useState } from 'react';
import { Anchor, CheckCircle2, Circle, FileSignature, Send, Wallet } from 'lucide-react';
@@ -31,6 +31,7 @@ import { RemindersInline } from '@/components/reminders/reminders-inline';
import { BerthRecommenderPanel } from '@/components/interests/berth-recommender-panel';
import { LinkedBerthsList } from '@/components/interests/linked-berths-list';
import { EoiGenerateDialog } from '@/components/documents/eoi-generate-dialog';
import { SigningProgress } from '@/components/documents/signing-progress';
// Shared parser for the interest's stringly-typed numeric columns (Drizzle
// returns Postgres numeric as string). Used by both the Overview milestone
@@ -627,6 +628,76 @@ function FutureMilestones({
);
}
/**
* Compact per-signer progress widget for the Overview tab's EOI milestone
* card. Mounts inside the milestone footer when the EOI is sent but not
* yet fully signed, so reps see who's signed at a glance without leaving
* Overview. Heavy lifting (resend, void, etc.) stays on the EOI tab — a
* "View EOI" link below the widget routes the rep there.
*/
function EoiMilestoneActiveProgress({
interestId,
portSlug,
}: {
interestId: string;
portSlug: string;
}) {
const { data: docsRes } = useQuery<{
data: Array<{ id: string; status: string }>;
}>({
queryKey: ['documents', { interestId, documentType: 'eoi' }],
queryFn: () =>
apiFetch<{ data: Array<{ id: string; status: string }> }>(
`/api/v1/documents?interestId=${interestId}&documentType=eoi`,
),
staleTime: 30_000,
});
const activeDoc = (docsRes?.data ?? []).find(
(d) => d.status === 'sent' || d.status === 'partially_signed' || d.status === 'signed',
);
const { data: signersRes } = useQuery<{
data: Array<{
id: string;
signerName: string;
signerEmail: string;
signerRole: string;
signingOrder: number;
status: string;
signedAt?: string | null;
invitedAt?: string | null;
openedAt?: string | null;
lastReminderSentAt?: string | null;
signingUrl?: string | null;
}>;
}>({
queryKey: ['documents', activeDoc?.id, 'signers'],
queryFn: () =>
apiFetch<{ data: Array<never> }>(`/api/v1/documents/${activeDoc!.id}/signers`) as never,
enabled: !!activeDoc,
staleTime: 30_000,
});
if (!activeDoc) return null;
const signers = signersRes?.data ?? [];
if (signers.length === 0) return null;
return (
<div className="space-y-2">
<SigningProgress documentId={activeDoc.id} signers={signers} />
<div className="flex justify-end">
<Button asChild type="button" size="sm" variant="ghost" className="h-7 text-xs">
<Link
// eslint-disable-next-line @typescript-eslint/no-explicit-any
href={`/${portSlug}/interests/${interestId}?tab=eoi` as any}
>
View EOI
</Link>
</Button>
</div>
</div>
);
}
function OverviewTab({
interestId,
interest,
@@ -863,6 +934,8 @@ function OverviewTab({
</Link>
</Button>
</div>
) : eoiPhase === 'current' && interest.dateEoiSent && !interest.dateEoiSigned ? (
<EoiMilestoneActiveProgress interestId={interestId} portSlug={portSlug} />
) : null,
pastSummary: interest.dateEoiSigned ? (
`Signed ${formatDate(interest.dateEoiSigned)}`

View File

@@ -117,11 +117,12 @@ function formatDimensions(
};
const l = toNum(length);
const w = toNum(width);
const d = toNum(draft);
if (l !== null) parts.push(`${l.toFixed(1)}ft L`);
if (w !== null) parts.push(`${w.toFixed(1)}ft W`);
if (d !== null) parts.push(`${d.toFixed(1)}ft D`);
return parts.length > 0 ? parts.join(' · ') : null;
// Draft intentionally omitted from the inline row strip per UAT 2026-05-24
// — opaque to sales reps; still visible on the berth detail page.
void toNum(draft);
if (l !== null) parts.push(`${l.toFixed(1)} ft`);
if (w !== null) parts.push(`${w.toFixed(1)} ft`);
return parts.length > 0 ? parts.join(' × ') : null;
}
const SPECIFIC_CONSEQUENCE_ON =

View File

@@ -78,7 +78,7 @@ export function getInvoiceColumns({
enableSorting: false,
cell: ({ row }) => (
<span className="font-medium tabular-nums">
{Number(row.original.total).toLocaleString('en-US', {
{Number(row.original.total).toLocaleString(undefined, {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})}{' '}

View File

@@ -230,7 +230,7 @@ export function InvoiceDetail({ invoiceId }: InvoiceDetailProps) {
</CardHeader>
<CardContent>
<p className="text-2xl font-bold tabular-nums">
{Number(invoice.total).toLocaleString('en-US', {
{Number(invoice.total).toLocaleString(undefined, {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})}{' '}

View File

@@ -65,7 +65,7 @@ export function ExportDashboardPdfButton({
} = {}) {
const { can } = usePermissions();
const [open, setOpen] = useState(false);
const [title, setTitle] = useState(`Report - ${new Date().toLocaleDateString('en-GB')}`);
const [title, setTitle] = useState(`Report - ${new Date().toLocaleDateString(undefined)}`);
const [selected, setSelected] = useState<PdfDashboardWidgetId[]>(
PDF_DASHBOARD_WIDGETS.map((w) => w.id),
);

View File

@@ -52,7 +52,7 @@ export function ExportListPdfButton({ kind, buttonLabel = 'Export PDF', defaultT
const [open, setOpen] = useState(false);
const [title, setTitle] = useState(
defaultTitle ??
`${KIND_LABEL[kind].charAt(0).toUpperCase() + KIND_LABEL[kind].slice(1)} report - ${new Date().toLocaleDateString('en-GB')}`,
`${KIND_LABEL[kind].charAt(0).toUpperCase() + KIND_LABEL[kind].slice(1)} report - ${new Date().toLocaleDateString(undefined)}`,
);
const [includeArchived, setIncludeArchived] = useState(false);
const [loading, setLoading] = useState(false);

View File

@@ -276,7 +276,7 @@ export function ReservationDetail({ reservationId, portSlug }: ReservationDetail
<PageHeader
eyebrow="Berth reservation"
title={`Reservation #${res.id.slice(0, 8)}`}
description={`${res.tenureType.replace(/_/g, ' ')} · ${new Date(res.startDate).toLocaleDateString('en-GB')}${res.endDate ? `${new Date(res.endDate).toLocaleDateString('en-GB')}` : ''}`}
description={`${res.tenureType.replace(/_/g, ' ')} · ${new Date(res.startDate).toLocaleDateString(undefined)}${res.endDate ? `${new Date(res.endDate).toLocaleDateString(undefined)}` : ''}`}
kpiLine={
<>
<StatusPill status={RESERVATION_PILL[res.status] ?? 'pending'} withDot>

View File

@@ -124,7 +124,7 @@ function formatTooltipLabel(value: unknown): string {
const datePart = value.slice(0, 10); // "YYYY-MM-DD"
const d = new Date(`${datePart}T00:00:00Z`);
if (isNaN(d.getTime())) return datePart;
return d.toLocaleDateString('en-US', {
return d.toLocaleDateString(undefined, {
year: 'numeric',
month: 'short',
day: 'numeric',