Changes
Co-authored-by: renee-png <262607627+renee-png@users.noreply.github.com>
This commit is contained in:
co-authored by
renee-png
parent
c1cd4f415b
commit
09d4acd58a
@@ -0,0 +1,362 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { z } from "zod";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { supabase } from "@/integrations/supabase/client";
|
||||
import { useAuth } from "@/lib/auth";
|
||||
import { Loader2, Plus, Trash2 } from "lucide-react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
const boardMember = z.object({
|
||||
name: z.string().trim().min(1, "Required").max(120),
|
||||
role: z.string().trim().max(60).optional().or(z.literal("")),
|
||||
email: z.string().trim().email("Invalid email").max(255).optional().or(z.literal("")),
|
||||
phone: z.string().trim().max(40).optional().or(z.literal("")),
|
||||
});
|
||||
|
||||
const schema = z.object({
|
||||
client_type: z.enum(["hoa", "individual", "business"]),
|
||||
name: z.string().trim().min(1, "Required").max(200),
|
||||
primary_contact_name: z.string().trim().max(120).optional().or(z.literal("")),
|
||||
primary_contact_email: z.string().trim().email("Invalid email").max(255).optional().or(z.literal("")),
|
||||
primary_contact_phone: z.string().trim().max(40).optional().or(z.literal("")),
|
||||
address_line1: z.string().trim().max(200).optional().or(z.literal("")),
|
||||
city: z.string().trim().max(100).optional().or(z.literal("")),
|
||||
state: z.string().trim().max(60).optional().or(z.literal("")),
|
||||
postal_code: z.string().trim().max(20).optional().or(z.literal("")),
|
||||
management_company: z.string().trim().max(200).optional().or(z.literal("")),
|
||||
num_units: z.coerce.number().int().min(0).max(100000).optional().or(z.literal("").transform(() => undefined)),
|
||||
board_members: z.array(boardMember),
|
||||
notes: z.string().trim().max(5000).optional().or(z.literal("")),
|
||||
});
|
||||
|
||||
type FormValues = z.infer<typeof schema>;
|
||||
|
||||
export function ClientFormDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
onSaved,
|
||||
client,
|
||||
}: {
|
||||
open: boolean;
|
||||
onOpenChange: (v: boolean) => void;
|
||||
onSaved?: () => void;
|
||||
client?: any;
|
||||
}) {
|
||||
const { user } = useAuth();
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
const form = useForm<FormValues>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: {
|
||||
client_type: "hoa",
|
||||
name: "",
|
||||
primary_contact_name: "",
|
||||
primary_contact_email: "",
|
||||
primary_contact_phone: "",
|
||||
address_line1: "",
|
||||
city: "",
|
||||
state: "",
|
||||
postal_code: "",
|
||||
management_company: "",
|
||||
num_units: undefined as any,
|
||||
board_members: [],
|
||||
notes: "",
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
form.reset({
|
||||
client_type: client?.client_type ?? "hoa",
|
||||
name: client?.name ?? "",
|
||||
primary_contact_name: client?.primary_contact_name ?? "",
|
||||
primary_contact_email: client?.primary_contact_email ?? "",
|
||||
primary_contact_phone: client?.primary_contact_phone ?? "",
|
||||
address_line1: client?.address_line1 ?? "",
|
||||
city: client?.city ?? "",
|
||||
state: client?.state ?? "",
|
||||
postal_code: client?.postal_code ?? "",
|
||||
management_company: client?.management_company ?? "",
|
||||
num_units: client?.num_units ?? (undefined as any),
|
||||
board_members: client?.board_members ?? [],
|
||||
notes: client?.notes ?? "",
|
||||
});
|
||||
}
|
||||
}, [open, client, form]);
|
||||
|
||||
const clientType = form.watch("client_type");
|
||||
const board = form.watch("board_members");
|
||||
|
||||
const addBoardMember = () => {
|
||||
form.setValue("board_members", [...board, { name: "", role: "", email: "", phone: "" }]);
|
||||
};
|
||||
const removeBoardMember = (idx: number) => {
|
||||
form.setValue("board_members", board.filter((_, i) => i !== idx));
|
||||
};
|
||||
|
||||
const onSubmit = async (values: FormValues) => {
|
||||
setSubmitting(true);
|
||||
const payload: any = {
|
||||
...values,
|
||||
num_units: values.num_units || null,
|
||||
// strip empty strings to nulls
|
||||
...Object.fromEntries(
|
||||
Object.entries(values).map(([k, v]) => [k, v === "" ? null : v]),
|
||||
),
|
||||
};
|
||||
payload.board_members = values.board_members;
|
||||
if (!client) payload.created_by = user?.id;
|
||||
|
||||
const { error } = client
|
||||
? await supabase.from("clients").update(payload).eq("id", client.id)
|
||||
: await supabase.from("clients").insert(payload);
|
||||
|
||||
setSubmitting(false);
|
||||
if (error) {
|
||||
toast.error("Could not save client", { description: error.message });
|
||||
return;
|
||||
}
|
||||
toast.success(client ? "Client updated" : "Client created");
|
||||
onOpenChange(false);
|
||||
onSaved?.();
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="font-serif">{client ? "Edit client" : "New client"}</DialogTitle>
|
||||
<DialogDescription>
|
||||
HOA associations support board members and management companies. Other client types only show
|
||||
relevant fields.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<Form {...form}>
|
||||
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="client_type"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Type</FormLabel>
|
||||
<Select value={field.value} onValueChange={field.onChange}>
|
||||
<FormControl>
|
||||
<SelectTrigger><SelectValue /></SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
<SelectItem value="hoa">HOA / Association</SelectItem>
|
||||
<SelectItem value="business">Business</SelectItem>
|
||||
<SelectItem value="individual">Individual</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>{clientType === "hoa" ? "Association name" : "Name"}</FormLabel>
|
||||
<FormControl><Input {...field} /></FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{clientType === "hoa" && (
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="management_company"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Management company</FormLabel>
|
||||
<FormControl><Input {...field} /></FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="num_units"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel># of units</FormLabel>
|
||||
<FormControl>
|
||||
<Input type="number" min={0} {...field} value={field.value ?? ""} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="primary_contact_name"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Primary contact</FormLabel>
|
||||
<FormControl><Input {...field} /></FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="primary_contact_email"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Email</FormLabel>
|
||||
<FormControl><Input type="email" {...field} /></FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="primary_contact_phone"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Phone</FormLabel>
|
||||
<FormControl><Input {...field} /></FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="address_line1"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Address</FormLabel>
|
||||
<FormControl><Input {...field} /></FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
<FormField control={form.control} name="city" render={({ field }) => (
|
||||
<FormItem><FormLabel>City</FormLabel><FormControl><Input {...field} /></FormControl><FormMessage /></FormItem>
|
||||
)} />
|
||||
<FormField control={form.control} name="state" render={({ field }) => (
|
||||
<FormItem><FormLabel>State</FormLabel><FormControl><Input {...field} /></FormControl><FormMessage /></FormItem>
|
||||
)} />
|
||||
<FormField control={form.control} name="postal_code" render={({ field }) => (
|
||||
<FormItem><FormLabel>Zip</FormLabel><FormControl><Input {...field} /></FormControl><FormMessage /></FormItem>
|
||||
)} />
|
||||
</div>
|
||||
|
||||
{clientType === "hoa" && (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<label className="text-sm font-medium">Board members</label>
|
||||
<Button type="button" variant="outline" size="sm" onClick={addBoardMember}>
|
||||
<Plus className="h-3 w-3 mr-1" /> Add member
|
||||
</Button>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
{board.length === 0 && (
|
||||
<p className="text-xs text-muted-foreground italic">No board members yet.</p>
|
||||
)}
|
||||
{board.map((_, idx) => (
|
||||
<div key={idx} className="grid grid-cols-12 gap-2 items-start p-3 border rounded-md bg-muted/30">
|
||||
<Input
|
||||
className="col-span-3"
|
||||
placeholder="Name"
|
||||
value={board[idx].name}
|
||||
onChange={(e) => {
|
||||
const next = [...board];
|
||||
next[idx].name = e.target.value;
|
||||
form.setValue("board_members", next);
|
||||
}}
|
||||
/>
|
||||
<Input
|
||||
className="col-span-2"
|
||||
placeholder="Role"
|
||||
value={board[idx].role}
|
||||
onChange={(e) => {
|
||||
const next = [...board];
|
||||
next[idx].role = e.target.value;
|
||||
form.setValue("board_members", next);
|
||||
}}
|
||||
/>
|
||||
<Input
|
||||
className="col-span-3"
|
||||
placeholder="Email"
|
||||
type="email"
|
||||
value={board[idx].email}
|
||||
onChange={(e) => {
|
||||
const next = [...board];
|
||||
next[idx].email = e.target.value;
|
||||
form.setValue("board_members", next);
|
||||
}}
|
||||
/>
|
||||
<Input
|
||||
className="col-span-3"
|
||||
placeholder="Phone"
|
||||
value={board[idx].phone}
|
||||
onChange={(e) => {
|
||||
const next = [...board];
|
||||
next[idx].phone = e.target.value;
|
||||
form.setValue("board_members", next);
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="col-span-1"
|
||||
onClick={() => removeBoardMember(idx)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 text-destructive" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name="notes"
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Notes</FormLabel>
|
||||
<FormControl><Textarea rows={3} {...field} /></FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={submitting}>
|
||||
{submitting && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||
{client ? "Save changes" : "Create client"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
+21
-3
@@ -12,6 +12,7 @@ import { Route as rootRouteImport } from './routes/__root'
|
||||
import { Route as SetupRouteImport } from './routes/setup'
|
||||
import { Route as LoginRouteImport } from './routes/login'
|
||||
import { Route as IndexRouteImport } from './routes/index'
|
||||
import { Route as ClientsIndexRouteImport } from './routes/clients.index'
|
||||
|
||||
const SetupRoute = SetupRouteImport.update({
|
||||
id: '/setup',
|
||||
@@ -28,35 +29,44 @@ const IndexRoute = IndexRouteImport.update({
|
||||
path: '/',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const ClientsIndexRoute = ClientsIndexRouteImport.update({
|
||||
id: '/clients/',
|
||||
path: '/clients/',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
|
||||
export interface FileRoutesByFullPath {
|
||||
'/': typeof IndexRoute
|
||||
'/login': typeof LoginRoute
|
||||
'/setup': typeof SetupRoute
|
||||
'/clients/': typeof ClientsIndexRoute
|
||||
}
|
||||
export interface FileRoutesByTo {
|
||||
'/': typeof IndexRoute
|
||||
'/login': typeof LoginRoute
|
||||
'/setup': typeof SetupRoute
|
||||
'/clients': typeof ClientsIndexRoute
|
||||
}
|
||||
export interface FileRoutesById {
|
||||
__root__: typeof rootRouteImport
|
||||
'/': typeof IndexRoute
|
||||
'/login': typeof LoginRoute
|
||||
'/setup': typeof SetupRoute
|
||||
'/clients/': typeof ClientsIndexRoute
|
||||
}
|
||||
export interface FileRouteTypes {
|
||||
fileRoutesByFullPath: FileRoutesByFullPath
|
||||
fullPaths: '/' | '/login' | '/setup'
|
||||
fullPaths: '/' | '/login' | '/setup' | '/clients/'
|
||||
fileRoutesByTo: FileRoutesByTo
|
||||
to: '/' | '/login' | '/setup'
|
||||
id: '__root__' | '/' | '/login' | '/setup'
|
||||
to: '/' | '/login' | '/setup' | '/clients'
|
||||
id: '__root__' | '/' | '/login' | '/setup' | '/clients/'
|
||||
fileRoutesById: FileRoutesById
|
||||
}
|
||||
export interface RootRouteChildren {
|
||||
IndexRoute: typeof IndexRoute
|
||||
LoginRoute: typeof LoginRoute
|
||||
SetupRoute: typeof SetupRoute
|
||||
ClientsIndexRoute: typeof ClientsIndexRoute
|
||||
}
|
||||
|
||||
declare module '@tanstack/react-router' {
|
||||
@@ -82,6 +92,13 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof IndexRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/clients/': {
|
||||
id: '/clients/'
|
||||
path: '/clients'
|
||||
fullPath: '/clients/'
|
||||
preLoaderRoute: typeof ClientsIndexRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,6 +106,7 @@ const rootRouteChildren: RootRouteChildren = {
|
||||
IndexRoute: IndexRoute,
|
||||
LoginRoute: LoginRoute,
|
||||
SetupRoute: SetupRoute,
|
||||
ClientsIndexRoute: ClientsIndexRoute,
|
||||
}
|
||||
export const routeTree = rootRouteImport
|
||||
._addFileChildren(rootRouteChildren)
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import { createFileRoute, Link } 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 { Input } from "@/components/ui/input";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { supabase } from "@/integrations/supabase/client";
|
||||
import { ClientFormDialog } from "@/components/clients/client-form-dialog";
|
||||
import { Plus, Search, Building2, User, Briefcase as Building } from "lucide-react";
|
||||
import { formatDate } from "@/lib/format";
|
||||
|
||||
export const Route = createFileRoute("/clients/")({
|
||||
component: () => (
|
||||
<ProtectedLayout>
|
||||
<ClientsList />
|
||||
</ProtectedLayout>
|
||||
),
|
||||
});
|
||||
|
||||
function ClientsList() {
|
||||
const [clients, setClients] = useState<any[]>([]);
|
||||
const [q, setQ] = useState("");
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
const load = async () => {
|
||||
const { data } = await supabase
|
||||
.from("clients")
|
||||
.select("*")
|
||||
.order("name", { ascending: true });
|
||||
setClients(data ?? []);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, []);
|
||||
|
||||
const filtered = clients.filter((c) =>
|
||||
[c.name, c.management_company, c.primary_contact_name, c.primary_contact_email]
|
||||
.filter(Boolean)
|
||||
.join(" ")
|
||||
.toLowerCase()
|
||||
.includes(q.toLowerCase()),
|
||||
);
|
||||
|
||||
const typeIcon = (t: string) =>
|
||||
t === "hoa" ? Building2 : t === "business" ? Building : User;
|
||||
|
||||
return (
|
||||
<PageContainer>
|
||||
<PageHeader
|
||||
title="Clients"
|
||||
description="HOA associations, businesses, and individual clients."
|
||||
actions={
|
||||
<Button onClick={() => setOpen(true)}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
New client
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
|
||||
<div className="relative mb-4 max-w-sm">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
placeholder="Search by name, contact, manager…"
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Card className="border-border/60 overflow-hidden">
|
||||
<CardContent className="p-0">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-muted/50 text-xs uppercase tracking-wider text-muted-foreground">
|
||||
<tr>
|
||||
<th className="text-left px-4 py-3 font-medium">Name</th>
|
||||
<th className="text-left px-4 py-3 font-medium">Type</th>
|
||||
<th className="text-left px-4 py-3 font-medium">Contact</th>
|
||||
<th className="text-left px-4 py-3 font-medium">Units</th>
|
||||
<th className="text-left px-4 py-3 font-medium">Created</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{filtered.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={5} className="text-center py-12 text-muted-foreground">
|
||||
{clients.length === 0 ? "No clients yet. Add your first one." : "No matches."}
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
{filtered.map((c) => {
|
||||
const Icon = typeIcon(c.client_type);
|
||||
return (
|
||||
<tr key={c.id} className="border-t hover:bg-muted/30 transition-colors">
|
||||
<td className="px-4 py-3">
|
||||
<Link
|
||||
to="/clients/$clientId"
|
||||
params={{ clientId: c.id }}
|
||||
className="flex items-center gap-2 font-medium text-foreground hover:text-primary"
|
||||
>
|
||||
<Icon className="h-4 w-4 text-muted-foreground" />
|
||||
{c.name}
|
||||
</Link>
|
||||
{c.management_company && (
|
||||
<div className="text-xs text-muted-foreground ml-6">{c.management_company}</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<Badge variant="outline" className="capitalize">{c.client_type}</Badge>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">
|
||||
{c.primary_contact_name || "—"}
|
||||
{c.primary_contact_email && (
|
||||
<div className="text-xs">{c.primary_contact_email}</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">{c.num_units ?? "—"}</td>
|
||||
<td className="px-4 py-3 text-muted-foreground">{formatDate(c.created_at)}</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<ClientFormDialog open={open} onOpenChange={setOpen} onSaved={load} />
|
||||
</PageContainer>
|
||||
);
|
||||
}
|
||||
+144
-19
@@ -1,26 +1,151 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
import { createFileRoute, Link } 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, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { supabase } from "@/integrations/supabase/client";
|
||||
import { useAuth } from "@/lib/auth";
|
||||
import { Briefcase, Users, Receipt, Clock, ArrowRight } from "lucide-react";
|
||||
import { formatCurrency, formatDate, statusBadgeClass } from "@/lib/format";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
export const Route = createFileRoute("/")({
|
||||
component: Index,
|
||||
component: () => (
|
||||
<ProtectedLayout>
|
||||
<Dashboard />
|
||||
</ProtectedLayout>
|
||||
),
|
||||
});
|
||||
|
||||
// IMPORTANT: Replace this placeholder. For sites with multiple pages (About, Services, Contact, etc.),
|
||||
// create separate route files (about.tsx, services.tsx, contact.tsx) — don't put all pages in this file.
|
||||
function PlaceholderIndex() {
|
||||
return (
|
||||
<div
|
||||
className="flex min-h-screen items-center justify-center"
|
||||
style={{ backgroundColor: "#fcfbf8" }}
|
||||
>
|
||||
<img
|
||||
data-lovable-blank-page-placeholder="REMOVE_THIS"
|
||||
src="https://cdn.gpteng.co/blank-app-v1.svg"
|
||||
alt="Your app will live here!"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
interface Stats {
|
||||
activeCases: number;
|
||||
clients: number;
|
||||
unpaidInvoices: number;
|
||||
unbilledHours: number;
|
||||
}
|
||||
|
||||
function Index() {
|
||||
return <PlaceholderIndex />;
|
||||
function Dashboard() {
|
||||
const { user } = useAuth();
|
||||
const [stats, setStats] = useState<Stats>({ activeCases: 0, clients: 0, unpaidInvoices: 0, unbilledHours: 0 });
|
||||
const [recentCases, setRecentCases] = useState<any[]>([]);
|
||||
const [recentInvoices, setRecentInvoices] = useState<any[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
(async () => {
|
||||
const [casesRes, clientsRes, invoicesRes, timeRes, recentCasesRes, recentInvRes] = await Promise.all([
|
||||
supabase.from("cases").select("id", { count: "exact", head: true }).in("status", ["intake", "active", "on_hold"]),
|
||||
supabase.from("clients").select("id", { count: "exact", head: true }),
|
||||
supabase.from("invoices").select("total, amount_paid").in("status", ["sent", "overdue"]),
|
||||
supabase.from("time_entries").select("hours").is("invoice_id", null).eq("billable", true),
|
||||
supabase.from("cases").select("id, case_number, title, status, updated_at, client:clients(name)").order("updated_at", { ascending: false }).limit(5),
|
||||
supabase.from("invoices").select("id, invoice_number, total, status, issue_date, client:clients(name)").order("created_at", { ascending: false }).limit(5),
|
||||
]);
|
||||
|
||||
const unpaid = (invoicesRes.data ?? []).reduce(
|
||||
(sum, i) => sum + (Number(i.total) - Number(i.amount_paid)),
|
||||
0,
|
||||
);
|
||||
const hours = (timeRes.data ?? []).reduce((s, t) => s + Number(t.hours), 0);
|
||||
|
||||
setStats({
|
||||
activeCases: casesRes.count ?? 0,
|
||||
clients: clientsRes.count ?? 0,
|
||||
unpaidInvoices: unpaid,
|
||||
unbilledHours: hours,
|
||||
});
|
||||
setRecentCases(recentCasesRes.data ?? []);
|
||||
setRecentInvoices(recentInvRes.data ?? []);
|
||||
})();
|
||||
}, [user?.id]);
|
||||
|
||||
const cards = [
|
||||
{ label: "Active cases", value: stats.activeCases, icon: Briefcase, to: "/cases" },
|
||||
{ label: "Clients", value: stats.clients, icon: Users, to: "/clients" },
|
||||
{ label: "Unbilled hours", value: stats.unbilledHours.toFixed(1), icon: Clock, to: "/cases" },
|
||||
{ label: "Outstanding A/R", value: formatCurrency(stats.unpaidInvoices), icon: Receipt, to: "/invoices" },
|
||||
];
|
||||
|
||||
return (
|
||||
<PageContainer>
|
||||
<PageHeader title="Dashboard" description="Practice snapshot and recent activity." />
|
||||
|
||||
<div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
|
||||
{cards.map((c) => (
|
||||
<Link key={c.label} to={c.to} className="group">
|
||||
<Card className="border-border/60 hover:border-primary/40 transition-colors">
|
||||
<CardContent className="p-5">
|
||||
<div className="flex items-start justify-between mb-3">
|
||||
<div className="text-xs uppercase tracking-wider text-muted-foreground">{c.label}</div>
|
||||
<c.icon className="h-4 w-4 text-muted-foreground group-hover:text-primary" />
|
||||
</div>
|
||||
<div className="font-serif text-3xl text-foreground">{c.value}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="grid lg:grid-cols-2 gap-6">
|
||||
<Card className="border-border/60">
|
||||
<CardHeader className="flex flex-row items-center justify-between">
|
||||
<CardTitle className="font-serif text-lg">Recent cases</CardTitle>
|
||||
<Button asChild variant="ghost" size="sm">
|
||||
<Link to="/cases">View all <ArrowRight className="h-3 w-3 ml-1" /></Link>
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-1">
|
||||
{recentCases.length === 0 && <p className="text-sm text-muted-foreground">No cases yet.</p>}
|
||||
{recentCases.map((c) => (
|
||||
<Link
|
||||
key={c.id}
|
||||
to="/cases/$caseId"
|
||||
params={{ caseId: c.id }}
|
||||
className="flex items-center justify-between py-2.5 px-2 rounded-md hover:bg-muted/60 -mx-2"
|
||||
>
|
||||
<div className="min-w-0">
|
||||
<div className="text-sm font-medium truncate">{c.title}</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{c.case_number} · {c.client?.name}
|
||||
</div>
|
||||
</div>
|
||||
<Badge variant="outline" className={statusBadgeClass(c.status)}>{c.status.replace("_", " ")}</Badge>
|
||||
</Link>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="border-border/60">
|
||||
<CardHeader className="flex flex-row items-center justify-between">
|
||||
<CardTitle className="font-serif text-lg">Recent invoices</CardTitle>
|
||||
<Button asChild variant="ghost" size="sm">
|
||||
<Link to="/invoices">View all <ArrowRight className="h-3 w-3 ml-1" /></Link>
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-1">
|
||||
{recentInvoices.length === 0 && <p className="text-sm text-muted-foreground">No invoices yet.</p>}
|
||||
{recentInvoices.map((i) => (
|
||||
<Link
|
||||
key={i.id}
|
||||
to="/invoices/$invoiceId"
|
||||
params={{ invoiceId: i.id }}
|
||||
className="flex items-center justify-between py-2.5 px-2 rounded-md hover:bg-muted/60 -mx-2"
|
||||
>
|
||||
<div className="min-w-0">
|
||||
<div className="text-sm font-medium">{i.invoice_number}</div>
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{i.client?.name} · {formatDate(i.issue_date)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium">{formatCurrency(i.total)}</span>
|
||||
<Badge variant="outline" className={statusBadgeClass(i.status)}>{i.status}</Badge>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</PageContainer>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user