feat: agency control panel for per-client connections
Matrix view of Meta/Google/Drive/Clientify, follow/archive clients, and per-channel ON/OFF with account IDs in the client hub. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -9,6 +9,7 @@
|
|||||||
- Re-aplicar RLS `agent_runs` si hace falta: `sql/agent_runs_rls.sql` (idempotente)
|
- Re-aplicar RLS `agent_runs` si hace falta: `sql/agent_runs_rls.sql` (idempotente)
|
||||||
- Biblioteca de activos (archivos): `sql/asset_files.sql` + bucket privado `tenant-assets` (máx. 80 MB/archivo). UI: `/dashboard/activos`. Apply: `python3 scripts/dokploy_apply_asset_files.py`
|
- Biblioteca de activos (archivos): `sql/asset_files.sql` + bucket privado `tenant-assets` (máx. 80 MB/archivo). UI: `/dashboard/activos`. Apply: `python3 scripts/dokploy_apply_asset_files.py`
|
||||||
- Google Drive (agencia): `sql/google_drive.sql`. OAuth marketing@ → auto-match carpetas por nombre de tenant. Env Dokploy: `GOOGLE_OAUTH_CLIENT_ID`, `GOOGLE_OAUTH_CLIENT_SECRET`, `NEXT_PUBLIC_APP_URL`. Redirect: `https://app.4ventures.es/api/admin/drive/callback`. UI: Agencia → Conectar Drive.
|
- Google Drive (agencia): `sql/google_drive.sql`. OAuth marketing@ → auto-match carpetas por nombre de tenant. Env Dokploy: `GOOGLE_OAUTH_CLIENT_ID`, `GOOGLE_OAUTH_CLIENT_SECRET`, `NEXT_PUBLIC_APP_URL`. Redirect: `https://app.4ventures.es/api/admin/drive/callback`. UI: Agencia → Conectar Drive.
|
||||||
|
- Panel control clientes: `sql/agency_control.sql` (`agency_followed` + `integrations.enabled`). Matriz en Agencia + hub por cliente.
|
||||||
|
|
||||||
## Login
|
## Login
|
||||||
|
|
||||||
|
|||||||
91
scripts/dokploy_apply_agency_control.py
Normal file
91
scripts/dokploy_apply_agency_control.py
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Apply sql/agency_control.sql via Dokploy supabase-db terminal."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from playwright.sync_api import sync_playwright
|
||||||
|
|
||||||
|
ROOT = Path("/Users/4ventures/4ventures-client-portal")
|
||||||
|
BPS = Path("/Users/4ventures/Projects/bps-facturacion")
|
||||||
|
SQL = ROOT / "sql" / "agency_control.sql"
|
||||||
|
BASE = "https://dokploy.4ventures.es"
|
||||||
|
|
||||||
|
|
||||||
|
def env(key: str) -> str:
|
||||||
|
v = os.environ.get(key, "").strip()
|
||||||
|
if v:
|
||||||
|
return v
|
||||||
|
p = BPS / ".env"
|
||||||
|
if not p.is_file():
|
||||||
|
return ""
|
||||||
|
for line in p.read_text().splitlines():
|
||||||
|
if line.startswith(f"{key}="):
|
||||||
|
return line.split("=", 1)[1].strip().strip('"').strip("'")
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
email = env("DOKPLOY_EMAIL") or "marketing@4ventures.es"
|
||||||
|
password = env("DOKPLOY_PASSWORD")
|
||||||
|
b64 = base64.b64encode(SQL.read_text(encoding="utf-8").encode()).decode()
|
||||||
|
chunks = [b64[i : i + 180] for i in range(0, len(b64), 180)]
|
||||||
|
|
||||||
|
with sync_playwright() as p:
|
||||||
|
browser = p.chromium.launch(headless=True)
|
||||||
|
page = browser.new_page(viewport={"width": 1400, "height": 1000})
|
||||||
|
page.goto(BASE + "/", wait_until="domcontentloaded", timeout=90000)
|
||||||
|
page.wait_for_timeout(800)
|
||||||
|
if "/dashboard" not in page.url:
|
||||||
|
page.locator('input[type="email"], input[name="email"]').first.fill(email)
|
||||||
|
page.locator('input[type="password"]').first.fill(password)
|
||||||
|
page.locator('button[type="submit"]').first.click()
|
||||||
|
page.wait_for_url(re.compile(r"/dashboard"), timeout=90000)
|
||||||
|
print("login ok", flush=True)
|
||||||
|
page.goto(f"{BASE}/dashboard/docker", wait_until="domcontentloaded", timeout=120000)
|
||||||
|
page.wait_for_timeout(800)
|
||||||
|
page.locator("input[placeholder*='ilter' i], input[placeholder*='earch' i]").first.fill(
|
||||||
|
"supabase-db"
|
||||||
|
)
|
||||||
|
page.wait_for_timeout(1000)
|
||||||
|
page.keyboard.press("Escape")
|
||||||
|
page.wait_for_timeout(200)
|
||||||
|
page.get_by_role("button", name=re.compile(r"Open menu", re.I)).first.click()
|
||||||
|
page.wait_for_timeout(400)
|
||||||
|
page.get_by_text("Terminal", exact=True).click()
|
||||||
|
page.wait_for_timeout(1000)
|
||||||
|
if page.locator("button", has_text="Bash").count():
|
||||||
|
page.locator("button", has_text="Bash").first.click()
|
||||||
|
page.wait_for_timeout(2800)
|
||||||
|
if page.locator("textarea.xterm-helper-textarea").count():
|
||||||
|
page.locator("textarea.xterm-helper-textarea").first.click()
|
||||||
|
|
||||||
|
def run(cmd: str, wait: int = 800) -> None:
|
||||||
|
page.keyboard.type(cmd, delay=1)
|
||||||
|
page.keyboard.press("Enter")
|
||||||
|
page.wait_for_timeout(wait)
|
||||||
|
|
||||||
|
run("rm -f /tmp/ac.b64 /tmp/ac.sql; echo READY", 1200)
|
||||||
|
for i, ch in enumerate(chunks):
|
||||||
|
op = ">" if i == 0 else ">>"
|
||||||
|
run(f"printf '%s' '{ch}' {op} /tmp/ac.b64", 400)
|
||||||
|
run(
|
||||||
|
"base64 -d /tmp/ac.b64 > /tmp/ac.sql && "
|
||||||
|
"psql -U postgres -d postgres -v ON_ERROR_STOP=1 -f /tmp/ac.sql; echo EXIT:$?",
|
||||||
|
8000,
|
||||||
|
)
|
||||||
|
text = page.evaluate(
|
||||||
|
"() => (document.querySelector('.xterm-rows')||{}).innerText||''"
|
||||||
|
)
|
||||||
|
browser.close()
|
||||||
|
ok = "EXIT:0" in text
|
||||||
|
print("SQL_OK", ok, flush=True)
|
||||||
|
return 0 if ok else 6
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
16
sql/agency_control.sql
Normal file
16
sql/agency_control.sql
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
-- Agency control: follow/archive clients + enable/disable channels
|
||||||
|
-- Idempotent.
|
||||||
|
|
||||||
|
alter table public.tenants
|
||||||
|
add column if not exists agency_followed boolean not null default true;
|
||||||
|
|
||||||
|
alter table public.tenants
|
||||||
|
add column if not exists agency_notes text;
|
||||||
|
|
||||||
|
alter table public.integrations
|
||||||
|
add column if not exists enabled boolean not null default true;
|
||||||
|
|
||||||
|
comment on column public.tenants.agency_followed is
|
||||||
|
'Agency portfolio: false = archived / not actively managed in Centro de Mando';
|
||||||
|
comment on column public.integrations.enabled is
|
||||||
|
'Agency wants this channel for the client (false = deliberately off)';
|
||||||
@@ -111,32 +111,43 @@ export async function PATCH(req: NextRequest) {
|
|||||||
typeof body.label === 'string' ? body.label.trim() : undefined;
|
typeof body.label === 'string' ? body.label.trim() : undefined;
|
||||||
const errorMessage =
|
const errorMessage =
|
||||||
typeof body.errorMessage === 'string' ? body.errorMessage.trim() : undefined;
|
typeof body.errorMessage === 'string' ? body.errorMessage.trim() : undefined;
|
||||||
|
const enabled =
|
||||||
|
typeof body.enabled === 'boolean' ? body.enabled : undefined;
|
||||||
|
|
||||||
if (!tenantId || !provider || !status) {
|
if (!tenantId || !provider) {
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ error: 'tenantId, provider y status requeridos' },
|
{ error: 'tenantId y provider requeridos' },
|
||||||
{ status: 400 }
|
{ status: 400 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (
|
if (status && !['disconnected', 'pending', 'connected', 'error'].includes(status)) {
|
||||||
!['disconnected', 'pending', 'connected', 'error'].includes(status)
|
|
||||||
) {
|
|
||||||
return NextResponse.json({ error: 'status inválido' }, { status: 400 });
|
return NextResponse.json({ error: 'status inválido' }, { status: 400 });
|
||||||
}
|
}
|
||||||
|
|
||||||
const patch: Record<string, unknown> = {
|
const patch: Record<string, unknown> = {
|
||||||
status,
|
|
||||||
updated_at: new Date().toISOString(),
|
updated_at: new Date().toISOString(),
|
||||||
};
|
};
|
||||||
|
if (status) patch.status = status;
|
||||||
if (externalAccountId !== undefined) {
|
if (externalAccountId !== undefined) {
|
||||||
patch.external_account_id = externalAccountId || null;
|
patch.external_account_id = externalAccountId || null;
|
||||||
}
|
}
|
||||||
if (label !== undefined) patch.label = label || null;
|
if (label !== undefined) patch.label = label || null;
|
||||||
if (errorMessage !== undefined) patch.error_message = errorMessage || null;
|
if (errorMessage !== undefined) patch.error_message = errorMessage || null;
|
||||||
|
if (enabled !== undefined) patch.enabled = enabled;
|
||||||
if (status === 'connected') {
|
if (status === 'connected') {
|
||||||
patch.last_sync_at = new Date().toISOString();
|
patch.last_sync_at = new Date().toISOString();
|
||||||
patch.error_message = null;
|
patch.error_message = null;
|
||||||
}
|
}
|
||||||
|
if (status === 'disconnected') {
|
||||||
|
// keep external id for re-link unless cleared
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!status && enabled === undefined && externalAccountId === undefined) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'status, enabled o externalAccountId requeridos' },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const base = supabaseUrl();
|
const base = supabaseUrl();
|
||||||
const url = `${base}/rest/v1/integrations?tenant_id=eq.${encodeURIComponent(tenantId)}&provider=eq.${encodeURIComponent(provider)}`;
|
const url = `${base}/rest/v1/integrations?tenant_id=eq.${encodeURIComponent(tenantId)}&provider=eq.${encodeURIComponent(provider)}`;
|
||||||
@@ -162,6 +173,7 @@ export async function PATCH(req: NextRequest) {
|
|||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
tenant_id: tenantId,
|
tenant_id: tenantId,
|
||||||
provider,
|
provider,
|
||||||
|
status: status || 'disconnected',
|
||||||
...patch,
|
...patch,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -33,12 +33,15 @@ export async function GET() {
|
|||||||
|
|
||||||
const base = supabaseUrl();
|
const base = supabaseUrl();
|
||||||
const [tenantsRes, integRes, alertsRes] = await Promise.all([
|
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(
|
fetch(
|
||||||
`${base}/rest/v1/integrations?select=id,tenant_id,provider,status,label,external_account_id,last_sync_at,error_message`,
|
`${base}/rest/v1/tenants?select=id,name,slug,created_at,agency_followed,agency_notes&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,enabled,meta`,
|
||||||
{ headers, cache: 'no-store' }
|
{ headers, cache: 'no-store' }
|
||||||
),
|
),
|
||||||
fetch(
|
fetch(
|
||||||
@@ -47,17 +50,35 @@ export async function GET() {
|
|||||||
),
|
),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const tenants = tenantsRes.ok ? await tenantsRes.json() : [];
|
let tenants = tenantsRes.ok ? await tenantsRes.json() : [];
|
||||||
const integrations = integRes.ok ? await integRes.json() : [];
|
// Fallback if agency_followed column missing
|
||||||
|
if (!tenantsRes.ok) {
|
||||||
|
const again = await fetch(
|
||||||
|
`${base}/rest/v1/tenants?select=id,name,slug,created_at&order=name.asc`,
|
||||||
|
{ headers, cache: 'no-store' }
|
||||||
|
);
|
||||||
|
tenants = again.ok ? await again.json() : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
let integrations: unknown[] = [];
|
||||||
|
let integMissing = false;
|
||||||
|
if (integRes.ok) {
|
||||||
|
integrations = await integRes.json();
|
||||||
|
} else {
|
||||||
|
const msg = await integRes.text();
|
||||||
|
integMissing = msg.toLowerCase().includes('does not exist');
|
||||||
|
}
|
||||||
const alerts = alertsRes.ok ? await alertsRes.json() : [];
|
const alerts = alertsRes.ok ? await alertsRes.json() : [];
|
||||||
const integMissing =
|
|
||||||
!integRes.ok &&
|
|
||||||
(await integRes.text().catch(() => '')).toLowerCase().includes('does not exist');
|
|
||||||
|
|
||||||
type Integ = {
|
type Integ = {
|
||||||
tenant_id: string;
|
tenant_id: string;
|
||||||
provider: string;
|
provider: string;
|
||||||
status: string;
|
status: string;
|
||||||
|
label?: string | null;
|
||||||
|
external_account_id?: string | null;
|
||||||
|
enabled?: boolean;
|
||||||
|
error_message?: string | null;
|
||||||
|
meta?: Record<string, unknown> | null;
|
||||||
};
|
};
|
||||||
const byTenant = new Map<string, Integ[]>();
|
const byTenant = new Map<string, Integ[]>();
|
||||||
for (const row of integrations as Integ[]) {
|
for (const row of integrations as Integ[]) {
|
||||||
@@ -66,32 +87,47 @@ export async function GET() {
|
|||||||
byTenant.set(row.tenant_id, list);
|
byTenant.set(row.tenant_id, list);
|
||||||
}
|
}
|
||||||
|
|
||||||
const portfolio = (tenants as { id: string; name: string; slug: string; created_at: string }[]).map(
|
const portfolio = (
|
||||||
(t) => {
|
tenants as {
|
||||||
const rows = byTenant.get(t.id) || [];
|
id: string;
|
||||||
const connected = rows.filter((r) => r.status === 'connected').length;
|
name: string;
|
||||||
const errors = rows.filter((r) => r.status === 'error').length;
|
slug: string;
|
||||||
const pending = rows.filter((r) => r.status === 'pending').length;
|
created_at: string;
|
||||||
return {
|
agency_followed?: boolean;
|
||||||
...t,
|
agency_notes?: string | null;
|
||||||
integrations: rows,
|
}[]
|
||||||
stats: {
|
).map((t) => {
|
||||||
connected,
|
const rows = byTenant.get(t.id) || [];
|
||||||
errors,
|
const active = rows.filter((r) => r.enabled !== false);
|
||||||
pending,
|
const connected = active.filter((r) => r.status === 'connected').length;
|
||||||
totalProviders: INTEGRATION_PROVIDERS.length,
|
const errors = active.filter((r) => r.status === 'error').length;
|
||||||
health:
|
const pending = active.filter((r) => r.status === 'pending').length;
|
||||||
errors > 0
|
const byProvider: Record<string, Integ | undefined> = {};
|
||||||
? 'critical'
|
for (const p of INTEGRATION_PROVIDERS) {
|
||||||
: connected === 0
|
byProvider[p.id] = rows.find((r) => r.provider === p.id);
|
||||||
? 'empty'
|
|
||||||
: pending > 0
|
|
||||||
? 'warning'
|
|
||||||
: 'ok',
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
);
|
return {
|
||||||
|
...t,
|
||||||
|
agency_followed: t.agency_followed !== false,
|
||||||
|
integrations: rows,
|
||||||
|
byProvider,
|
||||||
|
stats: {
|
||||||
|
connected,
|
||||||
|
errors,
|
||||||
|
pending,
|
||||||
|
enabledChannels: active.length,
|
||||||
|
totalProviders: INTEGRATION_PROVIDERS.length,
|
||||||
|
health:
|
||||||
|
errors > 0
|
||||||
|
? 'critical'
|
||||||
|
: connected === 0
|
||||||
|
? 'empty'
|
||||||
|
: pending > 0
|
||||||
|
? 'warning'
|
||||||
|
: 'ok',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
return NextResponse.json({
|
return NextResponse.json({
|
||||||
portfolio,
|
portfolio,
|
||||||
|
|||||||
86
src/app/api/admin/tenants/route.ts
Normal file
86
src/app/api/admin/tenants/route.ts
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
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';
|
||||||
|
|
||||||
|
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: 'no service role' }, { status: 503 }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return { headers };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** PATCH — follow/unfollow client or set notes. */
|
||||||
|
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() : '';
|
||||||
|
if (!tenantId) {
|
||||||
|
return NextResponse.json({ error: 'tenantId requerido' }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const patch: Record<string, unknown> = {};
|
||||||
|
if (typeof body.followed === 'boolean') {
|
||||||
|
patch.agency_followed = body.followed;
|
||||||
|
}
|
||||||
|
if (typeof body.notes === 'string') {
|
||||||
|
patch.agency_notes = body.notes.trim() || null;
|
||||||
|
}
|
||||||
|
if (!Object.keys(patch).length) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: 'followed o notes requeridos' },
|
||||||
|
{ status: 400 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const r = await fetch(
|
||||||
|
`${supabaseUrl()}/rest/v1/tenants?id=eq.${encodeURIComponent(tenantId)}`,
|
||||||
|
{
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: {
|
||||||
|
...headers,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
Prefer: 'return=representation',
|
||||||
|
},
|
||||||
|
body: JSON.stringify(patch),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
if (!r.ok) {
|
||||||
|
const msg = await r.text();
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
error: msg.includes('agency_followed')
|
||||||
|
? 'Aplicar sql/agency_control.sql'
|
||||||
|
: msg.slice(0, 300),
|
||||||
|
},
|
||||||
|
{ status: 500 }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const rows = await r.json();
|
||||||
|
return NextResponse.json({ tenant: rows[0] || rows });
|
||||||
|
}
|
||||||
@@ -77,7 +77,8 @@ export default async function AgencyPage() {
|
|||||||
</div>
|
</div>
|
||||||
<h2 className="text-2xl font-bold tracking-tight text-white">Centro de Mando 4Ventures</h2>
|
<h2 className="text-2xl font-bold tracking-tight text-white">Centro de Mando 4Ventures</h2>
|
||||||
<p className="text-sm text-gray-400 mt-1">
|
<p className="text-sm text-gray-400 mt-1">
|
||||||
Portafolio multi-cliente · integraciones (Meta, MCC, GA4, GSC, GTM, CRM, email) · alertas · modo superadmin.
|
Portafolio multi-cliente · control de conexiones (Meta, Google, Drive,
|
||||||
|
Clientify…) · seguir/archivar clientes · modo superadmin.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import React, { useEffect, useState } from 'react';
|
import React, { useEffect, useMemo, useState } from 'react';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import DriveConnectPanel from '@/components/DriveConnectPanel';
|
import DriveConnectPanel from '@/components/DriveConnectPanel';
|
||||||
import {
|
import {
|
||||||
@@ -8,15 +8,29 @@ import {
|
|||||||
Bell,
|
Bell,
|
||||||
CheckCircle2,
|
CheckCircle2,
|
||||||
CircleDashed,
|
CircleDashed,
|
||||||
|
Eye,
|
||||||
|
EyeOff,
|
||||||
ExternalLink,
|
ExternalLink,
|
||||||
Plug,
|
Plug,
|
||||||
XCircle,
|
XCircle,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
|
|
||||||
|
type IntegCell = {
|
||||||
|
provider: string;
|
||||||
|
status: string;
|
||||||
|
enabled?: boolean;
|
||||||
|
external_account_id?: string | null;
|
||||||
|
label?: string | null;
|
||||||
|
meta?: { folder_name?: string } | null;
|
||||||
|
};
|
||||||
|
|
||||||
type PortfolioRow = {
|
type PortfolioRow = {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
slug: string;
|
slug: string;
|
||||||
|
agency_followed?: boolean;
|
||||||
|
agency_notes?: string | null;
|
||||||
|
byProvider?: Record<string, IntegCell | undefined>;
|
||||||
stats: {
|
stats: {
|
||||||
connected: number;
|
connected: number;
|
||||||
errors: number;
|
errors: number;
|
||||||
@@ -26,17 +40,34 @@ type PortfolioRow = {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type Provider = { id: string; label: string; group: string };
|
||||||
|
|
||||||
type AlertRow = {
|
type AlertRow = {
|
||||||
id: string;
|
id: string;
|
||||||
title: string;
|
title: string;
|
||||||
body?: string | null;
|
body?: string | null;
|
||||||
severity: string;
|
severity: string;
|
||||||
tenant_id?: string | null;
|
|
||||||
href?: string | null;
|
href?: string | null;
|
||||||
created_at: string;
|
created_at: string;
|
||||||
read_at?: string | null;
|
read_at?: string | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const MATRIX_PROVIDERS = [
|
||||||
|
'meta_ads',
|
||||||
|
'google_ads',
|
||||||
|
'ga4',
|
||||||
|
'clientify',
|
||||||
|
'google_drive',
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
const SHORT: Record<string, string> = {
|
||||||
|
meta_ads: 'Meta',
|
||||||
|
google_ads: 'GAds',
|
||||||
|
ga4: 'GA4',
|
||||||
|
clientify: 'CRM',
|
||||||
|
google_drive: 'Drive',
|
||||||
|
};
|
||||||
|
|
||||||
function healthBadge(h: string) {
|
function healthBadge(h: string) {
|
||||||
if (h === 'ok')
|
if (h === 'ok')
|
||||||
return (
|
return (
|
||||||
@@ -63,17 +94,39 @@ function healthBadge(h: string) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function cellTone(row?: IntegCell) {
|
||||||
|
if (!row || row.enabled === false)
|
||||||
|
return 'border-gray-800 text-gray-600 bg-transparent';
|
||||||
|
if (row.status === 'connected')
|
||||||
|
return 'border-emerald-500/40 text-emerald-400 bg-emerald-500/10';
|
||||||
|
if (row.status === 'error')
|
||||||
|
return 'border-red-500/40 text-red-400 bg-red-500/10';
|
||||||
|
if (row.status === 'pending')
|
||||||
|
return 'border-amber-500/40 text-amber-400 bg-amber-500/10';
|
||||||
|
return 'border-gray-700 text-gray-500';
|
||||||
|
}
|
||||||
|
|
||||||
|
function cellTitle(row?: IntegCell) {
|
||||||
|
if (!row || row.enabled === false) return 'Canal apagado';
|
||||||
|
const id = row.external_account_id || row.meta?.folder_name || row.label || '';
|
||||||
|
return `${row.status}${id ? ` · ${id}` : ''}`;
|
||||||
|
}
|
||||||
|
|
||||||
export default function AgencyPortfolioBoard() {
|
export default function AgencyPortfolioBoard() {
|
||||||
const [portfolio, setPortfolio] = useState<PortfolioRow[]>([]);
|
const [portfolio, setPortfolio] = useState<PortfolioRow[]>([]);
|
||||||
|
const [providers, setProviders] = useState<Provider[]>([]);
|
||||||
const [alerts, setAlerts] = useState<AlertRow[]>([]);
|
const [alerts, setAlerts] = useState<AlertRow[]>([]);
|
||||||
const [warning, setWarning] = useState<string | null>(null);
|
const [warning, setWarning] = useState<string | null>(null);
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [showArchived, setShowArchived] = useState(false);
|
||||||
|
const [busyId, setBusyId] = useState<string | null>(null);
|
||||||
|
|
||||||
async function load() {
|
async function load() {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
const res = await fetch('/api/admin/portfolio');
|
const res = await fetch('/api/admin/portfolio');
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
setPortfolio(data.portfolio || []);
|
setPortfolio(data.portfolio || []);
|
||||||
|
setProviders(data.providers || []);
|
||||||
setAlerts((data.alerts || []).filter((a: AlertRow) => !a.read_at));
|
setAlerts((data.alerts || []).filter((a: AlertRow) => !a.read_at));
|
||||||
setWarning(data.warning || null);
|
setWarning(data.warning || null);
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
@@ -83,6 +136,13 @@ export default function AgencyPortfolioBoard() {
|
|||||||
void load();
|
void load();
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
const visible = useMemo(() => {
|
||||||
|
if (showArchived) return portfolio;
|
||||||
|
return portfolio.filter((t) => t.agency_followed !== false);
|
||||||
|
}, [portfolio, showArchived]);
|
||||||
|
|
||||||
|
const archivedCount = portfolio.filter((t) => t.agency_followed === false).length;
|
||||||
|
|
||||||
async function enterTenant(id: string) {
|
async function enterTenant(id: string) {
|
||||||
await fetch('/api/admin/active-tenant', {
|
await fetch('/api/admin/active-tenant', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
@@ -92,6 +152,17 @@ export default function AgencyPortfolioBoard() {
|
|||||||
window.location.href = '/dashboard/kpis';
|
window.location.href = '/dashboard/kpis';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function setFollowed(id: string, followed: boolean) {
|
||||||
|
setBusyId(id);
|
||||||
|
await fetch('/api/admin/tenants', {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ tenantId: id, followed }),
|
||||||
|
});
|
||||||
|
await load();
|
||||||
|
setBusyId(null);
|
||||||
|
}
|
||||||
|
|
||||||
async function dismiss(id: string) {
|
async function dismiss(id: string) {
|
||||||
await fetch('/api/admin/alerts', {
|
await fetch('/api/admin/alerts', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
@@ -163,63 +234,145 @@ export default function AgencyPortfolioBoard() {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
<section className="space-y-3">
|
<section className="space-y-3">
|
||||||
<div className="flex items-center justify-between">
|
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
|
||||||
<h3 className="text-sm font-semibold text-white flex items-center gap-2">
|
<div>
|
||||||
<Plug className="w-4 h-4 text-brand-400" />
|
<h3 className="text-sm font-semibold text-white flex items-center gap-2">
|
||||||
Portafolio · estado de conexiones
|
<Plug className="w-4 h-4 text-brand-400" />
|
||||||
</h3>
|
Panel de control · clientes y conexiones
|
||||||
<p className="text-[11px] text-gray-500">
|
</h3>
|
||||||
Meta · Google Ads · GA4 · GSC · GTM · CRM · Email · Drive
|
<p className="text-[11px] text-gray-500 mt-0.5">
|
||||||
</p>
|
Cada cliente con su Meta, Google Ads, GA4, Clientify y Drive.
|
||||||
|
Activa/apaga canales en Integraciones.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setShowArchived((v) => !v)}
|
||||||
|
className="inline-flex items-center gap-1.5 text-[11px] px-2.5 py-1.5 rounded-lg border border-gray-700 text-gray-400 hover:text-white"
|
||||||
|
>
|
||||||
|
{showArchived ? (
|
||||||
|
<Eye className="w-3.5 h-3.5" />
|
||||||
|
) : (
|
||||||
|
<EyeOff className="w-3.5 h-3.5" />
|
||||||
|
)}
|
||||||
|
{showArchived
|
||||||
|
? 'Ocultar archivados'
|
||||||
|
: `Archivados (${archivedCount})`}
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{portfolio.length === 0 ? (
|
{/* Matrix header */}
|
||||||
|
<div className="hidden lg:grid grid-cols-[minmax(0,1.4fr)_repeat(5,minmax(0,0.55fr))_auto] gap-2 px-1 text-[10px] uppercase tracking-wider text-gray-600">
|
||||||
|
<span>Cliente</span>
|
||||||
|
{MATRIX_PROVIDERS.map((p) => (
|
||||||
|
<span key={p} className="text-center">
|
||||||
|
{SHORT[p]}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
<span className="text-right">Acciones</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{visible.length === 0 ? (
|
||||||
<p className="text-sm text-gray-500">
|
<p className="text-sm text-gray-500">
|
||||||
No hay clientes. Usa «Dar de Alta Cliente» abajo.
|
No hay clientes activos. Usa «Dar de Alta Cliente» abajo o muestra
|
||||||
|
archivados.
|
||||||
</p>
|
</p>
|
||||||
) : (
|
) : (
|
||||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
<div className="space-y-2">
|
||||||
{portfolio.map((t) => (
|
{visible.map((t) => {
|
||||||
<div
|
const archived = t.agency_followed === false;
|
||||||
key={t.id}
|
return (
|
||||||
className="rounded-xl border border-gray-800 bg-[#111827] p-4 flex flex-col gap-3"
|
<div
|
||||||
>
|
key={t.id}
|
||||||
<div className="flex items-start justify-between gap-2">
|
className={`rounded-xl border bg-[#111827] p-4 ${
|
||||||
<div>
|
archived ? 'border-gray-800/60 opacity-60' : 'border-gray-800'
|
||||||
<p className="text-sm font-semibold text-white">{t.name}</p>
|
}`}
|
||||||
<p className="text-[11px] text-gray-500">{t.slug}</p>
|
>
|
||||||
|
<div className="lg:grid lg:grid-cols-[minmax(0,1.4fr)_repeat(5,minmax(0,0.55fr))_auto] gap-2 items-center space-y-3 lg:space-y-0">
|
||||||
|
<div className="min-w-0">
|
||||||
|
<div className="flex items-center gap-2 flex-wrap">
|
||||||
|
<p className="text-sm font-semibold text-white truncate">
|
||||||
|
{t.name}
|
||||||
|
</p>
|
||||||
|
{healthBadge(t.stats.health)}
|
||||||
|
{archived && (
|
||||||
|
<span className="text-[10px] uppercase text-gray-500">
|
||||||
|
Archivado
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<p className="text-[11px] text-gray-500 truncate">
|
||||||
|
{t.slug} · {t.stats.connected}/
|
||||||
|
{t.stats.totalProviders} conectadas
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{MATRIX_PROVIDERS.map((pid) => {
|
||||||
|
const cell = t.byProvider?.[pid];
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={pid}
|
||||||
|
title={cellTitle(cell)}
|
||||||
|
className={`text-center text-[10px] font-semibold px-1.5 py-1.5 rounded-md border ${cellTone(cell)}`}
|
||||||
|
>
|
||||||
|
<span className="lg:hidden text-gray-500 mr-1">
|
||||||
|
{SHORT[pid]}
|
||||||
|
</span>
|
||||||
|
{cell?.enabled === false
|
||||||
|
? 'OFF'
|
||||||
|
: cell?.status === 'connected'
|
||||||
|
? 'ON'
|
||||||
|
: cell?.status === 'error'
|
||||||
|
? 'ERR'
|
||||||
|
: cell?.status === 'pending'
|
||||||
|
? '…'
|
||||||
|
: '—'}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
|
||||||
|
<div className="flex flex-wrap gap-2 lg:justify-end">
|
||||||
|
<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
|
||||||
|
</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"
|
||||||
|
>
|
||||||
|
Conexiones
|
||||||
|
<ExternalLink className="w-3 h-3" />
|
||||||
|
</Link>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={busyId === t.id}
|
||||||
|
onClick={() => void setFollowed(t.id, archived)}
|
||||||
|
className="text-xs px-3 py-1.5 rounded-lg border border-gray-700 text-gray-400 hover:text-white"
|
||||||
|
title={
|
||||||
|
archived
|
||||||
|
? 'Volver a seguir en el portafolio'
|
||||||
|
: 'Archivar: deja de mostrarlo como activo'
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{archived ? 'Seguir' : 'Archivar'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{healthBadge(t.stats.health)}
|
|
||||||
</div>
|
</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>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{providers.length > 0 && (
|
||||||
|
<p className="text-[10px] text-gray-600">
|
||||||
|
Canales disponibles:{' '}
|
||||||
|
{providers.map((p) => p.label).join(' · ')}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import React, { useEffect, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import { ArrowLeft, Loader2 } from 'lucide-react';
|
import { ArrowLeft, Loader2, Power } from 'lucide-react';
|
||||||
|
|
||||||
type Integ = {
|
type Integ = {
|
||||||
id?: string;
|
id?: string;
|
||||||
@@ -12,16 +12,23 @@ type Integ = {
|
|||||||
external_account_id?: string | null;
|
external_account_id?: string | null;
|
||||||
error_message?: string | null;
|
error_message?: string | null;
|
||||||
last_sync_at?: string | null;
|
last_sync_at?: string | null;
|
||||||
|
enabled?: boolean;
|
||||||
|
meta?: { folder_name?: string; match_score?: number } | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
type Provider = { id: string; label: string; group: string };
|
type Provider = { id: string; label: string; group: string };
|
||||||
|
|
||||||
const STATUS_OPTS = [
|
const PLACEHOLDERS: Record<string, string> = {
|
||||||
{ value: 'disconnected', label: 'Desconectado' },
|
meta_ads: 'act_… (Ad Account ID)',
|
||||||
{ value: 'pending', label: 'Pendiente' },
|
google_ads: 'Customer ID MCC / cuenta',
|
||||||
{ value: 'connected', label: 'Conectado' },
|
ga4: 'G-… o Property ID',
|
||||||
{ value: 'error', label: 'Error' },
|
search_console: 'sc-domain:ejemplo.com',
|
||||||
] as const;
|
tag_manager: 'GTM-…',
|
||||||
|
clientify: 'ID / workspace Clientify',
|
||||||
|
klaviyo: 'Account / list ID',
|
||||||
|
mailchimp: 'Audience ID',
|
||||||
|
google_drive: 'Folder ID (auto-match o pegar)',
|
||||||
|
};
|
||||||
|
|
||||||
export default function ClientIntegrationsPanel({
|
export default function ClientIntegrationsPanel({
|
||||||
tenantId,
|
tenantId,
|
||||||
@@ -35,6 +42,8 @@ export default function ClientIntegrationsPanel({
|
|||||||
const [warning, setWarning] = useState<string | null>(null);
|
const [warning, setWarning] = useState<string | null>(null);
|
||||||
const [saving, setSaving] = useState<string | null>(null);
|
const [saving, setSaving] = useState<string | null>(null);
|
||||||
const [accountDraft, setAccountDraft] = useState<Record<string, string>>({});
|
const [accountDraft, setAccountDraft] = useState<Record<string, string>>({});
|
||||||
|
const [followed, setFollowed] = useState(true);
|
||||||
|
const [followBusy, setFollowBusy] = useState(false);
|
||||||
|
|
||||||
async function load() {
|
async function load() {
|
||||||
const res = await fetch(
|
const res = await fetch(
|
||||||
@@ -53,24 +62,43 @@ export default function ClientIntegrationsPanel({
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void load();
|
void load();
|
||||||
|
fetch('/api/admin/portfolio')
|
||||||
|
.then((r) => r.json())
|
||||||
|
.then((d) => {
|
||||||
|
const row = (d.portfolio || []).find(
|
||||||
|
(t: { id: string }) => t.id === tenantId
|
||||||
|
);
|
||||||
|
if (row) setFollowed(row.agency_followed !== false);
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
}, [tenantId]);
|
}, [tenantId]);
|
||||||
|
|
||||||
async function save(provider: string, status: string) {
|
async function patch(
|
||||||
|
provider: string,
|
||||||
|
body: Record<string, unknown>
|
||||||
|
) {
|
||||||
setSaving(provider);
|
setSaving(provider);
|
||||||
await fetch('/api/admin/integrations', {
|
await fetch('/api/admin/integrations', {
|
||||||
method: 'PATCH',
|
method: 'PATCH',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({ tenantId, provider, ...body }),
|
||||||
tenantId,
|
|
||||||
provider,
|
|
||||||
status,
|
|
||||||
externalAccountId: accountDraft[provider] || '',
|
|
||||||
}),
|
|
||||||
});
|
});
|
||||||
await load();
|
await load();
|
||||||
setSaving(null);
|
setSaving(null);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function toggleFollow() {
|
||||||
|
setFollowBusy(true);
|
||||||
|
const next = !followed;
|
||||||
|
await fetch('/api/admin/tenants', {
|
||||||
|
method: 'PATCH',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ tenantId, followed: next }),
|
||||||
|
});
|
||||||
|
setFollowed(next);
|
||||||
|
setFollowBusy(false);
|
||||||
|
}
|
||||||
|
|
||||||
const byProvider = new Map(integrations.map((i) => [i.provider, i]));
|
const byProvider = new Map(integrations.map((i) => [i.provider, i]));
|
||||||
|
|
||||||
const groups = [
|
const groups = [
|
||||||
@@ -83,22 +111,41 @@ export default function ClientIntegrationsPanel({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex flex-col sm:flex-row sm:items-start justify-between gap-3">
|
||||||
<Link
|
<div className="flex items-center gap-3">
|
||||||
href="/dashboard/agencia"
|
<Link
|
||||||
className="text-gray-400 hover:text-white"
|
href="/dashboard/agencia"
|
||||||
>
|
className="text-gray-400 hover:text-white"
|
||||||
<ArrowLeft className="w-4 h-4" />
|
>
|
||||||
</Link>
|
<ArrowLeft className="w-4 h-4" />
|
||||||
<div>
|
</Link>
|
||||||
<h2 className="text-2xl font-bold text-white tracking-tight">
|
<div>
|
||||||
{tenantName}
|
<h2 className="text-2xl font-bold text-white tracking-tight">
|
||||||
</h2>
|
{tenantName}
|
||||||
<p className="text-sm text-gray-400 mt-0.5">
|
</h2>
|
||||||
Integraciones del cliente · marca estado y account id (OAuth live en
|
<p className="text-sm text-gray-400 mt-0.5">
|
||||||
siguiente fase)
|
Hub de conexiones · asocia cuentas y decide qué entra a la
|
||||||
</p>
|
plataforma
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={followBusy}
|
||||||
|
onClick={() => void toggleFollow()}
|
||||||
|
className={`inline-flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-lg border ${
|
||||||
|
followed
|
||||||
|
? 'border-emerald-500/40 text-emerald-400'
|
||||||
|
: 'border-gray-700 text-gray-400'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{followBusy ? (
|
||||||
|
<Loader2 className="w-3.5 h-3.5 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<Power className="w-3.5 h-3.5" />
|
||||||
|
)}
|
||||||
|
{followed ? 'Cliente activo en portafolio' : 'Archivado'}
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{warning && (
|
{warning && (
|
||||||
@@ -119,16 +166,30 @@ export default function ClientIntegrationsPanel({
|
|||||||
{list.map((p) => {
|
{list.map((p) => {
|
||||||
const row = byProvider.get(p.id);
|
const row = byProvider.get(p.id);
|
||||||
const status = row?.status || 'disconnected';
|
const status = row?.status || 'disconnected';
|
||||||
|
const enabled = row?.enabled !== false;
|
||||||
|
const folderHint =
|
||||||
|
p.id === 'google_drive'
|
||||||
|
? row?.meta?.folder_name || row?.label
|
||||||
|
: null;
|
||||||
return (
|
return (
|
||||||
<li
|
<li
|
||||||
key={p.id}
|
key={p.id}
|
||||||
className="rounded-xl border border-gray-800 bg-[#111827] p-4 space-y-3"
|
className={`rounded-xl border p-4 space-y-3 ${
|
||||||
|
enabled
|
||||||
|
? 'border-gray-800 bg-[#111827]'
|
||||||
|
: 'border-gray-800/50 bg-[#0d121c] opacity-70'
|
||||||
|
}`}
|
||||||
>
|
>
|
||||||
<div className="flex items-center justify-between gap-3">
|
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
|
||||||
<div>
|
<div>
|
||||||
<p className="text-sm font-medium text-white">
|
<p className="text-sm font-medium text-white">
|
||||||
{p.label}
|
{p.label}
|
||||||
</p>
|
</p>
|
||||||
|
{folderHint && (
|
||||||
|
<p className="text-[11px] text-brand-400 mt-0.5">
|
||||||
|
Carpeta: {folderHint}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
{row?.last_sync_at && (
|
{row?.last_sync_at && (
|
||||||
<p className="text-[10px] text-gray-500">
|
<p className="text-[10px] text-gray-500">
|
||||||
Último sync{' '}
|
Último sync{' '}
|
||||||
@@ -141,24 +202,50 @@ export default function ClientIntegrationsPanel({
|
|||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
<select
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
className="text-xs rounded-lg bg-gray-900 border border-gray-700 text-gray-200 px-2 py-1.5"
|
<button
|
||||||
value={status}
|
type="button"
|
||||||
disabled={saving === p.id}
|
disabled={saving === p.id}
|
||||||
onChange={(e) => save(p.id, e.target.value)}
|
onClick={() =>
|
||||||
>
|
void patch(p.id, { enabled: !enabled })
|
||||||
{STATUS_OPTS.map((o) => (
|
}
|
||||||
<option key={o.value} value={o.value}>
|
className={`text-[11px] px-2.5 py-1 rounded-md border ${
|
||||||
{o.label}
|
enabled
|
||||||
</option>
|
? 'border-emerald-500/40 text-emerald-400'
|
||||||
))}
|
: 'border-gray-700 text-gray-500'
|
||||||
</select>
|
}`}
|
||||||
|
title="Si está OFF, no cuenta en salud ni se usa"
|
||||||
|
>
|
||||||
|
{enabled ? 'Canal ON' : 'Canal OFF'}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={saving === p.id || !enabled}
|
||||||
|
onClick={() =>
|
||||||
|
void patch(p.id, {
|
||||||
|
status:
|
||||||
|
status === 'connected'
|
||||||
|
? 'disconnected'
|
||||||
|
: 'connected',
|
||||||
|
externalAccountId: accountDraft[p.id] || '',
|
||||||
|
})
|
||||||
|
}
|
||||||
|
className={`text-[11px] px-2.5 py-1 rounded-md border ${
|
||||||
|
status === 'connected'
|
||||||
|
? 'border-brand-500/40 text-brand-400'
|
||||||
|
: 'border-gray-700 text-gray-400'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{status === 'connected' ? 'Desconectar' : 'Conectar'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex gap-2 items-center">
|
<div className="flex gap-2 items-center">
|
||||||
<input
|
<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"
|
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…)"
|
placeholder={PLACEHOLDERS[p.id] || 'Account ID'}
|
||||||
value={accountDraft[p.id] || ''}
|
value={accountDraft[p.id] || ''}
|
||||||
|
disabled={!enabled}
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
setAccountDraft((d) => ({
|
setAccountDraft((d) => ({
|
||||||
...d,
|
...d,
|
||||||
@@ -168,17 +255,29 @@ export default function ClientIntegrationsPanel({
|
|||||||
/>
|
/>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
disabled={saving === p.id}
|
disabled={saving === p.id || !enabled}
|
||||||
onClick={() => save(p.id, status)}
|
onClick={() =>
|
||||||
|
void patch(p.id, {
|
||||||
|
status: status === 'disconnected' ? 'pending' : status,
|
||||||
|
externalAccountId: accountDraft[p.id] || '',
|
||||||
|
})
|
||||||
|
}
|
||||||
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"
|
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 ? (
|
{saving === p.id ? (
|
||||||
<Loader2 className="w-3 h-3 animate-spin" />
|
<Loader2 className="w-3 h-3 animate-spin" />
|
||||||
) : (
|
) : (
|
||||||
'Guardar'
|
'Guardar ID'
|
||||||
)}
|
)}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
{p.id === 'google_drive' && (
|
||||||
|
<p className="text-[10px] text-gray-500">
|
||||||
|
Preferible: Agencia → Conectar Drive → Re-emparejar
|
||||||
|
(asigna carpeta por nombre). Aquí puedes pegar un Folder
|
||||||
|
ID manual.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
</li>
|
</li>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
|||||||
@@ -31,7 +31,9 @@ export default function TenantSwitcher({
|
|||||||
fetch('/api/admin/portfolio')
|
fetch('/api/admin/portfolio')
|
||||||
.then((r) => r.json())
|
.then((r) => r.json())
|
||||||
.then((d) => {
|
.then((d) => {
|
||||||
const list = (d.portfolio || []).map(
|
const list = (d.portfolio || [])
|
||||||
|
.filter((t: { agency_followed?: boolean }) => t.agency_followed !== false)
|
||||||
|
.map(
|
||||||
(t: { id: string; name: string; slug: string }) => ({
|
(t: { id: string; name: string; slug: string }) => ({
|
||||||
id: t.id,
|
id: t.id,
|
||||||
name: t.name,
|
name: t.name,
|
||||||
|
|||||||
Reference in New Issue
Block a user