---
phase: 10
plan: 03
type: execute
wave: 2
depends_on: [10-01, 10-02]
files_modified:
  - src/components/admin/leads/LogActivityModal.tsx
  - src/components/admin/leads/SendQuoteModal.tsx
  - src/app/admin/leads/actions.ts
  - src/components/admin/dashboard/FollowUpWidget.tsx
  - src/app/admin/page.tsx
autonomous: true
requirements:
  - CRM-04
  - CRM-05
  - CRM-06
  - CRM-07
---

<objective>
Phase 10 CRM UI (Part 2): Implement activity logging modal (<10 sec UX), send quote button with lead status update, and follow-up reminders widget on admin dashboard. Complete the CRM workflow with activity tracking and lead progression.

Purpose: Enable admins to quickly log interactions (calls, emails, meetings, notes) and transition leads through the pipeline. "Send Quote" button creates/selects quotes and updates lead status to "proposal_sent". Follow-up widget on dashboard highlights leads needing contact (last contact > 7 days ago).

Output:
- LogActivityModal: fast form (type dropdown, date picker, optional duration, notes) with server action
- SendQuoteModal: select existing quote or create new, auto-update lead.status → "proposal_sent"
- FollowUpWidget: dashboard card showing leads needing follow-up (count + link to /admin/leads)
- Server actions: createActivity (auto-updates lead.last_contact_date), updateLeadStageViaQuote
- Activity list updates immediately after form submit
</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
@.planning/phases/10-crm-pipeline-activity-logging/10-02-SUMMARY.md
</context>

<interfaces>
From src/lib/lead-service.ts (created in Plan 1):
```typescript
export async function createActivity(data: { 
  lead_id: string; 
  type: string; 
  activity_date: Date; 
  duration_minutes?: number; 
  notes: string; 
}): Promise<Activity>;
export async function getLeadsNeedingFollowUp(daysAgo?: number): Promise<Lead[]>;
```

From src/lib/lead-validators.ts (created in Plan 1):
```typescript
export const ACTIVITY_TYPES = ["call", "email", "meeting", "note"] as const;
export const createActivitySchema: ZodType<{ lead_id, type, activity_date, duration_minutes?, notes }>;
```

From existing quote-service.ts (Phase 9):
```typescript
export async function getQuoteByTokenAdmin(token: string);
export async function createQuote(data: any): Promise<Quote>;
```
</interfaces>

<tasks>

<task type="auto">
  <name>Task 1: Create LogActivityModal component and server action</name>
  <files>src/components/admin/leads/LogActivityModal.tsx, src/app/admin/leads/actions.ts</files>
  <action>
File: `src/components/admin/leads/LogActivityModal.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 { createActivitySchema, ACTIVITY_TYPES } from "@/lib/lead-validators";
import { logActivity } 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 LogActivityInput = z.infer<typeof createActivitySchema>;

export function LogActivityModal({ leadId }: { leadId: string }) {
  const [open, setOpen] = useState(false);
  const form = useForm<LogActivityInput>({
    resolver: zodResolver(createActivitySchema),
    defaultValues: {
      lead_id: leadId,
      type: "note",
      activity_date: new Date().toISOString().split("T")[0],
    },
  });

  async function onSubmit(data: LogActivityInput) {
    const result = await logActivity(data);
    if (result.success) {
      setOpen(false);
      form.reset({
        lead_id: leadId,
        type: "note",
        activity_date: new Date().toISOString().split("T")[0],
      });
      // TODO: Toast success + revalidate parent activity log
    }
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button variant="outline" size="sm">
          Registra Attività
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-sm">
        <DialogHeader>
          <DialogTitle>Registra Attività</DialogTitle>
        </DialogHeader>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <FormField
              control={form.control}
              name="type"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Tipo</FormLabel>
                  <Select onValueChange={field.onChange} defaultValue={field.value}>
                    <FormControl>
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                    </FormControl>
                    <SelectContent>
                      {ACTIVITY_TYPES.map((type) => (
                        <SelectItem key={type} value={type}>
                          {type.charAt(0).toUpperCase() + type.slice(1)}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="activity_date"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Data</FormLabel>
                  <FormControl>
                    <Input type="date" {...field} />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="duration_minutes"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Durata (minuti) - opzionale</FormLabel>
                  <FormControl>
                    <Input 
                      type="number" 
                      placeholder="30" 
                      {...field}
                      value={field.value || ""}
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

            <FormField
              control={form.control}
              name="notes"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Note</FormLabel>
                  <FormControl>
                    <Textarea 
                      placeholder="Descrivi l'interazione..." 
                      className="resize-none h-24"
                      {...field} 
                    />
                  </FormControl>
                  <FormMessage />
                </FormItem>
              )}
            />

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

**Update src/app/admin/leads/actions.ts** — add logActivity server action:

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

  try {
    const activity = await createActivity({
      lead_id: parsed.data.lead_id,
      type: parsed.data.type,
      activity_date: new Date(parsed.data.activity_date),
      duration_minutes: parsed.data.duration_minutes,
      notes: parsed.data.notes,
    });

    revalidatePath(`/admin/leads/${parsed.data.lead_id}`);
    return { success: true, activity };
  } catch (error) {
    console.error("logActivity error:", error);
    return { success: false, error: "Errore nella registrazione" };
  }
}
```

**Design notes:**
- Fast form: type dropdown, date picker (default today), optional duration, notes textarea
- All fields required except duration
- Submit calls createActivity server action (which auto-updates lead.last_contact_date)
- Modal closes on success, form resets
- Target <10 seconds UX per CRM-05
  </action>
  <verify>
    <automated>npm run build 2>&1 | grep -c "error" | grep -q 0 && echo "LogActivity modal compiles"</automated>
  </verify>
  <done>LogActivityModal component created with fast form (<10 sec UX). Server action logActivity handles activity creation and auto-updates lead.last_contact_date. Modal closes on success.</done>
</task>

<task type="auto">
  <name>Task 2: Create SendQuoteModal component and quote assignment logic</name>
  <files>src/components/admin/leads/SendQuoteModal.tsx, src/app/admin/leads/actions.ts</files>
  <action>
File: `src/components/admin/leads/SendQuoteModal.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 { assignQuoteToLead } 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 { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Loader2 } from "lucide-react";

const assignQuoteSchema = z.object({
  lead_id: z.string(),
  quote_token: z.string().optional(),
  generate_new: z.boolean().default(false),
});

export function SendQuoteModal({ leadId }: { leadId: string }) {
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const [tab, setTab] = useState<"existing" | "new">("existing");
  const form = useForm<z.infer<typeof assignQuoteSchema>>({
    resolver: zodResolver(assignQuoteSchema),
    defaultValues: {
      lead_id: leadId,
      generate_new: false,
    },
  });

  async function onSubmit(data: z.infer<typeof assignQuoteSchema>) {
    setLoading(true);
    try {
      const result = await assignQuoteToLead({
        ...data,
        generate_new: tab === "new",
      });
      if (result.success) {
        setOpen(false);
        form.reset();
        // TODO: Toast success
      }
    } finally {
      setLoading(false);
    }
  }

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button variant="outline" size="sm">
          Invia Preventivo
        </Button>
      </DialogTrigger>
      <DialogContent className="max-w-md">
        <DialogHeader>
          <DialogTitle>Invia Preventivo al Lead</DialogTitle>
        </DialogHeader>
        <Tabs value={tab} onValueChange={(v) => setTab(v as "existing" | "new")}>
          <TabsList className="grid w-full grid-cols-2">
            <TabsTrigger value="existing">Preventivo Esistente</TabsTrigger>
            <TabsTrigger value="new">Crea Nuovo</TabsTrigger>
          </TabsList>

          <TabsContent value="existing" className="mt-4">
            <Form {...form}>
              <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
                <FormField
                  control={form.control}
                  name="quote_token"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>Token Preventivo</FormLabel>
                      <FormControl>
                        <Input 
                          placeholder="Incolla il token del preventivo" 
                          {...field} 
                        />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
                <p className="text-xs text-gray-600">
                  Copia il token dal preventivo e incollalo qui. Il lead sarà aggiornato a "Proposal Sent".
                </p>
                <Button type="submit" disabled={loading} className="w-full">
                  {loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
                  Invia
                </Button>
              </form>
            </Form>
          </TabsContent>

          <TabsContent value="new" className="mt-4">
            <p className="text-sm text-gray-600 mb-4">
              Crea un nuovo preventivo per questo lead. Ti reindirizzeremo al builder.
            </p>
            <Button 
              className="w-full"
              onClick={() => {
                // Redirect to quote builder pre-filled with this lead
                window.location.href = `/admin/quotes/new?lead_id=${leadId}`;
              }}
            >
              Apri Quote Builder
            </Button>
          </TabsContent>
        </Tabs>
      </DialogContent>
    </Dialog>
  );
}
```

**Update src/app/admin/leads/actions.ts** — add assignQuoteToLead server action:

```typescript
const assignQuoteSchema = z.object({
  lead_id: z.string().min(1),
  quote_token: z.string().optional(),
  generate_new: z.boolean(),
});

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

  try {
    if (parsed.data.generate_new) {
      // Redirect handled on client; this is a no-op
      return { success: true };
    }

    // Link quote to lead and update lead status
    const token = parsed.data.quote_token;
    const leadId = parsed.data.lead_id;

    // Find quote by token
    const [quote] = await db
      .select()
      .from(quotes)
      .where(eq(quotes.token, token))
      .limit(1);

    if (!quote) {
      return { success: false, error: "Preventivo non trovato" };
    }

    // Update quote to link to lead (if not already linked)
    await db
      .update(quotes)
      .set({ lead_id: leadId })
      .where(eq(quotes.id, quote.id));

    // Update lead status to "proposal_sent"
    await updateLeadStage(leadId, "proposal_sent");

    revalidatePath(`/admin/leads/${leadId}`);
    return { success: true };
  } catch (error) {
    console.error("assignQuoteToLead error:", error);
    return { success: false, error: "Errore nell'assegnazione" };
  }
}
```

**Design notes:**
- Two tabs: existing quote (paste token) or create new (redirect to quote builder)
- Existing quote flow: copy token from /admin/quotes page, paste here, submit
- New quote flow: opens quote builder pre-filled with lead_id query param
- Submit updates lead.status → "proposal_sent" and links quote to lead
- CRM-07 requirement satisfied: "Send Quote" button + status update
  </action>
  <verify>
    <automated>npm run build 2>&1 | grep -c "error" | grep -q 0 && echo "SendQuote modal compiles"</automated>
  </verify>
  <done>SendQuoteModal component created with two tabs (existing quote / create new). Server action assignQuoteToLead links quote to lead and updates status to "proposal_sent".</done>
</task>

<task type="auto">
  <name>Task 3: Create FollowUpWidget for admin dashboard</name>
  <files>src/components/admin/dashboard/FollowUpWidget.tsx, src/app/admin/page.tsx</files>
  <action>
File: `src/components/admin/dashboard/FollowUpWidget.tsx`

```typescript
import { getLeadsNeedingFollowUp } from "@/lib/lead-service";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { AlertCircle } from "lucide-react";
import Link from "next/link";

export async function FollowUpWidget() {
  const leadsNeedingFollowUp = await getLeadsNeedingFollowUp(7); // 7 days

  return (
    <Card className="border-orange-200 bg-orange-50">
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <AlertCircle className="h-5 w-5 text-orange-600" />
          Require Follow-up
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        {leadsNeedingFollowUp.length > 0 ? (
          <>
            <p className="text-lg font-bold text-orange-900">
              {leadsNeedingFollowUp.length} lead{leadsNeedingFollowUp.length !== 1 ? "s" : ""} to contact
            </p>
            <ul className="space-y-2 text-sm">
              {leadsNeedingFollowUp.slice(0, 3).map((lead) => (
                <li key={lead.id} className="flex justify-between items-center">
                  <span>{lead.name}</span>
                  <Button variant="ghost" size="sm" asChild>
                    <Link href={`/admin/leads/${lead.id}`}>Contact</Link>
                  </Button>
                </li>
              ))}
            </ul>
            {leadsNeedingFollowUp.length > 3 && (
              <Button variant="outline" className="w-full" asChild>
                <Link href="/admin/leads">View All ({leadsNeedingFollowUp.length})</Link>
              </Button>
            )}
          </>
        ) : (
          <p className="text-gray-600 text-sm">All leads are up to date!</p>
        )}
      </CardContent>
    </Card>
  );
}
```

**Update src/app/admin/page.tsx** — add FollowUpWidget to dashboard:

```typescript
import { Suspense } from "react";
import { FollowUpWidget } from "@/components/admin/dashboard/FollowUpWidget";
// ... other imports

export default function AdminDashboard() {
  return (
    <div className="space-y-6">
      <h1 className="text-3xl font-bold">Dashboard</h1>

      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        {/* Existing KPI cards */}
        {/* ... */}

        {/* NEW: Follow-up Widget */}
        <Suspense fallback={<div className="animate-pulse">Loading...</div>}>
          <FollowUpWidget />
        </Suspense>
      </div>

      {/* Other dashboard sections */}
    </div>
  );
}
```

**Design notes:**
- Widget shows count of leads with last_contact_date < 7 days (or null)
- Lists top 3 leads with quick "Contact" link to lead detail page
- Link to /admin/leads for full list
- Orange highlight to grab attention (follow-up needed)
- CRM-06 requirement: "Follow up today" widget on dashboard
  </action>
  <verify>
    <automated>npm run build 2>&1 | grep -c "error" | grep -q 0 && echo "Dashboard widget compiles"</automated>
  </verify>
  <done>FollowUpWidget component created for admin dashboard. Displays count of leads needing follow-up (last contact > 7 days) and quick-access links to contact them.</done>
</task>

</tasks>

<threat_model>
## Trust Boundaries

| Boundary | Description |
|----------|-------------|
| Admin → Activity Form | Server-side validation; no XSS via notes field |
| Admin → Quote Linking | Quote token validated against database; no arbitrary token acceptance |

## STRIDE Threat Register

| Threat ID | Category | Component | Disposition | Mitigation Plan |
|-----------|----------|-----------|-------------|-----------------|
| T-10-10 | Tampering | Backdating activity with future date | accept | No validation in Phase 10; assume admin honesty; add validation if abuse occurs |
| T-10-11 | Tampering | Linking wrong quote to lead | mitigate | Quote token validated; admin must copy correct token; no fuzzy matching |
| T-10-12 | Information Disclosure | Lead names visible in dashboard widget | accept | Widget shown only to authenticated admin; no PII leakage |
| T-10-13 | Denial of Service | Spam activity creation | mitigate | Server action validates; no rate limit in Phase 10; add if needed |

</threat_model>

<verification>
After Phase 10 Plan 3 execution:

1. LogActivityModal opens from lead detail page
2. Activity form submits and closes on success
3. Lead.last_contact_date auto-updates after activity logged
4. Activity list on lead detail page refreshes
5. SendQuoteModal opens with two tabs (existing / new)
6. Existing quote: paste token, submit, lead status → "proposal_sent"
7. New quote: button redirects to quote builder with lead_id param
8. Dashboard FollowUpWidget displays lead count
9. Widget links lead to detail page for follow-up contact
</verification>

<success_criteria>
- LogActivityModal renders in lead detail page with all fields (type, date, duration, notes)
- Activity form validates and submits via server action
- Lead.last_contact_date updates automatically after activity logged
- Activity list on lead detail page reflects new activity immediately
- SendQuoteModal works with existing quote token flow
- SendQuoteModal "Create New" redirects to quote builder pre-filled with lead_id
- Quote assignment updates lead.status to "proposal_sent"
- FollowUpWidget on admin dashboard shows lead count needing follow-up
- Widget lists top 3 leads with quick-access links
- All forms follow <10 sec UX pattern (CRM-05)
</success_criteria>

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