Co-authored-by: renee-png <262607627+renee-png@users.noreply.github.com>
344 lines
15 KiB
TypeScript
344 lines
15 KiB
TypeScript
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 { Button } from "@/components/ui/button";
|
|
import { Card, CardContent } from "@/components/ui/card";
|
|
import { Badge } from "@/components/ui/badge";
|
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
|
import { supabase } from "@/integrations/supabase/client";
|
|
import { ClientFormDialog } from "@/components/clients/client-form-dialog";
|
|
import { useAuth } from "@/lib/auth";
|
|
import { ArrowLeft, Edit, Plus, Building2, User, MapPin, Mail, Phone, Users, Activity, Briefcase, FileDown, Contact, Receipt, Archive, ArchiveRestore, ListPlus } from "lucide-react";
|
|
import { ContactsLinkTab } from "@/components/contacts/contacts-link-tab";
|
|
import { ClientCustomFieldsTab } from "@/components/clients/client-custom-fields-tab";
|
|
import { formatCurrency, formatDate, formatDateTime, statusBadgeClass } from "@/lib/format";
|
|
import { toast } from "sonner";
|
|
import { downloadStatusReport } from "@/lib/status-pdf";
|
|
import { GenerateInvoiceDialog } from "@/components/invoices/generate-invoice-dialog";
|
|
import { TrustAccountPanel } from "@/components/trust/trust-account-panel";
|
|
import { setArchived } from "@/lib/archive";
|
|
|
|
export const Route = createFileRoute("/clients/$clientId")({
|
|
component: () => (
|
|
<ProtectedLayout>
|
|
<ClientDetail />
|
|
</ProtectedLayout>
|
|
),
|
|
});
|
|
|
|
function ClientDetail() {
|
|
const { clientId } = Route.useParams();
|
|
const navigate = useNavigate();
|
|
const { user, isAdmin } = useAuth();
|
|
const [client, setClient] = useState<any>(null);
|
|
const [cases, setCases] = useState<any[]>([]);
|
|
const [statusEntries, setStatusEntries] = useState<any[]>([]);
|
|
const [loading, setLoading] = useState(true);
|
|
const [editOpen, setEditOpen] = useState(false);
|
|
const [invoiceOpen, setInvoiceOpen] = useState(false);
|
|
|
|
const load = async () => {
|
|
setLoading(true);
|
|
const [{ data: c, error: ce }, { data: cs }] = await Promise.all([
|
|
supabase.from("clients").select("*").eq("id", clientId).maybeSingle(),
|
|
supabase.from("cases").select("id, case_number, title, status, opened_at").eq("client_id", clientId).order("opened_at", { ascending: false }),
|
|
]);
|
|
if (ce) toast.error("Failed to load client", { description: ce.message });
|
|
const caseIds = (cs ?? []).map((x: any) => x.id);
|
|
let totals: Record<string, { hours: number; amount: number }> = {};
|
|
let updates: any[] = [];
|
|
if (caseIds.length) {
|
|
const [{ data: te }, { data: su }] = await Promise.all([
|
|
supabase
|
|
.from("time_entries")
|
|
.select("case_id, hours, hourly_rate, billable")
|
|
.in("case_id", caseIds)
|
|
.eq("billable", true),
|
|
supabase
|
|
.from("status_updates")
|
|
.select("*")
|
|
.in("case_id", caseIds)
|
|
.order("title", { ascending: false }),
|
|
]);
|
|
(te ?? []).forEach((t: any) => {
|
|
const h = Number(t.hours) || 0;
|
|
const r = Number(t.hourly_rate) || 0;
|
|
if (!totals[t.case_id]) totals[t.case_id] = { hours: 0, amount: 0 };
|
|
totals[t.case_id].hours += h;
|
|
totals[t.case_id].amount += h * r;
|
|
});
|
|
const ids = Array.from(new Set((su ?? []).map((d: any) => d.created_by).filter(Boolean)));
|
|
let profileMap: Record<string, any> = {};
|
|
if (ids.length) {
|
|
const { data: profs } = await supabase.from("profiles").select("id, full_name, email").in("id", ids);
|
|
profileMap = Object.fromEntries((profs ?? []).map((p: any) => [p.id, p]));
|
|
}
|
|
const caseMap = Object.fromEntries((cs ?? []).map((x: any) => [x.id, x]));
|
|
updates = (su ?? []).map((d: any) => ({
|
|
...d,
|
|
user: d.created_by ? profileMap[d.created_by] : null,
|
|
case: caseMap[d.case_id],
|
|
}));
|
|
}
|
|
setClient(c);
|
|
setCases((cs ?? []).map((x: any) => ({ ...x, billed: totals[x.id] ?? { hours: 0, amount: 0 } })));
|
|
setStatusEntries(updates);
|
|
setLoading(false);
|
|
};
|
|
|
|
useEffect(() => {
|
|
load();
|
|
}, [clientId]);
|
|
|
|
if (loading) {
|
|
return (
|
|
<PageContainer>
|
|
<p className="text-muted-foreground">Loading…</p>
|
|
</PageContainer>
|
|
);
|
|
}
|
|
|
|
if (!client) {
|
|
return (
|
|
<PageContainer>
|
|
<p className="text-muted-foreground">Client not found.</p>
|
|
<Button variant="outline" className="mt-3" asChild>
|
|
<Link to="/clients"><ArrowLeft className="h-4 w-4 mr-2" /> Back to clients</Link>
|
|
</Button>
|
|
</PageContainer>
|
|
);
|
|
}
|
|
|
|
const Icon =
|
|
client.client_type === "hoa" || client.client_type === "condo" ? Building2 : User;
|
|
const canEdit = isAdmin || client.created_by === user?.id;
|
|
|
|
return (
|
|
<PageContainer>
|
|
<Button variant="ghost" size="sm" asChild className="mb-3 -ml-2">
|
|
<Link to="/clients"><ArrowLeft className="h-4 w-4 mr-1" /> All clients</Link>
|
|
</Button>
|
|
|
|
<PageHeader
|
|
title={client.name}
|
|
description={client.management_company || client.client_type.toUpperCase()}
|
|
actions={
|
|
<>
|
|
{client.archived_at && (
|
|
<Badge variant="outline" className="bg-muted text-muted-foreground">
|
|
<Archive className="h-3 w-3 mr-1" /> Archived
|
|
</Badge>
|
|
)}
|
|
{canEdit && (
|
|
<Button variant="outline" onClick={() => setEditOpen(true)}>
|
|
<Edit className="h-4 w-4 mr-2" /> Edit
|
|
</Button>
|
|
)}
|
|
{canEdit && (
|
|
<Button
|
|
variant="outline"
|
|
onClick={async () => {
|
|
if (await setArchived("clients", client.id, !client.archived_at)) load();
|
|
}}
|
|
>
|
|
{client.archived_at ? (
|
|
<><ArchiveRestore className="h-4 w-4 mr-2" /> Restore</>
|
|
) : (
|
|
<><Archive className="h-4 w-4 mr-2" /> Archive</>
|
|
)}
|
|
</Button>
|
|
)}
|
|
<Button variant="outline" onClick={() => setInvoiceOpen(true)}>
|
|
<Receipt className="h-4 w-4 mr-2" /> Generate invoice
|
|
</Button>
|
|
<Button onClick={() => navigate({ to: "/cases/new", search: { clientId: client.id } })}>
|
|
<Plus className="h-4 w-4 mr-2" /> New case
|
|
</Button>
|
|
</>
|
|
}
|
|
/>
|
|
|
|
<div className="grid lg:grid-cols-3 gap-6">
|
|
<div className="lg:col-span-2 space-y-6">
|
|
<Card className="border-border/60">
|
|
<CardContent className="p-5">
|
|
<div className="flex items-center gap-2 mb-4">
|
|
<Icon className="h-4 w-4 text-muted-foreground" />
|
|
<h3 className="font-serif text-lg">Details</h3>
|
|
</div>
|
|
<dl className="grid grid-cols-2 gap-y-3 gap-x-6 text-sm">
|
|
<DetailRow label="Type" value={client.client_type} />
|
|
{(client.client_type === "hoa" || client.client_type === "condo") && (
|
|
<>
|
|
<DetailRow label="Units" value={client.num_units} />
|
|
<DetailRow label="Management Co." value={client.management_company} />
|
|
<DetailRow
|
|
label="Interest rate"
|
|
value={
|
|
client.annual_interest_rate != null
|
|
? `${client.annual_interest_rate}% per annum`
|
|
: null
|
|
}
|
|
/>
|
|
</>
|
|
)}
|
|
<DetailRow label="Primary contact" value={client.primary_contact_name} />
|
|
<DetailRow label="Email" value={client.primary_contact_email} icon={Mail} />
|
|
<DetailRow label="Phone" value={client.primary_contact_phone} icon={Phone} />
|
|
<DetailRow
|
|
label="Address"
|
|
value={
|
|
[client.address_line1, client.city, client.state, client.postal_code]
|
|
.filter(Boolean)
|
|
.join(", ") || null
|
|
}
|
|
icon={MapPin}
|
|
/>
|
|
</dl>
|
|
{client.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">{client.notes}</p>
|
|
</div>
|
|
)}
|
|
</CardContent>
|
|
</Card>
|
|
|
|
{(client.client_type === "hoa" || client.client_type === "condo") && client.board_members?.length > 0 && (
|
|
<Card className="border-border/60">
|
|
<CardContent className="p-5">
|
|
<div className="flex items-center gap-2 mb-3">
|
|
<Users className="h-4 w-4 text-muted-foreground" />
|
|
<h3 className="font-serif text-lg">Board members</h3>
|
|
</div>
|
|
<div className="divide-y">
|
|
{client.board_members.map((m: any, i: number) => (
|
|
<div key={i} className="py-2.5 flex flex-wrap items-baseline gap-x-4 gap-y-1 text-sm">
|
|
<span className="font-medium">{m.name}</span>
|
|
{m.role && <span className="text-xs uppercase tracking-wider text-muted-foreground">{m.role}</span>}
|
|
{m.email && <span className="text-muted-foreground">{m.email}</span>}
|
|
{m.phone && <span className="text-muted-foreground">{m.phone}</span>}
|
|
</div>
|
|
))}
|
|
</div>
|
|
</CardContent>
|
|
</Card>
|
|
)}
|
|
|
|
<TrustAccountPanel clientId={clientId} />
|
|
</div>
|
|
|
|
<Card className="border-border/60 h-fit">
|
|
<CardContent className="p-5">
|
|
<Tabs defaultValue="cases">
|
|
<TabsList className="mb-3 w-full">
|
|
<TabsTrigger value="cases" className="flex-1"><Briefcase className="h-3.5 w-3.5 mr-1.5" />Cases</TabsTrigger>
|
|
<TabsTrigger value="status" className="flex-1"><Activity className="h-3.5 w-3.5 mr-1.5" />Status</TabsTrigger>
|
|
<TabsTrigger value="contacts" className="flex-1"><Contact className="h-3.5 w-3.5 mr-1.5" />Contacts</TabsTrigger>
|
|
<TabsTrigger value="custom" className="flex-1"><ListPlus className="h-3.5 w-3.5 mr-1.5" />Fields</TabsTrigger>
|
|
</TabsList>
|
|
|
|
<TabsContent value="cases">
|
|
{cases.length === 0 && <p className="text-sm text-muted-foreground">No cases yet.</p>}
|
|
<div className="space-y-1">
|
|
{cases.map((c) => (
|
|
<Link
|
|
key={c.id}
|
|
to="/cases/$caseId"
|
|
params={{ caseId: c.id }}
|
|
className="block p-2.5 rounded-md hover:bg-muted/60 -mx-2"
|
|
>
|
|
<div className="flex items-center justify-between gap-2">
|
|
<span className="text-sm font-medium truncate">{c.title}</span>
|
|
<Badge variant="outline" className={`text-[10px] ${statusBadgeClass(c.status)}`}>
|
|
{c.status.replace("_", " ")}
|
|
</Badge>
|
|
</div>
|
|
<div className="text-xs text-muted-foreground">
|
|
{c.case_number} · opened {formatDate(c.opened_at)}
|
|
</div>
|
|
<div className="text-xs text-muted-foreground mt-0.5">
|
|
Billed: {c.billed.hours.toFixed(1)} hr · {formatCurrency(c.billed.amount)}
|
|
</div>
|
|
</Link>
|
|
))}
|
|
</div>
|
|
</TabsContent>
|
|
|
|
<TabsContent value="status">
|
|
<div className="flex items-center justify-between mb-3">
|
|
<p className="text-xs text-muted-foreground">{statusEntries.length} update{statusEntries.length === 1 ? "" : "s"} across all cases</p>
|
|
<Button
|
|
size="sm"
|
|
variant="outline"
|
|
disabled={statusEntries.length === 0}
|
|
onClick={() => {
|
|
downloadStatusReport({
|
|
title: "Client Status Report",
|
|
subtitle: client.name,
|
|
groupByCase: true,
|
|
entries: statusEntries.map((u) => ({
|
|
title: u.title,
|
|
body: u.body,
|
|
created_at: u.created_at,
|
|
author_name: u.user?.full_name,
|
|
author_email: u.user?.email,
|
|
case_number: u.case?.case_number,
|
|
case_title: u.case?.title,
|
|
})),
|
|
}, `status-report-${client.name.replace(/[^a-z0-9]+/gi, "-")}.pdf`);
|
|
}}
|
|
>
|
|
<FileDown className="h-3.5 w-3.5 mr-1.5" /> Export
|
|
</Button>
|
|
</div>
|
|
{statusEntries.length === 0 && <p className="text-sm text-muted-foreground">No status updates logged.</p>}
|
|
<div className="space-y-3 max-h-[480px] overflow-auto">
|
|
{statusEntries.map((u) => (
|
|
<div key={u.id} className="border-l-2 border-primary/40 pl-3 py-1">
|
|
<div className="text-sm font-medium">{formatDateTime(u.title)}</div>
|
|
<div className="text-[11px] text-muted-foreground mb-1">
|
|
{u.case?.case_number} · {u.user?.full_name || u.user?.email || "Unknown"}
|
|
</div>
|
|
<p className="text-xs text-muted-foreground line-clamp-3 whitespace-pre-wrap">{u.body}</p>
|
|
</div>
|
|
))}
|
|
</div>
|
|
</TabsContent>
|
|
|
|
<TabsContent value="contacts">
|
|
<ContactsLinkTab parentId={clientId} parentTable="client_contacts" />
|
|
</TabsContent>
|
|
|
|
<TabsContent value="custom">
|
|
<ClientCustomFieldsTab clientId={clientId} />
|
|
</TabsContent>
|
|
</Tabs>
|
|
</CardContent>
|
|
</Card>
|
|
</div>
|
|
|
|
<ClientFormDialog open={editOpen} onOpenChange={setEditOpen} client={client} onSaved={load} />
|
|
<GenerateInvoiceDialog
|
|
open={invoiceOpen}
|
|
onOpenChange={setInvoiceOpen}
|
|
clientId={client.id}
|
|
clientName={client.name}
|
|
/>
|
|
</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>
|
|
</>
|
|
);
|
|
}
|