'use client'; import { useState, useEffect } from 'react'; import { DashboardShell } from '@/components/layouts/dashboard-shell'; import { Card, CardContent, CardHeader, CardTitle } 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 { useAllUsuarios, useUpdateUsuarioGlobal, useDeleteUsuarioGlobal } from '@/lib/hooks/use-usuarios'; import { getTenants, type Tenant } from '@/lib/api/tenants'; import { useAuthStore } from '@/stores/auth-store'; import { Users, Pencil, Trash2, Shield, Eye, Calculator, Building2, X, Check } from 'lucide-react'; import { cn } from '@/lib/utils'; const roleLabels = { admin: { label: 'Administrador', icon: Shield, color: 'text-primary' }, contador: { label: 'Contador', icon: Calculator, color: 'text-green-600' }, visor: { label: 'Visor', icon: Eye, color: 'text-muted-foreground' }, }; interface EditingUser { id: string; nombre: string; role: 'admin' | 'contador' | 'visor'; tenantId: string; } export default function AdminUsuariosPage() { const { user: currentUser } = useAuthStore(); const { data: usuarios, isLoading, error } = useAllUsuarios(); const updateUsuario = useUpdateUsuarioGlobal(); const deleteUsuario = useDeleteUsuarioGlobal(); const [tenants, setTenants] = useState([]); const [editingUser, setEditingUser] = useState(null); const [filterTenant, setFilterTenant] = useState('all'); const [searchTerm, setSearchTerm] = useState(''); useEffect(() => { getTenants().then(setTenants).catch(console.error); }, []); const handleEdit = (usuario: any) => { setEditingUser({ id: usuario.id, nombre: usuario.nombre, role: usuario.role, tenantId: usuario.tenantId, }); }; const handleSave = async () => { if (!editingUser) return; try { await updateUsuario.mutateAsync({ id: editingUser.id, data: { nombre: editingUser.nombre, role: editingUser.role, tenantId: editingUser.tenantId, }, }); setEditingUser(null); } catch (err: any) { alert(err.response?.data?.error || 'Error al actualizar usuario'); } }; const handleDelete = async (id: string) => { if (!confirm('Estas seguro de eliminar este usuario?')) return; try { await deleteUsuario.mutateAsync(id); } catch (err: any) { alert(err.response?.data?.error || 'Error al eliminar usuario'); } }; const filteredUsuarios = usuarios?.filter(u => { const matchesTenant = filterTenant === 'all' || u.tenantId === filterTenant; const matchesSearch = !searchTerm || u.nombre.toLowerCase().includes(searchTerm.toLowerCase()) || u.email.toLowerCase().includes(searchTerm.toLowerCase()); return matchesTenant && matchesSearch; }); // Agrupar por empresa const groupedByTenant = filteredUsuarios?.reduce((acc, u) => { const key = u.tenantId || 'sin-empresa'; if (!acc[key]) { acc[key] = { tenantName: u.tenantName || 'Sin empresa', users: [], }; } acc[key].users.push(u); return acc; }, {} as Record); if (error) { return (

No tienes permisos para ver esta pagina o ocurrio un error.

); } return (
{/* Filtros */}
setSearchTerm(e.target.value)} />
{/* Stats */}
{filteredUsuarios?.length || 0} usuarios
{Object.keys(groupedByTenant || {}).length} empresas
{/* Users by tenant */} {isLoading ? ( Cargando usuarios... ) : ( Object.entries(groupedByTenant || {}).map(([tenantId, { tenantName, users }]) => ( {tenantName} ({users?.length} usuarios)
{users?.map(usuario => { const roleInfo = roleLabels[usuario.role]; const RoleIcon = roleInfo.icon; const isCurrentUser = usuario.id === currentUser?.id; const isEditing = editingUser?.id === usuario.id; return (
{usuario.nombre.charAt(0).toUpperCase()}
{isEditing ? (
setEditingUser({ ...editingUser, nombre: e.target.value })} className="h-8" />
) : ( <>
{usuario.nombre} {isCurrentUser && ( Tu )} {!usuario.active && ( Inactivo )}
{usuario.email}
)}
{!isEditing && (
{roleInfo.label}
)} {!isCurrentUser && (
{isEditing ? ( <> ) : ( <> )}
)}
); })}
)) )}
); }