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

@@ -11,6 +11,7 @@ import { SocketProvider } from '@/providers/socket-provider';
import { PortProvider } from '@/providers/port-provider';
import { PermissionsProvider } from '@/providers/permissions-provider';
import { AppShell } from '@/components/layout/app-shell';
import { OnboardingBanner } from '@/components/admin/onboarding-banner';
import { DevModeBanner } from '@/components/shared/dev-mode-banner';
import { RealtimeToasts } from '@/components/shared/realtime-toasts';
import { WebVitalsReporter } from '@/components/shared/web-vitals-reporter';
@@ -84,6 +85,7 @@ export default async function DashboardLayout({ children }: { children: React.Re
rerouted. Production hides itself (env.ts forbids the
flag in prod) so the banner is dev/staging-only. */}
<DevModeBanner />
<OnboardingBanner />
{/* #26: AppShell mounts ONE responsive tree (desktop OR
* mobile) per render - never both - so pages don't pay the
* double-state, double-fetch, double-Tabs-provider tax. */}

View File

@@ -0,0 +1,24 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { resolveOnboardingStatus } from '@/lib/services/onboarding.service';
/**
* GET /api/v1/admin/onboarding/status — returns the resolved checklist
* state for the caller's port. Drives the topbar discoverability banner
* + dashboard onboarding tile + the admin checklist page summary.
*
* Permission-gated on `admin.manage_settings` to mirror the rest of the
* admin surface; non-admin users never see the banner / tile anyway.
*/
export const GET = withAuth(
withPermission('admin', 'manage_settings', async (_req, ctx) => {
try {
const status = await resolveOnboardingStatus(ctx.portId);
return NextResponse.json({ data: status });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -151,7 +151,7 @@ export default function SupplementalInfoPage({ params }: PageProps) {
if (error) {
return (
<BrandedAuthShell>
<div className="text-center space-y-2 py-6">
<div role="alert" aria-live="assertive" className="text-center space-y-2 py-6">
<p className="text-sm text-muted-foreground">{error}</p>
</div>
</BrandedAuthShell>

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',

View File

@@ -0,0 +1,44 @@
'use client';
import { useQuery } from '@tanstack/react-query';
import { apiFetch } from '@/lib/api/client';
export interface OnboardingStatusStep {
id: string;
href: string;
label: string;
description: string;
done: boolean;
auto: boolean;
}
export interface OnboardingStatusPayload {
steps: OnboardingStatusStep[];
completed: number;
total: number;
percent: number;
isComplete: boolean;
nextStep: { id: string; label: string; href: string } | null;
}
/**
* Shared onboarding-status query. Drives the topbar banner, dashboard tile,
* and the admin checklist summary. Cached for 60s so all three surfaces
* share a single fetch on first paint.
*
* Pass `enabled=false` to skip the network call (e.g. when the current
* user isn't a super_admin and the surface won't render anyway).
*/
export function useOnboardingStatus(opts: { enabled?: boolean } = {}) {
return useQuery<OnboardingStatusPayload>({
queryKey: ['admin', 'onboarding-status'],
queryFn: () =>
apiFetch<{ data: OnboardingStatusPayload }>('/api/v1/admin/onboarding/status').then(
(r) => r.data,
),
staleTime: 60_000,
enabled: opts.enabled ?? true,
retry: false,
});
}

View File

@@ -0,0 +1,7 @@
-- Backfill: ensure every primary interest_berths row carries is_in_eoi_bundle=true.
-- The service layer now enforces this invariant on insert + update, but
-- historical rows from before the guard could still violate it.
UPDATE interest_berths
SET is_in_eoi_bundle = TRUE
WHERE is_primary = TRUE
AND is_in_eoi_bundle = FALSE;

View File

@@ -293,12 +293,23 @@ export async function upsertInterestBerthTx(
if (opts.isInEoiBundle !== undefined) setForUpdate.isInEoiBundle = opts.isInEoiBundle;
// Invariant: primary berth is ALWAYS in the EOI bundle. The primary IS
// the canonical "berth for this deal" - excluding it from the signed
// envelope is semantically nonsense. If the caller is setting the row
// to primary OR opting to take out of the EOI bundle, force the bundle
// flag back on whenever the row is also (about to be) primary.
// envelope is semantically nonsense.
// • If the caller is setting the row to primary + opting out of bundle,
// force the bundle flag back on.
// • If the existing row is already primary and the caller is toggling
// the bundle off without changing primary, also force it back on.
const willBePrimary = opts.isPrimary === true;
if (willBePrimary && opts.isInEoiBundle === false) {
setForUpdate.isInEoiBundle = true;
} else if (opts.isInEoiBundle === false && opts.isPrimary !== false) {
const existing = await tx
.select({ isPrimary: interestBerths.isPrimary })
.from(interestBerths)
.where(and(eq(interestBerths.interestId, interestId), eq(interestBerths.berthId, berthId)))
.limit(1);
if (existing[0]?.isPrimary) {
setForUpdate.isInEoiBundle = true;
}
}
if (opts.addedBy !== undefined) setForUpdate.addedBy = opts.addedBy;
if (opts.notes !== undefined) setForUpdate.notes = opts.notes;

View File

@@ -10,7 +10,7 @@ import { berthReservations } from '@/lib/db/schema/reservations';
import { yachts } from '@/lib/db/schema/yachts';
import { companyMemberships } from '@/lib/db/schema/companies';
import { tags } from '@/lib/db/schema/system';
import { userProfiles } from '@/lib/db/schema/users';
import { userProfiles, userPortRoles, roles } from '@/lib/db/schema/users';
import { createAuditLog, type AuditMeta } from '@/lib/audit';
import { activeInterestsWhere } from '@/lib/services/active-interest';
import { getPortReminderConfig } from '@/lib/services/port-config';
@@ -755,14 +755,25 @@ export async function createInterest(portId: string, data: CreateInterestInput,
if (v?.userId) {
resolvedAssignedTo = v.userId;
} else {
// Tier 3: auto-assign to creator unless they're a super-admin.
// Tier 3: auto-assign to creator only when their role is a working
// sales rep — super_admin / director / residential_partner / viewer
// intentionally skip (they create on behalf of others or shouldn't
// own interests at all).
const AUTO_ASSIGN_ROLES = new Set(['sales_agent', 'sales_manager']);
const [profile] = await db
.select({ isSuperAdmin: userProfiles.isSuperAdmin })
.from(userProfiles)
.where(eq(userProfiles.userId, meta.userId))
.limit(1);
if (profile && !profile.isSuperAdmin) {
resolvedAssignedTo = meta.userId;
const userRoles = await db
.select({ name: roles.name })
.from(userPortRoles)
.innerJoin(roles, eq(userPortRoles.roleId, roles.id))
.where(and(eq(userPortRoles.userId, meta.userId), eq(userPortRoles.portId, portId)));
if (userRoles.some((r) => AUTO_ASSIGN_ROLES.has(r.name))) {
resolvedAssignedTo = meta.userId;
}
}
}
}

View File

@@ -0,0 +1,174 @@
/**
* Server-side onboarding status resolver. Shared by the admin checklist
* page, the topbar discoverability banner, and the dashboard onboarding
* tile so all three surfaces always agree on what's "done."
*
* Steps + auto-check rules live here (single source of truth); the UI
* surfaces consume the resolved status via the `/api/v1/admin/onboarding/status`
* endpoint.
*/
import { and, eq, isNull, or } from 'drizzle-orm';
import { db } from '@/lib/db';
import { systemSettings } from '@/lib/db/schema/system';
import { resolveForAdminAPI } from '@/lib/settings/resolver';
export interface OnboardingStep {
id: string;
href: string;
label: string;
description: string;
autoCheckSettingKey?: string;
autoCheckSettingKeysAll?: readonly string[];
/** When set, the step is marked done when the named list endpoint returns
* at least one row. The endpoint URL is read by the client only;
* server-side resolver treats these as manual-only. */
autoCheckListEndpoint?: string;
}
export const ONBOARDING_STEPS: readonly OnboardingStep[] = [
{
id: 'branding',
href: 'branding',
label: 'Set port name, logo, primary colour',
description: 'Branding flows into the navbar, emails, EOI PDFs, and the public auth shell.',
autoCheckSettingKey: 'branding_logo_url',
},
{
id: 'email',
href: 'email',
label: 'Configure outgoing email',
description:
'From-address, signature, footer, plus per-port SMTP overrides if you dont use the global account.',
autoCheckSettingKey: 'smtp_host_override',
},
{
id: 'documenso',
href: 'documenso',
label: 'Connect Documenso for EOIs',
description:
'API credentials, the EOI template id, plus the developer + approver identity that signs every EOI.',
autoCheckSettingKeysAll: [
'documenso_api_url_override',
'documenso_developer_email',
'documenso_approver_email',
'documenso_eoi_template_id',
],
},
{
id: 'settings',
href: 'settings',
label: 'Tune business rules + recommender weights',
description:
'Pipeline weights, net-10 discount, berth recommender knobs (heat weights, fall-through policy).',
autoCheckSettingKey: 'heat_weight_recency',
},
{
id: 'roles',
href: 'roles',
label: 'Create roles & assign users',
description: 'Per-port roles inherit from system roles; override permissions here.',
autoCheckListEndpoint: '/api/v1/admin/roles',
},
{
id: 'users',
href: 'users',
label: 'Invite the rest of the team',
description:
'Invite users, assign roles, optionally grant residential access. Track pending vs accepted.',
autoCheckListEndpoint: '/api/v1/admin/users',
},
{
id: 'tags',
href: 'tags',
label: 'Define starter tags',
description: 'Color-coded labels used across clients, yachts, companies, and interests.',
autoCheckListEndpoint: '/api/v1/tags/options',
},
{
id: 'storage',
href: 'storage',
label: 'Configure storage backend',
description:
'Verify S3/filesystem and run a test connection before going live so PDFs and avatars persist correctly.',
autoCheckSettingKey: 'storage_backend',
},
{
id: 'forms',
href: 'forms',
label: 'Wire the website intake forms',
description:
'Inquiry forms on the marketing site dual-write into the CRM via /api/public/website-inquiries. Manually mark complete when verified.',
},
];
export interface OnboardingStatus {
steps: Array<OnboardingStep & { done: boolean; auto: boolean }>;
completed: number;
total: number;
percent: number;
isComplete: boolean;
/** The next undone step the admin should tackle. Null when complete. */
nextStep: (OnboardingStep & { done: false }) | null;
}
/**
* Resolves onboarding status for the given port. Auto-checks read the full
* setting chain (port → global → env → default) via `resolveSettings`;
* list-endpoint checks are treated as not-auto-resolvable server-side and
* fall back to the manual-checkbox state in `onboarding_manual_status`.
*/
export async function resolveOnboardingStatus(portId: string): Promise<OnboardingStatus> {
const keys = new Set<string>();
for (const s of ONBOARDING_STEPS) {
if (s.autoCheckSettingKey) keys.add(s.autoCheckSettingKey);
if (s.autoCheckSettingKeysAll) for (const k of s.autoCheckSettingKeysAll) keys.add(k);
}
const resolved =
keys.size > 0
? await resolveForAdminAPI(Array.from(keys), portId)
: new Map<string, { isSet: boolean }>();
// Manual-checkbox state lives in a JSON blob row outside the registry.
// Same lookup pattern as the admin page: port-scoped row first, fall
// back to a global one when the port hasn't written its own.
const manualRow = await db
.select({ value: systemSettings.value })
.from(systemSettings)
.where(
and(
eq(systemSettings.key, 'onboarding_manual_status'),
or(eq(systemSettings.portId, portId), isNull(systemSettings.portId)),
),
)
.limit(1);
const manual = (manualRow[0]?.value ?? {}) as Record<string, boolean>;
let firstUndone: (OnboardingStep & { done: false }) | null = null;
const steps = ONBOARDING_STEPS.map((step) => {
let autoDone = false;
if (step.autoCheckSettingKey) {
autoDone = Boolean(resolved.get(step.autoCheckSettingKey)?.isSet);
} else if (step.autoCheckSettingKeysAll) {
autoDone = step.autoCheckSettingKeysAll.every((k) => Boolean(resolved.get(k)?.isSet));
}
const manualDone = Boolean(manual[step.id]);
const done = autoDone || manualDone;
if (!done && !firstUndone) firstUndone = { ...step, done: false };
return { ...step, done, auto: autoDone };
});
const completed = steps.filter((s) => s.done).length;
const total = steps.length;
const percent = total > 0 ? Math.round((completed / total) * 100) : 0;
return {
steps,
completed,
total,
percent,
isComplete: completed === total,
nextStep: firstUndone,
};
}

View File

@@ -37,10 +37,10 @@ const SUPPORTED_SET: ReadonlySet<string> = new Set(SUPPORTED_CURRENCIES.map((c)
* 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.
* When `options.locale` is omitted the runtime's default locale is used
* (Intl falls back to the browser/Node default). Pass `locale` explicitly
* to force a specific rendering. Unknown ISO codes fall through to Intl
* unchanged so the function never throws on legacy data.
*/
export function formatCurrency(
amount: number | string | null | undefined,
@@ -60,7 +60,7 @@ export function formatCurrency(
// `toLocaleString` throws "Computed minimumFractionDigits is larger
// than maximumFractionDigits". The same defensive clamp protects
// Intl.NumberFormat too.
const { locale = 'en-US', maxFractionDigits = 2 } = options;
const { locale, maxFractionDigits = 2 } = options;
const minFractionDigits = options.minFractionDigits ?? Math.min(2, maxFractionDigits);
try {
return new Intl.NumberFormat(locale, {