Files
mylegal-stage-law/src/routes/contacts.index.tsx
T
2026-04-18 16:03:01 +00:00

499 lines
20 KiB
TypeScript

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 { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Checkbox } from "@/components/ui/checkbox";
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 { Plus, Search, Mail, Phone, Building2, ChevronRight, Edit, Trash2, Briefcase, Users, Archive, ArchiveRestore, X } from "lucide-react";
import { ContactFormDialog, CONTACT_TYPES, type ContactRecord } from "@/components/contacts/contact-form-dialog";
import { setArchived } from "@/lib/archive";
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;
archived_at: string | null;
}
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 [view, setView] = useState<"active" | "archived">("active");
const [editing, setEditing] = useState<ContactRecord | null>(null);
const [open, setOpen] = useState(false);
const [selected, setSelected] = useState<Set<string>>(new Set());
const [bulkType, setBulkType] = useState<string>("");
const [letter, setLetter] = useState<string>("all");
const [visibleLimit, setVisibleLimit] = useState<number>(100);
const load = async () => {
setLoading(true);
// Paginate to bypass Supabase's 1000-row default limit
const fetchAllContacts = async () => {
const pageSize = 1000;
let from = 0;
const all: any[] = [];
while (true) {
const { data, error } = await supabase
.from("contacts")
.select("*")
.order("name")
.range(from, from + pageSize - 1);
if (error) return { data: all, error };
if (!data || data.length === 0) break;
all.push(...data);
if (data.length < pageSize) break;
from += pageSize;
}
return { data: all, error: null as any };
};
const fetchAllLinks = async (table: "case_contacts" | "client_contacts") => {
const pageSize = 1000;
let from = 0;
const all: any[] = [];
while (true) {
const { data, error } = await supabase
.from(table)
.select("contact_id")
.range(from, from + pageSize - 1);
if (error || !data || data.length === 0) break;
all.push(...data);
if (data.length < pageSize) break;
from += pageSize;
}
return { data: all };
};
const [{ data, error }, { data: cc }, { data: clc }] = await Promise.all([
fetchAllContacts(),
fetchAllLinks("case_contacts"),
fetchAllLinks("client_contacts"),
]);
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 letterOf = (name: string | null | undefined) => {
const ch = (name?.[0] ?? "#").toUpperCase();
return /[A-Z]/.test(ch) ? ch : "#";
};
const preLetterFiltered = useMemo(() => {
const term = q.trim().toLowerCase();
return rows.filter((r) => {
if (view === "archived" ? !r.archived_at : !!r.archived_at) return false;
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, view]);
const letterCounts = useMemo(() => {
const counts: Record<string, number> = { all: preLetterFiltered.length };
for (const r of preLetterFiltered) {
const l = letterOf(r.name);
counts[l] = (counts[l] ?? 0) + 1;
}
return counts;
}, [preLetterFiltered]);
const filtered = useMemo(() => {
if (letter === "all") return preLetterFiltered;
return preLetterFiltered.filter((r) => letterOf(r.name) === letter);
}, [preLetterFiltered, letter]);
// Reset paging window when filters change
useEffect(() => {
setVisibleLimit(100);
}, [q, typeFilter, view, letter]);
const visibleRows = useMemo(() => filtered.slice(0, visibleLimit), [filtered, visibleLimit]);
const hasMore = filtered.length > visibleRows.length;
const grouped = useMemo(() => {
const map = new Map<string, ContactRow[]>();
for (const r of visibleRows) {
const l = letterOf(r.name);
if (!map.has(l)) map.set(l, []);
map.get(l)!.push(r);
}
return Array.from(map.entries()).sort(([a], [b]) => {
if (a === "#") return 1;
if (b === "#") return -1;
return a.localeCompare(b);
});
}, [visibleRows]);
const archivedCount = rows.filter((r) => r.archived_at).length;
const activeCount = rows.length - archivedCount;
const typeCounts = useMemo(() => {
const base = rows.filter((r) => (view === "archived" ? !!r.archived_at : !r.archived_at));
const counts: Record<string, number> = { all: base.length };
for (const t of CONTACT_TYPES) {
counts[t.value] = base.filter((r) => (r.contact_type ?? "other") === t.value).length;
}
return counts;
}, [rows, view]);
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 onArchive = async (id: string, archived: boolean) => {
if (await setArchived("contacts", id, archived)) load();
};
const startNew = () => {
setEditing(null);
setOpen(true);
};
const startEdit = (c: ContactRow) => {
setEditing(c);
setOpen(true);
};
const toggleOne = (id: string) => {
setSelected((s) => {
const next = new Set(s);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
};
const toggleAllVisible = () => {
const ids = visibleRows.map((r) => r.id);
const allSelected = ids.every((id) => selected.has(id));
setSelected((s) => {
const next = new Set(s);
if (allSelected) ids.forEach((id) => next.delete(id));
else ids.forEach((id) => next.add(id));
return next;
});
};
const clearSelection = () => setSelected(new Set());
const bulkArchive = async (archived: boolean) => {
const ids = Array.from(selected);
if (!ids.length) return;
const patch = { archived_at: archived ? new Date().toISOString() : null };
const { error } = await (supabase.from("contacts") as any).update(patch).in("id", ids);
if (error) {
toast.error(error.message);
return;
}
toast.success(`${ids.length} contact${ids.length === 1 ? "" : "s"} ${archived ? "archived" : "restored"}`);
clearSelection();
load();
};
const bulkDelete = async () => {
const ids = Array.from(selected);
if (!ids.length) return;
if (!confirm(`Delete ${ids.length} contact${ids.length === 1 ? "" : "s"}? This will also remove all case and client links.`)) return;
const { error } = await supabase.from("contacts").delete().in("id", ids);
if (error) {
toast.error(error.message);
return;
}
toast.success(`${ids.length} contact${ids.length === 1 ? "" : "s"} deleted`);
clearSelection();
load();
};
const bulkChangeType = async (newType: string) => {
const ids = Array.from(selected);
if (!ids.length || !newType) return;
const { error } = await supabase.from("contacts").update({ contact_type: newType }).in("id", ids);
if (error) {
toast.error(error.message);
return;
}
const label = CONTACT_TYPES.find((t) => t.value === newType)?.label ?? newType;
toast.success(`${ids.length} contact${ids.length === 1 ? "" : "s"} changed to ${label}`);
setBulkType("");
clearSelection();
load();
};
const visibleIds = visibleRows.map((r) => r.id);
const allVisibleSelected = visibleIds.length > 0 && visibleIds.every((id) => selected.has(id));
const someVisibleSelected = visibleIds.some((id) => selected.has(id));
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">
<Tabs value={view} onValueChange={(v) => setView(v as "active" | "archived")}>
<TabsList>
<TabsTrigger value="active">Active ({activeCount})</TabsTrigger>
<TabsTrigger value="archived">Archived ({archivedCount})</TabsTrigger>
</TabsList>
</Tabs>
<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>
<div className="mb-4 flex flex-wrap gap-1.5">
<Button
size="sm"
variant={typeFilter === "all" ? "default" : "outline"}
onClick={() => setTypeFilter("all")}
>
All ({typeCounts.all ?? 0})
</Button>
{CONTACT_TYPES.map((t) => (
<Button
key={t.value}
size="sm"
variant={typeFilter === t.value ? "default" : "outline"}
onClick={() => setTypeFilter(t.value)}
>
{t.label} ({typeCounts[t.value] ?? 0})
</Button>
))}
</div>
<div className="mb-4 flex flex-wrap gap-1">
<Button
size="sm"
variant={letter === "all" ? "default" : "outline"}
className="h-8 px-2.5"
onClick={() => setLetter("all")}
>
All ({letterCounts.all ?? 0})
</Button>
{"ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("").concat("#").map((L) => {
const count = letterCounts[L] ?? 0;
const disabled = count === 0;
return (
<Button
key={L}
size="sm"
variant={letter === L ? "default" : "outline"}
className="h-8 w-8 p-0 text-xs"
disabled={disabled}
onClick={() => setLetter(L)}
title={`${L} (${count})`}
>
{L}
</Button>
);
})}
</div>
{selected.size > 0 && (
<Card className="mb-4 border-primary/50 bg-primary/5">
<CardContent className="p-3 flex flex-wrap items-center gap-2">
<span className="text-sm font-medium mr-2">
{selected.size} selected
</span>
<Button size="sm" variant="outline" onClick={() => bulkArchive(view !== "archived")}>
{view === "archived" ? <ArchiveRestore className="h-4 w-4 mr-1.5" /> : <Archive className="h-4 w-4 mr-1.5" />}
{view === "archived" ? "Restore" : "Archive"}
</Button>
<Select value={bulkType} onValueChange={bulkChangeType}>
<SelectTrigger className="h-8 w-48">
<SelectValue placeholder="Change type to…" />
</SelectTrigger>
<SelectContent>
{CONTACT_TYPES.map((t) => (
<SelectItem key={t.value} value={t.value}>{t.label}</SelectItem>
))}
</SelectContent>
</Select>
<Button size="sm" variant="destructive" onClick={bulkDelete}>
<Trash2 className="h-4 w-4 mr-1.5" /> Delete
</Button>
<Button size="sm" variant="ghost" onClick={clearSelection} className="ml-auto">
<X className="h-4 w-4 mr-1.5" /> Clear
</Button>
</CardContent>
</Card>
)}
<Card>
<CardContent className="p-0">
{filtered.length > 0 && !loading && (
<div className="px-4 py-2 border-b flex items-center gap-3 bg-muted/30">
<Checkbox
checked={allVisibleSelected ? true : someVisibleSelected ? "indeterminate" : false}
onCheckedChange={toggleAllVisible}
aria-label="Select all visible"
/>
<span className="text-xs text-muted-foreground">
Showing {visibleRows.length} of {filtered.length}
</span>
</div>
)}
{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." : view === "archived" ? "No archived contacts." : "No contacts match your filters."}
</p>
) : (
<div className="divide-y">
{grouped.map(([letter, items]) => (
<div key={letter}>
<div className="px-4 py-1.5 bg-muted/50 text-xs font-semibold text-muted-foreground">
{letter}
</div>
<ul className="divide-y">
{items.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 ${selected.has(c.id) ? "bg-primary/5" : ""}`}>
<div className="flex items-center gap-3">
<Checkbox
checked={selected.has(c.id)}
onCheckedChange={() => toggleOne(c.id)}
aria-label={`Select ${c.name}`}
/>
<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>
<div className="flex gap-1">
<Button
variant="ghost"
size="icon"
title={c.archived_at ? "Restore" : "Archive"}
onClick={() => onArchive(c.id, !c.archived_at)}
>
{c.archived_at ? <ArchiveRestore className="h-4 w-4" /> : <Archive className="h-4 w-4" />}
</Button>
{canEdit && (
<>
<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>
</div>
))}
</div>
)}
{!loading && hasMore && (
<div className="px-4 py-3 border-t flex items-center justify-center">
<Button variant="outline" size="sm" onClick={() => setVisibleLimit((n) => n + 100)}>
Load 100 more ({filtered.length - visibleRows.length} remaining)
</Button>
</div>
)}
</CardContent>
</Card>
<ContactFormDialog
open={open}
onOpenChange={setOpen}
contact={editing}
onSaved={() => load()}
/>
</PageContainer>
);
}