feat(04-03): add AddDocumentModal, PdfViewer, and document detail page

- Create AddDocumentModal: searchable forms library list + custom file picker
- Wire Add Document button into ClientProfileClient in Documents section header
- Update DocumentsTable: document names now link to /portal/documents/{id}
- Create PdfViewer with page nav, zoom, and download controls (pdfjs worker via import.meta.url)
- Create /portal/documents/[docId] page: server component with auth check, doc/client query
- Add documentsRelations and clientsRelations to schema.ts for db.query with-relations support
- Build verified: /portal/documents/[docId] route present, no errors
This commit is contained in:
Chandler Copeland
2026-03-19 21:44:17 -06:00
parent 63e5888968
commit c1f60cadf6
6 changed files with 306 additions and 53 deletions

View File

@@ -0,0 +1,66 @@
'use client';
import { useState } from 'react';
import { Document, Page, pdfjs } from 'react-pdf';
import 'react-pdf/dist/Page/AnnotationLayer.css';
import 'react-pdf/dist/Page/TextLayer.css';
// Worker setup — must use import.meta.url for local/Docker environments (no CDN)
pdfjs.GlobalWorkerOptions.workerSrc = new URL(
'pdfjs-dist/build/pdf.worker.min.mjs',
import.meta.url,
).toString();
export function PdfViewer({ docId }: { docId: string }) {
const [numPages, setNumPages] = useState(0);
const [pageNumber, setPageNumber] = useState(1);
const [scale, setScale] = useState(1.0);
return (
<div className="flex flex-col items-center gap-4">
<div className="flex items-center gap-3 text-sm">
<button
onClick={() => setPageNumber(p => Math.max(1, p - 1))}
disabled={pageNumber <= 1}
className="px-3 py-1 border rounded disabled:opacity-40 hover:bg-gray-100"
>
Prev
</button>
<span>{pageNumber} / {numPages || '?'}</span>
<button
onClick={() => setPageNumber(p => Math.min(numPages, p + 1))}
disabled={pageNumber >= numPages}
className="px-3 py-1 border rounded disabled:opacity-40 hover:bg-gray-100"
>
Next
</button>
<button
onClick={() => setScale(s => Math.min(3, s + 0.2))}
className="px-3 py-1 border rounded hover:bg-gray-100"
>
Zoom In
</button>
<button
onClick={() => setScale(s => Math.max(0.4, s - 0.2))}
className="px-3 py-1 border rounded hover:bg-gray-100"
>
Zoom Out
</button>
<a
href={`/api/documents/${docId}/file`}
download
className="px-3 py-1 border rounded hover:bg-gray-100"
>
Download
</a>
</div>
<Document
file={`/api/documents/${docId}/file`}
onLoadSuccess={({ numPages }) => setNumPages(numPages)}
className="shadow-lg"
>
<Page pageNumber={pageNumber} scale={scale} />
</Document>
</div>
);
}

View File

@@ -0,0 +1,43 @@
import { auth } from '@/lib/auth';
import { redirect } from 'next/navigation';
import { db } from '@/lib/db';
import { documents, clients } from '@/lib/db/schema';
import { eq } from 'drizzle-orm';
import Link from 'next/link';
import { PdfViewer } from './_components/PdfViewer';
export default async function DocumentPage({
params,
}: {
params: Promise<{ docId: string }>;
}) {
const session = await auth();
if (!session) redirect('/login');
const { docId } = await params;
const doc = await db.query.documents.findFirst({
where: eq(documents.id, docId),
with: { client: true },
});
if (!doc) redirect('/portal/dashboard');
return (
<div className="max-w-5xl mx-auto px-4 py-6">
<div className="mb-4 flex items-center justify-between">
<div>
<Link
href={`/portal/clients/${doc.clientId}`}
className="text-sm text-blue-600 hover:underline"
>
&larr; Back to {doc.client?.name ?? 'Client'}
</Link>
<h1 className="text-2xl font-bold mt-1">{doc.name}</h1>
<p className="text-sm text-gray-500">{doc.client?.name}</p>
</div>
</div>
<PdfViewer docId={docId} />
</div>
);
}

View File

@@ -0,0 +1,129 @@
'use client';
import { useState, useEffect, useTransition } from 'react';
import { useRouter } from 'next/navigation';
type FormTemplate = { id: string; name: string; filename: string };
export function AddDocumentModal({ clientId, onClose }: { clientId: string; onClose: () => void }) {
const [templates, setTemplates] = useState<FormTemplate[]>([]);
const [query, setQuery] = useState('');
const [docName, setDocName] = useState('');
const [selectedTemplate, setSelectedTemplate] = useState<FormTemplate | null>(null);
const [customFile, setCustomFile] = useState<File | null>(null);
const [isPending, startTransition] = useTransition();
const [saving, setSaving] = useState(false);
const router = useRouter();
useEffect(() => {
fetch('/api/forms-library')
.then(r => r.json())
.then(setTemplates)
.catch(console.error);
}, []);
const filtered = templates.filter(t =>
t.name.toLowerCase().includes(query.toLowerCase())
);
const handleSelectTemplate = (t: FormTemplate) => {
setSelectedTemplate(t);
setCustomFile(null);
setDocName(t.name);
};
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0] ?? null;
setCustomFile(file);
setSelectedTemplate(null);
if (file) setDocName(file.name.replace(/\.pdf$/i, ''));
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!docName.trim() || (!selectedTemplate && !customFile)) return;
setSaving(true);
try {
if (customFile) {
const fd = new FormData();
fd.append('clientId', clientId);
fd.append('name', docName.trim());
fd.append('file', customFile);
await fetch('/api/documents', { method: 'POST', body: fd });
} else {
await fetch('/api/documents', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ clientId, name: docName.trim(), formTemplateId: selectedTemplate!.id }),
});
}
startTransition(() => router.refresh());
onClose();
} catch (err) {
console.error(err);
} finally {
setSaving(false);
}
};
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
<div className="bg-white rounded-lg shadow-xl w-full max-w-lg mx-4 p-6">
<h2 className="text-xl font-semibold mb-4">Add Document</h2>
<input
type="text"
placeholder="Search forms..."
value={query}
onChange={e => setQuery(e.target.value)}
className="w-full border rounded px-3 py-2 mb-3 text-sm"
/>
<ul className="border rounded max-h-48 overflow-y-auto mb-4">
{filtered.length === 0 && (
<li className="px-3 py-2 text-sm text-gray-500">No forms found</li>
)}
{filtered.map(t => (
<li
key={t.id}
onClick={() => handleSelectTemplate(t)}
className={`px-3 py-2 text-sm cursor-pointer hover:bg-gray-100 ${selectedTemplate?.id === t.id ? 'bg-blue-50 font-medium' : ''}`}
>
{t.name}
</li>
))}
</ul>
<div className="mb-4">
<label className="block text-sm font-medium mb-1">Or upload a custom PDF</label>
<input type="file" accept="application/pdf" onChange={handleFileChange} className="text-sm" />
</div>
<form onSubmit={handleSubmit}>
<label className="block text-sm font-medium mb-1">Document name</label>
<input
type="text"
value={docName}
onChange={e => setDocName(e.target.value)}
required
className="w-full border rounded px-3 py-2 mb-4 text-sm"
placeholder="e.g. 123 Main St Purchase Agreement"
/>
<div className="flex gap-3 justify-end">
<button type="button" onClick={onClose} className="px-4 py-2 text-sm border rounded hover:bg-gray-50">
Cancel
</button>
<button
type="submit"
disabled={saving || (!selectedTemplate && !customFile) || !docName.trim()}
className="px-4 py-2 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50"
>
{saving ? 'Saving...' : 'Add Document'}
</button>
</div>
</form>
</div>
</div>
);
}

View File

@@ -6,6 +6,7 @@ import Link from "next/link";
import { ClientModal } from "./ClientModal";
import { ConfirmDialog } from "./ConfirmDialog";
import { DocumentsTable } from "./DocumentsTable";
import { AddDocumentModal } from "./AddDocumentModal";
import { deleteClient } from "@/lib/actions/clients";
type DocumentRow = {
@@ -26,6 +27,7 @@ export function ClientProfileClient({ client, docs }: Props) {
const router = useRouter();
const [isEditOpen, setIsEditOpen] = useState(false);
const [isDeleteOpen, setIsDeleteOpen] = useState(false);
const [isAddDocOpen, setIsAddDocOpen] = useState(false);
async function handleDelete() {
await deleteClient(client.id);
@@ -35,34 +37,30 @@ export function ClientProfileClient({ client, docs }: Props) {
return (
<div>
{/* Header card */}
<div className="bg-white rounded-xl shadow-sm p-6 mb-6">
<div className="mb-4">
<Link
href="/portal/clients"
className="text-[var(--gold)] text-sm hover:opacity-80 flex items-center gap-1"
>
<div style={{ backgroundColor: "white", borderRadius: "1rem", boxShadow: "0 1px 4px rgba(0,0,0,0.07)", padding: "1.5rem", marginBottom: "1.25rem" }}>
<div style={{ marginBottom: "1rem" }}>
<Link href="/portal/clients" style={{ color: "#C9A84C", fontSize: "0.875rem", textDecoration: "none", display: "inline-flex", alignItems: "center", gap: "0.25rem" }}>
<span aria-hidden="true">&larr;</span> Back to Clients
</Link>
</div>
<div className="flex items-start justify-between">
<div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between" }}>
<div>
<h1 className="text-[var(--navy)] text-2xl font-semibold">
{client.name}
</h1>
<p className="text-gray-500 text-sm mt-1">{client.email}</p>
<h1 style={{ color: "#1B2B4B", fontSize: "1.5rem", fontWeight: 700, marginBottom: "0.25rem" }}>{client.name}</h1>
<p style={{ color: "#6B7280", fontSize: "0.875rem" }}>{client.email}</p>
</div>
<div className="flex gap-3">
<div style={{ display: "flex", gap: "0.75rem" }}>
<button
type="button"
onClick={() => setIsEditOpen(true)}
className="border border-[var(--navy)] text-[var(--navy)] px-4 py-2 rounded-lg text-sm hover:bg-[var(--navy)] hover:text-white transition-colors"
className="px-4 py-2 text-sm font-medium rounded-lg border transition hover:bg-gray-50"
style={{ borderColor: "#1B2B4B", color: "#1B2B4B" }}
>
Edit
</button>
<button
type="button"
onClick={() => setIsDeleteOpen(true)}
className="border border-red-300 text-red-600 px-4 py-2 rounded-lg text-sm hover:bg-red-50 transition-colors"
className="px-4 py-2 text-sm font-medium rounded-lg border border-red-200 text-red-600 transition hover:bg-red-50"
>
Delete Client
</button>
@@ -71,36 +69,33 @@ export function ClientProfileClient({ client, docs }: Props) {
</div>
{/* Documents card */}
<div className="bg-white rounded-xl shadow-sm p-6">
<h2 className="text-[var(--navy)] text-lg font-semibold mb-4">
Documents
</h2>
<div style={{ backgroundColor: "white", borderRadius: "1rem", boxShadow: "0 1px 4px rgba(0,0,0,0.07)", overflow: "hidden" }}>
<div style={{ padding: "1rem 1.5rem", borderBottom: "1px solid #F3F4F6", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
<h2 style={{ color: "#1B2B4B", fontSize: "1rem", fontWeight: 600 }}>Documents</h2>
<button
type="button"
onClick={() => setIsAddDocOpen(true)}
className="px-4 py-2 text-sm font-medium rounded-lg transition hover:bg-blue-700"
style={{ backgroundColor: "#C9A84C", color: "white" }}
>
+ Add Document
</button>
</div>
{docs.length === 0 ? (
<p className="text-gray-500 text-sm">No documents yet.</p>
<div style={{ padding: "3rem", textAlign: "center", color: "#6B7280", fontSize: "0.875rem" }}>No documents yet.</div>
) : (
<DocumentsTable rows={docs} showClientColumn={false} />
)}
</div>
{/* Edit modal */}
<ClientModal
isOpen={isEditOpen}
onClose={() => setIsEditOpen(false)}
mode="edit"
clientId={client.id}
defaultName={client.name}
defaultEmail={client.email}
/>
{/* Delete confirmation */}
<ClientModal isOpen={isEditOpen} onClose={() => setIsEditOpen(false)} mode="edit" clientId={client.id} defaultName={client.name} defaultEmail={client.email} />
{isAddDocOpen && (
<AddDocumentModal clientId={client.id} onClose={() => setIsAddDocOpen(false)} />
)}
<ConfirmDialog
isOpen={isDeleteOpen}
title="Delete client?"
message={
"Delete " +
client.name +
"? This will also delete all associated documents. This cannot be undone."
}
message={`Delete ${client.name}? This will also delete all associated documents. This cannot be undone.`}
onConfirm={handleDelete}
onCancel={() => setIsDeleteOpen(false)}
/>

View File

@@ -1,3 +1,4 @@
import Link from "next/link";
import { StatusBadge } from "./StatusBadge";
type DocumentRow = {
@@ -12,45 +13,55 @@ type DocumentRow = {
type Props = { rows: DocumentRow[]; showClientColumn?: boolean };
export function DocumentsTable({ rows, showClientColumn = true }: Props) {
if (rows.length === 0) {
return (
<div style={{ padding: "3rem", textAlign: "center", color: "#6B7280", fontSize: "0.875rem" }}>
No documents found.
</div>
);
}
return (
<table className="w-full text-sm">
<table style={{ width: "100%", fontSize: "0.875rem", borderCollapse: "collapse" }}>
<thead>
<tr>
<th className="text-left text-xs font-medium text-gray-500 uppercase px-4 py-3">
<tr style={{ borderBottom: "1px solid #F3F4F6" }}>
<th style={{ textAlign: "left", fontSize: "0.75rem", fontWeight: 600, color: "#6B7280", textTransform: "uppercase", letterSpacing: "0.05em", padding: "0.75rem 1.5rem" }}>
Document Name
</th>
{showClientColumn && (
<th className="text-left text-xs font-medium text-gray-500 uppercase px-4 py-3">
<th style={{ textAlign: "left", fontSize: "0.75rem", fontWeight: 600, color: "#6B7280", textTransform: "uppercase", letterSpacing: "0.05em", padding: "0.75rem 1.5rem" }}>
Client
</th>
)}
<th className="text-left text-xs font-medium text-gray-500 uppercase px-4 py-3">
<th style={{ textAlign: "left", fontSize: "0.75rem", fontWeight: 600, color: "#6B7280", textTransform: "uppercase", letterSpacing: "0.05em", padding: "0.75rem 1.5rem" }}>
Status
</th>
<th className="text-left text-xs font-medium text-gray-500 uppercase px-4 py-3">
<th style={{ textAlign: "left", fontSize: "0.75rem", fontWeight: 600, color: "#6B7280", textTransform: "uppercase", letterSpacing: "0.05em", padding: "0.75rem 1.5rem" }}>
Date Sent
</th>
</tr>
</thead>
<tbody>
{rows.map((row) => (
<tr key={row.id}>
<td className="px-4 py-3 border-t border-gray-100">{row.name}</td>
<tr key={row.id} style={{ borderBottom: "1px solid #F9FAFB" }}>
<td style={{ padding: "0.875rem 1.5rem", fontWeight: 500 }}>
<Link
href={`/portal/documents/${row.id}`}
style={{ color: "#1B2B4B", textDecoration: "none" }}
className="hover:text-blue-600 hover:underline"
>
{row.name}
</Link>
</td>
{showClientColumn && (
<td className="px-4 py-3 border-t border-gray-100">
{row.clientName ?? "—"}
</td>
<td style={{ padding: "0.875rem 1.5rem", color: "#374151" }}>{row.clientName ?? "—"}</td>
)}
<td className="px-4 py-3 border-t border-gray-100">
<td style={{ padding: "0.875rem 1.5rem" }}>
<StatusBadge status={row.status} />
</td>
<td className="px-4 py-3 border-t border-gray-100">
<td style={{ padding: "0.875rem 1.5rem", color: "#6B7280" }}>
{row.sentAt
? row.sentAt.toLocaleDateString("en-US", {
month: "short",
day: "numeric",
year: "numeric",
})
? new Date(row.sentAt).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })
: "—"}
</td>
</tr>

View File

@@ -1,4 +1,5 @@
import { pgEnum, pgTable, text, timestamp } from "drizzle-orm/pg-core";
import { relations } from "drizzle-orm";
export const users = pgTable("users", {
id: text("id").primaryKey().$defaultFn(() => crypto.randomUUID()),
@@ -42,3 +43,11 @@ export const documents = pgTable("documents", {
formTemplateId: text("form_template_id").references(() => formTemplates.id),
filePath: text("file_path"),
});
export const documentsRelations = relations(documents, ({ one }) => ({
client: one(clients, { fields: [documents.clientId], references: [clients.id] }),
}));
export const clientsRelations = relations(clients, ({ many }) => ({
documents: many(documents),
}));