feat: make side panel Cultivos section read-only and place bed badge on the left
This commit is contained in:
@@ -0,0 +1,455 @@
|
||||
import { useState } from 'react';
|
||||
import { Activity, Plus, Search, Calendar, Clock } from 'lucide-react';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import type { AcidoBase, Paciente } from '@/types';
|
||||
|
||||
interface AcidoBaseProps {
|
||||
acidosBase: AcidoBase[];
|
||||
pacientes: Paciente[];
|
||||
onAgregarAcidoBase: (acidoBase: Omit<AcidoBase, 'id'>) => void;
|
||||
onEliminarAcidoBase: (id: string) => void;
|
||||
getPacienteById: (id: string) => Paciente | undefined;
|
||||
}
|
||||
|
||||
const REFERENCIAS = {
|
||||
ph: { min: 7.35, max: 7.45, unidad: '' },
|
||||
pco2: { min: 35, max: 45, unidad: 'mmHg' },
|
||||
po2: { min: 80, max: 100, unidad: 'mmHg' },
|
||||
hco3: { min: 22, max: 26, unidad: 'mEq/L' },
|
||||
be: { min: -2, max: 2, unidad: 'mEq/L' },
|
||||
sato2: { min: 95, max: 100, unidad: '%' },
|
||||
lactato: { min: 0.5, max: 2.2, unidad: 'mmol/L' },
|
||||
};
|
||||
|
||||
export function AcidoBaseSection({
|
||||
acidosBase,
|
||||
pacientes,
|
||||
onAgregarAcidoBase,
|
||||
onEliminarAcidoBase,
|
||||
getPacienteById,
|
||||
}: AcidoBaseProps) {
|
||||
const [busqueda, setBusqueda] = useState('');
|
||||
const [dialogoAbierto, setDialogoAbierto] = useState(false);
|
||||
|
||||
// Formulario
|
||||
const [pacienteSeleccionado, setPacienteSeleccionado] = useState('');
|
||||
const [busquedaPaciente, setBusquedaPaciente] = useState('');
|
||||
const [fecha, setFecha] = useState(new Date().toISOString().split('T')[0]);
|
||||
const [hora, setHora] = useState(new Date().toTimeString().slice(0, 5));
|
||||
const [ph, setPh] = useState('');
|
||||
const [pco2, setPco2] = useState('');
|
||||
const [po2, setPo2] = useState('');
|
||||
const [hco3, setHco3] = useState('');
|
||||
const [be, setBe] = useState('');
|
||||
const [sato2, setSato2] = useState('');
|
||||
const [lactato, setLactato] = useState('');
|
||||
const [interpretacion, setInterpretacion] = useState('');
|
||||
|
||||
const resetFormulario = () => {
|
||||
setPacienteSeleccionado('');
|
||||
setBusquedaPaciente('');
|
||||
setFecha(new Date().toISOString().split('T')[0]);
|
||||
setHora(new Date().toTimeString().slice(0, 5));
|
||||
setPh('');
|
||||
setPco2('');
|
||||
setPo2('');
|
||||
setHco3('');
|
||||
setBe('');
|
||||
setSato2('');
|
||||
setLactato('');
|
||||
setInterpretacion('');
|
||||
};
|
||||
|
||||
const getEstadoParametro = (parametro: keyof typeof REFERENCIAS, valor: number) => {
|
||||
const ref = REFERENCIAS[parametro];
|
||||
if (valor < ref.min) return { estado: 'Bajo', color: 'text-blue-600' };
|
||||
if (valor > ref.max) return { estado: 'Alto', color: 'text-red-600' };
|
||||
return { estado: 'Normal', color: 'text-green-600' };
|
||||
};
|
||||
|
||||
const pacientesFiltrados = pacientes.filter(p => {
|
||||
if (!busquedaPaciente) return true;
|
||||
const texto = `${p.apellido} ${p.nombre} ${p.dni}`.toLowerCase();
|
||||
return texto.includes(busquedaPaciente.toLowerCase());
|
||||
});
|
||||
|
||||
const interpretarGasometria = () => {
|
||||
const phVal = parseFloat(ph);
|
||||
const pco2Val = parseFloat(pco2);
|
||||
const hco3Val = parseFloat(hco3);
|
||||
const beVal = parseFloat(be);
|
||||
|
||||
if (!phVal || !pco2Val || !hco3Val) return '';
|
||||
|
||||
let interpretacion = '';
|
||||
|
||||
// Determinar acidosis o alcalosis
|
||||
if (phVal < 7.35) {
|
||||
interpretacion += 'Acidemia - ';
|
||||
if (pco2Val > 45) interpretacion += 'Acidosis Respiratoria';
|
||||
else if (hco3Val < 22) interpretacion += 'Acidosis Metabólica';
|
||||
else interpretacion += 'Acidosis Mixta';
|
||||
} else if (phVal > 7.45) {
|
||||
interpretacion += 'Alcalemia - ';
|
||||
if (pco2Val < 35) interpretacion += 'Alcalosis Respiratoria';
|
||||
else if (hco3Val > 26) interpretacion += 'Alcalosis Metabólica';
|
||||
else interpretacion += 'Alcalosis Mixta';
|
||||
} else {
|
||||
interpretacion += 'pH Normal - ';
|
||||
if (pco2Val > 45 || hco3Val < 22) interpretacion += 'Compensación en curso';
|
||||
else interpretacion += 'Equilibrio Ácido-Base';
|
||||
}
|
||||
|
||||
// Agregar información sobre compensación
|
||||
if (beVal && Math.abs(beVal) > 2) {
|
||||
interpretacion += beVal > 0 ? ' (Exceso de bases elevado)' : ' (Déficit de bases)';
|
||||
}
|
||||
|
||||
return interpretacion;
|
||||
};
|
||||
|
||||
const handleGuardar = () => {
|
||||
if (!pacienteSeleccionado || !ph || !pco2 || !po2 || !hco3 || !be || !sato2) return;
|
||||
|
||||
const interpretacionAuto = interpretarGasometria();
|
||||
|
||||
onAgregarAcidoBase({
|
||||
pacienteId: pacienteSeleccionado,
|
||||
fecha,
|
||||
hora,
|
||||
ph: parseFloat(ph),
|
||||
pco2: parseFloat(pco2),
|
||||
po2: parseFloat(po2),
|
||||
hco3: parseFloat(hco3),
|
||||
be: parseFloat(be),
|
||||
sato2: parseFloat(sato2),
|
||||
lactato: lactato ? parseFloat(lactato) : undefined,
|
||||
interpretacion: interpretacion || interpretacionAuto,
|
||||
});
|
||||
|
||||
resetFormulario();
|
||||
setDialogoAbierto(false);
|
||||
};
|
||||
|
||||
const acidosBaseFiltrados = acidosBase
|
||||
.filter(ab => {
|
||||
const paciente = getPacienteById(ab.pacienteId);
|
||||
if (!paciente) return false;
|
||||
|
||||
return !busqueda ||
|
||||
paciente.nombre.toLowerCase().includes(busqueda.toLowerCase()) ||
|
||||
paciente.apellido.toLowerCase().includes(busqueda.toLowerCase()) ||
|
||||
paciente.dni.includes(busqueda);
|
||||
})
|
||||
.sort((a, b) => new Date(b.fecha + 'T' + b.hora).getTime() - new Date(a.fecha + 'T' + a.hora).getTime());
|
||||
|
||||
const getColorPh = (ph: number) => {
|
||||
if (ph < 7.2 || ph > 7.6) return 'bg-red-100 text-red-800';
|
||||
if (ph < 7.35 || ph > 7.45) return 'bg-amber-100 text-amber-800';
|
||||
return 'bg-green-100 text-green-800';
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6 dark:text-white">
|
||||
{/* Header */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900 dark:text-white">Estados Ácido-Base</h1>
|
||||
<p className="text-gray-500 dark:text-gray-400">Gasometrías y análisis de equilibrio ácido-base</p>
|
||||
</div>
|
||||
<Dialog open={dialogoAbierto} onOpenChange={setDialogoAbierto}>
|
||||
<DialogTrigger asChild>
|
||||
<Button onClick={resetFormulario}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Nueva Gasometría
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-3xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Nueva Gasometría Arterial</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||||
<div className="sm:col-span-3">
|
||||
{!pacienteSeleccionado ? (
|
||||
<div>
|
||||
<Label>Buscar Paciente *</Label>
|
||||
<Input
|
||||
value={busquedaPaciente}
|
||||
onChange={(e) => setBusquedaPaciente(e.target.value)}
|
||||
placeholder="Ingrese apellido, nombre o DNI..."
|
||||
autoFocus
|
||||
/>
|
||||
{busquedaPaciente && (
|
||||
<div className="mt-2 border rounded-md max-h-48 overflow-y-auto">
|
||||
{pacientesFiltrados.length === 0 ? (
|
||||
<p className="p-3 text-sm text-gray-500">No se encontraron pacientes</p>
|
||||
) : (
|
||||
pacientesFiltrados.map(p => (
|
||||
<button
|
||||
key={p.id}
|
||||
type="button"
|
||||
onClick={() => setPacienteSeleccionado(p.id)}
|
||||
className="w-full text-left p-3 hover:bg-gray-50 border-b last:border-b-0"
|
||||
>
|
||||
{p.apellido}, {p.nombre} - DNI: {p.dni}
|
||||
</button>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<Badge className="bg-green-100 text-green-800 px-3 py-1">
|
||||
{(() => {
|
||||
const p = pacientes.find(x => x.id === pacienteSeleccionado);
|
||||
return p ? `${p.apellido}, ${p.nombre} - DNI: ${p.dni}` : '';
|
||||
})()}
|
||||
</Badge>
|
||||
<Button size="sm" variant="ghost" onClick={() => setPacienteSeleccionado('')}>Cambiar</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<Label>Fecha *</Label>
|
||||
<Input type="date" value={fecha} onChange={(e) => setFecha(e.target.value)} />
|
||||
</div>
|
||||
<div>
|
||||
<Label>Hora *</Label>
|
||||
<Input type="time" value={hora} onChange={(e) => setHora(e.target.value)} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-7 gap-2">
|
||||
<div>
|
||||
<Label>pH *</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="0.01"
|
||||
value={ph}
|
||||
onChange={(e) => setPh(e.target.value)}
|
||||
placeholder="7.40"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>pCO2 *</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={pco2}
|
||||
onChange={(e) => setPco2(e.target.value)}
|
||||
placeholder="40"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>pO2 *</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={po2}
|
||||
onChange={(e) => setPo2(e.target.value)}
|
||||
placeholder="85"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>HCO3- *</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="0.1"
|
||||
value={hco3}
|
||||
onChange={(e) => setHco3(e.target.value)}
|
||||
placeholder="24"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>BE *</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="0.1"
|
||||
value={be}
|
||||
onChange={(e) => setBe(e.target.value)}
|
||||
placeholder="0"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>SatO2 *</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={sato2}
|
||||
onChange={(e) => setSato2(e.target.value)}
|
||||
placeholder="97"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Lactato</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="0.1"
|
||||
value={lactato}
|
||||
onChange={(e) => setLactato(e.target.value)}
|
||||
placeholder="1.0"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{ph && pco2 && hco3 && (
|
||||
<div className="bg-blue-50 p-3 rounded-lg border border-blue-200">
|
||||
<p className="text-sm font-medium text-blue-800 flex items-center gap-2">
|
||||
<Activity className="h-4 w-4" />
|
||||
Interpretación automática: {interpretarGasometria()}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<Label>Interpretación / Comentarios</Label>
|
||||
<textarea
|
||||
className="w-full p-2 border rounded-md text-sm min-h-[80px]"
|
||||
value={interpretacion}
|
||||
onChange={(e) => setInterpretacion(e.target.value)}
|
||||
placeholder="Interpretación clínica..."
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 mt-4">
|
||||
<Button variant="outline" onClick={() => {
|
||||
resetFormulario();
|
||||
setDialogoAbierto(false);
|
||||
}}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleGuardar}
|
||||
disabled={!pacienteSeleccionado || !ph || !pco2 || !po2 || !hco3 || !be || !sato2}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Guardar Gasometría
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
{/* Búsqueda */}
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
|
||||
<Input
|
||||
className="pl-10"
|
||||
placeholder="Buscar por paciente..."
|
||||
value={busqueda}
|
||||
onChange={(e) => setBusqueda(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Lista de Gasometrías */}
|
||||
<div className="space-y-4">
|
||||
{acidosBaseFiltrados.map((ab) => {
|
||||
const paciente = getPacienteById(ab.pacienteId);
|
||||
const phEstado = getEstadoParametro('ph', ab.ph);
|
||||
|
||||
return (
|
||||
<Card key={ab.id} className="hover:shadow-md transition-shadow">
|
||||
<CardContent className="p-4">
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="h-10 w-10 bg-teal-100 rounded-full flex items-center justify-center">
|
||||
<Activity className="h-5 w-5 text-teal-600" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 className="font-bold">
|
||||
{paciente ? `${paciente.apellido}, ${paciente.nombre}` : 'Paciente no encontrado'}
|
||||
</h3>
|
||||
<div className="flex items-center gap-3 text-sm text-gray-500">
|
||||
<span className="flex items-center gap-1">
|
||||
<Calendar className="h-3 w-3" />
|
||||
{ab.fecha}
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<Clock className="h-3 w-3" />
|
||||
{ab.hora}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge className={getColorPh(ab.ph)}>
|
||||
pH: {ab.ph}
|
||||
</Badge>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-red-600 hover:bg-red-50"
|
||||
onClick={() => onEliminarAcidoBase(ab.id)}
|
||||
>
|
||||
Eliminar
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-3 sm:grid-cols-7 gap-2">
|
||||
<div className="bg-gray-50 p-2 rounded text-center">
|
||||
<p className="text-xs text-gray-500">pH</p>
|
||||
<p className={`font-bold ${phEstado.color}`}>{ab.ph}</p>
|
||||
</div>
|
||||
<div className="bg-gray-50 p-2 rounded text-center">
|
||||
<p className="text-xs text-gray-500">pCO2</p>
|
||||
<p className="font-bold">{ab.pco2}</p>
|
||||
</div>
|
||||
<div className="bg-gray-50 p-2 rounded text-center">
|
||||
<p className="text-xs text-gray-500">pO2</p>
|
||||
<p className="font-bold">{ab.po2}</p>
|
||||
</div>
|
||||
<div className="bg-gray-50 p-2 rounded text-center">
|
||||
<p className="text-xs text-gray-500">HCO3</p>
|
||||
<p className="font-bold">{ab.hco3}</p>
|
||||
</div>
|
||||
<div className="bg-gray-50 p-2 rounded text-center">
|
||||
<p className="text-xs text-gray-500">BE</p>
|
||||
<p className="font-bold">{ab.be}</p>
|
||||
</div>
|
||||
<div className="bg-gray-50 p-2 rounded text-center">
|
||||
<p className="text-xs text-gray-500">SatO2</p>
|
||||
<p className="font-bold">{ab.sato2}%</p>
|
||||
</div>
|
||||
{ab.lactato && (
|
||||
<div className="bg-gray-50 p-2 rounded text-center">
|
||||
<p className="text-xs text-gray-500">Lactato</p>
|
||||
<p className="font-bold">{ab.lactato}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{ab.interpretacion && (
|
||||
<div className="bg-teal-50 p-3 rounded-lg border border-teal-200">
|
||||
<p className="text-sm font-medium text-teal-800 flex items-center gap-2">
|
||||
Interpretación: {ab.interpretacion}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{acidosBaseFiltrados.length === 0 && (
|
||||
<div className="text-center py-12 text-gray-400">
|
||||
<Activity className="h-16 w-16 mx-auto mb-4 opacity-50" />
|
||||
<p className="text-lg">
|
||||
{busqueda ? 'No se encontraron gasometrías con esa búsqueda' : 'No hay gasometrías registradas'}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
import { useState } from 'react';
|
||||
import { Microscope, Search, Calendar, AlertCircle, CheckCircle2 } from 'lucide-react';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import type { Cultivo, Paciente, Cama, Internacion } from '@/types';
|
||||
|
||||
interface CultivosProps {
|
||||
cultivos: Cultivo[];
|
||||
pacientes?: Paciente[];
|
||||
internaciones?: Internacion[];
|
||||
camas?: Cama[];
|
||||
patient?: Paciente;
|
||||
internacionId?: string;
|
||||
onAgregarCultivo?: (cultivo: Omit<Cultivo, 'id'>) => void;
|
||||
onActualizarCultivo?: (id: string, datos: Partial<Cultivo>) => void;
|
||||
onEliminarCultivo?: (id: string) => void;
|
||||
getPacienteById?: (id: string) => Paciente | undefined;
|
||||
getInternacionActivaByPaciente?: (pacienteId: string) => Internacion | undefined;
|
||||
canEdit?: boolean;
|
||||
}
|
||||
|
||||
export function Cultivos({
|
||||
cultivos,
|
||||
pacientes = [],
|
||||
internaciones = [],
|
||||
camas = [],
|
||||
patient,
|
||||
getPacienteById,
|
||||
}: CultivosProps) {
|
||||
const [busqueda, setBusqueda] = useState('');
|
||||
const [filtroEstado, setFiltroEstado] = useState<'todos' | 'NAF/Pendiente' | 'Parcial' | 'Positivo' | 'Negativo'>('todos');
|
||||
|
||||
const findPaciente = (pacienteId: string): Paciente | undefined => {
|
||||
if (patient && patient.id === pacienteId) return patient;
|
||||
if (getPacienteById) return getPacienteById(pacienteId);
|
||||
return pacientes.find(p => p.id === pacienteId);
|
||||
};
|
||||
|
||||
const getCamaNombreForPaciente = (pacienteId: string) => {
|
||||
const inter = internaciones.find(i => i.pacienteId === pacienteId && i.activa);
|
||||
if (!inter) return '';
|
||||
const cama = camas.find(c => c.id === inter.camaId);
|
||||
return cama ? `Cama ${cama.numero}` : '';
|
||||
};
|
||||
|
||||
const cultivosFiltrados = cultivos.filter(c => {
|
||||
if (filtroEstado !== 'todos' && c.estado !== filtroEstado) return false;
|
||||
if (busqueda) {
|
||||
const term = busqueda.toLowerCase();
|
||||
const pac = findPaciente(c.pacienteId);
|
||||
const nombrePac = pac ? `${pac.apellido} ${pac.nombre} ${pac.dni}`.toLowerCase() : '';
|
||||
return (
|
||||
c.protocolo?.toLowerCase().includes(term) ||
|
||||
c.germen?.toLowerCase().includes(term) ||
|
||||
c.tipoMuestra.toLowerCase().includes(term) ||
|
||||
nombrePac.includes(term)
|
||||
);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
const getEstadoColor = (estado: string) => {
|
||||
switch (estado) {
|
||||
case 'NAF/Pendiente': return 'bg-amber-100 text-amber-800 dark:bg-amber-950/80 dark:text-amber-300 dark:border dark:border-amber-800';
|
||||
case 'Parcial': return 'bg-orange-100 text-orange-800 dark:bg-orange-950/80 dark:text-orange-300 dark:border dark:border-orange-800';
|
||||
case 'Positivo': return 'bg-red-100 text-red-800 dark:bg-red-950/80 dark:text-red-300 dark:border dark:border-red-800';
|
||||
case 'Negativo': return 'bg-green-100 text-green-800 dark:bg-green-950/80 dark:text-green-300 dark:border dark:border-green-800';
|
||||
default: return 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-300';
|
||||
}
|
||||
};
|
||||
|
||||
const getEstadoLabel = (estado: string) => {
|
||||
switch (estado) {
|
||||
case 'NAF/Pendiente': return 'NAF';
|
||||
case 'Parcial': return 'Parcial';
|
||||
case 'Positivo': return 'Positivo';
|
||||
case 'Negativo': return 'Negativo';
|
||||
default: return estado;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between">
|
||||
<div className="flex-1 flex gap-2">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-2 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-500" />
|
||||
<Input
|
||||
placeholder="Buscar por protocolo, germen, paciente..."
|
||||
value={busqueda}
|
||||
onChange={(e) => setBusqueda(e.target.value)}
|
||||
className="pl-8"
|
||||
/>
|
||||
</div>
|
||||
<Select value={filtroEstado} onValueChange={(v) => setFiltroEstado(v as Cultivo['estado'] | 'todos')}>
|
||||
<SelectTrigger className="w-[180px]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="todos">Todos</SelectItem>
|
||||
<SelectItem value="NAF/Pendiente">NAF/Pendiente</SelectItem>
|
||||
<SelectItem value="Parcial">Parcial</SelectItem>
|
||||
<SelectItem value="Positivo">Positivo</SelectItem>
|
||||
<SelectItem value="Negativo">Negativo</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
{cultivosFiltrados.map((cultivo) => {
|
||||
const pac = findPaciente(cultivo.pacienteId);
|
||||
const camaNombre = getCamaNombreForPaciente(cultivo.pacienteId);
|
||||
|
||||
return (
|
||||
<Card key={cultivo.id} className="hover:shadow-md transition-shadow">
|
||||
<CardContent className="p-4">
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-2">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className={`h-10 w-10 rounded-full flex items-center justify-center shrink-0 ${
|
||||
cultivo.estado === 'NAF/Pendiente' ? 'bg-amber-100 dark:bg-amber-950/80' :
|
||||
cultivo.estado === 'Parcial' ? 'bg-orange-100 dark:bg-orange-950/80' :
|
||||
cultivo.estado === 'Positivo' ? 'bg-red-100 dark:bg-red-950/80' : 'bg-green-100 dark:bg-green-950/80'
|
||||
}`}>
|
||||
<Microscope className={`h-5 w-5 ${
|
||||
cultivo.estado === 'NAF/Pendiente' ? 'text-amber-600 dark:text-amber-400' :
|
||||
cultivo.estado === 'Parcial' ? 'text-orange-600 dark:text-orange-400' :
|
||||
cultivo.estado === 'Positivo' ? 'text-red-600 dark:text-red-400' : 'text-green-600 dark:text-green-400'
|
||||
}`} />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
{camaNombre && (
|
||||
<Badge variant="outline" className="text-xs shrink-0 font-semibold bg-blue-50 text-blue-700 dark:bg-blue-950/80 dark:text-blue-300 dark:border-blue-800">
|
||||
{camaNombre}
|
||||
</Badge>
|
||||
)}
|
||||
<h3 className="font-bold text-sm sm:text-base truncate">
|
||||
{pac ? `${pac.apellido}, ${pac.nombre}` : 'Paciente no encontrado'}
|
||||
</h3>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2 text-xs sm:text-sm text-gray-500 mt-1">
|
||||
<span className="flex items-center gap-1">
|
||||
<Calendar className="h-3 w-3" />
|
||||
{cultivo.fechaToma}
|
||||
</span>
|
||||
<Badge variant="outline" className="text-xs">{cultivo.tipoMuestra}</Badge>
|
||||
<Badge className={`text-xs ${getEstadoColor(cultivo.estado)}`}>
|
||||
{getEstadoLabel(cultivo.estado)}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{cultivo.protocolo && (
|
||||
<p className="text-xs text-gray-500">
|
||||
Protocolo: {cultivo.protocolo}
|
||||
</p>
|
||||
)}
|
||||
{cultivo.observaciones && (
|
||||
<p className="text-sm text-gray-600 dark:text-gray-300 bg-gray-50 dark:bg-gray-800 p-2 rounded">
|
||||
{cultivo.observaciones}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{cultivo.estado === 'Parcial' && cultivo.germen && (
|
||||
<div className="bg-orange-50 p-3 rounded-lg border border-orange-200">
|
||||
<p className="text-sm font-medium text-orange-800 flex items-center gap-2">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
PARCIAL - Germen: {cultivo.germen}
|
||||
</p>
|
||||
{(cultivo.sensible || cultivo.resistente) && (
|
||||
<div className="mt-2 space-y-1">
|
||||
{cultivo.sensible && (
|
||||
<p className="text-xs text-orange-700">Sensible: {cultivo.sensible}</p>
|
||||
)}
|
||||
{cultivo.resistente && (
|
||||
<p className="text-xs text-orange-700">Resistente: {cultivo.resistente}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{cultivo.estado === 'Positivo' && cultivo.germen && (
|
||||
<div className="bg-red-50 p-3 rounded-lg border border-red-200">
|
||||
<p className="text-sm font-medium text-red-800 flex items-center gap-2">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
Germen: {cultivo.germen}
|
||||
</p>
|
||||
{cultivo.fechaResultado && (
|
||||
<p className="text-xs text-red-600 mt-1">
|
||||
Resultado: {cultivo.fechaResultado}
|
||||
</p>
|
||||
)}
|
||||
{(cultivo.sensible || cultivo.resistente) && (
|
||||
<div className="mt-2 space-y-2">
|
||||
{cultivo.sensible && (
|
||||
<div>
|
||||
<p className="text-xs font-medium text-green-700 mb-1">Sensible a:</p>
|
||||
<p className="text-sm text-green-800">{cultivo.sensible}</p>
|
||||
</div>
|
||||
)}
|
||||
{cultivo.resistente && (
|
||||
<div>
|
||||
<p className="text-xs font-medium text-red-700 mb-1">Resistente a:</p>
|
||||
<p className="text-sm text-red-800">{cultivo.resistente}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{cultivo.estado === 'Negativo' && (
|
||||
<div className="bg-green-50 p-3 rounded-lg border border-green-200">
|
||||
<p className="text-sm font-medium text-green-800 flex items-center gap-2">
|
||||
<CheckCircle2 className="h-4 w-4" />
|
||||
Cultivo Negativo
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
|
||||
{cultivosFiltrados.length === 0 && (
|
||||
<p className="text-center text-gray-500 py-8">
|
||||
No se encontraron cultivos con los filtros seleccionados
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
import {
|
||||
Bed,
|
||||
Users,
|
||||
ClipboardList,
|
||||
FlaskConical,
|
||||
Activity,
|
||||
Microscope,
|
||||
TrendingUp,
|
||||
AlertCircle,
|
||||
CheckCircle2,
|
||||
Clock
|
||||
} from 'lucide-react';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { formatDateDDMMYYYY } from '@/lib/utils';
|
||||
import type { Vista, Internacion, Paciente, Cultivo } from '@/types';
|
||||
|
||||
interface DashboardProps {
|
||||
estadisticas: {
|
||||
camasOcupadas: number;
|
||||
camasDisponibles: number;
|
||||
camasMantenimiento: number;
|
||||
totalCamas: number;
|
||||
totalCamasActivas: number;
|
||||
camasFueraDeArea: number;
|
||||
internacionesActivas: number;
|
||||
totalPacientes: number;
|
||||
cultivosPendientes: number;
|
||||
porcentajeOcupacion: number;
|
||||
};
|
||||
internaciones: Internacion[];
|
||||
cultivos: Cultivo[];
|
||||
onCambiarVista: (vista: Vista) => void;
|
||||
getPacienteById: (id: string) => Paciente | undefined;
|
||||
}
|
||||
|
||||
export function Dashboard({
|
||||
estadisticas,
|
||||
internaciones,
|
||||
cultivos,
|
||||
onCambiarVista,
|
||||
getPacienteById
|
||||
}: DashboardProps) {
|
||||
const internacionesActivas = internaciones.filter(i => i.activa).slice(0, 5);
|
||||
const cultivosRecientes = cultivos
|
||||
.filter(c => c.estado === 'NAF/Pendiente')
|
||||
.slice(0, 5);
|
||||
|
||||
return (
|
||||
<div className="space-y-6 dark:text-white">
|
||||
{/* Header */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900 dark:text-white">Dashboard</h1>
|
||||
<p className="text-gray-500 dark:text-gray-400">Resumen del servicio - Clinica Medica</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="outline" className="bg-green-50 text-green-700 border-green-200 dark:bg-green-900 dark:text-green-300 dark:border-green-700">
|
||||
<CheckCircle2 className="h-3 w-3 mr-1" />
|
||||
Sistema Operativo
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Estadísticas Principales */}
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||
<Card className="border-l-4 border-l-blue-500">
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-gray-500 dark:text-gray-400 flex items-center gap-2">
|
||||
<Bed className="h-4 w-4" />
|
||||
Ocupación de Camas
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className="text-3xl font-bold">{estadisticas.porcentajeOcupacion}%</span>
|
||||
<span className="text-sm text-gray-500 dark:text-gray-400">{estadisticas.camasOcupadas}/{estadisticas.totalCamasActivas}</span>
|
||||
</div>
|
||||
<p className="text-xs text-gray-400 dark:text-gray-400 mt-1">
|
||||
{estadisticas.camasDisponibles} camas disponibles
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="border-l-4 border-l-green-500">
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-gray-500 dark:text-gray-400 flex items-center gap-2">
|
||||
<Users className="h-4 w-4" />
|
||||
Camas fuera de área
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className="text-3xl font-bold">{estadisticas.camasFueraDeArea}</span>
|
||||
</div>
|
||||
<p className="text-xs text-gray-400 dark:text-gray-400 mt-1">
|
||||
Total de camas fuera de área
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="border-l-4 border-l-purple-500">
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-gray-500 dark:text-gray-400 flex items-center gap-2">
|
||||
<ClipboardList className="h-4 w-4" />
|
||||
Internaciones Activas
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className="text-3xl font-bold">{estadisticas.internacionesActivas}</span>
|
||||
</div>
|
||||
<p className="text-xs text-gray-400 dark:text-gray-400 mt-1">
|
||||
En curso actualmente
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="border-l-4 border-l-amber-500">
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-sm font-medium text-gray-500 dark:text-gray-400 flex items-center gap-2">
|
||||
<Microscope className="h-4 w-4" />
|
||||
Cultivos Pendientes
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-baseline gap-2">
|
||||
<span className="text-3xl font-bold">{estadisticas.cultivosPendientes}</span>
|
||||
</div>
|
||||
<p className="text-xs text-gray-400 dark:text-gray-400 mt-1">
|
||||
Esperando resultados
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Contenido Principal */}
|
||||
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
{/* Estado de Camas */}
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<Bed className="h-5 w-5 text-blue-600 dark:text-blue-400" />
|
||||
Estado de Camas
|
||||
</CardTitle>
|
||||
<Button variant="ghost" size="sm" onClick={() => onCambiarVista('camas')}>
|
||||
Ver todas
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="bg-green-50 dark:bg-green-950/60 border border-transparent dark:border-green-800/50 p-3 rounded-lg">
|
||||
<div className="flex items-center gap-2">
|
||||
<CheckCircle2 className="h-4 w-4 text-green-600 dark:text-green-400" />
|
||||
<span className="text-sm font-medium text-green-800 dark:text-green-300">Disponibles</span>
|
||||
</div>
|
||||
<p className="text-2xl font-bold text-green-700 dark:text-green-200 mt-1">{estadisticas.camasDisponibles}</p>
|
||||
</div>
|
||||
<div className="bg-red-50 dark:bg-red-950/60 border border-transparent dark:border-red-800/50 p-3 rounded-lg">
|
||||
<div className="flex items-center gap-2">
|
||||
<AlertCircle className="h-4 w-4 text-red-600 dark:text-red-400" />
|
||||
<span className="text-sm font-medium text-red-800 dark:text-red-300">Ocupadas</span>
|
||||
</div>
|
||||
<p className="text-2xl font-bold text-red-700 dark:text-red-200 mt-1">{estadisticas.camasOcupadas}</p>
|
||||
</div>
|
||||
<div className="bg-amber-50 dark:bg-amber-950/60 border border-transparent dark:border-amber-800/50 p-3 rounded-lg">
|
||||
<div className="flex items-center gap-2">
|
||||
<Clock className="h-4 w-4 text-amber-600 dark:text-amber-400" />
|
||||
<span className="text-sm font-medium text-amber-800 dark:text-amber-300">Mantenimiento</span>
|
||||
</div>
|
||||
<p className="text-2xl font-bold text-amber-700 dark:text-amber-200 mt-1">{estadisticas.camasMantenimiento}</p>
|
||||
</div>
|
||||
<div className="bg-blue-50 dark:bg-blue-950/60 border border-transparent dark:border-blue-800/50 p-3 rounded-lg">
|
||||
<div className="flex items-center gap-2">
|
||||
<TrendingUp className="h-4 w-4 text-blue-600 dark:text-blue-400" />
|
||||
<span className="text-sm font-medium text-blue-800 dark:text-blue-300">Ocupación</span>
|
||||
</div>
|
||||
<p className="text-2xl font-bold text-blue-700 dark:text-blue-200 mt-1">{estadisticas.porcentajeOcupacion}%</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Internaciones Activas */}
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<ClipboardList className="h-5 w-5 text-purple-600" />
|
||||
Internaciones Activas
|
||||
</CardTitle>
|
||||
<Button variant="ghost" size="sm" onClick={() => onCambiarVista('internaciones')}>
|
||||
Ver todas
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{internacionesActivas.length === 0 ? (
|
||||
<div className="text-center py-8 text-gray-400">
|
||||
<ClipboardList className="h-12 w-12 mx-auto mb-2 opacity-50" />
|
||||
<p>No hay internaciones activas</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{internacionesActivas.map((internacion) => {
|
||||
const paciente = getPacienteById(internacion.pacienteId);
|
||||
return (
|
||||
<div key={internacion.id} className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-800/80 border border-transparent dark:border-gray-700/50 rounded-lg">
|
||||
<div>
|
||||
<p className="font-medium text-gray-900 dark:text-gray-100">
|
||||
{paciente ? `${paciente.apellido}, ${paciente.nombre}` : 'Paciente no encontrado'}
|
||||
</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
Ingreso: {internacion.fechaIngresoClinica ? formatDateDDMMYYYY(internacion.fechaIngresoClinica) : 'N/A'}
|
||||
</p>
|
||||
</div>
|
||||
<Badge variant="outline" className="bg-purple-50 text-purple-700 dark:bg-purple-950/60 dark:text-purple-300 dark:border-purple-800">
|
||||
Activa
|
||||
</Badge>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Accesos Rápidos */}
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<Activity className="h-5 w-5 text-green-600" />
|
||||
Accesos Rápidos
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-auto py-4 flex flex-col items-center gap-2"
|
||||
onClick={() => onCambiarVista('pacientes')}
|
||||
>
|
||||
<Users className="h-6 w-6 text-blue-600" />
|
||||
<span className="text-sm">Nuevo Paciente</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-auto py-4 flex flex-col items-center gap-2"
|
||||
onClick={() => onCambiarVista('internaciones')}
|
||||
>
|
||||
<ClipboardList className="h-6 w-6 text-purple-600" />
|
||||
<span className="text-sm">Nueva Internación</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-auto py-4 flex flex-col items-center gap-2"
|
||||
onClick={() => onCambiarVista('laboratorios')}
|
||||
>
|
||||
<FlaskConical className="h-6 w-6 text-amber-600" />
|
||||
<span className="text-sm">Laboratorio</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
className="h-auto py-4 flex flex-col items-center gap-2"
|
||||
onClick={() => onCambiarVista('cultivos')}
|
||||
>
|
||||
<Microscope className="h-6 w-6 text-teal-600" />
|
||||
<span className="text-sm">Cultivo</span>
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Cultivos Pendientes */}
|
||||
<Card>
|
||||
<CardHeader className="flex flex-row items-center justify-between pb-2">
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<Microscope className="h-5 w-5 text-teal-600" />
|
||||
Cultivos Pendientes
|
||||
</CardTitle>
|
||||
<Button variant="ghost" size="sm" onClick={() => onCambiarVista('cultivos')}>
|
||||
Ver todos
|
||||
</Button>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{cultivosRecientes.length === 0 ? (
|
||||
<div className="text-center py-8 text-gray-400">
|
||||
<Microscope className="h-12 w-12 mx-auto mb-2 opacity-50" />
|
||||
<p>No hay cultivos pendientes</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{cultivosRecientes.map((cultivo) => {
|
||||
const paciente = getPacienteById(cultivo.pacienteId);
|
||||
return (
|
||||
<div key={cultivo.id} className="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-800/80 border border-transparent dark:border-gray-700/50 rounded-lg">
|
||||
<div>
|
||||
<p className="font-medium text-gray-900 dark:text-gray-100">
|
||||
{paciente ? `${paciente.apellido}, ${paciente.nombre}` : 'Paciente no encontrado'}
|
||||
</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">
|
||||
{cultivo.tipoMuestra} - {cultivo.fechaToma}
|
||||
</p>
|
||||
</div>
|
||||
<Badge className="bg-amber-100 text-amber-800 dark:bg-amber-950/60 dark:text-amber-300 dark:border dark:border-amber-800">
|
||||
<Clock className="h-3 w-3 mr-1" />
|
||||
Pendiente
|
||||
</Badge>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
import { useState } from 'react';
|
||||
import { Save, X, Bed, Stethoscope, User, Loader2, ClipboardList } from 'lucide-react';
|
||||
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 { Badge } from '@/components/ui/badge';
|
||||
import { toast } from 'sonner';
|
||||
import type { Paciente, Cama, Grupo, Internacion } from '@/types';
|
||||
import { getNombreProfesional, calcularEdad, computeSector } from '@/lib/utils';
|
||||
import { useHospitalStore } from '@/hooks/useHospitalStore';
|
||||
|
||||
interface EditIngresoProps {
|
||||
internacion: Internacion;
|
||||
paciente?: Paciente;
|
||||
cama?: Cama;
|
||||
pacientes: Paciente[];
|
||||
camas: Cama[];
|
||||
grupos: Grupo[];
|
||||
onActualizarInternacion: (id: string, datos: Partial<Internacion>) => Promise<void> | void;
|
||||
onAgregarCama?: (cama: Omit<Cama, 'id'>) => Promise<string>;
|
||||
onVolver: () => void;
|
||||
getGrupoName: (grupoId: string | undefined) => string;
|
||||
}
|
||||
|
||||
export function EditIngreso({
|
||||
internacion,
|
||||
pacientes,
|
||||
camas,
|
||||
grupos,
|
||||
onActualizarInternacion,
|
||||
onAgregarCama,
|
||||
onVolver,
|
||||
getGrupoName,
|
||||
}: EditIngresoProps) {
|
||||
const { currentUser } = useHospitalStore();
|
||||
const [pacienteSeleccionado] = useState(internacion.pacienteId);
|
||||
const [camaSeleccionada, setCamaSeleccionada] = useState(internacion.camaId);
|
||||
const [grupoSeleccionada] = useState(internacion.grupoId);
|
||||
const [camaInput, setCamaInput] = useState('');
|
||||
const [busqueda, setBusqueda] = useState('');
|
||||
const [modoCama, setModoCama] = useState<'seleccionar' | 'escribir'>('seleccionar');
|
||||
const effectiveMedico = getNombreProfesional(currentUser);
|
||||
const [fechaIngresoHospital, setFechaIngresoHospital] = useState(internacion.fechaIngresoHospital || '');
|
||||
const [fechaIngresoClinica, setFechaIngresoClinica] = useState(internacion.fechaIngresoClinica || '');
|
||||
const [motivoConsulta, setMotivoConsulta] = useState(internacion.motivoConsulta || '');
|
||||
const [diagnosticoIngreso, setDiagnosticoIngreso] = useState(internacion.diagnosticoIngreso || '');
|
||||
const [enfermedadActual, setEnfermedadActual] = useState(internacion.enfermedadActual || '');
|
||||
const [antecedentesEnfermedadActual, setAntecedentesEnfermedadActual] = useState(internacion.antecedentesEnfermedadActual || '');
|
||||
const [apache, setApache] = useState(internacion.apache || '');
|
||||
const [derivacion, setDerivacion] = useState(internacion.derivacion || '');
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const selectedPaciente = pacientes.find(p => p.id === pacienteSeleccionado);
|
||||
const normalizeStr = (str?: string) => (str || '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').trim().toLowerCase();
|
||||
const grupoFueraDeGrupo = grupos.find(a => normalizeStr(a.nombre) === 'fuera de grupo');
|
||||
const grupoFueraDeGrupoId = grupoFueraDeGrupo?.id || grupos[0]?.id || 'fuera-de-grupo';
|
||||
|
||||
const parseBedNumber = (numero: string) => {
|
||||
const match = numero.match(/^(\d{3})-(\d+)$/);
|
||||
if (!match) return { sala: 0, cama: 0 };
|
||||
return {
|
||||
sala: parseInt(match[1]),
|
||||
cama: parseInt(match[2])
|
||||
};
|
||||
};
|
||||
|
||||
const sortedCamas = [...camas].sort((a, b) => {
|
||||
const pa = parseBedNumber(a.numero);
|
||||
const pb = parseBedNumber(b.numero);
|
||||
|
||||
const getOrden = (sala: number) => {
|
||||
const grupo = Math.floor(sala / 100);
|
||||
const esPar = sala % 2 === 0;
|
||||
|
||||
if (grupo === 2) {
|
||||
if (esPar) return { grupo: 2, suborden: 0, sala };
|
||||
return { grupo: 1, suborden: 1, sala };
|
||||
}
|
||||
if (grupo === 3) {
|
||||
if (esPar) return { grupo: 3, suborden: 0, sala };
|
||||
return { grupo: 4, suborden: 1, sala };
|
||||
}
|
||||
if (grupo === 4) {
|
||||
if (esPar) return { grupo: 6, suborden: 0, sala };
|
||||
return { grupo: 5, suborden: 1, sala };
|
||||
}
|
||||
return { grupo: 10, suborden: 1, sala };
|
||||
};
|
||||
|
||||
const oa = getOrden(pa.sala);
|
||||
const ob = getOrden(pb.sala);
|
||||
|
||||
if (oa.grupo !== ob.grupo) return oa.grupo - ob.grupo;
|
||||
if (oa.suborden === ob.suborden) {
|
||||
if (oa.suborden === 0) return (oa.sala || pa.sala) - (ob.sala || pb.sala);
|
||||
return (ob.sala || 0) - (oa.sala || 0);
|
||||
}
|
||||
return oa.suborden - ob.suborden;
|
||||
});
|
||||
|
||||
const handleSubmit = async () => {
|
||||
if (!pacienteSeleccionado) {
|
||||
toast.error('Debe seleccionar un paciente');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!diagnosticoIngreso.trim()) {
|
||||
toast.error('Debe ingresar el diagnóstico de ingreso');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!enfermedadActual.trim()) {
|
||||
toast.error('Debe ingresar la enfermedad actual');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!effectiveMedico.trim()) {
|
||||
toast.error('Debe ingresar el médico ingresante');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
let camaId = '';
|
||||
let newGrupoId = '';
|
||||
|
||||
if (modoCama === 'escribir') {
|
||||
if (!camaInput.trim()) {
|
||||
toast.error('Ingrese el número de cama');
|
||||
setIsSubmitting(false);
|
||||
return;
|
||||
}
|
||||
const numeroCama = camaInput.trim();
|
||||
const camaExistente = camas.find(c => c.numero === numeroCama);
|
||||
if (camaExistente) {
|
||||
camaId = camaExistente.id;
|
||||
newGrupoId = camaExistente.grupoId || grupoFueraDeGrupoId;
|
||||
} else if (onAgregarCama) {
|
||||
camaId = await onAgregarCama({
|
||||
numero: numeroCama,
|
||||
grupoId: grupoFueraDeGrupoId,
|
||||
tipo: 'General',
|
||||
estado: 'Ocupada'
|
||||
});
|
||||
newGrupoId = grupoFueraDeGrupoId;
|
||||
} else {
|
||||
toast.error('No se puede crear la cama');
|
||||
setIsSubmitting(false);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
if (camaSeleccionada && camaSeleccionada !== internacion.camaId) {
|
||||
const camaElegida = sortedCamas.find(c => c.id === camaSeleccionada);
|
||||
if (!camaElegida) {
|
||||
toast.error('Cama no encontrada');
|
||||
setIsSubmitting(false);
|
||||
return;
|
||||
}
|
||||
newGrupoId = camaElegida.grupoId || grupoFueraDeGrupoId;
|
||||
camaId = camaSeleccionada;
|
||||
} else {
|
||||
newGrupoId = grupoSeleccionada || internacion.grupoId || grupoFueraDeGrupoId;
|
||||
camaId = internacion.camaId;
|
||||
}
|
||||
}
|
||||
|
||||
await onActualizarInternacion(internacion.id, {
|
||||
pacienteId: pacienteSeleccionado,
|
||||
camaId: camaId,
|
||||
grupoId: newGrupoId,
|
||||
medicoIngresante: effectiveMedico.trim(),
|
||||
diagnosticoIngreso: diagnosticoIngreso.trim(),
|
||||
motivoConsulta: motivoConsulta.trim() || undefined,
|
||||
enfermedadActual: enfermedadActual.trim(),
|
||||
antecedentesEnfermedadActual: antecedentesEnfermedadActual.trim() || undefined,
|
||||
fechaIngresoHospital: fechaIngresoHospital || undefined,
|
||||
fechaIngresoClinica: fechaIngresoClinica || undefined,
|
||||
apache: apache.trim() || undefined,
|
||||
derivacion: derivacion.trim() || undefined,
|
||||
});
|
||||
|
||||
toast.success('Ingreso actualizado correctamente');
|
||||
onVolver();
|
||||
} catch (err) {
|
||||
console.error('Error al actualizar ingreso:', err);
|
||||
toast.error('Error al actualizar el ingreso');
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6 dark:text-white">
|
||||
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-4">
|
||||
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-2">
|
||||
<User className="h-6 w-6 text-blue-600" />
|
||||
Editar Ingreso
|
||||
</h1>
|
||||
<p className="text-gray-500 dark:text-gray-400">Modificar datos de internación</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2 ml-auto sm:ml-0">
|
||||
<Button variant="secondary" onClick={() => onVolver()} disabled={isSubmitting}>
|
||||
<X className="h-4 w-4 mr-2" />
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button onClick={handleSubmit} disabled={isSubmitting}>
|
||||
{isSubmitting ? <Loader2 className="h-4 w-4 mr-2 animate-spin" /> : <Save className="h-4 w-4 mr-2" />}
|
||||
Guardar Cambios
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
{/* Columna 1: Datos del Paciente, Cama y Datos Adicionales */}
|
||||
<div className="space-y-6">
|
||||
<Card className="min-h-[200px]">
|
||||
<CardContent className="pt-6 space-y-4">
|
||||
<h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2">
|
||||
<User className="h-4 w-4" />
|
||||
Datos del Paciente
|
||||
</h3>
|
||||
|
||||
{selectedPaciente ? (
|
||||
<div className="space-y-2">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Badge variant="outline" className="bg-green-50 text-green-700 dark:bg-green-900 dark:text-green-300 dark:border-green-700">
|
||||
{selectedPaciente?.apellido}, {selectedPaciente?.nombre}
|
||||
</Badge>
|
||||
<Badge variant="outline" className="bg-primary/10 text-primary border-primary/30">
|
||||
{selectedPaciente?.fechaNacimiento ? calcularEdad(selectedPaciente.fechaNacimiento) + ' años' : ''}
|
||||
</Badge>
|
||||
<Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200">
|
||||
DNI: {selectedPaciente?.dni}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Badge variant="secondary">
|
||||
HC: {selectedPaciente?.historiaClinica || 'N/A'}
|
||||
</Badge>
|
||||
<Badge variant="secondary">
|
||||
{selectedPaciente?.obraSocial || 'Sin obra social'}
|
||||
</Badge>
|
||||
<Badge variant="secondary">
|
||||
{selectedPaciente?.nacionalidad || 'N/A'}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<Label>Buscar Paciente *</Label>
|
||||
<Input
|
||||
placeholder="Apellido, nombre o DNI"
|
||||
value={busqueda}
|
||||
onChange={(e) => setBusqueda(e.target.value)}
|
||||
/>
|
||||
<div className="max-h-48 overflow-auto border rounded-md">
|
||||
{(() => {
|
||||
const q = busqueda.trim().toLowerCase();
|
||||
if (!q) {
|
||||
return <div className="p-2 text-sm text-gray-500">Escriba para buscar</div>;
|
||||
}
|
||||
const matches = pacientes.filter(p =>
|
||||
p.apellido.toLowerCase().includes(q) ||
|
||||
p.nombre.toLowerCase().includes(q) ||
|
||||
p.dni.includes(q)
|
||||
);
|
||||
if (matches.length === 0) {
|
||||
return <div className="p-2 text-sm text-gray-500">Sin resultados</div>;
|
||||
}
|
||||
return matches.map(p => (
|
||||
<button
|
||||
key={p.id}
|
||||
type="button"
|
||||
onClick={() => setPacienteSeleccionado(p.id)}
|
||||
className="w-full text-left p-2 hover:bg-gray-50 text-sm"
|
||||
>
|
||||
{p.apellido}, {p.nombre} — DNI: {p.dni}
|
||||
</button>
|
||||
));
|
||||
})()}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Columna 2: Cama y Grupo */}
|
||||
<div className="space-y-6">
|
||||
<Card className="min-h-[200px]">
|
||||
<CardContent className="pt-6 space-y-4">
|
||||
<h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2">
|
||||
<Bed className="h-4 w-4" />
|
||||
Asignación de Cama y Grupo
|
||||
</h3>
|
||||
|
||||
<div className="flex gap-2 mb-4">
|
||||
<Button
|
||||
variant={modoCama === 'seleccionar' ? 'default' : 'outline'}
|
||||
onClick={() => setModoCama('seleccionar')}
|
||||
>
|
||||
Seleccionar Cama
|
||||
</Button>
|
||||
<Button
|
||||
variant={modoCama === 'escribir' ? 'default' : 'outline'}
|
||||
onClick={() => setModoCama('escribir')}
|
||||
>
|
||||
Escribir Cama
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{modoCama === 'seleccionar' ? (
|
||||
<>
|
||||
<div>
|
||||
<Label>Cama</Label>
|
||||
<Select value={camaSeleccionada} onValueChange={setCamaSeleccionada}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Seleccionar cama" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{sortedCamas.map(c => (
|
||||
<SelectItem key={c.id} value={c.id}>
|
||||
{c.numero} - {getGrupoName(c.grupoId)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div>
|
||||
<Label>Número de Cama (formato XXX-YY) *</Label>
|
||||
<Input
|
||||
placeholder="201-1"
|
||||
value={camaInput}
|
||||
onChange={(e) => setCamaInput(e.target.value)}
|
||||
/>
|
||||
<p className="text-xs text-gray-500 mt-1">
|
||||
{camaInput.trim() ? `Clasificación: ${computeSector(camaInput.trim())}` : 'Formato XXX-YY (Salas 3XX impares y 4XX son Fuera de Área)'}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardContent className="pt-6 space-y-4">
|
||||
<h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2">
|
||||
<ClipboardList className="h-4 w-4" />
|
||||
Datos de Ingreso
|
||||
</h3>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label>Fecha Ingreso al Hospital</Label>
|
||||
<Input
|
||||
type="date"
|
||||
value={fechaIngresoHospital}
|
||||
onChange={(e) => setFechaIngresoHospital(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Fecha Ingreso a Clínica Médica</Label>
|
||||
<Input
|
||||
type="date"
|
||||
value={fechaIngresoClinica}
|
||||
onChange={(e) => setFechaIngresoClinica(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Derivado de</Label>
|
||||
<Input
|
||||
placeholder="Hospital o clínica de derivación"
|
||||
value={derivacion}
|
||||
onChange={(e) => setDerivacion(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Apache / Mortalidad</Label>
|
||||
<Input
|
||||
placeholder="Valor Apache o riesgo"
|
||||
value={apache}
|
||||
onChange={(e) => setApache(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardContent className="pt-6 space-y-4">
|
||||
<h3 className="font-semibold text-gray-900 dark:text-white">
|
||||
Datos Clínicos
|
||||
</h3>
|
||||
|
||||
<div>
|
||||
<Label>Motivo de Consulta *</Label>
|
||||
<textarea
|
||||
className="w-full p-2 border rounded-md text-sm min-h-[80px]"
|
||||
placeholder="Motivo por el cual consulta"
|
||||
value={motivoConsulta}
|
||||
onChange={(e) => setMotivoConsulta(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Diagnóstico de Ingreso *</Label>
|
||||
<textarea
|
||||
className="w-full p-2 border rounded-md text-sm min-h-[80px]"
|
||||
placeholder="Diagnóstico principal"
|
||||
value={diagnosticoIngreso}
|
||||
onChange={(e) => setDiagnosticoIngreso(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Enfermedad Actual *</Label>
|
||||
<textarea
|
||||
className="w-full p-2 border rounded-md text-sm min-h-[100px]"
|
||||
placeholder="Descripción de la enfermedad actual"
|
||||
value={enfermedadActual}
|
||||
onChange={(e) => setEnfermedadActual(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Antecedentes de Enfermedad Actual</Label>
|
||||
<textarea
|
||||
className="w-full p-2 border rounded-md text-sm min-h-[80px]"
|
||||
placeholder="Antecedentes relevantes"
|
||||
value={antecedentesEnfermedadActual}
|
||||
onChange={(e) => setAntecedentesEnfermedadActual(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
|
||||
{/* Columna 4: Médico Ingresante */}
|
||||
<div className="space-y-6">
|
||||
|
||||
<Card>
|
||||
<CardContent className="pt-6 space-y-4">
|
||||
<h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2">
|
||||
<Stethoscope className="h-4 w-4" />
|
||||
Médico Ingresante
|
||||
</h3>
|
||||
|
||||
<div>
|
||||
<Label>Médico Ingresante *</Label>
|
||||
<Input
|
||||
placeholder="Nombre del médico"
|
||||
value={getNombreProfesional(currentUser)}
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,624 @@
|
||||
import { useState } from 'react';
|
||||
import { FileText, Plus, Search, Eye, MoreHorizontal, Pencil, Trash2, X, Save, Activity, Heart, Wind, Thermometer, Droplets } from 'lucide-react';
|
||||
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 { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
|
||||
import { toast } from 'sonner';
|
||||
import type { Evolucion, Internacion, Paciente, Cama, SignosVitales, ExamenFisico } from '@/types';
|
||||
import { useHospitalStore } from '@/hooks/useHospitalStore';
|
||||
import { getNombreProfesional } from '@/lib/utils';
|
||||
|
||||
|
||||
interface EvolucionesProps {
|
||||
evoluciones: Evolucion[];
|
||||
internaciones: Internacion[];
|
||||
pacientes: Paciente[];
|
||||
camas?: Cama[];
|
||||
getCamaById?: (id: string) => Cama | undefined;
|
||||
onAgregarEvolucion: (evolucion: Omit<Evolucion, 'id'>) => Promise<unknown> | void;
|
||||
onActualizarEvolucion?: (id: string, datos: Partial<Evolucion>) => Promise<unknown> | void;
|
||||
onEliminarEvolucion: (id: string) => Promise<unknown> | void;
|
||||
getPacienteById: (id: string) => Paciente | undefined;
|
||||
getInternacionActivaByPaciente: (pacienteId: string) => Internacion | undefined;
|
||||
}
|
||||
|
||||
export function Evoluciones({
|
||||
evoluciones,
|
||||
internaciones,
|
||||
pacientes,
|
||||
camas,
|
||||
getCamaById,
|
||||
onAgregarEvolucion,
|
||||
onActualizarEvolucion,
|
||||
onEliminarEvolucion,
|
||||
getPacienteById,
|
||||
getInternacionActivaByPaciente
|
||||
}: EvolucionesProps) {
|
||||
const { currentUser } = useHospitalStore();
|
||||
const [busqueda, setBusqueda] = useState('');
|
||||
const [pacienteSeleccionado, setPacienteSeleccionado] = useState<string>('');
|
||||
const [dialogoAbierto, setDialogoAbierto] = useState(false);
|
||||
const [evolucionDetalle, setEvolucionDetalle] = useState<Evolucion | null>(null);
|
||||
const [evolucionEditando, setEvolucionEditando] = useState<Evolucion | null>(null);
|
||||
|
||||
const [fecha, setFecha] = useState(new Date().toISOString().split('T')[0]);
|
||||
const [hora, setHora] = useState(new Date().toTimeString().slice(0, 5));
|
||||
const effectiveMedico = getNombreProfesional(currentUser);
|
||||
|
||||
const [temperatura, setTemperatura] = useState('');
|
||||
const [presionSistolica, setPresionSistolica] = useState('');
|
||||
const [presionDiastolica, setPresionDiastolica] = useState('');
|
||||
const [frecuenciaCardiaca, setFrecuenciaCardiaca] = useState('');
|
||||
const [frecuenciaRespiratoria, setFrecuenciaRespiratoria] = useState('');
|
||||
const [saturacionO2, setSaturacionO2] = useState('');
|
||||
const [snc, setSnc] = useState('');
|
||||
const [cardiovascular, setCardiovascular] = useState('');
|
||||
const [respiratorio, setRespiratorio] = useState('');
|
||||
const [abdominal, setAbdominal] = useState('');
|
||||
const [genitourinario, setGenitourinario] = useState('');
|
||||
const [pielAnexos, setPielAnexos] = useState('');
|
||||
const [soma, setSoma] = useState('');
|
||||
const [novedades, setNovedades] = useState('');
|
||||
const [comentario, setComentario] = useState('');
|
||||
const [pendientes, setPendientes] = useState('');
|
||||
|
||||
const resetFormulario = () => {
|
||||
setFecha(new Date().toISOString().split('T')[0]);
|
||||
setHora(new Date().toTimeString().slice(0, 5));
|
||||
setTemperatura('');
|
||||
setPresionSistolica('');
|
||||
setPresionDiastolica('');
|
||||
setFrecuenciaCardiaca('');
|
||||
setFrecuenciaRespiratoria('');
|
||||
setSaturacionO2('');
|
||||
setSnc('');
|
||||
setCardiovascular('');
|
||||
setRespiratorio('');
|
||||
setAbdominal('');
|
||||
setGenitourinario('');
|
||||
setPielAnexos('');
|
||||
setSoma('');
|
||||
setNovedades('');
|
||||
setComentario('');
|
||||
setPendientes('');
|
||||
setEvolucionEditando(null);
|
||||
};
|
||||
|
||||
const abrirEditar = (evo: Evolucion) => {
|
||||
setEvolucionEditando(evo);
|
||||
const internacion = internaciones.find(i => i.id === evo.internacionId);
|
||||
if (internacion) {
|
||||
setPacienteSeleccionado(internacion.pacienteId);
|
||||
}
|
||||
setFecha(evo.fecha);
|
||||
setHora(evo.hora);
|
||||
setTemperatura(evo.signosVitales?.temperatura?.toString() || '');
|
||||
setPresionSistolica(evo.signosVitales?.presionSistolica?.toString() || '');
|
||||
setPresionDiastolica(evo.signosVitales?.presionDiastolica?.toString() || '');
|
||||
setFrecuenciaCardiaca(evo.signosVitales?.frecuenciaCardiaca?.toString() || '');
|
||||
setFrecuenciaRespiratoria(evo.signosVitales?.frecuenciaRespiratoria?.toString() || '');
|
||||
setSaturacionO2(evo.signosVitales?.saturacionO2?.toString() || '');
|
||||
setSnc(evo.examenFisico?.SNC || '');
|
||||
setCardiovascular(evo.examenFisico?.Cardiovascular || '');
|
||||
setRespiratorio(evo.examenFisico?.Respiratorio || '');
|
||||
setAbdominal(evo.examenFisico?.Abdominal || '');
|
||||
setGenitourinario(evo.examenFisico?.Genitourinario || '');
|
||||
setPielAnexos(evo.examenFisico?.PielAnexos || '');
|
||||
setSoma(evo.examenFisico?.SOMA || '');
|
||||
setNovedades(evo.novedades || '');
|
||||
setComentario(evo.comentario || '');
|
||||
setPendientes(evo.pendientes || '');
|
||||
setDialogoAbierto(true);
|
||||
};
|
||||
|
||||
const handleGuardar = async () => {
|
||||
const internacion = evolucionEditando
|
||||
? internaciones.find(i => i.id === evolucionEditando.internacionId)
|
||||
: getInternacionActivaByPaciente(pacienteSeleccionado);
|
||||
|
||||
if (!effectiveMedico.trim()) {
|
||||
toast.error('Debe completar el nombre del médico');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!internacion) {
|
||||
toast.error('Seleccione un paciente internado');
|
||||
return;
|
||||
}
|
||||
|
||||
const signosVitales: SignosVitales | undefined =
|
||||
temperatura || presionSistolica || frecuenciaCardiaca
|
||||
? {
|
||||
temperatura: temperatura ? parseFloat(temperatura) : undefined,
|
||||
presionSistolica: presionSistolica ? parseInt(presionSistolica) : undefined,
|
||||
presionDiastolica: presionDiastolica ? parseInt(presionDiastolica) : undefined,
|
||||
frecuenciaCardiaca: frecuenciaCardiaca ? parseInt(frecuenciaCardiaca) : undefined,
|
||||
frecuenciaRespiratoria: frecuenciaRespiratoria ? parseInt(frecuenciaRespiratoria) : undefined,
|
||||
saturacionO2: saturacionO2 ? parseInt(saturacionO2) : undefined,
|
||||
}
|
||||
: undefined;
|
||||
|
||||
const examenFisico: ExamenFisico | undefined =
|
||||
snc || cardiovascular || respiratorio || abdominal || genitourinario || pielAnexos || soma
|
||||
? {
|
||||
SNC: snc || undefined,
|
||||
Cardiovascular: cardiovascular || undefined,
|
||||
Respiratorio: respiratorio || undefined,
|
||||
Abdominal: abdominal || undefined,
|
||||
Genitourinario: genitourinario || undefined,
|
||||
PielAnexos: pielAnexos || undefined,
|
||||
SOMA: soma || undefined,
|
||||
}
|
||||
: undefined;
|
||||
|
||||
const evolucionData = {
|
||||
fecha,
|
||||
hora,
|
||||
medico: effectiveMedico.trim(),
|
||||
signosVitales,
|
||||
examenFisico,
|
||||
novedades: novedades || undefined,
|
||||
comentario: comentario || undefined,
|
||||
pendientes: pendientes || undefined,
|
||||
};
|
||||
|
||||
try {
|
||||
if (evolucionEditando && onActualizarEvolucion) {
|
||||
await onActualizarEvolucion(evolucionEditando.id, evolucionData);
|
||||
toast.success('Evolución actualizada correctamente');
|
||||
} else {
|
||||
await onAgregarEvolucion({ ...evolucionData, internacionId: internacion.id });
|
||||
toast.success('Evolución agregada correctamente');
|
||||
}
|
||||
|
||||
resetFormulario();
|
||||
setDialogoAbierto(false);
|
||||
} catch (err) {
|
||||
console.error('Error al guardar evolución:', err);
|
||||
toast.error('Error al guardar los cambios de la evolución');
|
||||
}
|
||||
};
|
||||
|
||||
const pacientesInternados = pacientes.filter(p => {
|
||||
const internacion = getInternacionActivaByPaciente(p.id);
|
||||
return internacion !== undefined;
|
||||
});
|
||||
|
||||
const evolucionesFiltradas = evoluciones
|
||||
.filter(e => {
|
||||
const internacion = internaciones.find(i => i.id === e.internacionId);
|
||||
if (!internacion) return false;
|
||||
const paciente = getPacienteById(internacion.pacienteId);
|
||||
if (!paciente) return false;
|
||||
|
||||
return !busqueda ||
|
||||
paciente.nombre.toLowerCase().includes(busqueda.toLowerCase()) ||
|
||||
paciente.apellido.toLowerCase().includes(busqueda.toLowerCase()) ||
|
||||
paciente.dni.includes(busqueda);
|
||||
})
|
||||
.sort((a, b) => new Date(b.fecha + 'T' + b.hora).getTime() - new Date(a.fecha + 'T' + a.hora).getTime());
|
||||
|
||||
return (
|
||||
<div className="space-y-6 dark:text-white overflow-x-hidden max-w-screen">
|
||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900 dark:text-white">Evoluciones Diarias</h1>
|
||||
<p className="text-gray-500 dark:text-gray-400">Registro de evoluciones y signos vitales</p>
|
||||
</div>
|
||||
<Dialog open={dialogoAbierto} onOpenChange={setDialogoAbierto}>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="outline" onClick={resetFormulario}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Nueva Evolución
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{evolucionEditando ? 'Editar Evolución' : 'Nueva Evolución'}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
{!evolucionEditando && (
|
||||
<div>
|
||||
<Label>Paciente *</Label>
|
||||
<Select value={pacienteSeleccionado} onValueChange={setPacienteSeleccionado}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Seleccionar paciente internado" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{pacientesInternados.map(p => (
|
||||
<SelectItem key={p.id} value={p.id}>
|
||||
{p.apellido}, {p.nombre} - DNI: {p.dni}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label>Fecha *</Label>
|
||||
<Input type="date" value={fecha} onChange={(e) => setFecha(e.target.value)} />
|
||||
</div>
|
||||
<div>
|
||||
<Label>Hora *</Label>
|
||||
<Input type="time" value={hora} onChange={(e) => setHora(e.target.value)} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-blue-50 p-3 rounded-lg border border-blue-200">
|
||||
<p className="text-sm font-bold text-blue-800 mb-3 flex items-center gap-2">
|
||||
<Activity className="h-4 w-4" />
|
||||
Signos Vitales
|
||||
</p>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<Label className="flex items-center gap-1">
|
||||
<Heart className="h-4 w-4" />TAS
|
||||
</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={presionSistolica}
|
||||
onChange={(e) => setPresionSistolica(e.target.value)}
|
||||
placeholder="120"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="flex items-center gap-1">
|
||||
<Heart className="h-4 w-4" />TAD
|
||||
</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={presionDiastolica}
|
||||
onChange={(e) => setPresionDiastolica(e.target.value)}
|
||||
placeholder="80"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="flex items-center gap-1">
|
||||
<Activity className="h-4 w-4" />FC
|
||||
</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={frecuenciaCardiaca}
|
||||
onChange={(e) => setFrecuenciaCardiaca(e.target.value)}
|
||||
placeholder="72"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="flex items-center gap-1">
|
||||
<Wind className="h-4 w-4" />FR
|
||||
</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={frecuenciaRespiratoria}
|
||||
onChange={(e) => setFrecuenciaRespiratoria(e.target.value)}
|
||||
placeholder="16"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="flex items-center gap-1">
|
||||
<Thermometer className="h-4 w-4" />T°
|
||||
</Label>
|
||||
<Input
|
||||
type="number"
|
||||
step="0.1"
|
||||
value={temperatura}
|
||||
onChange={(e) => setTemperatura(e.target.value)}
|
||||
placeholder="36.5"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="flex items-center gap-1">
|
||||
<Droplets className="h-4 w-4" />SatO2
|
||||
</Label>
|
||||
<Input
|
||||
type="number"
|
||||
value={saturacionO2}
|
||||
onChange={(e) => setSaturacionO2(e.target.value)}
|
||||
placeholder="98"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-green-50 p-3 rounded-lg border border-green-200">
|
||||
<p className="text-sm font-bold text-green-800 mb-3 flex items-center gap-2">
|
||||
<FileText className="h-4 w-4" />
|
||||
Examen Físico
|
||||
</p>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label>SNC</Label>
|
||||
<textarea className="w-full p-2 border rounded-md text-sm min-h-[60px]" value={snc} onChange={(e) => setSnc(e.target.value)} placeholder="Estado neurológico" />
|
||||
</div>
|
||||
<div>
|
||||
<Label>Cardiovascular</Label>
|
||||
<textarea className="w-full p-2 border rounded-md text-sm min-h-[60px]" value={cardiovascular} onChange={(e) => setCardiovascular(e.target.value)} placeholder="Hallazgos cardiovasculares" />
|
||||
</div>
|
||||
<div>
|
||||
<Label>Respiratorio</Label>
|
||||
<textarea className="w-full p-2 border rounded-md text-sm min-h-[60px]" value={respiratorio} onChange={(e) => setRespiratorio(e.target.value)} placeholder="Hallazgos respiratorios" />
|
||||
</div>
|
||||
<div>
|
||||
<Label>Abdominal</Label>
|
||||
<textarea className="w-full p-2 border rounded-md text-sm min-h-[60px]" value={abdominal} onChange={(e) => setAbdominal(e.target.value)} placeholder="Hallazgos abdominales" />
|
||||
</div>
|
||||
<div>
|
||||
<Label>Genitourinario</Label>
|
||||
<textarea className="w-full p-2 border rounded-md text-sm min-h-[60px]" value={genitourinario} onChange={(e) => setGenitourinario(e.target.value)} placeholder="Hallazgos genitourinarios" />
|
||||
</div>
|
||||
<div>
|
||||
<Label>Piel y anexos</Label>
|
||||
<textarea className="w-full p-2 border rounded-md text-sm min-h-[60px]" value={pielAnexos} onChange={(e) => setPielAnexos(e.target.value)} placeholder="Estado de piel y anexos" />
|
||||
</div>
|
||||
<div>
|
||||
<Label>SOMA</Label>
|
||||
<Input value={soma} onChange={(e) => setSoma(e.target.value)} placeholder="Estado SOMA" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Novedades</Label>
|
||||
<textarea
|
||||
className="w-full p-2 border rounded-md text-sm min-h-[80px]"
|
||||
value={novedades}
|
||||
onChange={(e) => setNovedades(e.target.value)}
|
||||
placeholder="Novedades..."
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Comentario</Label>
|
||||
<textarea
|
||||
className="w-full p-2 border rounded-md text-sm min-h-[80px]"
|
||||
value={comentario}
|
||||
onChange={(e) => setComentario(e.target.value)}
|
||||
placeholder="Comentarios adicionales..."
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Pendientes</Label>
|
||||
<textarea
|
||||
className="w-full p-2 border rounded-md text-sm min-h-[80px]"
|
||||
value={pendientes}
|
||||
onChange={(e) => setPendientes(e.target.value)}
|
||||
placeholder="Pendientes..."
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Médico *</Label>
|
||||
<Input
|
||||
value={getNombreProfesional(currentUser)}
|
||||
disabled
|
||||
placeholder="Nombre del médico"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 mt-4">
|
||||
<Button variant="outline" onClick={() => { resetFormulario(); setDialogoAbierto(false); }}>
|
||||
<X className="h-4 w-4 mr-2" />
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button variant="outline"
|
||||
onClick={handleGuardar}
|
||||
disabled={!effectiveMedico || (!evolucionEditando && !pacienteSeleccionado)}
|
||||
>
|
||||
<Save className="h-4 w-4 mr-2" />
|
||||
Guardar Evolución
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
|
||||
<Input
|
||||
className="pl-10"
|
||||
placeholder="Buscar por paciente..."
|
||||
value={busqueda}
|
||||
onChange={(e) => setBusqueda(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{evolucionesFiltradas.length > 0 ? (
|
||||
<div className="grid grid-cols-1 w-full">
|
||||
<div className="w-full overflow-x-auto rounded-md border bg-card pb-2">
|
||||
<Table className="w-full min-w-max text-sm">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Fecha</TableHead>
|
||||
<TableHead>Cama</TableHead>
|
||||
<TableHead>Paciente</TableHead>
|
||||
<TableHead>Profesional</TableHead>
|
||||
<TableHead className="text-center">TAS</TableHead>
|
||||
<TableHead className="text-center">TAD</TableHead>
|
||||
<TableHead className="text-center">FC</TableHead>
|
||||
<TableHead className="text-center">FR</TableHead>
|
||||
<TableHead className="text-center">Tº</TableHead>
|
||||
<TableHead className="text-center">Sat</TableHead>
|
||||
<TableHead className="text-center w-[60px]">Acciones</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{evolucionesFiltradas.map((evolucion) => {
|
||||
const internacion = internaciones.find(i => i.id === evolucion.internacionId);
|
||||
const paciente = internacion ? getPacienteById(internacion.pacienteId) : null;
|
||||
const cama = internacion ? (getCamaById ? getCamaById(internacion.camaId) : camas?.find(c => c.id === internacion.camaId)) : null;
|
||||
const sv = evolucion.signosVitales;
|
||||
|
||||
return (
|
||||
<TableRow key={evolucion.id} className="hover:bg-muted/50">
|
||||
<TableCell className="whitespace-nowrap font-medium text-xs">
|
||||
{evolucion.fecha} {evolucion.hora || ''}
|
||||
</TableCell>
|
||||
<TableCell className="text-xs whitespace-nowrap">
|
||||
{cama ? cama.numero : '-'}
|
||||
</TableCell>
|
||||
<TableCell className="font-medium text-xs whitespace-nowrap">
|
||||
{paciente ? `${paciente.apellido}, ${paciente.nombre}` : 'Sin paciente'}
|
||||
</TableCell>
|
||||
<TableCell className="text-xs whitespace-nowrap">
|
||||
{evolucion.medico || '-'}
|
||||
</TableCell>
|
||||
<TableCell className="text-center text-xs">{sv?.presionSistolica ?? '-'}</TableCell>
|
||||
<TableCell className="text-center text-xs">{sv?.presionDiastolica ?? '-'}</TableCell>
|
||||
<TableCell className="text-center text-xs">{sv?.frecuenciaCardiaca ?? '-'}</TableCell>
|
||||
<TableCell className="text-center text-xs">{sv?.frecuenciaRespiratoria ?? '-'}</TableCell>
|
||||
<TableCell className="text-center text-xs">{sv?.temperatura !== undefined ? `${sv.temperatura}°C` : '-'}</TableCell>
|
||||
<TableCell className="text-center text-xs">{sv?.saturacionO2 !== undefined ? `${sv.saturacionO2}%` : '-'}</TableCell>
|
||||
<TableCell className="text-center p-1">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button size="sm" variant="ghost" className="h-8 w-8 p-0">
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => setEvolucionDetalle(evolucion)}>
|
||||
<Eye className="mr-2 h-4 w-4" />
|
||||
Detalles
|
||||
</DropdownMenuItem>
|
||||
{onActualizarEvolucion && (
|
||||
<DropdownMenuItem onClick={() => abrirEditar(evolucion)}>
|
||||
<Pencil className="mr-2 h-4 w-4" />
|
||||
Editar
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem onClick={() => onEliminarEvolucion(evolucion.id)} className="text-red-600 focus:text-red-600">
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Eliminar
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-center py-12 text-gray-400">
|
||||
<FileText className="h-16 w-16 mx-auto mb-4 opacity-50" />
|
||||
<p className="text-lg">
|
||||
{busqueda ? 'No se encontraron evoluciones con esa búsqueda' : 'No hay evoluciones registradas'}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Modal de Detalle de Evolución */}
|
||||
<Dialog open={!!evolucionDetalle} onOpenChange={(open) => { if (!open) setEvolucionDetalle(null); }}>
|
||||
<DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<FileText className="h-5 w-5 text-blue-600" />
|
||||
Detalle de Evolución
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
{evolucionDetalle && (() => {
|
||||
const internacionDet = internaciones.find(i => i.id === evolucionDetalle.internacionId);
|
||||
const pacienteDet = internacionDet ? getPacienteById(internacionDet.pacienteId) : null;
|
||||
const camaDet = internacionDet ? (getCamaById ? getCamaById(internacionDet.camaId) : camas?.find(c => c.id === internacionDet.camaId)) : null;
|
||||
const svDet = evolucionDetalle.signosVitales;
|
||||
const efDet = evolucionDetalle.examenFisico;
|
||||
|
||||
return (
|
||||
<div className="space-y-4 text-sm">
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 p-3 bg-muted/40 rounded-lg border">
|
||||
<div>
|
||||
{pacienteDet && (
|
||||
<p className="font-bold text-base text-gray-900 dark:text-white mb-1">
|
||||
{pacienteDet.apellido}, {pacienteDet.nombre} <span className="text-xs font-normal text-muted-foreground">(DNI: {pacienteDet.dni}{camaDet ? ` | Cama: ${camaDet.numero}` : ''})</span>
|
||||
</p>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
<span className="font-medium text-foreground">Fecha:</span> {evolucionDetalle.fecha} | <span className="font-medium text-foreground">Hora:</span> {evolucionDetalle.hora}
|
||||
</p>
|
||||
</div>
|
||||
<div className="text-right text-xs text-muted-foreground">
|
||||
<p><span className="font-medium text-foreground">Médico:</span> {evolucionDetalle.medico}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Signos Vitales */}
|
||||
{svDet && (
|
||||
<div className="bg-blue-50 dark:bg-blue-950/60 p-3 rounded-lg border border-blue-200 dark:border-blue-800/50">
|
||||
<p className="text-xs font-semibold text-blue-800 dark:text-blue-300 mb-2 flex items-center gap-1.5">
|
||||
<Activity className="h-4 w-4" />
|
||||
Signos Vitales
|
||||
</p>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 gap-2 text-xs">
|
||||
<div><span className="font-medium">TAS:</span> {svDet.presionSistolica ?? '-'} mmHg</div>
|
||||
<div><span className="font-medium">TAD:</span> {svDet.presionDiastolica ?? '-'} mmHg</div>
|
||||
<div><span className="font-medium">FC:</span> {svDet.frecuenciaCardiaca ?? '-'} lpm</div>
|
||||
<div><span className="font-medium">FR:</span> {svDet.frecuenciaRespiratoria ?? '-'} rpm</div>
|
||||
<div><span className="font-medium">Tº:</span> {svDet.temperatura !== undefined ? `${svDet.temperatura}°C` : '-'}</div>
|
||||
<div><span className="font-medium">SatO2:</span> {svDet.saturacionO2 !== undefined ? `${svDet.saturacionO2}%` : '-'}</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Examen Físico */}
|
||||
{efDet && (
|
||||
<div className="bg-green-50 dark:bg-green-950/60 p-3 rounded-lg border border-green-200 dark:border-green-800/50">
|
||||
<p className="text-xs font-semibold text-green-800 dark:text-green-300 mb-2">Examen Físico:</p>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2 text-xs">
|
||||
{efDet.SNC && <div><span className="font-semibold">SNC:</span> {efDet.SNC}</div>}
|
||||
{efDet.Cardiovascular && <div><span className="font-semibold">Cardiovascular:</span> {efDet.Cardiovascular}</div>}
|
||||
{efDet.Respiratorio && <div><span className="font-semibold">Respiratorio:</span> {efDet.Respiratorio}</div>}
|
||||
{efDet.Abdominal && <div><span className="font-semibold">Abdominal:</span> {efDet.Abdominal}</div>}
|
||||
{efDet.Genitourinario && <div><span className="font-semibold">Genitourinario:</span> {efDet.Genitourinario}</div>}
|
||||
{efDet.PielAnexos && <div><span className="font-semibold">Piel y Anexos:</span> {efDet.PielAnexos}</div>}
|
||||
{efDet.SOMA && <div><span className="font-semibold">SOMA:</span> {efDet.SOMA}</div>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Novedades */}
|
||||
{evolucionDetalle.novedades && (
|
||||
<div className="bg-red-50 dark:bg-red-950/60 p-3 rounded-lg border border-red-200 dark:border-red-800/50">
|
||||
<p className="text-xs font-semibold text-red-800 dark:text-red-300 mb-1">Novedades:</p>
|
||||
<p className="text-xs text-gray-800 dark:text-gray-200 whitespace-pre-wrap">{evolucionDetalle.novedades}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Comentario */}
|
||||
{evolucionDetalle.comentario && (
|
||||
<div className="bg-slate-100 dark:bg-slate-800/60 p-3 rounded-lg border border-slate-200 dark:border-slate-700/50">
|
||||
<p className="text-xs font-semibold text-slate-800 dark:text-slate-200 mb-1">Comentario:</p>
|
||||
<p className="text-xs text-slate-700 dark:text-slate-300 whitespace-pre-wrap">{evolucionDetalle.comentario}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Pendientes */}
|
||||
{evolucionDetalle.pendientes && (
|
||||
<div className="bg-amber-50 dark:bg-amber-950/60 p-3 rounded-lg border border-amber-200 dark:border-amber-800/50">
|
||||
<p className="text-xs font-semibold text-amber-800 dark:text-amber-300 mb-1">Pendientes:</p>
|
||||
<p className="text-xs text-amber-700 dark:text-amber-300 whitespace-pre-wrap">{evolucionDetalle.pendientes}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,616 @@
|
||||
import { useState } from 'react';
|
||||
import { ClipboardList, Plus, Search, LogOut, CheckCircle2, MoreHorizontal, FileText, Trash2 } from 'lucide-react';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
|
||||
import { toast } from 'sonner';
|
||||
import type { Internacion, Paciente, Cama, Grupo, Evolucion, Laboratorio, Cultivo } from '@/types';
|
||||
import { formatDateDDMMYYYY, getNombreProfesional } from '@/lib/utils';
|
||||
import { useHospitalStore } from '@/hooks/useHospitalStore';
|
||||
|
||||
interface InternacionesProps {
|
||||
internaciones: Internacion[];
|
||||
pacientes: Paciente[];
|
||||
camas: Cama[];
|
||||
evoluciones?: Evolucion[];
|
||||
laboratorios?: Laboratorio[];
|
||||
cultivos?: Cultivo[];
|
||||
grupos: Grupo[];
|
||||
onIniciarInternacion: (internacion: Omit<Internacion, 'id' | 'activa'>) => void;
|
||||
onFinalizarInternacion: (internacionId: string, datos: {
|
||||
fechaEgreso: string;
|
||||
diagnosticoEgreso: string;
|
||||
motivoEgreso: Internacion['motivoEgreso']
|
||||
}) => void;
|
||||
onEliminarInternacion?: (internacionId: string) => Promise<void> | void;
|
||||
getPacienteById: (id: string) => Paciente | undefined;
|
||||
getCamaById: (id: string) => Cama | undefined;
|
||||
onVerHC?: (internacionId: string) => void;
|
||||
onNuevoIngreso?: () => void;
|
||||
}
|
||||
|
||||
export function Internaciones({
|
||||
internaciones,
|
||||
pacientes,
|
||||
camas,
|
||||
onIniciarInternacion,
|
||||
onFinalizarInternacion,
|
||||
onEliminarInternacion,
|
||||
getPacienteById,
|
||||
getCamaById,
|
||||
grupos,
|
||||
onVerHC,
|
||||
onNuevoIngreso,
|
||||
}: InternacionesProps) {
|
||||
const { currentUser } = useHospitalStore();
|
||||
const [filtroEstado, setFiltroEstado] = useState<'todas' | 'activas' | 'finalizadas'>('todas');
|
||||
const [dialogoNuevaAbierto, setDialogoNuevaAbierto] = useState(false);
|
||||
const [dialogoEgresoAbierto, setDialogoEgresoAbierto] = useState(false);
|
||||
const [dialogoEliminarAbierto, setDialogoEliminarAbierto] = useState(false);
|
||||
const [internacionSeleccionada, setInternacionSeleccionada] = useState<Internacion | null>(null);
|
||||
const [internacionAEliminar, setInternacionAEliminar] = useState<Internacion | null>(null);
|
||||
const [busqueda, setBusqueda] = useState('');
|
||||
const [pacienteSeleccionado, setPacienteSeleccionado] = useState<string>('');
|
||||
const [camaSeleccionada, setCamaSeleccionada] = useState<string>('');
|
||||
const [grupoSeleccionada, setGrupoSeleccionada] = useState<string>('');
|
||||
const [diagnosticoIngreso, setDiagnosticoIngreso] = useState('');
|
||||
const [enfermedadActual, setEnfermedadActual] = useState('');
|
||||
const [motivoConsulta, setMotivoConsulta] = useState('');
|
||||
const [antecedentesEnfermedadActual, setAntecedentesEnfermedadActual] = useState('');
|
||||
const effectiveMedico = getNombreProfesional(currentUser);
|
||||
|
||||
// Formulario nueva internación
|
||||
const [fechaEgreso, setFechaEgreso] = useState('');
|
||||
const [diagnosticoEgreso, setDiagnosticoEgreso] = useState('');
|
||||
const [motivoEgreso, setMotivoEgreso] = useState<Internacion['motivoEgreso']>('Alta médica');
|
||||
|
||||
const resetFormularioNueva = () => {
|
||||
setPacienteSeleccionado('');
|
||||
setCamaSeleccionada('');
|
||||
setGrupoSeleccionada('');
|
||||
setDiagnosticoIngreso('');
|
||||
setEnfermedadActual('');
|
||||
setAntecedentesEnfermedadActual('');
|
||||
};
|
||||
|
||||
const resetFormularioEgreso = () => {
|
||||
setFechaEgreso('');
|
||||
setDiagnosticoEgreso('');
|
||||
setMotivoEgreso('Alta médica');
|
||||
setInternacionSeleccionada(null);
|
||||
};
|
||||
|
||||
const handleIniciarInternacion = async () => {
|
||||
if (pacienteSeleccionado && camaSeleccionada && grupoSeleccionada && (diagnosticoIngreso || motivoConsulta) && enfermedadActual && effectiveMedico) {
|
||||
try {
|
||||
await onIniciarInternacion({
|
||||
pacienteId: pacienteSeleccionado,
|
||||
camaId: camaSeleccionada,
|
||||
grupoId: grupoSeleccionada,
|
||||
diagnosticoIngreso: diagnosticoIngreso || motivoConsulta,
|
||||
motivoConsulta,
|
||||
enfermedadActual,
|
||||
antecedentesEnfermedadActual: antecedentesEnfermedadActual || undefined,
|
||||
medicoIngresante: effectiveMedico,
|
||||
});
|
||||
toast.success('Internación iniciada correctamente');
|
||||
resetFormularioNueva();
|
||||
setDialogoNuevaAbierto(false);
|
||||
} catch (err) {
|
||||
console.error('Error al iniciar internación:', err);
|
||||
toast.error('Error al iniciar la internación');
|
||||
}
|
||||
} else {
|
||||
toast.error('Por favor complete todos los campos obligatorios');
|
||||
}
|
||||
};
|
||||
|
||||
const handleFinalizarInternacion = () => {
|
||||
if (internacionSeleccionada && fechaEgreso && diagnosticoEgreso && motivoEgreso) {
|
||||
onFinalizarInternacion(internacionSeleccionada.id, {
|
||||
fechaEgreso,
|
||||
diagnosticoEgreso,
|
||||
motivoEgreso,
|
||||
});
|
||||
resetFormularioEgreso();
|
||||
setDialogoEgresoAbierto(false);
|
||||
}
|
||||
};
|
||||
|
||||
const internacionesFiltradas = internaciones.filter(i => {
|
||||
const paciente = getPacienteById(i.pacienteId);
|
||||
const cumpleBusqueda = !busqueda ||
|
||||
(paciente && (
|
||||
paciente.nombre.toLowerCase().includes(busqueda.toLowerCase()) ||
|
||||
paciente.apellido.toLowerCase().includes(busqueda.toLowerCase()) ||
|
||||
paciente.dni.includes(busqueda)
|
||||
));
|
||||
|
||||
const cumpleEstado = filtroEstado === 'todas' ||
|
||||
(filtroEstado === 'activas' && i.activa) ||
|
||||
(filtroEstado === 'finalizadas' && !i.activa);
|
||||
|
||||
return cumpleBusqueda && cumpleEstado;
|
||||
}).sort((a, b) => new Date(b.fechaIngresoClinica || '').getTime() - new Date(a.fechaIngresoClinica || '').getTime());
|
||||
|
||||
const pacientesSinInternar = pacientes.filter(p => {
|
||||
const internacionActiva = internaciones.find(i => i.pacienteId === p.id && i.activa);
|
||||
return !internacionActiva;
|
||||
});
|
||||
|
||||
const parseBedNumber = (numero: string) => {
|
||||
const match = numero.match(/^(\d{3})-(\d+)$/);
|
||||
if (!match) return { sala: 0, cama: 0 };
|
||||
return { sala: parseInt(match[1]), cama: parseInt(match[2]) };
|
||||
};
|
||||
|
||||
const sortedCamas = [...camas].sort((a, b) => {
|
||||
const pa = parseBedNumber(a.numero);
|
||||
const pb = parseBedNumber(b.numero);
|
||||
const getOrden = (sala: number) => {
|
||||
const grupo = Math.floor(sala / 100);
|
||||
const esPar = sala % 2 === 0;
|
||||
if (grupo === 2) return esPar ? { grupo: 2, suborden: 0, sala } : { grupo: 1, suborden: 1, sala };
|
||||
if (grupo === 3) return esPar ? { grupo: 3, suborden: 0, sala } : { grupo: 4, suborden: 1, sala };
|
||||
if (grupo === 4) return esPar ? { grupo: 6, suborden: 0, sala } : { grupo: 5, suborden: 1, sala };
|
||||
return { grupo: 10, suborden: 1, sala };
|
||||
};
|
||||
const oa = getOrden(pa.sala);
|
||||
const ob = getOrden(pb.sala);
|
||||
if (oa.grupo !== ob.grupo) return oa.grupo - ob.grupo;
|
||||
if (oa.suborden === ob.suborden) {
|
||||
return oa.suborden === 0 ? (oa.sala - ob.sala) : (ob.sala - oa.sala);
|
||||
}
|
||||
return oa.suborden - ob.suborden;
|
||||
});
|
||||
|
||||
const getGrupoName = (grupoId?: string) => grupos.find(a => a.id === grupoId)?.nombre;
|
||||
|
||||
const calcularEdad = (fechaNacimiento?: string) => {
|
||||
if (!fechaNacimiento) return '-';
|
||||
const hoy = new Date();
|
||||
const nacimiento = new Date(fechaNacimiento);
|
||||
if (isNaN(nacimiento.getTime())) return '-';
|
||||
let edad = hoy.getFullYear() - nacimiento.getFullYear();
|
||||
const m = hoy.getMonth() - nacimiento.getMonth();
|
||||
if (m < 0 || (m === 0 && hoy.getDate() < nacimiento.getDate())) {
|
||||
edad--;
|
||||
}
|
||||
return edad >= 0 ? `${edad} años` : '-';
|
||||
};
|
||||
|
||||
const calcularDiasDuracion = (internacion: Internacion) => {
|
||||
const fechaStr = internacion.fechaIngresoClinica || internacion.fechaIngreso;
|
||||
if (!fechaStr) return null;
|
||||
|
||||
const hoy = new Date();
|
||||
let fechaFin = hoy;
|
||||
|
||||
if (!internacion.activa && internacion.fechaEgreso) {
|
||||
const egreso = new Date(internacion.fechaEgreso.includes('T') ? internacion.fechaEgreso : `${internacion.fechaEgreso}T00:00:00`);
|
||||
if (!isNaN(egreso.getTime())) {
|
||||
fechaFin = egreso;
|
||||
}
|
||||
}
|
||||
|
||||
const ingreso = new Date(fechaStr.includes('T') ? fechaStr : `${fechaStr}T00:00:00`);
|
||||
if (isNaN(ingreso.getTime())) return null;
|
||||
|
||||
const inicioD = new Date(ingreso.getFullYear(), ingreso.getMonth(), ingreso.getDate());
|
||||
const finD = new Date(fechaFin.getFullYear(), fechaFin.getMonth(), fechaFin.getDate());
|
||||
|
||||
const diffMs = finD.getTime() - inicioD.getTime();
|
||||
const dias = Math.floor(diffMs / (1000 * 60 * 60 * 24));
|
||||
return dias < 0 ? 0 : dias;
|
||||
};
|
||||
|
||||
const abrirDialogoEgreso = (internacion: Internacion) => {
|
||||
setInternacionSeleccionada(internacion);
|
||||
setFechaEgreso(new Date().toISOString().split('T')[0]);
|
||||
setDialogoEgresoAbierto(true);
|
||||
};
|
||||
|
||||
// Ver Historia Clínica (navegar a página)
|
||||
|
||||
return (
|
||||
<div className="space-y-6 dark:text-white">
|
||||
{/* Header */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900 dark:text-white">Internaciones</h1>
|
||||
<p className="text-gray-500 dark:text-gray-400">Gestión de internaciones en sala</p>
|
||||
</div>
|
||||
<Dialog open={dialogoNuevaAbierto} onOpenChange={setDialogoNuevaAbierto}>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="outline" onClick={() => onNuevoIngreso ? onNuevoIngreso() : setDialogoNuevaAbierto(true)}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Nuevo Ingreso
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Nuevo Ingreso</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<Label>Paciente *</Label>
|
||||
{!pacienteSeleccionado ? (
|
||||
<>
|
||||
<Input
|
||||
placeholder="Buscar por apellido, nombre o DNI"
|
||||
value={busqueda}
|
||||
onChange={(e) => setBusqueda(e.target.value)}
|
||||
className="mb-2"
|
||||
/>
|
||||
<div className="max-h-48 overflow-auto border rounded-md">
|
||||
{(() => {
|
||||
const q = busqueda.trim().toLowerCase();
|
||||
if (!q) {
|
||||
return (
|
||||
<div className="p-2 text-sm text-gray-500">Escribe apellido, nombre o DNI para buscar</div>
|
||||
);
|
||||
}
|
||||
const matches = pacientesSinInternar.filter(p => (
|
||||
p.apellido.toLowerCase().includes(q) ||
|
||||
p.nombre.toLowerCase().includes(q) ||
|
||||
p.dni.includes(q)
|
||||
));
|
||||
if (matches.length === 0) {
|
||||
return <div className="p-2 text-sm text-gray-500">No se encontraron pacientes coincidentes</div>;
|
||||
}
|
||||
return matches.map(p => (
|
||||
<button
|
||||
key={p.id}
|
||||
type="button"
|
||||
onClick={() => setPacienteSeleccionado(p.id)}
|
||||
className={`w-full text-left p-2 hover:bg-gray-50 ${pacienteSeleccionado === p.id ? 'bg-gray-100' : ''}`}
|
||||
>
|
||||
{p.apellido}, {p.nombre} — DNI: {p.dni}
|
||||
</button>
|
||||
));
|
||||
})()}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge className="bg-gray-100 text-gray-800 px-3 py-1">
|
||||
{(() => {
|
||||
const p = pacientes.find(x => x.id === pacienteSeleccionado);
|
||||
return p ? `${p.apellido}, ${p.nombre} — DNI: ${p.dni}` : '';
|
||||
})()}
|
||||
</Badge>
|
||||
<Button size="sm" variant="outline" onClick={() => setPacienteSeleccionado('')}>Cambiar</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<Label>Grupo de Trabajo *</Label>
|
||||
<Select value={grupoSeleccionada} onValueChange={setGrupoSeleccionada}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Seleccionar área" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{grupos.filter(a => a.nombre !== 'Fuera de grupo').map(a => (
|
||||
<SelectItem key={a.id} value={a.id}>
|
||||
{a.nombre}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Cama *</Label>
|
||||
<Select value={camaSeleccionada} onValueChange={setCamaSeleccionada}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Seleccionar cama" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{sortedCamas.filter(c => c.estado === 'Disponible').map(c => (
|
||||
<SelectItem key={c.id} value={c.id}>
|
||||
{c.numero} - {getGrupoName(c.grupoId) || 'Sin grupo'} ({c.tipo})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Motivo de Consulta *</Label>
|
||||
<textarea
|
||||
className="w-full p-2 border rounded-md text-sm min-h-[80px]"
|
||||
value={motivoConsulta}
|
||||
onChange={(e) => setMotivoConsulta(e.target.value)}
|
||||
placeholder="Motivo de consulta..."
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Enfermedad Actual *</Label>
|
||||
<textarea
|
||||
className="w-full p-2 border rounded-md text-sm min-h-[100px]"
|
||||
value={enfermedadActual}
|
||||
onChange={(e) => setEnfermedadActual(e.target.value)}
|
||||
placeholder="Describa la enfermedad actual..."
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Antecedentes de Enfermedad Actual</Label>
|
||||
<textarea
|
||||
className="w-full p-2 border rounded-md text-sm min-h-[80px]"
|
||||
value={antecedentesEnfermedadActual}
|
||||
onChange={(e) => setAntecedentesEnfermedadActual(e.target.value)}
|
||||
placeholder="Antecedentes relevantes de la enfermedad actual..."
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Médico Ingresante *</Label>
|
||||
<Input
|
||||
value={getNombreProfesional(currentUser)}
|
||||
disabled
|
||||
placeholder="Nombre del médico ingresante"
|
||||
/>
|
||||
</div>
|
||||
<Button variant="outline"
|
||||
className="w-full"
|
||||
onClick={handleIniciarInternacion}
|
||||
disabled={!pacienteSeleccionado || !camaSeleccionada || !motivoConsulta || !enfermedadActual || !effectiveMedico}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Iniciar Internación
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
{/* Filtros */}
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||||
<div className="relative sm:col-span-2">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
|
||||
<Input
|
||||
className="pl-10"
|
||||
placeholder="Buscar paciente..."
|
||||
value={busqueda}
|
||||
onChange={(e) => setBusqueda(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Select value={filtroEstado} onValueChange={(v: 'todas' | 'activas' | 'finalizadas') => setFiltroEstado(v)}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Filtrar por estado" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="todas">Todas las internaciones</SelectItem>
|
||||
<SelectItem value="activas">Internaciones activas</SelectItem>
|
||||
<SelectItem value="finalizadas">Internaciones finalizadas</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Lista de Internaciones en Tabla */}
|
||||
{internacionesFiltradas.length === 0 ? (
|
||||
<div className="text-center py-12 text-gray-400">
|
||||
<ClipboardList className="h-16 w-16 mx-auto mb-4 opacity-50" />
|
||||
<p className="text-lg">
|
||||
{busqueda || filtroEstado !== 'todas'
|
||||
? 'No se encontraron internaciones con esos filtros'
|
||||
: 'No hay internaciones registradas'}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 w-full">
|
||||
<div className="w-full overflow-x-auto rounded-md border bg-card pb-2">
|
||||
<Table className="w-full min-w-max text-sm">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Cama</TableHead>
|
||||
<TableHead>Apellido</TableHead>
|
||||
<TableHead>Nombre</TableHead>
|
||||
<TableHead className="text-center">Edad</TableHead>
|
||||
<TableHead className="text-center">DNI</TableHead>
|
||||
<TableHead className="text-center">Estado</TableHead>
|
||||
<TableHead className="text-center">Fecha Ingreso</TableHead>
|
||||
<TableHead className="text-center">Duración</TableHead>
|
||||
<TableHead className="text-center w-[60px]">Acciones</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{internacionesFiltradas.map((internacion) => {
|
||||
const paciente = getPacienteById(internacion.pacienteId);
|
||||
const cama = getCamaById(internacion.camaId);
|
||||
const fechaIng = internacion.fechaIngresoClinica
|
||||
? formatDateDDMMYYYY(internacion.fechaIngresoClinica)
|
||||
: (internacion.fechaIngreso ? formatDateDDMMYYYY(internacion.fechaIngreso) : '-');
|
||||
|
||||
return (
|
||||
<TableRow key={internacion.id} className="hover:bg-muted/50">
|
||||
<TableCell className="font-medium text-xs whitespace-nowrap">
|
||||
{cama ? cama.numero : '-'}
|
||||
</TableCell>
|
||||
<TableCell className="text-xs font-medium whitespace-nowrap">
|
||||
{paciente?.apellido || '-'}
|
||||
</TableCell>
|
||||
<TableCell className="text-xs font-medium whitespace-nowrap">
|
||||
{paciente?.nombre || '-'}
|
||||
</TableCell>
|
||||
<TableCell className="text-center text-xs whitespace-nowrap">
|
||||
{calcularEdad(paciente?.fechaNacimiento)}
|
||||
</TableCell>
|
||||
<TableCell className="text-center text-xs whitespace-nowrap font-mono">
|
||||
{paciente?.dni || '-'}
|
||||
</TableCell>
|
||||
<TableCell className="text-center">
|
||||
{internacion.activa ? (
|
||||
<Badge className="bg-purple-100 text-purple-800 dark:bg-purple-950/80 dark:text-purple-300 border-purple-200 hover:bg-purple-100">
|
||||
Activa
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge variant="outline" className="bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300 border-gray-300">
|
||||
Alta
|
||||
</Badge>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="text-center text-xs whitespace-nowrap">
|
||||
{fechaIng}
|
||||
</TableCell>
|
||||
<TableCell className="text-center text-xs whitespace-nowrap">
|
||||
{(() => {
|
||||
const dias = calcularDiasDuracion(internacion);
|
||||
if (dias === null) return '-';
|
||||
const esMenorOIgual10 = dias <= 10;
|
||||
return (
|
||||
<Badge
|
||||
className={
|
||||
esMenorOIgual10
|
||||
? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950/80 dark:text-emerald-300 border-emerald-200 hover:bg-emerald-100'
|
||||
: 'bg-red-100 text-red-800 dark:bg-red-950/80 dark:text-red-300 border-red-200 hover:bg-red-100'
|
||||
}
|
||||
>
|
||||
{dias} {dias === 1 ? 'día' : 'días'}
|
||||
</Badge>
|
||||
);
|
||||
})()}
|
||||
</TableCell>
|
||||
<TableCell className="text-center p-1">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button size="sm" variant="ghost" className="h-8 w-8 p-0">
|
||||
<MoreHorizontal className="h-4 w-4" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => { if (typeof onVerHC === 'function') onVerHC(internacion.id); }}>
|
||||
<FileText className="mr-2 h-4 w-4" />
|
||||
Ver HC
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
className="text-red-600 focus:text-red-600"
|
||||
onClick={() => {
|
||||
setInternacionAEliminar(internacion);
|
||||
setDialogoEliminarAbierto(true);
|
||||
}}
|
||||
>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Eliminar HC
|
||||
</DropdownMenuItem>
|
||||
{internacion.activa && (
|
||||
<DropdownMenuItem onClick={() => abrirDialogoEgreso(internacion)}>
|
||||
<LogOut className="mr-2 h-4 w-4" />
|
||||
Registrar Egreso
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Modal Registrar Egreso */}
|
||||
<Dialog open={dialogoEgresoAbierto} onOpenChange={(open) => { if (!open) resetFormularioEgreso(); setDialogoEgresoAbierto(open); }}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Dar Alta</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<Label>Paciente</Label>
|
||||
<Input
|
||||
value={(() => {
|
||||
if (!internacionSeleccionada) return '';
|
||||
const p = getPacienteById(internacionSeleccionada.pacienteId);
|
||||
return p ? `${p.apellido}, ${p.nombre}` : '';
|
||||
})()}
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Fecha de Egreso *</Label>
|
||||
<Input
|
||||
type="date"
|
||||
value={fechaEgreso}
|
||||
onChange={(e) => setFechaEgreso(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Motivo de Egreso *</Label>
|
||||
<Select value={motivoEgreso} onValueChange={(v) => setMotivoEgreso(v as Internacion['motivoEgreso'])}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="Alta médica">Alta médica</SelectItem>
|
||||
<SelectItem value="Alta voluntaria">Alta voluntaria</SelectItem>
|
||||
<SelectItem value="Derivación">Derivación</SelectItem>
|
||||
<SelectItem value="Fallecimiento">Fallecimiento</SelectItem>
|
||||
<SelectItem value="Otro">Otro</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Diagnóstico de Egreso *</Label>
|
||||
<textarea
|
||||
className="w-full p-2 border rounded-md text-sm min-h-[80px]"
|
||||
value={diagnosticoEgreso}
|
||||
onChange={(e) => setDiagnosticoEgreso(e.target.value)}
|
||||
placeholder="Ingrese el diagnóstico de egreso..."
|
||||
/>
|
||||
</div>
|
||||
<Button variant="outline"
|
||||
className="w-full"
|
||||
onClick={handleFinalizarInternacion}
|
||||
disabled={!fechaEgreso || !diagnosticoEgreso || !motivoEgreso}
|
||||
>
|
||||
<CheckCircle2 className="h-4 w-4 mr-2" />
|
||||
Confirmar Egreso
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
{/* Modal Confirmar Eliminación HC */}
|
||||
<Dialog open={dialogoEliminarAbierto} onOpenChange={(open) => { if (!open) setInternacionAEliminar(null); setDialogoEliminarAbierto(open); }}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Eliminar Historia Clínica de Internación</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-2">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
¿Está seguro de que desea eliminar esta historia clínica de internación y todos sus registros asociados (evoluciones, laboratorios, cultivos, indicaciones, etc.)? Esta acción no se puede deshacer.
|
||||
</p>
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
<Button variant="outline" onClick={() => setDialogoEliminarAbierto(false)}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={async () => {
|
||||
if (internacionAEliminar && typeof onEliminarInternacion === 'function') {
|
||||
await onEliminarInternacion(internacionAEliminar.id);
|
||||
setDialogoEliminarAbierto(false);
|
||||
setInternacionAEliminar(null);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Eliminar Definitivamente
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
import { useState } from 'react';
|
||||
import {
|
||||
LayoutDashboard,
|
||||
Bed,
|
||||
Users,
|
||||
ClipboardList,
|
||||
FileText,
|
||||
Activity,
|
||||
Microscope,
|
||||
Menu,
|
||||
Sun,
|
||||
Moon,
|
||||
LogOut,
|
||||
UserCog
|
||||
} from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Sheet, SheetContent, SheetTrigger, SheetTitle, SheetDescription, SheetHeader } from '@/components/ui/sheet';
|
||||
|
||||
import type { Vista, Usuario } from '@/types';
|
||||
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { useTheme } from "@/components/theme-provider"
|
||||
|
||||
interface LayoutProps {
|
||||
children: React.ReactNode;
|
||||
vistaActual: Vista;
|
||||
onCambiarVista: (vista: Vista) => void;
|
||||
currentUser: Usuario | null;
|
||||
onLogout: () => void;
|
||||
}
|
||||
|
||||
export function Layout({ children, vistaActual, onCambiarVista, currentUser, onLogout }: LayoutProps) {
|
||||
const { theme, setTheme } = useTheme()
|
||||
const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
|
||||
|
||||
const toggleDarkMode = () => setTheme(theme === "dark" ? "light" : "dark")
|
||||
|
||||
const menuItems: { vista: Vista; label: string; icon: React.ElementType; rolRequerido?: string }[] = [
|
||||
{ vista: 'dashboard', label: 'Dashboard', icon: LayoutDashboard },
|
||||
{ vista: 'camas', label: 'Camas', icon: Bed, rolRequerido: 'medico' },
|
||||
{ vista: 'pacientes', label: 'Pacientes', icon: Users },
|
||||
{ vista: 'internaciones', label: 'Internaciones', icon: ClipboardList },
|
||||
{ vista: 'evoluciones', label: 'Evoluciones', icon: FileText },
|
||||
{ vista: 'cultivos', label: 'Cultivos', icon: Microscope },
|
||||
];
|
||||
|
||||
const filteredMenuItems = menuItems.filter(item => {
|
||||
const rol = currentUser?.rol as string | undefined;
|
||||
if (!item.rolRequerido) return true;
|
||||
if (rol === 'admin') return true;
|
||||
if (item.rolRequerido === 'medico' && (rol === 'medico' || rol === 'admin')) return true;
|
||||
return false;
|
||||
});
|
||||
|
||||
if ((currentUser?.rol as string) === 'admin') {
|
||||
filteredMenuItems.push({ vista: 'usuarios', label: 'Usuarios', icon: UserCog });
|
||||
}
|
||||
|
||||
const renderNavContent = (onItemClick?: () => void) => (
|
||||
<nav className="flex flex-col gap-2">
|
||||
{filteredMenuItems.map((item) => {
|
||||
const Icon = item.icon;
|
||||
const isActive = vistaActual === item.vista;
|
||||
return (
|
||||
<Button
|
||||
key={item.vista}
|
||||
variant={isActive ? 'default' : 'ghost'}
|
||||
className={`justify-start gap-3 ${isActive ? 'bg-blue-600 hover:bg-blue-700 text-white' : 'hover:bg-gray-100 dark:hover:bg-gray-700 dark:text-gray-200'}`}
|
||||
onClick={() => {
|
||||
onCambiarVista(item.vista);
|
||||
if (onItemClick) onItemClick();
|
||||
}}
|
||||
>
|
||||
<Icon className="h-5 w-5" />
|
||||
<span>{item.label}</span>
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
</nav>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex">
|
||||
{/* Sidebar Desktop */}
|
||||
<aside className="hidden lg:flex w-64 flex-col bg-white dark:bg-gray-800 border-r border-gray-200 dark:border-gray-700 fixed h-full">
|
||||
<div className="p-6 border-b border-gray-200 dark:border-gray-700">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="h-10 w-10 bg-blue-600 rounded-lg flex items-center justify-center">
|
||||
<Activity className="h-6 w-6 text-white" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="font-bold text-lg text-gray-900 dark:text-white leading-tight">Historia Clinica Electrónica</h1>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400">Servicio Clínica Médica - Hospital Santojanni</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-1 p-4 overflow-auto">
|
||||
{renderNavContent()}
|
||||
</div>
|
||||
<div className="p-4 border-t border-gray-200 dark:border-gray-700">
|
||||
<div className="text-sm text-gray-600 dark:text-gray-300 mb-2">
|
||||
<div className="font-medium">{currentUser?.apellido}, {currentUser?.nombre}</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400 capitalize">{currentUser?.rol}</div>
|
||||
</div>
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="icon">
|
||||
<Sun className="h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
|
||||
<Moon className="absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
|
||||
<span className="sr-only">Toggle theme</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem onClick={() => setTheme("light")}>
|
||||
Light
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setTheme("dark")}>
|
||||
Dark
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => setTheme("system")}>
|
||||
System
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<Button variant="outline" size="icon" onClick={onLogout} title="Cerrar sesión">
|
||||
<LogOut className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<div className="text-xs text-gray-400 dark:text-gray-500 text-center mt-2">
|
||||
v2.0
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
{/* Header Mobile */}
|
||||
<header className="lg:hidden fixed top-0 left-0 right-0 h-16 bg-white dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700 z-50 flex items-center justify-between px-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="h-8 w-8 bg-blue-600 rounded-lg flex items-center justify-center">
|
||||
<Activity className="h-5 w-5 text-white" />
|
||||
</div>
|
||||
<span className="font-bold text-gray-900 dark:text-white">Gestion Historia Clinica Electronica</span>
|
||||
</div>
|
||||
<Sheet open={mobileMenuOpen} onOpenChange={setMobileMenuOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<Button variant="ghost" size="icon" className="dark:text-white" onClick={() => setMobileMenuOpen(true)}>
|
||||
<Menu className="h-6 w-6" />
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
<SheetContent side="right" className="w-64 p-0 dark:bg-gray-800">
|
||||
<SheetHeader className="sr-only">
|
||||
<SheetTitle>Menú de navegación</SheetTitle>
|
||||
<SheetDescription>Navegación principal de la aplicación</SheetDescription>
|
||||
</SheetHeader>
|
||||
<div className="p-6 border-b border-gray-200 dark:border-gray-700">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="font-bold text-lg dark:text-white">Menú</span>
|
||||
</div>
|
||||
<div className="mt-2 text-sm text-gray-600 dark:text-gray-300">
|
||||
<div className="font-medium">{currentUser?.apellido}, {currentUser?.nombre}</div>
|
||||
<div className="text-xs text-gray-500 dark:text-gray-400 capitalize">{currentUser?.rol}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-4">
|
||||
{renderNavContent(() => setMobileMenuOpen(false))}
|
||||
</div>
|
||||
<div className="p-4 border-t border-gray-200 dark:border-gray-700 space-y-2">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
toggleDarkMode();
|
||||
setMobileMenuOpen(false);
|
||||
}}
|
||||
className="w-full flex items-center justify-center gap-2 dark:text-white"
|
||||
>
|
||||
{theme === "dark" ? <Sun className="h-4 w-4" /> : <Moon className="h-4 w-4" />}
|
||||
<span className="text-sm">{theme === "dark" ? 'Modo Claro' : 'Modo Oscuro'}</span>
|
||||
</Button>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
onLogout();
|
||||
setMobileMenuOpen(false);
|
||||
}}
|
||||
className="w-full flex items-center justify-center gap-2 dark:text-white"
|
||||
>
|
||||
<LogOut className="h-4 w-4" />
|
||||
<span className="text-sm">Cerrar Sesión</span>
|
||||
</Button>
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
</header>
|
||||
|
||||
{/* Main Content */}
|
||||
<main className="flex-1 lg:ml-64 pt-16 lg:pt-0 min-h-screen">
|
||||
<div className="p-4 lg:p-8 max-w-7xl mx-auto">
|
||||
{children}
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { useState } from 'react';
|
||||
import { useHospitalStore } from '@/hooks/useHospitalStore';
|
||||
import { Card, CardContent, CardDescription, 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 { Shield, Lock, User } from 'lucide-react';
|
||||
|
||||
export function Login() {
|
||||
const { login } = useHospitalStore();
|
||||
const [dni, setDni] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
await login(dni, password);
|
||||
window.location.reload();
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Error de autenticación');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-100 dark:bg-gray-900 p-4">
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader className="text-center">
|
||||
<div className="mx-auto mb-4 w-16 h-16 bg-blue-600 rounded-full flex items-center justify-center">
|
||||
<Shield className="w-8 h-8 text-white" />
|
||||
</div>
|
||||
<CardTitle className="text-2xl">Sistema de Gestión Hospitalaria</CardTitle>
|
||||
<CardDescription>Ingrese sus credenciales para acceder</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="dni">DNI</Label>
|
||||
<div className="relative">
|
||||
<User className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
|
||||
<Input
|
||||
id="dni"
|
||||
type="text"
|
||||
placeholder="Ingrese su DNI"
|
||||
value={dni}
|
||||
onChange={(e) => setDni(e.target.value)}
|
||||
className="pl-10"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Contraseña</Label>
|
||||
<div className="relative">
|
||||
<Lock className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
placeholder="Ingrese su contraseña"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
className="pl-10"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 text-red-600 dark:text-red-400 px-3 py-2 rounded-md text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button type="submit" className="w-full" disabled={loading}>
|
||||
{loading ? 'Ingresando...' : 'Ingresar'}
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,616 @@
|
||||
import { useState } from 'react';
|
||||
import { Bed, CheckCircle2, Clock, Wrench, User, Plus, Trash, Edit2, Save, X } from 'lucide-react';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { formatDateDDMMYYYY, getNombreProfesional, isCamaFueraDeGrupo, computeSector } from '@/lib/utils';
|
||||
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import type { Cama, Paciente, Internacion, Grupo } from '@/types';
|
||||
import { useHospitalStore } from '@/hooks/useHospitalStore';
|
||||
|
||||
interface MapaCamasProps {
|
||||
camas: Cama[];
|
||||
grupos: Grupo[];
|
||||
pacientes: Paciente[];
|
||||
internaciones: Internacion[];
|
||||
onActualizarCama: (id: string, datos: Partial<Cama>) => void;
|
||||
onAgregarCama: (cama: Omit<Cama, 'id'>) => Promise<string | void>;
|
||||
onEliminarCama: (id: string) => void;
|
||||
onIniciarInternacion: (internacion: Omit<Internacion, 'id' | 'activa'>) => Promise<string>;
|
||||
onAgregarGrupo: (grupo: Omit<Grupo, 'id'>) => Promise<string | void>;
|
||||
onActualizarGrupo: (id: string, datos: Partial<Grupo>) => void;
|
||||
onEliminarGrupo: (id: string) => void;
|
||||
getPacienteById: (id: string) => Paciente | undefined;
|
||||
getInternacionById: (id: string) => Internacion | undefined;
|
||||
}
|
||||
|
||||
export function MapaCamas({
|
||||
camas,
|
||||
grupos,
|
||||
pacientes,
|
||||
internaciones,
|
||||
onActualizarCama,
|
||||
onAgregarCama,
|
||||
onEliminarCama,
|
||||
onIniciarInternacion,
|
||||
onAgregarGrupo,
|
||||
onActualizarGrupo,
|
||||
onEliminarGrupo,
|
||||
getPacienteById,
|
||||
}: MapaCamasProps) {
|
||||
const { canEditCama, currentUser } = useHospitalStore();
|
||||
const [filtroSala, setFiltroSala] = useState<string>('todas');
|
||||
const [filtroTipo, setFiltroTipo] = useState<string>('todos');
|
||||
const [filtroEstado, setFiltroEstado] = useState<string>('todos');
|
||||
const [camaSeleccionada, setCamaSeleccionada] = useState<Cama | null>(null);
|
||||
const [grupoSeleccionada, setGrupoSeleccionada] = useState<string>('');
|
||||
const [pacienteSeleccionado, setPacienteSeleccionado] = useState<string>('');
|
||||
const [diagnostico, setDiagnostico] = useState('');
|
||||
const [enfermedadActual, setEnfermedadActual] = useState('');
|
||||
const [antecedentesEnfermedadActual, setAntecedentesEnfermedadActual] = useState('');
|
||||
const effectiveMedico = getNombreProfesional(currentUser);
|
||||
const [dialogoAbierto, setDialogoAbierto] = useState(false);
|
||||
// Grupo dialog state
|
||||
const [grupoDialogOpen, setGrupoDialogOpen] = useState(false);
|
||||
const [grupoNombre, setGrupoNombre] = useState('');
|
||||
const [editingGrupoId, setEditingGrupoId] = useState<string | null>(null);
|
||||
|
||||
// Cama dialog state
|
||||
const [bedDialogOpen, setBedDialogOpen] = useState(false);
|
||||
const [editingBed, setEditingBed] = useState<Cama | null>(null);
|
||||
const [bedNumero, setBedNumero] = useState('');
|
||||
const [bedTipo, setBedTipo] = useState<Cama['tipo']>('General');
|
||||
const [bedGrupoId, setBedGrupoId] = useState<string | undefined>(undefined);
|
||||
|
||||
const salas = Array.from(new Set(camas.map(c => c.grupoId).filter(Boolean))) as string[];
|
||||
const grupoById = Object.fromEntries(grupos.map(a => [a.id, a.nombre]));
|
||||
const tipos = Array.from(new Set(camas.map(c => c.tipo)));
|
||||
|
||||
const camasFiltradas = camas.filter(cama => {
|
||||
if (filtroSala !== 'todas' && cama.grupoId !== filtroSala) return false;
|
||||
if (filtroTipo !== 'todos' && cama.tipo !== filtroTipo) return false;
|
||||
if (filtroEstado !== 'todos' && cama.estado !== filtroEstado) return false;
|
||||
return true;
|
||||
});
|
||||
|
||||
const getEstadoColor = (cama: Cama) => {
|
||||
if (cama.estado === 'Disponible') {
|
||||
return 'bg-emerald-100 border-emerald-300 text-emerald-800 dark:bg-emerald-950/80 dark:border-emerald-700/60 dark:text-emerald-200';
|
||||
}
|
||||
if (cama.estado === 'Reservada') {
|
||||
return 'bg-orange-100 border-orange-300 text-orange-800 dark:bg-orange-950/80 dark:border-orange-700/60 dark:text-orange-200';
|
||||
}
|
||||
if (cama.estado === 'Ocupada') {
|
||||
// Tipos de aislamiento
|
||||
const aislamientos = ['Aislamiento KPC', 'Aislamiento COVID', 'Aislamiento Clostridium', 'Aislamiento Neutropenico'];
|
||||
if (aislamientos.includes(cama.tipo)) {
|
||||
return 'bg-red-100 border-red-300 text-red-800 dark:bg-red-950/80 dark:border-red-700/60 dark:text-red-200';
|
||||
}
|
||||
return 'bg-blue-100 border-blue-300 text-blue-800 dark:bg-blue-950/80 dark:border-blue-700/60 dark:text-blue-200';
|
||||
}
|
||||
return 'bg-amber-100 border-amber-300 text-amber-800 dark:bg-amber-950/80 dark:border-amber-700/60 dark:text-amber-200';
|
||||
};
|
||||
|
||||
const getEstadoIcono = (cama: Cama) => {
|
||||
switch (cama.estado) {
|
||||
case 'Disponible': return <CheckCircle2 className="h-5 w-5" />;
|
||||
case 'Ocupada': return <User className="h-5 w-5" />;
|
||||
case 'Reparacion': return <Wrench className="h-5 w-5" />;
|
||||
case 'Reservada': return <Clock className="h-5 w-5" />;
|
||||
}
|
||||
};
|
||||
|
||||
const parseBedNumber = (numero: string) => {
|
||||
const match = numero.match(/^(\d{3})-(\d+)$/);
|
||||
if (!match) return { sala: 0, cama: 0 };
|
||||
return {
|
||||
sala: parseInt(match[1]),
|
||||
cama: parseInt(match[2])
|
||||
};
|
||||
};
|
||||
|
||||
const sortedCamas = [...camasFiltradas].sort((a, b) => {
|
||||
const pa = parseBedNumber(a.numero);
|
||||
const pb = parseBedNumber(b.numero);
|
||||
|
||||
const getOrden = (sala: number) => {
|
||||
const grupo = Math.floor(sala / 100);
|
||||
const esPar = sala % 2 === 0;
|
||||
|
||||
if (grupo === 2) {
|
||||
if (esPar) return { grupo: 2, suborden: 0, sala }; // 2XX pares, menor a mayor
|
||||
return { grupo: 1, suborden: 1, sala }; // 2XX impares, mayor a menor
|
||||
}
|
||||
if (grupo === 3) {
|
||||
if (esPar) return { grupo: 3, suborden: 0, sala }; // 3XX pares, menor a mayor
|
||||
return { grupo: 4, suborden: 1, sala }; // 3XX impares, mayor a menor
|
||||
}
|
||||
if (grupo === 4) {
|
||||
if (esPar) return { grupo: 6, suborden: 0, sala }; // 4XX pares, menor a mayor
|
||||
return { grupo: 5, suborden: 1, sala }; // 4XX impares, mayor a menor
|
||||
}
|
||||
return { grupo: 10, suborden: 1, sala };
|
||||
};
|
||||
|
||||
const oa = getOrden(pa.sala);
|
||||
const ob = getOrden(pb.sala);
|
||||
|
||||
if (oa.grupo !== ob.grupo) return oa.grupo - ob.grupo;
|
||||
if (oa.suborden === ob.suborden) {
|
||||
if (oa.suborden === 0) return (oa.sala || pa.sala) - (ob.sala || pb.sala);
|
||||
return (ob.sala || 0) - (oa.sala || 0);
|
||||
}
|
||||
return oa.suborden - ob.suborden;
|
||||
});
|
||||
|
||||
const handleOcuparCama = () => {
|
||||
if (camaSeleccionada && grupoSeleccionada && pacienteSeleccionado && diagnostico && enfermedadActual && effectiveMedico) {
|
||||
onIniciarInternacion({
|
||||
pacienteId: pacienteSeleccionado,
|
||||
camaId: camaSeleccionada.id,
|
||||
grupoId: grupoSeleccionada,
|
||||
diagnosticoIngreso: diagnostico,
|
||||
enfermedadActual,
|
||||
antecedentesEnfermedadActual: antecedentesEnfermedadActual || undefined,
|
||||
medicoIngresante: effectiveMedico,
|
||||
});
|
||||
setDialogoAbierto(false);
|
||||
setCamaSeleccionada(null);
|
||||
setGrupoSeleccionada('');
|
||||
setPacienteSeleccionado('');
|
||||
setDiagnostico('');
|
||||
setEnfermedadActual('');
|
||||
setAntecedentesEnfermedadActual('');
|
||||
}
|
||||
};
|
||||
|
||||
const handleCambiarEstado = (cama: Cama, nuevoEstado: Cama['estado']) => {
|
||||
onActualizarCama(cama.id, { estado: nuevoEstado });
|
||||
};
|
||||
|
||||
const pacientesSinInternar = pacientes.filter(p => {
|
||||
const internacionActiva = internaciones.find(i => i.pacienteId === p.id && i.activa);
|
||||
return !internacionActiva;
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-6 dark:text-white">
|
||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900 dark:text-white">Mapa de Camas</h1>
|
||||
<p className="text-gray-500 dark:text-gray-400">Gestión de camas del servicio</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="outline" className="bg-green-50 text-green-700 dark:bg-green-900 dark:text-green-300 dark:border-green-700">
|
||||
{camas.filter(c => c.estado === 'Disponible' && !isCamaFueraDeGrupo(c, grupos)).length} Disponibles
|
||||
</Badge>
|
||||
<Badge variant="outline" className="bg-red-50 text-red-700 dark:bg-red-900 dark:text-red-300 dark:border-red-700">
|
||||
{camas.filter(c => c.estado === 'Ocupada' && !isCamaFueraDeGrupo(c, grupos)).length} Ocupadas
|
||||
</Badge>
|
||||
<div className="ml-4 flex items-center gap-2 flex-wrap sm:flex-nowrap">
|
||||
<Button variant="outline" onClick={() => {
|
||||
setEditingGrupoId(null);
|
||||
setGrupoNombre('');
|
||||
setGrupoDialogOpen(true);
|
||||
}} className="text-xs px-2 py-1 sm:text-sm sm:px-4 sm:py-2">
|
||||
Administrar Grupos
|
||||
</Button>
|
||||
<Button variant="outline" onClick={() => {
|
||||
setEditingBed(null);
|
||||
setBedNumero('');
|
||||
setBedTipo('General');
|
||||
setBedGrupoId(grupos?.[0]?.id);
|
||||
setBedDialogOpen(true);
|
||||
}} className="text-xs px-2 py-1 sm:text-sm sm:px-4 sm:py-2">
|
||||
<Plus className="h-3 w-3 sm:h-4 sm:w-4 sm:mr-1" />
|
||||
<span className="hidden sm:inline">Agregar Cama</span>
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Filtros */}
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<Label className="text-xs text-gray-500 mb-1 block">Grupo / Área</Label>
|
||||
<Select value={filtroSala} onValueChange={setFiltroSala}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Todos los grupos" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="todas">Todos los grupos</SelectItem>
|
||||
{salas.map(sala => (
|
||||
<SelectItem key={sala} value={sala}>{grupoById[sala] ?? sala}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs text-gray-500 mb-1 block">Tipo</Label>
|
||||
<Select value={filtroTipo} onValueChange={setFiltroTipo}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Todos los tipos" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="todos">Todos los tipos</SelectItem>
|
||||
{tipos.map(tipo => (
|
||||
<SelectItem key={tipo} value={tipo}>{tipo}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div>
|
||||
<Label className="text-xs text-gray-500 mb-1 block">Estado</Label>
|
||||
<Select value={filtroEstado} onValueChange={setFiltroEstado}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Todos los estados" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="todos">Todos los estados</SelectItem>
|
||||
<SelectItem value="Disponible">Disponible</SelectItem>
|
||||
<SelectItem value="Ocupada">Ocupada</SelectItem>
|
||||
<SelectItem value="Mantenimiento">Mantenimiento</SelectItem>
|
||||
<SelectItem value="Reservada">Reservada</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Mapa de Camas */}
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-2 sm:gap-4">
|
||||
{sortedCamas.map((cama) => {
|
||||
const internacion = internaciones.find(i => i.camaId === cama.id && i.activa);
|
||||
const paciente = internacion ? getPacienteById(internacion.pacienteId) : null;
|
||||
|
||||
return (
|
||||
<Dialog key={cama.id}>
|
||||
<DialogTrigger asChild>
|
||||
<Card
|
||||
className={`cursor-pointer hover:shadow-md transition-shadow border-2 w-full ${getEstadoColor(cama)}`}
|
||||
onClick={() => setCamaSeleccionada(cama)}
|
||||
>
|
||||
<CardContent className="p-2 sm:p-4">
|
||||
<div className="flex items-center justify-between mb-1 sm:mb-2">
|
||||
<Bed className="h-4 w-4 sm:h-6 sm:w-6" />
|
||||
{getEstadoIcono(cama)}
|
||||
</div>
|
||||
<p className="font-bold text-sm sm:text-lg">{cama.numero}</p>
|
||||
<p className="text-xs opacity-75 truncate">{cama.grupoId ? grupoById[cama.grupoId] ?? 'Grupo desconocido' : 'Sin grupo'} - {computeSector(cama.numero)}</p>
|
||||
<Badge variant="outline" className="mt-1 sm:mt-2 text-xs bg-white/50 dark:bg-gray-800 dark:text-gray-300">
|
||||
{cama.tipo}
|
||||
</Badge>
|
||||
{cama.estado === 'Ocupada' && paciente && (
|
||||
<div className="mt-1 sm:mt-2 pt-1 sm:pt-2 border-t border-current/20">
|
||||
<p className="text-xs font-medium truncate">
|
||||
{paciente.apellido}, {paciente.nombre}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
|
||||
</CardContent>
|
||||
</Card>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Bed className="h-5 w-5" />
|
||||
Cama {cama.numero} - {cama.grupoId ? grupoById[cama.grupoId] ?? 'Grupo desconocido' : 'Sin grupo'}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge className={getEstadoColor(cama)}>
|
||||
{cama.estado}
|
||||
</Badge>
|
||||
<Badge variant="outline">{cama.tipo}</Badge>
|
||||
</div>
|
||||
|
||||
{cama.estado === 'Ocupada' && paciente && internacion && (
|
||||
<div className="bg-gray-50 dark:bg-gray-800/80 border border-transparent dark:border-gray-700/60 p-4 rounded-lg space-y-2">
|
||||
<p className="font-medium text-gray-900 dark:text-gray-100">Paciente:</p>
|
||||
<p className="text-lg font-semibold text-gray-900 dark:text-gray-100">{paciente.apellido}, {paciente.nombre}</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">DNI: {paciente.dni}</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">Ingreso: {internacion.fechaIngresoClinica ? formatDateDDMMYYYY(internacion.fechaIngresoClinica) : 'N/A'}</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">Diagnóstico: {internacion.diagnosticoIngreso}</p>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">Médico: {internacion.medicoIngresante}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<p className="font-medium">Acciones:</p>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
|
||||
{cama.estado === 'Disponible' && canEditCama(cama.id) && (
|
||||
<Dialog open={dialogoAbierto} onOpenChange={setDialogoAbierto}>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="outline"
|
||||
className="w-full"
|
||||
onClick={() => {
|
||||
setCamaSeleccionada(cama);
|
||||
setDialogoAbierto(true);
|
||||
}}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Ocupar
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Nueva Internación - Cama {cama.numero}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<Label>Paciente *</Label>
|
||||
<Select value={pacienteSeleccionado} onValueChange={setPacienteSeleccionado}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Seleccionar paciente" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{pacientesSinInternar.map(p => (
|
||||
<SelectItem key={p.id} value={p.id}>
|
||||
{p.apellido}, {p.nombre} - DNI: {p.dni}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Grupo de Trabajo *</Label>
|
||||
<Select value={grupoSeleccionada} onValueChange={setGrupoSeleccionada}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Seleccionar área" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{grupos.filter(a => a.nombre !== 'Fuera de grupo').map(a => (
|
||||
<SelectItem key={a.id} value={a.id}>
|
||||
{a.nombre}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Diagnóstico de Ingreso *</Label>
|
||||
<textarea
|
||||
className="w-full p-2 border rounded-md text-sm"
|
||||
rows={3}
|
||||
value={diagnostico}
|
||||
onChange={(e) => setDiagnostico(e.target.value)}
|
||||
placeholder="Ingrese el diagnóstico..."
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Enfermedad Actual *</Label>
|
||||
<textarea
|
||||
className="w-full p-2 border rounded-md text-sm"
|
||||
rows={4}
|
||||
value={enfermedadActual}
|
||||
onChange={(e) => setEnfermedadActual(e.target.value)}
|
||||
placeholder="Describa la enfermedad actual..."
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Antecedentes de Enfermedad Actual</Label>
|
||||
<textarea
|
||||
className="w-full p-2 border rounded-md text-sm"
|
||||
rows={3}
|
||||
value={antecedentesEnfermedadActual}
|
||||
onChange={(e) => setAntecedentesEnfermedadActual(e.target.value)}
|
||||
placeholder="Antecedentes relevantes..."
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Médico Tratante *</Label>
|
||||
<input
|
||||
type="text"
|
||||
className="w-full p-2 border rounded-md text-sm bg-gray-100 dark:bg-gray-800 cursor-not-allowed"
|
||||
value={getNombreProfesional(currentUser)}
|
||||
disabled
|
||||
placeholder="Nombre del médico..."
|
||||
/>
|
||||
</div>
|
||||
<Button variant="outline"
|
||||
className="w-full"
|
||||
onClick={handleOcuparCama}
|
||||
disabled={!pacienteSeleccionado || !diagnostico || !enfermedadActual || !effectiveMedico}
|
||||
>
|
||||
<Plus className="h-4 w-4 mr-1" />
|
||||
Iniciar Internación
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)}
|
||||
|
||||
{cama.estado !== 'Disponible' && canEditCama(cama.id) && (
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
onClick={() => handleCambiarEstado(cama, 'Disponible')}
|
||||
>
|
||||
<CheckCircle2 className="h-4 w-4 mr-1" />
|
||||
Disponible
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{cama.estado !== 'Reparacion' && canEditCama(cama.id) && (
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
onClick={() => handleCambiarEstado(cama, 'Reparacion')}
|
||||
>
|
||||
<Wrench className="h-4 w-4 mr-1" />
|
||||
Reparacion
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{cama.estado !== 'Reservada' && canEditCama(cama.id) && (
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
onClick={() => handleCambiarEstado(cama, 'Reservada')}
|
||||
>
|
||||
<Clock className="h-4 w-4 mr-1" />
|
||||
Reservar
|
||||
</Button>
|
||||
)}
|
||||
|
||||
|
||||
{canEditCama(cama.id) && (
|
||||
<Button variant="outline" onClick={() => {
|
||||
setEditingBed(cama);
|
||||
setBedNumero(cama.numero);
|
||||
setBedTipo(cama.tipo);
|
||||
setBedGrupoId(cama.grupoId);
|
||||
setBedDialogOpen(true);
|
||||
}}>
|
||||
<Edit2 className="h-4 w-4 mr-1" />Editar
|
||||
</Button>
|
||||
)}
|
||||
{canEditCama(cama.id) && (
|
||||
<Button variant="destructive" onClick={() => {
|
||||
onEliminarCama(cama.id);
|
||||
}}>
|
||||
<Trash className="h-4 w-4 mr-1" />Eliminar
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Grupo dialog */}
|
||||
<Dialog open={grupoDialogOpen} onOpenChange={setGrupoDialogOpen}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{editingGrupoId ? 'Editar Grupo' : 'Nuevo Grupo'}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<Label>Nombre</Label>
|
||||
<Input value={grupoNombre} onChange={(e) => setGrupoNombre(e.target.value)} />
|
||||
</div>
|
||||
<div className="flex gap-2 justify-end">
|
||||
{editingGrupoId && (
|
||||
<Button size="sm" variant="destructive" onClick={() => { if (confirm('Eliminar grupo?')) { onEliminarGrupo(editingGrupoId); setGrupoDialogOpen(false); } }}>
|
||||
<Trash className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
<Button size="sm" variant="outline" onClick={() => setGrupoDialogOpen(false)}>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" onClick={() => {
|
||||
if (!grupoNombre.trim()) return alert('Nombre requerido');
|
||||
if (editingGrupoId) onActualizarGrupo(editingGrupoId, { nombre: grupoNombre });
|
||||
else onAgregarGrupo({ nombre: grupoNombre });
|
||||
setGrupoDialogOpen(false);
|
||||
}}>
|
||||
<Save className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium">Grupos existentes</p>
|
||||
<div className="mt-2 space-y-2">
|
||||
{grupos.map(a => (
|
||||
<div key={a.id} className="flex items-center justify-between">
|
||||
<div>{a.nombre}</div>
|
||||
<div className="flex gap-1">
|
||||
<Button size="sm" variant="outline" onClick={() => { setEditingGrupoId(a.id); setGrupoNombre(a.nombre); }}>
|
||||
<Edit2 className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button size="sm" variant="outline" className="text-red-600" onClick={() => { if (confirm('Eliminar grupo?')) onEliminarGrupo(a.id); }}>
|
||||
<Trash className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Bed dialog */}
|
||||
<Dialog open={bedDialogOpen} onOpenChange={setBedDialogOpen}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{editingBed ? `Editar Cama ${editingBed.numero}` : 'Nueva Cama'}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<Label>Número</Label>
|
||||
<Input value={bedNumero} onChange={(e) => setBedNumero(e.target.value)} />
|
||||
</div>
|
||||
<div>
|
||||
<Label>Tipo</Label>
|
||||
<Select value={bedTipo} onValueChange={(v) => setBedTipo(v as Cama['tipo'])}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="General">General</SelectItem>
|
||||
<SelectItem value="Aislamiento KPC">Aislamiento KPC</SelectItem>
|
||||
<SelectItem value="Aislamiento COVID">Aislamiento COVID</SelectItem>
|
||||
<SelectItem value="Aislamiento Clostridium">Aislamiento Clostridium</SelectItem>
|
||||
<SelectItem value="Aislamiento Neutropenico">Aislamiento Neutropenico</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Grupo / Área</Label>
|
||||
<Select value={bedGrupoId ?? '__none'} onValueChange={(v) => setBedGrupoId(v === '__none' ? undefined : v)}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Seleccione grupo" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="__none">Sin grupo</SelectItem>
|
||||
{grupos.map(a => (
|
||||
<SelectItem key={a.id} value={a.id}>{a.nombre}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex gap-2 justify-end">
|
||||
{editingBed && (
|
||||
<Button variant="destructive" onClick={() => { onEliminarCama(editingBed.id); setBedDialogOpen(false); }}>
|
||||
Eliminar
|
||||
</Button>
|
||||
)}
|
||||
<Button variant="outline" onClick={() => setBedDialogOpen(false)}><X className="h-4 w-4 mr-2" />Cancelar</Button>
|
||||
<Button variant="outline" onClick={() => {
|
||||
if (!bedNumero.trim()) return alert('Número requerido');
|
||||
if (editingBed) {
|
||||
onActualizarCama(editingBed.id, { numero: bedNumero, tipo: bedTipo, grupoId: bedGrupoId });
|
||||
} else {
|
||||
onAgregarCama({ numero: bedNumero, tipo: bedTipo, estado: 'Disponible', grupoId: bedGrupoId });
|
||||
}
|
||||
setBedDialogOpen(false);
|
||||
}}>Guardar</Button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{camasFiltradas.length === 0 && (
|
||||
<div className="text-center py-12 text-gray-400">
|
||||
<Bed className="h-16 w-16 mx-auto mb-4 opacity-50" />
|
||||
<p className="text-lg">No se encontraron camas con los filtros seleccionados</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,512 @@
|
||||
import { useState } from 'react';
|
||||
import { ArrowLeft, Save, X, Bed, Calendar, Stethoscope, User, Loader2 } from 'lucide-react';
|
||||
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 { Badge } from '@/components/ui/badge';
|
||||
import { toast } from 'sonner';
|
||||
import type { Paciente, Cama, Grupo, Internacion } from '@/types';
|
||||
import { getNombreProfesional, computeSector } from '@/lib/utils';
|
||||
import { useHospitalStore } from '@/hooks/useHospitalStore';
|
||||
|
||||
interface NuevoIngresoProps {
|
||||
pacientes: Paciente[];
|
||||
camas: Cama[];
|
||||
grupos: Grupo[];
|
||||
onIniciarInternacion: (internacion: Omit<Internacion, 'id' | 'activa'>) => Promise<string>;
|
||||
onAgregarCama?: (cama: Omit<Cama, 'id'>) => Promise<string>;
|
||||
onAgregarPaciente?: (paciente: Omit<Paciente, 'id'>) => void;
|
||||
onActualizarPaciente?: (id: string, datos: Partial<Paciente>) => void;
|
||||
onVolver: () => void;
|
||||
getGrupoName: (grupoId: string | undefined) => string;
|
||||
internaciones: Internacion[];
|
||||
}
|
||||
|
||||
export function NuevoIngreso({ pacientes, camas, grupos, onIniciarInternacion, onAgregarCama, onVolver, getGrupoName, internaciones }: NuevoIngresoProps) {
|
||||
const { currentUser } = useHospitalStore();
|
||||
const [pacienteSeleccionado, setPacienteSeleccionado] = useState<string>('');
|
||||
const [busqueda, setBusqueda] = useState('');
|
||||
const [camaSeleccionada, setCamaSeleccionada] = useState('');
|
||||
const [camaInput, setCamaInput] = useState('');
|
||||
const [modoCama, setModoCama] = useState<'seleccionar' | 'escribir'>('seleccionar');
|
||||
const effectiveMedico = getNombreProfesional(currentUser);
|
||||
const [fechaIngresoHospital, setFechaIngresoHospital] = useState('');
|
||||
const [fechaIngresoClinica, setFechaIngresoClinica] = useState('');
|
||||
const [motivoConsulta, setMotivoConsulta] = useState('');
|
||||
const [diagnosticoIngreso, setDiagnosticoIngreso] = useState('');
|
||||
const [enfermedadActual, setEnfermedadActual] = useState('');
|
||||
const [antecedentesEnfermedadActual, setAntecedentesEnfermedadActual] = useState('');
|
||||
const [apache, setApache] = useState('');
|
||||
const [derivacion, setDerivacion] = useState('');
|
||||
const [grupoSeleccionado, setGrupoSeleccionado] = useState<string>('');
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const resetFormulario = () => {
|
||||
setPacienteSeleccionado('');
|
||||
setBusqueda('');
|
||||
setCamaSeleccionada('');
|
||||
setCamaInput('');
|
||||
setGrupoSeleccionado('');
|
||||
setFechaIngresoHospital('');
|
||||
setFechaIngresoClinica('');
|
||||
setMotivoConsulta('');
|
||||
setDiagnosticoIngreso('');
|
||||
setEnfermedadActual('');
|
||||
setAntecedentesEnfermedadActual('');
|
||||
setApache('');
|
||||
setDerivacion('');
|
||||
};
|
||||
|
||||
const pacientesSinInternar = pacientes.filter(p => {
|
||||
const internacionActiva = internaciones.find(i => i.pacienteId === p.id && i.activa);
|
||||
return !internacionActiva;
|
||||
});
|
||||
|
||||
const parseBedNumber = (numero: string) => {
|
||||
const match = numero.match(/^(\d{3})-(\d+)$/);
|
||||
if (!match) return { sala: 0, cama: 0 };
|
||||
return {
|
||||
sala: parseInt(match[1]),
|
||||
cama: parseInt(match[2])
|
||||
};
|
||||
};
|
||||
|
||||
const sortedCamas = [...camas].sort((a, b) => {
|
||||
const pa = parseBedNumber(a.numero);
|
||||
const pb = parseBedNumber(b.numero);
|
||||
|
||||
const getOrden = (sala: number) => {
|
||||
const grupo = Math.floor(sala / 100);
|
||||
const esPar = sala % 2 === 0;
|
||||
|
||||
if (grupo === 2) {
|
||||
if (esPar) return { grupo: 2, suborden: 0, sala };
|
||||
return { grupo: 1, suborden: 1, sala };
|
||||
}
|
||||
if (grupo === 3) {
|
||||
if (esPar) return { grupo: 3, suborden: 0, sala };
|
||||
return { grupo: 4, suborden: 1, sala };
|
||||
}
|
||||
if (grupo === 4) {
|
||||
if (esPar) return { grupo: 6, suborden: 0, sala };
|
||||
return { grupo: 5, suborden: 1, sala };
|
||||
}
|
||||
return { grupo: 10, suborden: 1, sala };
|
||||
};
|
||||
|
||||
const oa = getOrden(pa.sala);
|
||||
const ob = getOrden(pb.sala);
|
||||
|
||||
if (oa.grupo !== ob.grupo) return oa.grupo - ob.grupo;
|
||||
if (oa.suborden === ob.suborden) {
|
||||
if (oa.suborden === 0) return (oa.sala || pa.sala) - (ob.sala || pb.sala);
|
||||
return (ob.sala || 0) - (oa.sala || 0);
|
||||
}
|
||||
return oa.suborden - ob.suborden;
|
||||
});
|
||||
|
||||
const handleSubmit = async () => {
|
||||
// Validaciones explícitas con feedback claro
|
||||
if (!pacienteSeleccionado) {
|
||||
toast.error('Debe seleccionar un paciente de la lista');
|
||||
return;
|
||||
}
|
||||
|
||||
if (modoCama === 'seleccionar' && !camaSeleccionada) {
|
||||
toast.error('Debe seleccionar una cama para el paciente');
|
||||
return;
|
||||
}
|
||||
|
||||
if (modoCama === 'escribir' && !camaInput.trim()) {
|
||||
toast.error('Debe ingresar el número de cama');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!grupoSeleccionado) {
|
||||
toast.error('Debe seleccionar un grupo para el seguimiento');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!diagnosticoIngreso.trim()) {
|
||||
toast.error('Debe completar el Diagnóstico de Ingreso');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!enfermedadActual.trim()) {
|
||||
toast.error('Debe completar la Enfermedad Actual');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!effectiveMedico.trim()) {
|
||||
toast.error('Debe ingresar el nombre del Médico Ingresante');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
let camaId = '';
|
||||
|
||||
if (modoCama === 'escribir') {
|
||||
const numeroCama = camaInput.trim();
|
||||
const camaExistente = camas.find(c => c.numero === numeroCama);
|
||||
if (camaExistente) {
|
||||
toast.error(`La cama ${numeroCama} ya existe en el sistema. Seleccione la cama del listado o ingrese un número diferente.`);
|
||||
setIsSubmitting(false);
|
||||
return;
|
||||
} else if (onAgregarCama) {
|
||||
camaId = await onAgregarCama({
|
||||
numero: numeroCama,
|
||||
grupoId: grupoSeleccionado,
|
||||
tipo: 'General',
|
||||
estado: 'Ocupada',
|
||||
sector: computeSector(numeroCama)
|
||||
});
|
||||
} else {
|
||||
toast.error('No se puede crear la cama');
|
||||
setIsSubmitting(false);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
const camaElegida = sortedCamas.find(c => c.id === camaSeleccionada);
|
||||
if (!camaElegida) {
|
||||
toast.error('Cama no encontrada');
|
||||
setIsSubmitting(false);
|
||||
return;
|
||||
}
|
||||
camaId = camaSeleccionada;
|
||||
}
|
||||
|
||||
await onIniciarInternacion({
|
||||
pacienteId: pacienteSeleccionado,
|
||||
camaId: camaId,
|
||||
grupoId: grupoSeleccionado,
|
||||
medicoIngresante: effectiveMedico.trim(),
|
||||
diagnosticoIngreso: diagnosticoIngreso.trim(),
|
||||
motivoConsulta: motivoConsulta.trim() || undefined,
|
||||
enfermedadActual: enfermedadActual.trim(),
|
||||
antecedentesEnfermedadActual: antecedentesEnfermedadActual.trim() || undefined,
|
||||
fechaIngresoHospital: fechaIngresoHospital || undefined,
|
||||
fechaIngresoClinica: fechaIngresoClinica || undefined,
|
||||
apache: apache.trim() || undefined,
|
||||
derivacion: derivacion.trim() || undefined,
|
||||
});
|
||||
|
||||
toast.success('Ingreso registrado con éxito');
|
||||
resetFormulario();
|
||||
onVolver();
|
||||
} catch (err) {
|
||||
console.error('Error al guardar ingreso:', err);
|
||||
toast.error('Ocurrió un error al guardar el ingreso');
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const selectedPaciente = pacientes.find(p => p.id === pacienteSeleccionado);
|
||||
|
||||
return (
|
||||
<div className="space-y-6 dark:text-white">
|
||||
<div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<Button variant="ghost" size="icon" onClick={onVolver} disabled={isSubmitting} className="shrink-0">
|
||||
<ArrowLeft className="h-5 w-5" />
|
||||
</Button>
|
||||
<div>
|
||||
<h1 className="text-xl sm:text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-2">
|
||||
<User className="h-6 w-6 text-blue-600" />
|
||||
Nuevo Ingreso
|
||||
</h1>
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400">Formulario de internación</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 w-full sm:w-auto justify-end">
|
||||
<Button variant="outline" className="flex-1 sm:flex-initial" onClick={() => { resetFormulario(); onVolver(); }} disabled={isSubmitting}>
|
||||
<X className="h-4 w-4 mr-2" />
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button className="bg-blue-600 hover:bg-blue-700 flex-1 sm:flex-initial" onClick={handleSubmit} disabled={isSubmitting}>
|
||||
{isSubmitting ? (
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<Save className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
Guardar Ingreso
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
{/* Columna 1: Datos del Paciente */}
|
||||
<div className="space-y-6">
|
||||
<Card className="min-h-[200px]">
|
||||
<CardContent className="pt-6 space-y-4">
|
||||
<h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2">
|
||||
<User className="h-4 w-4" />
|
||||
Datos del Paciente
|
||||
</h3>
|
||||
|
||||
{!pacienteSeleccionado ? (
|
||||
<>
|
||||
<Label>Buscar Paciente *</Label>
|
||||
<Input
|
||||
placeholder="Apellido, nombre o DNI"
|
||||
value={busqueda}
|
||||
onChange={(e) => setBusqueda(e.target.value)}
|
||||
/>
|
||||
<div className="max-h-48 overflow-auto border rounded-md divide-y dark:divide-gray-800">
|
||||
{(() => {
|
||||
const q = busqueda.trim().toLowerCase();
|
||||
if (!q) {
|
||||
return <div className="p-3 text-sm text-gray-500">Escriba para buscar</div>;
|
||||
}
|
||||
const matches = pacientesSinInternar.filter(p =>
|
||||
p.apellido.toLowerCase().includes(q) ||
|
||||
p.nombre.toLowerCase().includes(q) ||
|
||||
p.dni.includes(q)
|
||||
);
|
||||
if (matches.length === 0) {
|
||||
return <div className="p-3 text-sm text-gray-500">Sin resultados</div>;
|
||||
}
|
||||
return matches.map(p => (
|
||||
<button
|
||||
key={p.id}
|
||||
type="button"
|
||||
onClick={() => setPacienteSeleccionado(p.id)}
|
||||
className="w-full text-left p-3 hover:bg-gray-50 dark:hover:bg-gray-800 text-sm transition-colors"
|
||||
>
|
||||
<span className="font-medium">{p.apellido}, {p.nombre}</span> — DNI: {p.dni}
|
||||
</button>
|
||||
));
|
||||
})()}
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="flex items-center gap-2 flex-wrap pt-1">
|
||||
<Badge className="bg-blue-100 text-blue-800 dark:bg-blue-950/80 dark:text-blue-300 dark:border dark:border-blue-800 text-sm py-1 px-3">
|
||||
{selectedPaciente?.apellido}, {selectedPaciente?.nombre}
|
||||
</Badge>
|
||||
<Badge variant="outline" className="text-sm py-1 px-3">DNI: {selectedPaciente?.dni}</Badge>
|
||||
<Button size="sm" variant="ghost" onClick={() => { setPacienteSeleccionado(''); setBusqueda(''); }}>
|
||||
Cambiar
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Columna 2: Cama y Grupo */}
|
||||
<div className="space-y-6">
|
||||
<Card className="min-h-[200px]">
|
||||
<CardContent className="pt-6 space-y-4">
|
||||
<h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2">
|
||||
<Bed className="h-4 w-4" />
|
||||
Asignación de Cama y Grupo
|
||||
</h3>
|
||||
|
||||
<div className="flex flex-col sm:flex-row gap-2 mb-4">
|
||||
<Button
|
||||
className="flex-1 text-xs sm:text-sm"
|
||||
variant={modoCama === 'seleccionar' ? 'default' : 'outline'}
|
||||
onClick={() => setModoCama('seleccionar')}
|
||||
>
|
||||
Seleccionar Cama
|
||||
</Button>
|
||||
<Button
|
||||
className="flex-1 text-xs sm:text-sm"
|
||||
variant={modoCama === 'escribir' ? 'default' : 'outline'}
|
||||
onClick={() => {
|
||||
setModoCama('escribir');
|
||||
setGrupoSeleccionado('');
|
||||
}}
|
||||
>
|
||||
Cama Fuera Área
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{modoCama === 'escribir' && (
|
||||
<div className="space-y-2">
|
||||
<Label>Grupo de Seguimiento *</Label>
|
||||
<Select value={grupoSeleccionado} onValueChange={setGrupoSeleccionado}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Seleccionar grupo" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{grupos.map(g => (
|
||||
<SelectItem key={g.id} value={g.id}>
|
||||
{g.nombre}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{modoCama === 'seleccionar' ? (
|
||||
<>
|
||||
<div>
|
||||
<Label>Cama *</Label>
|
||||
<Select
|
||||
value={camaSeleccionada}
|
||||
onValueChange={(val) => {
|
||||
setCamaSeleccionada(val);
|
||||
const cama = camas.find(c => c.id === val);
|
||||
if (cama?.grupoId) {
|
||||
setGrupoSeleccionado(cama.grupoId);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Seleccionar cama" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{sortedCamas.map(c => (
|
||||
<SelectItem key={c.id} value={c.id}>
|
||||
{c.numero} - {getGrupoName(c.grupoId)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div>
|
||||
<Label>Número de Cama (formato XXX-YY) *</Label>
|
||||
<Input
|
||||
placeholder="201-1"
|
||||
value={camaInput}
|
||||
onChange={(e) => setCamaInput(e.target.value)}
|
||||
/>
|
||||
<p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
{camaInput.trim() ? `Clasificación: ${computeSector(camaInput.trim())}` : 'Formato XXX-YY (Salas 3XX impares y 4XX son Fuera de Área)'}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardContent className="pt-6 space-y-4">
|
||||
<h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2">
|
||||
<Calendar className="h-4 w-4" />
|
||||
Datos de Ingreso
|
||||
</h3>
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label>Fecha Ingreso al Hospital</Label>
|
||||
<Input
|
||||
type="date"
|
||||
value={fechaIngresoHospital}
|
||||
onChange={(e) => setFechaIngresoHospital(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Fecha Ingreso a Clínica Médica</Label>
|
||||
<Input
|
||||
type="date"
|
||||
value={fechaIngresoClinica}
|
||||
onChange={(e) => setFechaIngresoClinica(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Derivado de</Label>
|
||||
<Input
|
||||
placeholder="Hospital o clínica de derivación"
|
||||
value={derivacion}
|
||||
onChange={(e) => setDerivacion(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Apache / Mortalidad</Label>
|
||||
<Input
|
||||
placeholder="Valor Apache o riesgo"
|
||||
value={apache}
|
||||
onChange={(e) => setApache(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardContent className="pt-6 space-y-4">
|
||||
<h3 className="font-semibold text-gray-900 dark:text-white">
|
||||
Datos Clínicos
|
||||
</h3>
|
||||
|
||||
<div>
|
||||
<Label>Motivo de Consulta *</Label>
|
||||
<textarea
|
||||
className="w-full p-2 border rounded-md text-sm min-h-[80px]"
|
||||
placeholder="Motivo por el cual consulta"
|
||||
value={motivoConsulta}
|
||||
onChange={(e) => setMotivoConsulta(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Diagnóstico de Ingreso *</Label>
|
||||
<textarea
|
||||
className="w-full p-2 border rounded-md text-sm min-h-[80px]"
|
||||
placeholder="Diagnóstico principal"
|
||||
value={diagnosticoIngreso}
|
||||
onChange={(e) => setDiagnosticoIngreso(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Enfermedad Actual *</Label>
|
||||
<textarea
|
||||
className="w-full p-2 border rounded-md text-sm min-h-[100px]"
|
||||
placeholder="Descripción de la enfermedad actual"
|
||||
value={enfermedadActual}
|
||||
onChange={(e) => setEnfermedadActual(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Antecedentes de la Enfermedad Actual</Label>
|
||||
<textarea
|
||||
className="w-full p-2 border rounded-md text-sm min-h-[80px]"
|
||||
placeholder="Antecedentes relevantes"
|
||||
value={antecedentesEnfermedadActual}
|
||||
onChange={(e) => setAntecedentesEnfermedadActual(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="space-y-6">
|
||||
<Card>
|
||||
<CardContent className="pt-6 space-y-4">
|
||||
<h3 className="font-semibold text-gray-900 dark:text-white flex items-center gap-2">
|
||||
<Stethoscope className="h-4 w-4" />
|
||||
Médico Ingresante
|
||||
</h3>
|
||||
|
||||
<div>
|
||||
<Label>Médico Ingresante *</Label>
|
||||
<Input
|
||||
placeholder="Nombre del médico"
|
||||
value={getNombreProfesional(currentUser)}
|
||||
disabled
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,453 @@
|
||||
import { useState } from 'react';
|
||||
import { Users, Plus, Search, Edit2, Trash2, User, Calendar, Phone, Mail, Droplet, AlertTriangle, X, Save } from 'lucide-react';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
|
||||
import type { Paciente } from '@/types';
|
||||
|
||||
interface PacientesProps {
|
||||
pacientes: Paciente[];
|
||||
internaciones: { id: string; pacienteId: string; activa: boolean }[];
|
||||
onAgregar: (paciente: Omit<Paciente, 'id' | 'fechaRegistro'>) => void;
|
||||
onActualizar: (id: string, datos: Partial<Paciente>) => void;
|
||||
onEliminar: (id: string) => void;
|
||||
}
|
||||
|
||||
export function Pacientes({
|
||||
pacientes,
|
||||
internaciones,
|
||||
onAgregar,
|
||||
onActualizar,
|
||||
onEliminar
|
||||
}: PacientesProps) {
|
||||
const [busqueda, setBusqueda] = useState('');
|
||||
const [dialogoAbierto, setDialogoAbierto] = useState(false);
|
||||
const [pacienteEditando, setPacienteEditando] = useState<Paciente | null>(null);
|
||||
|
||||
// Formulario
|
||||
const [nombre, setNombre] = useState('');
|
||||
const [apellido, setApellido] = useState('');
|
||||
const [dni, setDni] = useState('');
|
||||
const [fechaNacimiento, setFechaNacimiento] = useState('');
|
||||
const [sexo, setSexo] = useState<'M' | 'F' | 'Otro'>('M');
|
||||
const [telefono, setTelefono] = useState('');
|
||||
const [email, setEmail] = useState('');
|
||||
const [direccion, setDireccion] = useState('');
|
||||
const [grupoSanguineo, setGrupoSanguineo] = useState('');
|
||||
const [alergias, setAlergias] = useState('');
|
||||
const [antecedentes, setAntecedentes] = useState('');
|
||||
const [obraSocial, setObraSocial] = useState('');
|
||||
const [nacionalidad, setNacionalidad] = useState('');
|
||||
const [medicacionHabitual, setMedicacionHabitual] = useState('');
|
||||
const [historiaClinica, setHistoriaClinica] = useState('');
|
||||
|
||||
const resetFormulario = () => {
|
||||
setNombre('');
|
||||
setApellido('');
|
||||
setDni('');
|
||||
setFechaNacimiento('');
|
||||
setSexo('M');
|
||||
setTelefono('');
|
||||
setEmail('');
|
||||
setDireccion('');
|
||||
setGrupoSanguineo('');
|
||||
setAlergias('');
|
||||
setAntecedentes('');
|
||||
setObraSocial('');
|
||||
setNacionalidad('');
|
||||
setMedicacionHabitual('');
|
||||
setHistoriaClinica('');
|
||||
setPacienteEditando(null);
|
||||
};
|
||||
|
||||
const handleEditar = (paciente: Paciente) => {
|
||||
setPacienteEditando(paciente);
|
||||
setNombre(paciente.nombre);
|
||||
setApellido(paciente.apellido);
|
||||
setDni(paciente.dni);
|
||||
setFechaNacimiento(paciente.fechaNacimiento);
|
||||
setSexo(paciente.sexo);
|
||||
setTelefono(paciente.telefono);
|
||||
setEmail(paciente.email || '');
|
||||
setDireccion(paciente.direccion || '');
|
||||
setGrupoSanguineo(paciente.grupoSanguineo || '');
|
||||
setAlergias(paciente.alergias || '');
|
||||
setAntecedentes(paciente.antecedentes || '');
|
||||
setObraSocial(paciente.obraSocial || '');
|
||||
setNacionalidad(paciente.nacionalidad || '');
|
||||
setMedicacionHabitual(paciente.medicacionHabitual || '');
|
||||
setHistoriaClinica(paciente.historiaClinica || '');
|
||||
setDialogoAbierto(true);
|
||||
};
|
||||
|
||||
const handleGuardar = () => {
|
||||
if (!nombre || !apellido || !dni || !fechaNacimiento) return;
|
||||
|
||||
const datos = {
|
||||
nombre,
|
||||
apellido,
|
||||
dni,
|
||||
fechaNacimiento,
|
||||
sexo,
|
||||
telefono: telefono || undefined,
|
||||
email: email || undefined,
|
||||
direccion: direccion || undefined,
|
||||
grupoSanguineo: grupoSanguineo || undefined,
|
||||
alergias: alergias || undefined,
|
||||
antecedentes: antecedentes || undefined,
|
||||
obraSocial: obraSocial || undefined,
|
||||
nacionalidad: nacionalidad || undefined,
|
||||
medicacionHabitual: medicacionHabitual || undefined,
|
||||
historiaClinica: historiaClinica || undefined,
|
||||
};
|
||||
|
||||
if (pacienteEditando) {
|
||||
onActualizar(pacienteEditando.id, datos);
|
||||
} else {
|
||||
onAgregar(datos);
|
||||
}
|
||||
|
||||
resetFormulario();
|
||||
setDialogoAbierto(false);
|
||||
};
|
||||
|
||||
const pacientesFiltrados = pacientes.filter(p =>
|
||||
p.nombre.toLowerCase().includes(busqueda.toLowerCase()) ||
|
||||
p.apellido.toLowerCase().includes(busqueda.toLowerCase()) ||
|
||||
p.dni.includes(busqueda)
|
||||
);
|
||||
|
||||
const getEdad = (fechaNacimiento: string) => {
|
||||
const hoy = new Date();
|
||||
const nacimiento = new Date(fechaNacimiento);
|
||||
let edad = hoy.getFullYear() - nacimiento.getFullYear();
|
||||
const mes = hoy.getMonth() - nacimiento.getMonth();
|
||||
if (mes < 0 || (mes === 0 && hoy.getDate() < nacimiento.getDate())) {
|
||||
edad--;
|
||||
}
|
||||
return edad;
|
||||
};
|
||||
|
||||
const estaInternado = (pacienteId: string) => {
|
||||
return internaciones.some(i => i.pacienteId === pacienteId && i.activa);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-6 dark:text-white">
|
||||
{/* Header */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900 dark:text-white">Pacientes</h1>
|
||||
<p className="text-gray-500 dark:text-gray-400">Gestión de pacientes del hospital</p>
|
||||
</div>
|
||||
<Dialog open={dialogoAbierto} onOpenChange={setDialogoAbierto}>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="outline" onClick={resetFormulario}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Nuevo Paciente
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
{pacienteEditando ? <Edit2 className="h-5 w-5" /> : <Plus className="h-5 w-5" />}
|
||||
{pacienteEditando ? 'Editar Paciente' : 'Nuevo Paciente'}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<Label>Nombre *</Label>
|
||||
<Input
|
||||
value={nombre}
|
||||
onChange={(e) => setNombre(e.target.value)}
|
||||
placeholder="Nombre del paciente"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Apellido *</Label>
|
||||
<Input
|
||||
value={apellido}
|
||||
onChange={(e) => setApellido(e.target.value)}
|
||||
placeholder="Apellido del paciente"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>DNI *</Label>
|
||||
<Input
|
||||
value={dni}
|
||||
onChange={(e) => setDni(e.target.value)}
|
||||
placeholder="Número de DNI"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Fecha de Nacimiento *</Label>
|
||||
<Input
|
||||
type="date"
|
||||
value={fechaNacimiento}
|
||||
onChange={(e) => setFechaNacimiento(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Sexo *</Label>
|
||||
<Select value={sexo} onValueChange={(v: 'M' | 'F' | 'Otro') => setSexo(v)}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="M">Masculino</SelectItem>
|
||||
<SelectItem value="F">Femenino</SelectItem>
|
||||
<SelectItem value="Otro">Otro</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Historia Clínica</Label>
|
||||
<Input
|
||||
value={historiaClinica}
|
||||
onChange={(e) => setHistoriaClinica(e.target.value)}
|
||||
placeholder="Historia clínica..."
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Obra Social</Label>
|
||||
<Input
|
||||
value={obraSocial}
|
||||
onChange={(e) => setObraSocial(e.target.value)}
|
||||
placeholder="Obra social del paciente"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Nacionalidad</Label>
|
||||
<Input
|
||||
value={nacionalidad}
|
||||
onChange={(e) => setNacionalidad(e.target.value)}
|
||||
placeholder="Nacionalidad del paciente"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Dirección</Label>
|
||||
<Input
|
||||
value={direccion}
|
||||
onChange={(e) => setDireccion(e.target.value)}
|
||||
placeholder="Dirección del paciente"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<Label>Grupo Sanguíneo</Label>
|
||||
<Select value={grupoSanguineo} onValueChange={setGrupoSanguineo}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Seleccionar" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="A+">A+</SelectItem>
|
||||
<SelectItem value="A-">A-</SelectItem>
|
||||
<SelectItem value="B+">B+</SelectItem>
|
||||
<SelectItem value="B-">B-</SelectItem>
|
||||
<SelectItem value="AB+">AB+</SelectItem>
|
||||
<SelectItem value="AB-">AB-</SelectItem>
|
||||
<SelectItem value="O+">O+</SelectItem>
|
||||
<SelectItem value="O-">O-</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<Label>Teléfono Contacto</Label>
|
||||
<Input
|
||||
value={telefono}
|
||||
onChange={(e) => setTelefono(e.target.value)}
|
||||
placeholder="Teléfono de contacto"
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<Label>Medicación Habitual</Label>
|
||||
<textarea
|
||||
className="w-full p-2 border rounded-md text-sm min-h-[60px]"
|
||||
value={medicacionHabitual}
|
||||
onChange={(e) => setMedicacionHabitual(e.target.value)}
|
||||
placeholder="Medicación habitual del paciente..."
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<Label>Antecedentes Médicos</Label>
|
||||
<textarea
|
||||
className="w-full p-2 border rounded-md text-sm min-h-[60px]"
|
||||
value={antecedentes}
|
||||
onChange={(e) => setAntecedentes(e.target.value)}
|
||||
placeholder="Antecedentes médicos relevantes..."
|
||||
/>
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<Label>Alergias</Label>
|
||||
<textarea
|
||||
className="w-full p-2 border rounded-md text-sm min-h-[60px]"
|
||||
value={alergias}
|
||||
onChange={(e) => setAlergias(e.target.value)}
|
||||
placeholder="Alergias conocidas..."
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 mt-4">
|
||||
<Button variant="outline" onClick={() => {
|
||||
resetFormulario();
|
||||
setDialogoAbierto(false);
|
||||
}}>
|
||||
<X className="h-4 w-4 mr-2" />
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button variant="outline"
|
||||
onClick={handleGuardar}
|
||||
disabled={!nombre || !apellido || !dni || !fechaNacimiento}
|
||||
>
|
||||
<Save className="h-4 w-4 mr-2" />
|
||||
{pacienteEditando ? 'Guardar Cambios' : 'Crear Paciente'}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
{/* Búsqueda */}
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
|
||||
<Input
|
||||
className="pl-10"
|
||||
placeholder="Buscar por nombre, apellido o DNI..."
|
||||
value={busqueda}
|
||||
onChange={(e) => setBusqueda(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Lista de Pacientes */}
|
||||
<div className="grid grid-cols-1 gap-4">
|
||||
{pacientesFiltrados.map((paciente) => (
|
||||
<Card key={paciente.id} className="hover:shadow-md transition-shadow">
|
||||
<CardContent className="p-4">
|
||||
<div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4">
|
||||
<div className="flex items-start gap-4">
|
||||
<div className="h-12 w-12 bg-blue-100 rounded-full flex items-center justify-center flex-shrink-0">
|
||||
<User className="h-6 w-6 text-blue-600" />
|
||||
</div>
|
||||
<div>
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<h3 className="font-bold text-lg">
|
||||
{paciente.apellido}, {paciente.nombre}
|
||||
</h3>
|
||||
{estaInternado(paciente.id) && (
|
||||
<Badge className="bg-purple-100 text-purple-800">
|
||||
Internado
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-x-4 gap-y-1 mt-2 text-sm text-gray-500">
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="font-medium">DNI:</span> {paciente.dni}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<Calendar className="h-3 w-3" />
|
||||
{getEdad(paciente.fechaNacimiento)} años
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="font-medium">Sexo:</span> {paciente.sexo}
|
||||
</div>
|
||||
{paciente.grupoSanguineo && (
|
||||
<div className="flex items-center gap-1">
|
||||
<Droplet className="h-3 w-3" />
|
||||
{paciente.grupoSanguineo}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-3 mt-2 text-sm text-gray-500">
|
||||
<div className="flex items-center gap-1">
|
||||
<Phone className="h-3 w-3" />
|
||||
{paciente.telefono}
|
||||
</div>
|
||||
{paciente.email && (
|
||||
<div className="flex items-center gap-1">
|
||||
<Mail className="h-3 w-3" />
|
||||
{paciente.email}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{(paciente.alergias || paciente.antecedentes) && (
|
||||
<div className="mt-2 flex flex-wrap gap-2">
|
||||
{paciente.alergias && (
|
||||
<Badge variant="outline" className="bg-amber-50 text-amber-700 border-amber-200">
|
||||
<AlertTriangle className="h-3 w-3 mr-1" />
|
||||
Alergias
|
||||
</Badge>
|
||||
)}
|
||||
{paciente.antecedentes && (
|
||||
<Badge variant="outline" className="bg-blue-50 text-blue-700 border-blue-200">
|
||||
Antecedentes
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => handleEditar(paciente)}
|
||||
>
|
||||
<Edit2 className="h-4 w-4" />
|
||||
</Button>
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button variant="outline" size="sm" className="text-red-600 hover:bg-red-50">
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>¿Eliminar paciente?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Esta acción no se puede deshacer. Se eliminará permanentemente el paciente{' '}
|
||||
<strong>{paciente.apellido}, {paciente.nombre}</strong>.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancelar</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => onEliminar(paciente.id)}
|
||||
className="bg-red-600 hover:bg-red-700"
|
||||
>
|
||||
Eliminar
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{pacientesFiltrados.length === 0 && (
|
||||
<div className="text-center py-12 text-gray-400">
|
||||
<Users className="h-16 w-16 mx-auto mb-4 opacity-50" />
|
||||
<p className="text-lg">
|
||||
{busqueda ? 'No se encontraron pacientes con esa búsqueda' : 'No hay pacientes registrados'}
|
||||
</p>
|
||||
{!busqueda && (
|
||||
<Button variant="outline" className="mt-4" onClick={() => setDialogoAbierto(true)}>
|
||||
<Plus className="h-4 w-4 mr-2" />
|
||||
Agregar primer paciente
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,550 @@
|
||||
import { useState } from 'react';
|
||||
import { toast } from 'sonner';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
|
||||
import { Plus, Pencil, Trash2, X } from 'lucide-react';
|
||||
import type { Indicacion, IndicacionTipo, ViaAdministracion, TipoPlanHidratacion, TipoInsulina, ATB } from '@/types';
|
||||
import { useHospitalStore } from '@/hooks/useHospitalStore';
|
||||
import { getNombreProfesional } from '@/lib/utils';
|
||||
|
||||
export function SeccionIndicaciones({ recomendaciones, internacionId, pacienteId, add, update, del, movimientos, onAgregarMovimiento, canEdit, atbList = [], addATB, updateATB }: {
|
||||
recomendaciones: Indicacion[];
|
||||
internacionId: string;
|
||||
pacienteId?: string;
|
||||
add: (i: Omit<Indicacion, 'id'>) => Promise<unknown>;
|
||||
update: (id: string, datos: Partial<Indicacion>) => void;
|
||||
del: (id: string) => void;
|
||||
movimientos?: unknown[];
|
||||
onAgregarMovimiento?: (m: unknown) => void;
|
||||
canEdit?: boolean;
|
||||
atbList?: ATB[];
|
||||
addATB?: (a: Omit<ATB, 'id'>) => Promise<unknown>;
|
||||
updateATB?: (id: string, datos: Partial<ATB>) => void;
|
||||
}) {
|
||||
const { currentUser } = useHospitalStore();
|
||||
const list: Indicacion[] = Array.isArray(recomendaciones) ? recomendaciones : [];
|
||||
const movs = Array.isArray(movimientos) ? movimientos : [];
|
||||
const [dialog, setDialog] = useState(false);
|
||||
const [edit, setEdit] = useState<Indicacion | null>(null);
|
||||
const [deleteConfirmInd, setDeleteConfirmInd] = useState<Indicacion | null>(null);
|
||||
const effectiveDeleteMedico = getNombreProfesional(currentUser);
|
||||
|
||||
const formatIndicacion = (i: Indicacion): string => {
|
||||
if (i.tipo === 'Farmacologica' || i.tipo === 'Farmacologica Profilactica' || i.tipo === 'Farmacologica Antibiótico') return `${i.droga || ''} ${i.dosis || ''} ${i.frecuenciaHoras ? `c/${i.frecuenciaHoras}hs` : ''} ${i.via || ''}`.trim();
|
||||
if (i.tipo === 'Farmacologica Insulina') return `${i.tipoInsulina || ''}${i.unidadesDesayuno ? ` - PreDesayuno: ${i.unidadesDesayuno}U` : ''}${i.unidadesAlmuerzo ? ` - PreAlmuerzo: ${i.unidadesAlmuerzo}U` : ''}${i.unidadesNoche ? ` - 23hs: ${i.unidadesNoche}U` : ''}`.trim();
|
||||
if (i.tipo === 'No Farmacologica') return i.indicacionNoFco || '';
|
||||
if (i.tipo === 'PHP' || i.tipo === 'PHP Paralelo') return `${i.tipoPlan || ''} ${i.cantidadMl || ''}ml en ${i.tiempoHoras || ''}hs`;
|
||||
if (i.tipo === 'PHP Alterno') return `${i.tipoPlan || ''} ${i.cantidadMl || ''}ml + ${i.tipoPlan2 || ''} ${i.cantidadMl2 || ''}ml en ${i.tiempoHoras || ''}hs`;
|
||||
return '';
|
||||
};
|
||||
const [tipo, setTipo] = useState<IndicacionTipo>('Farmacologica');
|
||||
const [sortField, setSortField] = useState<'fecha' | 'profesional' | 'tipo'>('fecha');
|
||||
const [sortDir, setSortDir] = useState<'asc' | 'desc'>('desc');
|
||||
|
||||
const handleSort = (field: 'fecha' | 'profesional' | 'tipo') => {
|
||||
if (sortField === field) {
|
||||
setSortDir(sortDir === 'asc' ? 'desc' : 'asc');
|
||||
} else {
|
||||
setSortField(field);
|
||||
setSortDir('desc');
|
||||
}
|
||||
};
|
||||
|
||||
const sortedMovs = [...movs].sort((a, b) => {
|
||||
const recordA = a as Record<string, unknown>;
|
||||
const recordB = b as Record<string, unknown>;
|
||||
const aVal = String(recordA[sortField] || '');
|
||||
const bVal = String(recordB[sortField] || '');
|
||||
if (sortField === 'fecha') {
|
||||
const timeA = new Date(aVal.replace(' ', 'T')).getTime();
|
||||
const timeB = new Date(bVal.replace(' ', 'T')).getTime();
|
||||
return sortDir === 'asc' ? timeA - timeB : timeB - timeA;
|
||||
}
|
||||
return sortDir === 'asc' ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal);
|
||||
});
|
||||
const [droga, setDroga] = useState('');
|
||||
const [dosis, setDosis] = useState('');
|
||||
const [frecuenciaHoras, setFrecuenciaHoras] = useState<number | ''>('');
|
||||
const [via, setVia] = useState<ViaAdministracion>('EV');
|
||||
const [indicacionNoFco, setIndicacionNoFco] = useState('');
|
||||
const [tipoPlan, setTipoPlan] = useState<TipoPlanHidratacion>('SF 0.9%');
|
||||
const [tipoPlan2, setTipoPlan2] = useState<TipoPlanHidratacion>('Ringer Lactato');
|
||||
const [cantidadMl, setCantidadMl] = useState<number | ''>('');
|
||||
const [cantidadMl2, setCantidadMl2] = useState<number | ''>('');
|
||||
const [tiempoHoras, setTiempoHoras] = useState<number | ''>(24);
|
||||
const [tipoInsulina, setTipoInsulina] = useState<TipoInsulina>('NPH');
|
||||
const [unidadesDesayuno, setUnidadesDesayuno] = useState<number | ''>('');
|
||||
const [unidadesAlmuerzo, setUnidadesAlmuerzo] = useState<number | ''>('');
|
||||
const [unidadesNoche, setUnidadesNoche] = useState<number | ''>('');
|
||||
const effectiveMedico = getNombreProfesional(currentUser);
|
||||
const [showHistorial, setShowHistorial] = useState(false);
|
||||
|
||||
const vias: ViaAdministracion[] = ['Via Oral', 'EV', 'IM', 'SC', 'Por GGT', 'Por SNG'];
|
||||
const planes: TipoPlanHidratacion[] = ['SF 0.9%', 'Dextrosa 5%', 'Dextrosa 10%', 'Dextrosa 25%', 'Ringer Lactato'];
|
||||
const tiposInsulina: TipoInsulina[] = ['NPH', 'Glargina'];
|
||||
const tipos: IndicacionTipo[] = ['Farmacologica', 'Farmacologica Antibiótico', 'Farmacologica Profilactica', 'Farmacologica Insulina', 'No Farmacologica', 'PHP', 'PHP Paralelo', 'PHP Alterno'];
|
||||
|
||||
const reset = () => {
|
||||
setEdit(null);
|
||||
setTipo('Farmacologica');
|
||||
setDroga('');
|
||||
setDosis('');
|
||||
setFrecuenciaHoras('');
|
||||
setVia('EV');
|
||||
setIndicacionNoFco('');
|
||||
setTipoPlan('SF 0.9%');
|
||||
setTipoPlan2('Ringer Lactato');
|
||||
setCantidadMl('');
|
||||
setCantidadMl2('');
|
||||
setTiempoHoras(24);
|
||||
setTipoInsulina('NPH');
|
||||
setUnidadesDesayuno('');
|
||||
setUnidadesAlmuerzo('');
|
||||
setUnidadesNoche('');
|
||||
};
|
||||
|
||||
const loadEdit = (i: Indicacion) => {
|
||||
setEdit(i);
|
||||
setTipo(i.tipo);
|
||||
setDroga(i.droga || '');
|
||||
setDosis(i.dosis || '');
|
||||
setFrecuenciaHoras(i.frecuenciaHoras || '');
|
||||
setVia(i.via || 'EV');
|
||||
setIndicacionNoFco(i.indicacionNoFco || '');
|
||||
setTipoPlan(i.tipoPlan || 'SF 0.9%');
|
||||
setTipoPlan2(i.tipoPlan2 || 'Ringer Lactato');
|
||||
setCantidadMl(i.cantidadMl || '');
|
||||
setCantidadMl2(i.cantidadMl2 || '');
|
||||
setTiempoHoras(i.tiempoHoras || 24);
|
||||
setTipoInsulina(i.tipoInsulina || 'NPH');
|
||||
setUnidadesDesayuno(i.unidadesDesayuno || '');
|
||||
setUnidadesAlmuerzo(i.unidadesAlmuerzo || '');
|
||||
setUnidadesNoche(i.unidadesNoche || '');
|
||||
setDialog(true);
|
||||
};
|
||||
|
||||
const handleGuardar = async () => {
|
||||
if (!effectiveMedico.trim()) return;
|
||||
if ((tipo === 'Farmacologica' || tipo === 'Farmacologica Profilactica' || tipo === 'Farmacologica Antibiótico') && (!droga.trim() || !dosis.trim())) return;
|
||||
if (tipo === 'Farmacologica Insulina' && (!unidadesDesayuno && !unidadesAlmuerzo && !unidadesNoche)) return;
|
||||
if (tipo === 'No Farmacologica' && !indicacionNoFco.trim()) return;
|
||||
if ((tipo === 'PHP' || tipo === 'PHP Paralelo') && !cantidadMl) return;
|
||||
if (tipo === 'PHP Alterno' && (!cantidadMl || !cantidadMl2)) return;
|
||||
|
||||
const data: Partial<Indicacion> = {
|
||||
internacionId,
|
||||
tipo,
|
||||
estado: 'Activa',
|
||||
medicoCrea: effectiveMedico,
|
||||
fechaCrea: new Date().toISOString().split('T')[0],
|
||||
};
|
||||
|
||||
if (tipo === 'Farmacologica' || tipo === 'Farmacologica Profilactica' || tipo === 'Farmacologica Antibiótico') {
|
||||
data.droga = droga;
|
||||
data.dosis = dosis;
|
||||
data.frecuenciaHoras = frecuenciaHoras || undefined;
|
||||
data.via = via;
|
||||
} else if (tipo === 'Farmacologica Insulina') {
|
||||
data.tipoInsulina = tipoInsulina;
|
||||
data.unidadesDesayuno = unidadesDesayuno || undefined;
|
||||
data.unidadesAlmuerzo = unidadesAlmuerzo || undefined;
|
||||
data.unidadesNoche = unidadesNoche || undefined;
|
||||
} else if (tipo === 'No Farmacologica') {
|
||||
data.indicacionNoFco = indicacionNoFco;
|
||||
} else if (tipo === 'PHP' || tipo === 'PHP Paralelo') {
|
||||
data.tipoPlan = tipoPlan;
|
||||
data.cantidadMl = cantidadMl;
|
||||
data.tiempoHoras = tiempoHoras;
|
||||
} else if (tipo === 'PHP Alterno') {
|
||||
data.tipoPlan = tipoPlan;
|
||||
data.cantidadMl = cantidadMl;
|
||||
data.tipoPlan2 = tipoPlan2;
|
||||
data.cantidadMl2 = cantidadMl2;
|
||||
data.tiempoHoras = tiempoHoras;
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const fecha = now.toISOString().split('T')[0] + ' ' + now.toTimeString().split(' ')[0].substring(0, 5);
|
||||
if (edit) {
|
||||
if (edit.tipo === 'Farmacologica Antibiótico' && updateATB && addATB && atbList && pacienteId) {
|
||||
const oldDrug = edit.droga || '';
|
||||
const newDrug = droga || '';
|
||||
if (oldDrug.toLowerCase() !== newDrug.toLowerCase()) {
|
||||
const activeATB = atbList.find(a =>
|
||||
a.internacionId === internacionId &&
|
||||
a.antibiotico.toLowerCase() === oldDrug.toLowerCase() &&
|
||||
!a.fechaFinalizacion
|
||||
);
|
||||
if (activeATB) {
|
||||
const todayStr = now.toISOString().split('T')[0];
|
||||
try {
|
||||
await updateATB(activeATB.id, { fechaFinalizacion: todayStr });
|
||||
await addATB({
|
||||
pacienteId,
|
||||
internacionId,
|
||||
antibiotico: newDrug,
|
||||
fechaInicio: todayStr,
|
||||
});
|
||||
} catch (atbErr) {
|
||||
console.error('Error al actualizar ATB en modificación de indicación:', atbErr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (onAgregarMovimiento) {
|
||||
await onAgregarMovimiento({
|
||||
indicacionId: edit.id,
|
||||
internacionId,
|
||||
tipo: 'Modificacion',
|
||||
fecha,
|
||||
profesional: effectiveMedico,
|
||||
indicacionPrevia: formatIndicacion(edit),
|
||||
indicacionNueva: formatIndicacion({ ...edit, ...data } as Indicacion),
|
||||
});
|
||||
}
|
||||
await update(edit.id, data);
|
||||
} else {
|
||||
const newId = await add(data);
|
||||
if (tipo === 'Farmacologica Antibiótico' && addATB && pacienteId) {
|
||||
try {
|
||||
await addATB({
|
||||
pacienteId,
|
||||
internacionId,
|
||||
antibiotico: droga,
|
||||
fechaInicio: data.fechaCrea,
|
||||
});
|
||||
} catch (atbErr) {
|
||||
console.error('Error al agregar ATB automáticamente:', atbErr);
|
||||
}
|
||||
}
|
||||
if (onAgregarMovimiento) {
|
||||
await onAgregarMovimiento({
|
||||
indicacionId: typeof newId === 'string' ? newId : '',
|
||||
internacionId,
|
||||
tipo: 'Nueva',
|
||||
fecha,
|
||||
profesional: effectiveMedico,
|
||||
indicacionNueva: formatIndicacion({ ...data, id: newId } as Indicacion),
|
||||
});
|
||||
}
|
||||
}
|
||||
setDialog(false);
|
||||
reset();
|
||||
};
|
||||
|
||||
const handleSuspender = async (i: Indicacion, suspendioMedico: string) => {
|
||||
const now = new Date();
|
||||
const fecha = now.toISOString().split('T')[0] + ' ' + now.toTimeString().split(' ')[0].substring(0, 5);
|
||||
try {
|
||||
if (onAgregarMovimiento) {
|
||||
await onAgregarMovimiento({
|
||||
indicacionId: i.id,
|
||||
internacionId,
|
||||
tipo: 'Suspencion',
|
||||
fecha,
|
||||
profesional: suspendioMedico,
|
||||
indicacionPrevia: formatIndicacion(i),
|
||||
});
|
||||
}
|
||||
|
||||
if (i.tipo === 'Farmacologica Antibiótico' && updateATB && atbList) {
|
||||
const fechaFin = now.toISOString().split('T')[0];
|
||||
const activeATB = atbList.find(a =>
|
||||
a.internacionId === internacionId &&
|
||||
a.antibiotico.toLowerCase() === (i.droga || '').toLowerCase() &&
|
||||
!a.fechaFinalizacion
|
||||
);
|
||||
if (activeATB) {
|
||||
try {
|
||||
await updateATB(activeATB.id, { fechaFinalizacion: fechaFin });
|
||||
} catch (atbErr) {
|
||||
console.error('Error al finalizar ATB automáticamente:', atbErr);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await del(i.id);
|
||||
toast.success('Indicación eliminada correctamente');
|
||||
} catch (err) {
|
||||
console.error('Error al eliminar indicación:', err);
|
||||
toast.error('Error al eliminar la indicación');
|
||||
}
|
||||
};
|
||||
|
||||
const indsFilter = list.filter(ind => ind.internacionId === internacionId);
|
||||
const activas = indsFilter.filter(ind => ind.estado === 'Activa');
|
||||
|
||||
return (
|
||||
<div className="space-y-2.5">
|
||||
<div className="flex justify-between items-center">
|
||||
{canEdit && <Button size="sm" variant="outline" onClick={() => { reset(); setDialog(true); }}>
|
||||
<Plus className="h-4 w-4 mr-1.5" />Nueva Indicación
|
||||
</Button>}
|
||||
<Button size="sm" variant="ghost" onClick={() => setShowHistorial(!showHistorial)}>
|
||||
{showHistorial ? 'Ocultar Historial' : `Ver Historial (${movs.length})`}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Dialog open={dialog} onOpenChange={setDialog}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{edit ? 'Editar' : 'Nueva'} Indicación</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<Label>Tipo de Indicación</Label>
|
||||
<Select value={tipo} onValueChange={(v: IndicacionTipo) => setTipo(v)}>
|
||||
<SelectTrigger><SelectValue placeholder="Seleccionar tipo" /></SelectTrigger>
|
||||
<SelectContent>
|
||||
{tipos.map(t => <SelectItem key={t} value={t}>{t}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label>Médico *</Label>
|
||||
<Input value={getNombreProfesional(currentUser)} disabled placeholder="Nombre del médico" />
|
||||
</div>
|
||||
|
||||
{(tipo === 'Farmacologica' || tipo === 'Farmacologica Antibiótico') && (
|
||||
<>
|
||||
<div><Label>Droga *</Label><Input value={droga} onChange={e => setDroga(e.target.value)} placeholder="Nombre del medicamento" /></div>
|
||||
<div><Label>Dosis *</Label><Input value={dosis} onChange={e => setDosis(e.target.value)} placeholder="Ej: 500mg, 1g, 10ml" /></div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div><Label>Frecuencia (hs)</Label><Input type="number" value={frecuenciaHoras} onChange={e => setFrecuenciaHoras(e.target.value ? parseInt(e.target.value) : '')} placeholder="Cada X horas" /></div>
|
||||
<div><Label>Vía</Label><Select value={via} onValueChange={(v: ViaAdministracion) => setVia(v)}><SelectTrigger><SelectValue /></SelectTrigger><SelectContent>{vias.map(v => <SelectItem key={v} value={v}>{v}</SelectItem>)}</SelectContent></Select></div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{tipo === 'Farmacologica Profilactica' && (
|
||||
<>
|
||||
<div><Label>Droga *</Label><Input value={droga} onChange={e => setDroga(e.target.value)} placeholder="Nombre del medicamento" /></div>
|
||||
<div><Label>Dosis *</Label><Input value={dosis} onChange={e => setDosis(e.target.value)} placeholder="Ej: 500mg, 1g, 10ml" /></div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div><Label>Frecuencia (hs)</Label><Input type="number" value={frecuenciaHoras} onChange={e => setFrecuenciaHoras(e.target.value ? parseInt(e.target.value) : '')} placeholder="Cada X horas" /></div>
|
||||
<div><Label>Vía</Label><Select value={via} onValueChange={(v: ViaAdministracion) => setVia(v)}><SelectTrigger><SelectValue /></SelectTrigger><SelectContent>{vias.map(v => <SelectItem key={v} value={v}>{v}</SelectItem>)}</SelectContent></Select></div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
{tipo === 'Farmacologica Insulina' && (
|
||||
<>
|
||||
<div><Label>Tipo de Insulina</Label><Select value={tipoInsulina} onValueChange={(v: TipoInsulina) => setTipoInsulina(v)}><SelectTrigger><SelectValue /></SelectTrigger><SelectContent>{tiposInsulina.map(t => <SelectItem key={t} value={t}>{t}</SelectItem>)}</SelectContent></Select></div>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
<div className="flex flex-col justify-end space-y-1.5">
|
||||
<Label className="text-xs sm:text-sm">Pre Desayuno (U)</Label>
|
||||
<Input type="number" value={unidadesDesayuno} onChange={e => setUnidadesDesayuno(e.target.value ? parseInt(e.target.value) : '')} placeholder="U" />
|
||||
</div>
|
||||
<div className="flex flex-col justify-end space-y-1.5">
|
||||
<Label className="text-xs sm:text-sm">Pre Almuerzo (U)</Label>
|
||||
<Input type="number" value={unidadesAlmuerzo} onChange={e => setUnidadesAlmuerzo(e.target.value ? parseInt(e.target.value) : '')} placeholder="U" />
|
||||
</div>
|
||||
<div className="flex flex-col justify-end space-y-1.5">
|
||||
<Label className="text-xs sm:text-sm">23hs (U)</Label>
|
||||
<Input type="number" value={unidadesNoche} onChange={e => setUnidadesNoche(e.target.value ? parseInt(e.target.value) : '')} placeholder="U" />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{tipo === 'No Farmacologica' && (
|
||||
<div><Label>Indicacionión *</Label><textarea className="w-full p-2 border rounded-md text-sm min-h-[80px] bg-transparent dark:bg-input/30" value={indicacionNoFco} onChange={e => setIndicacionNoFco(e.target.value)} placeholder="Ej: Control de signos vitales, Dieta, etc." /></div>
|
||||
)}
|
||||
|
||||
{(tipo === 'PHP' || tipo === 'PHP Paralelo') && (
|
||||
<>
|
||||
<div><Label>Tipo de Plan</Label><Select value={tipoPlan} onValueChange={(v: TipoPlanHidratacion) => setTipoPlan(v)}><SelectTrigger><SelectValue /></SelectTrigger><SelectContent>{planes.map(p => <SelectItem key={p} value={p}>{p}</SelectItem>)}</SelectContent></Select></div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div><Label>Cantidad (ml) *</Label><Input type="number" value={cantidadMl} onChange={e => setCantidadMl(e.target.value ? parseInt(e.target.value) : '')} placeholder="ml" /></div>
|
||||
<div><Label>Tiempo (hs)</Label><Input type="number" value={tiempoHoras} onChange={e => setTiempoHoras(e.target.value ? parseInt(e.target.value) : 24)} placeholder="24" /></div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{tipo === 'PHP Alterno' && (
|
||||
<>
|
||||
<div><Label>Plan 1</Label><Select value={tipoPlan} onValueChange={(v: TipoPlanHidratacion) => setTipoPlan(v)}><SelectTrigger><SelectValue /></SelectTrigger><SelectContent>{planes.map(p => <SelectItem key={p} value={p}>{p}</SelectItem>)}</SelectContent></Select></div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div><Label>Cantidad Plan 1 (ml) *</Label><Input type="number" value={cantidadMl} onChange={e => setCantidadMl(e.target.value ? parseInt(e.target.value) : '')} placeholder="ml" /></div>
|
||||
</div>
|
||||
<div><Label>Plan 2</Label><Select value={tipoPlan2} onValueChange={(v: TipoPlanHidratacion) => setTipoPlan2(v)}><SelectTrigger><SelectValue /></SelectTrigger><SelectContent>{planes.map(p => <SelectItem key={p} value={p}>{p}</SelectItem>)}</SelectContent></Select></div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div><Label>Cantidad Plan 2 (ml) *</Label><Input type="number" value={cantidadMl2} onChange={e => setCantidadMl2(e.target.value ? parseInt(e.target.value) : '')} placeholder="ml" /></div>
|
||||
<div><Label>Tiempo Total (hs)</Label><Input type="number" value={tiempoHoras} onChange={e => setTiempoHoras(e.target.value ? parseInt(e.target.value) : 24)} placeholder="24" /></div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 mt-4">
|
||||
<Button variant="outline" onClick={() => setDialog(false)}><X className="h-4 w-4 mr-2" />Cancelar</Button>
|
||||
<Button onClick={handleGuardar} disabled={!effectiveMedico.trim()}>Guardar</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{activas.length === 0 ? (
|
||||
<div className="text-center py-6 text-gray-500 text-sm">No hay indicaciones activas</div>
|
||||
) : (
|
||||
<div className="space-y-1.5">
|
||||
{activas.map(ind => (
|
||||
<Card key={ind.id}>
|
||||
<CardContent className="py-2 px-3 flex flex-col sm:flex-row sm:items-center justify-between gap-2">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-1.5 mb-0.5">
|
||||
<Badge variant="outline" className="text-xs py-0 px-1.5 h-5">{ind.tipo}</Badge>
|
||||
{ind.medicoCrea && <span className="text-xs text-muted-foreground">Dr: {ind.medicoCrea}</span>}
|
||||
</div>
|
||||
{ind.tipo === 'Farmacologica' && (
|
||||
<div className="font-medium text-sm leading-tight">{ind.droga} {ind.dosis} {ind.frecuenciaHoras ? `c/${ind.frecuenciaHoras}hs` : ''} {ind.via}</div>
|
||||
)}
|
||||
{ind.tipo === 'Farmacologica Antibiótico' && (
|
||||
<div className="font-medium text-sm leading-tight">{ind.droga} {ind.dosis} {ind.frecuenciaHoras ? `c/${ind.frecuenciaHoras}hs` : ''} {ind.via} <Badge className="ml-1.5 py-0 px-1.5 h-5 text-xs bg-purple-100 text-purple-800 dark:bg-purple-950 dark:text-purple-300 hover:bg-purple-100">Antibiótico</Badge></div>
|
||||
)}
|
||||
{ind.tipo === 'Farmacologica Profilactica' && (
|
||||
<div className="font-medium text-sm leading-tight">{ind.droga} {ind.dosis} {ind.frecuenciaHoras ? `c/${ind.frecuenciaHoras}hs` : ''} {ind.via}</div>
|
||||
)}
|
||||
{ind.tipo === 'Farmacologica Insulina' && (
|
||||
<div className="font-medium text-sm leading-tight">{ind.tipoInsulina}
|
||||
{ind.unidadesDesayuno && ` - PreDesayuno: ${ind.unidadesDesayuno}U`}
|
||||
{ind.unidadesAlmuerzo && ` - PreAlmuerzo: ${ind.unidadesAlmuerzo}U`}
|
||||
{ind.unidadesNoche && ` - 23hs: ${ind.unidadesNoche}U`}
|
||||
</div>
|
||||
)}
|
||||
{ind.tipo === 'No Farmacologica' && (
|
||||
<div className="font-medium text-sm leading-tight">{ind.indicacionNoFco}</div>
|
||||
)}
|
||||
{(ind.tipo === 'PHP' || ind.tipo === 'PHP Paralelo') && (
|
||||
<div className="font-medium text-sm leading-tight">{ind.tipoPlan} {ind.cantidadMl}ml en {ind.tiempoHoras}hs</div>
|
||||
)}
|
||||
{ind.tipo === 'PHP Alterno' && (
|
||||
<div className="font-medium text-sm leading-tight">{ind.tipoPlan} {ind.cantidadMl}ml + {ind.tipoPlan2} {ind.cantidadMl2}ml en {ind.tiempoHoras}hs</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex gap-1 shrink-0">
|
||||
{canEdit && <Button size="sm" variant="outline" className="h-7 w-7 p-0" title="Editar" onClick={() => loadEdit(ind)}>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>}
|
||||
{canEdit && <Button size="sm" variant="outline" className="h-7 w-7 p-0 text-red-600 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-950/30" title="Eliminar" onClick={() => {
|
||||
setDeleteConfirmInd(ind);
|
||||
}}>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{deleteConfirmInd && (
|
||||
<Dialog open={!!deleteConfirmInd} onOpenChange={(open) => { if (!open) setDeleteConfirmInd(null); }}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="text-red-600 flex items-center gap-2">
|
||||
<Trash2 className="h-5 w-5" />
|
||||
Confirmar eliminación de indicación
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-2">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
¿Está seguro de que desea suspender/eliminar esta indicación? Se registrará la baja en el historial.
|
||||
</p>
|
||||
<div className="p-3 bg-muted rounded-md text-sm font-medium">
|
||||
<span className="text-xs text-muted-foreground block mb-1">Indicación:</span>
|
||||
{formatIndicacion(deleteConfirmInd)}
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="delete-medico">Médico que suspende / elimina *</Label>
|
||||
<Input
|
||||
id="delete-medico"
|
||||
value={getNombreProfesional(currentUser)}
|
||||
disabled
|
||||
placeholder="Nombre del profesional..."
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 mt-2">
|
||||
<Button variant="outline" onClick={() => setDeleteConfirmInd(null)}>
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={async () => {
|
||||
const med = effectiveDeleteMedico.trim() || deleteConfirmInd.medicoCrea || 'Médico';
|
||||
const indToDel = deleteConfirmInd;
|
||||
setDeleteConfirmInd(null);
|
||||
await handleSuspender(indToDel, med);
|
||||
}}
|
||||
>
|
||||
Eliminar
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)}
|
||||
|
||||
{showHistorial && (
|
||||
<Dialog open={showHistorial} onOpenChange={setShowHistorial}>
|
||||
<DialogContent className="max-w-4xl max-h-[80vh] overflow-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Historial de Indicaciones</DialogTitle>
|
||||
</DialogHeader>
|
||||
{movs.length === 0 ? (
|
||||
<p className="text-gray-500 py-4">Sin movimientos registrados</p>
|
||||
) : (
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-800" onClick={() => handleSort('fecha')}>
|
||||
Fecha {sortField === 'fecha' && (sortDir === 'asc' ? '↑' : '↓')}
|
||||
</TableHead>
|
||||
<TableHead className="cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-800" onClick={() => handleSort('profesional')}>
|
||||
Profesional {sortField === 'profesional' && (sortDir === 'asc' ? '↑' : '↓')}
|
||||
</TableHead>
|
||||
<TableHead className="cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-800" onClick={() => handleSort('tipo')}>
|
||||
Tipo {sortField === 'tipo' && (sortDir === 'asc' ? '↑' : '↓')}
|
||||
</TableHead>
|
||||
<TableHead>Indicación</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{sortedMovs.map(mov => (
|
||||
<TableRow key={mov.id}>
|
||||
<TableCell>{mov.fecha}</TableCell>
|
||||
<TableCell>{mov.profesional}</TableCell>
|
||||
<TableCell>
|
||||
<Badge className={
|
||||
mov.tipo === 'Nueva' || mov.tipo === 'Indicacion'
|
||||
? 'bg-green-600 hover:bg-green-700 text-white'
|
||||
: mov.tipo === 'Suspencion' || mov.tipo === 'Suspensión' || mov.tipo === 'Eliminacion'
|
||||
? 'bg-red-600 hover:bg-red-700 text-white'
|
||||
: 'bg-orange-500 hover:bg-orange-600 text-white'
|
||||
}>
|
||||
{mov.tipo === 'Nueva' || mov.tipo === 'Indicacion' ? 'Nueva' : mov.tipo === 'Suspencion' || mov.tipo === 'Suspensión' || mov.tipo === 'Eliminacion' ? 'Suspensión' : 'Modificación'}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{mov.tipo === 'Modificacion' ? (
|
||||
<div className="text-sm">
|
||||
<div className="text-red-500 line-through">{mov.indicacionPrevia}</div>
|
||||
<div className="text-green-500">{mov.indicacionNueva}</div>
|
||||
</div>
|
||||
) : (mov.tipo === 'Suspencion' || mov.tipo === 'Suspensión' || mov.tipo === 'Eliminacion') ? mov.indicacionPrevia : mov.indicacionNueva || mov.indicacionPrevia}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user