feat(shell): selector de cliente en sidebar, layout fijo, cabecera contextual y reordenacion de menu

This commit is contained in:
Marcos Fargas
2026-10-17 19:36:53 +02:00
parent ae52f2f50a
commit 80bfa3035f
5 changed files with 393 additions and 125 deletions

2
.gitignore vendored
View File

@@ -62,3 +62,5 @@ coverage/
.turbo/ .turbo/
.ops/gitea-deploy/ .ops/gitea-deploy/
design-backup/
login_*.png

View File

@@ -104,6 +104,7 @@ export default async function DashboardLayout({
role={role} role={role}
isAgency={isAgency} isAgency={isAgency}
viewName={viewName} viewName={viewName}
activeTenantId={isAgency ? viewId : null}
enabledModules={enabledModules} enabledModules={enabledModules}
clientLogoUrl={!isAgency ? clientLogoUrl : null} clientLogoUrl={!isAgency ? clientLogoUrl : null}
brandLabel={brandLabel} brandLabel={brandLabel}

View File

@@ -1,7 +1,6 @@
'use client'; 'use client';
import React, { useState } from 'react'; import React, { useState } from 'react';
import Image from 'next/image';
import Link from 'next/link'; import Link from 'next/link';
import { usePathname } from 'next/navigation'; import { usePathname } from 'next/navigation';
import { import {
@@ -26,11 +25,10 @@ import {
Images, Images,
History, History,
} from 'lucide-react'; } from 'lucide-react';
import TenantSwitcher from '@/components/TenantSwitcher'; import SidebarTenantSwitcher from '@/components/SidebarTenantSwitcher';
import type { DashboardModuleId } from '@/lib/tenant-modules'; import type { DashboardModuleId } from '@/lib/tenant-modules';
import DateRangePicker from '@/components/DateRangePicker'; import DateRangePicker from '@/components/DateRangePicker';
import { useDateRange } from '@/components/DateRangeContext'; import { useDateRange } from '@/components/DateRangeContext';
import SyncNowButton from '@/components/SyncNowButton';
type NavItem = { type NavItem = {
href: string; href: string;
@@ -69,13 +67,6 @@ const NAV_ITEMS: NavItem[] = [
iconClass: 'text-emerald-500', iconClass: 'text-emerald-500',
moduleId: 'estrategia', moduleId: 'estrategia',
}, },
{
href: '/dashboard/marca',
label: 'Zona de marca',
icon: BookMarked,
iconClass: 'text-rose-500',
moduleId: 'marca',
},
{ {
href: '/dashboard/ad-tracker', href: '/dashboard/ad-tracker',
label: 'Ads', label: 'Ads',
@@ -97,6 +88,13 @@ const NAV_ITEMS: NavItem[] = [
iconClass: 'text-lime-600', iconClass: 'text-lime-600',
moduleId: 'organico', moduleId: 'organico',
}, },
{
href: '/dashboard/marca',
label: 'Zona de marca',
icon: BookMarked,
iconClass: 'text-rose-500',
moduleId: 'marca',
},
{ {
href: '/dashboard/activos', href: '/dashboard/activos',
label: 'Biblioteca de Activos', label: 'Biblioteca de Activos',
@@ -120,6 +118,23 @@ const NAV_ITEMS: NavItem[] = [
}, },
]; ];
const EXCLUDED_DATE_HEADER_ROUTES = [
'/dashboard/seguimiento',
'/dashboard/marca',
'/dashboard/activos',
'/dashboard/creatividades',
'/dashboard/creatives',
'/dashboard/asistente',
'/dashboard/agencia',
];
function shouldShowDateHeader(pathname: string | null): boolean {
if (!pathname) return true;
return !EXCLUDED_DATE_HEADER_ROUTES.some(
(route) => pathname === route || pathname.startsWith(route + '/')
);
}
function isActive(pathname: string, href: string): boolean { function isActive(pathname: string, href: string): boolean {
if (pathname === href) return true; if (pathname === href) return true;
if (href !== '/dashboard' && pathname.startsWith(href + '/')) return true; if (href !== '/dashboard' && pathname.startsWith(href + '/')) return true;
@@ -163,6 +178,7 @@ export default function DashboardShell({
role, role,
isAgency, isAgency,
viewName, viewName,
activeTenantId,
enabledModules, enabledModules,
clientLogoUrl, clientLogoUrl,
brandLabel, brandLabel,
@@ -174,6 +190,7 @@ export default function DashboardShell({
role: string; role: string;
isAgency: boolean; isAgency: boolean;
viewName?: string; viewName?: string;
activeTenantId?: string | null;
/** null = show all (agency default). */ /** null = show all (agency default). */
enabledModules?: Record<DashboardModuleId, boolean> | null; enabledModules?: Record<DashboardModuleId, boolean> | null;
clientLogoUrl?: string | null; clientLogoUrl?: string | null;
@@ -184,6 +201,7 @@ export default function DashboardShell({
const close = () => setOpen(false); const close = () => setOpen(false);
const dateRange = useDateRange(); const dateRange = useDateRange();
const pathname = usePathname(); const pathname = usePathname();
const showDateHeader = shouldShowDateHeader(pathname);
const moduleOn = (id: DashboardModuleId) => { const moduleOn = (id: DashboardModuleId) => {
if (isAgency) return true; if (isAgency) return true;
@@ -193,48 +211,17 @@ export default function DashboardShell({
const visibleNav = NAV_ITEMS.filter((item) => moduleOn(item.moduleId)); const visibleNav = NAV_ITEMS.filter((item) => moduleOn(item.moduleId));
// Agencia siempre mantiene identidad 4Ventures (aunque esté "viendo" un cliente).
const title = isAgency
? '4VENTURES'
: clientLogoUrl
? brandLabel || company
: '4VENTURES';
const subtitle = isAgency
? viewName
? `Agencia · viendo ${viewName}`
: 'Centro de Mando'
: 'Portal cliente';
const sidebar = ( const sidebar = (
<div className="flex h-full flex-col"> <div className="flex h-full flex-col">
<div className="mb-6 flex items-center gap-3 border-b border-white/10 px-2 pb-4 pt-2"> <div className="mb-4 flex shrink-0 items-center gap-2 border-b border-white/10 px-1 pb-3 pt-1">
{clientLogoUrl ? ( <SidebarTenantSwitcher
// eslint-disable-next-line @next/next/no-img-element isAgency={isAgency}
<img initialActiveId={activeTenantId}
src={clientLogoUrl} initialActiveName={viewName}
alt={title} clientLogoUrl={clientLogoUrl}
width={40} brandLabel={brandLabel}
height={40} company={company}
className="h-10 w-10 shrink-0 rounded-md bg-white object-contain p-1" />
/>
) : (
<Image
src="/logo-4ventures.png"
alt="4Ventures"
width={40}
height={40}
className="h-10 w-10 shrink-0 rounded-md object-cover"
priority
/>
)}
<div className="min-w-0">
<p className="truncate text-[15px] font-medium leading-tight text-white">
{title}
</p>
<p className="mt-0.5 text-[12px] leading-tight text-mist-400">
{subtitle}
</p>
</div>
<button <button
type="button" type="button"
className="ml-auto rounded-md p-2 text-mist-400 hover:bg-white/10 hover:text-white md:hidden" className="ml-auto rounded-md p-2 text-mist-400 hover:bg-white/10 hover:text-white md:hidden"
@@ -245,7 +232,7 @@ export default function DashboardShell({
</button> </button>
</div> </div>
<nav className="flex-1 space-y-0.5 overflow-y-auto pr-1"> <nav className="flex-1 min-h-0 space-y-0.5 overflow-y-auto pr-1">
{visibleNav.map((item) => { {visibleNav.map((item) => {
// Sub-enlaces de Social: siempre que Social esté en el menú. // Sub-enlaces de Social: siempre que Social esté en el menú.
const underSocial = item.moduleId === 'social'; const underSocial = item.moduleId === 'social';
@@ -315,7 +302,7 @@ export default function DashboardShell({
) : null} ) : null}
</nav> </nav>
<div className="mt-4 space-y-3 border-t border-white/10 pt-4"> <div className="mt-auto shrink-0 space-y-2.5 border-t border-white/10 pt-3">
<div className="rounded-md bg-white/[0.05] px-3 py-2.5"> <div className="rounded-md bg-white/[0.05] px-3 py-2.5">
<div className="mb-1 flex items-center gap-2"> <div className="mb-1 flex items-center gap-2">
<UserCheck className="h-3.5 w-3.5 shrink-0 text-mist-400" /> <UserCheck className="h-3.5 w-3.5 shrink-0 text-mist-400" />
@@ -358,8 +345,8 @@ export default function DashboardShell({
); );
return ( return (
<div className="flex min-h-screen bg-background text-ink"> <div className="flex h-screen overflow-hidden bg-background text-ink">
<aside className="hidden w-[248px] shrink-0 flex-col bg-sidebar p-4 text-white md:flex"> <aside className="sticky top-0 hidden h-screen w-[248px] shrink-0 flex-col bg-sidebar p-4 text-white md:flex overflow-hidden">
{sidebar} {sidebar}
</aside> </aside>
@@ -371,48 +358,51 @@ export default function DashboardShell({
aria-label="Cerrar menú" aria-label="Cerrar menú"
onClick={close} onClick={close}
/> />
<aside className="absolute left-0 top-0 h-full w-[280px] bg-sidebar p-4 text-white shadow-xl"> <aside className="absolute left-0 top-0 h-full w-[280px] bg-sidebar p-4 text-white shadow-xl overflow-hidden">
{sidebar} {sidebar}
</aside> </aside>
</div> </div>
) : null} ) : null}
<div className="flex min-w-0 flex-1 flex-col"> <div className="flex min-w-0 flex-1 flex-col h-full overflow-hidden">
<header className="sticky top-0 z-30 space-y-2 border-b border-border bg-background/90 px-4 py-2.5 backdrop-blur-md md:px-8"> {showDateHeader ? (
<div className="flex items-center gap-3 min-h-10"> <header className="shrink-0 z-30 border-b border-border bg-background/90 px-4 py-2.5 backdrop-blur-md md:px-8">
<button <div className="flex min-h-10 flex-wrap items-center gap-3">
type="button" <button
className="rounded-md p-2 text-ink-muted hover:bg-mist-100 md:hidden" type="button"
onClick={() => setOpen(true)} className="rounded-md p-2 text-ink-muted hover:bg-mist-100 md:hidden"
aria-label="Abrir menú" onClick={() => setOpen(true)}
> aria-label="Abrir menú"
<Menu className="w-5 h-5" /> >
</button> <Menu className="w-5 h-5" />
</button>
<div className="flex min-w-0 items-center gap-2 text-sm text-ink-muted"> <div className="min-w-0 flex-1">
<span className="hidden sm:inline shrink-0"> <DateRangePicker
{isAgency ? 'Contexto:' : 'Cliente / Portal:'} compact
</span> preset={dateRange.preset}
<TenantSwitcher customSince={dateRange.customSince}
isAgency={isAgency} customUntil={dateRange.customUntil}
initialName={viewName || company} onPreset={dateRange.setPreset}
/> onCustomChange={dateRange.setCustom}
/>
</div>
</div> </div>
</div> </header>
<div className="flex flex-wrap items-center gap-3"> ) : (
<div className="min-w-0 flex-1"> <header className="shrink-0 z-30 border-b border-border bg-background/90 px-4 py-2.5 backdrop-blur-md md:hidden">
<DateRangePicker <div className="flex min-h-10 items-center">
compact <button
preset={dateRange.preset} type="button"
customSince={dateRange.customSince} className="rounded-md p-2 text-ink-muted hover:bg-mist-100"
customUntil={dateRange.customUntil} onClick={() => setOpen(true)}
onPreset={dateRange.setPreset} aria-label="Abrir menú"
onCustomChange={dateRange.setCustom} >
/> <Menu className="w-5 h-5" />
</button>
</div> </div>
{isAgency ? <SyncNowButton /> : null} </header>
</div> )}
</header>
<main className="canvas-dots flex-1 overflow-y-auto"> <main className="canvas-dots flex-1 overflow-y-auto">
<div className="mx-auto w-full max-w-7xl px-4 py-6 md:px-8 md:py-9"> <div className="mx-auto w-full max-w-7xl px-4 py-6 md:px-8 md:py-9">

View File

@@ -0,0 +1,305 @@
'use client';
import React, { useEffect, useRef, useState } from 'react';
import Image from 'next/image';
import {
Building2,
Check,
ChevronsUpDown,
Loader2,
Search,
} from 'lucide-react';
export type TenantOption = {
id: string;
name: string;
slug: string;
};
interface SidebarTenantSwitcherProps {
isAgency: boolean;
initialActiveId?: string | null;
initialActiveName?: string;
clientLogoUrl?: string | null;
brandLabel?: string;
company?: string;
}
export default function SidebarTenantSwitcher({
isAgency,
initialActiveId = null,
initialActiveName = '',
clientLogoUrl = null,
brandLabel = '',
company = '4Ventures',
}: SidebarTenantSwitcherProps) {
const [open, setOpen] = useState(false);
const [tenants, setTenants] = useState<TenantOption[]>([]);
const [activeId, setActiveId] = useState<string | null>(initialActiveId);
const [activeName, setActiveName] = useState<string>(
initialActiveName || brandLabel || company || ''
);
const [switching, setSwitching] = useState(false);
const [loading, setLoading] = useState(false);
const [search, setSearch] = useState('');
const dropdownRef = useRef<HTMLDivElement>(null);
// Sincronizar cookies y cargar lista de tenants en cliente
useEffect(() => {
if (!isAgency) return;
const matchName = document.cookie.match(/(?:^|; )4v_view_tenant_name=([^;]*)/);
const matchId = document.cookie.match(/(?:^|; )4v_view_tenant_id=([^;]*)/);
if (matchName?.[1]) setActiveName(decodeURIComponent(matchName[1]));
if (matchId?.[1]) setActiveId(decodeURIComponent(matchId[1]));
setLoading(true);
fetch('/api/admin/portfolio')
.then((r) => r.json())
.then((d) => {
const list = (d.portfolio || [])
.filter((t: { agency_followed?: boolean }) => t.agency_followed !== false)
.map((t: { id: string; name: string; slug: string }) => ({
id: t.id,
name: t.name,
slug: t.slug,
}));
setTenants(list);
})
.catch(() => {})
.finally(() => setLoading(false));
}, [isAgency]);
// Cerrar al hacer clic fuera
useEffect(() => {
if (!open) return;
function handleClickOutside(event: MouseEvent) {
if (
dropdownRef.current &&
!dropdownRef.current.contains(event.target as Node)
) {
setOpen(false);
}
}
function handleKeyDown(event: KeyboardEvent) {
if (event.key === 'Escape') {
setOpen(false);
}
}
document.addEventListener('mousedown', handleClickOutside);
document.addEventListener('keydown', handleKeyDown);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
document.removeEventListener('keydown', handleKeyDown);
};
}, [open]);
async function select(tenant: TenantOption | null) {
setOpen(false);
setSwitching(true);
try {
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 de agencia');
// Limpiar query params de tenant para que no haya conflicto
const currentUrl = new URL(window.location.href);
const hadTenantParam =
currentUrl.searchParams.has('tenant') ||
currentUrl.searchParams.has('tenant_id') ||
currentUrl.searchParams.has('tenantId');
currentUrl.searchParams.delete('tenant');
currentUrl.searchParams.delete('tenant_id');
currentUrl.searchParams.delete('tenantId');
if (hadTenantParam) {
window.location.href = currentUrl.toString();
} else {
window.location.reload();
}
} catch {
window.location.reload();
}
}
const showClientBrand = Boolean(activeId && (clientLogoUrl || activeName));
const displayTitle = showClientBrand
? activeName || brandLabel || company
: '4VENTURES';
const displaySubtitle = showClientBrand
? isAgency
? 'Vista cliente'
: 'Portal cliente'
: isAgency
? 'Vista global de agencia'
: 'Centro de Mando';
const filteredTenants = tenants.filter((t) => {
if (!search.trim()) return true;
const q = search.toLowerCase();
return t.name.toLowerCase().includes(q) || t.slug.toLowerCase().includes(q);
});
return (
<div ref={dropdownRef} className="relative min-w-0 flex-1">
<button
type="button"
disabled={!isAgency || switching}
onClick={() => isAgency && setOpen((v) => !v)}
className={`group flex w-full items-center gap-3 rounded-lg p-1.5 text-left transition-colors ${
isAgency
? 'cursor-pointer hover:bg-white/[0.07] focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-brand-500/50'
: 'cursor-default'
}`}
aria-haspopup={isAgency ? 'menu' : undefined}
aria-expanded={isAgency ? open : undefined}
title={isAgency ? 'Cambiar cliente o vista global' : undefined}
>
{/* Logo del cliente o de 4Ventures */}
{clientLogoUrl && activeId ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={clientLogoUrl}
alt={displayTitle}
width={40}
height={40}
className="h-10 w-10 shrink-0 rounded-md bg-white object-contain p-1 shadow-xs"
/>
) : (
<Image
src="/logo-4ventures.png"
alt="4Ventures"
width={40}
height={40}
className="h-10 w-10 shrink-0 rounded-md object-cover shadow-xs"
priority
/>
)}
{/* Textos del cliente / vista */}
<div className="min-w-0 flex-1">
<p className="truncate text-[15px] font-medium leading-tight text-white group-hover:text-white">
{displayTitle}
</p>
<p className="mt-0.5 truncate text-[12px] leading-tight text-mist-400">
{displaySubtitle}
</p>
</div>
{/* Chevron interactivo para agencia */}
{isAgency && (
<div className="shrink-0 text-mist-400 transition-colors group-hover:text-white">
{switching ? (
<Loader2 className="h-4 w-4 animate-spin text-brand-500" />
) : (
<ChevronsUpDown className="h-4 w-4" />
)}
</div>
)}
</button>
{/* Menú desplegable */}
{open && isAgency && (
<div className="absolute left-0 top-[calc(100%+8px)] z-50 w-full min-w-[240px] rounded-xl border border-white/15 bg-[#0C1524] p-1.5 text-white shadow-2xl backdrop-blur-xl">
<div className="px-2 py-1 text-[11px] font-medium uppercase tracking-wider text-mist-400">
Cambiar vista
</div>
{/* Opción: Vista global de agencia */}
<button
type="button"
disabled={switching}
onClick={() => select(null)}
className={`flex w-full items-center justify-between gap-2.5 rounded-lg px-2.5 py-2 text-left transition-colors cursor-pointer ${
!activeId
? 'bg-brand-500/15 text-white font-medium'
: 'text-mist-300 hover:bg-white/[0.08] hover:text-white'
}`}
>
<div className="flex items-center gap-2.5 min-w-0">
<div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-white/[0.08] text-brand-400">
<Building2 className="h-4 w-4" />
</div>
<div className="min-w-0">
<span className="block truncate text-[13px] font-medium leading-tight">
Vista global de agencia
</span>
<span className="block truncate text-[11px] text-mist-400 leading-tight">
Portafolio completo
</span>
</div>
</div>
{!activeId && <Check className="h-4 w-4 shrink-0 text-brand-500" />}
</button>
<div className="my-1.5 border-t border-white/10" />
{/* Buscador de clientes si hay más de 4 */}
{tenants.length > 4 && (
<div className="px-1 pb-1">
<div className="relative">
<Search className="absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-mist-400" />
<input
type="text"
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Buscar cliente..."
className="w-full rounded-md border border-white/10 bg-white/[0.06] py-1 pl-8 pr-2.5 text-[12px] text-white placeholder:text-mist-400 focus:border-brand-500/50 focus:outline-none"
onClick={(e) => e.stopPropagation()}
/>
</div>
</div>
)}
{/* Lista de clientes */}
<div className="max-h-[220px] space-y-0.5 overflow-y-auto pr-0.5">
{filteredTenants.length === 0 ? (
<p className="px-2.5 py-3 text-center text-[12px] text-mist-400">
{loading ? 'Cargando clientes…' : 'No hay clientes disponibles'}
</p>
) : (
filteredTenants.map((t) => {
const isSelected = activeId === t.id;
return (
<button
key={t.id}
type="button"
disabled={switching}
onClick={() => select(t)}
className={`flex w-full items-center justify-between gap-2.5 rounded-lg px-2.5 py-2 text-left transition-colors cursor-pointer ${
isSelected
? 'bg-brand-500/15 text-white font-medium'
: 'text-mist-300 hover:bg-white/[0.08] hover:text-white'
}`}
>
<div className="flex items-center gap-2.5 min-w-0">
<div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-white/[0.08] text-[12px] font-semibold text-white uppercase">
{t.name.slice(0, 2)}
</div>
<div className="min-w-0">
<span className="block truncate text-[13px] font-medium leading-tight">
{t.name}
</span>
<span className="block truncate font-mono text-[11px] text-mist-400 leading-tight">
{t.slug}
</span>
</div>
</div>
{isSelected && (
<Check className="h-4 w-4 shrink-0 text-brand-500" />
)}
</button>
);
})
)}
</div>
</div>
)}
</div>
);
}

View File

@@ -55,43 +55,6 @@ export const DASHBOARD_MODULES: DashboardModuleDef[] = [
providers: [], providers: [],
hint: 'Targets y presupuesto', hint: 'Targets y presupuesto',
}, },
{
id: 'marca',
href: '/dashboard/marca',
label: 'Zona de marca',
providers: [],
hint: 'Brandbook: voz, oferta, ads, LinkedIn, blog',
},
{
id: 'ad-tracker',
href: '/dashboard/ad-tracker',
label: 'Ads',
providers: ['meta_ads', 'google_ads'],
hint: 'Paid: Meta Ads, Google Ads y creatividades',
},
{
id: 'social',
href: '/dashboard/social',
label: 'Social',
providers: ['instagram', 'facebook', 'tiktok', 'linkedin'],
hint: 'RRSS orgánicas: perfiles, alcance y contenido',
},
{
id: 'calendario',
href: '/dashboard/calendario',
label: 'Calendario editorial',
providers: ['instagram', 'facebook', 'tiktok', 'linkedin'],
hint: 'Submenú de Social · planificación RRSS',
parentId: 'social',
},
{
id: 'pipeline',
href: '/dashboard/creatives',
label: 'Pipeline RRSS',
providers: ['instagram', 'facebook', 'tiktok', 'linkedin', 'google_drive'],
hint: 'Submenú de Social · piezas orgánicas a publicar',
parentId: 'social',
},
{ {
id: 'organico', id: 'organico',
href: '/dashboard/organico', href: '/dashboard/organico',
@@ -99,6 +62,13 @@ export const DASHBOARD_MODULES: DashboardModuleDef[] = [
providers: ['ga4', 'search_console'], providers: ['ga4', 'search_console'],
hint: 'SEO (Search Console y GA4)', hint: 'SEO (Search Console y GA4)',
}, },
{
id: 'marca',
href: '/dashboard/marca',
label: 'Zona de marca',
providers: [],
hint: 'Brandbook: voz, oferta, ads, LinkedIn, blog',
},
{ {
id: 'activos', id: 'activos',
href: '/dashboard/activos', href: '/dashboard/activos',