feat(10-02): lead CRUD UI with list, detail, and form components

- /admin/leads list page with LeadTable component (all leads with status badges)
- /admin/leads/[id] detail page with full lead profile and activity log
- LeadForm component for creating/editing leads (modal dialogs)
- Server actions: createLead, updateLead, deleteLead with Zod validation
- Admin sidebar updated to include Lead link
- Added missing UI dependencies: @radix-ui/react-dialog, date-fns, Form component

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-06-11 15:37:34 +02:00
parent 0eccfe3a4d
commit 97f58d23d2
16 changed files with 1823 additions and 1 deletions
+16
View File
@@ -0,0 +1,16 @@
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} />;
}
+161
View File
@@ -0,0 +1,161 @@
"use server";
import { z } from "zod";
import { db } from "@/db";
import { leads, quotes } from "@/db/schema";
import { eq } from "drizzle-orm";
import { createLeadSchema, updateLeadSchema, createActivitySchema } from "@/lib/lead-validators";
import { revalidatePath } from "next/cache";
import { createActivity, updateLeadStage } from "@/lib/lead-service";
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 updateData: Record<string, any> = { updated_at: new Date() };
if (parsed.data.name !== undefined) updateData.name = parsed.data.name;
if (parsed.data.email !== undefined) updateData.email = parsed.data.email || null;
if (parsed.data.phone !== undefined) updateData.phone = parsed.data.phone || null;
if (parsed.data.company !== undefined) updateData.company = parsed.data.company || null;
if (parsed.data.status !== undefined) updateData.status = parsed.data.status;
if (parsed.data.notes !== undefined) updateData.notes = parsed.data.notes || null;
const [updated] = await db
.update(leads)
.set(updateData)
.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" };
}
}
// Activity logging
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" };
}
}
// Quote assignment
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;
if (!token) {
return { success: false, error: "Token preventivo richiesto" };
}
// 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" };
}
}
+25
View File
@@ -0,0 +1,25 @@
import { Suspense } from "react";
import { getAllLeads } from "@/lib/lead-service";
import { LeadTable } from "@/components/admin/leads/LeadTable";
import { CreateLeadModal } from "@/components/admin/leads/LeadForm";
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 className="animate-pulse">Loading...</div>}>
<LeadTable leads={leads} />
</Suspense>
</div>
);
}
export default function LeadsPage() {
return <LeadsList />;
}
+9
View File
@@ -1,4 +1,6 @@
import { Suspense } from "react";
import { getDashboardStats } from "@/lib/dashboard-queries";
import { FollowUpWidget } from "@/components/admin/dashboard/FollowUpWidget";
import { Users, FolderOpen, Euro, Clock } from "lucide-react";
export const revalidate = 0;
@@ -59,6 +61,13 @@ export default async function AdminDashboard() {
<div className="max-w-5xl">
<h1 className="text-2xl font-bold text-gray-900 mb-6">Dashboard</h1>
{/* Follow-up Widget */}
<div className="mb-8">
<Suspense fallback={<div className="animate-pulse h-40 bg-gray-200 rounded-lg" />}>
<FollowUpWidget />
</Suspense>
</div>
{/* KPI cards */}
<div className="grid grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
<KpiCard
+2
View File
@@ -12,11 +12,13 @@ import {
BookOpen,
Settings,
LogOut,
Zap,
} from "lucide-react";
const NAV_ITEMS = [
{ href: "/admin", label: "Dashboard", icon: LayoutDashboard, exact: true },
{ href: "/admin/clients", label: "Clienti", icon: Users },
{ href: "/admin/leads", label: "Lead", icon: Zap },
{ href: "/admin/projects", label: "Progetti", icon: FolderOpen },
{ href: "/admin/offers", label: "Offerte", icon: Tag },
{ href: "/admin/forecast", label: "Forecast", icon: TrendingUp },
@@ -0,0 +1,47 @@
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);
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>
);
}
+164
View File
@@ -0,0 +1,164 @@
"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 { it } from "date-fns/locale";
import { LogActivityModal } from "./LogActivityModal";
import { SendQuoteModal } from "./SendQuoteModal";
import { EditLeadModal } from "./LeadForm";
const ACTIVITY_ICON: Record<string, string> = {
call: "📞",
email: "📧",
meeting: "📅",
note: "📝",
};
const STAGE_COLOR: Record<string, string> = {
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 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} />
<EditLeadModal lead={lead} />
</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={STAGE_COLOR[lead.status as keyof typeof STAGE_COLOR] || ""}>
{lead.status.replace(/_/g, " ")}
</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>
);
}
+365
View File
@@ -0,0 +1,365 @@
"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 [loading, setLoading] = useState(false);
const form = useForm<any>({
resolver: zodResolver(createLeadSchema),
defaultValues: {
name: "",
email: "",
phone: "",
company: "",
status: "contacted",
notes: "",
},
});
async function onSubmit(data: CreateLeadInput) {
setLoading(true);
try {
const result = await createLead(data);
if (result.success) {
setOpen(false);
form.reset();
} else {
console.error("Error creating lead:", result.error);
}
} finally {
setLoading(false);
}
}
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} value={field.value || ""} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input
type="email"
placeholder="email@example.com"
{...field}
value={field.value || ""}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="phone"
render={({ field }) => (
<FormItem>
<FormLabel>Telefono</FormLabel>
<FormControl>
<Input
placeholder="+39 3XX XXXXXXX"
{...field}
value={field.value || ""}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="company"
render={({ field }) => (
<FormItem>
<FormLabel>Azienda</FormLabel>
<FormControl>
<Input
placeholder="Nome azienda"
{...field}
value={field.value || ""}
/>
</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}
value={field.value || ""}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit" className="w-full" disabled={loading}>
{loading ? "Creazione..." : "Crea Lead"}
</Button>
</form>
</Form>
</DialogContent>
</Dialog>
);
}
export function EditLeadModal({ lead }: { lead: Lead }) {
const [open, setOpen] = useState(false);
const [loading, setLoading] = useState(false);
const form = useForm<any>({
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) {
setLoading(true);
try {
const result = await updateLead(lead.id, data);
if (result.success) {
setOpen(false);
} else {
console.error("Error updating lead:", result.error);
}
} finally {
setLoading(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">
<FormField
control={form.control}
name="name"
render={({ field }) => (
<FormItem>
<FormLabel>Nome</FormLabel>
<FormControl>
<Input placeholder="Nome lead" {...field} value={field.value || ""} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="email"
render={({ field }) => (
<FormItem>
<FormLabel>Email</FormLabel>
<FormControl>
<Input
type="email"
placeholder="email@example.com"
{...field}
value={field.value || ""}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="phone"
render={({ field }) => (
<FormItem>
<FormLabel>Telefono</FormLabel>
<FormControl>
<Input
placeholder="+39 3XX XXXXXXX"
{...field}
value={field.value || ""}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="company"
render={({ field }) => (
<FormItem>
<FormLabel>Azienda</FormLabel>
<FormControl>
<Input
placeholder="Nome azienda"
{...field}
value={field.value || ""}
/>
</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}
value={field.value || ""}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit" className="w-full" disabled={loading}>
{loading ? "Salvataggio..." : "Salva"}
</Button>
</form>
</Form>
</DialogContent>
</Dialog>
);
}
+81
View File
@@ -0,0 +1,81 @@
"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 { it } from "date-fns/locale";
import { LEAD_STAGES } from "@/lib/lead-validators";
const STAGE_COLOR: Record<string, string> = {
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 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, " ")}
</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>
{leads.length === 0 && (
<div className="text-center py-8 text-gray-500">Nessun lead trovato</div>
)}
</div>
);
}
@@ -0,0 +1,173 @@
"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 [loading, setLoading] = useState(false);
const form = useForm<any>({
resolver: zodResolver(createActivitySchema),
defaultValues: {
lead_id: leadId,
type: "note",
activity_date: new Date().toISOString().split("T")[0],
notes: "",
},
});
async function onSubmit(data: LogActivityInput) {
setLoading(true);
try {
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],
notes: "",
});
} else {
console.error("Error logging activity:", result.error);
}
} finally {
setLoading(false);
}
}
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} value={field.value || ""} />
</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 || ""}
onChange={(e) => {
const val = e.target.value;
field.onChange(val ? parseInt(val) : undefined);
}}
/>
</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}
value={field.value || ""}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit" className="w-full" disabled={loading}>
{loading ? "Registrazione..." : "Registra"}
</Button>
</form>
</Form>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,139 @@
"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<any>({
resolver: zodResolver(assignQuoteSchema),
defaultValues: {
lead_id: leadId,
generate_new: false,
quote_token: "",
},
});
async function onSubmit(data: any) {
setLoading(true);
try {
if (tab === "new") {
// Redirect to quote builder pre-filled with this lead
window.location.href = `/admin/quotes/new?lead_id=${leadId}`;
return;
}
const result = await assignQuoteToLead({
lead_id: leadId,
quote_token: data.quote_token,
generate_new: false,
});
if (result.success) {
setOpen(false);
form.reset();
} else {
console.error("Error assigning quote:", result.error);
}
} 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}
value={field.value || ""}
/>
</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={() => {
window.location.href = `/admin/quotes/new?lead_id=${leadId}`;
}}
>
Apri Quote Builder
</Button>
</TabsContent>
</Tabs>
</DialogContent>
</Dialog>
);
}
+122
View File
@@ -0,0 +1,122 @@
"use client"
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const Dialog = DialogPrimitive.Root
const DialogTrigger = DialogPrimitive.Trigger
const DialogPortal = DialogPrimitive.Portal
const DialogClose = DialogPrimitive.Close
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
/>
))
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border border-gray-200 bg-white p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-white transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-gray-950 focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-gray-100 data-[state=open]:text-gray-500">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
))
DialogContent.displayName = DialogPrimitive.Content.displayName
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-1.5 text-center sm:text-left",
className
)}
{...props}
/>
)
DialogHeader.displayName = "DialogHeader"
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
DialogFooter.displayName = "DialogFooter"
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
))
DialogTitle.displayName = DialogPrimitive.Title.displayName
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-gray-500", className)}
{...props}
/>
))
DialogDescription.displayName = DialogPrimitive.Description.displayName
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogTrigger,
DialogClose,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
}
+174
View File
@@ -0,0 +1,174 @@
"use client"
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import {
Controller,
ControllerProps,
FieldPath,
FieldValues,
FormProvider,
useFormContext,
} from "react-hook-form"
import { cn } from "@/lib/utils"
import { Label } from "@/components/ui/label"
const Form = FormProvider
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
> = {
name: TName
}
const FormFieldContext = React.createContext<FormFieldContextValue>(
{} as FormFieldContextValue
)
const FormField = React.forwardRef<
any,
ControllerProps<any, any>
>(({ ...props }, ref) => (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
))
FormField.displayName = "FormField"
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext)
const itemContext = React.useContext(FormItemContext)
const { getFieldState, formState } = useFormContext()
const fieldState = getFieldState(fieldContext.name, formState)
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>")
}
const { id } = itemContext
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
}
}
type FormItemContextValue = {
id: string
}
const FormItemContext = React.createContext<FormItemContextValue>(
{} as FormItemContextValue
)
const FormItem = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const id = React.useId()
return (
<FormItemContext.Provider value={{ id }}>
<div ref={ref} className={cn("space-y-2", className)} {...props} />
</FormItemContext.Provider>
)
})
FormItem.displayName = "FormItem"
const FormLabel = React.forwardRef<
React.ElementRef<typeof Label>,
React.ComponentPropsWithoutRef<typeof Label>
>(({ className, ...props }, ref) => {
const { error, formItemId } = useFormField()
return (
<Label
ref={ref}
htmlFor={formItemId}
className={cn(error && "text-red-500", className)}
{...props}
/>
)
})
FormLabel.displayName = "FormLabel"
const FormControl = React.forwardRef<
React.ElementRef<typeof Slot>,
React.ComponentPropsWithoutRef<typeof Slot>
>(({ ...props }, ref) => {
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
return (
<Slot
ref={ref}
id={formItemId}
aria-describedby={
!error
? `${formDescriptionId}`
: `${formDescriptionId} ${formMessageId}`
}
aria-invalid={!!error}
{...props}
/>
)
})
FormControl.displayName = "FormControl"
const FormDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => {
const { formDescriptionId } = useFormField()
return (
<p
ref={ref}
id={formDescriptionId}
className={cn("text-sm text-gray-500", className)}
{...props}
/>
)
})
FormDescription.displayName = "FormDescription"
const FormMessage = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => {
const { error, formMessageId } = useFormField()
const body = error ? String(error?.message) : null
if (!body) {
return null
}
return (
<p
ref={ref}
id={formMessageId}
className={cn("text-sm font-medium text-red-500", className)}
{...props}
>
{body}
</p>
)
})
FormMessage.displayName = "FormMessage"
export {
useFormField,
Form,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
FormField,
}
+1 -1
View File
@@ -18,7 +18,7 @@ export const createLeadSchema = z.object({
email: z.string().email("Email valida").optional().or(z.literal("")),
phone: z.string().optional().or(z.literal("")),
company: z.string().optional().or(z.literal("")),
status: z.enum(LEAD_STAGES).default("contacted"),
status: z.enum(LEAD_STAGES),
notes: z.string().optional().or(z.literal("")),
});