feat(post-audit): batch A+B quick-wins + audit-side residuals

Bundles the user-prioritised follow-ups from the post-audit punch-list.

Batch A — pipeline + EOI safety:
 - §1.1 timeline buildAuditDescription renders diff fields ("leadCategory → hot_lead").
 - §4.13 EOI rejection cascade: notification to assigned rep + audit row + rose banner.
 - §4.10b finish doc-detail: SigningProgress reuse, linked-entity names (server-resolved),
   per-event icons + tooltips + show-more in activity panel.
 - §7.2 stage guidance card replaces empty Payments slot pre-reservation.
 - §4.15 deal-pulse trigger audit (docs/deal-pulse-trigger-audit.md).

Batch B — UX consistency + docs:
 - §1.4 quick log-contact button on interest header.
 - §2.1 contact-log compose: Dialog → Sheet.
 - §7.1 docs/deal-pulse explainer page; /docs/ in PUBLIC_PATHS.
 - DocumentStatus now includes 'rejected' + 'declined' across constants, labels, tone maps.

Audit-side residuals:
 - M-NEW-1 /me/ports skips port-context requirement.
 - M-AU03 audit log CSV export endpoint + UI button.
 - M-IN03 dead receipt-scanner.ts deleted; live path already per-port.
 - M-P01 pg_trgm GIN indexes (migration 0071).
 - §10.1 webhook tests verified passing (was stale).

Deferred per user direction:
 - §11.3 email copy refactor (needs old-CRM reference).
 - M-EM03 IMAP bounce-to-interest linking.

Tests: 1374/1374. tsc + lint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-18 14:22:11 +02:00
parent 4b5f85cb7d
commit 0f99f054b3
21 changed files with 1399 additions and 258 deletions

View File

@@ -5,7 +5,23 @@ import Link from 'next/link';
import type { Route } from 'next';
import { useRouter } from 'next/navigation';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { ArrowLeft, Bell, Download, Mail, Send, Trash2, UserPlus, X } from 'lucide-react';
import {
ArrowLeft,
Bell,
CheckCircle2,
ChevronDown,
Clock,
Download,
Eye,
FileText,
Mail,
Send,
Trash2,
UserPlus,
X,
XCircle,
} from 'lucide-react';
import { format, formatDistanceToNowStrict } from 'date-fns';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
@@ -15,7 +31,7 @@ import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
import { useConfirmation } from '@/hooks/use-confirmation';
import { apiFetch } from '@/lib/api/client';
import { toastError } from '@/lib/api/toast-error';
import { cleanSignerName } from '@/components/documents/signing-progress';
import { SigningProgress } from '@/components/documents/signing-progress';
import {
Select,
SelectContent,
@@ -76,12 +92,20 @@ interface DetailWatcher {
addedAt: string;
}
interface DetailLinked {
interest: { id: string; clientName: string | null } | null;
client: { id: string; fullName: string } | null;
yacht: { id: string; name: string } | null;
company: { id: string; name: string } | null;
}
interface DetailResponse {
data: {
document: DetailDoc;
signers: DetailSigner[];
events: DetailEvent[];
watchers: DetailWatcher[];
linked: DetailLinked;
};
}
@@ -98,12 +122,6 @@ const STATUS_PILL_MAP: Record<string, StatusPillStatus> = {
declined: 'declined',
};
const SIGNER_PILL_MAP: Record<string, StatusPillStatus> = {
pending: 'pending',
signed: 'signed',
declined: 'declined',
};
interface DocumentDetailProps {
documentId: string;
portSlug: string;
@@ -111,7 +129,6 @@ interface DocumentDetailProps {
export function DocumentDetail({ documentId, portSlug }: DocumentDetailProps) {
const router = useRouter();
const queryClient = useQueryClient();
const [isCancelling, setIsCancelling] = useState(false);
const { confirm, dialog: confirmDialog } = useConfirmation();
@@ -162,36 +179,13 @@ export function DocumentDetail({ documentId, portSlug }: DocumentDetailProps) {
);
}
const { document: doc, signers, events, watchers } = data.data;
const { document: doc, signers, events, watchers, linked } = data.data;
const handleRemind = async (signerId: string) => {
try {
await apiFetch(`/api/v1/documents/${documentId}/remind`, {
method: 'POST',
body: { signerId },
});
toast.success('Reminder sent');
queryClient.invalidateQueries({ queryKey: ['document-detail', documentId] });
} catch (err) {
toastError(err);
}
};
// #67: state-aware action button. When a signer has no `invitedAt`
// they've never been mailed — fire the initial invitation (the same
// route the EOI tab uses; handles v2 distribute-or-self-heal).
const handleSendInvitation = async (signerId: string) => {
try {
await apiFetch(`/api/v1/documents/${documentId}/send-invitation`, {
method: 'POST',
body: { signerId },
});
toast.success('Invitation sent');
queryClient.invalidateQueries({ queryKey: ['document-detail', documentId] });
} catch (err) {
toastError(err);
}
};
// #67: signer-row "Send invitation" / "Send reminder" handlers used
// to live here on the doc-detail page directly. The Signers section
// now reuses <SigningProgress>, which owns those handlers internally
// (calls the same /remind and /send-invitation routes). The wrappers
// were intentionally removed in the doc-detail polish wave.
const handleCancel = async () => {
const ok = await confirm({
@@ -227,17 +221,47 @@ export function DocumentDetail({ documentId, portSlug }: DocumentDetailProps) {
const isInFlight = ['sent', 'partially_signed'].includes(doc.status);
const isComplete = ['completed', 'signed'].includes(doc.status);
const subjectLink = doc.reservationId
? { href: `/${portSlug}/berth-reservations/${doc.reservationId}`, label: 'Reservation' }
: doc.interestId
? { href: `/${portSlug}/interests/${doc.interestId}`, label: 'Interest' }
: doc.clientId
? { href: `/${portSlug}/clients/${doc.clientId}`, label: 'Client' }
: doc.yachtId
? { href: `/${portSlug}/yachts/${doc.yachtId}`, label: 'Yacht' }
: doc.companyId
? { href: `/${portSlug}/companies/${doc.companyId}`, label: 'Company' }
: null;
// #67: linked-entity rows now show the entity TYPE + NAME (resolved
// server-side in getDocumentDetail) so the card reads "Interest —
// Matt Ciaccio" instead of "Interest →". Multiple linked entities
// render as a chip row; nothing renders when there's nothing to
// link.
const linkedRows: Array<{ href: string; label: string; sub: string | null }> = [];
if (doc.reservationId) {
linkedRows.push({
href: `/${portSlug}/berth-reservations/${doc.reservationId}`,
label: 'Reservation',
sub: null,
});
}
if (linked.interest) {
linkedRows.push({
href: `/${portSlug}/interests/${linked.interest.id}`,
label: 'Interest',
sub: linked.interest.clientName,
});
}
if (linked.client) {
linkedRows.push({
href: `/${portSlug}/clients/${linked.client.id}`,
label: 'Client',
sub: linked.client.fullName,
});
}
if (linked.yacht) {
linkedRows.push({
href: `/${portSlug}/yachts/${linked.yacht.id}`,
label: 'Yacht',
sub: linked.yacht.name,
});
}
if (linked.company) {
linkedRows.push({
href: `/${portSlug}/companies/${linked.company.id}`,
label: 'Company',
sub: linked.company.name,
});
}
return (
<div className="flex flex-col gap-4">
@@ -295,93 +319,35 @@ export function DocumentDetail({ documentId, portSlug }: DocumentDetailProps) {
{signers.length === 0 ? (
<p className="text-sm text-muted-foreground">No signers attached.</p>
) : (
<ul className="space-y-3">
{signers.map((signer, idx) => (
<li
key={signer.id}
className="flex items-start gap-3 rounded-md border bg-white p-3 shadow-xs transition-colors hover:bg-muted/30"
>
<div
className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-xs font-semibold ${
signer.status === 'signed'
? 'bg-success-bg text-success'
: signer.status === 'declined'
? 'bg-error-bg text-error'
: 'bg-slate-100 text-slate-600'
}`}
>
{idx + 1}
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center justify-between gap-2">
<div className="font-medium text-foreground">
{/* #67 cleanup: strip `(was: …)` / `(placeholder)`
email-redirect leak suffixes that the EOI tab
already scrubs on its own SigningProgress card. */}
{cleanSignerName(signer.signerName) || signer.signerEmail}
</div>
<StatusPill status={SIGNER_PILL_MAP[signer.status] ?? 'pending'}>
{capFirst(signer.status)}
</StatusPill>
</div>
<div className="text-xs text-muted-foreground">
{signer.signerEmail} · {capFirst(signer.signerRole)}
</div>
<div className="mt-1 text-xs text-muted-foreground">
{signer.signedAt
? `Signed ${new Date(signer.signedAt).toLocaleDateString('en-GB')}`
: signer.invitedAt
? `Invited ${new Date(signer.invitedAt).toLocaleDateString('en-GB')}`
: 'Not yet invited'}
</div>
{signer.status === 'pending' && doc.documensoId && isInFlight ? (
<div className="mt-2 flex items-center gap-2">
{/* #67 state-aware CTA: invited yet? remind. else: send. */}
{signer.invitedAt ? (
<Button
size="sm"
variant="outline"
onClick={() => handleRemind(signer.id)}
>
<Bell className="mr-1.5 h-3 w-3" aria-hidden /> Send reminder
</Button>
) : (
<Button size="sm" onClick={() => handleSendInvitation(signer.id)}>
<Send className="mr-1.5 h-3 w-3" aria-hidden /> Send invitation
</Button>
)}
{signer.signingUrl ? (
<button
type="button"
onClick={() => {
navigator.clipboard.writeText(signer.signingUrl!);
toast.success('Signing link copied');
}}
className="text-xs text-brand hover:underline"
>
Copy signing link
</button>
) : null}
</div>
) : null}
</div>
</li>
))}
</ul>
// #67 visual parity: re-use the EOI tab's <SigningProgress>
// so the doc-detail card matches every other surface that
// shows signer state (cleaned names, status-tinted card,
// state-aware action button, signing-link copy, role chip).
<SigningProgress documentId={documentId} signers={signers} />
)}
</section>
{subjectLink ? (
{linkedRows.length > 0 ? (
<section className="rounded-md border bg-white p-4">
<h2 className="mb-2 text-sm font-semibold uppercase tracking-wide text-muted-foreground">
Linked entity
Linked {linkedRows.length === 1 ? 'entity' : 'entities'}
</h2>
<Link
href={subjectLink.href as Route}
className="text-sm font-medium text-brand hover:underline"
>
{subjectLink.label}
</Link>
<div className="flex flex-wrap gap-2">
{linkedRows.map((row) => (
<Link
key={row.href}
href={row.href as Route}
className="inline-flex flex-col rounded-md border px-3 py-2 text-sm hover:bg-muted/50"
>
<span className="text-xs uppercase tracking-wide text-muted-foreground">
{row.label}
</span>
<span className="font-medium text-brand">
{row.sub ?? `Open ${row.label.toLowerCase()}`}
</span>
</Link>
))}
</div>
</section>
) : null}
</div>
@@ -390,27 +356,7 @@ export function DocumentDetail({ documentId, portSlug }: DocumentDetailProps) {
<div className="flex flex-col gap-4">
<WatchersCard documentId={documentId} watchers={watchers} />
<section className="rounded-md border bg-white p-4">
<h2 className="mb-2 text-sm font-semibold uppercase tracking-wide text-muted-foreground">
Activity
</h2>
{events.length === 0 ? (
<p className="text-xs text-muted-foreground">No events yet.</p>
) : (
<ul className="space-y-2">
{events.slice(0, 12).map((e) => (
<li key={e.id} className="text-xs">
<div className="font-medium text-foreground">
{e.eventType.replace(/_/g, ' ')}
</div>
<div className="text-muted-foreground">
{new Date(e.createdAt).toLocaleString('en-GB')}
</div>
</li>
))}
</ul>
)}
</section>
<ActivityCard events={events} />
</div>
</div>
{confirmDialog}
@@ -418,6 +364,114 @@ export function DocumentDetail({ documentId, portSlug }: DocumentDetailProps) {
);
}
// #67 activity panel polish: per-event icons + actor-aware copy +
// precise tooltip + reverse-chronological order. Same data the
// previous flat list rendered, just legible.
const EVENT_META: Record<
string,
{ label: (data?: Record<string, unknown>) => string; icon: typeof Clock; tone: string }
> = {
created: { label: () => 'Created', icon: FileText, tone: 'text-slate-500' },
sent: {
label: (d) => (d?.recipientEmail ? `Sent to ${d.recipientEmail}` : 'Sent for signing'),
icon: Send,
tone: 'text-sky-600',
},
viewed: {
label: (d) => (d?.recipientEmail ? `${d.recipientEmail} opened` : 'Opened'),
icon: Eye,
tone: 'text-amber-600',
},
signed: {
label: (d) => (d?.recipientEmail ? `${d.recipientEmail} signed` : 'Signed'),
icon: CheckCircle2,
tone: 'text-emerald-600',
},
reminder_sent: {
label: (d) => (d?.recipientEmail ? `Reminder → ${d.recipientEmail}` : 'Reminder sent'),
icon: Bell,
tone: 'text-amber-700',
},
completed: { label: () => 'All parties signed', icon: CheckCircle2, tone: 'text-emerald-700' },
rejected: {
label: (d) => (d?.recipientEmail ? `${d.recipientEmail} declined` : 'Declined'),
icon: XCircle,
tone: 'text-rose-600',
},
declined: {
label: (d) => (d?.recipientEmail ? `${d.recipientEmail} declined` : 'Declined'),
icon: XCircle,
tone: 'text-rose-600',
},
expired: { label: () => 'Expired', icon: Clock, tone: 'text-rose-500' },
cancelled: { label: () => 'Cancelled', icon: X, tone: 'text-slate-500' },
deleted: { label: () => 'Deleted', icon: Trash2, tone: 'text-slate-500' },
};
function ActivityCard({ events }: { events: DetailEvent[] }) {
const [showAll, setShowAll] = useState(false);
// Server returns oldest-first; reverse so most recent reads top of card.
const sorted = [...events].sort(
(a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),
);
const visible = showAll ? sorted : sorted.slice(0, 8);
return (
<section className="rounded-md border bg-white p-4">
<h2 className="mb-2 text-sm font-semibold uppercase tracking-wide text-muted-foreground">
Activity
</h2>
{sorted.length === 0 ? (
<p className="text-xs text-muted-foreground">No events yet.</p>
) : (
<>
<ul className="space-y-2.5">
{visible.map((e) => {
const meta = EVENT_META[e.eventType] ?? {
label: () => e.eventType.replace(/_/g, ' '),
icon: Clock,
tone: 'text-muted-foreground',
};
const Icon = meta.icon;
const data = (e.eventData ?? {}) as Record<string, unknown>;
const label = meta.label(data);
const when = new Date(e.createdAt);
return (
<li key={e.id} className="flex items-start gap-2 text-xs">
<Icon className={`mt-0.5 size-3.5 shrink-0 ${meta.tone}`} aria-hidden />
<div className="min-w-0 flex-1">
<div className="truncate font-medium text-foreground">{label}</div>
<time
dateTime={when.toISOString()}
title={format(when, 'PPpp')}
className="text-muted-foreground"
>
{formatDistanceToNowStrict(when, { addSuffix: true })}
</time>
</div>
</li>
);
})}
</ul>
{sorted.length > 8 ? (
<button
type="button"
onClick={() => setShowAll((v) => !v)}
className="mt-3 inline-flex items-center gap-1 text-xs text-brand hover:underline"
>
<ChevronDown
className={`size-3 transition-transform ${showAll ? 'rotate-180' : ''}`}
aria-hidden
/>
{showAll ? 'Show fewer' : `Show all ${sorted.length} events`}
</button>
) : null}
</>
)}
</section>
);
}
/**
* #67 watcher Add UI. The watchers list previously displayed only
* user-id stubs (truncated UUID) with a delete button and no way to