From 4887a319f7abe2e4f117b426e6f55b13b4b6dd8b Mon Sep 17 00:00:00 2001 From: Simone Cavalli Date: Sun, 14 Jun 2026 13:21:23 +0200 Subject: [PATCH 1/3] 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 --- src/components/admin/leads/LeadTable.tsx | 276 ++++++++++++++++++----- 1 file changed, 218 insertions(+), 58 deletions(-) diff --git a/src/components/admin/leads/LeadTable.tsx b/src/components/admin/leads/LeadTable.tsx index 37b8768..efbfb94 100644 --- a/src/components/admin/leads/LeadTable.tsx +++ b/src/components/admin/leads/LeadTable.tsx @@ -1,20 +1,21 @@ "use client"; import Link from "next/link"; -import { Lead } from "@/db/schema"; -import { - Table, - TableBody, - TableCell, - TableHead, - TableHeader, - TableRow, -} from "@/components/ui/table"; +import { useState, useRef, useEffect, useTransition } from "react"; +import { useRouter } from "next/navigation"; +import { Check } from "lucide-react"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; -import { formatDistanceToNow } from "date-fns"; -import { it } from "date-fns/locale"; -import { LEAD_STAGES } from "@/lib/lead-validators"; +import { EditableCell } from "@/components/ui/editable-cell"; +import { OptionMultiSelect } from "@/components/ui/option-multi-select"; +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 = { contacted: "bg-blue-100 text-blue-800", @@ -25,54 +26,213 @@ const STAGE_COLOR: Record = { 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) => void; +}) { + const [isOpen, setIsOpen] = useState(false); + const containerRef = useRef(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 ( -
- - - - Nome - Email - Azienda - Stato - Ultimo Contatto - Prossima Azione - - - - - {leads.map((lead) => ( - - - - {lead.name} - - - {lead.email || "—"} - {lead.company || "—"} - - - {lead.status.replace(/_/g, " ")} +
+
setIsOpen((v) => !v)} + className="flex items-center gap-1 px-2 py-1 rounded transition-colors duration-150 min-h-[28px] cursor-pointer hover:bg-[#f0f0f0]" + > + + {lead.status.replace(/_/g, " ")} + +
+ {isOpen && ( +
+
+ {options.status.map((stage) => ( + - - - ))} - -
+ + ))} +
+ + )} + + ); +} + +function LeadRow({ + lead, + options, +}: { + lead: LeadWithTags; + options: LeadFieldOptions; +}) { + const router = useRouter(); + const [, startTransition] = useTransition(); + const [error, setError] = useState(null); + + function run(fn: () => Promise) { + setError(null); + startTransition(async () => { + try { + await fn(); + router.refresh(); + } catch (e) { + setError(e instanceof Error ? e.message : "Errore nel salvataggio"); + } + }); + } + + return ( + <> + + + run(() => updateLeadField(lead.id, "name", v))} + /> + + + run(() => updateLeadField(lead.id, "email", v))} + /> + + + run(() => updateLeadField(lead.id, "phone", v))} + /> + + + run(() => updateLeadField(lead.id, "company", v))} + /> + + + + + + run(() => updateLeadField(lead.id, "next_action", v))} + /> + + + run(() => addLeadTag(lead.id, v))} + onRemove={(v) => run(() => removeLeadTag(lead.id, v))} + onRename={(o, n) => run(() => renameLeadTag(o, n))} + /> + + + + + + {error && ( + + + {error} + + + )} + + ); +} + +export function LeadTable({ + leads, + options, +}: { + leads: LeadWithTags[]; + options: LeadFieldOptions; +}) { + return ( +
+
+ + + + {COLUMN_HEADERS.map((header) => ( + + ))} + + + + {leads.map((lead) => ( + + ))} + +
+ {header} +
+
+ {leads.length === 0 && (
Nessun lead trovato
)} From ab7fa62059d49f4ef6a7314233aaf5d536d53f89 Mon Sep 17 00:00:00 2001 From: Simone Cavalli Date: Sun, 14 Jun 2026 13:21:55 +0200 Subject: [PATCH 2/3] feat(14-02): add LeadsSearch, rewire leads pages, surface tags in LeadDetail (CRM-08/09) - New LeadsSearch.tsx: client-side instant filter across name/email/ company/status/tags (mirrors CatalogSearch.tsx) - page.tsx: fetch via getLeadsWithTags()/getLeadFieldOptions(), render LeadsSearch + CreateLeadModal, revalidate=0 - [id]/page.tsx: fetch getLeadsWithTags()/getLeadFieldOptions(), find lead by id, pass tags/tagOptions to LeadDetail - LeadDetail.tsx: add OptionMultiSelect for lead tags in the "Profilo" card, wired to addLeadTag/removeLeadTag/renameLeadTag with error display --- src/app/admin/leads/LeadsSearch.tsx | 46 +++++++++++++++++++++++ src/app/admin/leads/[id]/page.tsx | 21 +++++++++-- src/app/admin/leads/page.tsx | 24 ++++++------ src/components/admin/leads/LeadDetail.tsx | 35 +++++++++++++++++ 4 files changed, 110 insertions(+), 16 deletions(-) create mode 100644 src/app/admin/leads/LeadsSearch.tsx diff --git a/src/app/admin/leads/LeadsSearch.tsx b/src/app/admin/leads/LeadsSearch.tsx new file mode 100644 index 0000000..912c478 --- /dev/null +++ b/src/app/admin/leads/LeadsSearch.tsx @@ -0,0 +1,46 @@ +"use client"; + +import { useState, useMemo } from "react"; +import { Input } from "@/components/ui/input"; +import { Search } from "lucide-react"; +import { LeadTable } from "@/components/admin/leads/LeadTable"; +import type { LeadWithTags, LeadFieldOptions } from "@/lib/admin-queries"; + +export function LeadsSearch({ + leads, + options, +}: { + leads: LeadWithTags[]; + options: LeadFieldOptions; +}) { + const [query, setQuery] = useState(""); + + const filtered = useMemo(() => { + const q = query.trim().toLowerCase(); + if (!q) return leads; + return leads.filter((l) => { + if (l.name.toLowerCase().includes(q)) return true; + if (l.email?.toLowerCase().includes(q)) return true; + if (l.company?.toLowerCase().includes(q)) return true; + if (l.status.toLowerCase().includes(q)) return true; + if (l.tags.some((t) => t.toLowerCase().includes(q))) return true; + return false; + }); + }, [leads, query]); + + return ( +
+
+ + setQuery(e.target.value)} + className="pl-9 h-9" + /> +
+ +
+ ); +} diff --git a/src/app/admin/leads/[id]/page.tsx b/src/app/admin/leads/[id]/page.tsx index 161f577..f9aee2f 100644 --- a/src/app/admin/leads/[id]/page.tsx +++ b/src/app/admin/leads/[id]/page.tsx @@ -1,10 +1,17 @@ import { notFound } from "next/navigation"; -import { getLeadById, getActivityLog, getUpcomingReminders } from "@/lib/lead-service"; +import { getActivityLog, getUpcomingReminders } from "@/lib/lead-service"; +import { getLeadsWithTags, getLeadFieldOptions } from "@/lib/admin-queries"; import { LeadDetail } from "@/components/admin/leads/LeadDetail"; export default async function LeadDetailPage({ params }: { params: Promise<{ id: string }> }) { const { id } = await params; - const lead = await getLeadById(id); + + const [leads, options] = await Promise.all([ + getLeadsWithTags(), + getLeadFieldOptions(), + ]); + + const lead = leads.find((l) => l.id === id); if (!lead) { notFound(); @@ -13,5 +20,13 @@ export default async function LeadDetailPage({ params }: { params: Promise<{ id: const activities = await getActivityLog(id); const reminders = await getUpcomingReminders(id); - return ; + return ( + + ); } diff --git a/src/app/admin/leads/page.tsx b/src/app/admin/leads/page.tsx index 1e3ba87..59158f4 100644 --- a/src/app/admin/leads/page.tsx +++ b/src/app/admin/leads/page.tsx @@ -1,25 +1,23 @@ -import { Suspense } from "react"; -import { getAllLeads } from "@/lib/lead-service"; -import { LeadTable } from "@/components/admin/leads/LeadTable"; +import { getLeadsWithTags, getLeadFieldOptions } from "@/lib/admin-queries"; +import { LeadsSearch } from "./LeadsSearch"; import { CreateLeadModal } from "@/components/admin/leads/LeadForm"; -async function LeadsList() { - const leads = await getAllLeads(); +export const revalidate = 0; + +export default async function LeadsPage() { + const [leads, options] = await Promise.all([ + getLeadsWithTags(), + getLeadFieldOptions(), + ]); return (
-

Lead Pipeline

+

Lead Pipeline

- Loading...
}> - - +
); } - -export default function LeadsPage() { - return ; -} diff --git a/src/components/admin/leads/LeadDetail.tsx b/src/components/admin/leads/LeadDetail.tsx index 2dec91b..df23b9e 100644 --- a/src/components/admin/leads/LeadDetail.tsx +++ b/src/components/admin/leads/LeadDetail.tsx @@ -1,9 +1,13 @@ "use client"; +import { useState, useTransition } from "react"; +import { useRouter } from "next/navigation"; import { Lead, Activity, Reminder } from "@/db/schema"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; +import { OptionMultiSelect } from "@/components/ui/option-multi-select"; +import { addLeadTag, removeLeadTag, renameLeadTag } from "@/app/admin/leads/actions"; import { formatDistanceToNow, format } from "date-fns"; import { it } from "date-fns/locale"; import { LogActivityModal } from "./LogActivityModal"; @@ -30,11 +34,31 @@ export function LeadDetail({ lead, activities, reminders, + tags, + tagOptions, }: { lead: Lead; activities: Activity[]; reminders: Reminder[]; + tags: string[]; + tagOptions: string[]; }) { + const router = useRouter(); + const [, startTransition] = useTransition(); + const [tagError, setTagError] = useState(null); + + function run(fn: () => Promise) { + setTagError(null); + startTransition(async () => { + try { + await fn(); + router.refresh(); + } catch (e) { + setTagError(e instanceof Error ? e.message : "Errore nel salvataggio"); + } + }); + } + return (
{/* Header + Actions */} @@ -63,6 +87,17 @@ export function LeadDetail({ {lead.status.replace(/_/g, " ")}
+
+ + run(() => addLeadTag(lead.id, v))} + onRemove={(v) => run(() => removeLeadTag(lead.id, v))} + onRename={(o, n) => run(() => renameLeadTag(o, n))} + /> + {tagError &&

{tagError}

} +

{lead.email || "—"}

From 2a02ca8fbf96346aff173d3c74428575bd7ed3c0 Mon Sep 17 00:00:00 2001 From: Simone Cavalli Date: Sun, 14 Jun 2026 13:24:47 +0200 Subject: [PATCH 3/3] docs(14-02): add plan summary for LeadTable Attio rewrite --- .../14-crm-attio-style-fix/14-02-SUMMARY.md | 133 ++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 .planning/phases/14-crm-attio-style-fix/14-02-SUMMARY.md diff --git a/.planning/phases/14-crm-attio-style-fix/14-02-SUMMARY.md b/.planning/phases/14-crm-attio-style-fix/14-02-SUMMARY.md new file mode 100644 index 0000000..37a72f1 --- /dev/null +++ b/.planning/phases/14-crm-attio-style-fix/14-02-SUMMARY.md @@ -0,0 +1,133 @@ +--- +phase: 14-crm-attio-style-fix +plan: 02 +subsystem: frontend +tags: [react, nextjs, leads, crm, database-view, inline-edit, tags] + +# Dependency graph +requires: + - phase: 14-01-leads-data-layer + provides: "LeadWithTags/LeadFieldOptions types, getLeadsWithTags()/getLeadFieldOptions() queries, updateLeadField/addLeadTag/removeLeadTag/renameLeadTag server actions" +provides: + - "LeadTable.tsx — raw database-view component (8 columns: Nome/Email/Telefono/Azienda/Stato/Prossima Azione/Tag/Azioni), EditableCell + StatusCell + OptionMultiSelect" + - "LeadsSearch.tsx — client-side instant filter across name/email/company/status/tags" + - "LeadDetail.tsx Profilo card — OptionMultiSelect for lead tags, wired to addLeadTag/removeLeadTag/renameLeadTag" +affects: [] + +# Tech tracking +tech-stack: + added: [] + patterns: + - "Local StatusCell component: closed click-to-open dropdown over a fixed enum (LEAD_STAGES), preserving a semantic color map — used instead of OptionSelect when a shared component's props contract can't express semantic per-value badge colors without modification" + - "run() transition+error helper pattern (from ServiceRow) replicated in LeadRow and LeadDetail for inline-edit/tag mutations with router.refresh()" + +key-files: + created: + - src/app/admin/leads/LeadsSearch.tsx + modified: + - src/components/admin/leads/LeadTable.tsx + - src/app/admin/leads/page.tsx + - src/app/admin/leads/[id]/page.tsx + - src/components/admin/leads/LeadDetail.tsx + +key-decisions: + - "[id]/page.tsx now sources lead+tags via getLeadsWithTags().find(id) + getLeadFieldOptions() (plan's approach (a)) instead of getLeadById, removing one query function call while reusing Plan 14-01's left-join" + - "Two plan acceptance_criteria greps are stale relative to their own analog files (CatalogSearch.tsx) and were treated as documentation inaccuracies, not implementation defects — see Deviations" + +patterns-established: + - "StatusCell-style local closed-dropdown for fixed-enum fields needing semantic per-value badge colors, as an alternative to OptionSelect" + +requirements-completed: [CRM-08, CRM-09] + +# Metrics +duration: ~25min +completed: 2026-06-14 +--- + +# Phase 14 Plan 02: LeadTable Attio Rewrite Summary + +**Rewrote `LeadTable.tsx` as a raw-table Attio-style database view with inline editing, a closed status dropdown preserving semantic colors, and lead tags via `OptionMultiSelect`; added `LeadsSearch.tsx` for client-side instant filtering; rewired `/admin/leads` and `/admin/leads/[id]` to the new data layer; surfaced lead tags in `LeadDetail`'s "Profilo" card.** + +## Performance + +- **Duration:** ~25 min +- **Completed:** 2026-06-14T13:22:00+02:00 +- **Tasks:** 2 +- **Files modified:** 4 (+1 created) + +## Accomplishments +- `LeadTable.tsx` fully rewritten: raw `
` (no shadcn Table wrapper), 8 columns (Nome/Email/Telefono/Azienda/Stato/Prossima Azione/Tag/Azioni) +- `EditableCell` wired for name (required), email, phone, company, next_action → `updateLeadField` +- New local `StatusCell`: click-to-open closed dropdown over the 6 `LEAD_STAGES` values only (no free-text/create option), preserving semantic `STAGE_COLOR` badges (won=green, lost=red, etc.) per UI-SPEC Decision 1 — implemented without modifying shared `option-select.tsx` +- `OptionMultiSelect` for lead tags, wired to `addLeadTag`/`removeLeadTag`/`renameLeadTag` +- Per-row error `` and "Nessun lead trovato" empty state +- New `LeadsSearch.tsx`: instant client-side filter over name/email/company/status/tags (mirrors `CatalogSearch.tsx`) +- `page.tsx` rewired to fetch `getLeadsWithTags()` + `getLeadFieldOptions()` in parallel, render `LeadsSearch` + `CreateLeadModal`, `revalidate = 0` +- `[id]/page.tsx` rewired to fetch `getLeadsWithTags()`/`getLeadFieldOptions()`, locate the lead by id, pass `tags`/`tagOptions` to `LeadDetail` +- `LeadDetail.tsx` "Profilo" card now includes an `OptionMultiSelect` for lead tags with its own `run()`/error-display helper, identical mutation pattern to `LeadTable` + +## Task Commits + +Each task was committed atomically: + +1. **Task 1: Rewrite LeadTable.tsx as raw-table database-view (CRM-08, CRM-09)** - `4887a31` (feat) +2. **Task 2: Create LeadsSearch.tsx, rewire page.tsx, surface tags in LeadDetail.tsx** - `ab7fa62` (feat) + +## Files Created/Modified +- `src/components/admin/leads/LeadTable.tsx` - Full rewrite: raw-table `LeadRow`/`LeadTable`, new `StatusCell`, `EditableCell`/`OptionMultiSelect` wiring +- `src/app/admin/leads/LeadsSearch.tsx` - New file: client-side instant filter wrapper around `LeadTable` +- `src/app/admin/leads/page.tsx` - Rewired to `getLeadsWithTags()`/`getLeadFieldOptions()` + `LeadsSearch`, `revalidate = 0`, dropped `Suspense`/`LeadsList` +- `src/app/admin/leads/[id]/page.tsx` - Rewired to `getLeadsWithTags()`/`getLeadFieldOptions()` (dropped `getLeadById`), passes `tags`/`tagOptions` to `LeadDetail` +- `src/components/admin/leads/LeadDetail.tsx` - Added `tags`/`tagOptions` props, `OptionMultiSelect` + `run()` helper in "Profilo" card, imports for `useState`/`useTransition`/`useRouter`/`addLeadTag`/`removeLeadTag`/`renameLeadTag`/`OptionMultiSelect` + +## Decisions Made +- Followed the plan's `` blocks essentially verbatim, including the plan's own correction to use a local `StatusCell` instead of `OptionSelect` (the plan pre-emptively documents and resolves this — not a Claude-discretion deviation, just executing the plan as written) +- For `[id]/page.tsx`, used plan's approach (a): `getLeadsWithTags().find(l => l.id === id)` + `getLeadFieldOptions()`, calling `notFound()` if no match — removes the `getLeadById` import entirely + +## Deviations from Plan + +### Documentation-only (plan acceptance_criteria inaccuracies, not implementation defects) + +**1. `grep -c '"Dettagli"' LeadTable.tsx` expects 1, returns 0** +- The plan's own `` code renders `Dettagli` — "Dettagli" as JSX text content, not a quoted string literal `"Dettagli"`. The implementation matches the `` block exactly; the acceptance grep (which looks for literal `"Dettagli"`) was simply never going to match this code shape. +- No fix needed — `` and `` blocks both specify this exact JSX form. + +**2. `grep -c "useMemo" LeadsSearch.tsx` expects 1, returns 2** +- `LeadsSearch.tsx` is a 1:1 structural port of `CatalogSearch.tsx`, which itself returns 2 for this same grep (1 import line + 1 usage line). Verified: `grep -c "useMemo" src/app/admin/catalog/CatalogSearch.tsx` also returns 2. The acceptance criterion is stale relative to its own reference implementation. +- No fix needed — implementation matches the established pattern exactly. + +### Pre-existing, unrelated (not introduced by this plan) + +**3. Unused `Button` import in `LeadDetail.tsx`** +- `npx eslint src/components/admin/leads/LeadDetail.tsx` reports 1 warning: `@typescript-eslint/no-unused-vars` for the `Button` import. +- Confirmed pre-existing: `git show main:src/components/admin/leads/LeadDetail.tsx | grep -c '\bButton\b'` returns 1 (import-only) on `main` as well, before this plan's edits. Not touched — out of scope per "Do not modify any other part of LeadDetail.tsx" instruction. + +--- + +**Total deviations:** 0 implementation deviations. 2 stale plan-doc acceptance criteria (documented above, both verified against their reference analogs). 1 pre-existing lint warning (unrelated, untouched). +**Impact on plan:** None — `npx tsc --noEmit` exits 0 across the whole project; `npx eslint` exits 0 (errors) with only the 1 pre-existing warning noted above. + +## Issues Encountered +None beyond the documentation-only items above. + +## User Setup Required +None — no new dependencies, no schema/migration changes (this plan is pure frontend wiring on top of Plan 14-01's already-applied data layer). + +## Next Phase Readiness +- `/admin/leads` and `/admin/leads/[id]` now fully deliver CRM-08 (inline-edit database view) and CRM-09 (lead tags) +- This was the only plan in Wave 2 and the last plan in Phase 14 — ready for phase-level verification (CRM-08 through CRM-12 across all 3 plans) + +--- +*Phase: 14-crm-attio-style-fix* +*Completed: 2026-06-14* + +## Self-Check: PASSED + +- FOUND: src/components/admin/leads/LeadTable.tsx +- FOUND: src/app/admin/leads/LeadsSearch.tsx +- FOUND: src/app/admin/leads/page.tsx +- FOUND: src/app/admin/leads/[id]/page.tsx +- FOUND: src/components/admin/leads/LeadDetail.tsx +- FOUND: .planning/phases/14-crm-attio-style-fix/14-02-SUMMARY.md +- FOUND commit: 4887a31 +- FOUND commit: ab7fa62