feat(creatives): implement agency and client views (Tasks 6 & 7) with fatigue panel and Claude queue
This commit is contained in:
5
next-env.d.ts
vendored
Normal file
5
next-env.d.ts
vendored
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
/// <reference types="next" />
|
||||||
|
/// <reference types="next/image-types/global" />
|
||||||
|
|
||||||
|
// NOTE: This file should not be edited
|
||||||
|
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
|
||||||
@@ -23,15 +23,7 @@ export async function POST(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const { id } = await params;
|
const { id } = await params;
|
||||||
const ctx = await resolveActiveTenant(user);
|
const role = userRole(user);
|
||||||
const tenantId = ctx.tenantId;
|
|
||||||
|
|
||||||
if (!tenantId) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ error: 'Tenant context required' },
|
|
||||||
{ status: 400 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
let body: any;
|
let body: any;
|
||||||
try {
|
try {
|
||||||
@@ -40,8 +32,28 @@ export async function POST(
|
|||||||
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
|
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const ctx = await resolveActiveTenant(user);
|
||||||
|
let tenantId = ctx.tenantId;
|
||||||
|
|
||||||
|
if (!tenantId && (role === 'agency_admin' || role === 'agency_member' || role === 'admin')) {
|
||||||
|
if (body.tenant_id) {
|
||||||
|
tenantId = body.tenant_id;
|
||||||
|
} else {
|
||||||
|
const { getAdminClient } = await import('@/lib/creatives-workflow');
|
||||||
|
const adminClient = getAdminClient();
|
||||||
|
const { data: c } = await adminClient.from('creatives').select('tenant_id').eq('id', id).maybeSingle();
|
||||||
|
if (c?.tenant_id) tenantId = c.tenant_id;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!tenantId) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'Tenant context required' },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const action = body.action; // 'send_to_client' | 'approve' | 'reject' | 'retire'
|
const action = body.action; // 'send_to_client' | 'approve' | 'reject' | 'retire'
|
||||||
const role = userRole(user);
|
|
||||||
const actor = { role, userId: user.id };
|
const actor = { role, userId: user.id };
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|||||||
180
src/app/api/creatives/[id]/route.ts
Normal file
180
src/app/api/creatives/[id]/route.ts
Normal file
@@ -0,0 +1,180 @@
|
|||||||
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
|
import { createClient } from '@/lib/supabase/server';
|
||||||
|
import { isAgencyRole, userRole } from '@/lib/agency';
|
||||||
|
import { resolveActiveTenant } from '@/lib/tenant-context';
|
||||||
|
import { createClient as createAdminClient } from '@supabase/supabase-js';
|
||||||
|
|
||||||
|
function getAdmin() {
|
||||||
|
const url = process.env.NEXT_PUBLIC_SUPABASE_URL!;
|
||||||
|
const key = process.env.SUPABASE_SERVICE_ROLE_KEY!;
|
||||||
|
return createAdminClient(url, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function GET(
|
||||||
|
req: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
|
) {
|
||||||
|
const { id } = await params;
|
||||||
|
const supabase = await createClient();
|
||||||
|
const {
|
||||||
|
data: { user },
|
||||||
|
} = await supabase.auth.getUser();
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const role = userRole(user);
|
||||||
|
const isAgency = isAgencyRole(role);
|
||||||
|
const ctx = await resolveActiveTenant(user);
|
||||||
|
const activeTenantId = ctx.tenantId;
|
||||||
|
|
||||||
|
const admin = getAdmin();
|
||||||
|
|
||||||
|
const { data: creative, error } = await admin
|
||||||
|
.from('creatives')
|
||||||
|
.select('*')
|
||||||
|
.eq('id', id)
|
||||||
|
.maybeSingle();
|
||||||
|
|
||||||
|
if (error || !creative) {
|
||||||
|
return NextResponse.json({ error: 'Creatividad no encontrada' }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Si no es agencia, validar pertenencia al tenant
|
||||||
|
if (!isAgency && creative.tenant_id !== activeTenantId) {
|
||||||
|
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Obtener métricas diarias
|
||||||
|
const { data: metrics } = await admin
|
||||||
|
.from('creative_metrics_daily')
|
||||||
|
.select('*')
|
||||||
|
.eq('creative_id', id)
|
||||||
|
.order('date', { ascending: false })
|
||||||
|
.limit(30);
|
||||||
|
|
||||||
|
// Obtener eventos
|
||||||
|
const { data: events } = await admin
|
||||||
|
.from('creative_events')
|
||||||
|
.select('*')
|
||||||
|
.eq('creative_id', id)
|
||||||
|
.order('created_at', { ascending: false })
|
||||||
|
.limit(20);
|
||||||
|
|
||||||
|
// Obtener aprobaciones
|
||||||
|
const { data: approvals } = await admin
|
||||||
|
.from('approvals')
|
||||||
|
.select('*')
|
||||||
|
.eq('creative_id', id)
|
||||||
|
.order('created_at', { ascending: false });
|
||||||
|
|
||||||
|
const { sanitizeForRole } = await import('@/lib/creatives-visibility');
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
creative: sanitizeForRole(creative, role),
|
||||||
|
metrics: metrics || [],
|
||||||
|
events: events || [],
|
||||||
|
approvals: approvals || [],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function PATCH(
|
||||||
|
req: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
|
) {
|
||||||
|
const { id } = await params;
|
||||||
|
const supabase = await createClient();
|
||||||
|
const {
|
||||||
|
data: { user },
|
||||||
|
} = await supabase.auth.getUser();
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const role = userRole(user);
|
||||||
|
const isAgency = isAgencyRole(role);
|
||||||
|
const ctx = await resolveActiveTenant(user);
|
||||||
|
const activeTenantId = ctx.tenantId;
|
||||||
|
|
||||||
|
let body: any;
|
||||||
|
try {
|
||||||
|
body = await req.json();
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const admin = getAdmin();
|
||||||
|
|
||||||
|
const { data: existing, error: getErr } = await admin
|
||||||
|
.from('creatives')
|
||||||
|
.select('*')
|
||||||
|
.eq('id', id)
|
||||||
|
.maybeSingle();
|
||||||
|
|
||||||
|
if (getErr || !existing) {
|
||||||
|
return NextResponse.json({ error: 'Creatividad no encontrada' }, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isAgency && existing.tenant_id !== activeTenantId) {
|
||||||
|
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const prevStatus = existing.status;
|
||||||
|
const updates: Record<string, any> = {
|
||||||
|
updated_at: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
|
||||||
|
if (body.asset_url !== undefined) updates.asset_url = body.asset_url;
|
||||||
|
if (body.thumbnail_url !== undefined) updates.thumbnail_url = body.thumbnail_url;
|
||||||
|
if (body.asset_final !== undefined) updates.asset_final = Boolean(body.asset_final);
|
||||||
|
if (body.headline !== undefined) updates.headline = body.headline;
|
||||||
|
if (body.primary_text !== undefined) updates.primary_text = body.primary_text;
|
||||||
|
if (body.cta !== undefined) updates.cta = body.cta;
|
||||||
|
if (body.angle !== undefined) updates.angle = body.angle;
|
||||||
|
if (body.hook !== undefined) updates.hook = body.hook;
|
||||||
|
if (body.campaign_name !== undefined) updates.campaign_name = body.campaign_name;
|
||||||
|
if (body.adset_id !== undefined) updates.adset_id = body.adset_id;
|
||||||
|
if (body.format !== undefined) updates.format = body.format;
|
||||||
|
if (body.visibility !== undefined) updates.visibility = body.visibility;
|
||||||
|
if (body.status !== undefined) updates.status = body.status;
|
||||||
|
|
||||||
|
const { data: updated, error: updateErr } = await admin
|
||||||
|
.from('creatives')
|
||||||
|
.update(updates)
|
||||||
|
.eq('id', id)
|
||||||
|
.select('*')
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (updateErr) {
|
||||||
|
return NextResponse.json({ error: updateErr.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Si cambia el status o se sube imagen final, registrar en creative_events
|
||||||
|
if (updates.status && updates.status !== prevStatus) {
|
||||||
|
await admin.from('creative_events').insert({
|
||||||
|
tenant_id: existing.tenant_id,
|
||||||
|
creative_id: id,
|
||||||
|
event_type: 'status_change',
|
||||||
|
actor: `user:${user.id}`,
|
||||||
|
from_status: prevStatus,
|
||||||
|
to_status: updates.status,
|
||||||
|
payload: { changed_by: role, reason: body.status_reason || null },
|
||||||
|
visibility: updates.status === 'publicada' || updates.status === 'aprobada' ? 'client' : 'agency',
|
||||||
|
});
|
||||||
|
} else if (updates.asset_final && !existing.asset_final) {
|
||||||
|
await admin.from('creative_events').insert({
|
||||||
|
tenant_id: existing.tenant_id,
|
||||||
|
creative_id: id,
|
||||||
|
event_type: 'asset_final_uploaded',
|
||||||
|
actor: `user:${user.id}`,
|
||||||
|
from_status: prevStatus,
|
||||||
|
to_status: prevStatus,
|
||||||
|
payload: { asset_url: updates.asset_url },
|
||||||
|
visibility: 'agency',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({ ok: true, creative: updated });
|
||||||
|
}
|
||||||
@@ -7,9 +7,11 @@ import {
|
|||||||
userRole,
|
userRole,
|
||||||
} from '@/lib/agency';
|
} from '@/lib/agency';
|
||||||
import { resolveActiveTenant } from '@/lib/tenant-context';
|
import { resolveActiveTenant } from '@/lib/tenant-context';
|
||||||
|
import { sanitizeForRole } from '@/lib/creatives-visibility';
|
||||||
|
import { createClient as createAdminClient } from '@supabase/supabase-js';
|
||||||
|
|
||||||
const SELECT =
|
const SELECT =
|
||||||
'id,title,status,channel,placement,format,headline,primary_text,description,cta,media_url,brand_name,landing_url,storage_path,mime_type,bytes,meta,created_at,updated_at';
|
'id,tenant_id,title,status,channel,placement,format,headline,primary_text,description,cta,media_url,brand_name,landing_url,storage_path,mime_type,bytes,meta,campaign_name,adset_id,meta_ad_id,angle,hook,asset_url,thumbnail_url,visibility,parent_id,generation_request_id,asset_final,created_by,created_at,updated_at';
|
||||||
|
|
||||||
const CHANNELS = new Set([
|
const CHANNELS = new Set([
|
||||||
'meta_ads',
|
'meta_ads',
|
||||||
@@ -90,7 +92,7 @@ async function fetchCurrentStatus(
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET(req: NextRequest) {
|
||||||
const supabase = await createClient();
|
const supabase = await createClient();
|
||||||
const {
|
const {
|
||||||
data: { user },
|
data: { user },
|
||||||
@@ -99,76 +101,112 @@ export async function GET() {
|
|||||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const ctx = await resolveActiveTenant(user);
|
const role = userRole(user);
|
||||||
const tenantId = ctx.tenantId;
|
const isAgency = isAgencyRole(role);
|
||||||
const viaView = ctx.viaView;
|
const { searchParams } = new URL(req.url);
|
||||||
|
const queryTenantId = searchParams.get('tenant_id');
|
||||||
|
|
||||||
if (viaView && tenantId) {
|
let tenantId: string | null = null;
|
||||||
const headers = serviceHeaders();
|
if (isAgency && queryTenantId) {
|
||||||
if (!headers) {
|
tenantId = queryTenantId;
|
||||||
return NextResponse.json(
|
} else {
|
||||||
{ creatives: [], warning: 'Service role required for superadmin view' },
|
const ctx = await resolveActiveTenant(user);
|
||||||
{ status: 200 }
|
tenantId = ctx.tenantId;
|
||||||
);
|
|
||||||
}
|
|
||||||
const r = await fetch(
|
|
||||||
`${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(),
|
|
||||||
viewTenantId: tenantId,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
return NextResponse.json({
|
|
||||||
creatives: await r.json(),
|
|
||||||
viewTenantId: tenantId,
|
|
||||||
isAgency: isAgencyRole(userRole(user)),
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const { data, error } = await supabase
|
if (!tenantId) {
|
||||||
|
return NextResponse.json({ creatives: [], isAgency });
|
||||||
|
}
|
||||||
|
|
||||||
|
const adminUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
|
||||||
|
const adminKey = process.env.SUPABASE_SERVICE_ROLE_KEY!;
|
||||||
|
const admin = createAdminClient(adminUrl, adminKey);
|
||||||
|
|
||||||
|
let query = admin
|
||||||
.from('creatives')
|
.from('creatives')
|
||||||
.select(SELECT)
|
.select(SELECT)
|
||||||
|
.eq('tenant_id', tenantId)
|
||||||
.order('updated_at', { ascending: false });
|
.order('updated_at', { ascending: false });
|
||||||
|
|
||||||
if (error) {
|
// Si es cliente, aplicar visibilidad estricta
|
||||||
const { data: basic, error: e2 } = await supabase
|
if (!isAgency) {
|
||||||
.from('creatives')
|
query = query
|
||||||
.select('id,title,status,mime_type,bytes,created_at,updated_at')
|
.eq('visibility', 'client')
|
||||||
.order('updated_at', { ascending: false });
|
.in('status', ['pendiente_aprobacion', 'aprobada', 'publicada', 'fatigada', 'retirada', 'rechazada']);
|
||||||
if (e2) {
|
|
||||||
return NextResponse.json(
|
|
||||||
{ creatives: [], warning: error.message },
|
|
||||||
{ status: 200 }
|
|
||||||
);
|
|
||||||
}
|
|
||||||
return NextResponse.json({
|
|
||||||
creatives: basic ?? [],
|
|
||||||
isAgency: isAgencyRole(userRole(user)),
|
|
||||||
warning:
|
|
||||||
'Aplica sql/creatives_preview.sql para canales, copy y media preview',
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const { data: rows, error } = await query;
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const creatives = rows || [];
|
||||||
|
|
||||||
|
// Obtener métricas agregadas de los últimos 30 días para estas creatividades
|
||||||
|
const creativeIds = creatives.map((c: any) => c.id);
|
||||||
|
const metricsMap: Record<string, any> = {};
|
||||||
|
|
||||||
|
if (creativeIds.length > 0) {
|
||||||
|
const { data: metrics } = await admin
|
||||||
|
.from('creative_metrics_daily')
|
||||||
|
.select('creative_id, impressions, clicks, spend, results, frequency, ctr, cpa')
|
||||||
|
.in('creative_id', creativeIds);
|
||||||
|
|
||||||
|
if (metrics && metrics.length > 0) {
|
||||||
|
for (const m of metrics) {
|
||||||
|
const cid = m.creative_id;
|
||||||
|
metricsMap[cid] = metricsMap[cid] || {
|
||||||
|
impressions: 0,
|
||||||
|
clicks: 0,
|
||||||
|
spend: 0,
|
||||||
|
results: 0,
|
||||||
|
count: 0,
|
||||||
|
freq_sum: 0,
|
||||||
|
ctr_sum: 0,
|
||||||
|
cpa_sum: 0,
|
||||||
|
cpa_count: 0,
|
||||||
|
};
|
||||||
|
metricsMap[cid].impressions += Number(m.impressions || 0);
|
||||||
|
metricsMap[cid].clicks += Number(m.clicks || 0);
|
||||||
|
metricsMap[cid].spend += Number(m.spend || 0);
|
||||||
|
metricsMap[cid].results += Number(m.results || 0);
|
||||||
|
metricsMap[cid].count += 1;
|
||||||
|
metricsMap[cid].freq_sum += Number(m.frequency || 0);
|
||||||
|
metricsMap[cid].ctr_sum += Number(m.ctr || 0);
|
||||||
|
if (m.cpa != null) {
|
||||||
|
metricsMap[cid].cpa_sum += Number(m.cpa);
|
||||||
|
metricsMap[cid].cpa_count += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Adjuntar métricas resumidas
|
||||||
|
const enriched = creatives.map((c: any) => {
|
||||||
|
const agg = metricsMap[c.id];
|
||||||
|
const metrics = agg
|
||||||
|
? {
|
||||||
|
impressions: agg.impressions,
|
||||||
|
clicks: agg.clicks,
|
||||||
|
spend: Number(agg.spend.toFixed(2)),
|
||||||
|
results: agg.results,
|
||||||
|
frequency: agg.count > 0 ? Number((agg.freq_sum / agg.count).toFixed(2)) : 0,
|
||||||
|
ctr: agg.impressions > 0 ? Number(((agg.clicks / agg.impressions) * 100).toFixed(2)) : 0,
|
||||||
|
cpa: agg.cpa_count > 0 ? Number((agg.cpa_sum / agg.cpa_count).toFixed(2)) : null,
|
||||||
|
}
|
||||||
|
: null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
...c,
|
||||||
|
metrics,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
creatives: data ?? [],
|
creatives: sanitizeForRole(enriched, role),
|
||||||
isAgency: isAgencyRole(userRole(user)),
|
isAgency,
|
||||||
|
tenantId,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -150,8 +150,13 @@ export async function POST(req: NextRequest) {
|
|||||||
return NextResponse.json({ error: up.error.message }, { status: 500 });
|
return NextResponse.json({ error: up.error.message }, { status: 500 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const mediaUrl = `/api/creatives/media?id=${encodeURIComponent(creativeId)}`;
|
const mediaUrl = `/api/creatives/media?path=${encodeURIComponent(storagePath)}`;
|
||||||
const patch = {
|
|
||||||
|
const isFinal =
|
||||||
|
form.get('is_final') === 'true' ||
|
||||||
|
form.get('asset_final') === 'true';
|
||||||
|
|
||||||
|
const patch: Record<string, any> = {
|
||||||
storage_path: storagePath,
|
storage_path: storagePath,
|
||||||
mime_type: mime,
|
mime_type: mime,
|
||||||
bytes: file.size,
|
bytes: file.size,
|
||||||
@@ -159,6 +164,12 @@ export async function POST(req: NextRequest) {
|
|||||||
updated_at: new Date().toISOString(),
|
updated_at: new Date().toISOString(),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (isFinal) {
|
||||||
|
const appUrl = process.env.NEXT_PUBLIC_APP_URL || 'https://app.4ventures.es';
|
||||||
|
patch.asset_url = `${appUrl.replace(/\/$/, '')}${mediaUrl}`;
|
||||||
|
patch.asset_final = true;
|
||||||
|
}
|
||||||
|
|
||||||
if (agency && headers) {
|
if (agency && headers) {
|
||||||
const r = await fetch(
|
const r = await fetch(
|
||||||
`${supabaseUrl()}/rest/v1/creatives?id=eq.${encodeURIComponent(creativeId)}`,
|
`${supabaseUrl()}/rest/v1/creatives?id=eq.${encodeURIComponent(creativeId)}`,
|
||||||
|
|||||||
125
src/app/api/fatigue/rules/route.ts
Normal file
125
src/app/api/fatigue/rules/route.ts
Normal file
@@ -0,0 +1,125 @@
|
|||||||
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
|
import { createClient } from '@/lib/supabase/server';
|
||||||
|
import { isAgencyRole, userRole } from '@/lib/agency';
|
||||||
|
import { resolveActiveTenant } from '@/lib/tenant-context';
|
||||||
|
import { createClient as createAdminClient } from '@supabase/supabase-js';
|
||||||
|
|
||||||
|
const DEFAULT_RULES = {
|
||||||
|
lookback_days: 7,
|
||||||
|
min_impressions: 1000,
|
||||||
|
max_frequency: 2.8,
|
||||||
|
ctr_drop_pct: 35,
|
||||||
|
cpa_rise_pct: 40,
|
||||||
|
signals_required: 2,
|
||||||
|
auto_request_relief: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
function getAdmin() {
|
||||||
|
const url = process.env.NEXT_PUBLIC_SUPABASE_URL!;
|
||||||
|
const key = process.env.SUPABASE_SERVICE_ROLE_KEY!;
|
||||||
|
return createAdminClient(url, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
const supabase = await createClient();
|
||||||
|
const {
|
||||||
|
data: { user },
|
||||||
|
} = await supabase.auth.getUser();
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const role = userRole(user);
|
||||||
|
const isAgency = isAgencyRole(role);
|
||||||
|
const { searchParams } = new URL(req.url);
|
||||||
|
const queryTenantId = searchParams.get('tenant_id');
|
||||||
|
|
||||||
|
let tenantId: string | null = null;
|
||||||
|
if (isAgency && queryTenantId) {
|
||||||
|
tenantId = queryTenantId;
|
||||||
|
} else {
|
||||||
|
const ctx = await resolveActiveTenant(user);
|
||||||
|
tenantId = ctx.tenantId;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!tenantId) {
|
||||||
|
return NextResponse.json({ error: 'Tenant context required' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const admin = getAdmin();
|
||||||
|
const { data: rules, error } = await admin
|
||||||
|
.from('fatigue_rules')
|
||||||
|
.select('*')
|
||||||
|
.eq('tenant_id', tenantId)
|
||||||
|
.maybeSingle();
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!rules) {
|
||||||
|
return NextResponse.json({
|
||||||
|
rules: {
|
||||||
|
tenant_id: tenantId,
|
||||||
|
...DEFAULT_RULES,
|
||||||
|
},
|
||||||
|
isDefault: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({ rules, isDefault: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function PUT(req: NextRequest) {
|
||||||
|
const supabase = await createClient();
|
||||||
|
const {
|
||||||
|
data: { user },
|
||||||
|
} = await supabase.auth.getUser();
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const role = userRole(user);
|
||||||
|
if (!isAgencyRole(role)) {
|
||||||
|
return NextResponse.json({ error: 'Solo la agencia puede modificar reglas de fatiga' }, { status: 403 });
|
||||||
|
}
|
||||||
|
|
||||||
|
let body: any;
|
||||||
|
try {
|
||||||
|
body = await req.json();
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const tenantId = body.tenant_id;
|
||||||
|
if (!tenantId) {
|
||||||
|
return NextResponse.json({ error: 'tenant_id is required' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
tenant_id: tenantId,
|
||||||
|
lookback_days: Math.max(1, Number(body.lookback_days || DEFAULT_RULES.lookback_days)),
|
||||||
|
min_impressions: Math.max(0, Number(body.min_impressions || DEFAULT_RULES.min_impressions)),
|
||||||
|
max_frequency: Math.max(1, Number(body.max_frequency || DEFAULT_RULES.max_frequency)),
|
||||||
|
ctr_drop_pct: Math.max(1, Number(body.ctr_drop_pct || DEFAULT_RULES.ctr_drop_pct)),
|
||||||
|
cpa_rise_pct: Math.max(1, Number(body.cpa_rise_pct || DEFAULT_RULES.cpa_rise_pct)),
|
||||||
|
signals_required: Math.min(3, Math.max(1, Number(body.signals_required || DEFAULT_RULES.signals_required))),
|
||||||
|
auto_request_relief: body.auto_request_relief !== undefined ? Boolean(body.auto_request_relief) : DEFAULT_RULES.auto_request_relief,
|
||||||
|
updated_at: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
|
||||||
|
const admin = getAdmin();
|
||||||
|
const { data: updated, error } = await admin
|
||||||
|
.from('fatigue_rules')
|
||||||
|
.upsert(payload, { onConflict: 'tenant_id' })
|
||||||
|
.select('*')
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({ ok: true, rules: updated });
|
||||||
|
}
|
||||||
137
src/app/api/generation-requests/route.ts
Normal file
137
src/app/api/generation-requests/route.ts
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
import { NextRequest, NextResponse } from 'next/server';
|
||||||
|
import { createClient } from '@/lib/supabase/server';
|
||||||
|
import { isAgencyRole, userRole } from '@/lib/agency';
|
||||||
|
import { resolveActiveTenant } from '@/lib/tenant-context';
|
||||||
|
import { createClient as createAdminClient } from '@supabase/supabase-js';
|
||||||
|
|
||||||
|
function getAdmin() {
|
||||||
|
const url = process.env.NEXT_PUBLIC_SUPABASE_URL!;
|
||||||
|
const key = process.env.SUPABASE_SERVICE_ROLE_KEY!;
|
||||||
|
return createAdminClient(url, key);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
const supabase = await createClient();
|
||||||
|
const {
|
||||||
|
data: { user },
|
||||||
|
} = await supabase.auth.getUser();
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const role = userRole(user);
|
||||||
|
const isAgency = isAgencyRole(role);
|
||||||
|
const { searchParams } = new URL(req.url);
|
||||||
|
const queryTenantId = searchParams.get('tenant_id');
|
||||||
|
|
||||||
|
let tenantId: string | null = null;
|
||||||
|
if (isAgency && queryTenantId) {
|
||||||
|
tenantId = queryTenantId;
|
||||||
|
} else {
|
||||||
|
const ctx = await resolveActiveTenant(user);
|
||||||
|
tenantId = ctx.tenantId;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!tenantId) {
|
||||||
|
return NextResponse.json({ error: 'Tenant context required' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const admin = getAdmin();
|
||||||
|
const { data: requests, error } = await admin
|
||||||
|
.from('generation_requests')
|
||||||
|
.select('*')
|
||||||
|
.eq('tenant_id', tenantId)
|
||||||
|
.order('requested_at', { ascending: false })
|
||||||
|
.limit(50);
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
return NextResponse.json({ requests });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(req: NextRequest) {
|
||||||
|
const supabase = await createClient();
|
||||||
|
const {
|
||||||
|
data: { user },
|
||||||
|
} = await supabase.auth.getUser();
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const role = userRole(user);
|
||||||
|
if (!isAgencyRole(role)) {
|
||||||
|
return NextResponse.json({ error: 'Solo la agencia puede solicitar relevos a Claude' }, { status: 403 });
|
||||||
|
}
|
||||||
|
|
||||||
|
let body: any;
|
||||||
|
try {
|
||||||
|
body = await req.json();
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const tenantId = body.tenant_id;
|
||||||
|
if (!tenantId) {
|
||||||
|
return NextResponse.json({ error: 'tenant_id is required' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const admin = getAdmin();
|
||||||
|
|
||||||
|
// Get tenant slug
|
||||||
|
const { data: tenant } = await admin
|
||||||
|
.from('tenants')
|
||||||
|
.select('slug, name')
|
||||||
|
.eq('id', tenantId)
|
||||||
|
.maybeSingle();
|
||||||
|
|
||||||
|
const brief = {
|
||||||
|
tenant_id: tenantId,
|
||||||
|
client_id: tenantId,
|
||||||
|
client_slug: tenant?.slug || 'cliente',
|
||||||
|
reason: body.reason || 'manual',
|
||||||
|
source_creative_id: body.source_creative_id || null,
|
||||||
|
format: body.format || 'estatico',
|
||||||
|
variants_requested: Number(body.variants_requested || 3),
|
||||||
|
campaign_name: body.campaign_name || null,
|
||||||
|
adset_id: body.adset_id || null,
|
||||||
|
notes: body.notes || null,
|
||||||
|
};
|
||||||
|
|
||||||
|
const { data: created, error } = await admin
|
||||||
|
.from('generation_requests')
|
||||||
|
.insert({
|
||||||
|
tenant_id: tenantId,
|
||||||
|
reason: brief.reason,
|
||||||
|
source_creative_id: brief.source_creative_id,
|
||||||
|
brief,
|
||||||
|
status: 'pendiente',
|
||||||
|
})
|
||||||
|
.select('*')
|
||||||
|
.single();
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
return NextResponse.json({ error: error.message }, { status: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Registrar en creative_events
|
||||||
|
await admin.from('creative_events').insert({
|
||||||
|
tenant_id: tenantId,
|
||||||
|
creative_id: brief.source_creative_id,
|
||||||
|
event_type: 'generation_requested',
|
||||||
|
actor: `user:${user.id}`,
|
||||||
|
from_status: null,
|
||||||
|
to_status: null,
|
||||||
|
payload: {
|
||||||
|
generation_request_id: created.id,
|
||||||
|
reason: brief.reason,
|
||||||
|
variants_requested: brief.variants_requested,
|
||||||
|
},
|
||||||
|
visibility: 'agency',
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({ ok: true, request: created });
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import AgencyCreativesView from '@/components/AgencyCreativesView';
|
||||||
|
import { createClient } from '@/lib/supabase/server';
|
||||||
|
import { redirect } from 'next/navigation';
|
||||||
|
import {
|
||||||
|
isAgencyRole,
|
||||||
|
serviceHeaders,
|
||||||
|
supabaseUrl,
|
||||||
|
userRole,
|
||||||
|
} from '@/lib/agency';
|
||||||
|
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
|
export default async function AgencyClienteCreatividadesPage({
|
||||||
|
params,
|
||||||
|
}: {
|
||||||
|
params: Promise<{ id: string }>;
|
||||||
|
}) {
|
||||||
|
const { id } = await params;
|
||||||
|
const supabase = await createClient();
|
||||||
|
const {
|
||||||
|
data: { user },
|
||||||
|
} = await supabase.auth.getUser();
|
||||||
|
|
||||||
|
if (!user) redirect('/login');
|
||||||
|
if (!isAgencyRole(userRole(user))) redirect('/dashboard/kpis');
|
||||||
|
|
||||||
|
let name = 'Cliente';
|
||||||
|
const headers = serviceHeaders();
|
||||||
|
if (headers) {
|
||||||
|
const r = await fetch(
|
||||||
|
`${supabaseUrl()}/rest/v1/tenants?id=eq.${encodeURIComponent(id)}&select=name,slug`,
|
||||||
|
{ headers, cache: 'no-store' }
|
||||||
|
);
|
||||||
|
if (r.ok) {
|
||||||
|
const rows = await r.json();
|
||||||
|
if (rows[0]?.name) name = rows[0].name;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return <AgencyCreativesView tenantId={id} clientName={name} />;
|
||||||
|
}
|
||||||
@@ -1,11 +1,46 @@
|
|||||||
/**
|
/**
|
||||||
* Pipeline de creatividades — producción editorial (agencia programa IG/FB).
|
* Pipeline de creatividades — selector entre Aprobación Meta Ads y Pipeline RRSS.
|
||||||
* El cliente solo ve y aprueba/rechaza en revisión interna.
|
|
||||||
*/
|
*/
|
||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
|
import React, { useState } from 'react';
|
||||||
import CreativePipelineBoard from '@/components/CreativePipelineBoard';
|
import CreativePipelineBoard from '@/components/CreativePipelineBoard';
|
||||||
|
import ClientCreativesView from '@/components/ClientCreativesView';
|
||||||
|
import { Sparkles, CalendarDays } from 'lucide-react';
|
||||||
|
|
||||||
export default function CreativesPage() {
|
export default function CreativesPage() {
|
||||||
return <CreativePipelineBoard />;
|
const [mode, setMode] = useState<'ads' | 'social'>('ads');
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex items-center gap-2 px-4 pt-2 border-b border-gray-200">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setMode('ads')}
|
||||||
|
className={`flex items-center gap-1.5 pb-2.5 px-3 text-xs font-semibold border-b-2 transition-colors ${
|
||||||
|
mode === 'ads'
|
||||||
|
? 'border-brand-500 text-brand-600'
|
||||||
|
: 'border-transparent text-gray-500 hover:text-gray-700'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<Sparkles className="w-3.5 h-3.5" />
|
||||||
|
Aprobación & Anuncios Meta Ads
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setMode('social')}
|
||||||
|
className={`flex items-center gap-1.5 pb-2.5 px-3 text-xs font-semibold border-b-2 transition-colors ${
|
||||||
|
mode === 'social'
|
||||||
|
? 'border-brand-500 text-brand-600'
|
||||||
|
: 'border-transparent text-gray-500 hover:text-gray-700'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<CalendarDays className="w-3.5 h-3.5" />
|
||||||
|
Pipeline Editorial RRSS
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{mode === 'ads' ? <ClientCreativesView /> : <CreativePipelineBoard />}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
20
src/app/dashboard/creatividades/page.tsx
Normal file
20
src/app/dashboard/creatividades/page.tsx
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import React from 'react';
|
||||||
|
import { createClient } from '@/lib/supabase/server';
|
||||||
|
import { redirect } from 'next/navigation';
|
||||||
|
import { resolveActiveTenant } from '@/lib/tenant-context';
|
||||||
|
import ClientCreativesView from '@/components/ClientCreativesView';
|
||||||
|
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
|
export default async function CreatividadesPage() {
|
||||||
|
const supabase = await createClient();
|
||||||
|
const {
|
||||||
|
data: { user },
|
||||||
|
} = await supabase.auth.getUser();
|
||||||
|
|
||||||
|
if (!user) redirect('/login');
|
||||||
|
|
||||||
|
const ctx = await resolveActiveTenant(user);
|
||||||
|
|
||||||
|
return <ClientCreativesView tenantName={ctx.label || 'Cliente'} />;
|
||||||
|
}
|
||||||
1130
src/components/AgencyCreativesView.tsx
Normal file
1130
src/components/AgencyCreativesView.tsx
Normal file
File diff suppressed because it is too large
Load Diff
806
src/components/ClientCreativesView.tsx
Normal file
806
src/components/ClientCreativesView.tsx
Normal file
@@ -0,0 +1,806 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import React, { useState, useEffect, useCallback, useMemo } from 'react';
|
||||||
|
import {
|
||||||
|
Sparkles,
|
||||||
|
CheckCircle2,
|
||||||
|
XCircle,
|
||||||
|
AlertTriangle,
|
||||||
|
Flame,
|
||||||
|
ArrowRight,
|
||||||
|
TrendingUp,
|
||||||
|
Eye,
|
||||||
|
MousePointerClick,
|
||||||
|
DollarSign,
|
||||||
|
BarChart3,
|
||||||
|
Calendar,
|
||||||
|
Layers,
|
||||||
|
ExternalLink,
|
||||||
|
MessageSquare,
|
||||||
|
ShieldCheck,
|
||||||
|
RefreshCw,
|
||||||
|
Loader2,
|
||||||
|
Inbox,
|
||||||
|
Clock,
|
||||||
|
Archive,
|
||||||
|
Info,
|
||||||
|
} from 'lucide-react';
|
||||||
|
import { PageHeader, Surface, SegmentedControl, EmptyState } from '@/components/ui';
|
||||||
|
import CreativePlacementPreview, {
|
||||||
|
CreativePreviewData,
|
||||||
|
} from '@/components/CreativePlacementPreview';
|
||||||
|
|
||||||
|
type Tab = 'pendientes' | 'activas' | 'historico';
|
||||||
|
|
||||||
|
type CreativeItem = {
|
||||||
|
id: string;
|
||||||
|
tenant_id: string;
|
||||||
|
campaign_name?: string | null;
|
||||||
|
adset_id?: string | null;
|
||||||
|
meta_ad_id?: string | null;
|
||||||
|
meta_creative_id?: string | null;
|
||||||
|
format?: string | null;
|
||||||
|
headline?: string | null;
|
||||||
|
primary_text?: string | null;
|
||||||
|
description?: string | null;
|
||||||
|
cta?: string | null;
|
||||||
|
destination_url?: string | null;
|
||||||
|
asset_url?: string | null;
|
||||||
|
thumbnail_url?: string | null;
|
||||||
|
asset_final?: boolean;
|
||||||
|
status:
|
||||||
|
| 'borrador'
|
||||||
|
| 'pendiente_aprobacion'
|
||||||
|
| 'aprobada'
|
||||||
|
| 'publicada'
|
||||||
|
| 'fatigada'
|
||||||
|
| 'rechazada'
|
||||||
|
| 'retirada';
|
||||||
|
visibility: 'agency' | 'client';
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
metrics?: {
|
||||||
|
impressions: number;
|
||||||
|
clicks: number;
|
||||||
|
spend: number;
|
||||||
|
results: number;
|
||||||
|
frequency: number;
|
||||||
|
ctr: number;
|
||||||
|
cpa: number | null;
|
||||||
|
} | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function ClientCreativesView({
|
||||||
|
tenantName = 'Blue Parrot School',
|
||||||
|
}: {
|
||||||
|
tenantName?: string;
|
||||||
|
}) {
|
||||||
|
const [tab, setTab] = useState<Tab>('pendientes');
|
||||||
|
const [creatives, setCreatives] = useState<CreativeItem[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [actionSuccess, setActionSuccess] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Modal de rechazo
|
||||||
|
const [rejectingCreative, setRejectingCreative] = useState<CreativeItem | null>(null);
|
||||||
|
const [rejectComment, setRejectComment] = useState('');
|
||||||
|
const [isRejecting, setIsRejecting] = useState(false);
|
||||||
|
|
||||||
|
// Modal de aprobación rápida
|
||||||
|
const [approvingCreative, setApprovingCreative] = useState<CreativeItem | null>(null);
|
||||||
|
const [isApproving, setIsApproving] = useState(false);
|
||||||
|
|
||||||
|
// Filtro de histórico
|
||||||
|
const [historicoFilter, setHistoricoFilter] = useState<'todos' | 'fatigada' | 'retirada' | 'rechazada'>('todos');
|
||||||
|
|
||||||
|
const fetchCreatives = useCallback(async () => {
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/creatives');
|
||||||
|
if (!res.ok) {
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
throw new Error(data.error || 'Error al obtener creatividades');
|
||||||
|
}
|
||||||
|
const data = await res.json();
|
||||||
|
setCreatives(data.creatives || []);
|
||||||
|
} catch (err: any) {
|
||||||
|
setError(err.message || 'Error de conexión');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void fetchCreatives();
|
||||||
|
}, [fetchCreatives]);
|
||||||
|
|
||||||
|
// Grupos por pestaña
|
||||||
|
const pendientes = useMemo(
|
||||||
|
() => creatives.filter((c) => c.status === 'pendiente_aprobacion'),
|
||||||
|
[creatives]
|
||||||
|
);
|
||||||
|
|
||||||
|
const activas = useMemo(
|
||||||
|
() => creatives.filter((c) => c.status === 'publicada'),
|
||||||
|
[creatives]
|
||||||
|
);
|
||||||
|
|
||||||
|
const historico = useMemo(
|
||||||
|
() =>
|
||||||
|
creatives.filter((c) =>
|
||||||
|
['aprobada', 'fatigada', 'retirada', 'rechazada'].includes(c.status)
|
||||||
|
),
|
||||||
|
[creatives]
|
||||||
|
);
|
||||||
|
|
||||||
|
const filteredHistorico = useMemo(() => {
|
||||||
|
if (historicoFilter === 'todos') return historico;
|
||||||
|
return historico.filter((c) => c.status === historicoFilter);
|
||||||
|
}, [historico, historicoFilter]);
|
||||||
|
|
||||||
|
async function handleApprove(c: CreativeItem) {
|
||||||
|
setIsApproving(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/creatives/${c.id}/action`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ action: 'approve' }),
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(data.error || 'Error al aprobar creatividad');
|
||||||
|
}
|
||||||
|
setApprovingCreative(null);
|
||||||
|
setActionSuccess(`¡Creatividad aprobada! Se ha enviado la orden de publicación a Meta Ads.`);
|
||||||
|
await fetchCreatives();
|
||||||
|
} catch (err: any) {
|
||||||
|
setError(err.message);
|
||||||
|
} finally {
|
||||||
|
setIsApproving(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleReject() {
|
||||||
|
if (!rejectingCreative) return;
|
||||||
|
if (!rejectComment.trim()) {
|
||||||
|
setError('Por favor indica tus observaciones o el motivo del rechazo.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsRejecting(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/creatives/${rejectingCreative.id}/action`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
action: 'reject',
|
||||||
|
comment: rejectComment.trim(),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const data = await res.json();
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(data.error || 'Error al rechazar creatividad');
|
||||||
|
}
|
||||||
|
setRejectingCreative(null);
|
||||||
|
setRejectComment('');
|
||||||
|
setActionSuccess(`Creatividad rechazada y devuelta al equipo creativo con tus observaciones.`);
|
||||||
|
await fetchCreatives();
|
||||||
|
} catch (err: any) {
|
||||||
|
setError(err.message);
|
||||||
|
} finally {
|
||||||
|
setIsRejecting(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6 max-w-7xl mx-auto px-4 sm:px-6 py-6">
|
||||||
|
<PageHeader
|
||||||
|
eyebrow="Meta Ads & Creatividades"
|
||||||
|
title="Creatividades y Anuncios"
|
||||||
|
description="Revisa las propuestas preparadas para tus campañas, valida los copies y piezas finales con un clic, consulta el rendimiento de los anuncios en circulación y accede al archivo histórico."
|
||||||
|
actions={
|
||||||
|
<button
|
||||||
|
onClick={() => void fetchCreatives()}
|
||||||
|
className="inline-flex items-center gap-1.5 text-xs font-semibold px-3 py-2 rounded-lg border border-gray-200 bg-white hover:bg-gray-50 text-gray-700 shadow-sm"
|
||||||
|
>
|
||||||
|
<RefreshCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} />
|
||||||
|
Actualizar
|
||||||
|
</button>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* Alertas */}
|
||||||
|
{actionSuccess && (
|
||||||
|
<div className="p-4 rounded-xl bg-emerald-50 border border-emerald-200 text-emerald-800 text-sm flex items-center justify-between shadow-sm">
|
||||||
|
<div className="flex items-center gap-2 font-medium">
|
||||||
|
<CheckCircle2 className="w-5 h-5 text-emerald-600 shrink-0" />
|
||||||
|
<span>{actionSuccess}</span>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => setActionSuccess(null)}
|
||||||
|
className="text-xs text-emerald-700 hover:text-emerald-900 font-semibold"
|
||||||
|
>
|
||||||
|
Cerrar
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div className="p-4 rounded-xl bg-red-50 border border-red-200 text-red-800 text-sm flex items-center justify-between shadow-sm">
|
||||||
|
<div className="flex items-center gap-2 font-medium">
|
||||||
|
<AlertTriangle className="w-5 h-5 text-red-600 shrink-0" />
|
||||||
|
<span>{error}</span>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={() => setError(null)}
|
||||||
|
className="text-xs text-red-700 hover:text-red-900 font-semibold"
|
||||||
|
>
|
||||||
|
Cerrar
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Pestañas principales */}
|
||||||
|
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 border-b border-gray-200 pb-4">
|
||||||
|
<SegmentedControl
|
||||||
|
value={tab}
|
||||||
|
onChange={setTab}
|
||||||
|
options={[
|
||||||
|
{
|
||||||
|
id: 'pendientes',
|
||||||
|
label: `Pendientes de aprobación ${pendientes.length > 0 ? `(${pendientes.length})` : ''}`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'activas',
|
||||||
|
label: `En activo ${activas.length > 0 ? `(${activas.length})` : ''}`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'historico',
|
||||||
|
label: `Histórico ${historico.length > 0 ? `(${historico.length})` : ''}`,
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-2 text-xs text-gray-500">
|
||||||
|
<ShieldCheck className="w-4 h-4 text-brand-600" />
|
||||||
|
<span>Publicación sincronizada con Meta Graph API</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* CONTENIDO DE PESTAÑAS */}
|
||||||
|
{loading && creatives.length === 0 ? (
|
||||||
|
<div className="py-20 flex flex-col items-center justify-center gap-3 text-gray-500">
|
||||||
|
<Loader2 className="w-6 h-6 animate-spin text-brand-500" />
|
||||||
|
<p className="text-sm font-medium">Cargando creatividades…</p>
|
||||||
|
</div>
|
||||||
|
) : tab === 'pendientes' ? (
|
||||||
|
/* PESTAÑA: PENDIENTES DE APROBACIÓN */
|
||||||
|
pendientes.length === 0 ? (
|
||||||
|
<EmptyState
|
||||||
|
title="¡Todo al día! No tienes creatividades pendientes de revisión"
|
||||||
|
description="El equipo de 4Ventures y los agentes automáticos monitorizan el rendimiento de tus campañas. En cuanto una creatividad empiece a mostrar signos de fatiga o se proponga una nueva variante, aparecerá aquí para tu validación."
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-8">
|
||||||
|
<div className="bg-amber-50 border border-amber-200 rounded-2xl p-4 text-xs text-amber-900 flex items-start gap-3">
|
||||||
|
<Clock className="w-4 h-4 text-amber-600 shrink-0 mt-0.5" />
|
||||||
|
<div>
|
||||||
|
<p className="font-semibold text-amber-950">
|
||||||
|
{pendientes.length} {pendientes.length === 1 ? 'propuesta creativa pendiente' : 'propuestas creativas pendientes'} de tu validación
|
||||||
|
</p>
|
||||||
|
<p className="text-amber-800 mt-0.5">
|
||||||
|
Revisa el copy y la imagen final antes de aprobar. Al aprobar, el sistema enviará automáticamente la creatividad a Meta Ads y la dejará lista en tu cuenta publicitaria.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
|
||||||
|
{pendientes.map((c) => {
|
||||||
|
const previewData: CreativePreviewData = {
|
||||||
|
title: c.headline || 'Anuncio Meta',
|
||||||
|
brand_name: tenantName,
|
||||||
|
headline: c.headline,
|
||||||
|
primary_text: c.primary_text,
|
||||||
|
description: c.description,
|
||||||
|
cta: c.cta || 'Más información',
|
||||||
|
media_url: c.asset_url,
|
||||||
|
landing_url: c.destination_url || 'https://blueparrotschool.com',
|
||||||
|
format: c.format || '4:5',
|
||||||
|
channel: 'meta_ads',
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Surface key={c.id} className="p-6 flex flex-col justify-between border-brand-200 shadow-md">
|
||||||
|
<div className="space-y-5">
|
||||||
|
{/* Cabecera de la propuesta */}
|
||||||
|
<div className="flex items-center justify-between pb-3 border-b border-gray-100">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<span className="px-2.5 py-1 rounded-full text-[11px] font-semibold bg-amber-100 text-amber-800">
|
||||||
|
Revisión interna
|
||||||
|
</span>
|
||||||
|
<span className="text-xs text-gray-500 font-medium">
|
||||||
|
Formato {c.format || '4:5'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<span className="text-[11px] text-gray-500">
|
||||||
|
{new Date(c.created_at).toLocaleDateString('es-ES', {
|
||||||
|
day: 'numeric',
|
||||||
|
month: 'short',
|
||||||
|
})}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Mockup y detalle */}
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 items-start">
|
||||||
|
{/* Mockup interactivo */}
|
||||||
|
<div className="w-full max-w-[280px] mx-auto">
|
||||||
|
<CreativePlacementPreview data={previewData} compact />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Detalles de Copy y Campaña */}
|
||||||
|
<div className="space-y-4 text-xs">
|
||||||
|
<div>
|
||||||
|
<span className="font-semibold text-gray-500 block uppercase tracking-wider text-[10px]">
|
||||||
|
Titular / Headline
|
||||||
|
</span>
|
||||||
|
<p className="text-sm font-bold text-gray-900 mt-1">
|
||||||
|
{c.headline || 'Sin titular'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<span className="font-semibold text-gray-500 block uppercase tracking-wider text-[10px]">
|
||||||
|
Texto principal / Copy
|
||||||
|
</span>
|
||||||
|
<p className="text-gray-700 mt-1 leading-relaxed whitespace-pre-line bg-gray-50 p-2.5 rounded-lg border border-gray-200 max-h-36 overflow-y-auto">
|
||||||
|
{c.primary_text || 'Sin texto'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 gap-2">
|
||||||
|
<div>
|
||||||
|
<span className="font-semibold text-gray-500 block uppercase tracking-wider text-[10px]">
|
||||||
|
Botón CTA
|
||||||
|
</span>
|
||||||
|
<span className="inline-block mt-1 font-semibold text-gray-800 bg-white border border-gray-200 px-2 py-1 rounded">
|
||||||
|
{c.cta || 'Más información'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span className="font-semibold text-gray-500 block uppercase tracking-wider text-[10px]">
|
||||||
|
Destino
|
||||||
|
</span>
|
||||||
|
<p className="mt-1 text-brand-600 truncate font-mono text-[11px]">
|
||||||
|
{c.destination_url || 'blueparrotschool.com'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Botones de acción cliente */}
|
||||||
|
<div className="mt-6 pt-4 border-t border-gray-100 flex items-center justify-end gap-3">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
setRejectingCreative(c);
|
||||||
|
setRejectComment('');
|
||||||
|
}}
|
||||||
|
className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl text-xs font-semibold text-red-700 bg-red-50 hover:bg-red-100 border border-red-200 transition-colors"
|
||||||
|
>
|
||||||
|
<XCircle className="w-4 h-4" />
|
||||||
|
Rechazar con feedback
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setApprovingCreative(c)}
|
||||||
|
className="inline-flex items-center gap-1.5 px-4 py-2 rounded-xl text-xs font-semibold text-white bg-emerald-600 hover:bg-emerald-700 shadow-sm transition-colors"
|
||||||
|
>
|
||||||
|
<CheckCircle2 className="w-4 h-4" />
|
||||||
|
Aprobar y publicar
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</Surface>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
) : tab === 'activas' ? (
|
||||||
|
/* PESTAÑA: EN ACTIVO */
|
||||||
|
activas.length === 0 ? (
|
||||||
|
<EmptyState
|
||||||
|
title="No hay creatividades activas publicadas actualmente"
|
||||||
|
description="Las creatividades que apruebes se publicarán en Meta Ads y aparecerán aquí junto con sus impresiones, clics, CTR, frecuencia y gasto acumulado."
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||||
|
{activas.map((c) => {
|
||||||
|
const m = c.metrics;
|
||||||
|
const previewData: CreativePreviewData = {
|
||||||
|
title: c.headline || 'Anuncio activo',
|
||||||
|
brand_name: tenantName,
|
||||||
|
headline: c.headline,
|
||||||
|
primary_text: c.primary_text,
|
||||||
|
description: c.description,
|
||||||
|
cta: c.cta || 'Más información',
|
||||||
|
media_url: c.asset_url,
|
||||||
|
landing_url: c.destination_url || 'https://blueparrotschool.com',
|
||||||
|
format: c.format || '4:5',
|
||||||
|
channel: 'meta_ads',
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Surface key={c.id} className="p-5 flex flex-col justify-between border-emerald-100 shadow-sm">
|
||||||
|
<div className="space-y-4">
|
||||||
|
{/* Estado y Meta ID */}
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-semibold bg-emerald-100 text-emerald-800">
|
||||||
|
<span className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse" />
|
||||||
|
En circulación
|
||||||
|
</span>
|
||||||
|
{c.meta_ad_id && (
|
||||||
|
<span className="text-[10px] text-gray-500 font-mono">
|
||||||
|
ID: {c.meta_ad_id}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Mockup preview */}
|
||||||
|
<div className="w-full max-w-[240px] mx-auto">
|
||||||
|
<CreativePlacementPreview data={previewData} compact />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* KPIs del Anuncio */}
|
||||||
|
<div className="pt-2 border-t border-gray-100 space-y-2">
|
||||||
|
<div className="text-[11px] font-bold text-gray-700 uppercase tracking-wider">
|
||||||
|
Métricas acumuladas (30 días)
|
||||||
|
</div>
|
||||||
|
<div className="grid grid-cols-3 gap-2 bg-gray-50 p-2.5 rounded-xl border border-gray-100 text-center">
|
||||||
|
<div>
|
||||||
|
<span className="text-[10px] text-gray-500 block">Impresiones</span>
|
||||||
|
<span className="text-xs font-bold text-gray-900">
|
||||||
|
{m?.impressions?.toLocaleString('es-ES') || '0'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span className="text-[10px] text-gray-500 block">Clics</span>
|
||||||
|
<span className="text-xs font-bold text-gray-900">
|
||||||
|
{m?.clicks?.toLocaleString('es-ES') || '0'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span className="text-[10px] text-gray-500 block">CTR</span>
|
||||||
|
<span className="text-xs font-bold text-brand-600">
|
||||||
|
{m?.ctr != null ? `${m.ctr}%` : '0%'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span className="text-[10px] text-gray-500 block">Frecuencia</span>
|
||||||
|
<span className="text-xs font-bold text-gray-900">
|
||||||
|
{m?.frequency ? m.frequency.toFixed(2) : '1.00'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span className="text-[10px] text-gray-500 block">Gasto</span>
|
||||||
|
<span className="text-xs font-bold text-gray-900">
|
||||||
|
{m?.spend != null ? `${m.spend.toFixed(2)}€` : '0€'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span className="text-[10px] text-gray-500 block">CPA</span>
|
||||||
|
<span className="text-xs font-bold text-emerald-600">
|
||||||
|
{m?.cpa != null ? `${m.cpa.toFixed(2)}€` : '—'}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4 pt-3 border-t border-gray-100 flex items-center justify-between text-[11px] text-gray-500">
|
||||||
|
<span>Formato {c.format || '4:5'}</span>
|
||||||
|
<span className="text-emerald-700 font-semibold">Activo en Meta Ads</span>
|
||||||
|
</div>
|
||||||
|
</Surface>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
) : (
|
||||||
|
/* PESTAÑA: HISTÓRICO */
|
||||||
|
<div className="space-y-6">
|
||||||
|
{/* Subfiltro de estado histórico */}
|
||||||
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
|
{[
|
||||||
|
{ id: 'todos', label: 'Todas las piezas' },
|
||||||
|
{ id: 'fatigada', label: 'Fatigadas' },
|
||||||
|
{ id: 'retirada', label: 'Retiradas' },
|
||||||
|
{ id: 'rechazada', label: 'Rechazadas' },
|
||||||
|
].map((f) => (
|
||||||
|
<button
|
||||||
|
key={f.id}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setHistoricoFilter(f.id as any)}
|
||||||
|
className={`text-xs px-3 py-1.5 rounded-lg font-medium transition-colors ${
|
||||||
|
historicoFilter === f.id
|
||||||
|
? 'bg-gray-900 text-white shadow-sm'
|
||||||
|
: 'bg-white border border-gray-200 text-gray-600 hover:bg-gray-50'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{f.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{filteredHistorico.length === 0 ? (
|
||||||
|
<EmptyState
|
||||||
|
title="No hay creatividades en esta sección del histórico"
|
||||||
|
description="A medida que tus anuncios cumplan su ciclo, se reemplacen por fatiga o se archiven, se conservarán aquí junto con su historial de métricas y observaciones."
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||||
|
{filteredHistorico.map((c) => {
|
||||||
|
const m = c.metrics;
|
||||||
|
const statusMetaMap: Record<
|
||||||
|
string,
|
||||||
|
{
|
||||||
|
label: string;
|
||||||
|
badge: string;
|
||||||
|
icon: React.ComponentType<{ className?: string }>;
|
||||||
|
}
|
||||||
|
> = {
|
||||||
|
fatigada: {
|
||||||
|
label: 'Fatigada (Relevo en marcha)',
|
||||||
|
badge: 'bg-amber-100 text-amber-800 border-amber-200',
|
||||||
|
icon: Flame,
|
||||||
|
},
|
||||||
|
rechazada: {
|
||||||
|
label: 'Rechazada por cliente',
|
||||||
|
badge: 'bg-red-100 text-red-800 border-red-200',
|
||||||
|
icon: XCircle,
|
||||||
|
},
|
||||||
|
retirada: {
|
||||||
|
label: 'Retirada de circulación',
|
||||||
|
badge: 'bg-gray-100 text-gray-700 border-gray-200',
|
||||||
|
icon: Archive,
|
||||||
|
},
|
||||||
|
aprobada: {
|
||||||
|
label: 'Aprobada (En cola de publicación)',
|
||||||
|
badge: 'bg-blue-100 text-blue-800 border-blue-200',
|
||||||
|
icon: CheckCircle2,
|
||||||
|
},
|
||||||
|
publicada: {
|
||||||
|
label: 'En circulación',
|
||||||
|
badge: 'bg-emerald-100 text-emerald-800 border-emerald-200',
|
||||||
|
icon: CheckCircle2,
|
||||||
|
},
|
||||||
|
pendiente_aprobacion: {
|
||||||
|
label: 'Pendiente de aprobación',
|
||||||
|
badge: 'bg-amber-100 text-amber-800 border-amber-200',
|
||||||
|
icon: Clock,
|
||||||
|
},
|
||||||
|
borrador: {
|
||||||
|
label: 'Borrador interno',
|
||||||
|
badge: 'bg-gray-100 text-gray-700 border-gray-200',
|
||||||
|
icon: Info,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const statusMeta = statusMetaMap[c.status] || {
|
||||||
|
label: c.status,
|
||||||
|
badge: 'bg-gray-100 text-gray-700 border-gray-200',
|
||||||
|
icon: Info,
|
||||||
|
};
|
||||||
|
|
||||||
|
const Icon = statusMeta.icon;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Surface key={c.id} className="p-5 flex flex-col justify-between border-gray-200">
|
||||||
|
<div className="space-y-4">
|
||||||
|
{/* Badge de estado */}
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span
|
||||||
|
className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-semibold border ${statusMeta.badge}`}
|
||||||
|
>
|
||||||
|
<Icon className="w-3.5 h-3.5" />
|
||||||
|
{statusMeta.label}
|
||||||
|
</span>
|
||||||
|
<span className="text-[11px] text-gray-500">
|
||||||
|
{new Date(c.updated_at).toLocaleDateString('es-ES', {
|
||||||
|
day: 'numeric',
|
||||||
|
month: 'short',
|
||||||
|
})}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Imagen o miniatura */}
|
||||||
|
{c.asset_url ? (
|
||||||
|
<div className="aspect-[4/5] max-h-56 w-full rounded-xl overflow-hidden bg-gray-100 border border-gray-200">
|
||||||
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
|
<img
|
||||||
|
src={c.asset_url}
|
||||||
|
alt={c.headline || 'Creatividad histórica'}
|
||||||
|
className="w-full h-full object-cover"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="aspect-[4/5] max-h-48 w-full rounded-xl bg-gray-50 border border-dashed border-gray-200 flex items-center justify-center text-gray-400 text-xs">
|
||||||
|
Sin visual
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Titular y copy resumido */}
|
||||||
|
<div>
|
||||||
|
<h4 className="text-sm font-bold text-gray-900 line-clamp-2">
|
||||||
|
{c.headline || 'Sin titular'}
|
||||||
|
</h4>
|
||||||
|
{c.primary_text && (
|
||||||
|
<p className="text-xs text-gray-600 line-clamp-3 mt-1 leading-relaxed">
|
||||||
|
{c.primary_text}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Métricas históricas alcanzadas */}
|
||||||
|
{m && m.impressions > 0 && (
|
||||||
|
<div className="bg-gray-50 p-2.5 rounded-xl border border-gray-100 text-xs grid grid-cols-3 gap-2 text-center">
|
||||||
|
<div>
|
||||||
|
<span className="text-[10px] text-gray-500 block">Gasto total</span>
|
||||||
|
<span className="font-bold text-gray-900">{m.spend.toFixed(2)}€</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span className="text-[10px] text-gray-500 block">Impresiones</span>
|
||||||
|
<span className="font-bold text-gray-900">
|
||||||
|
{m.impressions.toLocaleString('es-ES')}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<span className="text-[10px] text-gray-500 block">CTR</span>
|
||||||
|
<span className="font-bold text-brand-600">{m.ctr}%</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-4 pt-3 border-t border-gray-100 flex items-center justify-between text-[11px] text-gray-500">
|
||||||
|
<span>Formato {c.format || '4:5'}</span>
|
||||||
|
{c.meta_ad_id && (
|
||||||
|
<span className="font-mono text-[10px]">Meta: {c.meta_ad_id}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</Surface>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* MODAL DE CONFIRMACIÓN DE APROBACIÓN */}
|
||||||
|
{approvingCreative && (
|
||||||
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
|
||||||
|
<div className="bg-white rounded-2xl max-w-md w-full p-6 shadow-2xl space-y-4">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="w-10 h-10 rounded-full bg-emerald-100 text-emerald-600 flex items-center justify-center shrink-0">
|
||||||
|
<CheckCircle2 className="w-6 h-6" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="text-base font-bold text-gray-900">
|
||||||
|
¿Aprobar creatividad para Meta Ads?
|
||||||
|
</h3>
|
||||||
|
<p className="text-xs text-gray-500 mt-0.5">
|
||||||
|
Confirmarás el lanzamiento de esta propuesta.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="bg-gray-50 p-3 rounded-xl border border-gray-200 text-xs text-gray-700 space-y-1.5">
|
||||||
|
<p className="font-semibold text-gray-900">
|
||||||
|
{approvingCreative.headline || 'Propuesta de anuncio'}
|
||||||
|
</p>
|
||||||
|
<p className="line-clamp-2 text-gray-600">
|
||||||
|
{approvingCreative.primary_text || 'Sin copy'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p className="text-xs text-gray-600 leading-relaxed">
|
||||||
|
Al confirmar, la creatividad se marcará como <strong>aprobada</strong> y el flujo automático en n8n la creará en tu cuenta de Meta Ads con su imagen final en alta resolución, titular, enlace y llamada a la acción.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-end gap-2 pt-3">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={isApproving}
|
||||||
|
onClick={() => setApprovingCreative(null)}
|
||||||
|
className="px-4 py-2 rounded-xl text-xs font-semibold text-gray-700 hover:bg-gray-100"
|
||||||
|
>
|
||||||
|
Cancelar
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={isApproving}
|
||||||
|
onClick={() => void handleApprove(approvingCreative)}
|
||||||
|
className="inline-flex items-center gap-1.5 px-4 py-2 rounded-xl text-xs font-semibold text-white bg-emerald-600 hover:bg-emerald-700 shadow-sm"
|
||||||
|
>
|
||||||
|
{isApproving ? (
|
||||||
|
<>
|
||||||
|
<Loader2 className="w-3.5 h-3.5 animate-spin" />
|
||||||
|
Procesando…
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
'Confirmar y publicar'
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* MODAL DE RECHAZO CON FEEDBACK */}
|
||||||
|
{rejectingCreative && (
|
||||||
|
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4">
|
||||||
|
<div className="bg-white rounded-2xl max-w-lg w-full p-6 shadow-2xl space-y-4">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="w-10 h-10 rounded-full bg-red-100 text-red-600 flex items-center justify-center shrink-0">
|
||||||
|
<XCircle className="w-6 h-6" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="text-base font-bold text-gray-900">
|
||||||
|
Rechazar creatividad y solicitar cambios
|
||||||
|
</h3>
|
||||||
|
<p className="text-xs text-gray-500 mt-0.5">
|
||||||
|
Tus observaciones llegarán directamente al equipo de marketing para generar una nueva versión.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<label className="block text-xs font-semibold text-gray-700">
|
||||||
|
Observaciones y cambios requeridos <span className="text-red-500">*</span>
|
||||||
|
</label>
|
||||||
|
<textarea
|
||||||
|
rows={4}
|
||||||
|
value={rejectComment}
|
||||||
|
onChange={(e) => setRejectComment(e.target.value)}
|
||||||
|
placeholder="Indica qué cambios necesitas: tono del texto, titular más directo, enfoque de la imagen, llamada a la acción diferente..."
|
||||||
|
className="w-full text-xs p-3 rounded-xl border border-gray-300 focus:outline-none focus:ring-2 focus:ring-brand-500 text-gray-900"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center justify-end gap-2 pt-3">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={isRejecting}
|
||||||
|
onClick={() => setRejectingCreative(null)}
|
||||||
|
className="px-4 py-2 rounded-xl text-xs font-semibold text-gray-700 hover:bg-gray-100"
|
||||||
|
>
|
||||||
|
Cancelar
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={isRejecting || !rejectComment.trim()}
|
||||||
|
onClick={() => void handleReject()}
|
||||||
|
className="inline-flex items-center gap-1.5 px-4 py-2 rounded-xl text-xs font-semibold text-white bg-red-600 hover:bg-red-700 shadow-sm disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{isRejecting ? (
|
||||||
|
<>
|
||||||
|
<Loader2 className="w-3.5 h-3.5 animate-spin" />
|
||||||
|
Enviando feedback…
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
'Enviar observaciones'
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -269,6 +269,13 @@ export default function ClientFicha({
|
|||||||
<ArrowLeft className="w-3.5 h-3.5" />
|
<ArrowLeft className="w-3.5 h-3.5" />
|
||||||
Portafolio
|
Portafolio
|
||||||
</Link>
|
</Link>
|
||||||
|
<Link
|
||||||
|
href={`/dashboard/agencia/cliente/${tenantId}/creatividades`}
|
||||||
|
className="inline-flex items-center gap-1.5 text-xs font-semibold px-3 py-1.5 rounded-lg border border-brand-200 bg-brand-50 text-brand-700 hover:bg-brand-100"
|
||||||
|
>
|
||||||
|
<Sparkles className="w-3.5 h-3.5" />
|
||||||
|
Creatividades Meta/IA
|
||||||
|
</Link>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => void enterAsClient()}
|
onClick={() => void enterAsClient()}
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ import {
|
|||||||
X,
|
X,
|
||||||
Leaf,
|
Leaf,
|
||||||
BookMarked,
|
BookMarked,
|
||||||
|
Sparkles,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import TenantSwitcher from '@/components/TenantSwitcher';
|
import TenantSwitcher from '@/components/TenantSwitcher';
|
||||||
import type { DashboardModuleId } from '@/lib/tenant-modules';
|
import type { DashboardModuleId } from '@/lib/tenant-modules';
|
||||||
@@ -102,10 +103,10 @@ const NAV_ITEMS: NavItem[] = [
|
|||||||
moduleId: 'activos',
|
moduleId: 'activos',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
href: '/dashboard/creatives',
|
href: '/dashboard/creatividades',
|
||||||
label: 'Pipeline creatividades',
|
label: 'Creatividades Ads',
|
||||||
icon: FolderGit2,
|
icon: Sparkles,
|
||||||
iconClass: 'text-orange-500',
|
iconClass: 'text-brand-500',
|
||||||
moduleId: 'creatives',
|
moduleId: 'creatives',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -49,10 +49,10 @@ export function applyVisibilityScope<T extends Record<string, any>>(
|
|||||||
// Rol CLIENT: reglas estrictas de la sección 4
|
// Rol CLIENT: reglas estrictas de la sección 4
|
||||||
switch (resource) {
|
switch (resource) {
|
||||||
case 'creatives':
|
case 'creatives':
|
||||||
// Solo status in ('pendiente_aprobacion','aprobada','publicada','retirada') Y visibility = 'client'
|
// Solo status visibles para el cliente Y visibility = 'client'
|
||||||
query = query
|
query = query
|
||||||
.eq('visibility', 'client')
|
.eq('visibility', 'client')
|
||||||
.in('status', ['pendiente_aprobacion', 'aprobada', 'publicada', 'retirada']);
|
.in('status', ['pendiente_aprobacion', 'aprobada', 'publicada', 'fatigada', 'retirada', 'rechazada']);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'creative_events':
|
case 'creative_events':
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ export interface ActionActor {
|
|||||||
userId?: string | null;
|
userId?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function getAdminClient() {
|
export function getAdminClient() {
|
||||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
|
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL!;
|
||||||
const serviceRoleKey = process.env.SUPABASE_SERVICE_ROLE_KEY!;
|
const serviceRoleKey = process.env.SUPABASE_SERVICE_ROLE_KEY!;
|
||||||
return createClient(supabaseUrl, serviceRoleKey);
|
return createClient(supabaseUrl, serviceRoleKey);
|
||||||
|
|||||||
@@ -96,10 +96,10 @@ export const DASHBOARD_MODULES: DashboardModuleDef[] = [
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'creatives',
|
id: 'creatives',
|
||||||
href: '/dashboard/creatives',
|
href: '/dashboard/creatividades',
|
||||||
label: 'Pipeline creatividades',
|
label: 'Creatividades Ads',
|
||||||
providers: ['google_drive', 'meta_ads', 'google_ads'],
|
providers: ['google_drive', 'meta_ads', 'google_ads'],
|
||||||
hint: 'Aprobación de piezas ads y RRSS',
|
hint: 'Aprobación de anuncios Meta y rendimiento',
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'asistente',
|
id: 'asistente',
|
||||||
|
|||||||
Reference in New Issue
Block a user