feat: sync Meta metrics, objetivos ppto/consecución y simulador por tenant
Rellena ad_daily desde Meta, KPIs con fallback a daily, objetivos de presupuesto vs consecución, y simulador sin TikTok anclado a métricas del cliente. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -1,10 +1,52 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { createClient } from '@/lib/supabase/server';
|
||||
import { resolveActiveTenant, restGet } from '@/lib/tenant-context';
|
||||
import { isAgencyRole, userRole } from '@/lib/agency';
|
||||
import { AdDailyRow, KpiWeeklyRow } from '@/lib/metrics';
|
||||
import {
|
||||
SimChannel,
|
||||
simulateFromTenantMetrics,
|
||||
} from '@/lib/simulate';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
async function loadTenantMetrics(tenantId: string, agencyView: boolean) {
|
||||
let daily: AdDailyRow[] = [];
|
||||
let weekly: KpiWeeklyRow[] = [];
|
||||
|
||||
if (agencyView) {
|
||||
const tid = encodeURIComponent(tenantId);
|
||||
const [d, w] = await Promise.all([
|
||||
restGet<AdDailyRow[]>(
|
||||
`/rest/v1/ad_daily?tenant_id=eq.${tid}&select=*&order=date.desc&limit=400`
|
||||
),
|
||||
restGet<KpiWeeklyRow[]>(
|
||||
`/rest/v1/kpi_weekly?tenant_id=eq.${tid}&select=*&order=week.desc&limit=52`
|
||||
),
|
||||
]);
|
||||
daily = d.data || [];
|
||||
weekly = w.data || [];
|
||||
} else {
|
||||
const supabase = await createClient();
|
||||
const [{ data: d }, { data: w }] = await Promise.all([
|
||||
supabase
|
||||
.from('ad_daily')
|
||||
.select('*')
|
||||
.order('date', { ascending: false })
|
||||
.limit(400),
|
||||
supabase
|
||||
.from('kpi_weekly')
|
||||
.select('*')
|
||||
.order('week', { ascending: false })
|
||||
.limit(52),
|
||||
]);
|
||||
daily = (d as AdDailyRow[]) || [];
|
||||
weekly = (w as KpiWeeklyRow[]) || [];
|
||||
}
|
||||
return { daily, weekly };
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || 'https://supabase.4ventures.es';
|
||||
const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY?.trim() || '';
|
||||
|
||||
const supabase = await createClient();
|
||||
const {
|
||||
data: { user },
|
||||
@@ -13,42 +55,50 @@ export async function POST(req: NextRequest) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const tenantId =
|
||||
user.app_metadata?.tenant_id || user.user_metadata?.tenant_id || null;
|
||||
if (!tenantId) {
|
||||
const ctx = await resolveActiveTenant(user);
|
||||
if (!ctx.tenantId || ctx.portfolioWide) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Usuario sin tenant_id' },
|
||||
{ status: 403 }
|
||||
{ error: 'Selecciona un cliente en Contexto para simular.' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const keyForRpc = serviceKey || process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || '';
|
||||
|
||||
try {
|
||||
const body = await req.json();
|
||||
const spend = parseFloat(body.spend || 1000);
|
||||
const channel = body.channel || 'meta';
|
||||
let channel = String(body.channel || 'blended').toLowerCase();
|
||||
|
||||
const res = await fetch(`${supabaseUrl}/rest/v1/rpc/simulate_budget`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
apikey: keyForRpc,
|
||||
Authorization: `Bearer ${keyForRpc}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
p_tenant_id: tenantId,
|
||||
p_additional_spend: spend,
|
||||
p_target_channel: channel === 'blended' ? null : channel,
|
||||
}),
|
||||
if (channel === 'tiktok') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
'TikTok no está activo aún en este portafolio. Usa Meta, Google o blended.',
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
if (!['meta', 'google', 'blended'].includes(channel)) {
|
||||
channel = 'blended';
|
||||
}
|
||||
|
||||
const agency = isAgencyRole(userRole(user));
|
||||
const { daily, weekly } = await loadTenantMetrics(
|
||||
ctx.tenantId,
|
||||
agency && ctx.viaView
|
||||
);
|
||||
|
||||
const sim = simulateFromTenantMetrics({
|
||||
spend: Number.isFinite(spend) && spend > 0 ? spend : 1000,
|
||||
channel: channel as SimChannel,
|
||||
daily,
|
||||
weekly,
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
return NextResponse.json(data);
|
||||
}
|
||||
const err = await res.text();
|
||||
return NextResponse.json({ error: err }, { status: 500 });
|
||||
return NextResponse.json({
|
||||
...sim,
|
||||
tenant_label: ctx.label,
|
||||
hint: 'Estimación con CPL, cierre y ticket del cliente en contexto (ad_daily + kpi_weekly).',
|
||||
});
|
||||
} catch (e: unknown) {
|
||||
const message = e instanceof Error ? e.message : 'Error';
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
|
||||
Reference in New Issue
Block a user