---
phase: 20-knowledge-base-cliente
plan: 03
type: execute
wave: 3
depends_on:
  - 20-01
  - 20-02
files_modified:
  - src/components/admin/leads/TranscriptModal.tsx
  - src/components/admin/leads/LeadDetail.tsx
  - src/app/admin/leads/[id]/page.tsx
autonomous: true
requirements:
  - KB-02
must_haves:
  truths:
    - "L'admin può aggiungere un transcript dalla pagina dettaglio lead via modal"
    - "I transcript sono elencati in call_date DESC con titolo, data formattata e anteprima del testo"
    - "Il testo completo di ogni transcript è espandibile/collassabile"
    - "L'admin può eliminare un transcript con un bottone 'Elimina'"
    - "La sezione Transcript appare dopo lo Storico Attività nel LeadDetail"
  artifacts:
    - path: "src/components/admin/leads/TranscriptModal.tsx"
      provides: "Modal form per aggiungere transcript (call_date, title opzionale, content textarea)"
      exports: ["TranscriptModal"]
    - path: "src/components/admin/leads/LeadDetail.tsx"
      provides: "Sezione Transcript con lista collassabile e azione Elimina"
      contains: "Transcript"
    - path: "src/app/admin/leads/[id]/page.tsx"
      provides: "getTranscripts(id) nel Promise.all + prop transcripts passato a LeadDetail"
      contains: "getTranscripts"
  key_links:
    - from: "src/components/admin/leads/TranscriptModal.tsx"
      to: "src/app/admin/leads/actions.ts"
      via: "import addTranscript"
      pattern: "addTranscript"
    - from: "src/components/admin/leads/LeadDetail.tsx"
      to: "src/app/admin/leads/actions.ts"
      via: "import deleteTranscript"
      pattern: "deleteTranscript"
    - from: "src/app/admin/leads/[id]/page.tsx"
      to: "src/lib/lead-service.ts"
      via: "import getTranscripts"
      pattern: "getTranscripts"
---

<objective>
Creare il componente `TranscriptModal` (form per aggiungere transcript) e integrare la sezione Transcript in `LeadDetail`, con wiring nella page server.

Purpose: Completa il loop KB-02 — l'admin può incollare transcript datati e vederli elencati in ordine cronologico nel profilo lead. I dati sono pronti per essere letti dall'agente AI in Phase 21.

Output: UI completa funzionante — modal di aggiunta + lista con expand/collapse + elimina.
</objective>

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

<context>
@.planning/phases/20-knowledge-base-cliente/20-CONTEXT.md
@.planning/phases/20-knowledge-base-cliente/20-02-SUMMARY.md

<interfaces>
<!-- Pattern estratti da file esistenti — l'executor NON deve rileggere questi file -->

Da LogActivityModal.tsx — pattern modal con react-hook-form + zod + shadcn Dialog:
```typescript
"use client";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
// ... action import ...
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } 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";

export function LogActivityModal({ leadId }: { leadId: string }) {
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const form = useForm<any>({
    resolver: zodResolver(schema),
    defaultValues: { lead_id: leadId, activity_date: new Date().toISOString().split("T")[0], ... },
  });
  async function onSubmit(data) {
    setLoading(true);
    try {
      const result = await logActivity(data);
      if (result.success) { setOpen(false); form.reset({...}); }
    } finally { setLoading(false); }
  }
  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild><Button variant="outline" size="sm">...</Button></DialogTrigger>
      <DialogContent className="max-w-sm">
        ...
        <Input type="date" {...field} value={field.value || ""} />
        <Textarea className="resize-none h-24" {...field} value={field.value || ""} />
        <Button type="submit" className="w-full" disabled={loading}>...</Button>
      </DialogContent>
    </Dialog>
  );
}
```

Da LeadDetail.tsx — struttura esistente con Card shadcn + sezione attività (pattern da replicare per Transcript):
```typescript
"use client";
import { useState, useTransition } from "react";
import { useRouter } from "next/navigation";
import { Lead, Activity, Reminder } from "@/db/schema";  // ← aggiungere ClientTranscript
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { format } from "date-fns";
import { it } from "date-fns/locale";

// Signature attuale LeadDetail:
export function LeadDetail({
  lead, activities, reminders, tags, tagOptions
}: {
  lead: Lead; activities: Activity[]; reminders: Reminder[];
  tags: string[]; tagOptions: string[];
})

// Sezione Attività (pattern da replicare per Transcript):
<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">
            ...testo e date formattate con date-fns...
          </div>
        ))}
      </div>
    ) : (
      <p className="text-gray-500 text-sm">Nessuna attività registrata</p>
    )}
  </CardContent>
</Card>
```

Da page.tsx — pattern Promise.all e passaggio props:
```typescript
import { getActivityLog, getUpcomingReminders } from "@/lib/lead-service";
// ← aggiungere: import { getTranscripts } from "@/lib/lead-service";

const activities = await getActivityLog(id);
const reminders = await getUpcomingReminders(id);
// ← aggiungere nel Promise.all oppure sequenzialmente dopo

return (
  <LeadDetail
    lead={lead}
    activities={activities}
    reminders={reminders}
    tags={lead.tags}
    tagOptions={options.tags}
    // ← aggiungere: transcripts={transcripts}
  />
);
```

Tipo ClientTranscript (da schema.ts dopo Plan 02):
```typescript
export type ClientTranscript = typeof clientTranscripts.$inferSelect;
// Campi: id, lead_id, client_id, title, content, call_date, created_at
```

Formattazione date italiana con date-fns (già usato nel progetto):
```typescript
import { format } from "date-fns";
import { it } from "date-fns/locale";
// call_date è string "YYYY-MM-DD" — usare new Date(t.call_date + "T00:00:00") per evitare timezone shift
format(new Date(t.call_date + "T00:00:00"), "d MMMM yyyy", { locale: it })
// → "12 giugno 2026"
```
</interfaces>
</context>

<tasks>

<task type="auto">
  <name>Task 1: Creare TranscriptModal.tsx e aggiornare page.tsx</name>
  <files>src/components/admin/leads/TranscriptModal.tsx, src/app/admin/leads/[id]/page.tsx</files>
  <read_first>
    - src/components/admin/leads/LogActivityModal.tsx (pattern esatto del modal da replicare)
    - src/app/admin/leads/[id]/page.tsx (vedere la struttura attuale per capire dove aggiungere getTranscripts)
  </read_first>
  <action>
**Creare src/components/admin/leads/TranscriptModal.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 { addTranscript } 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 { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";

const transcriptSchema = z.object({
  lead_id: z.string().min(1),
  title: z.string().optional(),
  content: z.string().min(1, "Il testo del transcript è obbligatorio"),
  call_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Data non valida"),
});

type TranscriptInput = z.infer<typeof transcriptSchema>;

export function TranscriptModal({ leadId }: { leadId: string }) {
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const form = useForm<TranscriptInput>({
    resolver: zodResolver(transcriptSchema),
    defaultValues: {
      lead_id: leadId,
      title: "",
      content: "",
      call_date: new Date().toISOString().split("T")[0],
    },
  });

  async function onSubmit(data: TranscriptInput) {
    setLoading(true);
    setError(null);
    try {
      const result = await addTranscript(data);
      if (result.success) {
        setOpen(false);
        form.reset({
          lead_id: leadId,
          title: "",
          content: "",
          call_date: new Date().toISOString().split("T")[0],
        });
      } else {
        setError(result.error ?? "Errore nel salvataggio");
      }
    } finally {
      setLoading(false);
    }
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button variant="outline" size="sm">
          Aggiungi Transcript
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-2xl">
        <DialogHeader>
          <DialogTitle>Aggiungi Transcript Call</DialogTitle>
        </DialogHeader>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <FormField
                control={form.control}
                name="call_date"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Data call</FormLabel>
                    <FormControl>
                      <Input type="date" {...field} value={field.value || ""} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="title"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>Titolo (opzionale)</FormLabel>
                    <FormControl>
                      <Input
                        placeholder="es. Discovery call"
                        {...field}
                        value={field.value || ""}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <FormField
              control={form.control}
              name="content"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Transcript</FormLabel>
                  <FormControl>
                    <Textarea
                      placeholder="Incolla qui il testo del transcript..."
                      className="min-h-48 resize-y"
                      {...field}
                      value={field.value || ""}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            {error && <p className="text-sm text-red-600">{error}</p>}

            <Button type="submit" className="w-full" disabled={loading}>
              {loading ? "Salvataggio..." : "Salva Transcript"}
            </Button>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
```

---

**Aggiornare src/app/admin/leads/[id]/page.tsx:**

Aggiungere `getTranscripts` all'import da lead-service:
```typescript
import { getActivityLog, getUpcomingReminders, getTranscripts } from "@/lib/lead-service";
```

Aggiungere la fetch nel corpo del componente. La page attualmente fa due call sequenziali dopo il Promise.all. Aggiungere `getTranscripts(id)` in parallelo con le altre:

```typescript
const [leads, options, transcripts] = await Promise.all([
  getLeadsWithTags(),
  getLeadFieldOptions(),
  getTranscripts(id),
]);
```

Oppure, se la struttura attuale non usa Promise.all per tutte le chiamate, aggiungere sequenzialmente dopo `reminders`:
```typescript
const transcripts = await getTranscripts(id);
```

Passare la prop al componente:
```typescript
return (
  <LeadDetail
    lead={lead}
    activities={activities}
    reminders={reminders}
    tags={lead.tags}
    tagOptions={options.tags}
    transcripts={transcripts}
  />
);
```
  </action>
  <verify>
    <automated>cd /Users/simonecavalli/Vault/IAMCAVALLI && npx tsc --noEmit 2>&1 | grep -E "TranscriptModal|page" | head -10</automated>
  </verify>
  <acceptance_criteria>
    - File `src/components/admin/leads/TranscriptModal.tsx` esiste
    - `grep -c "export function TranscriptModal" src/components/admin/leads/TranscriptModal.tsx` restituisce 1
    - `grep -c "min-h-48" src/components/admin/leads/TranscriptModal.tsx` restituisce 1 (textarea generosa)
    - `grep -c "Aggiungi Transcript" src/components/admin/leads/TranscriptModal.tsx` restituisce almeno 1
    - `grep -c "getTranscripts" src/app/admin/leads/[id]/page.tsx` restituisce almeno 2 (import + chiamata)
    - `grep -c "transcripts={transcripts}" src/app/admin/leads/[id]/page.tsx` restituisce 1
    - `npx tsc --noEmit` passa senza errori su questi file
  </acceptance_criteria>
  <done>TranscriptModal creato, page.tsx aggiornata con getTranscripts e prop transcripts passata a LeadDetail.</done>
</task>

<task type="auto">
  <name>Task 2: Aggiornare LeadDetail.tsx — aggiungere prop transcripts e sezione Transcript</name>
  <files>src/components/admin/leads/LeadDetail.tsx</files>
  <read_first>
    - src/components/admin/leads/LeadDetail.tsx (leggere per vedere la struttura attuale — dove finisce la sezione Attività e dove inserire Transcript)
  </read_first>
  <action>
Aggiornare `src/components/admin/leads/LeadDetail.tsx` con le seguenti modifiche:

**1. Aggiungere import:**
```typescript
import { ClientTranscript } from "@/db/schema";
import { useTransition } from "react";  // già importato — verificare che ci sia
import { TranscriptModal } from "./TranscriptModal";
import { deleteTranscript } from "@/app/admin/leads/actions";
```

**2. Aggiungere `transcripts` alla prop interface:**
```typescript
export function LeadDetail({
  lead,
  activities,
  reminders,
  tags,
  tagOptions,
  transcripts,  // ← aggiungere
}: {
  lead: Lead;
  activities: Activity[];
  reminders: Reminder[];
  tags: string[];
  tagOptions: string[];
  transcripts: ClientTranscript[];  // ← aggiungere
})
```

**3. Aggiungere state per expand/collapse e delete nel corpo del componente:**

Aggiungere dopo gli useState esistenti:
```typescript
const [expandedIds, setExpandedIds] = useState<Set<string>>(new Set());
const [deletingId, setDeletingId] = useState<string | null>(null);
const [, startDeleteTransition] = useTransition();

function toggleExpand(id: string) {
  setExpandedIds((prev) => {
    const next = new Set(prev);
    if (next.has(id)) next.delete(id);
    else next.add(id);
    return next;
  });
}

function handleDelete(transcriptId: string) {
  setDeletingId(transcriptId);
  startDeleteTransition(async () => {
    try {
      await deleteTranscript(transcriptId, lead.id);
      router.refresh();
    } catch (e) {
      console.error("deleteTranscript error:", e);
    } finally {
      setDeletingId(null);
    }
  });
}
```

**4. Aggiungere il pulsante TranscriptModal nell'header (accanto a LogActivityModal):**
```typescript
<div className="flex gap-2">
  <LogActivityModal leadId={lead.id} />
  <TranscriptModal leadId={lead.id} />  {/* ← aggiungere */}
  <SendQuoteModal leadId={lead.id} />
  <EditLeadModal lead={lead} />
</div>
```

**5. Aggiungere la sezione Transcript dopo la sezione Storico Attività (dopo la chiusura del `</Card>` dell'attività):**

```typescript
{/* Transcript */}
<Card>
  <CardHeader className="flex flex-row items-center justify-between">
    <CardTitle>Transcript Call</CardTitle>
    <span className="text-sm text-gray-500">
      {transcripts.length} {transcripts.length === 1 ? "transcript" : "transcript"}
    </span>
  </CardHeader>
  <CardContent>
    {transcripts.length > 0 ? (
      <div className="space-y-4">
        {transcripts.map((t) => {
          const isExpanded = expandedIds.has(t.id);
          // Formattare call_date come "12 giugno 2026"
          // call_date è string "YYYY-MM-DD" — aggiungere T00:00:00 per evitare timezone shift
          const formattedDate = format(
            new Date(t.call_date + "T00:00:00"),
            "d MMMM yyyy",
            { locale: it }
          );
          // Anteprima: prime 3 righe o 200 caratteri (il primo valore raggiunto)
          const preview = t.content
            .split("\n")
            .slice(0, 3)
            .join("\n")
            .slice(0, 200);
          const hasMore = t.content.length > preview.length || t.content.split("\n").length > 3;

          return (
            <div key={t.id} className="border-l-4 border-purple-300 pl-4 pb-4">
              <div className="flex items-start justify-between gap-2">
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2 flex-wrap">
                    <span className="font-medium text-sm">{formattedDate}</span>
                    {t.title && (
                      <span className="text-gray-600 text-sm">— {t.title}</span>
                    )}
                  </div>
                  <div className="mt-2 text-sm text-gray-700 whitespace-pre-wrap">
                    {isExpanded ? t.content : preview}
                    {!isExpanded && hasMore && (
                      <span className="text-gray-400">...</span>
                    )}
                  </div>
                  {hasMore && (
                    <button
                      onClick={() => toggleExpand(t.id)}
                      className="text-xs text-blue-600 hover:underline mt-1"
                    >
                      {isExpanded ? "Mostra meno" : "Mostra tutto"}
                    </button>
                  )}
                </div>
                <Button
                  variant="ghost"
                  size="sm"
                  className="text-red-600 hover:text-red-700 shrink-0"
                  disabled={deletingId === t.id}
                  onClick={() => handleDelete(t.id)}
                >
                  {deletingId === t.id ? "..." : "Elimina"}
                </Button>
              </div>
            </div>
          );
        })}
      </div>
    ) : (
      <p className="text-gray-500 text-sm">Nessun transcript registrato</p>
    )}
  </CardContent>
</Card>
```
  </action>
  <verify>
    <automated>cd /Users/simonecavalli/Vault/IAMCAVALLI && npx tsc --noEmit 2>&1 | grep "LeadDetail" | head -10</automated>
  </verify>
  <acceptance_criteria>
    - `grep -c "transcripts: ClientTranscript\[\]" src/components/admin/leads/LeadDetail.tsx` restituisce 1
    - `grep -c "TranscriptModal" src/components/admin/leads/LeadDetail.tsx` restituisce almeno 2 (import + uso nel JSX)
    - `grep -c "deleteTranscript" src/components/admin/leads/LeadDetail.tsx` restituisce almeno 2 (import + uso in handleDelete)
    - `grep -c "Transcript Call" src/components/admin/leads/LeadDetail.tsx` restituisce 1 (titolo Card sezione)
    - `grep -c "Mostra tutto" src/components/admin/leads/LeadDetail.tsx` restituisce 1 (expand/collapse)
    - `grep -c "T00:00:00" src/components/admin/leads/LeadDetail.tsx` restituisce 1 (fix timezone per call_date)
    - `grep -c "border-l-4 border-purple-300" src/components/admin/leads/LeadDetail.tsx` restituisce 1 (stile sezione transcript, distinto dal blu delle attività)
    - `npx tsc --noEmit` passa senza errori su LeadDetail.tsx
    - `npm run build` completa senza errori (verificare alla fine)
  </acceptance_criteria>
  <done>LeadDetail aggiornato con prop transcripts, sezione Transcript con lista expand/collapse e azione Elimina posizionata dopo Storico Attività.</done>
</task>

</tasks>

<threat_model>
## Trust Boundaries

| Boundary | Descrizione |
|----------|-------------|
| browser → TranscriptModal form | Input utente admin non sanitizzato prima del submit |
| TranscriptModal → addTranscript server action | "use server" boundary — Zod valida il payload |

## STRIDE Threat Register

| Threat ID | Category | Component | Disposition | Mitigation Plan |
|-----------|----------|-----------|-------------|-----------------|
| T-20-08 | Tampering | TranscriptModal — content field | accept | Il content è testo grezzo (textarea), non renderizzato come HTML nella UI — nessun XSS possibile con `whitespace-pre-wrap` senza `dangerouslySetInnerHTML`; Zod valida min length 1 |
| T-20-09 | Elevation of Privilege | TranscriptModal — addTranscript call | mitigate | La route `/admin/leads/[id]` è protetta dal middleware Auth.js (sessione admin richiesta); `addTranscript` server action chiama `requireAdmin()` come prima istruzione |
| T-20-10 | Elevation of Privilege | deleteTranscript client call | mitigate | `deleteTranscript` server action chiama `requireAdmin()` come prima istruzione; il transcriptId viene dalla prop SSR, non da input utente libero |
| T-20-11 | Information Disclosure | Transcript content nel DOM | accept | La pagina è `/admin/*` — solo admin autenticato la vede; nessuna esposizione lato client pubblico |
</threat_model>

<verification>
```bash
cd /Users/simonecavalli/Vault/IAMCAVALLI

# Verificare che tutti i file esistano
ls -la src/components/admin/leads/TranscriptModal.tsx
grep -c "getTranscripts" src/app/admin/leads/\[id\]/page.tsx
grep -c "transcripts: ClientTranscript" src/components/admin/leads/LeadDetail.tsx

# Verificare struttura sezione Transcript
grep -n "Transcript\|deleteTranscript\|TranscriptModal" src/components/admin/leads/LeadDetail.tsx

# Build completo
npm run build 2>&1 | tail -15
```
</verification>

<success_criteria>
- `TranscriptModal.tsx` esiste con form: call_date (date input), title (optional text), content (textarea min-h-48) (KB-02)
- `LeadDetail.tsx` ha prop `transcripts: ClientTranscript[]` e sezione "Transcript Call" dopo "Storico Attività" (KB-02, D-05)
- Lista transcript mostra: data formattata in italiano, titolo se presente, anteprima testo con expand/collapse, bottone Elimina (KB-02)
- `page.tsx` chiama `getTranscripts(id)` e passa `transcripts` a `LeadDetail` (KB-02)
- `npm run build` completa senza errori TypeScript o di compilazione
</success_criteria>

<output>
Dopo il completamento, creare `.planning/phases/20-knowledge-base-cliente/20-03-SUMMARY.md` con:
- Componenti creati: TranscriptModal.tsx
- Componenti modificati: LeadDetail.tsx, page.tsx
- Features: modal aggiunta, lista con expand/collapse, eliminazione, data in italiano
- Build status: passed/failed
- Note su eventuali adattamenti ai pattern esistenti
</output>
