From 8c5c91830444962bb2193be4c5af6aff3e667759 Mon Sep 17 00:00:00 2001 From: Simone Cavalli Date: Mon, 15 Jun 2026 10:25:02 +0200 Subject: [PATCH] feat(12-05): build offer editor client component - Add OfferEditorClient: full editor for /admin/offers/[id]/edit - Categoria/Ticket single-select (OptionSelect) + Tipo/Obiettivo multi-select with on-the-fly creation (OptionMultiSelect) - Services matrix (A/B/C checkboxes) pre-filtered by macro.category, with live "Totale Servizi" recalculation via useMemo (OFFER-11) - Independent manual "Prezzo Pubblico" per tier (OFFER-16) - 5-field "Promessa di Trasformazione" block via EditableCell (OFFER-17) - Salva Offerta / Annulla / Archivia actions wired to saveOfferEditor, toggleOfferArchived and renameOfferOption (OFFER-15) --- .../admin/offers/OfferEditorClient.tsx | 500 ++++++++++++++++++ 1 file changed, 500 insertions(+) create mode 100644 src/components/admin/offers/OfferEditorClient.tsx diff --git a/src/components/admin/offers/OfferEditorClient.tsx b/src/components/admin/offers/OfferEditorClient.tsx new file mode 100644 index 0000000..f3ec2e9 --- /dev/null +++ b/src/components/admin/offers/OfferEditorClient.tsx @@ -0,0 +1,500 @@ +"use client"; + +import { useState, useMemo, useTransition } from "react"; +import { useRouter } from "next/navigation"; +import Link from "next/link"; +import { + saveOfferEditor, + toggleOfferArchived, + renameOfferOption, + type SaveOfferEditorPayload, +} from "@/app/admin/offers/actions"; +import { OptionSelect } from "@/components/ui/option-select"; +import { OptionMultiSelect } from "@/components/ui/option-multi-select"; +import { EditableCell } from "@/components/ui/editable-cell"; +import type { OfferEditorData, OfferFieldOptions, OfferTierData } from "@/lib/offer-queries"; + +type TierLetter = "A" | "B" | "C"; +const TIER_LETTERS: TierLetter[] = ["A", "B", "C"]; + +function emptyTier(letter: TierLetter): OfferTierData { + return { + id: "", + tier_letter: letter, + internal_name: "", + public_name: "", + duration_months: 1, + public_price: null, + assignedServiceIds: [], + servicesTotal: "0", + }; +} + +function padTiers(tiers: OfferTierData[]): OfferTierData[] { + return TIER_LETTERS.map( + (letter) => tiers.find((t) => t.tier_letter === letter) ?? emptyTier(letter) + ); +} + +function formatEuro(value: number): string { + return `€${value.toLocaleString("it-IT", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`; +} + +function formatUnitPrice(raw: string): string { + const num = parseFloat(raw); + return `€${(isNaN(num) ? 0 : num).toLocaleString("it-IT", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`; +} + +type MacroFields = { + internal_name: string; + public_name: string; + description: string; + category: string | null; + ticket: string | null; + cliente_ideale: string; + risultato: string; + tempo: string; + pain: string; + metodo: string; +}; + +export function OfferEditorClient({ + data, + fieldOptions, +}: { + data: OfferEditorData; + fieldOptions: OfferFieldOptions; +}) { + const router = useRouter(); + const [isPending, startTransition] = useTransition(); + const [saveError, setSaveError] = useState(null); + + const [macro, setMacro] = useState({ + internal_name: data.macro.internal_name, + public_name: data.macro.public_name, + description: data.macro.description ?? "", + category: data.macro.category, + ticket: data.macro.ticket, + cliente_ideale: data.macro.cliente_ideale ?? "", + risultato: data.macro.risultato ?? "", + tempo: data.macro.tempo ?? "", + pain: data.macro.pain ?? "", + metodo: data.macro.metodo ?? "", + }); + + const [tiers, setTiers] = useState(() => padTiers(data.tiers)); + const [tipoTags, setTipoTags] = useState(data.tipoTags); + const [obiettivoTags, setObiettivoTags] = useState(data.obiettivoTags); + + const [categoriaOptions, setCategoriaOptions] = useState(fieldOptions.categoria); + const [ticketOptions, setTicketOptions] = useState(fieldOptions.ticket); + const [tipoOptions, setTipoOptions] = useState(fieldOptions.tipo); + const [obiettivoOptions, setObiettivoOptions] = useState(fieldOptions.obiettivo); + + const [initialArchived] = useState(data.macro.is_archived); + + const filteredServices = useMemo(() => { + return macro.category + ? data.availableServices.filter((s) => s.category === macro.category) + : data.availableServices; + }, [macro.category, data.availableServices]); + + const tierTotals = useMemo(() => { + return tiers.map((tier) => + tier.assignedServiceIds.reduce((sum, id) => { + const service = filteredServices.find((s) => s.id === id); + return sum + Number(service?.unit_price ?? 0); + }, 0) + ); + }, [tiers, filteredServices]); + + const canSave = tiers.some((t) => t.assignedServiceIds.length > 0); + + function updateMacro(key: K, value: MacroFields[K]) { + setMacro((prev) => ({ ...prev, [key]: value })); + } + + function toggleService(tierIdx: number, serviceId: string) { + setTiers((prev) => + prev.map((tier, idx) => { + if (idx !== tierIdx) return tier; + const has = tier.assignedServiceIds.includes(serviceId); + return { + ...tier, + assignedServiceIds: has + ? tier.assignedServiceIds.filter((id) => id !== serviceId) + : [...tier.assignedServiceIds, serviceId], + }; + }) + ); + } + + function updateTierPublicPrice(tierIdx: number, value: string) { + setTiers((prev) => + prev.map((tier, idx) => (idx === tierIdx ? { ...tier, public_price: value } : tier)) + ); + } + + function handleSave() { + setSaveError(null); + const payload: SaveOfferEditorPayload = { + internal_name: macro.internal_name, + public_name: macro.public_name || macro.internal_name, + description: macro.description, + category: macro.category ?? undefined, + ticket: macro.ticket ?? undefined, + cliente_ideale: macro.cliente_ideale, + risultato: macro.risultato, + tempo: macro.tempo, + pain: macro.pain, + metodo: macro.metodo, + tiers: tiers.map((t) => ({ + id: t.id || undefined, + tier_letter: (t.tier_letter ?? "A") as "A" | "B" | "C", + internal_name: t.internal_name || `Tier ${t.tier_letter}`, + public_name: t.public_name || t.tier_letter || "Tier", + duration_months: t.duration_months || 1, + public_price: t.public_price ? Number(t.public_price) : null, + assignedServiceIds: t.assignedServiceIds, + })), + tipoTags, + obiettivoTags, + }; + + startTransition(async () => { + try { + await saveOfferEditor(data.macro.id, payload); + router.push("/admin/offers"); + } catch { + setSaveError("Errore nel salvataggio. Verifica i campi."); + } + }); + } + + function handleArchive() { + if (!window.confirm("Sei sicuro? L'offerta non sarà visibile nella lista.")) return; + startTransition(async () => { + try { + await toggleOfferArchived(data.macro.id, true); + router.push("/admin/offers"); + } catch { + setSaveError("Errore nel salvataggio. Verifica i campi."); + } + }); + } + + function handleRenameCategoria(oldValue: string, newValue: string) { + setCategoriaOptions((prev) => prev.map((o) => (o === oldValue ? newValue : o))); + if (macro.category === oldValue) updateMacro("category", newValue); + startTransition(async () => { + try { + await renameOfferOption("categoria", oldValue, newValue); + } catch { + setSaveError("Errore nel salvataggio. Verifica i campi."); + } + }); + } + + function handleRenameTicket(oldValue: string, newValue: string) { + setTicketOptions((prev) => prev.map((o) => (o === oldValue ? newValue : o))); + if (macro.ticket === oldValue) updateMacro("ticket", newValue); + startTransition(async () => { + try { + await renameOfferOption("ticket", oldValue, newValue); + } catch { + setSaveError("Errore nel salvataggio. Verifica i campi."); + } + }); + } + + function handleRenameTipo(oldValue: string, newValue: string) { + setTipoOptions((prev) => prev.map((o) => (o === oldValue ? newValue : o))); + setTipoTags((prev) => prev.map((t) => (t === oldValue ? newValue : t))); + startTransition(async () => { + try { + await renameOfferOption("tipo", oldValue, newValue); + } catch { + setSaveError("Errore nel salvataggio. Verifica i campi."); + } + }); + } + + function handleRenameObiettivo(oldValue: string, newValue: string) { + setObiettivoOptions((prev) => prev.map((o) => (o === oldValue ? newValue : o))); + setObiettivoTags((prev) => prev.map((t) => (t === oldValue ? newValue : t))); + startTransition(async () => { + try { + await renameOfferOption("obiettivo", oldValue, newValue); + } catch { + setSaveError("Errore nel salvataggio. Verifica i campi."); + } + }); + } + + return ( +
+ {/* Header & navigation */} +
+ + ← Indietro + +
+

Modifica Offerta

+
+
+

+ updateMacro("internal_name", v)} + /> +

+
+
+ + {/* Tags block */} +
+

Tag

+ +
+ Categoria + updateMacro("category", v)} + onRename={handleRenameCategoria} + placeholder="Seleziona categoria..." + /> +
+ +
+ Ticket + updateMacro("ticket", v)} + onRename={handleRenameTicket} + placeholder="Seleziona ticket..." + /> +
+ +
+ Tipo + { + setTipoTags((prev) => [...prev, v]); + if (!tipoOptions.includes(v)) setTipoOptions((prev) => [...prev, v]); + }} + onRemove={(v) => setTipoTags((prev) => prev.filter((t) => t !== v))} + onRename={handleRenameTipo} + placeholder="+ Crea Tipo" + /> +
+ +
+ Obiettivo + { + setObiettivoTags((prev) => [...prev, v]); + if (!obiettivoOptions.includes(v)) setObiettivoOptions((prev) => [...prev, v]); + }} + onRemove={(v) => setObiettivoTags((prev) => prev.filter((t) => t !== v))} + onRename={handleRenameObiettivo} + placeholder="+ Crea Obiettivo" + /> +
+
+ + {/* Services matrix */} +
+

Servizi Inclusi

+ +
+
+ + + + + + {TIER_LETTERS.map((letter) => ( + + ))} + + + + {filteredServices.length === 0 ? ( + + + + ) : ( + filteredServices.map((service) => ( + + + + {tiers.map((tier, tierIdx) => ( + + ))} + + )) + )} + + + + + {tierTotals.map((total, idx) => ( + + ))} + + + + {tiers.map((tier, tierIdx) => ( + + ))} + + +
ServizioPrezzo + {letter} +
+ Nessun servizio disponibile per questa categoria +
{service.name} + {formatUnitPrice(service.unit_price)} + + toggleService(tierIdx, service.id)} + style={{ accentColor: "#1A463C" }} + className="h-4 w-4 cursor-pointer" + /> +
+ Totale Servizi + + {formatEuro(total)} +
+ Prezzo Pubblico + + updateTierPublicPrice(tierIdx, e.target.value)} + placeholder="€0,00" + className="w-20 text-center text-sm border border-[#e5e7eb] rounded px-1 py-1 tabular-nums focus-visible:ring-1 focus-visible:ring-primary focus:outline-none" + /> +
+
+
+
+ + {/* Transformation promise block */} +
+

Promessa di Trasformazione

+ +
+ Aiuto +
+ updateMacro("cliente_ideale", v)} + /> +
+
+ +
+ A ottenere +
+ updateMacro("risultato", v)} + /> +
+
+ +
+ In +
+ updateMacro("tempo", v)} + /> +
+
+ +
+ Senza +
+ updateMacro("pain", v)} + /> +
+
+ +
+ Grazie a +
+ updateMacro("metodo", v)} + /> +
+
+
+ + {/* Action buttons */} + {saveError &&

{saveError}

} +
+ + + Annulla + + {!initialArchived && ( + + )} +
+
+ ); +}