Conectar funnel B2C real sin claves: captura → fotos → presupuesto

El formulario de la landing ahora crea un lead real en BD y redirige a
/solicitud/[id]/fotos, donde el cliente sube fotos y datos de la reforma.
El orquestador simula los pasos de IA (pre-llamada, llamada, render) y
calcula el presupuesto DE VERDAD con el catálogo del reformista, dejando
el lead listo en el panel con render y desglose.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Carlos Narro
2026-05-31 14:29:21 +02:00
parent b95c588efe
commit b582f3ac33
10 changed files with 733 additions and 19 deletions

View File

@@ -0,0 +1,133 @@
import { notFound } from 'next/navigation';
import { getPublicLead } from '@/lib/funnel/public-queries';
import { PIPELINE_ORDER, PIPELINE_LABEL, TIPO_LABEL, formatEuros } from '@/lib/funnel';
import type { BudgetResult } from '@/budget/types';
export const dynamic = 'force-dynamic';
export default async function EstadoPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const data = await getPublicLead(id);
if (!data) notFound();
const { lead, eventos } = data;
const reachedStages = new Set(eventos.map((e) => e.stage));
const snapshot = lead.desgloseSnapshot as { result: BudgetResult } | null;
const desglose = snapshot?.result ?? null;
const entregado = lead.pipelineStage === 'whatsapp_entregado';
const tipo = lead.tipoReforma ? TIPO_LABEL[lead.tipoReforma] : 'tu reforma';
return (
<div className="flex flex-col gap-6">
{/* Cabecera de éxito */}
<div className="flex flex-col items-center text-center gap-3">
<div className="w-14 h-14 bg-black text-white rounded-full flex items-center justify-center">
<svg width="26" height="26" viewBox="0 0 32 32" fill="none" aria-hidden="true">
<path
d="M6 16l7 7L26 9"
stroke="currentColor"
strokeWidth="3"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</div>
<h1 className="text-2xl font-black tracking-tight text-black">
¡Tu presupuesto está listo, {lead.nombre.split(' ')[0]}!
</h1>
<p className="text-sm text-gray-500 leading-relaxed max-w-md">
{entregado
? 'Te lo hemos enviado por WhatsApp. Aquí tienes un adelanto del render y el presupuesto orientativo de tu reforma.'
: 'Estamos preparando tu render y presupuesto. En breve lo recibirás por WhatsApp.'}
</p>
</div>
{/* Render */}
{lead.renderUrl && (
<div className="bg-white border border-gray-200 rounded-xl overflow-hidden shadow-sm">
<div className="px-5 py-3 border-b border-gray-100">
<h2 className="text-xs uppercase tracking-wide font-semibold text-gray-400">
Render de {tipo.toLowerCase()}
</h2>
</div>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img src={lead.renderUrl} alt="Render de tu reforma" className="w-full object-cover" />
</div>
)}
{/* Presupuesto */}
{desglose ? (
<div className="bg-white border border-gray-200 rounded-xl p-6 shadow-sm flex flex-col gap-4">
<div className="flex items-end justify-between gap-4">
<div>
<div className="text-xs text-gray-400 uppercase tracking-wide">
Presupuesto orientativo
</div>
<div className="text-3xl font-black text-black">{formatEuros(desglose.total)}</div>
</div>
<div className="text-right text-sm text-gray-500">
<div className="text-xs text-gray-400">Rango estimado</div>
{formatEuros(desglose.rango.min)} {formatEuros(desglose.rango.max)}
</div>
</div>
<ul className="flex flex-col divide-y divide-gray-100 text-sm">
{desglose.partidas.map((p) => (
<li key={p.key} className="flex justify-between py-2">
<span className="text-gray-600">{p.label}</span>
<span className="text-black font-medium">{formatEuros(p.importe)}</span>
</li>
))}
</ul>
{desglose.avisos.length > 0 && (
<ul className="text-xs text-amber-700 bg-amber-50 rounded-lg p-3 flex flex-col gap-1">
{desglose.avisos.map((aviso, i) => (
<li key={i}> {aviso}</li>
))}
</ul>
)}
<p className="text-xs text-gray-400">
Presupuesto orientativo. El precio final puede variar según la visita técnica.
</p>
</div>
) : (
<div className="bg-white border border-gray-200 rounded-xl p-6 shadow-sm text-center text-sm text-gray-500">
Calculando tu presupuesto
</div>
)}
{/* Progreso del pipeline */}
<div className="bg-white border border-gray-200 rounded-xl p-6 shadow-sm">
<h2 className="text-xs uppercase tracking-wide font-semibold text-gray-400 mb-3">
Estado de tu solicitud
</h2>
<ol className="flex flex-col gap-2">
{PIPELINE_ORDER.map((stage) => {
const reached = reachedStages.has(stage);
return (
<li key={stage} className="flex items-center gap-3 text-sm">
<span
className={`w-2.5 h-2.5 rounded-full shrink-0 ${
reached ? 'bg-green-500' : 'bg-gray-200'
}`}
/>
<span className={reached ? 'text-black font-medium' : 'text-gray-400'}>
{PIPELINE_LABEL[stage]}
</span>
</li>
);
})}
</ol>
</div>
{entregado && (
<div className="text-sm font-medium text-green-700 bg-green-50 rounded-lg px-4 py-3 text-center">
Presupuesto enviado a tu WhatsApp
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,35 @@
import { notFound } from 'next/navigation';
import { getPublicLead } from '@/lib/funnel/public-queries';
import { guardarDetallesYFotos } from '../../actions';
import FotosUploader from '@/components/funnel/FotosUploader';
export const dynamic = 'force-dynamic';
export default async function FotosPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const data = await getPublicLead(id);
if (!data) notFound();
const { lead } = data;
return (
<div className="flex flex-col gap-6">
<div className="flex flex-col gap-2">
<span className="text-xs font-semibold uppercase tracking-widest text-gray-400">
Paso 2 de 2
</span>
<h1 className="text-2xl font-black tracking-tight text-black">
Hola {lead.nombre.split(' ')[0]}, cuéntanos sobre tu reforma
</h1>
<p className="text-sm text-gray-500 leading-relaxed">
Sube unas fotos del espacio y dinos qué tienes en mente. Con eso preparamos tu render y un
presupuesto orientativo en menos de un minuto.
</p>
</div>
<div className="bg-white border border-gray-200 rounded-xl p-6 md:p-8 shadow-sm">
<FotosUploader action={guardarDetallesYFotos.bind(null, id)} />
</div>
</div>
);
}

View File

@@ -0,0 +1,140 @@
'use server';
import { z } from 'zod';
import { and, eq } from 'drizzle-orm';
import { redirect } from 'next/navigation';
import { revalidatePath } from 'next/cache';
import { db } from '@/db';
import { leads, leadFotos, leadPipelineEventos } from '@/db/schema';
import { getDemoTenantId } from '@/lib/funnel/public-queries';
import { procesarLead } from '@/lib/funnel/orchestrator';
const MAX_FOTOS = 4;
const MAX_FOTO_BYTES = 6 * 1024 * 1024; // 6 MB por foto
const crearLeadSchema = z.object({
nombre: z.string().trim().min(2, 'El nombre es obligatorio'),
email: z.string().trim().email('Introduce un email válido'),
telefono: z
.string()
.trim()
.regex(/^[+\d\s\-().]{7,20}$/, 'Introduce un teléfono válido'),
consentPrivacidad: z.boolean(),
consentContratacion: z.boolean(),
});
export type CrearLeadInput = z.input<typeof crearLeadSchema>;
export type CrearLeadResult =
| { ok: true; leadId: string }
| { ok: false; error: string };
export async function crearLead(input: CrearLeadInput): Promise<CrearLeadResult> {
const parsed = crearLeadSchema.safeParse(input);
if (!parsed.success) {
return { ok: false, error: parsed.error.issues[0]?.message ?? 'Datos inválidos.' };
}
const data = parsed.data;
// RF-LEG-01: los dos consentimientos son obligatorios para iniciar el funnel.
if (!data.consentPrivacidad || !data.consentContratacion) {
return { ok: false, error: 'Debes aceptar la política de privacidad y las condiciones.' };
}
const tenantId = await getDemoTenantId();
const [lead] = await db
.insert(leads)
.values({
tenantId,
nombre: data.nombre,
email: data.email,
telefono: data.telefono,
consentPrivacidad: data.consentPrivacidad,
consentContratacion: data.consentContratacion,
pipelineStage: 'form_completado',
estado: 'nuevo',
})
.returning({ id: leads.id });
await db.insert(leadPipelineEventos).values({
leadId: lead.id,
stage: 'form_completado',
metadata: { origen: 'landing' },
});
return { ok: true, leadId: lead.id };
}
const TIPOS = ['cocina', 'bano', 'salon', 'comedor', 'integral', 'otro'] as const;
const CALIDADES = ['basica', 'media', 'premium'] as const;
async function fileToDataUri(file: File): Promise<string | null> {
if (file.size === 0 || file.size > MAX_FOTO_BYTES) return null;
if (!file.type.startsWith('image/')) return null;
const buffer = Buffer.from(await file.arrayBuffer());
return `data:${file.type};base64,${buffer.toString('base64')}`;
}
// Paso 3 del funnel: el cliente sube fotos y confirma los datos clave de la reforma.
// Guardamos las fotos como data URI (no hay storage externo en esta fase) y disparamos
// el orquestador que simula la llamada/render y calcula el presupuesto real.
export async function guardarDetallesYFotos(leadId: string, formData: FormData): Promise<void> {
const tenantId = await getDemoTenantId();
const [lead] = await db
.select()
.from(leads)
.where(and(eq(leads.id, leadId), eq(leads.tenantId, tenantId)))
.limit(1);
if (!lead) throw new Error('Solicitud no encontrada.');
const tipoRaw = String(formData.get('tipoReforma') ?? '');
const calidadRaw = String(formData.get('calidad') ?? '');
const m2Raw = Number(formData.get('m2'));
const provincia = String(formData.get('provincia') ?? '').trim() || null;
const tipoReforma = (TIPOS as readonly string[]).includes(tipoRaw)
? (tipoRaw as (typeof TIPOS)[number])
: 'otro';
const calidadGlobal = (CALIDADES as readonly string[]).includes(calidadRaw)
? (calidadRaw as (typeof CALIDADES)[number])
: 'media';
const m2Suelo = Number.isFinite(m2Raw) && m2Raw > 0 ? m2Raw : null;
const archivos = formData.getAll('fotos').filter((f): f is File => f instanceof File);
const dataUris: string[] = [];
for (const file of archivos.slice(0, MAX_FOTOS)) {
const uri = await fileToDataUri(file);
if (uri) dataUris.push(uri);
}
if (dataUris.length > 0) {
await db.insert(leadFotos).values(
dataUris.map((url, orden) => ({ leadId, url, orden }))
);
}
await db
.update(leads)
.set({
tipoReforma,
calidadGlobal,
m2Suelo,
provincia,
pipelineStage: 'fotos_subidas',
updatedAt: new Date(),
})
.where(and(eq(leads.id, leadId), eq(leads.tenantId, tenantId)));
await db.insert(leadPipelineEventos).values({
leadId,
stage: 'fotos_subidas',
metadata: { fotos: dataUris.length },
});
// Dispara el resto del pipeline (llamada simulada → render → presupuesto real → WhatsApp).
await procesarLead(leadId);
revalidatePath('/panel');
redirect(`/solicitud/${leadId}/estado`);
}

View File

@@ -0,0 +1,26 @@
import Link from 'next/link';
export default function SolicitudLayout({ children }: { children: React.ReactNode }) {
return (
<div className="min-h-screen bg-gray-50 flex flex-col">
<header className="bg-white border-b border-gray-200">
<div className="container py-4 flex items-center justify-between">
<Link href="/" className="text-lg font-black tracking-tight text-black">
Reformix
</Link>
<span className="text-xs font-semibold uppercase tracking-widest text-gray-400">
Tu presupuesto
</span>
</div>
</header>
<main className="flex-1">
<div className="container py-10 max-w-2xl">{children}</div>
</main>
<footer className="border-t border-gray-200 bg-white">
<div className="container py-6 text-xs text-gray-400 text-center">
Reformix · Presupuesto orientativo. El precio final puede variar según la visita técnica.
</div>
</footer>
</div>
);
}