Merge branch 'worktree-agent-a260f91fada48defd'

This commit is contained in:
2026-06-14 13:25:23 +02:00
6 changed files with 461 additions and 74 deletions
@@ -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 <table> 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 `<table>` (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 `<tr>` 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 `<action>` 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 `<action>` code renders `<Link href={...}>Dettagli</Link>` — "Dettagli" as JSX text content, not a quoted string literal `"Dettagli"`. The implementation matches the `<action>` block exactly; the acceptance grep (which looks for literal `"Dettagli"`) was simply never going to match this code shape.
- No fix needed — `<behavior>` and `<action>` 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
+46
View File
@@ -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 (
<div className="space-y-4">
<div className="relative max-w-sm">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-[#71717a]" />
<Input
type="text"
placeholder="Cerca lead..."
value={query}
onChange={(e) => setQuery(e.target.value)}
className="pl-9 h-9"
/>
</div>
<LeadTable leads={filtered} options={options} />
</div>
);
}
+18 -3
View File
@@ -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 <LeadDetail lead={lead} activities={activities} reminders={reminders} />;
return (
<LeadDetail
lead={lead}
activities={activities}
reminders={reminders}
tags={lead.tags}
tagOptions={options.tags}
/>
);
}
+11 -13
View File
@@ -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 (
<div className="space-y-6">
<div className="flex justify-between items-center">
<h1 className="text-3xl font-bold">Lead Pipeline</h1>
<h1 className="text-2xl font-bold text-[#1a1a1a]">Lead Pipeline</h1>
<CreateLeadModal />
</div>
<Suspense fallback={<div className="animate-pulse">Loading...</div>}>
<LeadTable leads={leads} />
</Suspense>
<LeadsSearch leads={leads} options={options} />
</div>
);
}
export default function LeadsPage() {
return <LeadsList />;
}
+35
View File
@@ -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<string | null>(null);
function run(fn: () => Promise<unknown>) {
setTagError(null);
startTransition(async () => {
try {
await fn();
router.refresh();
} catch (e) {
setTagError(e instanceof Error ? e.message : "Errore nel salvataggio");
}
});
}
return (
<div className="space-y-6">
{/* Header + Actions */}
@@ -63,6 +87,17 @@ export function LeadDetail({
{lead.status.replace(/_/g, " ")}
</Badge>
</div>
<div>
<label className="text-sm text-gray-600">Tag</label>
<OptionMultiSelect
values={tags}
options={tagOptions}
onAdd={(v) => run(() => addLeadTag(lead.id, v))}
onRemove={(v) => run(() => removeLeadTag(lead.id, v))}
onRename={(o, n) => run(() => renameLeadTag(o, n))}
/>
{tagError && <p className="text-xs text-red-600 mt-1">{tagError}</p>}
</div>
<div>
<label className="text-sm text-gray-600">Email</label>
<p>{lead.email || "—"}</p>
+218 -58
View File
@@ -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<string, string> = {
contacted: "bg-blue-100 text-blue-800",
@@ -25,54 +26,213 @@ const STAGE_COLOR: Record<string, string> = {
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 (
<div className="border rounded-lg overflow-hidden bg-white">
<Table>
<TableHeader>
<TableRow>
<TableHead>Nome</TableHead>
<TableHead>Email</TableHead>
<TableHead>Azienda</TableHead>
<TableHead>Stato</TableHead>
<TableHead>Ultimo Contatto</TableHead>
<TableHead>Prossima Azione</TableHead>
<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, " ")}
<div ref={containerRef} className="relative w-full min-w-[120px]">
<div
onClick={() => 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]"
>
<Badge
variant="outline"
className={cn(
STAGE_COLOR[lead.status] ?? "",
"border-transparent text-xs px-2 py-0.5 font-medium truncate"
)}
>
{lead.status.replace(/_/g, " ")}
</Badge>
</div>
{isOpen && (
<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]">
<div className="flex flex-col gap-0.5">
{options.status.map((stage) => (
<button
key={stage}
type="button"
onClick={() => {
setIsOpen(false);
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>
</TableCell>
<TableCell>
{lead.last_contact_date
? formatDistanceToNow(new Date(lead.last_contact_date), {
addSuffix: true,
locale: it,
})
: "—"}
</TableCell>
<TableCell className="text-sm">{lead.next_action || "—"}</TableCell>
<TableCell>
<Button variant="ghost" size="sm" asChild>
<Link href={`/admin/leads/${lead.id}`}>Dettagli</Link>
</Button>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</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>
<Link href={`/admin/leads/${lead.id}`}>Dettagli</Link>
</Button>
</td>
</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>
))}
</tr>
</thead>
<tbody>
{leads.map((lead) => (
<LeadRow key={lead.id} lead={lead} options={options} />
))}
</tbody>
</table>
</div>
{leads.length === 0 && (
<div className="text-center py-8 text-gray-500">Nessun lead trovato</div>
)}