Reorganiza el routing multi-tenant: funnel por slug, B2B en raíz
- / y /b2b sirven la landing B2B estática (rewrites beforeFiles)
- /{slug} resuelve el funnel del reformista (app/[slug]/page.tsx) con
branding propio (TenantBrand) y atribución de leads por tenant
- crearLead(slug) y páginas /solicitud usan el tenant del lead
- Panel: edición del slug del funnel + URL pública en /panel/empresa
- Helper de slugs reservados para evitar colisiones con rutas reales
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -4,10 +4,17 @@ const nextConfig: NextConfig = {
|
||||
// @react-pdf/renderer usa módulos nativos/wasm (yoga, fontkit) que no deben bundlearse.
|
||||
serverExternalPackages: ['@react-pdf/renderer'],
|
||||
async rewrites() {
|
||||
return [
|
||||
// Landing B2B estática (mvp/b2b) servida en /b2b. El fichero vive en public/b2b.html.
|
||||
{ source: "/b2b", destination: "/b2b.html" },
|
||||
];
|
||||
// beforeFiles: estas reglas ganan a las rutas del filesystem (incluida [slug]).
|
||||
// La raíz y /b2b sirven la landing B2B estática (public/b2b.html); cada reformista
|
||||
// tiene su funnel en /{slug} vía app/[slug]/page.tsx.
|
||||
return {
|
||||
beforeFiles: [
|
||||
{ source: "/", destination: "/b2b.html" },
|
||||
{ source: "/b2b", destination: "/b2b.html" },
|
||||
],
|
||||
afterFiles: [],
|
||||
fallback: [],
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
44
mvp/b2c/src/app/[slug]/page.tsx
Normal file
44
mvp/b2c/src/app/[slug]/page.tsx
Normal file
@@ -0,0 +1,44 @@
|
||||
import type { Metadata } from 'next';
|
||||
import { notFound } from 'next/navigation';
|
||||
import Hero from '@/components/Hero/Hero';
|
||||
import ReformaSlider from '@/components/ReformaSlider/ReformaSlider';
|
||||
import Features from '@/components/Features/Features';
|
||||
import Testimonials from '@/components/Testimonials/Testimonials';
|
||||
import Footer from '@/components/Footer/Footer';
|
||||
import TenantBrand from '@/components/funnel/TenantBrand';
|
||||
import { getTenantBySlug } from '@/lib/funnel/public-queries';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
export async function generateMetadata({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ slug: string }>;
|
||||
}): Promise<Metadata> {
|
||||
const { slug } = await params;
|
||||
const tenant = await getTenantBySlug(slug);
|
||||
if (!tenant) return { title: 'Reforma no encontrada' };
|
||||
return {
|
||||
title: `${tenant.nombreEmpresa} · Presupuesto de reforma`,
|
||||
description: `Pide tu presupuesto de reforma a ${tenant.nombreEmpresa}. Render IA y presupuesto orientativo en minutos.`,
|
||||
};
|
||||
}
|
||||
|
||||
export default async function FunnelPage({ params }: { params: Promise<{ slug: string }> }) {
|
||||
const { slug } = await params;
|
||||
const tenant = await getTenantBySlug(slug);
|
||||
if (!tenant) notFound();
|
||||
|
||||
return (
|
||||
<>
|
||||
<TenantBrand nombreEmpresa={tenant.nombreEmpresa} logoUrl={tenant.logoUrl} />
|
||||
<main id="main-content">
|
||||
<Hero slug={tenant.slug} />
|
||||
<ReformaSlider />
|
||||
<Features />
|
||||
<Testimonials />
|
||||
</main>
|
||||
<Footer />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
import Navbar from '@/components/Navbar/Navbar';
|
||||
import Hero from '@/components/Hero/Hero';
|
||||
import ReformaSlider from '@/components/ReformaSlider/ReformaSlider';
|
||||
import Features from '@/components/Features/Features';
|
||||
import Testimonials from '@/components/Testimonials/Testimonials';
|
||||
import ContactForm from '@/components/ContactForm/ContactForm';
|
||||
import Footer from '@/components/Footer/Footer';
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<>
|
||||
{/* <Navbar /> */}
|
||||
<main id="main-content">
|
||||
<Hero />
|
||||
<ReformaSlider />
|
||||
<Features />
|
||||
<Testimonials />
|
||||
</main>
|
||||
<Footer />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
'use server';
|
||||
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { and, eq, ne } from 'drizzle-orm';
|
||||
import { revalidatePath } from 'next/cache';
|
||||
import { db } from '@/db';
|
||||
import { tenants } from '@/db/schema';
|
||||
import { getCurrentTenantId as getTenantId } from '@/lib/auth/current-user';
|
||||
import { validarSlug } from '@/lib/validation/signup';
|
||||
|
||||
const LOGO_MAX_BYTES = 500_000;
|
||||
const LOGO_TIPOS = ['image/png', 'image/jpeg', 'image/webp', 'image/svg+xml'];
|
||||
@@ -20,10 +21,32 @@ export async function actualizarEmpresa(formData: FormData) {
|
||||
if (!nombreEmpresa) {
|
||||
throw new Error('El nombre de la empresa es obligatorio.');
|
||||
}
|
||||
|
||||
const slugRaw = limpiar(formData.get('slug'));
|
||||
if (!slugRaw) {
|
||||
throw new Error('El enlace de tu funnel es obligatorio.');
|
||||
}
|
||||
const validacion = validarSlug(slugRaw);
|
||||
if (!validacion.ok) {
|
||||
throw new Error(validacion.error);
|
||||
}
|
||||
const slug = validacion.slug;
|
||||
|
||||
// El slug es único en todo el sistema; comprobamos que no lo use otro reformista.
|
||||
const [colision] = await db
|
||||
.select({ id: tenants.id })
|
||||
.from(tenants)
|
||||
.where(and(eq(tenants.slug, slug), ne(tenants.id, tenantId)))
|
||||
.limit(1);
|
||||
if (colision) {
|
||||
throw new Error('Ese enlace ya está en uso. Elige otro.');
|
||||
}
|
||||
|
||||
await db
|
||||
.update(tenants)
|
||||
.set({
|
||||
nombreEmpresa,
|
||||
slug,
|
||||
cif: limpiar(formData.get('cif')),
|
||||
direccion: limpiar(formData.get('direccion')),
|
||||
provincia: limpiar(formData.get('provincia')),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { headers } from 'next/headers';
|
||||
import { getTenantPerfil } from '@/db/tenant-queries';
|
||||
import { actualizarEmpresa } from './actions';
|
||||
import LogoUploader from '@/components/panel/LogoUploader';
|
||||
@@ -7,6 +8,11 @@ export const dynamic = 'force-dynamic';
|
||||
export default async function EmpresaPage() {
|
||||
const perfil = await getTenantPerfil();
|
||||
|
||||
const h = await headers();
|
||||
const host = h.get('x-forwarded-host') ?? h.get('host') ?? 'reformix.dv3.com.es';
|
||||
const proto = h.get('x-forwarded-proto') ?? 'https';
|
||||
const funnelUrl = `${proto}://${host}/${perfil.slug}`;
|
||||
|
||||
return (
|
||||
<div className="space-y-10 max-w-2xl">
|
||||
<div>
|
||||
@@ -34,6 +40,32 @@ export default async function EmpresaPage() {
|
||||
className="w-full border border-gray-300 rounded-lg px-3 py-2"
|
||||
/>
|
||||
</label>
|
||||
<label className="text-sm md:col-span-2">
|
||||
<span className="block text-gray-500 mb-1">Enlace de tu funnel *</span>
|
||||
<div className="flex items-center border border-gray-300 rounded-lg overflow-hidden">
|
||||
<span className="px-3 py-2 text-gray-400 bg-gray-50 border-r border-gray-200 select-none whitespace-nowrap">
|
||||
{host}/
|
||||
</span>
|
||||
<input
|
||||
name="slug"
|
||||
required
|
||||
defaultValue={perfil.slug}
|
||||
pattern="[a-z0-9-]+"
|
||||
className="flex-1 px-3 py-2 outline-none min-w-0"
|
||||
/>
|
||||
</div>
|
||||
<span className="block text-gray-400 mt-1.5 text-xs">
|
||||
Esta es la dirección que compartes con tus clientes:{' '}
|
||||
<a
|
||||
href={funnelUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-black underline underline-offset-2 break-all"
|
||||
>
|
||||
{funnelUrl}
|
||||
</a>
|
||||
</span>
|
||||
</label>
|
||||
<label className="text-sm">
|
||||
<span className="block text-gray-500 mb-1">CIF / NIF</span>
|
||||
<input
|
||||
|
||||
@@ -2,6 +2,7 @@ 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';
|
||||
import TenantBrand from '@/components/funnel/TenantBrand';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
@@ -10,7 +11,7 @@ export default async function EstadoPage({ params }: { params: Promise<{ id: str
|
||||
const data = await getPublicLead(id);
|
||||
if (!data) notFound();
|
||||
|
||||
const { lead, eventos } = data;
|
||||
const { lead, tenant, eventos } = data;
|
||||
const reachedStages = new Set(eventos.map((e) => e.stage));
|
||||
|
||||
const snapshot = lead.desgloseSnapshot as { result: BudgetResult } | null;
|
||||
@@ -19,7 +20,9 @@ export default async function EstadoPage({ params }: { params: Promise<{ id: str
|
||||
const tipo = lead.tipoReforma ? TIPO_LABEL[lead.tipoReforma] : 'tu reforma';
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<>
|
||||
{tenant && <TenantBrand nombreEmpresa={tenant.nombreEmpresa} logoUrl={tenant.logoUrl} />}
|
||||
<div className="container py-10 max-w-2xl 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">
|
||||
@@ -128,6 +131,7 @@ export default async function EstadoPage({ params }: { params: Promise<{ id: str
|
||||
Presupuesto enviado a tu WhatsApp ✓
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { notFound } from 'next/navigation';
|
||||
import { getPublicLead } from '@/lib/funnel/public-queries';
|
||||
import { guardarDetallesYFotos } from '../../actions';
|
||||
import FotosUploader from '@/components/funnel/FotosUploader';
|
||||
import TenantBrand from '@/components/funnel/TenantBrand';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
@@ -10,10 +11,12 @@ export default async function FotosPage({ params }: { params: Promise<{ id: stri
|
||||
const data = await getPublicLead(id);
|
||||
if (!data) notFound();
|
||||
|
||||
const { lead } = data;
|
||||
const { lead, tenant } = data;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<>
|
||||
{tenant && <TenantBrand nombreEmpresa={tenant.nombreEmpresa} logoUrl={tenant.logoUrl} />}
|
||||
<div className="container py-10 max-w-2xl 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
|
||||
@@ -31,5 +34,6 @@ export default async function FotosPage({ params }: { params: Promise<{ id: stri
|
||||
<FotosUploader action={guardarDetallesYFotos.bind(null, id)} />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ 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 { getTenantBySlug } from '@/lib/funnel/public-queries';
|
||||
import { procesarLead } from '@/lib/funnel/orchestrator';
|
||||
|
||||
const MAX_FOTOS = 4;
|
||||
@@ -28,7 +28,7 @@ export type CrearLeadResult =
|
||||
| { ok: true; leadId: string }
|
||||
| { ok: false; error: string };
|
||||
|
||||
export async function crearLead(input: CrearLeadInput): Promise<CrearLeadResult> {
|
||||
export async function crearLead(slug: string, input: CrearLeadInput): Promise<CrearLeadResult> {
|
||||
const parsed = crearLeadSchema.safeParse(input);
|
||||
if (!parsed.success) {
|
||||
return { ok: false, error: parsed.error.issues[0]?.message ?? 'Datos inválidos.' };
|
||||
@@ -40,12 +40,16 @@ export async function crearLead(input: CrearLeadInput): Promise<CrearLeadResult>
|
||||
return { ok: false, error: 'Debes aceptar la política de privacidad y las condiciones.' };
|
||||
}
|
||||
|
||||
const tenantId = await getDemoTenantId();
|
||||
// El lead se atribuye al reformista dueño del funnel (slug de la URL pública).
|
||||
const tenant = await getTenantBySlug(slug);
|
||||
if (!tenant) {
|
||||
return { ok: false, error: 'No hemos podido identificar al reformista. Recarga la página.' };
|
||||
}
|
||||
|
||||
const [lead] = await db
|
||||
.insert(leads)
|
||||
.values({
|
||||
tenantId,
|
||||
tenantId: tenant.id,
|
||||
nombre: data.nombre,
|
||||
email: data.email,
|
||||
telefono: data.telefono,
|
||||
@@ -79,14 +83,9 @@ async function fileToDataUri(file: File): Promise<string | null> {
|
||||
// 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);
|
||||
const [lead] = await db.select().from(leads).where(eq(leads.id, leadId)).limit(1);
|
||||
if (!lead) throw new Error('Solicitud no encontrada.');
|
||||
const tenantId = lead.tenantId;
|
||||
|
||||
const tipoRaw = String(formData.get('tipoReforma') ?? '');
|
||||
const calidadRaw = String(formData.get('calidad') ?? '');
|
||||
|
||||
@@ -1,24 +1,10 @@
|
||||
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>
|
||||
<main className="flex-1">{children}</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.
|
||||
Presupuesto orientativo. El precio final puede variar según la visita técnica.
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
@@ -40,7 +40,7 @@ function validateForm(data: FormData): FormErrors {
|
||||
return errors;
|
||||
}
|
||||
|
||||
export default function ContactForm() {
|
||||
export default function ContactForm({ slug }: { slug: string }) {
|
||||
const [formData, setFormData] = useState<FormData>(initialData);
|
||||
const [consents, setConsents] = useState(initialConsents);
|
||||
const [errors, setErrors] = useState<FormErrors>({});
|
||||
@@ -99,7 +99,7 @@ export default function ContactForm() {
|
||||
|
||||
setStatus('loading');
|
||||
setSubmitError(null);
|
||||
const result = await crearLead({
|
||||
const result = await crearLead(slug, {
|
||||
nombre: formData.name,
|
||||
email: formData.email,
|
||||
telefono: formData.phone,
|
||||
|
||||
@@ -40,7 +40,7 @@ function validateForm(data: FormData): FormErrors {
|
||||
return errors;
|
||||
}
|
||||
|
||||
function LeadForm() {
|
||||
function LeadForm({ slug }: { slug: string }) {
|
||||
const router = useRouter();
|
||||
const [formData, setFormData] = useState<FormData>(initialData);
|
||||
const [consents, setConsents] = useState(initialConsents);
|
||||
@@ -79,7 +79,7 @@ function LeadForm() {
|
||||
|
||||
setStatus('loading');
|
||||
setSubmitError(null);
|
||||
const result = await crearLead({
|
||||
const result = await crearLead(slug, {
|
||||
nombre: formData.name,
|
||||
email: formData.email,
|
||||
telefono: formData.phone,
|
||||
@@ -326,7 +326,7 @@ function LeadForm() {
|
||||
);
|
||||
}
|
||||
|
||||
export default function Hero() {
|
||||
export default function Hero({ slug }: { slug: string }) {
|
||||
const heroRef = useRef<HTMLElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -393,7 +393,7 @@ export default function Hero() {
|
||||
<h2 className="text-xl font-black tracking-tight text-black">Pide tu presupuesto</h2>
|
||||
<p className="text-sm text-gray-400 mt-1">En menos de 2 minutos te llamamos · Render por WhatsApp</p>
|
||||
</div>
|
||||
<LeadForm />
|
||||
<LeadForm slug={slug} />
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
44
mvp/b2c/src/components/funnel/TenantBrand.tsx
Normal file
44
mvp/b2c/src/components/funnel/TenantBrand.tsx
Normal file
@@ -0,0 +1,44 @@
|
||||
type TenantBrandProps = {
|
||||
nombreEmpresa: string;
|
||||
logoUrl: string | null;
|
||||
subtitle?: string;
|
||||
};
|
||||
|
||||
function iniciales(nombre: string): string {
|
||||
return nombre
|
||||
.split(/\s+/)
|
||||
.slice(0, 2)
|
||||
.map((p) => p[0]?.toUpperCase() ?? '')
|
||||
.join('');
|
||||
}
|
||||
|
||||
// Cabecera de marca del reformista para el funnel público y las páginas de
|
||||
// solicitud. El cliente final ve el branding del reformista, no el de Reformix.
|
||||
export default function TenantBrand({ nombreEmpresa, logoUrl, subtitle }: TenantBrandProps) {
|
||||
return (
|
||||
<header className="bg-white border-b border-gray-200">
|
||||
<div className="container py-4 flex items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-3 min-w-0">
|
||||
{logoUrl ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={logoUrl}
|
||||
alt={nombreEmpresa}
|
||||
className="h-9 w-auto max-w-[160px] object-contain"
|
||||
/>
|
||||
) : (
|
||||
<span className="h-9 w-9 rounded-lg bg-black text-white text-sm font-black flex items-center justify-center shrink-0">
|
||||
{iniciales(nombreEmpresa)}
|
||||
</span>
|
||||
)}
|
||||
<span className="text-lg font-black tracking-tight text-black truncate">
|
||||
{nombreEmpresa}
|
||||
</span>
|
||||
</div>
|
||||
<span className="text-xs font-semibold uppercase tracking-widest text-gray-400 shrink-0">
|
||||
{subtitle ?? 'Presupuesto de reforma'}
|
||||
</span>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { getCurrentTenantId as getTenantId } from '@/lib/auth/current-user';
|
||||
|
||||
export type TenantPerfil = {
|
||||
nombreEmpresa: string;
|
||||
slug: string;
|
||||
logoUrl: string | null;
|
||||
provincia: string | null;
|
||||
cif: string | null;
|
||||
@@ -19,6 +20,7 @@ export async function getTenantPerfil(): Promise<TenantPerfil> {
|
||||
const [row] = await db
|
||||
.select({
|
||||
nombreEmpresa: tenants.nombreEmpresa,
|
||||
slug: tenants.slug,
|
||||
logoUrl: tenants.logoUrl,
|
||||
provincia: tenants.provincia,
|
||||
cif: tenants.cif,
|
||||
@@ -34,6 +36,7 @@ export async function getTenantPerfil(): Promise<TenantPerfil> {
|
||||
return (
|
||||
row ?? {
|
||||
nombreEmpresa: 'Reformix',
|
||||
slug: '',
|
||||
logoUrl: null,
|
||||
provincia: null,
|
||||
cif: null,
|
||||
|
||||
@@ -1,35 +1,41 @@
|
||||
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> {
|
||||
export type PublicTenant = {
|
||||
id: string;
|
||||
slug: string;
|
||||
nombreEmpresa: string;
|
||||
logoUrl: string | null;
|
||||
};
|
||||
|
||||
const TENANT_PUBLIC_COLUMNS = {
|
||||
id: tenants.id,
|
||||
slug: tenants.slug,
|
||||
nombreEmpresa: tenants.nombreEmpresa,
|
||||
logoUrl: tenants.logoUrl,
|
||||
} as const;
|
||||
|
||||
// Resuelve el reformista dueño del funnel a partir de su slug público.
|
||||
// Devuelve null si el slug no corresponde a ningún reformista.
|
||||
export async function getTenantBySlug(slug: string): Promise<PublicTenant | null> {
|
||||
const [row] = await db
|
||||
.select({ id: tenants.id })
|
||||
.select(TENANT_PUBLIC_COLUMNS)
|
||||
.from(tenants)
|
||||
.where(eq(tenants.slug, TENANT_SLUG))
|
||||
.where(eq(tenants.slug, 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;
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
// Lectura del lead para las páginas públicas del funnel. Scoped al tenant demo,
|
||||
// nunca expone leads de otros reformistas.
|
||||
// Lectura del lead para las páginas públicas del funnel (/solicitud/[id]).
|
||||
// El lead se identifica por su UUID (no enumerable); devolvemos su reformista
|
||||
// para mostrar el branding correcto sin exponer datos de otros tenants.
|
||||
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);
|
||||
|
||||
const [lead] = await db.select().from(leads).where(eq(leads.id, id)).limit(1);
|
||||
if (!lead) return null;
|
||||
|
||||
const [fotos, eventos] = await Promise.all([
|
||||
const [[tenant], fotos, eventos] = await Promise.all([
|
||||
db.select(TENANT_PUBLIC_COLUMNS).from(tenants).where(eq(tenants.id, lead.tenantId)).limit(1),
|
||||
db.select().from(leadFotos).where(eq(leadFotos.leadId, id)).orderBy(asc(leadFotos.orden)),
|
||||
db
|
||||
.select()
|
||||
@@ -38,5 +44,15 @@ export async function getPublicLead(id: string) {
|
||||
.orderBy(asc(leadPipelineEventos.occurredAt)),
|
||||
]);
|
||||
|
||||
return { lead, fotos, eventos };
|
||||
return { lead, tenant: tenant ?? null, fotos, eventos };
|
||||
}
|
||||
|
||||
// Verifica que un lead pertenece al tenant indicado (scoping de mutaciones).
|
||||
export async function leadPerteneceATenant(leadId: string, tenantId: string): Promise<boolean> {
|
||||
const [row] = await db
|
||||
.select({ id: leads.id })
|
||||
.from(leads)
|
||||
.where(and(eq(leads.id, leadId), eq(leads.tenantId, tenantId)))
|
||||
.limit(1);
|
||||
return !!row;
|
||||
}
|
||||
|
||||
@@ -19,3 +19,45 @@ export function slugify(value: string): string {
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
}
|
||||
|
||||
// Rutas de la app que NO pueden ser slug de un reformista: colisionarían con
|
||||
// páginas reales o con ficheros públicos servidos en la raíz del dominio.
|
||||
export const RESERVED_SLUGS = new Set([
|
||||
'panel',
|
||||
'login',
|
||||
'logout',
|
||||
'signup',
|
||||
'admin',
|
||||
'solicitud',
|
||||
'api',
|
||||
'b2b',
|
||||
'b2b-assets',
|
||||
'assets',
|
||||
'_next',
|
||||
'favicon.ico',
|
||||
'icon.svg',
|
||||
'robots.txt',
|
||||
'sitemap.xml',
|
||||
]);
|
||||
|
||||
export function isReservedSlug(slug: string): boolean {
|
||||
return RESERVED_SLUGS.has(slug);
|
||||
}
|
||||
|
||||
export type SlugValidation = { ok: true; slug: string } | { ok: false; error: string };
|
||||
|
||||
// Normaliza y valida un slug propuesto para el funnel público de un reformista.
|
||||
// No comprueba unicidad (eso requiere BD); solo formato y palabras reservadas.
|
||||
export function validarSlug(raw: string): SlugValidation {
|
||||
const slug = slugify(raw);
|
||||
if (slug.length < 2) {
|
||||
return { ok: false, error: 'El enlace debe tener al menos 2 caracteres.' };
|
||||
}
|
||||
if (slug.length > 40) {
|
||||
return { ok: false, error: 'El enlace no puede superar los 40 caracteres.' };
|
||||
}
|
||||
if (isReservedSlug(slug)) {
|
||||
return { ok: false, error: 'Ese enlace está reservado. Elige otro.' };
|
||||
}
|
||||
return { ok: true, slug };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user