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:
133
mvp/b2c/src/app/solicitud/[id]/estado/page.tsx
Normal file
133
mvp/b2c/src/app/solicitud/[id]/estado/page.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
35
mvp/b2c/src/app/solicitud/[id]/fotos/page.tsx
Normal file
35
mvp/b2c/src/app/solicitud/[id]/fotos/page.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
140
mvp/b2c/src/app/solicitud/actions.ts
Normal file
140
mvp/b2c/src/app/solicitud/actions.ts
Normal 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`);
|
||||
}
|
||||
26
mvp/b2c/src/app/solicitud/layout.tsx
Normal file
26
mvp/b2c/src/app/solicitud/layout.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
'use client';
|
||||
|
||||
import { useState, useRef, useEffect, FormEvent } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { crearLead } from '@/app/solicitud/actions';
|
||||
|
||||
type FormData = {
|
||||
name: string;
|
||||
@@ -44,6 +46,8 @@ export default function ContactForm() {
|
||||
const [errors, setErrors] = useState<FormErrors>({});
|
||||
const [touched, setTouched] = useState<Partial<Record<keyof FormData, boolean>>>({});
|
||||
const [status, setStatus] = useState<SubmitStatus>('idle');
|
||||
const [submitError, setSubmitError] = useState<string | null>(null);
|
||||
const router = useRouter();
|
||||
const sectionRef = useRef<HTMLElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -94,13 +98,20 @@ export default function ContactForm() {
|
||||
if (!consentsGranted) return;
|
||||
|
||||
setStatus('loading');
|
||||
// TODO: integrar con backend captación (lead -> pending_photos). De momento mock.
|
||||
await new Promise((resolve) => setTimeout(resolve, 1500));
|
||||
setStatus('success');
|
||||
setFormData(initialData);
|
||||
setConsents(initialConsents);
|
||||
setTouched({});
|
||||
setErrors({});
|
||||
setSubmitError(null);
|
||||
const result = await crearLead({
|
||||
nombre: formData.name,
|
||||
email: formData.email,
|
||||
telefono: formData.phone,
|
||||
consentPrivacidad: consents.privacy,
|
||||
consentContratacion: consents.contracting,
|
||||
});
|
||||
if (!result.ok) {
|
||||
setStatus('error');
|
||||
setSubmitError(result.error);
|
||||
return;
|
||||
}
|
||||
router.push(`/solicitud/${result.leadId}/fotos`);
|
||||
};
|
||||
|
||||
const handleReset = () => {
|
||||
@@ -405,6 +416,12 @@ export default function ContactForm() {
|
||||
</label>
|
||||
</fieldset>
|
||||
|
||||
{submitError && (
|
||||
<p className="text-sm text-error font-medium" role="alert">
|
||||
{submitError}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Submit */}
|
||||
<button
|
||||
type="submit"
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { crearLead } from '@/app/solicitud/actions';
|
||||
|
||||
type FormData = {
|
||||
name: string;
|
||||
@@ -39,11 +41,13 @@ function validateForm(data: FormData): FormErrors {
|
||||
}
|
||||
|
||||
function LeadForm() {
|
||||
const router = useRouter();
|
||||
const [formData, setFormData] = useState<FormData>(initialData);
|
||||
const [consents, setConsents] = useState(initialConsents);
|
||||
const [errors, setErrors] = useState<FormErrors>({});
|
||||
const [touched, setTouched] = useState<Partial<Record<keyof FormData, boolean>>>({});
|
||||
const [status, setStatus] = useState<SubmitStatus>('idle');
|
||||
const [submitError, setSubmitError] = useState<string | null>(null);
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const { name, value } = e.target;
|
||||
@@ -74,12 +78,20 @@ function LeadForm() {
|
||||
if (!consentsGranted) return;
|
||||
|
||||
setStatus('loading');
|
||||
await new Promise((resolve) => setTimeout(resolve, 1500));
|
||||
setStatus('success');
|
||||
setFormData(initialData);
|
||||
setConsents(initialConsents);
|
||||
setTouched({});
|
||||
setErrors({});
|
||||
setSubmitError(null);
|
||||
const result = await crearLead({
|
||||
nombre: formData.name,
|
||||
email: formData.email,
|
||||
telefono: formData.phone,
|
||||
consentPrivacidad: consents.privacy,
|
||||
consentContratacion: consents.contracting,
|
||||
});
|
||||
if (!result.ok) {
|
||||
setStatus('error');
|
||||
setSubmitError(result.error);
|
||||
return;
|
||||
}
|
||||
router.push(`/solicitud/${result.leadId}/fotos`);
|
||||
};
|
||||
|
||||
const handleReset = () => {
|
||||
@@ -273,6 +285,12 @@ function LeadForm() {
|
||||
</label>
|
||||
</fieldset>
|
||||
|
||||
{submitError && (
|
||||
<p className="text-xs text-error font-medium" role="alert">
|
||||
{submitError}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Submit */}
|
||||
<button
|
||||
type="submit"
|
||||
|
||||
153
mvp/b2c/src/components/funnel/FotosUploader.tsx
Normal file
153
mvp/b2c/src/components/funnel/FotosUploader.tsx
Normal file
@@ -0,0 +1,153 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useFormStatus } from 'react-dom';
|
||||
import { TIPO_LABEL } from '@/lib/funnel';
|
||||
|
||||
const TIPOS = ['cocina', 'bano', 'salon', 'comedor', 'integral', 'otro'] as const;
|
||||
const CALIDADES = [
|
||||
{ value: 'basica', label: 'Básica' },
|
||||
{ value: 'media', label: 'Media' },
|
||||
{ value: 'premium', label: 'Premium' },
|
||||
] as const;
|
||||
|
||||
const MAX_FOTOS = 4;
|
||||
|
||||
const inputClass =
|
||||
'w-full px-4 py-3 text-base font-sans text-dark bg-white border-[1.5px] border-gray-200 rounded-lg transition-all duration-150 outline-none placeholder:text-gray-400 focus:border-black focus:shadow-[0_0_0_3px_rgba(0,0,0,0.06)]';
|
||||
|
||||
function SubmitButton({ disabled }: { disabled: boolean }) {
|
||||
const { pending } = useFormStatus();
|
||||
return (
|
||||
<button
|
||||
type="submit"
|
||||
className="btn btn-primary btn-lg w-full justify-center mt-1 disabled:opacity-60 disabled:cursor-not-allowed disabled:transform-none"
|
||||
disabled={pending || disabled}
|
||||
aria-busy={pending}
|
||||
>
|
||||
{pending ? (
|
||||
<>
|
||||
<span
|
||||
className="w-[18px] h-[18px] border-2 border-white/30 border-t-white rounded-full animate-[spin_0.7s_linear_infinite] shrink-0"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
Generando tu presupuesto...
|
||||
</>
|
||||
) : (
|
||||
'Generar mi presupuesto'
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export default function FotosUploader({
|
||||
action,
|
||||
}: {
|
||||
action: (formData: FormData) => void | Promise<void>;
|
||||
}) {
|
||||
const [previews, setPreviews] = useState<string[]>([]);
|
||||
|
||||
const handleFiles = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const files = Array.from(e.target.files ?? []).slice(0, MAX_FOTOS);
|
||||
previews.forEach((url) => URL.revokeObjectURL(url));
|
||||
setPreviews(files.map((f) => URL.createObjectURL(f)));
|
||||
};
|
||||
|
||||
return (
|
||||
<form action={action} className="flex flex-col gap-5">
|
||||
{/* Fotos */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<label htmlFor="fotos" className="text-sm font-semibold text-dark">
|
||||
Sube fotos del espacio <span className="text-gray-400 font-normal">(hasta {MAX_FOTOS})</span>
|
||||
</label>
|
||||
<input
|
||||
id="fotos"
|
||||
name="fotos"
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
onChange={handleFiles}
|
||||
className="block w-full text-sm text-gray-600 file:mr-4 file:py-2.5 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-black file:text-white hover:file:bg-gray-800 file:cursor-pointer cursor-pointer"
|
||||
/>
|
||||
{previews.length > 0 && (
|
||||
<div className="flex flex-wrap gap-3 mt-2">
|
||||
{previews.map((url, i) => (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
key={i}
|
||||
src={url}
|
||||
alt=""
|
||||
className="w-20 h-20 object-cover rounded-lg border border-gray-200"
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Tipo de reforma */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<label htmlFor="tipoReforma" className="text-sm font-semibold text-dark">
|
||||
¿Qué quieres reformar?
|
||||
</label>
|
||||
<select id="tipoReforma" name="tipoReforma" defaultValue="cocina" className={inputClass}>
|
||||
{TIPOS.map((t) => (
|
||||
<option key={t} value={t}>
|
||||
{TIPO_LABEL[t]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* m2 + calidad */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div className="flex flex-col gap-2">
|
||||
<label htmlFor="m2" className="text-sm font-semibold text-dark">
|
||||
Metros cuadrados <span className="text-gray-400 font-normal">(aprox.)</span>
|
||||
</label>
|
||||
<input
|
||||
id="m2"
|
||||
name="m2"
|
||||
type="number"
|
||||
min="1"
|
||||
step="1"
|
||||
inputMode="numeric"
|
||||
placeholder="12"
|
||||
className={inputClass}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<label htmlFor="calidad" className="text-sm font-semibold text-dark">
|
||||
Nivel de acabado
|
||||
</label>
|
||||
<select id="calidad" name="calidad" defaultValue="media" className={inputClass}>
|
||||
{CALIDADES.map((c) => (
|
||||
<option key={c.value} value={c.value}>
|
||||
{c.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Provincia */}
|
||||
<div className="flex flex-col gap-2">
|
||||
<label htmlFor="provincia" className="text-sm font-semibold text-dark">
|
||||
Provincia
|
||||
</label>
|
||||
<input
|
||||
id="provincia"
|
||||
name="provincia"
|
||||
type="text"
|
||||
placeholder="Madrid"
|
||||
autoComplete="address-level1"
|
||||
className={inputClass}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<SubmitButton disabled={false} />
|
||||
<p className="text-xs text-gray-400 text-center">
|
||||
Calculamos un presupuesto orientativo con tus datos. Sin compromiso.
|
||||
</p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -6,8 +6,7 @@ import { getCurrentTenantId as getTenantId } from '@/lib/auth/current-user';
|
||||
|
||||
export type EnvioMode = (typeof tenants.envioPresupuesto.enumValues)[number];
|
||||
|
||||
export async function getEnvioMode(): Promise<EnvioMode> {
|
||||
const tenantId = await getTenantId();
|
||||
export async function getEnvioModeFor(tenantId: string): Promise<EnvioMode> {
|
||||
const [row] = await db
|
||||
.select({ modo: tenants.envioPresupuesto })
|
||||
.from(tenants)
|
||||
@@ -16,6 +15,10 @@ export async function getEnvioMode(): Promise<EnvioMode> {
|
||||
return row?.modo ?? 'automatico';
|
||||
}
|
||||
|
||||
export async function getEnvioMode(): Promise<EnvioMode> {
|
||||
return getEnvioModeFor(await getTenantId());
|
||||
}
|
||||
|
||||
const MANO_OBRA_DEFAULT: Record<ManoObraKey, number> = {
|
||||
demolicion: 0,
|
||||
fontaneria: 0,
|
||||
@@ -23,8 +26,7 @@ const MANO_OBRA_DEFAULT: Record<ManoObraKey, number> = {
|
||||
mano_de_obra: 0,
|
||||
};
|
||||
|
||||
export async function getPricingConfig(): Promise<PricingConfig> {
|
||||
const tenantId = await getTenantId();
|
||||
export async function getPricingConfigFor(tenantId: string): Promise<PricingConfig> {
|
||||
const [row] = await db
|
||||
.select()
|
||||
.from(pricingConfig)
|
||||
@@ -41,8 +43,11 @@ export async function getPricingConfig(): Promise<PricingConfig> {
|
||||
};
|
||||
}
|
||||
|
||||
export async function getCatalog(): Promise<CatalogItem[]> {
|
||||
const tenantId = await getTenantId();
|
||||
export async function getPricingConfig(): Promise<PricingConfig> {
|
||||
return getPricingConfigFor(await getTenantId());
|
||||
}
|
||||
|
||||
export async function getCatalogFor(tenantId: string): Promise<CatalogItem[]> {
|
||||
const rows = await db.select().from(catalogItems).where(eq(catalogItems.tenantId, tenantId));
|
||||
return rows.map((r) => ({
|
||||
id: r.id,
|
||||
@@ -57,4 +62,8 @@ export async function getCatalog(): Promise<CatalogItem[]> {
|
||||
}));
|
||||
}
|
||||
|
||||
export async function getCatalog(): Promise<CatalogItem[]> {
|
||||
return getCatalogFor(await getTenantId());
|
||||
}
|
||||
|
||||
export { getTenantId };
|
||||
|
||||
141
mvp/b2c/src/lib/funnel/orchestrator.ts
Normal file
141
mvp/b2c/src/lib/funnel/orchestrator.ts
Normal file
@@ -0,0 +1,141 @@
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { db } from '@/db';
|
||||
import { leads, leadPipelineEventos } from '@/db/schema';
|
||||
import { getPricingConfigFor, getCatalogFor, getEnvioModeFor } from '@/db/pricing-queries';
|
||||
import { computeBudget } from '@/budget';
|
||||
import type { BudgetInputs } from '@/budget/types';
|
||||
import type { Lead } from '@/db/schema';
|
||||
|
||||
// Render demo por tipo de reforma. No hay generación IA real en esta fase (keyless):
|
||||
// reusamos los renders de muestra del directorio público.
|
||||
const RENDER_POR_TIPO: Record<NonNullable<Lead['tipoReforma']>, string> = {
|
||||
cocina: '/despues.webp',
|
||||
bano: '/despues-bano.webp',
|
||||
salon: '/despues-comedor.webp',
|
||||
comedor: '/despues-comedor.webp',
|
||||
integral: '/despues.webp',
|
||||
otro: '/despues.webp',
|
||||
};
|
||||
|
||||
const TIPO_TEXTO: Record<NonNullable<Lead['tipoReforma']>, string> = {
|
||||
cocina: 'la cocina',
|
||||
bano: 'el baño',
|
||||
salon: 'el salón',
|
||||
comedor: 'el comedor',
|
||||
integral: 'el piso entero',
|
||||
otro: 'la reforma',
|
||||
};
|
||||
|
||||
function construirTranscripcion(lead: Lead): string {
|
||||
const tipo = lead.tipoReforma ?? 'otro';
|
||||
const m2 = lead.m2Suelo ? `${Math.round(lead.m2Suelo)} metros` : 'el espacio';
|
||||
const calidad = lead.calidadGlobal ?? 'media';
|
||||
return [
|
||||
`Agente: Hola ${lead.nombre.split(' ')[0]}, te llamo de Reformas Ejemplo. Te aviso de que soy un asistente con inteligencia artificial y de que la llamada queda grabada. ¿Tienes un momento?`,
|
||||
`Cliente: Sí, sin problema.`,
|
||||
`Agente: Perfecto. Me comentas que quieres reformar ${TIPO_TEXTO[tipo]}, ¿unos ${m2} aproximadamente?`,
|
||||
`Cliente: Eso es, ${m2}. Quiero un acabado de calidad ${calidad}.`,
|
||||
`Agente: Genial. Con las fotos que has subido y estos datos te preparo ahora mismo el render y el presupuesto orientativo, y te lo enviamos por WhatsApp. Muchas gracias.`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function construirEntidades(lead: Lead) {
|
||||
return {
|
||||
espacio: lead.tipoReforma ?? 'otro',
|
||||
m2_aprox: lead.m2Suelo ?? null,
|
||||
calidad: lead.calidadGlobal ?? 'media',
|
||||
provincia: lead.provincia ?? null,
|
||||
estructural: lead.estructural,
|
||||
};
|
||||
}
|
||||
|
||||
// Avanza un lead recién capturado por todo el pipeline B2C.
|
||||
// Los pasos de IA (pre-llamada, llamada, render) se simulan de forma realista;
|
||||
// el presupuesto se calcula DE VERDAD con el motor y el catálogo del reformista.
|
||||
// Respeta la preferencia de envío del reformista: 'automatico' entrega por WhatsApp,
|
||||
// 'revision' se detiene en 'presupuesto_generado' para que el reformista lo revise.
|
||||
export async function procesarLead(leadId: string): Promise<void> {
|
||||
const [lead] = await db.select().from(leads).where(eq(leads.id, leadId)).limit(1);
|
||||
if (!lead) throw new Error('Lead no encontrado.');
|
||||
|
||||
const tipo = lead.tipoReforma ?? 'otro';
|
||||
|
||||
// Paso 4: pre-llamada (SMS + WhatsApp)
|
||||
await db.insert(leadPipelineEventos).values({
|
||||
leadId,
|
||||
stage: 'prellamada_enviada',
|
||||
metadata: { via: ['sms', 'whatsapp'], simulado: true },
|
||||
});
|
||||
|
||||
// Paso 5: llamada del agente IA completada
|
||||
const transcripcion = construirTranscripcion(lead);
|
||||
const entidades = construirEntidades(lead);
|
||||
await db.insert(leadPipelineEventos).values({
|
||||
leadId,
|
||||
stage: 'llamada_completada',
|
||||
metadata: { simulado: true, duracionSeg: 95 },
|
||||
});
|
||||
|
||||
// Paso 6a: render IA generado
|
||||
const renderUrl = RENDER_POR_TIPO[tipo];
|
||||
await db.insert(leadPipelineEventos).values({
|
||||
leadId,
|
||||
stage: 'render_generado',
|
||||
metadata: { simulado: true, renderUrl },
|
||||
});
|
||||
|
||||
// Paso 6b: presupuesto calculado (REAL) con el catálogo del reformista
|
||||
const [config, catalog] = await Promise.all([
|
||||
getPricingConfigFor(lead.tenantId),
|
||||
getCatalogFor(lead.tenantId),
|
||||
]);
|
||||
const inputs: BudgetInputs = {
|
||||
tipoReforma: tipo,
|
||||
m2Suelo: lead.m2Suelo ?? null,
|
||||
alturaTecho: lead.alturaTecho ?? null,
|
||||
calidadGlobal: lead.calidadGlobal ?? 'media',
|
||||
estructural: lead.estructural,
|
||||
provincia: lead.provincia ?? null,
|
||||
materialSelections: (lead.materialSelections as Record<string, string>) ?? {},
|
||||
};
|
||||
const result = computeBudget(inputs, config, catalog);
|
||||
|
||||
await db
|
||||
.update(leads)
|
||||
.set({
|
||||
transcripcion,
|
||||
entidades,
|
||||
renderUrl,
|
||||
presupuestoEstimado: result.total,
|
||||
desgloseSnapshot: { stage: 'presupuesto_generado', result },
|
||||
pipelineStage: 'presupuesto_generado',
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(leads.id, leadId));
|
||||
|
||||
await db.insert(leadPipelineEventos).values({
|
||||
leadId,
|
||||
stage: 'presupuesto_generado',
|
||||
metadata: { total: result.total, confianza: result.confianza },
|
||||
});
|
||||
|
||||
// Paso 7: entrega por WhatsApp si el reformista tiene envío automático.
|
||||
const envio = await getEnvioModeFor(lead.tenantId);
|
||||
if (envio === 'automatico') {
|
||||
await db
|
||||
.update(leads)
|
||||
.set({
|
||||
pipelineStage: 'whatsapp_entregado',
|
||||
estado: 'presupuesto_enviado',
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(leads.id, leadId));
|
||||
await db.insert(leadPipelineEventos).values({
|
||||
leadId,
|
||||
stage: 'whatsapp_entregado',
|
||||
metadata: { via: 'whatsapp', simulado: true, total: result.total },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export { RENDER_POR_TIPO };
|
||||
42
mvp/b2c/src/lib/funnel/public-queries.ts
Normal file
42
mvp/b2c/src/lib/funnel/public-queries.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { and, asc, eq } from 'drizzle-orm';
|
||||
import { db } from '@/db';
|
||||
import { tenants, leads, leadFotos, leadPipelineEventos } from '@/db/schema';
|
||||
import { TENANT_SLUG } from '@/lib/funnel';
|
||||
|
||||
// Tenant demo del MVP ("Reformas Ejemplo"). El funnel público es anónimo:
|
||||
// todos los leads se atribuyen a este reformista hasta que multi-tenant B2C (F1.5) exista.
|
||||
export async function getDemoTenantId(): Promise<string> {
|
||||
const [row] = await db
|
||||
.select({ id: tenants.id })
|
||||
.from(tenants)
|
||||
.where(eq(tenants.slug, TENANT_SLUG))
|
||||
.limit(1);
|
||||
if (!row) {
|
||||
throw new Error(`Tenant demo "${TENANT_SLUG}" no encontrado. Ejecuta el seed de la base de datos.`);
|
||||
}
|
||||
return row.id;
|
||||
}
|
||||
|
||||
// Lectura del lead para las páginas públicas del funnel. Scoped al tenant demo,
|
||||
// nunca expone leads de otros reformistas.
|
||||
export async function getPublicLead(id: string) {
|
||||
const tenantId = await getDemoTenantId();
|
||||
const [lead] = await db
|
||||
.select()
|
||||
.from(leads)
|
||||
.where(and(eq(leads.id, id), eq(leads.tenantId, tenantId)))
|
||||
.limit(1);
|
||||
|
||||
if (!lead) return null;
|
||||
|
||||
const [fotos, eventos] = await Promise.all([
|
||||
db.select().from(leadFotos).where(eq(leadFotos.leadId, id)).orderBy(asc(leadFotos.orden)),
|
||||
db
|
||||
.select()
|
||||
.from(leadPipelineEventos)
|
||||
.where(eq(leadPipelineEventos.leadId, id))
|
||||
.orderBy(asc(leadPipelineEventos.occurredAt)),
|
||||
]);
|
||||
|
||||
return { lead, fotos, eventos };
|
||||
}
|
||||
Reference in New Issue
Block a user