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:
223
src/components/AgencyPortfolioBoard.tsx
Normal file
223
src/components/AgencyPortfolioBoard.tsx
Normal file
@@ -0,0 +1,223 @@
|
||||
'use client';
|
||||
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import Link from 'next/link';
|
||||
import {
|
||||
AlertTriangle,
|
||||
Bell,
|
||||
CheckCircle2,
|
||||
CircleDashed,
|
||||
ExternalLink,
|
||||
Plug,
|
||||
XCircle,
|
||||
} from 'lucide-react';
|
||||
|
||||
type PortfolioRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
stats: {
|
||||
connected: number;
|
||||
errors: number;
|
||||
pending: number;
|
||||
totalProviders: number;
|
||||
health: string;
|
||||
};
|
||||
};
|
||||
|
||||
type AlertRow = {
|
||||
id: string;
|
||||
title: string;
|
||||
body?: string | null;
|
||||
severity: string;
|
||||
tenant_id?: string | null;
|
||||
href?: string | null;
|
||||
created_at: string;
|
||||
read_at?: string | null;
|
||||
};
|
||||
|
||||
function healthBadge(h: string) {
|
||||
if (h === 'ok')
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 text-[10px] uppercase tracking-wider text-emerald-400">
|
||||
<CheckCircle2 className="w-3 h-3" /> OK
|
||||
</span>
|
||||
);
|
||||
if (h === 'critical')
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 text-[10px] uppercase tracking-wider text-red-400">
|
||||
<XCircle className="w-3 h-3" /> Error
|
||||
</span>
|
||||
);
|
||||
if (h === 'warning')
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 text-[10px] uppercase tracking-wider text-amber-400">
|
||||
<AlertTriangle className="w-3 h-3" /> Pendiente
|
||||
</span>
|
||||
);
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1 text-[10px] uppercase tracking-wider text-gray-500">
|
||||
<CircleDashed className="w-3 h-3" /> Sin conectar
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export default function AgencyPortfolioBoard() {
|
||||
const [portfolio, setPortfolio] = useState<PortfolioRow[]>([]);
|
||||
const [alerts, setAlerts] = useState<AlertRow[]>([]);
|
||||
const [warning, setWarning] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
async function load() {
|
||||
setLoading(true);
|
||||
const res = await fetch('/api/admin/portfolio');
|
||||
const data = await res.json();
|
||||
setPortfolio(data.portfolio || []);
|
||||
setAlerts((data.alerts || []).filter((a: AlertRow) => !a.read_at));
|
||||
setWarning(data.warning || null);
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, []);
|
||||
|
||||
async function enterTenant(id: string) {
|
||||
await fetch('/api/admin/active-tenant', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ tenantId: id }),
|
||||
});
|
||||
window.location.href = '/dashboard/kpis';
|
||||
}
|
||||
|
||||
async function dismiss(id: string) {
|
||||
await fetch('/api/admin/alerts', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ id, markRead: true }),
|
||||
});
|
||||
setAlerts((prev) => prev.filter((a) => a.id !== id));
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return <p className="text-sm text-gray-500">Cargando portafolio…</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{warning && (
|
||||
<p className="text-xs text-amber-400/90 border border-amber-500/20 rounded-lg px-3 py-2">
|
||||
{warning}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{alerts.length > 0 && (
|
||||
<section className="space-y-2">
|
||||
<div className="flex items-center gap-2 text-sm font-semibold text-white">
|
||||
<Bell className="w-4 h-4 text-amber-400" />
|
||||
Alertas ({alerts.length})
|
||||
</div>
|
||||
<ul className="space-y-2">
|
||||
{alerts.map((a) => (
|
||||
<li
|
||||
key={a.id}
|
||||
className={`flex items-start justify-between gap-3 rounded-lg border px-4 py-3 ${
|
||||
a.severity === 'critical'
|
||||
? 'border-red-500/30 bg-red-500/5'
|
||||
: a.severity === 'warning'
|
||||
? 'border-amber-500/30 bg-amber-500/5'
|
||||
: 'border-gray-800 bg-[#111827]'
|
||||
}`}
|
||||
>
|
||||
<div>
|
||||
<p className="text-sm text-white font-medium">{a.title}</p>
|
||||
{a.body && (
|
||||
<p className="text-xs text-gray-400 mt-0.5">{a.body}</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
{a.href && (
|
||||
<Link
|
||||
href={a.href}
|
||||
className="text-xs text-brand-400 hover:underline"
|
||||
>
|
||||
Ver
|
||||
</Link>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => dismiss(a.id)}
|
||||
className="text-[10px] uppercase tracking-wider text-gray-500 hover:text-gray-300"
|
||||
>
|
||||
OK
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
)}
|
||||
|
||||
<section className="space-y-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="text-sm font-semibold text-white flex items-center gap-2">
|
||||
<Plug className="w-4 h-4 text-brand-400" />
|
||||
Portafolio · estado de conexiones
|
||||
</h3>
|
||||
<p className="text-[11px] text-gray-500">
|
||||
Meta · Google Ads · GA4 · GSC · GTM · CRM · Email
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{portfolio.length === 0 ? (
|
||||
<p className="text-sm text-gray-500">
|
||||
No hay clientes. Usa «Dar de Alta Cliente» abajo.
|
||||
</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
{portfolio.map((t) => (
|
||||
<div
|
||||
key={t.id}
|
||||
className="rounded-xl border border-gray-800 bg-[#111827] p-4 flex flex-col gap-3"
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div>
|
||||
<p className="text-sm font-semibold text-white">{t.name}</p>
|
||||
<p className="text-[11px] text-gray-500">{t.slug}</p>
|
||||
</div>
|
||||
{healthBadge(t.stats.health)}
|
||||
</div>
|
||||
<p className="text-xs text-gray-400">
|
||||
{t.stats.connected}/{t.stats.totalProviders} conectadas
|
||||
{t.stats.errors > 0 && (
|
||||
<span className="text-red-400">
|
||||
{' '}
|
||||
· {t.stats.errors} error
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2 mt-auto">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => enterTenant(t.id)}
|
||||
className="text-xs font-medium px-3 py-1.5 rounded-lg bg-brand-500/90 hover:bg-brand-500 text-white"
|
||||
>
|
||||
Entrar (superadmin)
|
||||
</button>
|
||||
<Link
|
||||
href={`/dashboard/agencia/cliente/${t.id}`}
|
||||
className="inline-flex items-center gap-1 text-xs font-medium px-3 py-1.5 rounded-lg border border-gray-700 text-gray-300 hover:border-gray-500 hover:text-white"
|
||||
>
|
||||
Integraciones
|
||||
<ExternalLink className="w-3 h-3" />
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
190
src/components/ClientIntegrationsPanel.tsx
Normal file
190
src/components/ClientIntegrationsPanel.tsx
Normal file
@@ -0,0 +1,190 @@
|
||||
'use client';
|
||||
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { ArrowLeft, Loader2 } from 'lucide-react';
|
||||
|
||||
type Integ = {
|
||||
id?: string;
|
||||
provider: string;
|
||||
status: string;
|
||||
label?: string | null;
|
||||
external_account_id?: string | null;
|
||||
error_message?: string | null;
|
||||
last_sync_at?: string | null;
|
||||
};
|
||||
|
||||
type Provider = { id: string; label: string; group: string };
|
||||
|
||||
const STATUS_OPTS = [
|
||||
{ value: 'disconnected', label: 'Desconectado' },
|
||||
{ value: 'pending', label: 'Pendiente' },
|
||||
{ value: 'connected', label: 'Conectado' },
|
||||
{ value: 'error', label: 'Error' },
|
||||
] as const;
|
||||
|
||||
export default function ClientIntegrationsPanel({
|
||||
tenantId,
|
||||
tenantName,
|
||||
}: {
|
||||
tenantId: string;
|
||||
tenantName: string;
|
||||
}) {
|
||||
const [integrations, setIntegrations] = useState<Integ[]>([]);
|
||||
const [providers, setProviders] = useState<Provider[]>([]);
|
||||
const [warning, setWarning] = useState<string | null>(null);
|
||||
const [saving, setSaving] = useState<string | null>(null);
|
||||
const [accountDraft, setAccountDraft] = useState<Record<string, string>>({});
|
||||
|
||||
async function load() {
|
||||
const res = await fetch(
|
||||
`/api/admin/integrations?tenantId=${encodeURIComponent(tenantId)}`
|
||||
);
|
||||
const data = await res.json();
|
||||
setIntegrations(data.integrations || []);
|
||||
setProviders(data.providers || []);
|
||||
setWarning(data.warning || null);
|
||||
const drafts: Record<string, string> = {};
|
||||
for (const i of data.integrations || []) {
|
||||
drafts[i.provider] = i.external_account_id || '';
|
||||
}
|
||||
setAccountDraft(drafts);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
void load();
|
||||
}, [tenantId]);
|
||||
|
||||
async function save(provider: string, status: string) {
|
||||
setSaving(provider);
|
||||
await fetch('/api/admin/integrations', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
tenantId,
|
||||
provider,
|
||||
status,
|
||||
externalAccountId: accountDraft[provider] || '',
|
||||
}),
|
||||
});
|
||||
await load();
|
||||
setSaving(null);
|
||||
}
|
||||
|
||||
const byProvider = new Map(integrations.map((i) => [i.provider, i]));
|
||||
|
||||
const groups = [
|
||||
{ id: 'paid', title: 'Paid media' },
|
||||
{ id: 'analytics', title: 'Analítica y medición' },
|
||||
{ id: 'crm', title: 'CRM' },
|
||||
{ id: 'email', title: 'Email / lifecycle' },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center gap-3">
|
||||
<Link
|
||||
href="/dashboard/agencia"
|
||||
className="text-gray-400 hover:text-white"
|
||||
>
|
||||
<ArrowLeft className="w-4 h-4" />
|
||||
</Link>
|
||||
<div>
|
||||
<h2 className="text-2xl font-bold text-white tracking-tight">
|
||||
{tenantName}
|
||||
</h2>
|
||||
<p className="text-sm text-gray-400 mt-0.5">
|
||||
Integraciones del cliente · marca estado y account id (OAuth live en
|
||||
siguiente fase)
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{warning && (
|
||||
<p className="text-xs text-amber-400 border border-amber-500/20 rounded-lg px-3 py-2">
|
||||
{warning}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{groups.map((g) => {
|
||||
const list = providers.filter((p) => p.group === g.id);
|
||||
if (!list.length) return null;
|
||||
return (
|
||||
<section key={g.id} className="space-y-2">
|
||||
<h3 className="text-xs font-bold uppercase tracking-wider text-gray-500">
|
||||
{g.title}
|
||||
</h3>
|
||||
<ul className="space-y-2">
|
||||
{list.map((p) => {
|
||||
const row = byProvider.get(p.id);
|
||||
const status = row?.status || 'disconnected';
|
||||
return (
|
||||
<li
|
||||
key={p.id}
|
||||
className="rounded-xl border border-gray-800 bg-[#111827] p-4 space-y-3"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<p className="text-sm font-medium text-white">
|
||||
{p.label}
|
||||
</p>
|
||||
{row?.last_sync_at && (
|
||||
<p className="text-[10px] text-gray-500">
|
||||
Último sync{' '}
|
||||
{new Date(row.last_sync_at).toLocaleString('es-ES')}
|
||||
</p>
|
||||
)}
|
||||
{row?.error_message && (
|
||||
<p className="text-[11px] text-red-400 mt-1">
|
||||
{row.error_message}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<select
|
||||
className="text-xs rounded-lg bg-gray-900 border border-gray-700 text-gray-200 px-2 py-1.5"
|
||||
value={status}
|
||||
disabled={saving === p.id}
|
||||
onChange={(e) => save(p.id, e.target.value)}
|
||||
>
|
||||
{STATUS_OPTS.map((o) => (
|
||||
<option key={o.value} value={o.value}>
|
||||
{o.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div className="flex gap-2 items-center">
|
||||
<input
|
||||
className="flex-1 text-xs rounded-lg bg-gray-900 border border-gray-700 px-3 py-2 text-white placeholder:text-gray-600"
|
||||
placeholder="Account / Property ID (act_…, G-…, UA…)"
|
||||
value={accountDraft[p.id] || ''}
|
||||
onChange={(e) =>
|
||||
setAccountDraft((d) => ({
|
||||
...d,
|
||||
[p.id]: e.target.value,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
disabled={saving === p.id}
|
||||
onClick={() => save(p.id, status)}
|
||||
className="text-xs px-3 py-2 rounded-lg border border-gray-700 text-gray-300 hover:text-white hover:border-gray-500 inline-flex items-center gap-1"
|
||||
>
|
||||
{saving === p.id ? (
|
||||
<Loader2 className="w-3 h-3 animate-spin" />
|
||||
) : (
|
||||
'Guardar'
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
115
src/components/TenantSwitcher.tsx
Normal file
115
src/components/TenantSwitcher.tsx
Normal file
@@ -0,0 +1,115 @@
|
||||
'use client';
|
||||
|
||||
import React, { useEffect, useState, useTransition } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { ChevronDown, Eye, Building2 } from 'lucide-react';
|
||||
|
||||
type TenantOpt = { id: string; name: string; slug: string };
|
||||
|
||||
export default function TenantSwitcher({
|
||||
initialName,
|
||||
isAgency,
|
||||
}: {
|
||||
initialName: string;
|
||||
isAgency: boolean;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [tenants, setTenants] = useState<TenantOpt[]>([]);
|
||||
const [activeName, setActiveName] = useState(initialName);
|
||||
const [activeId, setActiveId] = useState<string | null>(null);
|
||||
const [pending, startTransition] = useTransition();
|
||||
|
||||
useEffect(() => {
|
||||
if (!isAgency) return;
|
||||
// read cookies
|
||||
const match = document.cookie.match(/(?:^|; )4v_view_tenant_name=([^;]*)/);
|
||||
const idMatch = document.cookie.match(/(?:^|; )4v_view_tenant_id=([^;]*)/);
|
||||
if (match?.[1]) setActiveName(decodeURIComponent(match[1]));
|
||||
if (idMatch?.[1]) setActiveId(decodeURIComponent(idMatch[1]));
|
||||
|
||||
fetch('/api/admin/portfolio')
|
||||
.then((r) => r.json())
|
||||
.then((d) => {
|
||||
const list = (d.portfolio || []).map(
|
||||
(t: { id: string; name: string; slug: string }) => ({
|
||||
id: t.id,
|
||||
name: t.name,
|
||||
slug: t.slug,
|
||||
})
|
||||
);
|
||||
setTenants(list);
|
||||
})
|
||||
.catch(() => {});
|
||||
}, [isAgency]);
|
||||
|
||||
if (!isAgency) {
|
||||
return (
|
||||
<span className="bg-brand-500/10 text-brand-400 font-semibold px-2.5 py-1 rounded-md border border-brand-500/20">
|
||||
{initialName}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
async function select(tenant: TenantOpt | null) {
|
||||
setOpen(false);
|
||||
await fetch('/api/admin/active-tenant', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ tenantId: tenant?.id ?? null }),
|
||||
});
|
||||
setActiveId(tenant?.id ?? null);
|
||||
setActiveName(tenant?.name ?? 'Vista global agencia');
|
||||
startTransition(() => router.refresh());
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
className="inline-flex items-center gap-2 bg-brand-500/10 text-brand-400 font-semibold px-2.5 py-1 rounded-md border border-brand-500/20 hover:bg-brand-500/20 transition-colors"
|
||||
>
|
||||
<Eye className="w-3.5 h-3.5" />
|
||||
<span className="max-w-[200px] truncate">
|
||||
{activeId ? activeName : 'Vista global agencia'}
|
||||
</span>
|
||||
<ChevronDown className="w-3.5 h-3.5 opacity-70" />
|
||||
</button>
|
||||
{open && (
|
||||
<div className="absolute left-0 top-full mt-2 z-50 w-72 rounded-xl border border-gray-700 bg-[#111827] shadow-xl py-1 max-h-80 overflow-y-auto">
|
||||
<button
|
||||
type="button"
|
||||
disabled={pending}
|
||||
onClick={() => select(null)}
|
||||
className="w-full text-left px-3 py-2 text-sm text-gray-300 hover:bg-gray-800 flex items-center gap-2"
|
||||
>
|
||||
<Building2 className="w-3.5 h-3.5 text-amber-400" />
|
||||
Vista global agencia
|
||||
</button>
|
||||
<div className="border-t border-gray-800 my-1" />
|
||||
{tenants.length === 0 ? (
|
||||
<p className="px-3 py-2 text-xs text-gray-500">
|
||||
Sin tenants · da de alta en Agencia OS
|
||||
</p>
|
||||
) : (
|
||||
tenants.map((t) => (
|
||||
<button
|
||||
key={t.id}
|
||||
type="button"
|
||||
disabled={pending}
|
||||
onClick={() => select(t)}
|
||||
className={`w-full text-left px-3 py-2 text-sm hover:bg-gray-800 ${
|
||||
activeId === t.id ? 'text-brand-400' : 'text-gray-200'
|
||||
}`}
|
||||
>
|
||||
<span className="font-medium">{t.name}</span>
|
||||
<span className="block text-[10px] text-gray-500">{t.slug}</span>
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user