Co-authored-by: renee-png <262607627+renee-png@users.noreply.github.com>
This commit is contained in:
gpt-engineer-app[bot]
2026-04-17 02:23:12 +00:00
co-authored by renee-png
parent 46f2d14c5d
commit 1f3fd28159
5 changed files with 880 additions and 0 deletions
@@ -0,0 +1,200 @@
import { useEffect, useState } from "react";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/lib/auth";
import { toast } from "sonner";
import { Loader2 } from "lucide-react";
export const CONTACT_TYPES = [
{ value: "opposing_counsel", label: "Opposing counsel" },
{ value: "co_counsel", label: "Co-counsel" },
{ value: "expert", label: "Expert" },
{ value: "witness", label: "Witness" },
{ value: "vendor", label: "Vendor" },
{ value: "court", label: "Court / clerk" },
{ value: "process_server", label: "Process server" },
{ value: "client_contact", label: "Client contact" },
{ value: "other", label: "Other" },
] as const;
export interface ContactRecord {
id?: string;
name: string;
company?: string | null;
title?: string | null;
email?: string | null;
phone?: string | null;
address_line1?: string | null;
address_line2?: string | null;
city?: string | null;
state?: string | null;
postal_code?: string | null;
notes?: string | null;
contact_type?: string | null;
}
export function ContactFormDialog({
open,
onOpenChange,
contact,
onSaved,
}: {
open: boolean;
onOpenChange: (v: boolean) => void;
contact?: ContactRecord | null;
onSaved?: (saved: { id: string; name: string }) => void;
}) {
const { user } = useAuth();
const [saving, setSaving] = useState(false);
const [form, setForm] = useState<ContactRecord>({
name: "",
contact_type: "other",
});
useEffect(() => {
if (open) {
setForm(
contact
? { ...contact }
: { name: "", contact_type: "other" },
);
}
}, [open, contact]);
const set = <K extends keyof ContactRecord>(k: K, v: ContactRecord[K]) =>
setForm((f) => ({ ...f, [k]: v }));
const onSave = async () => {
if (!form.name.trim()) {
toast.error("Name is required");
return;
}
setSaving(true);
const payload = {
name: form.name.trim(),
company: form.company || null,
title: form.title || null,
email: form.email || null,
phone: form.phone || null,
address_line1: form.address_line1 || null,
address_line2: form.address_line2 || null,
city: form.city || null,
state: form.state || null,
postal_code: form.postal_code || null,
notes: form.notes || null,
contact_type: form.contact_type || "other",
};
let saved: { id: string; name: string } | null = null;
if (contact?.id) {
const { data, error } = await supabase
.from("contacts")
.update(payload)
.eq("id", contact.id)
.select("id, name")
.single();
if (error) {
toast.error(error.message);
setSaving(false);
return;
}
saved = data;
} else {
const { data, error } = await supabase
.from("contacts")
.insert({ ...payload, created_by: user?.id })
.select("id, name")
.single();
if (error) {
toast.error(error.message);
setSaving(false);
return;
}
saved = data;
}
setSaving(false);
toast.success(contact?.id ? "Contact updated" : "Contact created");
onOpenChange(false);
if (saved) onSaved?.(saved);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>{contact?.id ? "Edit contact" : "New contact"}</DialogTitle>
</DialogHeader>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-1.5 sm:col-span-2">
<Label>Name *</Label>
<Input value={form.name} onChange={(e) => set("name", e.target.value)} />
</div>
<div className="space-y-1.5">
<Label>Type</Label>
<Select value={form.contact_type ?? "other"} onValueChange={(v) => set("contact_type", v)}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
{CONTACT_TYPES.map((t) => (
<SelectItem key={t.value} value={t.value}>{t.label}</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label>Title</Label>
<Input value={form.title ?? ""} onChange={(e) => set("title", e.target.value)} />
</div>
<div className="space-y-1.5 sm:col-span-2">
<Label>Company / Firm</Label>
<Input value={form.company ?? ""} onChange={(e) => set("company", e.target.value)} />
</div>
<div className="space-y-1.5">
<Label>Email</Label>
<Input type="email" value={form.email ?? ""} onChange={(e) => set("email", e.target.value)} />
</div>
<div className="space-y-1.5">
<Label>Phone</Label>
<Input value={form.phone ?? ""} onChange={(e) => set("phone", e.target.value)} />
</div>
<div className="space-y-1.5 sm:col-span-2">
<Label>Address line 1</Label>
<Input value={form.address_line1 ?? ""} onChange={(e) => set("address_line1", e.target.value)} />
</div>
<div className="space-y-1.5 sm:col-span-2">
<Label>Address line 2</Label>
<Input value={form.address_line2 ?? ""} onChange={(e) => set("address_line2", e.target.value)} />
</div>
<div className="space-y-1.5">
<Label>City</Label>
<Input value={form.city ?? ""} onChange={(e) => set("city", e.target.value)} />
</div>
<div className="space-y-1.5">
<Label>State</Label>
<Input value={form.state ?? ""} onChange={(e) => set("state", e.target.value)} />
</div>
<div className="space-y-1.5">
<Label>Postal code</Label>
<Input value={form.postal_code ?? ""} onChange={(e) => set("postal_code", e.target.value)} />
</div>
<div className="space-y-1.5 sm:col-span-2">
<Label>Notes</Label>
<Textarea rows={3} value={form.notes ?? ""} onChange={(e) => set("notes", e.target.value)} />
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
<Button onClick={onSave} disabled={saving}>
{saving && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
{contact?.id ? "Save" : "Create"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,240 @@
import { useEffect, useMemo, useState } from "react";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/lib/auth";
import { toast } from "sonner";
import { Plus, Trash2, Mail, Phone, Building2, MapPin, Search, UserPlus } from "lucide-react";
import { ContactFormDialog, CONTACT_TYPES } from "./contact-form-dialog";
interface LinkedContact {
id: string; // join row id
role: string | null;
contact: {
id: string;
name: string;
company: string | null;
title: string | null;
email: string | null;
phone: string | null;
contact_type: string;
address_line1: string | null;
city: string | null;
state: string | null;
postal_code: string | null;
};
}
export function ContactsLinkTab({
parentId,
parentTable,
}: {
parentId: string;
parentTable: "case_contacts" | "client_contacts";
}) {
const { user } = useAuth();
const fkColumn = parentTable === "case_contacts" ? "case_id" : "client_id";
const [linked, setLinked] = useState<LinkedContact[]>([]);
const [loading, setLoading] = useState(true);
const [pickerOpen, setPickerOpen] = useState(false);
const [createOpen, setCreateOpen] = useState(false);
const load = async () => {
setLoading(true);
const { data, error } = await supabase
.from(parentTable)
.select("id, role, contact:contacts(id, name, company, title, email, phone, contact_type, address_line1, city, state, postal_code)")
.eq(fkColumn, parentId);
if (error) toast.error(error.message);
setLinked(((data ?? []) as any[]).filter((d) => d.contact));
setLoading(false);
};
useEffect(() => {
load();
}, [parentId, parentTable]);
const linkContact = async (contactId: string) => {
const payload: Record<string, unknown> = {
contact_id: contactId,
created_by: user?.id,
};
payload[fkColumn] = parentId;
const { error } = await supabase.from(parentTable).insert(payload as any);
if (error) {
if (error.code === "23505") toast.info("Already linked");
else toast.error(error.message);
return;
}
toast.success("Contact linked");
setPickerOpen(false);
load();
};
const unlink = async (joinId: string) => {
const { error } = await supabase.from(parentTable).delete().eq("id", joinId);
if (error) {
toast.error(error.message);
return;
}
setLinked((rows) => rows.filter((r) => r.id !== joinId));
};
const linkedIds = useMemo(() => new Set(linked.map((l) => l.contact.id)), [linked]);
return (
<Card className="border-border/60">
<CardContent className="p-5">
<div className="flex items-center justify-between mb-4">
<div>
<div className="text-xs uppercase tracking-wider text-muted-foreground font-medium">Contacts</div>
<div className="text-sm text-muted-foreground">
{linked.length} linked contact{linked.length === 1 ? "" : "s"}
</div>
</div>
<div className="flex gap-2">
<Button variant="outline" size="sm" onClick={() => setCreateOpen(true)}>
<UserPlus className="h-3.5 w-3.5 mr-1.5" /> New contact
</Button>
<Button size="sm" onClick={() => setPickerOpen(true)}>
<Plus className="h-3.5 w-3.5 mr-1.5" /> Link existing
</Button>
</div>
</div>
{loading ? (
<p className="text-sm text-muted-foreground">Loading…</p>
) : linked.length === 0 ? (
<p className="text-sm text-muted-foreground">No contacts linked yet.</p>
) : (
<ul className="divide-y">
{linked.map((row) => {
const c = row.contact;
const typeLabel = CONTACT_TYPES.find((t) => t.value === c.contact_type)?.label ?? c.contact_type;
const addr = [c.address_line1, c.city, c.state, c.postal_code].filter(Boolean).join(", ");
return (
<li key={row.id} className="py-3 flex items-start justify-between gap-4">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-medium">{c.name}</span>
<Badge variant="outline" className="text-[10px]">{typeLabel}</Badge>
{c.title && <span className="text-xs text-muted-foreground">{c.title}</span>}
</div>
<div className="mt-1 grid sm:grid-cols-2 gap-x-4 gap-y-1 text-xs text-muted-foreground">
{c.company && <span className="flex items-center gap-1.5"><Building2 className="h-3 w-3" />{c.company}</span>}
{c.email && <a href={`mailto:${c.email}`} className="flex items-center gap-1.5 hover:text-primary"><Mail className="h-3 w-3" />{c.email}</a>}
{c.phone && <a href={`tel:${c.phone}`} className="flex items-center gap-1.5 hover:text-primary"><Phone className="h-3 w-3" />{c.phone}</a>}
{addr && <span className="flex items-center gap-1.5"><MapPin className="h-3 w-3" />{addr}</span>}
</div>
</div>
<Button variant="ghost" size="icon" onClick={() => unlink(row.id)} title="Unlink">
<Trash2 className="h-4 w-4 text-destructive" />
</Button>
</li>
);
})}
</ul>
)}
<ContactPickerDialog
open={pickerOpen}
onOpenChange={setPickerOpen}
excludeIds={linkedIds}
onPick={linkContact}
/>
<ContactFormDialog
open={createOpen}
onOpenChange={setCreateOpen}
onSaved={async (saved) => {
await linkContact(saved.id);
}}
/>
</CardContent>
</Card>
);
}
function ContactPickerDialog({
open,
onOpenChange,
excludeIds,
onPick,
}: {
open: boolean;
onOpenChange: (v: boolean) => void;
excludeIds: Set<string>;
onPick: (id: string) => void;
}) {
const [q, setQ] = useState("");
const [rows, setRows] = useState<any[]>([]);
useEffect(() => {
if (!open) return;
setQ("");
supabase
.from("contacts")
.select("id, name, company, contact_type, email")
.order("name")
.limit(200)
.then(({ data }) => setRows(data ?? []));
}, [open]);
const filtered = useMemo(() => {
const term = q.trim().toLowerCase();
return rows
.filter((r) => !excludeIds.has(r.id))
.filter((r) => {
if (!term) return true;
return (
r.name.toLowerCase().includes(term) ||
(r.company ?? "").toLowerCase().includes(term) ||
(r.email ?? "").toLowerCase().includes(term)
);
});
}, [rows, q, excludeIds]);
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-lg">
<DialogHeader>
<DialogTitle>Link existing contact</DialogTitle>
</DialogHeader>
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input className="pl-9" placeholder="Search by name, company, email…" value={q} onChange={(e) => setQ(e.target.value)} autoFocus />
</div>
<div className="max-h-[400px] overflow-auto -mx-2">
{filtered.length === 0 ? (
<p className="text-sm text-muted-foreground p-3">No matching contacts.</p>
) : (
<ul className="divide-y">
{filtered.map((c) => {
const typeLabel = CONTACT_TYPES.find((t) => t.value === c.contact_type)?.label ?? c.contact_type;
return (
<li key={c.id}>
<button
type="button"
onClick={() => onPick(c.id)}
className="w-full text-left px-3 py-2.5 hover:bg-muted/60 flex items-center justify-between gap-3"
>
<div className="min-w-0">
<div className="font-medium text-sm truncate">{c.name}</div>
<div className="text-xs text-muted-foreground truncate">
{[c.company, c.email].filter(Boolean).join(" · ") || "—"}
</div>
</div>
<Badge variant="outline" className="text-[10px] shrink-0">{typeLabel}</Badge>
</button>
</li>
);
})}
</ul>
)}
</div>
</DialogContent>
</Dialog>
);
}
+51
View File
@@ -17,11 +17,13 @@ import { Route as StatusIndexRouteImport } from './routes/status.index'
import { Route as SettingsIndexRouteImport } from './routes/settings.index'
import { Route as FilesIndexRouteImport } from './routes/files.index'
import { Route as DocumentsIndexRouteImport } from './routes/documents.index'
import { Route as ContactsIndexRouteImport } from './routes/contacts.index'
import { Route as CollectionsIndexRouteImport } from './routes/collections.index'
import { Route as ClientsIndexRouteImport } from './routes/clients.index'
import { Route as CasesIndexRouteImport } from './routes/cases.index'
import { Route as SettingsWorkflowRouteImport } from './routes/settings.workflow'
import { Route as SettingsFeesRouteImport } from './routes/settings.fees'
import { Route as ContactsContactIdRouteImport } from './routes/contacts.$contactId'
import { Route as CollectionsCollectionIdRouteImport } from './routes/collections.$collectionId'
import { Route as ClientsClientIdRouteImport } from './routes/clients.$clientId'
import { Route as CasesNewRouteImport } from './routes/cases.new'
@@ -72,6 +74,11 @@ const DocumentsIndexRoute = DocumentsIndexRouteImport.update({
path: '/documents/',
getParentRoute: () => rootRouteImport,
} as any)
const ContactsIndexRoute = ContactsIndexRouteImport.update({
id: '/contacts/',
path: '/contacts/',
getParentRoute: () => rootRouteImport,
} as any)
const CollectionsIndexRoute = CollectionsIndexRouteImport.update({
id: '/collections/',
path: '/collections/',
@@ -97,6 +104,11 @@ const SettingsFeesRoute = SettingsFeesRouteImport.update({
path: '/fees',
getParentRoute: () => SettingsRoute,
} as any)
const ContactsContactIdRoute = ContactsContactIdRouteImport.update({
id: '/contacts/$contactId',
path: '/contacts/$contactId',
getParentRoute: () => rootRouteImport,
} as any)
const CollectionsCollectionIdRoute = CollectionsCollectionIdRouteImport.update({
id: '/collections/$collectionId',
path: '/collections/$collectionId',
@@ -154,11 +166,13 @@ export interface FileRoutesByFullPath {
'/cases/new': typeof CasesNewRoute
'/clients/$clientId': typeof ClientsClientIdRoute
'/collections/$collectionId': typeof CollectionsCollectionIdRoute
'/contacts/$contactId': typeof ContactsContactIdRoute
'/settings/fees': typeof SettingsFeesRoute
'/settings/workflow': typeof SettingsWorkflowRoute
'/cases/': typeof CasesIndexRoute
'/clients/': typeof ClientsIndexRoute
'/collections/': typeof CollectionsIndexRoute
'/contacts/': typeof ContactsIndexRoute
'/documents/': typeof DocumentsIndexRoute
'/files/': typeof FilesIndexRoute
'/settings/': typeof SettingsIndexRoute
@@ -177,11 +191,13 @@ export interface FileRoutesByTo {
'/cases/new': typeof CasesNewRoute
'/clients/$clientId': typeof ClientsClientIdRoute
'/collections/$collectionId': typeof CollectionsCollectionIdRoute
'/contacts/$contactId': typeof ContactsContactIdRoute
'/settings/fees': typeof SettingsFeesRoute
'/settings/workflow': typeof SettingsWorkflowRoute
'/cases': typeof CasesIndexRoute
'/clients': typeof ClientsIndexRoute
'/collections': typeof CollectionsIndexRoute
'/contacts': typeof ContactsIndexRoute
'/documents': typeof DocumentsIndexRoute
'/files': typeof FilesIndexRoute
'/settings': typeof SettingsIndexRoute
@@ -202,11 +218,13 @@ export interface FileRoutesById {
'/cases/new': typeof CasesNewRoute
'/clients/$clientId': typeof ClientsClientIdRoute
'/collections/$collectionId': typeof CollectionsCollectionIdRoute
'/contacts/$contactId': typeof ContactsContactIdRoute
'/settings/fees': typeof SettingsFeesRoute
'/settings/workflow': typeof SettingsWorkflowRoute
'/cases/': typeof CasesIndexRoute
'/clients/': typeof ClientsIndexRoute
'/collections/': typeof CollectionsIndexRoute
'/contacts/': typeof ContactsIndexRoute
'/documents/': typeof DocumentsIndexRoute
'/files/': typeof FilesIndexRoute
'/settings/': typeof SettingsIndexRoute
@@ -228,11 +246,13 @@ export interface FileRouteTypes {
| '/cases/new'
| '/clients/$clientId'
| '/collections/$collectionId'
| '/contacts/$contactId'
| '/settings/fees'
| '/settings/workflow'
| '/cases/'
| '/clients/'
| '/collections/'
| '/contacts/'
| '/documents/'
| '/files/'
| '/settings/'
@@ -251,11 +271,13 @@ export interface FileRouteTypes {
| '/cases/new'
| '/clients/$clientId'
| '/collections/$collectionId'
| '/contacts/$contactId'
| '/settings/fees'
| '/settings/workflow'
| '/cases'
| '/clients'
| '/collections'
| '/contacts'
| '/documents'
| '/files'
| '/settings'
@@ -275,11 +297,13 @@ export interface FileRouteTypes {
| '/cases/new'
| '/clients/$clientId'
| '/collections/$collectionId'
| '/contacts/$contactId'
| '/settings/fees'
| '/settings/workflow'
| '/cases/'
| '/clients/'
| '/collections/'
| '/contacts/'
| '/documents/'
| '/files/'
| '/settings/'
@@ -300,9 +324,11 @@ export interface RootRouteChildren {
CasesNewRoute: typeof CasesNewRoute
ClientsClientIdRoute: typeof ClientsClientIdRoute
CollectionsCollectionIdRoute: typeof CollectionsCollectionIdRoute
ContactsContactIdRoute: typeof ContactsContactIdRoute
CasesIndexRoute: typeof CasesIndexRoute
ClientsIndexRoute: typeof ClientsIndexRoute
CollectionsIndexRoute: typeof CollectionsIndexRoute
ContactsIndexRoute: typeof ContactsIndexRoute
DocumentsIndexRoute: typeof DocumentsIndexRoute
FilesIndexRoute: typeof FilesIndexRoute
StatusIndexRoute: typeof StatusIndexRoute
@@ -370,6 +396,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof DocumentsIndexRouteImport
parentRoute: typeof rootRouteImport
}
'/contacts/': {
id: '/contacts/'
path: '/contacts'
fullPath: '/contacts/'
preLoaderRoute: typeof ContactsIndexRouteImport
parentRoute: typeof rootRouteImport
}
'/collections/': {
id: '/collections/'
path: '/collections'
@@ -405,6 +438,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SettingsFeesRouteImport
parentRoute: typeof SettingsRoute
}
'/contacts/$contactId': {
id: '/contacts/$contactId'
path: '/contacts/$contactId'
fullPath: '/contacts/$contactId'
preLoaderRoute: typeof ContactsContactIdRouteImport
parentRoute: typeof rootRouteImport
}
'/collections/$collectionId': {
id: '/collections/$collectionId'
path: '/collections/$collectionId'
@@ -497,9 +537,11 @@ const rootRouteChildren: RootRouteChildren = {
CasesNewRoute: CasesNewRoute,
ClientsClientIdRoute: ClientsClientIdRoute,
CollectionsCollectionIdRoute: CollectionsCollectionIdRoute,
ContactsContactIdRoute: ContactsContactIdRoute,
CasesIndexRoute: CasesIndexRoute,
ClientsIndexRoute: ClientsIndexRoute,
CollectionsIndexRoute: CollectionsIndexRoute,
ContactsIndexRoute: ContactsIndexRoute,
DocumentsIndexRoute: DocumentsIndexRoute,
FilesIndexRoute: FilesIndexRoute,
StatusIndexRoute: StatusIndexRoute,
@@ -511,3 +553,12 @@ const rootRouteChildren: RootRouteChildren = {
export const routeTree = rootRouteImport
._addFileChildren(rootRouteChildren)
._addFileTypes<FileRouteTypes>()
import type { getRouter } from './router.tsx'
import type { createStart } from '@tanstack/react-start'
declare module '@tanstack/react-start' {
interface Register {
ssr: true
router: Awaited<ReturnType<typeof getRouter>>
}
}
+188
View File
@@ -0,0 +1,188 @@
import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { ProtectedLayout } from "@/components/protected-layout";
import { PageContainer, PageHeader } from "@/components/app-shell";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/lib/auth";
import { toast } from "sonner";
import { ArrowLeft, Edit, Trash2, Mail, Phone, MapPin, Building2, Briefcase, Users } from "lucide-react";
import { ContactFormDialog, CONTACT_TYPES } from "@/components/contacts/contact-form-dialog";
export const Route = createFileRoute("/contacts/$contactId")({
component: () => (
<ProtectedLayout>
<ContactDetail />
</ProtectedLayout>
),
});
function ContactDetail() {
const { contactId } = Route.useParams();
const navigate = useNavigate();
const { user, isAdmin } = useAuth();
const [contact, setContact] = useState<any>(null);
const [cases, setCases] = useState<any[]>([]);
const [clients, setClients] = useState<any[]>([]);
const [loading, setLoading] = useState(true);
const [editOpen, setEditOpen] = useState(false);
const load = async () => {
setLoading(true);
const [{ data: c, error }, { data: cc }, { data: clc }] = await Promise.all([
supabase.from("contacts").select("*").eq("id", contactId).maybeSingle(),
supabase.from("case_contacts").select("role, case:cases(id, case_number, title, status)").eq("contact_id", contactId),
supabase.from("client_contacts").select("role, client:clients(id, name, client_type)").eq("contact_id", contactId),
]);
if (error) toast.error(error.message);
setContact(c);
setCases(((cc ?? []) as any[]).filter((r) => r.case));
setClients(((clc ?? []) as any[]).filter((r) => r.client));
setLoading(false);
};
useEffect(() => {
load();
}, [contactId]);
const remove = async () => {
if (!contact) return;
if (!confirm(`Delete contact "${contact.name}"?`)) return;
const { error } = await supabase.from("contacts").delete().eq("id", contactId);
if (error) {
toast.error(error.message);
return;
}
toast.success("Contact deleted");
navigate({ to: "/contacts" });
};
if (loading) {
return <PageContainer><p className="text-muted-foreground">Loading…</p></PageContainer>;
}
if (!contact) {
return (
<PageContainer>
<p className="text-muted-foreground">Contact not found.</p>
<Button variant="outline" className="mt-3" asChild>
<Link to="/contacts"><ArrowLeft className="h-4 w-4 mr-2" /> Back to contacts</Link>
</Button>
</PageContainer>
);
}
const canEdit = isAdmin || contact.created_by === user?.id;
const typeLabel = CONTACT_TYPES.find((t) => t.value === contact.contact_type)?.label ?? contact.contact_type;
const addr = [contact.address_line1, contact.address_line2, contact.city, contact.state, contact.postal_code].filter(Boolean).join(", ");
return (
<PageContainer>
<Button variant="ghost" size="sm" asChild className="mb-3 -ml-2">
<Link to="/contacts"><ArrowLeft className="h-4 w-4 mr-1" /> All contacts</Link>
</Button>
<PageHeader
title={contact.name}
description={[contact.title, contact.company].filter(Boolean).join(" · ") || typeLabel}
actions={
canEdit ? (
<>
<Button variant="outline" onClick={() => setEditOpen(true)}><Edit className="h-4 w-4 mr-2" /> Edit</Button>
<Button variant="outline" onClick={remove}><Trash2 className="h-4 w-4 mr-2" /> Delete</Button>
</>
) : null
}
/>
<div className="grid lg:grid-cols-3 gap-6">
<Card className="lg:col-span-2 border-border/60">
<CardContent className="p-5">
<div className="flex items-center gap-2 mb-4">
<Badge variant="outline" className="text-[10px]">{typeLabel}</Badge>
</div>
<dl className="grid grid-cols-2 gap-y-3 gap-x-6 text-sm">
<DetailRow label="Email" value={contact.email} icon={Mail} />
<DetailRow label="Phone" value={contact.phone} icon={Phone} />
<DetailRow label="Company" value={contact.company} icon={Building2} />
<DetailRow label="Title" value={contact.title} />
<DetailRow label="Address" value={addr || null} icon={MapPin} />
</dl>
{contact.notes && (
<div className="mt-4 pt-4 border-t">
<div className="text-xs uppercase tracking-wider text-muted-foreground mb-1">Notes</div>
<p className="text-sm whitespace-pre-wrap">{contact.notes}</p>
</div>
)}
</CardContent>
</Card>
<Card className="border-border/60 h-fit">
<CardContent className="p-5 space-y-4">
<div>
<div className="flex items-center gap-2 mb-2">
<Briefcase className="h-4 w-4 text-muted-foreground" />
<h3 className="font-serif text-base">Cases ({cases.length})</h3>
</div>
{cases.length === 0 ? (
<p className="text-xs text-muted-foreground">Not linked to any cases.</p>
) : (
<div className="space-y-1">
{cases.map((row, i) => (
<Link
key={i}
to="/cases/$caseId"
params={{ caseId: row.case.id }}
className="block p-2 rounded-md hover:bg-muted/60 -mx-2"
>
<div className="text-sm font-medium truncate">{row.case.title}</div>
<div className="text-xs text-muted-foreground">{row.case.case_number}</div>
</Link>
))}
</div>
)}
</div>
<div className="pt-3 border-t">
<div className="flex items-center gap-2 mb-2">
<Users className="h-4 w-4 text-muted-foreground" />
<h3 className="font-serif text-base">Clients ({clients.length})</h3>
</div>
{clients.length === 0 ? (
<p className="text-xs text-muted-foreground">Not linked to any clients.</p>
) : (
<div className="space-y-1">
{clients.map((row, i) => (
<Link
key={i}
to="/clients/$clientId"
params={{ clientId: row.client.id }}
className="block p-2 rounded-md hover:bg-muted/60 -mx-2"
>
<div className="text-sm font-medium truncate">{row.client.name}</div>
<div className="text-xs text-muted-foreground capitalize">{row.client.client_type}</div>
</Link>
))}
</div>
)}
</div>
</CardContent>
</Card>
</div>
<ContactFormDialog open={editOpen} onOpenChange={setEditOpen} contact={contact} onSaved={() => load()} />
</PageContainer>
);
}
function DetailRow({ label, value, icon: Icon }: { label: string; value: any; icon?: any }) {
return (
<>
<dt className="text-xs uppercase tracking-wider text-muted-foreground self-center">{label}</dt>
<dd className="text-sm flex items-center gap-1.5">
{Icon && value && <Icon className="h-3 w-3 text-muted-foreground" />}
{value || <span className="text-muted-foreground italic">—</span>}
</dd>
</>
);
}
+201
View File
@@ -0,0 +1,201 @@
import { createFileRoute, Link } from "@tanstack/react-router";
import { useEffect, useMemo, useState } from "react";
import { ProtectedLayout } from "@/components/protected-layout";
import { PageContainer, PageHeader } from "@/components/app-shell";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/lib/auth";
import { toast } from "sonner";
import { Plus, Search, Mail, Phone, Building2, ChevronRight, Edit, Trash2, Briefcase, Users } from "lucide-react";
import { ContactFormDialog, CONTACT_TYPES, type ContactRecord } from "@/components/contacts/contact-form-dialog";
export const Route = createFileRoute("/contacts/")({
component: () => (
<ProtectedLayout>
<ContactsIndex />
</ProtectedLayout>
),
});
interface ContactRow extends Required<Pick<ContactRecord, "name">>, ContactRecord {
id: string;
created_by: string | null;
case_links: number;
client_links: number;
}
function ContactsIndex() {
const { user, isAdmin } = useAuth();
const [rows, setRows] = useState<ContactRow[]>([]);
const [loading, setLoading] = useState(true);
const [q, setQ] = useState("");
const [typeFilter, setTypeFilter] = useState<string>("all");
const [editing, setEditing] = useState<ContactRecord | null>(null);
const [open, setOpen] = useState(false);
const load = async () => {
setLoading(true);
const [{ data, error }, { data: cc }, { data: clc }] = await Promise.all([
supabase.from("contacts").select("*").order("name"),
supabase.from("case_contacts").select("contact_id"),
supabase.from("client_contacts").select("contact_id"),
]);
if (error) toast.error(error.message);
const caseCounts = new Map<string, number>();
(cc ?? []).forEach((r: any) => caseCounts.set(r.contact_id, (caseCounts.get(r.contact_id) ?? 0) + 1));
const clientCounts = new Map<string, number>();
(clc ?? []).forEach((r: any) => clientCounts.set(r.contact_id, (clientCounts.get(r.contact_id) ?? 0) + 1));
setRows(
(data ?? []).map((c: any) => ({
...c,
case_links: caseCounts.get(c.id) ?? 0,
client_links: clientCounts.get(c.id) ?? 0,
})),
);
setLoading(false);
};
useEffect(() => {
load();
}, []);
const filtered = useMemo(() => {
const term = q.trim().toLowerCase();
return rows.filter((r) => {
if (typeFilter !== "all" && r.contact_type !== typeFilter) return false;
if (!term) return true;
return (
r.name.toLowerCase().includes(term) ||
(r.company ?? "").toLowerCase().includes(term) ||
(r.email ?? "").toLowerCase().includes(term) ||
(r.phone ?? "").toLowerCase().includes(term)
);
});
}, [rows, q, typeFilter]);
const remove = async (id: string, name: string) => {
if (!confirm(`Delete contact "${name}"? This will also remove all case and client links.`)) return;
const { error } = await supabase.from("contacts").delete().eq("id", id);
if (error) {
toast.error(error.message);
return;
}
toast.success("Contact deleted");
setRows((r) => r.filter((x) => x.id !== id));
};
const startNew = () => {
setEditing(null);
setOpen(true);
};
const startEdit = (c: ContactRow) => {
setEditing(c);
setOpen(true);
};
return (
<PageContainer>
<PageHeader
title="Contacts"
description="Shared directory of opposing counsel, witnesses, vendors, experts, and other contacts."
actions={
<Button onClick={startNew}>
<Plus className="h-4 w-4 mr-2" /> New contact
</Button>
}
/>
<Card className="mb-4">
<CardContent className="p-4 flex flex-col sm:flex-row gap-3">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
placeholder="Search name, company, email, phone…"
value={q}
onChange={(e) => setQ(e.target.value)}
className="pl-9"
/>
</div>
<select
value={typeFilter}
onChange={(e) => setTypeFilter(e.target.value)}
className="h-9 rounded-md border border-input bg-transparent px-3 text-sm sm:w-56"
>
<option value="all">All types</option>
{CONTACT_TYPES.map((t) => (
<option key={t.value} value={t.value}>{t.label}</option>
))}
</select>
</CardContent>
</Card>
<Card>
<CardContent className="p-0">
{loading ? (
<p className="p-6 text-sm text-muted-foreground">Loading…</p>
) : filtered.length === 0 ? (
<p className="p-6 text-sm text-muted-foreground text-center">
{rows.length === 0 ? "No contacts yet." : "No contacts match your filters."}
</p>
) : (
<ul className="divide-y">
{filtered.map((c) => {
const typeLabel = CONTACT_TYPES.find((t) => t.value === c.contact_type)?.label ?? c.contact_type;
const canEdit = isAdmin || c.created_by === user?.id;
return (
<li key={c.id} className="px-4 py-3 hover:bg-muted/40 transition-colors">
<div className="flex items-center gap-3">
<Link
to="/contacts/$contactId"
params={{ contactId: c.id }}
className="flex-1 min-w-0 flex items-center gap-3"
>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 flex-wrap">
<span className="font-medium truncate">{c.name}</span>
<Badge variant="outline" className="text-[10px]">{typeLabel}</Badge>
{c.title && <span className="text-xs text-muted-foreground">{c.title}</span>}
</div>
<div className="mt-1 flex flex-wrap gap-x-4 gap-y-0.5 text-xs text-muted-foreground">
{c.company && <span className="flex items-center gap-1.5"><Building2 className="h-3 w-3" />{c.company}</span>}
{c.email && <span className="flex items-center gap-1.5"><Mail className="h-3 w-3" />{c.email}</span>}
{c.phone && <span className="flex items-center gap-1.5"><Phone className="h-3 w-3" />{c.phone}</span>}
</div>
</div>
<div className="hidden md:flex flex-col items-end text-[11px] text-muted-foreground gap-0.5 mr-2">
{c.case_links > 0 && <span className="flex items-center gap-1"><Briefcase className="h-3 w-3" />{c.case_links} case{c.case_links === 1 ? "" : "s"}</span>}
{c.client_links > 0 && <span className="flex items-center gap-1"><Users className="h-3 w-3" />{c.client_links} client{c.client_links === 1 ? "" : "s"}</span>}
</div>
<ChevronRight className="h-4 w-4 text-muted-foreground" />
</Link>
{canEdit && (
<div className="flex gap-1">
<Button variant="ghost" size="icon" onClick={() => startEdit(c)}>
<Edit className="h-4 w-4" />
</Button>
<Button variant="ghost" size="icon" onClick={() => remove(c.id, c.name)}>
<Trash2 className="h-4 w-4 text-destructive" />
</Button>
</div>
)}
</div>
</li>
);
})}
</ul>
)}
</CardContent>
</Card>
<ContactFormDialog
open={open}
onOpenChange={setOpen}
contact={editing}
onSaved={() => load()}
/>
</PageContainer>
);
}