feat: make side panel Cultivos section read-only and place bed badge on the left
This commit is contained in:
@@ -0,0 +1,371 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useHospitalStore } from '@/hooks/useHospitalStore';
|
||||
import type { Usuario, RolUsuario, Grupo } from '@/types';
|
||||
import { Card, CardContent } 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 { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Plus, Pencil, Trash2 } from 'lucide-react';
|
||||
|
||||
const API_BASE = import.meta.env.VITE_API_URL || '/api';
|
||||
|
||||
export function GestionUsuarios() {
|
||||
const { currentUser } = useHospitalStore();
|
||||
const [usuarios, setUsuarios] = useState<Usuario[]>([]);
|
||||
const [grupos, setGrupos] = useState<Grupo[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [editUsuario, setEditUsuario] = useState<Usuario | null>(null);
|
||||
|
||||
const [form, setForm] = useState({
|
||||
apellido: '',
|
||||
nombre: '',
|
||||
dni: '',
|
||||
fechaNacimiento: '',
|
||||
email: '',
|
||||
rol: 'medico' as RolUsuario,
|
||||
matriculaProfesional: '',
|
||||
password: '',
|
||||
grupoId: '',
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
fetchUsuarios();
|
||||
fetchGrupos();
|
||||
}, []);
|
||||
|
||||
const fetchUsuarios = async () => {
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/usuarios`);
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
if (Array.isArray(data)) setUsuarios(data);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const fetchGrupos = async () => {
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/grupos`);
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
if (Array.isArray(data)) setGrupos(data);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
};
|
||||
|
||||
const resetForm = () => {
|
||||
setForm({
|
||||
apellido: '',
|
||||
nombre: '',
|
||||
dni: '',
|
||||
fechaNacimiento: '',
|
||||
email: '',
|
||||
rol: 'medico',
|
||||
matriculaProfesional: '',
|
||||
password: '',
|
||||
grupoId: '',
|
||||
});
|
||||
setEditUsuario(null);
|
||||
};
|
||||
|
||||
const openEdit = (usu: Usuario) => {
|
||||
setEditUsuario(usu);
|
||||
setForm({
|
||||
apellido: usu.apellido,
|
||||
nombre: usu.nombre,
|
||||
dni: usu.dni,
|
||||
fechaNacimiento: usu.fechaNacimiento,
|
||||
email: usu.email,
|
||||
rol: usu.rol,
|
||||
matriculaProfesional: usu.matriculaProfesional || '',
|
||||
password: '',
|
||||
grupoId: usu.grupoId || '',
|
||||
});
|
||||
setDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!form.apellido.trim() || !form.nombre.trim() || !form.dni.trim()) {
|
||||
alert('Por favor ingrese Apellido, Nombre y DNI.');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
let res: Response;
|
||||
if (editUsuario) {
|
||||
res = await fetch(`${API_BASE}/usuarios/${editUsuario.id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(form),
|
||||
});
|
||||
} else {
|
||||
res = await fetch(`${API_BASE}/usuarios`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(form),
|
||||
});
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
const errData = await res.json().catch(() => ({ error: 'Error al guardar usuario' }));
|
||||
alert(errData.error || 'Error al guardar usuario');
|
||||
return;
|
||||
}
|
||||
|
||||
setDialogOpen(false);
|
||||
resetForm();
|
||||
await fetchUsuarios();
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
alert('Error al guardar usuario');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
if (!confirm('¿Está seguro de eliminar este usuario?')) return;
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/usuarios/${id}`, { method: 'DELETE' });
|
||||
if (!res.ok) {
|
||||
const errData = await res.json().catch(() => ({ error: 'Error al eliminar usuario' }));
|
||||
alert(errData.error || 'Error al eliminar usuario');
|
||||
return;
|
||||
}
|
||||
await fetchUsuarios();
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
alert('Error al eliminar usuario');
|
||||
}
|
||||
};
|
||||
|
||||
const getRolLabel = (rol: RolUsuario) => {
|
||||
switch (rol) {
|
||||
case 'admin': return 'Administrador';
|
||||
case 'medico': return 'Médico';
|
||||
case 'enfermero': return 'Enfermero';
|
||||
}
|
||||
};
|
||||
|
||||
const getGrupoName = (grupoId?: string) => {
|
||||
if (!grupoId) return '-';
|
||||
return grupos.find(a => a.id === grupoId)?.nombre || '-';
|
||||
};
|
||||
|
||||
if (!currentUser || currentUser.rol !== 'admin') {
|
||||
return (
|
||||
<div className="p-8 text-center text-red-500 font-semibold">
|
||||
No tiene permisos para acceder al módulo de gestión de usuarios.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return <div>Cargando...</div>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold dark:text-white">Gestión de Usuarios</h1>
|
||||
<p className="text-gray-500 dark:text-gray-400">Administrar usuarios del sistema</p>
|
||||
</div>
|
||||
<Button className="w-full sm:w-auto" onClick={() => { resetForm(); setDialogOpen(true); }}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Nuevo Usuario
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Desktop Table View */}
|
||||
<Card className="hidden md:block">
|
||||
<CardContent className="p-0 overflow-x-auto">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Apellido, Nombre</TableHead>
|
||||
<TableHead>DNI</TableHead>
|
||||
<TableHead>Rol</TableHead>
|
||||
<TableHead>Grupo</TableHead>
|
||||
<TableHead>Email</TableHead>
|
||||
<TableHead>Matrícula</TableHead>
|
||||
<TableHead>Acciones</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{usuarios.map((usu) => (
|
||||
<TableRow key={usu.id}>
|
||||
<TableCell className="font-medium">{usu.apellido}, {usu.nombre}</TableCell>
|
||||
<TableCell>{usu.dni}</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={usu.rol === 'admin' ? 'default' : 'secondary'}>
|
||||
{getRolLabel(usu.rol)}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>{getGrupoName(usu.grupoId)}</TableCell>
|
||||
<TableCell>{usu.email || '-'}</TableCell>
|
||||
<TableCell>{usu.matriculaProfesional || '-'}</TableCell>
|
||||
<TableCell>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="ghost" size="icon" onClick={() => openEdit(usu)}>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button variant="ghost" size="icon" onClick={() => handleDelete(usu.id)}>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Mobile Cards View */}
|
||||
<div className="grid grid-cols-1 gap-3 md:hidden">
|
||||
{usuarios.map((usu) => (
|
||||
<Card key={usu.id} className="p-4 space-y-3">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div>
|
||||
<h3 className="font-semibold text-lg text-gray-900 dark:text-gray-100">
|
||||
{usu.apellido}, {usu.nombre}
|
||||
</h3>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">DNI: {usu.dni}</p>
|
||||
</div>
|
||||
<Badge variant={usu.rol === 'admin' ? 'default' : 'secondary'}>
|
||||
{getRolLabel(usu.rol)}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-2 text-sm pt-2 border-t border-gray-100 dark:border-gray-800">
|
||||
<div>
|
||||
<span className="text-xs text-gray-400 block">Grupo</span>
|
||||
<span className="font-medium text-gray-700 dark:text-gray-300">{getGrupoName(usu.grupoId)}</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-xs text-gray-400 block">Matrícula</span>
|
||||
<span className="font-medium text-gray-700 dark:text-gray-300">{usu.matriculaProfesional || '-'}</span>
|
||||
</div>
|
||||
{usu.email && (
|
||||
<div className="col-span-2">
|
||||
<span className="text-xs text-gray-400 block">Email</span>
|
||||
<span className="font-medium text-gray-700 dark:text-gray-300 truncate block">{usu.email}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2 border-t border-gray-100 dark:border-gray-800">
|
||||
<Button variant="outline" size="sm" onClick={() => openEdit(usu)}>
|
||||
<Pencil className="h-4 w-4 mr-1" />
|
||||
Editar
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" className="text-red-600 hover:text-red-700 dark:text-red-400" onClick={() => handleDelete(usu.id)}>
|
||||
<Trash2 className="h-4 w-4 mr-1" />
|
||||
Eliminar
|
||||
</Button>
|
||||
</div>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Dialog open={dialogOpen} onOpenChange={setDialogOpen}>
|
||||
<DialogContent className="max-w-lg w-[95vw] sm:w-full max-h-[90vh] overflow-y-auto p-4 sm:p-6">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{editUsuario ? 'Editar Usuario' : 'Nuevo Usuario'}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 pt-2">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Apellido</Label>
|
||||
<Input value={form.apellido} onChange={(e) => setForm({ ...form, apellido: e.target.value })} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Nombre</Label>
|
||||
<Input value={form.nombre} onChange={(e) => setForm({ ...form, nombre: e.target.value })} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>DNI</Label>
|
||||
<Input value={form.dni} onChange={(e) => setForm({ ...form, dni: e.target.value })} disabled={!!editUsuario} />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Fecha de Nacimiento</Label>
|
||||
<Input type="date" value={form.fechaNacimiento} onChange={(e) => setForm({ ...form, fechaNacimiento: e.target.value })} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>Email</Label>
|
||||
<Input type="email" value={form.email} onChange={(e) => setForm({ ...form, email: e.target.value })} />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Rol</Label>
|
||||
<Select value={form.rol} onValueChange={(v) => setForm({ ...form, rol: v as RolUsuario })}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="admin">Administrador</SelectItem>
|
||||
<SelectItem value="medico">Médico</SelectItem>
|
||||
<SelectItem value="enfermero">Enfermero</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Matrícula Profesional</Label>
|
||||
<Input value={form.matriculaProfesional} onChange={(e) => setForm({ ...form, matriculaProfesional: e.target.value })} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{form.rol !== 'admin' && (
|
||||
<div className="space-y-2">
|
||||
<Label>Grupo Asignado</Label>
|
||||
<Select value={form.grupoId} onValueChange={(v) => setForm({ ...form, grupoId: v })}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Seleccionar área" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{grupos.map((grupo) => (
|
||||
<SelectItem key={grupo.id} value={grupo.id}>{grupo.nombre}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label>{editUsuario ? 'Nueva Contraseña (opcional)' : 'Contraseña (opcional)'}</Label>
|
||||
<Input
|
||||
type="password"
|
||||
placeholder={editUsuario ? 'Dejar en blanco para no modificar' : 'Por defecto se usará el DNI'}
|
||||
value={form.password}
|
||||
onChange={(e) => setForm({ ...form, password: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col-reverse sm:flex-row justify-end gap-2 mt-4">
|
||||
<Button variant="outline" className="w-full sm:w-auto" onClick={() => setDialogOpen(false)}>Cancelar</Button>
|
||||
<Button className="w-full sm:w-auto" onClick={handleSubmit}>
|
||||
{editUsuario ? 'Actualizar' : 'Crear'}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user