feat(14-02): rewrite LeadTable as raw-table database view (CRM-08/09)

Replace shadcn Table-based read-only LeadTable with an Attio-style raw
table database view (1:1 structural port of ServiceTable.tsx):
- EditableCell for name/email/phone/company/next_action, persisted via
  updateLeadField
- Local StatusCell: closed click-to-open dropdown over the 6 fixed
  LEAD_STAGES values, preserving semantic STAGE_COLOR badges (won=green,
  lost=red, etc.) without modifying shared option-select.tsx
- OptionMultiSelect for lead tags, wired to addLeadTag/removeLeadTag/
  renameLeadTag
- Per-row error display and "Nessun lead trovato" empty state
This commit is contained in:
2026-06-14 13:21:23 +02:00
parent 39bd1ce2eb
commit 4887a319f7
+213 -53
View File
@@ -1,20 +1,21 @@
"use client"; "use client";
import Link from "next/link"; import Link from "next/link";
import { Lead } from "@/db/schema"; import { useState, useRef, useEffect, useTransition } from "react";
import { import { useRouter } from "next/navigation";
Table, import { Check } from "lucide-react";
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { formatDistanceToNow } from "date-fns"; import { EditableCell } from "@/components/ui/editable-cell";
import { it } from "date-fns/locale"; import { OptionMultiSelect } from "@/components/ui/option-multi-select";
import { LEAD_STAGES } from "@/lib/lead-validators"; import {
updateLeadField,
addLeadTag,
removeLeadTag,
renameLeadTag,
} from "@/app/admin/leads/actions";
import type { LeadWithTags, LeadFieldOptions } from "@/lib/admin-queries";
import { cn } from "@/lib/utils";
const STAGE_COLOR: Record<string, string> = { const STAGE_COLOR: Record<string, string> = {
contacted: "bg-blue-100 text-blue-800", contacted: "bg-blue-100 text-blue-800",
@@ -25,54 +26,213 @@ const STAGE_COLOR: Record<string, string> = {
lost: "bg-red-100 text-red-800", lost: "bg-red-100 text-red-800",
}; };
export function LeadTable({ leads }: { leads: Lead[] }) { const COLUMN_HEADERS = [
"Nome",
"Email",
"Telefono",
"Azienda",
"Stato",
"Prossima Azione",
"Tag",
"Azioni",
];
const COL_COUNT = COLUMN_HEADERS.length;
function StatusCell({
lead,
options,
run,
}: {
lead: LeadWithTags;
options: LeadFieldOptions;
run: (fn: () => Promise<unknown>) => void;
}) {
const [isOpen, setIsOpen] = useState(false);
const containerRef = useRef<HTMLDivElement>(null);
useEffect(() => {
function handleClickOutside(e: MouseEvent) {
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
setIsOpen(false);
}
}
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
return ( return (
<div className="border rounded-lg overflow-hidden bg-white"> <div ref={containerRef} className="relative w-full min-w-[120px]">
<Table> <div
<TableHeader> onClick={() => setIsOpen((v) => !v)}
<TableRow> className="flex items-center gap-1 px-2 py-1 rounded transition-colors duration-150 min-h-[28px] cursor-pointer hover:bg-[#f0f0f0]"
<TableHead>Nome</TableHead> >
<TableHead>Email</TableHead> <Badge
<TableHead>Azienda</TableHead> variant="outline"
<TableHead>Stato</TableHead> className={cn(
<TableHead>Ultimo Contatto</TableHead> STAGE_COLOR[lead.status] ?? "",
<TableHead>Prossima Azione</TableHead> "border-transparent text-xs px-2 py-0.5 font-medium truncate"
<TableHead></TableHead> )}
</TableRow> >
</TableHeader>
<TableBody>
{leads.map((lead) => (
<TableRow key={lead.id}>
<TableCell className="font-medium">
<Link href={`/admin/leads/${lead.id}`} className="hover:underline">
{lead.name}
</Link>
</TableCell>
<TableCell>{lead.email || "—"}</TableCell>
<TableCell>{lead.company || "—"}</TableCell>
<TableCell>
<Badge className={STAGE_COLOR[lead.status as keyof typeof STAGE_COLOR] || ""}>
{lead.status.replace(/_/g, " ")} {lead.status.replace(/_/g, " ")}
</Badge> </Badge>
</TableCell> </div>
<TableCell> {isOpen && (
{lead.last_contact_date <div className="absolute top-full left-0 mt-1 bg-white border border-[#e5e7eb] rounded-md shadow-md p-1.5 z-20 min-w-[180px]">
? formatDistanceToNow(new Date(lead.last_contact_date), { <div className="flex flex-col gap-0.5">
addSuffix: true, {options.status.map((stage) => (
locale: it, <button
}) key={stage}
: "—"} type="button"
</TableCell> onClick={() => {
<TableCell className="text-sm">{lead.next_action || "—"}</TableCell> setIsOpen(false);
<TableCell> run(() => updateLeadField(lead.id, "status", stage));
}}
className="flex items-center gap-2 rounded px-1.5 py-1 hover:bg-[#f5f5f5] text-left"
>
<span className="w-3.5 flex-shrink-0">
{lead.status === stage && <Check className="h-3.5 w-3.5 text-[#1A463C]" />}
</span>
<Badge
variant="outline"
className={cn(STAGE_COLOR[stage] ?? "", "border-transparent text-xs px-2 py-0.5 font-medium truncate")}
>
{stage.replace(/_/g, " ")}
</Badge>
</button>
))}
</div>
</div>
)}
</div>
);
}
function LeadRow({
lead,
options,
}: {
lead: LeadWithTags;
options: LeadFieldOptions;
}) {
const router = useRouter();
const [, startTransition] = useTransition();
const [error, setError] = useState<string | null>(null);
function run(fn: () => Promise<unknown>) {
setError(null);
startTransition(async () => {
try {
await fn();
router.refresh();
} catch (e) {
setError(e instanceof Error ? e.message : "Errore nel salvataggio");
}
});
}
return (
<>
<tr className="border-b border-[#e5e7eb] hover:bg-[#f9f9f9] transition-colors duration-150">
<td className="py-2 px-3 font-medium text-[#1a1a1a] min-w-[160px]">
<EditableCell
value={lead.name}
type="text"
required
onSave={(v) => run(() => updateLeadField(lead.id, "name", v))}
/>
</td>
<td className="py-2 px-3 min-w-[160px]">
<EditableCell
value={lead.email ?? ""}
type="text"
placeholder="email@esempio.com"
onSave={(v) => run(() => updateLeadField(lead.id, "email", v))}
/>
</td>
<td className="py-2 px-3 min-w-[140px]">
<EditableCell
value={lead.phone ?? ""}
type="text"
placeholder="+39 3XX XXXXXXX"
onSave={(v) => run(() => updateLeadField(lead.id, "phone", v))}
/>
</td>
<td className="py-2 px-3 min-w-[140px]">
<EditableCell
value={lead.company ?? ""}
type="text"
placeholder="Nome azienda"
onSave={(v) => run(() => updateLeadField(lead.id, "company", v))}
/>
</td>
<td className="py-2 px-3 min-w-[120px]">
<StatusCell lead={lead} options={options} run={run} />
</td>
<td className="py-2 px-3 min-w-[180px]">
<EditableCell
value={lead.next_action ?? ""}
type="text"
placeholder="Prossima azione..."
onSave={(v) => run(() => updateLeadField(lead.id, "next_action", v))}
/>
</td>
<td className="py-2 px-3 min-w-[180px]">
<OptionMultiSelect
values={lead.tags}
options={options.tags}
onAdd={(v) => run(() => addLeadTag(lead.id, v))}
onRemove={(v) => run(() => removeLeadTag(lead.id, v))}
onRename={(o, n) => run(() => renameLeadTag(o, n))}
/>
</td>
<td className="py-2 px-3 min-w-[80px]">
<Button variant="ghost" size="sm" asChild> <Button variant="ghost" size="sm" asChild>
<Link href={`/admin/leads/${lead.id}`}>Dettagli</Link> <Link href={`/admin/leads/${lead.id}`}>Dettagli</Link>
</Button> </Button>
</TableCell> </td>
</TableRow> </tr>
{error && (
<tr>
<td colSpan={COL_COUNT} className="py-1 px-3 text-xs text-red-600">
{error}
</td>
</tr>
)}
</>
);
}
export function LeadTable({
leads,
options,
}: {
leads: LeadWithTags[];
options: LeadFieldOptions;
}) {
return (
<div className="bg-white rounded-xl border border-[#e5e7eb] overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead className="bg-[#f9f9f9] border-b border-[#e5e7eb] sticky top-0 z-[1]">
<tr>
{COLUMN_HEADERS.map((header) => (
<th
key={header}
className="text-left py-2 px-3 font-semibold text-[#71717a]"
>
{header}
</th>
))} ))}
</TableBody> </tr>
</Table> </thead>
<tbody>
{leads.map((lead) => (
<LeadRow key={lead.id} lead={lead} options={options} />
))}
</tbody>
</table>
</div>
{leads.length === 0 && ( {leads.length === 0 && (
<div className="text-center py-8 text-gray-500">Nessun lead trovato</div> <div className="text-center py-8 text-gray-500">Nessun lead trovato</div>
)} )}