fix(context): recarga completa y refresco automatico al cambiar de cliente en Contexto

This commit is contained in:
Marcos Fargas
2026-10-15 03:40:22 +02:00
parent 0b3f80d790
commit de546e00e0
2 changed files with 62 additions and 29 deletions

View File

@@ -66,10 +66,7 @@ export default function CalendarPortfolioBoard({
const href = latest const href = latest
? `/dashboard/calendario?view=archive&month=${latest}` ? `/dashboard/calendario?view=archive&month=${latest}`
: '/dashboard/calendario?view=archive'; : '/dashboard/calendario?view=archive';
startTransition(() => { window.location.href = href;
router.push(href);
router.refresh();
});
} }
return ( return (

View File

@@ -1,8 +1,7 @@
'use client'; 'use client';
import React, { useEffect, useState, useTransition } from 'react'; import React, { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation'; import { ChevronDown, Eye, Building2, Loader2, Check } from 'lucide-react';
import { ChevronDown, Eye, Building2 } from 'lucide-react';
type TenantOpt = { id: string; name: string; slug: string }; type TenantOpt = { id: string; name: string; slug: string };
@@ -13,12 +12,11 @@ export default function TenantSwitcher({
initialName: string; initialName: string;
isAgency: boolean; isAgency: boolean;
}) { }) {
const router = useRouter();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [tenants, setTenants] = useState<TenantOpt[]>([]); const [tenants, setTenants] = useState<TenantOpt[]>([]);
const [activeName, setActiveName] = useState(initialName); const [activeName, setActiveName] = useState(initialName);
const [activeId, setActiveId] = useState<string | null>(null); const [activeId, setActiveId] = useState<string | null>(null);
const [pending, startTransition] = useTransition(); const [switching, setSwitching] = useState(false);
useEffect(() => { useEffect(() => {
if (!isAgency) return; if (!isAgency) return;
@@ -52,39 +50,74 @@ export default function TenantSwitcher({
async function select(tenant: TenantOpt | null) { async function select(tenant: TenantOpt | null) {
setOpen(false); setOpen(false);
await fetch('/api/admin/active-tenant', { setSwitching(true);
method: 'POST', try {
headers: { 'Content-Type': 'application/json' }, await fetch('/api/admin/active-tenant', {
body: JSON.stringify({ tenantId: tenant?.id ?? null }), method: 'POST',
}); headers: { 'Content-Type': 'application/json' },
setActiveId(tenant?.id ?? null); body: JSON.stringify({ tenantId: tenant?.id ?? null }),
setActiveName(tenant?.name ?? 'Vista global agencia'); });
startTransition(() => router.refresh()); setActiveId(tenant?.id ?? null);
setActiveName(tenant?.name ?? 'Vista global 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();
}
} }
return ( return (
<div className="relative"> <div className="relative">
<button <button
type="button" type="button"
disabled={switching}
onClick={() => setOpen((v) => !v)} onClick={() => setOpen((v) => !v)}
className="inline-flex items-center gap-2 bg-brand-50 text-brand-700 font-semibold px-2.5 py-1 rounded-md border border-brand-200 hover:bg-brand-100 transition-colors" className="inline-flex items-center gap-2 bg-brand-50 text-brand-700 font-semibold px-2.5 py-1 rounded-md border border-brand-200 hover:bg-brand-100 transition-colors disabled:opacity-75 cursor-pointer"
title="Cambiar cliente en contexto"
> >
<Eye className="w-3.5 h-3.5" /> {switching ? (
<Loader2 className="w-3.5 h-3.5 animate-spin text-brand-600" />
) : (
<Eye className="w-3.5 h-3.5" />
)}
<span className="max-w-[200px] truncate"> <span className="max-w-[200px] truncate">
{activeId ? activeName : 'Vista global agencia'} {switching
? 'Cargando cliente…'
: activeId
? activeName
: 'Vista global agencia'}
</span> </span>
<ChevronDown className="w-3.5 h-3.5 opacity-70" /> <ChevronDown className="w-3.5 h-3.5 opacity-70" />
</button> </button>
{open && ( {open && (
<div className="absolute left-0 top-full mt-2 z-50 w-72 rounded-xl border border-gray-200 bg-white shadow-xl py-1 max-h-80 overflow-y-auto"> <div className="absolute left-0 top-full mt-2 z-50 w-72 rounded-xl border border-gray-200 bg-white shadow-xl py-1 max-h-80 overflow-y-auto">
<button <button
type="button" type="button"
disabled={pending} disabled={switching}
onClick={() => select(null)} onClick={() => select(null)}
className="w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 flex items-center gap-2" className="w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 flex items-center justify-between cursor-pointer"
> >
<Building2 className="w-3.5 h-3.5 text-amber-500" /> <div className="flex items-center gap-2">
Vista global agencia <Building2 className="w-3.5 h-3.5 text-amber-500" />
<span>Vista global agencia</span>
</div>
{!activeId && <Check className="w-3.5 h-3.5 text-brand-600" />}
</button> </button>
<div className="border-t border-gray-100 my-1" /> <div className="border-t border-gray-100 my-1" />
{tenants.length === 0 ? ( {tenants.length === 0 ? (
@@ -96,14 +129,17 @@ export default function TenantSwitcher({
<button <button
key={t.id} key={t.id}
type="button" type="button"
disabled={pending} disabled={switching}
onClick={() => select(t)} onClick={() => select(t)}
className={`w-full text-left px-3 py-2 text-sm hover:bg-gray-50 ${ className={`w-full text-left px-3 py-2 text-sm hover:bg-gray-50 flex items-center justify-between cursor-pointer ${
activeId === t.id ? 'text-brand-600' : 'text-gray-800' activeId === t.id ? 'text-brand-600 font-semibold bg-brand-50/50' : 'text-gray-800'
}`} }`}
> >
<span className="font-medium">{t.name}</span> <div>
<span className="block text-[10px] text-gray-500">{t.slug}</span> <span className="font-medium block leading-snug">{t.name}</span>
<span className="block text-[10px] text-gray-500 font-mono">{t.slug}</span>
</div>
{activeId === t.id && <Check className="w-3.5 h-3.5 text-brand-600 shrink-0 ml-2" />}
</button> </button>
)) ))
)} )}