---
phase: 10
plan: 02
type: execute
wave: 2
depends_on: [10-01]
files_modified:
  - src/app/admin/leads/page.tsx
  - src/app/admin/leads/[id]/page.tsx
  - src/components/admin/leads/LeadTable.tsx
  - src/components/admin/leads/LeadForm.tsx
  - src/components/admin/leads/PipelineKanban.tsx
  - src/app/admin/leads/actions.ts
autonomous: true
requirements:
  - CRM-01
  - CRM-02
  - CRM-03
---

<objective>
Phase 10 CRM UI (Part 1): Implement Lead CRUD pages (/admin/leads) and Kanban pipeline view showing leads by stage. Establish form patterns for lead creation/editing and stage transitions via drag-and-drop.

Purpose: Create the admin-facing lead management interface and pipeline view. Admins can create leads, view full lead details, and transition leads between pipeline stages visually. This enables the core CRM workflow: Contacted → Qualified → Proposal Sent → Negotiating → Won/Lost.

Output:
- `/admin/leads` list page with table (name, email, company, status, last_contact_date, next_action)
- `/admin/leads/[id]` detail page with profilo, action menu (log activity, send quote, mark won)
- `/admin/leads/kanban` Kanban board view (drag-drop leads between 6 stages)
- LeadForm component (create + edit modal)
- Server actions for createLead, updateLead, updateLeadStage, deleteLead
</objective>

<execution_context>
@$HOME/.claude/get-shit-done/workflows/execute-plan.md
@$HOME/.claude/get-shit-done/templates/summary.md
</execution_context>

<context>
@.planning/PROJECT.md
@.planning/ROADMAP.md
@.planning/STATE.md
@.planning/REQUIREMENTS.md
@.planning/phases/10-crm-pipeline-activity-logging/10-01-SUMMARY.md
</context>

<interfaces>
From src/lib/lead-validators.ts (created in Plan 1):
```typescript
export const LEAD_STAGES = ["contacted", "qualified", "proposal_sent", "negotiating", "won", "lost"] as const;
export const ACTIVITY_TYPES = ["call", "email", "meeting", "note"] as const;
export const createLeadSchema: ZodType<{ name, email?, phone?, company?, status?, notes? }>;
export const updateLeadSchema: ZodType<Partial<CreateLead>>;
```

From src/lib/lead-service.ts (created in Plan 1):
```typescript
export async function getAllLeads(): Promise<Lead[]>;
export async function getLeadById(id: string): Promise<Lead | undefined>;
export async function getLeadsByStage(stage: string): Promise<Lead[]>;
export async function createActivity(...): Promise<Activity>;
export async function updateLeadStage(leadId, stage): Promise<Lead>;
```

From src/db/schema.ts (expanded in Plan 1):
```typescript
export type Lead = typeof leads.$inferSelect;
export type NewLead = typeof leads.$inferInsert;
export type Activity = typeof activities.$inferSelect;
```
</interfaces>

<tasks>

<task type="auto">
  <name>Task 1: Create /admin/leads list page and LeadTable component</name>
  <files>src/app/admin/leads/page.tsx, src/components/admin/leads/LeadTable.tsx</files>
  <action>
**Step 1: Create `/admin/leads` list page**

File: `src/app/admin/leads/page.tsx`

```typescript
import { Suspense } from "react";
import { getAllLeads } from "@/lib/lead-service";
import { LeadTable } from "@/components/admin/leads/LeadTable";
import { CreateLeadModal } from "@/components/admin/leads/LeadForm";
import { Button } from "@/components/ui/button";

async function LeadsList() {
  const leads = await getAllLeads();

  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <h1 className="text-3xl font-bold">Lead Pipeline</h1>
        <CreateLeadModal />
      </div>

      <Suspense fallback={<div>Loading...</div>}>
        <LeadTable leads={leads} />
      </Suspense>
    </div>
  );
}

export default function LeadsPage() {
  return <LeadsList />;
}
```

**Step 2: Create LeadTable component**

File: `src/components/admin/leads/LeadTable.tsx`

```typescript
"use client";

import Link from "next/link";
import { Lead } from "@/db/schema";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { formatDistanceToNow } from "date-fns";
import { LEAD_STAGES } from "@/lib/lead-validators";

const STAGE_COLOR = {
  contacted: "bg-blue-100 text-blue-800",
  qualified: "bg-purple-100 text-purple-800",
  proposal_sent: "bg-amber-100 text-amber-800",
  negotiating: "bg-orange-100 text-orange-800",
  won: "bg-green-100 text-green-800",
  lost: "bg-red-100 text-red-800",
};

export function LeadTable({ leads }: { leads: Lead[] }) {
  return (
    <div className="border rounded-lg">
      <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("_", " ")}
                </Badge>
              </TableCell>
              <TableCell>
                {lead.last_contact_date
                  ? formatDistanceToNow(new Date(lead.last_contact_date), { addSuffix: true })
                  : "—"}
              </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>
      {leads.length === 0 && (
        <div className="text-center py-8 text-gray-500">Nessun lead trovato</div>
      )}
    </div>
  );
}
```

**Design notes:**
- Table shows all required fields per CRM-01 (name, email, company, status, last_contact_date, next_action)
- Status badge color-coded by stage (blue=contacted, purple=qualified, amber=proposal_sent, orange=negotiating, green=won, red=lost)
- Click row to navigate to lead detail page
- "Create Lead" button opens modal form
  </action>
  <verify>
    <automated>npm run build 2>&1 | grep -c "error" | grep -q 0 && echo "Leads list page compiles"</automated>
  </verify>
  <done>LeadTable component and /admin/leads page created. Table displays all leads with status badge coloring, last contact date, and navigation links to detail page.</done>
</task>

<task type="auto">
  <name>Task 2: Create /admin/leads/[id] detail page with activity log and action menu</name>
  <files>src/app/admin/leads/[id]/page.tsx, src/components/admin/leads/LeadDetail.tsx</files>
  <action>
File: `src/app/admin/leads/[id]/page.tsx`

```typescript
import { notFound } from "next/navigation";
import { getLeadById, getActivityLog, getUpcomingReminders } from "@/lib/lead-service";
import { LeadDetail } from "@/components/admin/leads/LeadDetail";

export default async function LeadDetailPage({ params }: { params: { id: string } }) {
  const lead = await getLeadById(params.id);
  
  if (!lead) {
    notFound();
  }

  const activities = await getActivityLog(params.id);
  const reminders = await getUpcomingReminders(params.id);

  return (
    <LeadDetail lead={lead} activities={activities} reminders={reminders} />
  );
}
```

File: `src/components/admin/leads/LeadDetail.tsx`

```typescript
"use client";

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 { formatDistanceToNow, format } from "date-fns";
import { LogActivityModal } from "./LogActivityModal";
import { SendQuoteModal } from "./SendQuoteModal";
import { it } from "date-fns/locale";

const ACTIVITY_ICON = {
  call: "📞",
  email: "📧",
  meeting: "📅",
  note: "📝",
};

export function LeadDetail({
  lead,
  activities,
  reminders,
}: {
  lead: Lead;
  activities: Activity[];
  reminders: Reminder[];
}) {
  return (
    <div className="space-y-6">
      {/* Header + Actions */}
      <div className="flex justify-between items-start">
        <div>
          <h1 className="text-3xl font-bold">{lead.name}</h1>
          <p className="text-gray-600">{lead.company || "Azienda non specificata"}</p>
        </div>
        <div className="flex gap-2">
          <LogActivityModal leadId={lead.id} />
          <SendQuoteModal leadId={lead.id} />
          <Button variant="outline">Segna come vinto</Button>
        </div>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        {/* Lead Profile Card */}
        <Card>
          <CardHeader>
            <CardTitle>Profilo</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <div>
              <label className="text-sm text-gray-600">Stato</label>
              <Badge className="mt-1">{lead.status.replace("_", " ")}</Badge>
            </div>
            <div>
              <label className="text-sm text-gray-600">Email</label>
              <p>{lead.email || "—"}</p>
            </div>
            <div>
              <label className="text-sm text-gray-600">Telefono</label>
              <p>{lead.phone || "—"}</p>
            </div>
            <div>
              <label className="text-sm text-gray-600">Ultimo contatto</label>
              <p>
                {lead.last_contact_date
                  ? formatDistanceToNow(new Date(lead.last_contact_date), {
                      addSuffix: true,
                      locale: it,
                    })
                  : "—"}
              </p>
            </div>
            <div>
              <label className="text-sm text-gray-600">Prossima azione</label>
              <p className="font-medium">{lead.next_action || "—"}</p>
            </div>
          </CardContent>
        </Card>

        {/* Upcoming Reminders Card */}
        <Card>
          <CardHeader>
            <CardTitle>Prossimi Follow-up</CardTitle>
          </CardHeader>
          <CardContent>
            {reminders.length > 0 ? (
              <ul className="space-y-2">
                {reminders.map((r) => (
                  <li key={r.id} className="text-sm border-l-2 border-blue-300 pl-2">
                    <p className="font-medium">{r.title}</p>
                    <p className="text-gray-600">
                      {format(new Date(r.due_date), "dd MMM yyyy", { locale: it })}
                    </p>
                  </li>
                ))}
              </ul>
            ) : (
              <p className="text-gray-500 text-sm">Nessun reminder</p>
            )}
          </CardContent>
        </Card>

        {/* Notes Card */}
        <Card>
          <CardHeader>
            <CardTitle>Note</CardTitle>
          </CardHeader>
          <CardContent>
            <p className="text-sm">{lead.notes || "Nessuna nota"}</p>
          </CardContent>
        </Card>
      </div>

      {/* Activity Log */}
      <Card>
        <CardHeader>
          <CardTitle>Storico Attività</CardTitle>
        </CardHeader>
        <CardContent>
          {activities.length > 0 ? (
            <div className="space-y-4">
              {activities.map((activity) => (
                <div
                  key={activity.id}
                  className="border-l-4 border-blue-300 pl-4 pb-4"
                >
                  <div className="flex items-center gap-2">
                    <span className="text-xl">
                      {ACTIVITY_ICON[activity.type as keyof typeof ACTIVITY_ICON]}
                    </span>
                    <span className="font-medium capitalize">
                      {activity.type}
                    </span>
                    <span className="text-gray-600 text-sm">
                      {formatDistanceToNow(new Date(activity.activity_date), {
                        addSuffix: true,
                        locale: it,
                      })}
                    </span>
                  </div>
                  <p className="text-sm mt-2">{activity.notes}</p>
                  {activity.duration_minutes && (
                    <p className="text-xs text-gray-500 mt-1">
                      Durata: {activity.duration_minutes} minuti
                    </p>
                  )}
                </div>
              ))}
            </div>
          ) : (
            <p className="text-gray-500 text-sm">Nessuna attività registrata</p>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
```

**Design notes:**
- Full lead profile on left (name, email, phone, company, status, next_action)
- Activity log in reverse chronological order with type icons (📞📧📅📝)
- Action buttons for log activity, send quote, mark as won
- Upcoming reminders list
- Notes section for free-form notes
  </action>
  <verify>
    <automated>npm run build 2>&1 | grep -c "error" | grep -q 0 && echo "Lead detail page compiles"</automated>
  </verify>
  <done>Lead detail page and LeadDetail component created. Shows full lead profile, activity log (reverse chronological), upcoming reminders, and action menu (log activity, send quote, mark as won).</done>
</task>

<task type="auto">
  <name>Task 3: Create LeadForm component (create/edit modal) and server actions</name>
  <files>src/components/admin/leads/LeadForm.tsx, src/app/admin/leads/actions.ts</files>
  <action>
File: `src/components/admin/leads/LeadForm.tsx`

```typescript
"use client";

import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { createLeadSchema, LEAD_STAGES } from "@/lib/lead-validators";
import { Lead } from "@/db/schema";
import { createLead, updateLead } from "@/app/admin/leads/actions";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";

type CreateLeadInput = z.infer<typeof createLeadSchema>;

export function CreateLeadModal() {
  const [open, setOpen] = useState(false);
  const form = useForm<CreateLeadInput>({
    resolver: zodResolver(createLeadSchema),
    defaultValues: { status: "contacted" },
  });

  async function onSubmit(data: CreateLeadInput) {
    const result = await createLead(data);
    if (result.success) {
      setOpen(false);
      form.reset();
      // Toast success
    }
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button>+ Nuovo Lead</Button>
      </DialogTrigger>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>Nuovo Lead</DialogTitle>
        </DialogHeader>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <FormField
              control={form.control}
              name="name"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Nome</FormLabel>
                  <FormControl>
                    <Input placeholder="Nome lead" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="email"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Email</FormLabel>
                  <FormControl>
                    <Input type="email" placeholder="email@example.com" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="phone"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Telefono</FormLabel>
                  <FormControl>
                    <Input placeholder="+39 3XX XXXXXXX" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="company"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Azienda</FormLabel>
                  <FormControl>
                    <Input placeholder="Nome azienda" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="status"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Stato</FormLabel>
                  <Select onValueChange={field.onChange} defaultValue={field.value}>
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      {LEAD_STAGES.map((stage) => (
                        <SelectItem key={stage} value={stage}>
                          {stage.replace(/_/g, " ")}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="notes"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Note</FormLabel>
                  <FormControl>
                    <Textarea
                      placeholder="Appunti su questo lead"
                      className="resize-none"
                      {...field}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <Button type="submit" className="w-full">
              Crea Lead
            </Button>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}

export function EditLeadModal({ lead }: { lead: Lead }) {
  const [open, setOpen] = useState(false);
  const form = useForm<CreateLeadInput>({
    resolver: zodResolver(createLeadSchema),
    defaultValues: {
      name: lead.name,
      email: lead.email || "",
      phone: lead.phone || "",
      company: lead.company || "",
      status: lead.status as any,
      notes: lead.notes || "",
    },
  });

  async function onSubmit(data: CreateLeadInput) {
    const result = await updateLead(lead.id, data);
    if (result.success) {
      setOpen(false);
    }
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button variant="outline" size="sm">
          Modifica
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>Modifica Lead</DialogTitle>
        </DialogHeader>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            {/* Same form fields as CreateLeadModal */}
            <Button type="submit" className="w-full">
              Salva
            </Button>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
```

File: `src/app/admin/leads/actions.ts`

```typescript
"use server";

import { z } from "zod";
import { db } from "@/db";
import { leads } from "@/db/schema";
import { eq } from "drizzle-orm";
import { createLeadSchema, updateLeadSchema } from "@/lib/lead-validators";
import { revalidatePath } from "next/cache";

export async function createLead(data: z.infer<typeof createLeadSchema>) {
  const parsed = createLeadSchema.safeParse(data);
  
  if (!parsed.success) {
    return { success: false, error: parsed.error.issues[0].message };
  }

  try {
    const [lead] = await db
      .insert(leads)
      .values({
        name: parsed.data.name,
        email: parsed.data.email || null,
        phone: parsed.data.phone || null,
        company: parsed.data.company || null,
        status: parsed.data.status || "contacted",
        notes: parsed.data.notes || null,
      })
      .returning();

    revalidatePath("/admin/leads");
    return { success: true, lead };
  } catch (error) {
    console.error("createLead error:", error);
    return { success: false, error: "Errore nella creazione del lead" };
  }
}

export async function updateLead(
  id: string,
  data: z.infer<typeof updateLeadSchema>
) {
  const parsed = updateLeadSchema.safeParse(data);
  
  if (!parsed.success) {
    return { success: false, error: parsed.error.issues[0].message };
  }

  try {
    const [updated] = await db
      .update(leads)
      .set({
        ...parsed.data,
        updated_at: new Date(),
      })
      .where(eq(leads.id, id))
      .returning();

    revalidatePath("/admin/leads");
    revalidatePath(`/admin/leads/${id}`);
    return { success: true, lead: updated };
  } catch (error) {
    console.error("updateLead error:", error);
    return { success: false, error: "Errore nell'aggiornamento" };
  }
}

export async function deleteLead(id: string) {
  try {
    await db.delete(leads).where(eq(leads.id, id));
    revalidatePath("/admin/leads");
    return { success: true };
  } catch (error) {
    console.error("deleteLead error:", error);
    return { success: false, error: "Errore nell'eliminazione" };
  }
}
```

**Design notes:**
- LeadForm uses React Hook Form + Zod for validation per existing patterns
- Modal dialog for create/edit (reusable component)
- Server actions handle DB mutations with error handling
- Revalidate paths after mutation to sync UI
  </action>
  <verify>
    <automated>npm run build 2>&1 | grep -c "error" | grep -q 0 && echo "Lead form and actions compile"</automated>
  </verify>
  <done>LeadForm component (create/edit modal) and server actions (createLead, updateLead, deleteLead) created. Forms integrate React Hook Form + Zod. Server actions handle validation and DB mutations.</done>
</task>

</tasks>

<threat_model>
## Trust Boundaries

| Boundary | Description |
|----------|-------------|
| Admin → Lead Form Input | Server-side validation via Zod; no XSS via textarea notes; sanitize on display |
| Lead List Export | No export endpoint in Phase 10; leads data accessible to admin only |

## STRIDE Threat Register

| Threat ID | Category | Component | Disposition | Mitigation Plan |
|-----------|----------|-----------|-------------|-----------------|
| T-10-07 | Injection | XSS via lead notes textarea | mitigate | Notes stored as text; rendered in admin area with React (auto-escaped); no HTML parsing |
| T-10-08 | Tampering | Bulk delete leads via API | mitigate | Delete action requires Auth.js session; no bulk-delete in Phase 10 UI |
| T-10-09 | Information Disclosure | Lead data exposed via form autocomplete | accept | Browser autocomplete on email/phone fields; acceptable for internal admin |

</threat_model>

<verification>
After Phase 10 Plan 2 execution:

1. `/admin/leads` list page loads and displays all leads with status badges
2. `/admin/leads/[id]` detail page shows full lead profile, activity log, reminders, and action buttons
3. Create Lead modal opens and submits via server action
4. Form validation rejects invalid emails, empty names
5. Server actions handle DB inserts/updates and revalidate paths
6. Lead Table component renders with correct badge colors per stage
</verification>

<success_criteria>
- `/admin/leads` list page operational with searchable lead table
- `/admin/leads/[id]` detail page shows lead profile, activity log, upcoming reminders
- Create Lead modal form with all fields (name, email, phone, company, status, notes)
- Edit Lead modal reuses same form schema
- Server actions createLead, updateLead, deleteLead working with Zod validation
- UI integrates with lead-service query layer
- Path revalidation syncs UI after mutations
</success_criteria>

<output>
After execution, create `.planning/phases/10-crm-pipeline-activity-logging/10-02-SUMMARY.md`
</output>
