feat: preview de placement en pipeline de creatividades

Cada pieza muestra mock Meta/Google Ads o RRSS (feed, Stories, LinkedIn) como el Ad Tracker, con copy, media y canal editables.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
4Ventures
2026-09-23 03:36:28 +02:00
parent b4ee23874e
commit a7704567bd
6 changed files with 1448 additions and 207 deletions

View File

@@ -10,6 +10,31 @@ import {
userRole,
} from '@/lib/agency';
const SELECT =
'id,title,status,channel,placement,format,headline,primary_text,description,cta,media_url,brand_name,landing_url,mime_type,bytes,created_at,updated_at';
const CHANNELS = new Set([
'meta_ads',
'google_ads',
'instagram',
'facebook',
'linkedin',
'tiktok',
'stories',
'other',
]);
const FORMATS = new Set([
'image',
'video',
'carousel',
'reel',
'story',
'rsa',
'pmax',
'other',
]);
const ALLOWED_STATUS = new Set(['draft', 'in_review', 'approved', 'rejected']);
async function resolveTenantId(user: {
app_metadata?: Record<string, unknown>;
user_metadata?: Record<string, unknown>;
@@ -23,6 +48,30 @@ async function resolveTenantId(user: {
return { tenantId: homeTenantId(user), viaView: false };
}
function str(v: unknown, max = 2000): string | null {
if (typeof v !== 'string') return null;
const t = v.trim();
if (!t) return null;
return t.slice(0, max);
}
function previewFields(body: Record<string, unknown>) {
const channel = str(body.channel, 40);
const format = str(body.format, 40);
return {
channel: channel && CHANNELS.has(channel) ? channel : null,
placement: str(body.placement, 40),
format: format && FORMATS.has(format) ? format : null,
headline: str(body.headline, 500),
primary_text: str(body.primary_text, 8000),
description: str(body.description, 2000),
cta: str(body.cta, 120),
media_url: str(body.media_url, 2000),
brand_name: str(body.brand_name, 200),
landing_url: str(body.landing_url, 2000),
};
}
export async function GET() {
const supabase = await createClient();
const {
@@ -43,10 +92,23 @@ export async function GET() {
);
}
const r = await fetch(
`${supabaseUrl()}/rest/v1/creatives?tenant_id=eq.${encodeURIComponent(tenantId)}&select=id,title,status,mime_type,bytes,created_at,updated_at&order=updated_at.desc`,
`${supabaseUrl()}/rest/v1/creatives?tenant_id=eq.${encodeURIComponent(tenantId)}&select=${SELECT}&order=updated_at.desc`,
{ headers, cache: 'no-store' }
);
if (!r.ok) {
// Fallback if preview columns not migrated yet
const fallback = await fetch(
`${supabaseUrl()}/rest/v1/creatives?tenant_id=eq.${encodeURIComponent(tenantId)}&select=id,title,status,mime_type,bytes,created_at,updated_at&order=updated_at.desc`,
{ headers, cache: 'no-store' }
);
if (fallback.ok) {
return NextResponse.json({
creatives: await fallback.json(),
viewTenantId: tenantId,
warning:
'Aplica sql/creatives_preview.sql para canales, copy y media preview',
});
}
return NextResponse.json({
creatives: [],
warning: await r.text(),
@@ -61,14 +123,25 @@ export async function GET() {
const { data, error } = await supabase
.from('creatives')
.select('id,title,status,mime_type,bytes,created_at,updated_at')
.select(SELECT)
.order('updated_at', { ascending: false });
if (error) {
return NextResponse.json(
{ creatives: [], warning: error.message },
{ status: 200 }
);
const { data: basic, error: e2 } = await supabase
.from('creatives')
.select('id,title,status,mime_type,bytes,created_at,updated_at')
.order('updated_at', { ascending: false });
if (e2) {
return NextResponse.json(
{ creatives: [], warning: error.message },
{ status: 200 }
);
}
return NextResponse.json({
creatives: basic ?? [],
warning:
'Aplica sql/creatives_preview.sql para canales, copy y media preview',
});
}
return NextResponse.json({ creatives: data ?? [] });
@@ -88,8 +161,8 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ error: 'Usuario sin tenant_id' }, { status: 403 });
}
const body = await req.json().catch(() => ({}));
const title = typeof body.title === 'string' ? body.title.trim() : '';
const body = (await req.json().catch(() => ({}))) as Record<string, unknown>;
const title = str(body.title, 300);
if (!title) {
return NextResponse.json({ error: 'title requerido' }, { status: 400 });
}
@@ -99,6 +172,7 @@ export async function POST(req: NextRequest) {
title,
status: 'draft',
created_by: user.id,
...previewFields(body),
};
if (viaView) {
@@ -131,18 +205,36 @@ export async function POST(req: NextRequest) {
const { data, error } = await supabase
.from('creatives')
.insert(row)
.select('id,title,status,created_at')
.select(SELECT)
.single();
if (error) {
return NextResponse.json({ error: error.message }, { status: 500 });
// Retry without preview columns if migration pending
const { data: basic, error: e2 } = await supabase
.from('creatives')
.insert({
tenant_id: tenantId,
title,
status: 'draft',
created_by: user.id,
})
.select('id,title,status,created_at')
.single();
if (e2) {
return NextResponse.json({ error: error.message }, { status: 500 });
}
return NextResponse.json(
{
creative: basic,
warning: 'Preview columns missing — apply sql/creatives_preview.sql',
},
{ status: 201 }
);
}
return NextResponse.json({ creative: data }, { status: 201 });
}
const ALLOWED = new Set(['draft', 'in_review', 'approved', 'rejected']);
export async function PATCH(req: NextRequest) {
const supabase = await createClient();
const {
@@ -152,11 +244,23 @@ export async function PATCH(req: NextRequest) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const body = await req.json().catch(() => ({}));
const id = typeof body.id === 'string' ? body.id.trim() : '';
const status = typeof body.status === 'string' ? body.status.trim() : '';
if (!id || !ALLOWED.has(status)) {
return NextResponse.json({ error: 'id y status válidos requeridos' }, { status: 400 });
const body = (await req.json().catch(() => ({}))) as Record<string, unknown>;
const id = str(body.id, 80);
if (!id) {
return NextResponse.json({ error: 'id requerido' }, { status: 400 });
}
const clean: Record<string, unknown> = {
updated_at: new Date().toISOString(),
};
if (typeof body.status === 'string' && ALLOWED_STATUS.has(body.status)) {
clean.status = body.status;
}
const title = str(body.title, 300);
if (title) clean.title = title;
for (const [k, v] of Object.entries(previewFields(body))) {
if (k in body) clean[k] = v;
}
const agency = isAgencyRole(userRole(user));
@@ -172,10 +276,7 @@ export async function PATCH(req: NextRequest) {
'Content-Type': 'application/json',
Prefer: 'return=representation',
},
body: JSON.stringify({
status,
updated_at: new Date().toISOString(),
}),
body: JSON.stringify(clean),
}
);
if (!r.ok) {
@@ -187,9 +288,9 @@ export async function PATCH(req: NextRequest) {
const { data, error } = await supabase
.from('creatives')
.update({ status, updated_at: new Date().toISOString() })
.update(clean)
.eq('id', id)
.select('id,title,status')
.select(SELECT)
.single();
if (error) {
return NextResponse.json({ error: error.message }, { status: 500 });

View File

@@ -1,191 +1,11 @@
/**
* Pipeline de creatividades publicitarias del cliente en contexto.
* No es la librería de assets (documentos) ni el sync live de Meta — es la cola de aprobación.
* Pipeline de creatividades — cola de aprobación con preview de placement
* (Meta/Google Ads + RRSS), estilo Ad Tracker.
*/
'use client';
import React, { FormEvent, useEffect, useState } from 'react';
import { Image as ImageIcon, Plus, Trash2 } from 'lucide-react';
type Creative = {
id: string;
title: string;
status: string;
created_at?: string;
};
const STATUSES = [
{ id: 'draft', label: 'Borrador' },
{ id: 'in_review', label: 'En review' },
{ id: 'approved', label: 'Aprobado' },
{ id: 'rejected', label: 'Rechazado' },
] as const;
import CreativesPipeline from '@/components/CreativesPipeline';
export default function CreativesPage() {
const [creatives, setCreatives] = useState<Creative[]>([]);
const [title, setTitle] = useState('');
const [warning, setWarning] = useState<string | null>(null);
const [err, setErr] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [busyId, setBusyId] = useState<string | null>(null);
async function load() {
setLoading(true);
const res = await fetch('/api/creatives');
const data = await res.json();
setCreatives(data.creatives ?? []);
setWarning(data.warning ?? null);
setLoading(false);
}
useEffect(() => {
void load();
}, []);
async function create(e: FormEvent) {
e.preventDefault();
setErr(null);
const res = await fetch('/api/creatives', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title }),
});
const data = await res.json();
if (!res.ok) {
setErr(data.error ?? 'Error al crear');
return;
}
setTitle('');
await load();
}
async function setStatus(id: string, status: string) {
setBusyId(id);
setErr(null);
const res = await fetch('/api/creatives', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id, status }),
});
const data = await res.json();
if (!res.ok) setErr(data.error ?? 'No se pudo actualizar');
await load();
setBusyId(null);
}
async function remove(id: string) {
if (!confirm('¿Borrar esta creatividad?')) return;
setBusyId(id);
setErr(null);
const res = await fetch(`/api/creatives?id=${encodeURIComponent(id)}`, {
method: 'DELETE',
});
const data = await res.json().catch(() => ({}));
if (!res.ok) setErr(data.error ?? 'No se pudo borrar');
await load();
setBusyId(null);
}
return (
<div className="space-y-8">
<div>
<h2 className="text-2xl font-bold tracking-tight text-white">
Pipeline de creatividades
</h2>
<p className="text-sm text-gray-400 mt-1 max-w-2xl">
Cola de aprobación de piezas ads del <strong className="text-gray-300">cliente en contexto</strong> (selector arriba):
borrador → review → aprobado. No sustituye Meta Ads Manager; el sync
automático de anuncios live llegará con la integración Meta.
</p>
</div>
{warning && (
<p className="text-xs text-amber-400/90 border border-amber-500/20 rounded-lg px-3 py-2">
{warning}
</p>
)}
{err && <p className="text-xs text-red-400">{err}</p>}
<form onSubmit={create} className="flex gap-3 items-end">
<div className="flex-1">
<label className="text-[11px] uppercase text-gray-500">
Nueva pieza
</label>
<input
className="mt-1 w-full rounded-lg bg-gray-900 border border-gray-700 px-3 py-2 text-sm text-white"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Video Meta · testimonial ES"
required
/>
</div>
<button
type="submit"
className="inline-flex items-center gap-2 rounded-lg bg-brand-500/90 hover:bg-brand-500 px-4 py-2 text-sm font-medium text-white"
>
<Plus className="w-4 h-4" /> Añadir
</button>
</form>
{loading ? (
<p className="text-sm text-gray-500">Cargando…</p>
) : creatives.length === 0 ? (
<div className="bg-[#111827] border border-dashed border-gray-700 rounded-xl p-12 text-center">
<ImageIcon className="w-10 h-10 text-gray-600 mx-auto mb-3" />
<p className="text-gray-300 font-medium">Pipeline vacío</p>
<p className="text-xs text-gray-500 mt-2 max-w-md mx-auto">
Úsalo para piezas en producción creativa por cliente. La biblioteca
de activos guarda archivos validados (PDF, Excel, packs…); esto es
el flow de ads.
</p>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">
{STATUSES.map((col) => {
const items = creatives.filter((c) => c.status === col.id);
return (
<div key={col.id} className="space-y-2">
<p className="text-[11px] uppercase tracking-wider text-gray-500 font-semibold px-1">
{col.label} ({items.length})
</p>
<ul className="space-y-2 min-h-[80px]">
{items.map((c) => (
<li
key={c.id}
className="rounded-lg border border-gray-800 bg-[#111827] p-3 space-y-2"
>
<p className="text-sm text-white font-medium">{c.title}</p>
<div className="flex items-center gap-2">
<select
className="flex-1 text-[11px] rounded bg-gray-900 border border-gray-700 text-gray-300 px-2 py-1"
value={c.status}
disabled={busyId === c.id}
onChange={(e) => setStatus(c.id, e.target.value)}
>
{STATUSES.map((s) => (
<option key={s.id} value={s.id}>
{s.label}
</option>
))}
</select>
<button
type="button"
title="Borrar"
disabled={busyId === c.id}
onClick={() => remove(c.id)}
className="p-1.5 rounded text-gray-500 hover:text-red-400 hover:bg-red-500/10"
>
<Trash2 className="w-3.5 h-3.5" />
</button>
</div>
</li>
))}
</ul>
</div>
);
})}
</div>
)}
</div>
);
return <CreativesPipeline />;
}