feat: agency portfolio with per-client integrations hub

Admin home lists tenants, alerts, and connection health; header
selector enables superadmin context; Meta/GA4/GSC/GTM/CRM/email
slots live per tenant (manual status until OAuth).

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
4Ventures
2026-09-22 01:31:47 +02:00
parent 9d1609c88b
commit 791976a3d8
19 changed files with 1503 additions and 20 deletions

View File

@@ -0,0 +1,91 @@
import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import {
VIEW_TENANT_COOKIE,
VIEW_TENANT_NAME_COOKIE,
VIEW_TENANT_SLUG_COOKIE,
isAgencyRole,
serviceHeaders,
supabaseUrl,
userRole,
} from '@/lib/agency';
export const dynamic = 'force-dynamic';
/** POST { tenantId } — set superadmin view context cookie. null clears. */
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 });
}
if (!isAgencyRole(userRole(user))) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const body = await req.json().catch(() => ({}));
const tenantId =
typeof body.tenantId === 'string' && body.tenantId.trim()
? body.tenantId.trim()
: null;
const cookieOpts = {
path: '/',
maxAge: 60 * 60 * 24 * 30,
sameSite: 'lax' as const,
secure: process.env.NODE_ENV === 'production',
httpOnly: false,
};
if (!tenantId) {
const res = NextResponse.json({ ok: true, cleared: true });
res.cookies.set(VIEW_TENANT_COOKIE, '', { ...cookieOpts, maxAge: 0 });
res.cookies.set(VIEW_TENANT_SLUG_COOKIE, '', { ...cookieOpts, maxAge: 0 });
res.cookies.set(VIEW_TENANT_NAME_COOKIE, '', { ...cookieOpts, maxAge: 0 });
return res;
}
const headers = serviceHeaders();
if (!headers) {
return NextResponse.json(
{ error: 'Falta SUPABASE_SERVICE_ROLE_KEY' },
{ status: 503 }
);
}
const r = await fetch(
`${supabaseUrl()}/rest/v1/tenants?id=eq.${encodeURIComponent(tenantId)}&select=id,name,slug`,
{ headers, cache: 'no-store' }
);
if (!r.ok) {
return NextResponse.json({ error: 'Tenant lookup failed' }, { status: 500 });
}
const rows = await r.json();
const tenant = Array.isArray(rows) ? rows[0] : null;
if (!tenant) {
return NextResponse.json({ error: 'Tenant no encontrado' }, { status: 404 });
}
const res = NextResponse.json({
ok: true,
tenant: { id: tenant.id, name: tenant.name, slug: tenant.slug },
});
res.cookies.set(VIEW_TENANT_COOKIE, tenant.id, cookieOpts);
res.cookies.set(VIEW_TENANT_SLUG_COOKIE, tenant.slug || '', cookieOpts);
res.cookies.set(VIEW_TENANT_NAME_COOKIE, tenant.name || '', cookieOpts);
return res;
}
export async function GET() {
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// readable from client via document.cookie too; this is for SSR helpers
return NextResponse.json({ ok: true });
}

View File

@@ -0,0 +1,104 @@
import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import {
isAgencyRole,
serviceHeaders,
supabaseUrl,
userRole,
} from '@/lib/agency';
export const dynamic = 'force-dynamic';
export async function GET() {
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
if (!isAgencyRole(userRole(user))) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const headers = serviceHeaders();
if (!headers) {
return NextResponse.json({ alerts: [], warning: 'no service role' });
}
const r = await fetch(
`${supabaseUrl()}/rest/v1/agency_alerts?select=*&order=created_at.desc&limit=50`,
{ headers, cache: 'no-store' }
);
if (!r.ok) {
return NextResponse.json({
alerts: [],
warning: 'Aplicar sql/agency_portfolio.sql',
});
}
return NextResponse.json({ alerts: await r.json() });
}
/** POST { id } mark read — or { title, body, severity, tenantId } create */
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 });
}
if (!isAgencyRole(userRole(user))) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const headers = serviceHeaders();
if (!headers) {
return NextResponse.json({ error: 'no service role' }, { status: 503 });
}
const body = await req.json().catch(() => ({}));
const base = supabaseUrl();
if (typeof body.id === 'string' && body.markRead) {
const r = await fetch(
`${base}/rest/v1/agency_alerts?id=eq.${encodeURIComponent(body.id)}`,
{
method: 'PATCH',
headers: { ...headers, 'Content-Type': 'application/json' },
body: JSON.stringify({ read_at: new Date().toISOString() }),
}
);
if (!r.ok) {
return NextResponse.json({ error: await r.text() }, { status: 500 });
}
return NextResponse.json({ ok: true });
}
const title = typeof body.title === 'string' ? body.title.trim() : '';
if (!title) {
return NextResponse.json({ error: 'title requerido' }, { status: 400 });
}
const row = {
title,
body: typeof body.body === 'string' ? body.body : null,
severity: body.severity || 'info',
tenant_id: body.tenantId || null,
source: body.source || 'manual',
href: body.href || null,
};
const r = await fetch(`${base}/rest/v1/agency_alerts`, {
method: 'POST',
headers: {
...headers,
'Content-Type': 'application/json',
Prefer: 'return=representation',
},
body: JSON.stringify(row),
});
if (!r.ok) {
return NextResponse.json({ error: await r.text() }, { status: 500 });
}
const created = await r.json();
return NextResponse.json({ alert: created[0] || created }, { status: 201 });
}

View File

@@ -38,6 +38,45 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ error: error.message || 'Error al provisionar cliente en base de datos.' }, { status: 500 });
}
// Seed integration slots (best-effort; ignore if table missing)
try {
const tenantId =
data?.tenant_id || data?.id || data?.client?.tenant_id || null;
const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY?.trim();
const url = process.env.NEXT_PUBLIC_SUPABASE_URL || 'https://supabase.4ventures.es';
if (tenantId && serviceKey) {
const providers = [
['meta_ads', 'Meta Ads'],
['google_ads', 'Google Ads (MCC)'],
['ga4', 'Google Analytics 4'],
['search_console', 'Search Console'],
['tag_manager', 'Tag Manager'],
['clientify', 'Clientify'],
['klaviyo', 'Klaviyo'],
['mailchimp', 'Mailchimp'],
];
await fetch(`${url}/rest/v1/integrations`, {
method: 'POST',
headers: {
apikey: serviceKey,
Authorization: `Bearer ${serviceKey}`,
'Content-Type': 'application/json',
Prefer: 'resolution=ignore-duplicates',
},
body: JSON.stringify(
providers.map(([provider, label]) => ({
tenant_id: tenantId,
provider,
status: 'disconnected',
label,
}))
),
});
}
} catch (e) {
console.warn('seed integrations skipped', e);
}
return NextResponse.json({ success: true, client: data });
} catch (err: any) {
console.error('Server error creating client:', err);

View File

@@ -0,0 +1,180 @@
import { NextRequest, NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import {
INTEGRATION_PROVIDERS,
isAgencyRole,
serviceHeaders,
supabaseUrl,
userRole,
} from '@/lib/agency';
export const dynamic = 'force-dynamic';
async function requireAgency() {
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) return { error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) };
if (!isAgencyRole(userRole(user))) {
return { error: NextResponse.json({ error: 'Forbidden' }, { status: 403 }) };
}
const headers = serviceHeaders();
if (!headers) {
return {
error: NextResponse.json(
{ error: 'Falta SUPABASE_SERVICE_ROLE_KEY' },
{ status: 503 }
),
};
}
return { user, headers };
}
/** GET ?tenantId= — integrations for one tenant (seed missing providers). */
export async function GET(req: NextRequest) {
const gate = await requireAgency();
if ('error' in gate && gate.error) return gate.error;
const { headers } = gate as { headers: { apikey: string; Authorization: string } };
const tenantId = req.nextUrl.searchParams.get('tenantId');
if (!tenantId) {
return NextResponse.json({ error: 'tenantId requerido' }, { status: 400 });
}
const base = supabaseUrl();
const listRes = await fetch(
`${base}/rest/v1/integrations?tenant_id=eq.${encodeURIComponent(tenantId)}&select=*`,
{ headers, cache: 'no-store' }
);
if (!listRes.ok) {
const msg = await listRes.text();
return NextResponse.json(
{
integrations: [],
providers: INTEGRATION_PROVIDERS,
warning: msg.includes('does not exist')
? 'Aplicar sql/agency_portfolio.sql'
: msg.slice(0, 200),
},
{ status: 200 }
);
}
let integrations = await listRes.json();
const have = new Set(
(integrations as { provider: string }[]).map((i) => i.provider)
);
const missing = INTEGRATION_PROVIDERS.filter((p) => !have.has(p.id));
if (missing.length) {
const rows = missing.map((p) => ({
tenant_id: tenantId,
provider: p.id,
status: 'disconnected',
label: p.label,
}));
await fetch(`${base}/rest/v1/integrations`, {
method: 'POST',
headers: { ...headers, 'Content-Type': 'application/json', Prefer: 'return=representation' },
body: JSON.stringify(rows),
});
const again = await fetch(
`${base}/rest/v1/integrations?tenant_id=eq.${encodeURIComponent(tenantId)}&select=*`,
{ headers, cache: 'no-store' }
);
if (again.ok) integrations = await again.json();
}
return NextResponse.json({
integrations,
providers: INTEGRATION_PROVIDERS,
});
}
/** PATCH — update one integration status/account (manual connect for now). */
export async function PATCH(req: NextRequest) {
const gate = await requireAgency();
if ('error' in gate && gate.error) return gate.error;
const { headers } = gate as { headers: { apikey: string; Authorization: string } };
const body = await req.json().catch(() => ({}));
const tenantId = typeof body.tenantId === 'string' ? body.tenantId.trim() : '';
const provider = typeof body.provider === 'string' ? body.provider.trim() : '';
const status = typeof body.status === 'string' ? body.status.trim() : '';
const externalAccountId =
typeof body.externalAccountId === 'string'
? body.externalAccountId.trim()
: undefined;
const label =
typeof body.label === 'string' ? body.label.trim() : undefined;
const errorMessage =
typeof body.errorMessage === 'string' ? body.errorMessage.trim() : undefined;
if (!tenantId || !provider || !status) {
return NextResponse.json(
{ error: 'tenantId, provider y status requeridos' },
{ status: 400 }
);
}
if (
!['disconnected', 'pending', 'connected', 'error'].includes(status)
) {
return NextResponse.json({ error: 'status inválido' }, { status: 400 });
}
const patch: Record<string, unknown> = {
status,
updated_at: new Date().toISOString(),
};
if (externalAccountId !== undefined) {
patch.external_account_id = externalAccountId || null;
}
if (label !== undefined) patch.label = label || null;
if (errorMessage !== undefined) patch.error_message = errorMessage || null;
if (status === 'connected') {
patch.last_sync_at = new Date().toISOString();
patch.error_message = null;
}
const base = supabaseUrl();
const url = `${base}/rest/v1/integrations?tenant_id=eq.${encodeURIComponent(tenantId)}&provider=eq.${encodeURIComponent(provider)}`;
const r = await fetch(url, {
method: 'PATCH',
headers: {
...headers,
'Content-Type': 'application/json',
Prefer: 'return=representation',
},
body: JSON.stringify(patch),
});
if (!r.ok) {
// upsert if missing
const ins = await fetch(`${base}/rest/v1/integrations`, {
method: 'POST',
headers: {
...headers,
'Content-Type': 'application/json',
Prefer: 'return=representation,resolution=merge-duplicates',
},
body: JSON.stringify({
tenant_id: tenantId,
provider,
...patch,
}),
});
if (!ins.ok) {
return NextResponse.json(
{ error: await ins.text() },
{ status: 500 }
);
}
const created = await ins.json();
return NextResponse.json({ integration: created[0] || created });
}
const updated = await r.json();
return NextResponse.json({ integration: updated[0] || updated });
}

View File

@@ -0,0 +1,105 @@
import { NextResponse } from 'next/server';
import { createClient } from '@/lib/supabase/server';
import {
INTEGRATION_PROVIDERS,
isAgencyRole,
serviceHeaders,
supabaseUrl,
userRole,
} from '@/lib/agency';
export const dynamic = 'force-dynamic';
/** GET portfolio: tenants + integration summary + unread alerts (agency only). */
export async function GET() {
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
if (!isAgencyRole(userRole(user))) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
const headers = serviceHeaders();
if (!headers) {
return NextResponse.json(
{ error: 'Falta SUPABASE_SERVICE_ROLE_KEY' },
{ status: 503 }
);
}
const base = supabaseUrl();
const [tenantsRes, integRes, alertsRes] = await Promise.all([
fetch(`${base}/rest/v1/tenants?select=id,name,slug,created_at&order=name.asc`, {
headers,
cache: 'no-store',
}),
fetch(
`${base}/rest/v1/integrations?select=id,tenant_id,provider,status,label,external_account_id,last_sync_at,error_message`,
{ headers, cache: 'no-store' }
),
fetch(
`${base}/rest/v1/agency_alerts?select=*&read_at=is.null&order=created_at.desc&limit=40`,
{ headers, cache: 'no-store' }
),
]);
const tenants = tenantsRes.ok ? await tenantsRes.json() : [];
const integrations = integRes.ok ? await integRes.json() : [];
const alerts = alertsRes.ok ? await alertsRes.json() : [];
const integMissing =
!integRes.ok &&
(await integRes.text().catch(() => '')).toLowerCase().includes('does not exist');
type Integ = {
tenant_id: string;
provider: string;
status: string;
};
const byTenant = new Map<string, Integ[]>();
for (const row of integrations as Integ[]) {
const list = byTenant.get(row.tenant_id) || [];
list.push(row);
byTenant.set(row.tenant_id, list);
}
const portfolio = (tenants as { id: string; name: string; slug: string; created_at: string }[]).map(
(t) => {
const rows = byTenant.get(t.id) || [];
const connected = rows.filter((r) => r.status === 'connected').length;
const errors = rows.filter((r) => r.status === 'error').length;
const pending = rows.filter((r) => r.status === 'pending').length;
return {
...t,
integrations: rows,
stats: {
connected,
errors,
pending,
totalProviders: INTEGRATION_PROVIDERS.length,
health:
errors > 0
? 'critical'
: connected === 0
? 'empty'
: pending > 0
? 'warning'
: 'ok',
},
};
}
);
return NextResponse.json({
portfolio,
alerts,
providers: INTEGRATION_PROVIDERS,
schemaReady: !integMissing,
warning: integMissing
? 'Falta aplicar sql/agency_portfolio.sql en Supabase'
: null,
});
}

View File

@@ -1,5 +1,27 @@
import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { createClient } from '@/lib/supabase/server';
import {
VIEW_TENANT_COOKIE,
homeTenantId,
isAgencyRole,
serviceHeaders,
supabaseUrl,
userRole,
} from '@/lib/agency';
async function resolveTenantId(user: {
app_metadata?: Record<string, unknown>;
user_metadata?: Record<string, unknown>;
}): Promise<{ tenantId: string | null; viaView: boolean }> {
const role = userRole(user);
const cookieStore = await cookies();
const viewId = cookieStore.get(VIEW_TENANT_COOKIE)?.value || null;
if (isAgencyRole(role) && viewId) {
return { tenantId: viewId, viaView: true };
}
return { tenantId: homeTenantId(user), viaView: false };
}
export async function GET() {
const supabase = await createClient();
@@ -10,13 +32,39 @@ export async function GET() {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { tenantId, viaView } = await resolveTenantId(user);
if (viaView && tenantId) {
const headers = serviceHeaders();
if (!headers) {
return NextResponse.json(
{ creatives: [], warning: 'Service role required for superadmin view' },
{ status: 200 }
);
}
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`,
{ headers, cache: 'no-store' }
);
if (!r.ok) {
return NextResponse.json({
creatives: [],
warning: await r.text(),
viewTenantId: tenantId,
});
}
return NextResponse.json({
creatives: await r.json(),
viewTenantId: tenantId,
});
}
const { data, error } = await supabase
.from('creatives')
.select('id,title,status,mime_type,bytes,created_at,updated_at')
.order('updated_at', { ascending: false });
if (error) {
// Table may not exist yet — soft message for pre-migration
return NextResponse.json(
{ creatives: [], warning: error.message },
{ status: 200 }
@@ -35,8 +83,7 @@ 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;
const { tenantId, viaView } = await resolveTenantId(user);
if (!tenantId) {
return NextResponse.json({ error: 'Usuario sin tenant_id' }, { status: 403 });
}
@@ -47,14 +94,43 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ error: 'title requerido' }, { status: 400 });
}
const row = {
tenant_id: tenantId,
title,
status: 'draft',
created_by: user.id,
};
if (viaView) {
const headers = serviceHeaders();
if (!headers) {
return NextResponse.json(
{ error: 'Service role required' },
{ status: 503 }
);
}
const r = await fetch(`${supabaseUrl()}/rest/v1/creatives`, {
method: 'POST',
headers: {
...headers,
'Content-Type': 'application/json',
Prefer: 'return=representation',
},
body: JSON.stringify(row),
});
if (!r.ok) {
return NextResponse.json({ error: await r.text() }, { status: 500 });
}
const data = await r.json();
return NextResponse.json(
{ creative: Array.isArray(data) ? data[0] : data },
{ status: 201 }
);
}
const { data, error } = await supabase
.from('creatives')
.insert({
tenant_id: tenantId,
title,
status: 'draft',
created_by: user.id,
})
.insert(row)
.select('id,title,status,created_at')
.single();

View File

@@ -0,0 +1,41 @@
import React from 'react';
import ClientIntegrationsPanel from '@/components/ClientIntegrationsPanel';
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 ClienteIntegrationsPage({
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');
const headers = serviceHeaders();
let name = 'Cliente';
if (headers) {
const r = await fetch(
`${supabaseUrl()}/rest/v1/tenants?id=eq.${encodeURIComponent(id)}&select=name`,
{ headers, cache: 'no-store' }
);
if (r.ok) {
const rows = await r.json();
if (rows[0]?.name) name = rows[0].name;
}
}
return <ClientIntegrationsPanel tenantId={id} tenantName={name} />;
}

View File

@@ -1,6 +1,7 @@
import React from 'react';
import { Building2, DollarSign, Users, TrendingUp, Layers } from 'lucide-react';
import ClientManagement from '@/components/ClientManagement';
import AgencyPortfolioBoard from '@/components/AgencyPortfolioBoard';
import { createClient } from '@/lib/supabase/server';
import { redirect } from 'next/navigation';
@@ -76,10 +77,12 @@ export default async function AgencyPage() {
</div>
<h2 className="text-2xl font-bold tracking-tight text-white">Centro de Mando 4Ventures</h2>
<p className="text-sm text-gray-400 mt-1">
Métricas consolidadas de infraestructura, inversión publicitaria y cartera de clientes.
Portafolio multi-cliente · integraciones (Meta, MCC, GA4, GSC, GTM, CRM, email) · alertas · modo superadmin.
</p>
</div>
<AgencyPortfolioBoard />
{/* Global Agency KPI Cards */}
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
<div className="bg-[#111827] border border-gray-800 rounded-xl p-5">

View File

@@ -57,7 +57,8 @@ export default function CreativesPage() {
Creatividades
</h2>
<p className="text-sm text-gray-400 mt-1">
Borradores por tenant con RLS · visibles solo para tu <code>tenant_id</code>.
Borradores del cliente en contexto (selector arriba). Con superadmin
activo, ves/creas en ese tenant.
</p>
</div>

View File

@@ -13,6 +13,9 @@ import {
} from 'lucide-react';
import { createClient } from '@/lib/supabase/server';
import { logoutAction } from '@/app/auth/actions';
import TenantSwitcher from '@/components/TenantSwitcher';
import { cookies } from 'next/headers';
import { VIEW_TENANT_NAME_COOKIE } from '@/lib/agency';
export default async function DashboardLayout({
children,
@@ -26,6 +29,8 @@ export default async function DashboardLayout({
const company = user?.user_metadata?.company || '4Ventures Central';
const email = user?.email || 'usuario@4ventures.es';
const isAgency = role === 'admin' || role === 'team';
const cookieStore = await cookies();
const viewName = cookieStore.get(VIEW_TENANT_NAME_COOKIE)?.value;
return (
<div className="flex min-h-screen bg-[#0B0F19]">
@@ -94,7 +99,7 @@ export default async function DashboardLayout({
className="flex items-center gap-3 px-3 py-2.5 mt-1 rounded-lg text-sm font-medium text-gray-300 hover:text-white hover:bg-gray-800/60 transition-all"
>
<Layers className="w-4 h-4 text-amber-400" />
Cartera Cross-Tenant
Portafolio Agencia
</Link>
</div>
)}
@@ -139,10 +144,11 @@ export default async function DashboardLayout({
<div className="flex-1 flex flex-col min-w-0">
<header className="h-16 border-b border-gray-800 bg-[#0D121F]/50 backdrop-blur px-8 flex items-center justify-between">
<div className="flex items-center gap-2 text-sm text-gray-400">
<span>Cliente / Portal:</span>
<span className="bg-brand-500/10 text-brand-400 font-semibold px-2.5 py-1 rounded-md border border-brand-500/20">
{company}
</span>
<span>{isAgency ? 'Contexto:' : 'Cliente / Portal:'}</span>
<TenantSwitcher
isAgency={isAgency}
initialName={viewName || company}
/>
</div>
<div className="flex items-center gap-4">
<div className="flex items-center gap-2 text-xs bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 px-2.5 py-1 rounded-full">

View File

@@ -1,5 +1,14 @@
import { redirect } from 'next/navigation';
import { createClient } from '@/lib/supabase/server';
import { isAgencyRole, userRole } from '@/lib/agency';
export default function DashboardIndex() {
export default async function DashboardIndex() {
const supabase = await createClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (user && isAgencyRole(userRole(user))) {
redirect('/dashboard/agencia');
}
redirect('/dashboard/kpis');
}