merge: PR5 — document detail page (Phase A)

This commit is contained in:
Matt Ciaccio
2026-04-28 02:39:52 +02:00
8 changed files with 568 additions and 16 deletions

View File

@@ -1,6 +1,4 @@
import Link from 'next/link';
import { Button } from '@/components/ui/button';
import { PageHeader } from '@/components/shared/page-header';
import { DocumentDetail } from '@/components/documents/document-detail';
interface PageProps {
params: Promise<{ portSlug: string; id: string }>;
@@ -8,17 +6,5 @@ interface PageProps {
export default async function DocumentDetailPage({ params }: PageProps) {
const { portSlug, id } = await params;
return (
<div className="flex flex-col gap-4">
<PageHeader
title="Document detail"
description={`Document ${id} — full detail view ships in PR5 of the Phase A rollout.`}
actions={
<Button asChild variant="outline">
<Link href={`/${portSlug}/documents`}>Back to documents</Link>
</Button>
}
/>
</div>
);
return <DocumentDetail documentId={id} portSlug={portSlug} />;
}

View File

@@ -0,0 +1,21 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { cancelDocument } from '@/lib/services/documents.service';
export const POST = withAuth(
withPermission('documents', 'edit', async (_req, ctx, params) => {
try {
const doc = await cancelDocument(params.id!, ctx.portId, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: doc });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,16 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { composeSignedDocEmail } from '@/lib/services/documents.service';
export const POST = withAuth(
withPermission('documents', 'view', async (_req, ctx, params) => {
try {
const draft = await composeSignedDocEmail(params.id!, ctx.portId);
return NextResponse.json({ data: draft });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -5,6 +5,7 @@ import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import {
getDocumentById,
getDocumentDetail,
updateDocument,
deleteDocument,
} from '@/lib/services/documents.service';
@@ -13,6 +14,11 @@ import { updateDocumentSchema } from '@/lib/validators/documents';
export const GET = withAuth(
withPermission('documents', 'view', async (req, ctx, params) => {
try {
const url = new URL(req.url);
if (url.searchParams.get('detail') === 'true') {
const detail = await getDocumentDetail(params.id!, ctx.portId);
return NextResponse.json({ data: detail });
}
const doc = await getDocumentById(params.id!, ctx.portId);
return NextResponse.json({ data: doc });
} catch (error) {

View File

@@ -0,0 +1,21 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { removeDocumentWatcher } from '@/lib/services/documents.service';
export const DELETE = withAuth(
withPermission('documents', 'edit', async (_req, ctx, params) => {
try {
await removeDocumentWatcher(params.id!, ctx.portId, params.userId!, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: { ok: true } });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,39 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { addDocumentWatcher, listDocumentWatchers } from '@/lib/services/documents.service';
const addWatcherSchema = z.object({
userId: z.string().min(1),
});
export const GET = withAuth(
withPermission('documents', 'view', async (_req, ctx, params) => {
try {
const watchers = await listDocumentWatchers(params.id!, ctx.portId);
return NextResponse.json({ data: watchers });
} catch (error) {
return errorResponse(error);
}
}),
);
export const POST = withAuth(
withPermission('documents', 'edit', async (req, ctx, params) => {
try {
const body = await parseBody(req, addWatcherSchema);
const watcher = await addDocumentWatcher(params.id!, ctx.portId, body.userId, {
userId: ctx.userId,
portId: ctx.portId,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
return NextResponse.json({ data: watcher }, { status: 201 });
} catch (error) {
return errorResponse(error);
}
}),
);

View File

@@ -0,0 +1,400 @@
'use client';
import { useState } from 'react';
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, Trash2, X } from 'lucide-react';
import { toast } from 'sonner';
import { Button } from '@/components/ui/button';
import { PageHeader } from '@/components/shared/page-header';
import { StatusPill, type StatusPillStatus } from '@/components/ui/status-pill';
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
import { apiFetch } from '@/lib/api/client';
interface DetailDoc {
id: string;
title: string;
status: string;
documentType: string;
documensoId: string | null;
signedFileId: string | null;
reservationId: string | null;
interestId: string | null;
clientId: string | null;
yachtId: string | null;
companyId: string | null;
createdAt: string;
createdBy: string;
}
interface DetailSigner {
id: string;
signerName: string;
signerEmail: string;
signerRole: string;
signingOrder: number;
status: string;
signedAt: string | null;
signingUrl: string | null;
}
interface DetailEvent {
id: string;
eventType: string;
createdAt: string;
signerId: string | null;
eventData: Record<string, unknown> | null;
}
interface DetailWatcher {
userId: string;
addedBy: string;
addedAt: string;
}
interface DetailResponse {
data: {
document: DetailDoc;
signers: DetailSigner[];
events: DetailEvent[];
watchers: DetailWatcher[];
};
}
const STATUS_PILL_MAP: Record<string, StatusPillStatus> = {
draft: 'draft',
sent: 'sent',
partially_signed: 'partial',
completed: 'completed',
signed: 'signed',
expired: 'expired',
cancelled: 'cancelled',
rejected: 'rejected',
pending: 'pending',
declined: 'declined',
};
const SIGNER_PILL_MAP: Record<string, StatusPillStatus> = {
pending: 'pending',
signed: 'signed',
declined: 'declined',
};
interface DocumentDetailProps {
documentId: string;
portSlug: string;
}
export function DocumentDetail({ documentId, portSlug }: DocumentDetailProps) {
const router = useRouter();
const queryClient = useQueryClient();
const [isCancelling, setIsCancelling] = useState(false);
const { data, isLoading, error } = useQuery<DetailResponse>({
queryKey: ['document-detail', documentId],
queryFn: () => apiFetch<DetailResponse>(`/api/v1/documents/${documentId}?detail=true`),
});
useRealtimeInvalidation({
'document:updated': [['document-detail', documentId]],
'document:sent': [['document-detail', documentId]],
'document:completed': [['document-detail', documentId]],
'document:cancelled': [['document-detail', documentId]],
'document:rejected': [['document-detail', documentId]],
'document:expired': [['document-detail', documentId]],
'document:signer:signed': [['document-detail', documentId]],
'document:signer:opened': [['document-detail', documentId]],
});
if (isLoading) {
return (
<div className="flex flex-col gap-4">
<div className="h-24 animate-pulse rounded-xl bg-muted/40" />
<div className="grid gap-4 lg:grid-cols-[2fr_1fr]">
<div className="h-64 animate-pulse rounded-md bg-muted/40" />
<div className="h-64 animate-pulse rounded-md bg-muted/40" />
</div>
</div>
);
}
if (error || !data) {
return (
<div className="flex flex-col gap-4">
<PageHeader
title="Document not found"
description="This document was deleted or you don't have access to it."
actions={
<Button asChild variant="outline">
<Link href={`/${portSlug}/documents`}>
<ArrowLeft className="mr-1.5 h-4 w-4" />
Back to documents
</Link>
</Button>
}
/>
</div>
);
}
const { document: doc, signers, events, watchers } = 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) {
toast.error(err instanceof Error ? err.message : 'Failed to send reminder');
}
};
const handleCancel = async () => {
if (!confirm('Cancel this document? This voids it in Documenso and cannot be undone.')) return;
setIsCancelling(true);
try {
await apiFetch(`/api/v1/documents/${documentId}/cancel`, { method: 'POST' });
toast.success('Document cancelled');
router.push(`/${portSlug}/documents`);
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Cancel failed');
setIsCancelling(false);
}
};
const handleEmailSignedPdf = async () => {
try {
const draft = await apiFetch<{
data: { to: string[]; subject: string; attachments: Array<{ fileId: string }> };
}>(`/api/v1/documents/${documentId}/compose-completion-email`, { method: 'POST' });
toast.info(
`Email composer prepared for ${draft.data.to.length} signer${draft.data.to.length === 1 ? '' : 's'} — opens in PR8 wizard`,
);
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Failed to prepare email');
}
};
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;
return (
<div className="flex flex-col gap-4">
<PageHeader
eyebrow={doc.documentType.replace(/_/g, ' ')}
title={doc.title}
description={`Created ${new Date(doc.createdAt).toLocaleDateString('en-GB')}`}
kpiLine={
<>
<StatusPill status={STATUS_PILL_MAP[doc.status] ?? 'pending'} withDot>
{doc.status.replace(/_/g, ' ')}
</StatusPill>
<span>
{signers.filter((s) => s.status === 'signed').length}/{signers.length} signed
</span>
{watchers.length > 0 ? <span>{watchers.length} watching</span> : null}
</>
}
actions={
<div className="flex items-center gap-2">
<Button asChild variant="outline" size="sm">
<Link href={`/${portSlug}/documents`}>
<ArrowLeft className="mr-1.5 h-4 w-4" /> Back
</Link>
</Button>
{isComplete && doc.signedFileId ? (
<>
<Button asChild size="sm">
<Link href={`/api/v1/files/${doc.signedFileId}/download`}>
<Download className="mr-1.5 h-4 w-4" /> Download signed PDF
</Link>
</Button>
<Button size="sm" variant="outline" onClick={handleEmailSignedPdf}>
<Mail className="mr-1.5 h-4 w-4" /> Email signatories
</Button>
</>
) : null}
{isInFlight ? (
<Button size="sm" variant="outline" onClick={handleCancel} disabled={isCancelling}>
<X className="mr-1.5 h-4 w-4" /> Cancel
</Button>
) : null}
</div>
}
variant="gradient"
/>
<div className="grid gap-4 lg:grid-cols-[2fr_1fr]">
{/* Left column */}
<div className="flex flex-col gap-4">
<section className="rounded-md border bg-white p-4">
<h2 className="mb-3 text-sm font-semibold uppercase tracking-wide text-muted-foreground">
Signers
</h2>
{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">{signer.signerName}</div>
<StatusPill status={SIGNER_PILL_MAP[signer.status] ?? 'pending'}>
{signer.status}
</StatusPill>
</div>
<div className="text-xs text-muted-foreground">
{signer.signerEmail} · {signer.signerRole}
</div>
<div className="mt-1 text-xs text-muted-foreground">
{signer.signedAt
? `Signed ${new Date(signer.signedAt).toLocaleDateString('en-GB')}`
: 'Pending'}
</div>
{signer.status === 'pending' && doc.documensoId && isInFlight ? (
<div className="mt-2 flex items-center gap-2">
<Button
size="sm"
variant="outline"
onClick={() => handleRemind(signer.id)}
>
<Bell className="mr-1.5 h-3 w-3" /> Remind
</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>
)}
</section>
{subjectLink ? (
<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
</h2>
<Link
href={subjectLink.href as Route}
className="text-sm font-medium text-brand hover:underline"
>
{subjectLink.label}
</Link>
</section>
) : null}
</div>
{/* Right column */}
<div className="flex flex-col gap-4">
<section className="rounded-md border bg-white p-4">
<h2 className="mb-2 text-sm font-semibold uppercase tracking-wide text-muted-foreground">
Watchers
</h2>
{watchers.length === 0 ? (
<p className="text-xs text-muted-foreground">No one is watching this document yet.</p>
) : (
<ul className="space-y-1">
{watchers.map((w) => (
<li key={w.userId} className="flex items-center justify-between text-sm">
<span className="truncate font-mono text-xs text-muted-foreground">
{w.userId.slice(0, 8)}
</span>
<button
type="button"
aria-label="Remove watcher"
onClick={async () => {
try {
await apiFetch(`/api/v1/documents/${documentId}/watchers/${w.userId}`, {
method: 'DELETE',
});
toast.success('Watcher removed');
queryClient.invalidateQueries({
queryKey: ['document-detail', documentId],
});
} catch (err) {
toast.error(
err instanceof Error ? err.message : 'Failed to remove watcher',
);
}
}}
className="text-muted-foreground hover:text-destructive"
>
<Trash2 className="h-3.5 w-3.5" />
</button>
</li>
))}
</ul>
)}
</section>
<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>
</div>
</div>
</div>
);
}

View File

@@ -1095,6 +1095,69 @@ export async function composeSignedDocEmail(
};
}
// ─── Watchers (PR5) ───────────────────────────────────────────────────────────
export async function listDocumentWatchers(documentId: string, portId: string) {
await getDocumentById(documentId, portId); // port-scope check
return db
.select({
userId: documentWatchers.userId,
addedBy: documentWatchers.addedBy,
addedAt: documentWatchers.addedAt,
})
.from(documentWatchers)
.where(eq(documentWatchers.documentId, documentId));
}
export async function addDocumentWatcher(
documentId: string,
portId: string,
userId: string,
meta: AuditMeta,
): Promise<{ userId: string; addedAt: Date }> {
await getDocumentById(documentId, portId);
const [row] = await db
.insert(documentWatchers)
.values({ documentId, userId, addedBy: meta.userId })
.onConflictDoNothing()
.returning();
void createAuditLog({
userId: meta.userId,
portId,
action: 'create',
entityType: 'document_watcher',
entityId: documentId,
newValue: { documentId, watcherUserId: userId },
ipAddress: meta.ipAddress,
userAgent: meta.userAgent,
});
emitToRoom(`port:${portId}`, 'document:updated', { documentId });
return row ? { userId: row.userId, addedAt: row.addedAt } : { userId, addedAt: new Date() };
}
export async function removeDocumentWatcher(
documentId: string,
portId: string,
userId: string,
meta: AuditMeta,
): Promise<void> {
await getDocumentById(documentId, portId);
await db
.delete(documentWatchers)
.where(and(eq(documentWatchers.documentId, documentId), eq(documentWatchers.userId, userId)));
void createAuditLog({
userId: meta.userId,
portId,
action: 'delete',
entityType: 'document_watcher',
entityId: documentId,
oldValue: { documentId, watcherUserId: userId },
ipAddress: meta.ipAddress,
userAgent: meta.userAgent,
});
emitToRoom(`port:${portId}`, 'document:updated', { documentId });
}
/**
* Skeleton for the create-document wizard entry point (PR6).
*