feat: add multi-tenant client management for admins

- Add tenants API endpoints (list, get, create)
- Add tenant middleware override via X-View-Tenant header
- Add TenantSelector dropdown component in header
- Add tenant view store with persistence
- Add Clientes management page
- Update all navigation layouts with Clientes link for admins

Admins can now:
- View list of all clients
- Create new clients with automatic schema setup
- Switch between viewing different clients' data
- See which client they are currently viewing

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Consultoria AS
2026-01-22 03:55:44 +00:00
parent 6e3e69005b
commit 0c10c887d2
16 changed files with 768 additions and 6 deletions

View File

@@ -12,6 +12,7 @@ import { alertasRoutes } from './routes/alertas.routes.js';
import { calendarioRoutes } from './routes/calendario.routes.js'; import { calendarioRoutes } from './routes/calendario.routes.js';
import { reportesRoutes } from './routes/reportes.routes.js'; import { reportesRoutes } from './routes/reportes.routes.js';
import { usuariosRoutes } from './routes/usuarios.routes.js'; import { usuariosRoutes } from './routes/usuarios.routes.js';
import { tenantsRoutes } from './routes/tenants.routes.js';
const app = express(); const app = express();
@@ -41,6 +42,7 @@ app.use('/api/alertas', alertasRoutes);
app.use('/api/calendario', calendarioRoutes); app.use('/api/calendario', calendarioRoutes);
app.use('/api/reportes', reportesRoutes); app.use('/api/reportes', reportesRoutes);
app.use('/api/usuarios', usuariosRoutes); app.use('/api/usuarios', usuariosRoutes);
app.use('/api/tenants', tenantsRoutes);
// Error handling // Error handling
app.use(errorMiddleware); app.use(errorMiddleware);

View File

@@ -0,0 +1,60 @@
import { Request, Response, NextFunction } from 'express';
import * as tenantsService from '../services/tenants.service.js';
import { AppError } from '../utils/errors.js';
export async function getAllTenants(req: Request, res: Response, next: NextFunction) {
try {
// Only admin can list all tenants
if (req.user!.role !== 'admin') {
throw new AppError(403, 'Solo administradores pueden ver todos los clientes');
}
const tenants = await tenantsService.getAllTenants();
res.json(tenants);
} catch (error) {
next(error);
}
}
export async function getTenant(req: Request, res: Response, next: NextFunction) {
try {
if (req.user!.role !== 'admin') {
throw new AppError(403, 'Solo administradores pueden ver detalles de clientes');
}
const tenant = await tenantsService.getTenantById(req.params.id);
if (!tenant) {
throw new AppError(404, 'Cliente no encontrado');
}
res.json(tenant);
} catch (error) {
next(error);
}
}
export async function createTenant(req: Request, res: Response, next: NextFunction) {
try {
if (req.user!.role !== 'admin') {
throw new AppError(403, 'Solo administradores pueden crear clientes');
}
const { nombre, rfc, plan, cfdiLimit, usersLimit } = req.body;
if (!nombre || !rfc) {
throw new AppError(400, 'Nombre y RFC son requeridos');
}
const tenant = await tenantsService.createTenant({
nombre,
rfc,
plan,
cfdiLimit,
usersLimit,
});
res.status(201).json(tenant);
} catch (error) {
next(error);
}
}

View File

@@ -6,6 +6,7 @@ declare global {
namespace Express { namespace Express {
interface Request { interface Request {
tenantSchema?: string; tenantSchema?: string;
viewingTenantId?: string;
} }
} }
} }
@@ -16,8 +17,18 @@ export async function tenantMiddleware(req: Request, res: Response, next: NextFu
} }
try { try {
// Check if admin is viewing a different tenant
const viewTenantId = req.headers['x-view-tenant'] as string | undefined;
let tenantId = req.user.tenantId;
// Only admins can view other tenants
if (viewTenantId && req.user.role === 'admin') {
tenantId = viewTenantId;
req.viewingTenantId = viewTenantId;
}
const tenant = await prisma.tenant.findUnique({ const tenant = await prisma.tenant.findUnique({
where: { id: req.user.tenantId }, where: { id: tenantId },
select: { schemaName: true, active: true }, select: { schemaName: true, active: true },
}); });

View File

@@ -0,0 +1,13 @@
import { Router } from 'express';
import { authenticate } from '../middlewares/auth.middleware.js';
import * as tenantsController from '../controllers/tenants.controller.js';
const router = Router();
router.use(authenticate);
router.get('/', tenantsController.getAllTenants);
router.get('/:id', tenantsController.getTenant);
router.post('/', tenantsController.createTenant);
export { router as tenantsRoutes };

View File

@@ -0,0 +1,141 @@
import { prisma } from '../config/database.js';
export async function getAllTenants() {
return prisma.tenant.findMany({
where: { active: true },
select: {
id: true,
nombre: true,
rfc: true,
plan: true,
schemaName: true,
createdAt: true,
_count: {
select: { users: true }
}
},
orderBy: { nombre: 'asc' }
});
}
export async function getTenantById(id: string) {
return prisma.tenant.findUnique({
where: { id },
select: {
id: true,
nombre: true,
rfc: true,
plan: true,
schemaName: true,
cfdiLimit: true,
usersLimit: true,
createdAt: true,
}
});
}
export async function createTenant(data: {
nombre: string;
rfc: string;
plan?: 'starter' | 'business' | 'professional' | 'enterprise';
cfdiLimit?: number;
usersLimit?: number;
}) {
const schemaName = `tenant_${data.rfc.toLowerCase().replace(/[^a-z0-9]/g, '')}`;
// Create tenant record
const tenant = await prisma.tenant.create({
data: {
nombre: data.nombre,
rfc: data.rfc.toUpperCase(),
plan: data.plan || 'starter',
schemaName,
cfdiLimit: data.cfdiLimit || 500,
usersLimit: data.usersLimit || 3,
}
});
// Create schema and tables for the tenant
await prisma.$executeRawUnsafe(`CREATE SCHEMA IF NOT EXISTS "${schemaName}"`);
// Create CFDIs table
await prisma.$executeRawUnsafe(`
CREATE TABLE IF NOT EXISTS "${schemaName}"."cfdis" (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
uuid_fiscal VARCHAR(36) UNIQUE NOT NULL,
tipo VARCHAR(20) NOT NULL,
serie VARCHAR(25),
folio VARCHAR(40),
fecha_emision TIMESTAMP NOT NULL,
fecha_timbrado TIMESTAMP NOT NULL,
rfc_emisor VARCHAR(13) NOT NULL,
nombre_emisor VARCHAR(300) NOT NULL,
rfc_receptor VARCHAR(13) NOT NULL,
nombre_receptor VARCHAR(300) NOT NULL,
subtotal DECIMAL(18,2) NOT NULL,
descuento DECIMAL(18,2) DEFAULT 0,
iva DECIMAL(18,2) DEFAULT 0,
isr_retenido DECIMAL(18,2) DEFAULT 0,
iva_retenido DECIMAL(18,2) DEFAULT 0,
total DECIMAL(18,2) NOT NULL,
moneda VARCHAR(3) DEFAULT 'MXN',
tipo_cambio DECIMAL(10,4) DEFAULT 1,
metodo_pago VARCHAR(3),
forma_pago VARCHAR(2),
uso_cfdi VARCHAR(4),
estado VARCHAR(20) DEFAULT 'vigente',
xml_url TEXT,
pdf_url TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
// Create IVA monthly table
await prisma.$executeRawUnsafe(`
CREATE TABLE IF NOT EXISTS "${schemaName}"."iva_mensual" (
id SERIAL PRIMARY KEY,
año INT NOT NULL,
mes INT NOT NULL,
iva_trasladado DECIMAL(18,2) NOT NULL,
iva_acreditable DECIMAL(18,2) NOT NULL,
iva_retenido DECIMAL(18,2) DEFAULT 0,
resultado DECIMAL(18,2) NOT NULL,
acumulado DECIMAL(18,2) NOT NULL,
estado VARCHAR(20) DEFAULT 'pendiente',
fecha_declaracion TIMESTAMP,
UNIQUE(año, mes)
)
`);
// Create alerts table
await prisma.$executeRawUnsafe(`
CREATE TABLE IF NOT EXISTS "${schemaName}"."alertas" (
id SERIAL PRIMARY KEY,
tipo VARCHAR(50) NOT NULL,
titulo VARCHAR(200) NOT NULL,
mensaje TEXT NOT NULL,
prioridad VARCHAR(20) DEFAULT 'media',
fecha_vencimiento TIMESTAMP,
leida BOOLEAN DEFAULT FALSE,
resuelta BOOLEAN DEFAULT FALSE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
// Create calendario_fiscal table
await prisma.$executeRawUnsafe(`
CREATE TABLE IF NOT EXISTS "${schemaName}"."calendario_fiscal" (
id SERIAL PRIMARY KEY,
titulo VARCHAR(200) NOT NULL,
descripcion TEXT,
tipo VARCHAR(20) NOT NULL,
fecha_limite TIMESTAMP NOT NULL,
recurrencia VARCHAR(20) DEFAULT 'mensual',
completado BOOLEAN DEFAULT FALSE,
notas TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
return tenant;
}

View File

@@ -0,0 +1,259 @@
'use client';
import { useState } from 'react';
import { Header } from '@/components/layouts/header';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useTenants, useCreateTenant } from '@/lib/hooks/use-tenants';
import { useTenantViewStore } from '@/stores/tenant-view-store';
import { useAuthStore } from '@/stores/auth-store';
import { Building, Plus, Users, Eye, Calendar } from 'lucide-react';
export default function ClientesPage() {
const { user } = useAuthStore();
const { data: tenants, isLoading } = useTenants();
const createTenant = useCreateTenant();
const { setViewingTenant } = useTenantViewStore();
const [showForm, setShowForm] = useState(false);
const [formData, setFormData] = useState({
nombre: '',
rfc: '',
plan: 'starter' as const,
});
// Only admins can access this page
if (user?.role !== 'admin') {
return (
<>
<Header title="Clientes" />
<main className="p-6">
<Card>
<CardContent className="py-12 text-center">
<p className="text-muted-foreground">
No tienes permisos para ver esta página.
</p>
</CardContent>
</Card>
</main>
</>
);
}
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
await createTenant.mutateAsync(formData);
setFormData({ nombre: '', rfc: '', plan: 'starter' });
setShowForm(false);
} catch (error) {
console.error('Error creating tenant:', error);
}
};
const handleViewClient = (tenantId: string, tenantName: string) => {
setViewingTenant(tenantId, tenantName);
window.location.href = '/dashboard';
};
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleDateString('es-MX', {
year: 'numeric',
month: 'short',
day: 'numeric',
});
};
const planLabels: Record<string, string> = {
starter: 'Starter',
business: 'Business',
professional: 'Professional',
enterprise: 'Enterprise',
};
const planColors: Record<string, string> = {
starter: 'bg-muted text-muted-foreground',
business: 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-100',
professional: 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-100',
enterprise: 'bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-100',
};
return (
<>
<Header title="Gestión de Clientes" />
<main className="p-6 space-y-6">
{/* Stats */}
<div className="grid gap-4 md:grid-cols-3">
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-4">
<div className="p-3 bg-primary/10 rounded-lg">
<Building className="h-6 w-6 text-primary" />
</div>
<div>
<p className="text-2xl font-bold">{tenants?.length || 0}</p>
<p className="text-sm text-muted-foreground">Total Clientes</p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<div className="flex items-center gap-4">
<div className="p-3 bg-success/10 rounded-lg">
<Users className="h-6 w-6 text-success" />
</div>
<div>
<p className="text-2xl font-bold">
{tenants?.reduce((acc, t) => acc + (t._count?.users || 0), 0) || 0}
</p>
<p className="text-sm text-muted-foreground">Total Usuarios</p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="pt-6">
<Button onClick={() => setShowForm(true)} className="w-full h-full min-h-[60px]">
<Plus className="h-5 w-5 mr-2" />
Agregar Cliente
</Button>
</CardContent>
</Card>
</div>
{/* Add Client Form */}
{showForm && (
<Card>
<CardHeader>
<CardTitle className="text-base">Nuevo Cliente</CardTitle>
<CardDescription>
Registra un nuevo cliente para gestionar su facturación
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="grid gap-4 md:grid-cols-2">
<div className="space-y-2">
<Label htmlFor="nombre">Nombre de la Empresa</Label>
<Input
id="nombre"
value={formData.nombre}
onChange={(e) => setFormData({ ...formData, nombre: e.target.value })}
placeholder="Empresa SA de CV"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="rfc">RFC</Label>
<Input
id="rfc"
value={formData.rfc}
onChange={(e) => setFormData({ ...formData, rfc: e.target.value.toUpperCase() })}
placeholder="XAXX010101000"
maxLength={13}
required
/>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="plan">Plan</Label>
<Select
value={formData.plan}
onValueChange={(value: 'starter' | 'business' | 'professional' | 'enterprise') =>
setFormData({ ...formData, plan: value })
}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="starter">Starter - 500 CFDIs, 3 usuarios</SelectItem>
<SelectItem value="business">Business - 1,000 CFDIs, 5 usuarios</SelectItem>
<SelectItem value="professional">Professional - 2,000 CFDIs, 10 usuarios</SelectItem>
<SelectItem value="enterprise">Enterprise - Ilimitado</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex gap-2 justify-end">
<Button type="button" variant="outline" onClick={() => setShowForm(false)}>
Cancelar
</Button>
<Button type="submit" disabled={createTenant.isPending}>
{createTenant.isPending ? 'Creando...' : 'Crear Cliente'}
</Button>
</div>
</form>
</CardContent>
</Card>
)}
{/* Clients List */}
<Card>
<CardHeader>
<CardTitle className="text-base">Lista de Clientes</CardTitle>
</CardHeader>
<CardContent>
{isLoading ? (
<div className="text-center py-8 text-muted-foreground">Cargando...</div>
) : tenants && tenants.length > 0 ? (
<div className="space-y-3">
{tenants.map((tenant) => (
<div
key={tenant.id}
className="flex items-center justify-between p-4 rounded-lg border hover:bg-muted/50 transition-colors"
>
<div className="flex items-center gap-4">
<div className="h-12 w-12 rounded-lg bg-primary/10 flex items-center justify-center">
<span className="font-bold text-primary">
{tenant.nombre.substring(0, 2).toUpperCase()}
</span>
</div>
<div>
<p className="font-medium">{tenant.nombre}</p>
<div className="flex items-center gap-3 text-sm text-muted-foreground">
<span>{tenant.rfc}</span>
<span className={`px-2 py-0.5 rounded-full text-xs font-medium ${planColors[tenant.plan]}`}>
{planLabels[tenant.plan]}
</span>
</div>
</div>
</div>
<div className="flex items-center gap-6">
<div className="text-right">
<div className="flex items-center gap-1 text-sm">
<Users className="h-4 w-4 text-muted-foreground" />
<span>{tenant._count?.users || 0} usuarios</span>
</div>
<div className="flex items-center gap-1 text-xs text-muted-foreground">
<Calendar className="h-3 w-3" />
<span>{formatDate(tenant.createdAt)}</span>
</div>
</div>
<Button
variant="outline"
size="sm"
onClick={() => handleViewClient(tenant.id, tenant.nombre)}
>
<Eye className="h-4 w-4 mr-1" />
Ver
</Button>
</div>
</div>
))}
</div>
) : (
<div className="text-center py-8 text-muted-foreground">
No hay clientes registrados
</div>
)}
</CardContent>
</Card>
</main>
</>
);
}

View File

@@ -3,6 +3,7 @@
import { useThemeStore } from '@/stores/theme-store'; import { useThemeStore } from '@/stores/theme-store';
import { themes, type ThemeName } from '@/themes'; import { themes, type ThemeName } from '@/themes';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { TenantSelector } from '@/components/tenant-selector';
import { Sun, Moon, Palette } from 'lucide-react'; import { Sun, Moon, Palette } from 'lucide-react';
const themeIcons: Record<ThemeName, React.ReactNode> = { const themeIcons: Record<ThemeName, React.ReactNode> = {
@@ -27,7 +28,8 @@ export function Header({ title }: { title: string }) {
<header className="sticky top-0 z-30 flex h-16 items-center justify-between border-b bg-background/95 backdrop-blur px-6"> <header className="sticky top-0 z-30 flex h-16 items-center justify-between border-b bg-background/95 backdrop-blur px-6">
<h1 className="text-xl font-semibold">{title}</h1> <h1 className="text-xl font-semibold">{title}</h1>
<div className="flex items-center gap-2"> <div className="flex items-center gap-3">
<TenantSelector />
<Button <Button
variant="ghost" variant="ghost"
size="icon" size="icon"

View File

@@ -13,6 +13,7 @@ import {
Calendar, Calendar,
Bell, Bell,
Users, Users,
Building2,
} from 'lucide-react'; } from 'lucide-react';
import { useAuthStore } from '@/stores/auth-store'; import { useAuthStore } from '@/stores/auth-store';
import { logout } from '@/lib/api/auth'; import { logout } from '@/lib/api/auth';
@@ -30,12 +31,20 @@ const navigation = [
{ name: 'Configuración', href: '/configuracion', icon: Settings }, { name: 'Configuración', href: '/configuracion', icon: Settings },
]; ];
const adminNavigation = [
{ name: 'Clientes', href: '/clientes', icon: Building2 },
];
export function SidebarCompact() { export function SidebarCompact() {
const pathname = usePathname(); const pathname = usePathname();
const router = useRouter(); const router = useRouter();
const { user, logout: clearAuth } = useAuthStore(); const { user, logout: clearAuth } = useAuthStore();
const [expanded, setExpanded] = useState(false); const [expanded, setExpanded] = useState(false);
const allNavigation = user?.role === 'admin'
? [...navigation.slice(0, -1), ...adminNavigation, navigation[navigation.length - 1]]
: navigation;
const handleLogout = async () => { const handleLogout = async () => {
try { try {
await logout(); await logout();
@@ -74,7 +83,7 @@ export function SidebarCompact() {
{/* Navigation */} {/* Navigation */}
<nav className="flex-1 space-y-1 px-2 py-3"> <nav className="flex-1 space-y-1 px-2 py-3">
{navigation.map((item) => { {allNavigation.map((item) => {
const isActive = pathname === item.href || pathname.startsWith(`${item.href}/`); const isActive = pathname === item.href || pathname.startsWith(`${item.href}/`);
return ( return (
<Link <Link

View File

@@ -13,6 +13,7 @@ import {
Calendar, Calendar,
Bell, Bell,
Users, Users,
Building2,
} from 'lucide-react'; } from 'lucide-react';
import { useAuthStore } from '@/stores/auth-store'; import { useAuthStore } from '@/stores/auth-store';
import { logout } from '@/lib/api/auth'; import { logout } from '@/lib/api/auth';
@@ -29,11 +30,19 @@ const navigation = [
{ name: 'Config', href: '/configuracion', icon: Settings }, { name: 'Config', href: '/configuracion', icon: Settings },
]; ];
const adminNavigation = [
{ name: 'Clientes', href: '/clientes', icon: Building2 },
];
export function SidebarFloating() { export function SidebarFloating() {
const pathname = usePathname(); const pathname = usePathname();
const router = useRouter(); const router = useRouter();
const { user, logout: clearAuth } = useAuthStore(); const { user, logout: clearAuth } = useAuthStore();
const allNavigation = user?.role === 'admin'
? [...navigation.slice(0, -1), ...adminNavigation, navigation[navigation.length - 1]]
: navigation;
const handleLogout = async () => { const handleLogout = async () => {
try { try {
await logout(); await logout();
@@ -61,7 +70,7 @@ export function SidebarFloating() {
{/* Navigation */} {/* Navigation */}
<nav className="flex-1 space-y-1"> <nav className="flex-1 space-y-1">
{navigation.map((item) => { {allNavigation.map((item) => {
const isActive = pathname === item.href || pathname.startsWith(`${item.href}/`); const isActive = pathname === item.href || pathname.startsWith(`${item.href}/`);
return ( return (
<Link <Link

View File

@@ -13,6 +13,7 @@ import {
Calendar, Calendar,
Bell, Bell,
Users, Users,
Building2,
} from 'lucide-react'; } from 'lucide-react';
import { useAuthStore } from '@/stores/auth-store'; import { useAuthStore } from '@/stores/auth-store';
import { logout } from '@/lib/api/auth'; import { logout } from '@/lib/api/auth';
@@ -29,6 +30,10 @@ const navigation = [
{ name: 'Configuracion', href: '/configuracion', icon: Settings }, { name: 'Configuracion', href: '/configuracion', icon: Settings },
]; ];
const adminNavigation = [
{ name: 'Clientes', href: '/clientes', icon: Building2 },
];
export function Sidebar() { export function Sidebar() {
const pathname = usePathname(); const pathname = usePathname();
const router = useRouter(); const router = useRouter();
@@ -45,6 +50,10 @@ export function Sidebar() {
} }
}; };
const allNavigation = user?.role === 'admin'
? [...navigation.slice(0, -1), ...adminNavigation, navigation[navigation.length - 1]]
: navigation;
return ( return (
<aside className="fixed left-0 top-0 z-40 h-screen w-64 border-r bg-card"> <aside className="fixed left-0 top-0 z-40 h-screen w-64 border-r bg-card">
<div className="flex h-full flex-col"> <div className="flex h-full flex-col">
@@ -60,7 +69,7 @@ export function Sidebar() {
{/* Navigation */} {/* Navigation */}
<nav className="flex-1 space-y-1 px-3 py-4"> <nav className="flex-1 space-y-1 px-3 py-4">
{navigation.map((item) => { {allNavigation.map((item) => {
const isActive = pathname === item.href || pathname.startsWith(`${item.href}/`); const isActive = pathname === item.href || pathname.startsWith(`${item.href}/`);
return ( return (
<Link <Link

View File

@@ -14,6 +14,7 @@ import {
Bell, Bell,
Users, Users,
ChevronDown, ChevronDown,
Building2,
} from 'lucide-react'; } from 'lucide-react';
import { useAuthStore } from '@/stores/auth-store'; import { useAuthStore } from '@/stores/auth-store';
import { logout } from '@/lib/api/auth'; import { logout } from '@/lib/api/auth';
@@ -31,12 +32,20 @@ const navigation = [
{ name: 'Config', href: '/configuracion', icon: Settings }, { name: 'Config', href: '/configuracion', icon: Settings },
]; ];
const adminNavigation = [
{ name: 'Clientes', href: '/clientes', icon: Building2 },
];
export function TopNav() { export function TopNav() {
const pathname = usePathname(); const pathname = usePathname();
const router = useRouter(); const router = useRouter();
const { user, logout: clearAuth } = useAuthStore(); const { user, logout: clearAuth } = useAuthStore();
const [userMenuOpen, setUserMenuOpen] = useState(false); const [userMenuOpen, setUserMenuOpen] = useState(false);
const allNavigation = user?.role === 'admin'
? [...navigation.slice(0, -1), ...adminNavigation, navigation[navigation.length - 1]]
: navigation;
const handleLogout = async () => { const handleLogout = async () => {
try { try {
await logout(); await logout();
@@ -61,7 +70,7 @@ export function TopNav() {
{/* Navigation */} {/* Navigation */}
<nav className="flex-1 flex items-center gap-1"> <nav className="flex-1 flex items-center gap-1">
{navigation.map((item) => { {allNavigation.map((item) => {
const isActive = pathname === item.href || pathname.startsWith(`${item.href}/`); const isActive = pathname === item.href || pathname.startsWith(`${item.href}/`);
return ( return (
<Link <Link

View File

@@ -0,0 +1,146 @@
'use client';
import { useState, useEffect } from 'react';
import { useQuery } from '@tanstack/react-query';
import { getTenants, type Tenant } from '@/lib/api/tenants';
import { useTenantViewStore } from '@/stores/tenant-view-store';
import { useAuthStore } from '@/stores/auth-store';
import { Building, ChevronDown, Check, X } from 'lucide-react';
import { cn } from '@/lib/utils';
export function TenantSelector() {
const [open, setOpen] = useState(false);
const { user } = useAuthStore();
const { viewingTenantId, viewingTenantName, setViewingTenant, clearViewingTenant } = useTenantViewStore();
const { data: tenants, isLoading } = useQuery({
queryKey: ['tenants'],
queryFn: getTenants,
enabled: user?.role === 'admin',
});
// Close dropdown when clicking outside
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
const target = e.target as HTMLElement;
if (!target.closest('.tenant-selector')) {
setOpen(false);
}
};
document.addEventListener('click', handleClickOutside);
return () => document.removeEventListener('click', handleClickOutside);
}, []);
// Only show for admin users
if (user?.role !== 'admin') {
return null;
}
const currentTenant = viewingTenantId
? tenants?.find(t => t.id === viewingTenantId)
: null;
const displayName = viewingTenantName || currentTenant?.nombre || user?.tenantName;
const isViewingOther = viewingTenantId && viewingTenantId !== user?.tenantId;
return (
<div className="tenant-selector relative">
<button
onClick={() => setOpen(!open)}
className={cn(
'flex items-center gap-2 rounded-lg px-3 py-2 text-sm font-medium transition-colors',
isViewingOther
? 'bg-primary/10 text-primary border border-primary/30'
: 'hover:bg-accent'
)}
>
<Building className="h-4 w-4" />
<span className="max-w-[150px] truncate">{displayName}</span>
{isViewingOther && (
<button
onClick={(e) => {
e.stopPropagation();
clearViewingTenant();
window.location.reload();
}}
className="ml-1 p-0.5 rounded hover:bg-primary/20"
title="Volver a mi empresa"
>
<X className="h-3 w-3" />
</button>
)}
<ChevronDown className={cn('h-4 w-4 transition-transform', open && 'rotate-180')} />
</button>
{open && (
<div className="absolute top-full left-0 mt-2 w-72 rounded-lg border bg-card shadow-lg z-50">
<div className="p-2 border-b">
<p className="text-xs text-muted-foreground px-2">Seleccionar cliente</p>
</div>
<div className="max-h-64 overflow-y-auto p-1">
{isLoading ? (
<div className="px-3 py-2 text-sm text-muted-foreground">Cargando...</div>
) : tenants && tenants.length > 0 ? (
<>
{/* Option to go back to own tenant */}
<button
onClick={() => {
clearViewingTenant();
setOpen(false);
window.location.reload();
}}
className={cn(
'flex w-full items-center gap-3 rounded-md px-3 py-2 text-sm hover:bg-accent transition-colors',
!viewingTenantId && 'bg-primary/10'
)}
>
<div className="h-8 w-8 rounded bg-primary/10 flex items-center justify-center">
<Building className="h-4 w-4 text-primary" />
</div>
<div className="flex-1 text-left">
<p className="font-medium">{user?.tenantName}</p>
<p className="text-xs text-muted-foreground">Mi empresa</p>
</div>
{!viewingTenantId && <Check className="h-4 w-4 text-primary" />}
</button>
<div className="my-1 border-t" />
{/* Other tenants */}
{tenants
.filter(t => t.id !== user?.tenantId)
.map((tenant) => (
<button
key={tenant.id}
onClick={() => {
setViewingTenant(tenant.id, tenant.nombre);
setOpen(false);
window.location.reload();
}}
className={cn(
'flex w-full items-center gap-3 rounded-md px-3 py-2 text-sm hover:bg-accent transition-colors',
viewingTenantId === tenant.id && 'bg-primary/10'
)}
>
<div className="h-8 w-8 rounded bg-muted flex items-center justify-center text-xs font-medium">
{tenant.nombre.substring(0, 2).toUpperCase()}
</div>
<div className="flex-1 text-left">
<p className="font-medium truncate">{tenant.nombre}</p>
<p className="text-xs text-muted-foreground">{tenant.rfc}</p>
</div>
{viewingTenantId === tenant.id && <Check className="h-4 w-4 text-primary" />}
</button>
))}
</>
) : (
<div className="px-3 py-2 text-sm text-muted-foreground">
No hay otros clientes
</div>
)}
</div>
</div>
)}
</div>
);
}

View File

@@ -13,6 +13,19 @@ apiClient.interceptors.request.use((config) => {
if (token) { if (token) {
config.headers.Authorization = `Bearer ${token}`; config.headers.Authorization = `Bearer ${token}`;
} }
// Add viewing tenant header for admin users
const tenantViewStore = localStorage.getItem('horux-tenant-view');
if (tenantViewStore) {
try {
const { state } = JSON.parse(tenantViewStore);
if (state?.viewingTenantId) {
config.headers['X-View-Tenant'] = state.viewingTenantId;
}
} catch {
// Ignore parse errors
}
}
} }
return config; return config;
}); });

View File

@@ -0,0 +1,36 @@
import { apiClient } from './client';
export interface Tenant {
id: string;
nombre: string;
rfc: string;
plan: string;
schemaName: string;
createdAt: string;
_count?: {
users: number;
};
}
export interface CreateTenantData {
nombre: string;
rfc: string;
plan?: 'starter' | 'business' | 'professional' | 'enterprise';
cfdiLimit?: number;
usersLimit?: number;
}
export async function getTenants(): Promise<Tenant[]> {
const response = await apiClient.get<Tenant[]>('/tenants');
return response.data;
}
export async function getTenant(id: string): Promise<Tenant> {
const response = await apiClient.get<Tenant>(`/tenants/${id}`);
return response.data;
}
export async function createTenant(data: CreateTenantData): Promise<Tenant> {
const response = await apiClient.post<Tenant>('/tenants', data);
return response.data;
}

View File

@@ -0,0 +1,20 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { getTenants, createTenant, type CreateTenantData } from '@/lib/api/tenants';
export function useTenants() {
return useQuery({
queryKey: ['tenants'],
queryFn: getTenants,
});
}
export function useCreateTenant() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (data: CreateTenantData) => createTenant(data),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['tenants'] });
},
});
}

View File

@@ -0,0 +1,23 @@
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
interface TenantViewState {
viewingTenantId: string | null;
viewingTenantName: string | null;
setViewingTenant: (id: string | null, name: string | null) => void;
clearViewingTenant: () => void;
}
export const useTenantViewStore = create<TenantViewState>()(
persist(
(set) => ({
viewingTenantId: null,
viewingTenantName: null,
setViewingTenant: (id, name) => set({ viewingTenantId: id, viewingTenantName: name }),
clearViewingTenant: () => set({ viewingTenantId: null, viewingTenantName: null }),
}),
{
name: 'horux-tenant-view',
}
)
);