Agregar hora a laboratorios: modal importar, save con hora seleccionada

This commit is contained in:
2026-04-17 01:43:22 -03:00
parent e9df92a1fb
commit 711b910344
6 changed files with 497 additions and 545 deletions
+44 -53
View File
@@ -1,64 +1,55 @@
import * as React from "react" import * as React from "react"
import * as AccordionPrimitive from "@radix-ui/react-accordion" import * as AccordionPrimitive from "@radix-ui/react-accordion"
import { ChevronDownIcon } from "lucide-react" import { ChevronDown } from "lucide-react"
import { cn } from "@/lib/utils" import { cn } from "@/lib/utils"
function Accordion({ const Accordion = AccordionPrimitive.Root
...props
}: React.ComponentProps<typeof AccordionPrimitive.Root>) {
return <AccordionPrimitive.Root data-slot="accordion" {...props} />
}
function AccordionItem({ const AccordionItem = React.forwardRef<
className, React.ElementRef<typeof AccordionPrimitive.Item>,
...props React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Item>
}: React.ComponentProps<typeof AccordionPrimitive.Item>) { >(({ className, ...props }, ref) => (
return ( <AccordionPrimitive.Item
<AccordionPrimitive.Item ref={ref}
data-slot="accordion-item" className={cn("border-b", className)}
className={cn("border-b last:border-b-0", className)} {...props}
{...props} />
/> ))
) AccordionItem.displayName = "AccordionItem"
}
function AccordionTrigger({ const AccordionTrigger = React.forwardRef<
className, React.ElementRef<typeof AccordionPrimitive.Trigger>,
children, React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Trigger>
...props >(({ className, children, ...props }, ref) => (
}: React.ComponentProps<typeof AccordionPrimitive.Trigger>) { <AccordionPrimitive.Header className="flex">
return ( <AccordionPrimitive.Trigger
<AccordionPrimitive.Header className="flex"> ref={ref}
<AccordionPrimitive.Trigger className={cn(
data-slot="accordion-trigger" "flex flex-1 items-center justify-between py-4 text-sm font-medium transition-all hover:underline text-left [&[data-state=open]>svg]:rotate-180",
className={cn( className
"focus-visible:border-ring focus-visible:ring-ring/50 flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180", )}
className
)}
{...props}
>
{children}
<ChevronDownIcon className="text-muted-foreground pointer-events-none size-4 shrink-0 translate-y-0.5 transition-transform duration-200" />
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
)
}
function AccordionContent({
className,
children,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Content>) {
return (
<AccordionPrimitive.Content
data-slot="accordion-content"
className="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm"
{...props} {...props}
> >
<div className={cn("pt-0 pb-4", className)}>{children}</div> {children}
</AccordionPrimitive.Content> <ChevronDown className="h-4 w-4 shrink-0 text-muted-foreground transition-transform duration-200" />
) </AccordionPrimitive.Trigger>
} </AccordionPrimitive.Header>
))
AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName
const AccordionContent = React.forwardRef<
React.ElementRef<typeof AccordionPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<AccordionPrimitive.Content
ref={ref}
className="overflow-hidden text-sm data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down"
{...props}
>
<div className={cn("pb-4 pt-0", className)}>{children}</div>
</AccordionPrimitive.Content>
))
AccordionContent.displayName = AccordionPrimitive.Content.displayName
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent } export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }
+1 -3
View File
@@ -84,9 +84,7 @@ export function EditIngreso({
<div className="space-y-6 dark:text-white"> <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 flex-col sm:flex-row items-start sm:items-center justify-between gap-4">
<div className="flex items-center gap-4"> <div className="flex items-center gap-4">
<Button variant="ghost" size="icon" onClick={onVolver}>
<ArrowLeft className="h-5 w-5" />
</Button>
<div> <div>
<h1 className="text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-2"> <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" /> <User className="h-6 w-6 text-blue-600" />
+332 -368
View File
@@ -1,5 +1,13 @@
import { useState } from 'react'; import { useState } from 'react';
import { PDFDocument } from 'pdf-lib'; import { PDFDocument } from 'pdf-lib';
import { User } from 'lucide-react';
import {
Accordion,
AccordionContent,
AccordionItem,
AccordionTrigger,
} from "@/components/ui/accordion";
import { import {
FlaskConical, FlaskConical,
Microscope, Microscope,
@@ -117,10 +125,10 @@ const RANGOS_LABORATORIO: Record<string, { min: number; max: number }> = {
function calcularEstadoLaboratorio(parametro: string, valor: string): 'Normal' | 'Alto' | 'Bajo' { function calcularEstadoLaboratorio(parametro: string, valor: string): 'Normal' | 'Alto' | 'Bajo' {
const rango = RANGOS_LABORATORIO[parametro]; const rango = RANGOS_LABORATORIO[parametro];
if (!rango) return 'Normal'; if (!rango) return 'Normal';
const num = parseFloat(valor); const num = parseFloat(valor);
if (isNaN(num)) return 'Normal'; if (isNaN(num)) return 'Normal';
if (num < rango.min) return 'Bajo'; if (num < rango.min) return 'Bajo';
if (num > rango.max) return 'Alto'; if (num > rango.max) return 'Alto';
return 'Normal'; return 'Normal';
@@ -130,7 +138,7 @@ function wrapText(text: string, font: any, fontSize: number, maxWidth: number):
const words = text.split(' '); const words = text.split(' ');
const lines: string[] = []; const lines: string[] = [];
let currentLine = ''; let currentLine = '';
for (const word of words) { for (const word of words) {
const testLine = currentLine ? `${currentLine} ${word}` : word; const testLine = currentLine ? `${currentLine} ${word}` : word;
const testWidth = font.widthOfTextAtSize(testLine, fontSize); const testWidth = font.widthOfTextAtSize(testLine, fontSize);
@@ -145,6 +153,8 @@ function wrapText(text: string, font: any, fontSize: number, maxWidth: number):
return lines; return lines;
} }
export function HistoriaClinica({ export function HistoriaClinica({
internacion, internacion,
paciente, paciente,
@@ -203,40 +213,23 @@ export function HistoriaClinica({
return Math.floor(diff / (1000 * 60 * 60 * 24)); return Math.floor(diff / (1000 * 60 * 60 * 24));
}; };
const handleGuardarEdicion = () => {
if (editCamaId && editCamaId !== internacion.camaId && cama) {
onActualizarCama(cama.id, { estado: 'Disponible', pacienteId: undefined, internacionId: undefined });
}
if (editCamaId) {
onActualizarCama(editCamaId, { estado: 'Ocupada', pacienteId: paciente.id, internacionId: internacion.id });
}
onActualizarInternacion(internacion.id, {
fechaIngresoClinica: editFechaIngreso,
motivoConsulta: editMotivoConsulta,
diagnosticoIngreso: editDiagnostico,
enfermedadActual: editEnfermedadActual,
antecedentesEnfermedadActual: editAntecedentes,
medicoIngresante: editMedico,
camaId: editCamaId || undefined,
});
setEditIngresoDialog(false);
};
return ( return (
<div className="space-y-6 dark:text-white"> <div className="space-y-6 dark:text-white">
<div>
<div className="flex items-center gap-4 mb-4">
<div> <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<h1 className="text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-2"><ClipboardList className="h-6 w-6" />Historia Clínica</h1>
<p className="text-gray-500">
Cama: {cama?.numero || 'N/A'} | {paciente.apellido}, {paciente.nombre} | {paciente.fechaNacimiento ? calcularEdad(paciente.fechaNacimiento) + ' años' : ''} | DNI: {paciente.dni}
</p>
</div>
<div>
<h1 className="text-2xl font-bold text-gray-900 dark:text-white flex items-center gap-2">
<ClipboardList className="h-6 w-6 text-blue-600" />
{cama?.numero || 'N/A'} - Historia Clínica
</h1>
<p className="text-gray-500 dark:text-gray-400">Módulo de Historia Clínica de Internación</p>
</div> </div>
<div className="flex items-center gap-2 flex-wrap"> <div className="flex items-center gap-2">
<Button variant="outline" onClick={onVolver}> <Button variant="outline" onClick={onVolver}>
<ArrowLeft className="h-4 w-4 mr-2" /> <ArrowLeft className="h-4 w-4 mr-2" />
Volver Volver
@@ -246,253 +239,224 @@ export function HistoriaClinica({
Editar Ingreso Editar Ingreso
</Button> </Button>
</div> </div>
</div> </div>
<Dialog open={editIngresoDialog} onOpenChange={setEditIngresoDialog}>
<DialogContent className="sm:max-w-2xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>Editar Ingreso</DialogTitle>
</DialogHeader>
<Card className="bg-muted/50">
<CardContent className="p-4">
<div className="flex flex-wrap gap-2 mb-2">
<Badge variant="outline" className="bg-primary/10 text-primary border-primary/30">
{paciente.apellido}, {paciente.nombre}
</Badge>
<Badge variant="outline" className="bg-primary/10 text-primary border-primary/30">
{paciente.fechaNacimiento ? calcularEdad(paciente.fechaNacimiento) + ' años' : ''}
</Badge>
<Badge variant="outline" className="bg-primary/10 text-primary border-primary/30">
DNI: {paciente.dni}
</Badge>
</div>
<div className="flex flex-wrap gap-2">
<Badge variant="secondary">
HC: {paciente.historiaClinica || 'N/A'}
</Badge>
<Badge variant="secondary">
{paciente.obraSocial || 'Sin obra social'}
</Badge>
<Badge variant="secondary">
{paciente.nacionalidad || 'N/A'}
</Badge>
</div>
</CardContent>
</Card>
<div className="space-y-4">
<div className="grid grid-cols-3 gap-4">
<div>
<Label>Fecha de Ingreso *</Label>
<Input type="date" value={editFechaIngreso} onChange={e => setEditFechaIngreso(e.target.value)} />
</div>
<div>
<Label>Médico Ingresante *</Label>
<Input value={editMedico} onChange={e => setEditMedico(e.target.value)} placeholder="Nombre del médico" />
</div>
<div>
<Label>Cama</Label>
<Select value={editCamaId} onValueChange={setEditCamaId}>
<SelectTrigger><SelectValue placeholder="Seleccionar cama" /></SelectTrigger>
<SelectContent>
{(allCamas || []).filter((c: Cama) => c.estado === 'Disponible' || c.id === cama?.id).map((c: Cama) => (
<SelectItem key={c.id} value={c.id}>{c.numero}</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div>
<Label>Motivo de Consulta</Label>
<textarea className="w-full p-2 border rounded-md text-sm min-h-[60px]" value={editMotivoConsulta} onChange={e => setEditMotivoConsulta(e.target.value)} />
</div>
<div>
<Label>Diagnóstico de Ingreso *</Label>
<textarea className="w-full p-2 border rounded-md text-sm min-h-[60px]" value={editDiagnostico} onChange={e => setEditDiagnostico(e.target.value)} />
</div>
<div>
<Label>Enfermedad Actual</Label>
<textarea className="w-full p-2 border rounded-md text-sm min-h-[80px]" value={editEnfermedadActual} onChange={e => setEditEnfermedadActual(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]" value={editAntecedentes} onChange={e => setEditAntecedentes(e.target.value)} />
</div>
</div>
<div className="flex justify-end gap-2 mt-4">
<Button variant="outline" onClick={() => setEditIngresoDialog(false)}><X className="h-4 w-4 mr-2" />Cancelar</Button>
<Button onClick={handleGuardarEdicion} disabled={!editFechaIngreso || !editDiagnostico || !editMedico}><Save className="h-4 w-4 mr-2" />Guardar</Button>
</div>
</DialogContent>
</Dialog>
<Card> <Card>
<CardContent className="p-0"> <CardContent className="p-4">
<button type="button" className="w-full p-4 flex items-center justify-between hover:bg-gray-50" onClick={() => setDetalleExpandido(!detalleExpandido)}> <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div className="grid grid-cols-2 sm:grid-cols-4 gap-4 text-sm w-full"> <div><h2 className="font-bold text-lg text-gray-900 flex items-center gap-2">
<User className="h-4 w-4" />
{paciente.apellido}, {paciente.nombre}
</h2>
</div>
<div className="flex items-center gap-2">
<Badge className={internacion.fechaIngresoClinica && calcularDiasInternado(internacion.fechaIngresoClinica) > 7 ? 'bg-red-100 text-red-800' : 'bg-blue-100 text-blue-800'}>
{internacion.fechaIngresoClinica ? calcularDiasInternado(internacion.fechaIngresoClinica) : 0} días internado
</Badge>
</div>
</div>
<div className="space-y-2">
<div className="flex flex-wrap gap-2">
<Badge variant="outline" className="text-sm px-3 py-1 bg-green-50 text-green-700 dark:bg-green-950 dark:text-green-300">
{paciente.fechaNacimiento ? calcularEdad(paciente.fechaNacimiento) + ' años' : ''}
</Badge>
<Badge variant="outline" className="text-sm px-3 py-1 bg-blue-50 text-blue-700 border-blue-200">
DNI: {paciente.dni}
</Badge>
</div>
<div className="flex flex-wrap gap-2">
<Badge variant="secondary" className="text-sm px-3 py-1">
HC: {paciente.historiaClinica || 'No posee'}
</Badge>
<Badge variant="secondary" className="text-sm px-3 py-1">
OS: {paciente.obraSocial || 'No posee'}
</Badge>
<Badge variant="secondary" className="text-sm px-3 py-1">
Nacionalidad: {paciente.nacionalidad || 'N/A'}
</Badge>
</div>
<div className="border-t p-4 space-y-4">
<div> <div>
<p className="text-gray-500">Antecedentes</p> <p className="text-gray-500 text-sm">Antecedentes</p>
<p className="font-medium truncate">{paciente.antecedentes || 'No constan'}</p> <p className="font-medium">{paciente.antecedentes || 'No refiere'}</p>
</div> </div>
<div>
<p className="text-gray-500 text-sm">MH</p>
<p className="font-medium">{paciente.medicacionHabitual || 'No refiere'}</p>
</div>
<div> <div>
<p className="text-gray-500">Fecha de Ingreso</p> <p className="text-gray-500">Fecha de Ingreso</p>
<p className="font-medium">{internacion.fechaIngresoClinica ? formatDateDDMMYYYY(internacion.fechaIngresoClinica) : 'N/A'}</p> <p className="font-medium">{internacion.fechaIngresoClinica ? formatDateDDMMYYYY(internacion.fechaIngresoClinica) : 'N/A'}</p>
</div> </div>
<div> <div>
<p className="text-gray-500">Diagnóstico de Ingreso</p> <p className="text-gray-500">Diagnóstico de Ingreso</p>
<p className="font-medium truncate">{internacion.diagnosticoIngreso}</p> <p className="font-medium">{internacion.diagnosticoIngreso}</p>
</div> </div>
<div>
<p className="text-gray-500">Días de Internación</p> <Accordion type="single" collapsible defaultValue="item-1">
<Badge className={internacion.fechaIngresoClinica && calcularDiasInternado(internacion.fechaIngresoClinica) > 7 ? 'bg-red-100 text-red-800' : 'bg-blue-100 text-blue-800'}> <AccordionItem value="item-1">
{internacion.fechaIngresoClinica ? calcularDiasInternado(internacion.fechaIngresoClinica) : 0} días <AccordionTrigger>Detalle Episodio Actual</AccordionTrigger>
</Badge> <AccordionContent className="p4">
</div> <div className="border-t p-4 space-y-4">
<div>
<p className="text-gray-500 text-sm">Motivo de Consulta</p>
<p className="font-medium">{internacion.motivoConsulta || 'Sin motivo registrado'}</p>
</div>
<div>
<p className="text-gray-500 text-sm">Enfermedad Actual</p>
<p className="font-medium">{internacion.enfermedadActual || 'Sin información'}</p>
</div>
<div>
<p className="text-gray-500 text-sm">Antecedentes de Enfermedad Actual</p>
<p className="font-medium">{internacion.antecedentesEnfermedadActual || 'Sin antecedentes registrados'}</p>
</div>
<Button variant="outline" className="bg-blue-50 border-blue-300 text-blue-700 hover:bg-blue-100" onClick={async (e) => {
e.stopPropagation();
try {
const { PDFDocument, StandardFonts, rgb } = await import('pdf-lib');
const pdfDoc = await PDFDocument.create();
const page = pdfDoc.addPage([595, 842]);
const { width, height } = page.getSize();
const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
const fontBold = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
const colorPrimary = rgb(0.18, 0.34, 0.55);
const colorText = rgb(0.13, 0.13, 0.13);
const colorGray = rgb(0.45, 0.45, 0.45);
const colorLightGray = rgb(0.92, 0.92, 0.92);
const edad = paciente.fechaNacimiento ? calcularEdad(paciente.fechaNacimiento) : '';
const fechaFormateada = internacion.fechaIngresoClinica ? formatDateDDMMYYYY(internacion.fechaIngresoClinica) : 'N/A';
const fechaHospital = internacion.fechaIngresoHospital ? formatDateDDMMYYYY(internacion.fechaIngresoHospital) : '';
// Header
page.drawRectangle({ x: 0, y: height - 100, width, height: 100, color: colorPrimary });
page.drawText('HOSPITAL DONACIÓN F. SANTOJANNI DIVISIÓN CLÍNICA MÉDICA', { x: 60, y: height - 35, size: 14, font: fontBold, color: rgb(1, 1, 1) });
page.drawText('HISTORIA CLÍNICA DE INGRESO', { x: 170, y: height - 55, size: 12, font: fontBold, color: rgb(1, 1, 1) });
let y = height - 140;
// Datos Filiatorios
page.drawRectangle({ x: 45, y: y - 8, width: 505, height: 24, color: colorLightGray });
page.drawText('DATOS FILIATORIOS', { x: 50, y: y, size: 12, font: fontBold, color: colorPrimary });
y -= 35;
// Primera línea: Fechas y cama
const fechaIngresoHospText = fechaHospital ? `Fecha ingreso al hospital: ${fechaHospital}` : '';
const fechaIngresoClinText = fechaFormateada ? `Fecha ingreso a clínica: ${fechaFormateada}` : '';
const camaText = `Cama: ${cama?.numero || 'N/A'}`;
page.drawText(fechaIngresoHospText, { x: 50, y, size: 10, font: fontBold, color: colorGray });
page.drawText(fechaIngresoClinText, { x: 260, y, size: 10, font: fontBold, color: colorGray });
y -= 18;
page.drawText(camaText, { x: 50, y, size: 10, font: fontBold, color: colorGray });
y -= 25;
// Segunda línea: Apellido, Nombre y DNI
page.drawText(`Apellido y Nombre: ${paciente.apellido || ''}, ${paciente.nombre || ''}`, { x: 50, y, size: 10, font: fontBold, color: colorGray });
y -= 18;
page.drawText(`DNI: ${paciente.dni || ''}`, { x: 50, y, size: 10, font: fontBold, color: colorGray });
page.drawText(`Edad: ${edad ? `${edad} años` : ''}`, { x: 280, y, size: 10, font: fontBold, color: colorGray });
y -= 40;
// Datos Clínicos
page.drawRectangle({ x: 45, y: y - 8, width: 505, height: 24, color: colorLightGray });
page.drawText('DATOS CLÍNICOS', { x: 50, y: y, size: 12, font: fontBold, color: colorPrimary });
y -= 35;
page.drawText('Motivo de Consulta:', { x: 50, y, size: 10, font: fontBold, color: colorGray });
y -= 18;
const motivoLines = wrapText(internacion.motivoConsulta || 'Sin información', font, 10, 480);
for (const line of motivoLines.slice(0, 4)) {
page.drawText(line, { x: 50, y, size: 10, font, color: colorText });
y -= 14;
}
y -= 10;
if (motivoLines.length > 4) y -= (motivoLines.length - 4) * 14;
page.drawText('Enfermedad Actual:', { x: 50, y, size: 10, font: fontBold, color: colorGray });
y -= 18;
const enfermedadLines = wrapText(internacion.enfermedadActual || 'Sin información', font, 10, 480);
for (const line of enfermedadLines.slice(0, 4)) {
page.drawText(line, { x: 50, y, size: 10, font, color: colorText });
y -= 14;
}
y -= 10;
if (enfermedadLines.length > 4) y -= (enfermedadLines.length - 4) * 14;
page.drawText('Antecedentes de la Enfermedad Actual:', { x: 50, y, size: 10, font: fontBold, color: colorGray });
y -= 18;
const antecedentesLines = wrapText(internacion.antecedentesEnfermedadActual || 'Sin antecedentes registrados', font, 10, 480);
for (const line of antecedentesLines.slice(0, 4)) {
page.drawText(line, { x: 50, y, size: 10, font, color: colorText });
y -= 14;
}
y -= 10;
if (antecedentesLines.length > 4) y -= (antecedentesLines.length - 4) * 14;
page.drawText('Diagnóstico de Ingreso:', { x: 50, y, size: 10, font: fontBold, color: colorGray });
y -= 18;
const diagnosticoLines = wrapText(internacion.diagnosticoIngreso || 'Sin diagnóstico', font, 10, 480);
for (const line of diagnosticoLines.slice(0, 3)) {
page.drawText(line, { x: 50, y, size: 10, font, color: colorText });
y -= 14;
}
// Footer
y -= 20;
page.drawLine({ start: { x: 50, y }, end: { x: 250, y }, thickness: 0.5, color: colorGray });
page.drawText('Firma del Médico', { x: 50, y: y - 15, size: 9, font, color: colorGray });
page.drawLine({ start: { x: 320, y }, end: { x: 520, y }, thickness: 0.5, color: colorGray });
page.drawText('Aclaración / Sello', { x: 320, y: y - 15, size: 9, font, color: colorGray });
page.drawText('v2.0', { x: width - 60, y: 30, size: 8, font, color: colorGray });
const pdfBytes = await pdfDoc.save();
const blob = new Blob([new Uint8Array(pdfBytes)], { type: 'application/pdf' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `FormularioIngreso_${paciente.apellido}_${paciente.dni}.pdf`;
link.click();
URL.revokeObjectURL(url);
} catch (err) {
console.error('Error generating PDF:', err);
}
}}>
<FileDown className="h-4 w-4 mr-2" />
Descargar Formulario de Ingreso
</Button>
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
</div> </div>
{detalleExpandido ? <ChevronUp className="h-5 w-5 text-gray-400" /> : <ChevronDown className="h-5 w-5 text-gray-400" />}
</button>
{detalleExpandido && (
<div className="border-t p-4 space-y-4">
<div>
<p className="text-gray-500 text-sm">Motivo de Consulta</p>
<p className="font-medium">{internacion.motivoConsulta || 'Sin motivo registrado'}</p>
</div>
<div>
<p className="text-gray-500 text-sm">Enfermedad Actual</p>
<p className="font-medium">{internacion.enfermedadActual || 'Sin información'}</p>
</div>
<div>
<p className="text-gray-500 text-sm">Antecedentes de Enfermedad Actual</p>
<p className="font-medium">{internacion.antecedentesEnfermedadActual || 'Sin antecedentes registrados'}</p>
</div>
<Button variant="outline" className="bg-blue-50 border-blue-300 text-blue-700 hover:bg-blue-100" onClick={async (e) => {
e.stopPropagation();
try {
const { PDFDocument, StandardFonts, rgb } = await import('pdf-lib');
const pdfDoc = await PDFDocument.create();
const page = pdfDoc.addPage([595, 842]);
const { width, height } = page.getSize();
const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
const fontBold = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
const colorPrimary = rgb(0.18, 0.34, 0.55);
const colorText = rgb(0.13, 0.13, 0.13);
const colorGray = rgb(0.45, 0.45, 0.45);
const colorLightGray = rgb(0.92, 0.92, 0.92);
const edad = paciente.fechaNacimiento ? calcularEdad(paciente.fechaNacimiento) : ''; </div>
const fechaFormateada = internacion.fechaIngresoClinica ? formatDateDDMMYYYY(internacion.fechaIngresoClinica) : 'N/A';
const fechaHospital = internacion.fechaIngresoHospital ? formatDateDDMMYYYY(internacion.fechaIngresoHospital) : '';
// Header
page.drawRectangle({ x: 0, y: height - 100, width, height: 100, color: colorPrimary });
page.drawText('HOSPITAL DONACIÓN F. SANTOJANNI DIVISIÓN CLÍNICA MÉDICA', { x: 60, y: height - 35, size: 14, font: fontBold, color: rgb(1, 1, 1) });
page.drawText('HISTORIA CLÍNICA DE INGRESO', { x: 170, y: height - 55, size: 12, font: fontBold, color: rgb(1, 1, 1) });
let y = height - 140;
// Datos Filiatorios
page.drawRectangle({ x: 45, y: y - 8, width: 505, height: 24, color: colorLightGray });
page.drawText('DATOS FILIATORIOS', { x: 50, y: y, size: 12, font: fontBold, color: colorPrimary });
y -= 35;
// Primera línea: Fechas y cama
const fechaIngresoHospText = fechaHospital ? `Fecha ingreso al hospital: ${fechaHospital}` : '';
const fechaIngresoClinText = fechaFormateada ? `Fecha ingreso a clínica: ${fechaFormateada}` : '';
const camaText = `Cama: ${cama?.numero || 'N/A'}`;
page.drawText(fechaIngresoHospText, { x: 50, y, size: 10, font: fontBold, color: colorGray });
page.drawText(fechaIngresoClinText, { x: 260, y, size: 10, font: fontBold, color: colorGray });
y -= 18;
page.drawText(camaText, { x: 50, y, size: 10, font: fontBold, color: colorGray });
y -= 25;
// Segunda línea: Apellido, Nombre y DNI
page.drawText(`Apellido y Nombre: ${paciente.apellido || ''}, ${paciente.nombre || ''}`, { x: 50, y, size: 10, font: fontBold, color: colorGray });
y -= 18;
page.drawText(`DNI: ${paciente.dni || ''}`, { x: 50, y, size: 10, font: fontBold, color: colorGray });
page.drawText(`Edad: ${edad ? `${edad} años` : ''}`, { x: 280, y, size: 10, font: fontBold, color: colorGray });
y -= 40;
// Datos Clínicos
page.drawRectangle({ x: 45, y: y - 8, width: 505, height: 24, color: colorLightGray });
page.drawText('DATOS CLÍNICOS', { x: 50, y: y, size: 12, font: fontBold, color: colorPrimary });
y -= 35;
page.drawText('Motivo de Consulta:', { x: 50, y, size: 10, font: fontBold, color: colorGray });
y -= 18;
const motivoLines = wrapText(internacion.motivoConsulta || 'Sin información', font, 10, 480);
for (const line of motivoLines.slice(0, 4)) {
page.drawText(line, { x: 50, y, size: 10, font, color: colorText });
y -= 14;
}
y -= 10;
if (motivoLines.length > 4) y -= (motivoLines.length - 4) * 14;
page.drawText('Enfermedad Actual:', { x: 50, y, size: 10, font: fontBold, color: colorGray });
y -= 18;
const enfermedadLines = wrapText(internacion.enfermedadActual || 'Sin información', font, 10, 480);
for (const line of enfermedadLines.slice(0, 4)) {
page.drawText(line, { x: 50, y, size: 10, font, color: colorText });
y -= 14;
}
y -= 10;
if (enfermedadLines.length > 4) y -= (enfermedadLines.length - 4) * 14;
page.drawText('Antecedentes de la Enfermedad Actual:', { x: 50, y, size: 10, font: fontBold, color: colorGray });
y -= 18;
const antecedentesLines = wrapText(internacion.antecedentesEnfermedadActual || 'Sin antecedentes registrados', font, 10, 480);
for (const line of antecedentesLines.slice(0, 4)) {
page.drawText(line, { x: 50, y, size: 10, font, color: colorText });
y -= 14;
}
y -= 10;
if (antecedentesLines.length > 4) y -= (antecedentesLines.length - 4) * 14;
page.drawText('Diagnóstico de Ingreso:', { x: 50, y, size: 10, font: fontBold, color: colorGray });
y -= 18;
const diagnosticoLines = wrapText(internacion.diagnosticoIngreso || 'Sin diagnóstico', font, 10, 480);
for (const line of diagnosticoLines.slice(0, 3)) {
page.drawText(line, { x: 50, y, size: 10, font, color: colorText });
y -= 14;
}
// Footer
y -= 20;
page.drawLine({ start: { x: 50, y }, end: { x: 250, y }, thickness: 0.5, color: colorGray });
page.drawText('Firma del Médico', { x: 50, y: y - 15, size: 9, font, color: colorGray });
page.drawLine({ start: { x: 320, y }, end: { x: 520, y }, thickness: 0.5, color: colorGray });
page.drawText('Aclaración / Sello', { x: 320, y: y - 15, size: 9, font, color: colorGray });
page.drawText('v2.0', { x: width - 60, y: 30, size: 8, font, color: colorGray });
const pdfBytes = await pdfDoc.save();
const blob = new Blob([new Uint8Array(pdfBytes)], { type: 'application/pdf' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `FormularioIngreso_${paciente.apellido}_${paciente.dni}.pdf`;
link.click();
URL.revokeObjectURL(url);
} catch (err) {
console.error('Error generating PDF:', err);
}
}}>
<FileDown className="h-4 w-4 mr-2" />
Descargar Formulario de Ingreso
</Button>
</div>
)}
</CardContent> </CardContent>
</Card> </Card>
<Tabs value={tabActivo} onValueChange={setTabActivo}> <Tabs value={tabActivo} onValueChange={setTabActivo}>
<TabsList className="flex w-full overflow-x-auto gap-1 pb-2"> <TabsList className="flex w-full overflow-x-auto gap-1 pb-2">
<TabsTrigger value="evoluciones" className="flex-shrink-0 flex items-center gap-1 text-xs sm:text-sm"> <TabsTrigger value="evoluciones" className="flex-shrink-0 flex items-center gap-1 text-xs sm:text-sm">
@@ -544,12 +508,12 @@ export function HistoriaClinica({
</TabsContent> </TabsContent>
<TabsContent value="estudios" className="mt-4"> <TabsContent value="estudios" className="mt-4">
<SeccionEstudiosComplementarios <SeccionEstudiosComplementarios
estudios={estudiosComplementarios} estudios={estudiosComplementarios}
internacionId={internacion.id} internacionId={internacion.id}
pacienteId={paciente.id} pacienteId={paciente.id}
add={onAgregarEstudioComplementario} add={onAgregarEstudioComplementario}
del={onEliminarEstudioComplementario} del={onEliminarEstudioComplementario}
/> />
</TabsContent> </TabsContent>
</Tabs> </Tabs>
@@ -665,7 +629,7 @@ function SeccionLaboratorios({ lab, patientId, add, update, del, addAcidoBase }:
if (tp) res.push({ parametro: 'Tiempo de Protrombina', valor: tp, unidad: 'seg', estado: calcularEstadoLaboratorio('Tiempo de Protrombina', tp) }); if (tp) res.push({ parametro: 'Tiempo de Protrombina', valor: tp, unidad: 'seg', estado: calcularEstadoLaboratorio('Tiempo de Protrombina', tp) });
if (kptt) res.push({ parametro: 'KPTT', valor: kptt, unidad: 'seg', estado: calcularEstadoLaboratorio('KPTT', kptt) }); if (kptt) res.push({ parametro: 'KPTT', valor: kptt, unidad: 'seg', estado: calcularEstadoLaboratorio('KPTT', kptt) });
if (rin) res.push({ parametro: 'INR', valor: rin, unidad: '', estado: calcularEstadoLaboratorio('INR', rin) }); if (rin) res.push({ parametro: 'INR', valor: rin, unidad: '', estado: calcularEstadoLaboratorio('INR', rin) });
return res; return res;
}; };
const reset = () => { const reset = () => {
@@ -683,7 +647,7 @@ return res;
const parseLaboratorioTexto = (texto: string): { resultados: ResultadoLaboratorio[]; observaciones: string } => { const parseLaboratorioTexto = (texto: string): { resultados: ResultadoLaboratorio[]; observaciones: string } => {
const resultados: ResultadoLaboratorio[] = []; const resultados: ResultadoLaboratorio[] = [];
const observacionesExtra: string[] = []; const observacionesExtra: string[] = [];
const mapeoParametros: Record<string, { nombre: string; unidad: string; esPrincipal: boolean }> = { const mapeoParametros: Record<string, { nombre: string; unidad: string; esPrincipal: boolean }> = {
'hematíes': { nombre: 'Hematíes', unidad: '10⁶/µl', esPrincipal: false }, 'hematíes': { nombre: 'Hematíes', unidad: '10⁶/µl', esPrincipal: false },
'hematocrito': { nombre: 'Hematocrito', unidad: '%', esPrincipal: true }, 'hematocrito': { nombre: 'Hematocrito', unidad: '%', esPrincipal: true },
@@ -725,10 +689,10 @@ return res;
}; };
const lineas = texto.split('\n'); const lineas = texto.split('\n');
for (const linea of lineas) { for (const linea of lineas) {
const lineaLower = linea.toLowerCase().trim(); const lineaLower = linea.toLowerCase().trim();
for (const [clave, info] of Object.entries(mapeoParametros)) { for (const [clave, info] of Object.entries(mapeoParametros)) {
if (lineaLower.includes(clave)) { if (lineaLower.includes(clave)) {
// buscar primer valor numérico después de cualquier texto (letra o palabra) // buscar primer valor numérico después de cualquier texto (letra o palabra)
@@ -741,7 +705,7 @@ for (const linea of lineas) {
if (nombreNormalizado === 'Leucocitos' || nombreNormalizado === 'Plaquetas') { if (nombreNormalizado === 'Leucocitos' || nombreNormalizado === 'Plaquetas') {
valorFinal = valor * 1000; valorFinal = valor * 1000;
} }
if (info.esPrincipal) { if (info.esPrincipal) {
resultados.push({ resultados.push({
parametro: nombreNormalizado, parametro: nombreNormalizado,
@@ -757,13 +721,13 @@ for (const linea of lineas) {
} }
} }
} }
return { resultados, observaciones: observacionesExtra.join('\n') }; return { resultados, observaciones: observacionesExtra.join('\n') };
}; };
const parseAcidoBaseTexto = (texto: string): Omit<AcidoBase, 'id'> | null => { const parseAcidoBaseTexto = (texto: string): Omit<AcidoBase, 'id'> | null => {
const lineas = texto.split('\n'); const lineas = texto.split('\n');
let ph: number | undefined; let ph: number | undefined;
let pco2: number | undefined; let pco2: number | undefined;
let po2: number | undefined; let po2: number | undefined;
@@ -773,10 +737,10 @@ for (const linea of lineas) {
let lactato: number | undefined; let lactato: number | undefined;
let fio2: number | undefined; let fio2: number | undefined;
let fecha = importFecha; let fecha = importFecha;
for (const linea of lineas) { for (const linea of lineas) {
const cleanLinea = linea.replace(/show_chart|list_alt|\t+/g, ' ').replace(/,/g, '.').replace(/\s+/g, ' ').trim().toLowerCase(); const cleanLinea = linea.replace(/show_chart|list_alt|\t+/g, ' ').replace(/,/g, '.').replace(/\s+/g, ' ').trim().toLowerCase();
const getValue = (param: string): number | undefined => { const getValue = (param: string): number | undefined => {
const idx = cleanLinea.indexOf(param); const idx = cleanLinea.indexOf(param);
if (idx === -1) return undefined; if (idx === -1) return undefined;
@@ -788,7 +752,7 @@ for (const linea of lineas) {
} }
return undefined; return undefined;
}; };
if (cleanLinea.includes('estado') && cleanLinea.includes('ácido') || cleanLinea.includes('base')) { if (cleanLinea.includes('estado') && cleanLinea.includes('ácido') || cleanLinea.includes('base')) {
ph = getValue('ph') || (cleanLinea.match(/ph\s+(\d+\.?\d*)/)?.[1] ? parseFloat(cleanLinea.match(/ph\s+(\d+\.?\d*)/)![1]) : undefined); ph = getValue('ph') || (cleanLinea.match(/ph\s+(\d+\.?\d*)/)?.[1] ? parseFloat(cleanLinea.match(/ph\s+(\d+\.?\d*)/)![1]) : undefined);
pco2 = getValue('pco2') || getValue('pco₂'); pco2 = getValue('pco2') || getValue('pco₂');
@@ -801,7 +765,7 @@ for (const linea of lineas) {
break; break;
} }
} }
if (!ph) { if (!ph) {
for (const linea of lineas) { for (const linea of lineas) {
const cleanLinea = linea.replace(/show_chart|list_alt|\t+/g, ' ').replace(/,/g, '.').replace(/\s+/g, ' ').trim().toLowerCase(); const cleanLinea = linea.replace(/show_chart|list_alt|\t+/g, ' ').replace(/,/g, '.').replace(/\s+/g, ' ').trim().toLowerCase();
@@ -816,7 +780,7 @@ for (const linea of lineas) {
} }
return undefined; return undefined;
}; };
if (cleanLinea.includes('ph') && !cleanLinea.includes('pco2') && !cleanLinea.includes('pco')) { ph = getValue('ph'); } if (cleanLinea.includes('ph') && !cleanLinea.includes('pco2') && !cleanLinea.includes('pco')) { ph = getValue('ph'); }
else if (cleanLinea.includes('pco2') || cleanLinea.includes('pco₂')) { pco2 = getValue('pco2'); } else if (cleanLinea.includes('pco2') || cleanLinea.includes('pco₂')) { pco2 = getValue('pco2'); }
else if (cleanLinea.includes('po2') || cleanLinea.includes('po₂')) { po2 = getValue('po2'); } else if (cleanLinea.includes('po2') || cleanLinea.includes('po₂')) { po2 = getValue('po2'); }
@@ -827,7 +791,7 @@ for (const linea of lineas) {
else if (cleanLinea.includes('fio2')) { fio2 = getValue('fio2'); } else if (cleanLinea.includes('fio2')) { fio2 = getValue('fio2'); }
} }
} }
if (ph) { if (ph) {
return { pacienteId: patientId, fecha, hora: '', ph, pco2: pco2 || 40, po2: po2 || 85, hco3: hco3 || 24, be: be || 0, sato2: sato2 || 97, lactato, fio2, interpretacion: '' }; return { pacienteId: patientId, fecha, hora: '', ph, pco2: pco2 || 40, po2: po2 || 85, hco3: hco3 || 24, be: be || 0, sato2: sato2 || 97, lactato, fio2, interpretacion: '' };
} }
@@ -837,7 +801,7 @@ for (const linea of lineas) {
const handleProcesarTexto = () => { const handleProcesarTexto = () => {
const { resultados, observaciones } = parseLaboratorioTexto(importTexto); const { resultados, observaciones } = parseLaboratorioTexto(importTexto);
const acidoBase = parseAcidoBaseTexto(importTexto); const acidoBase = parseAcidoBaseTexto(importTexto);
setImportResultados(resultados); setImportResultados(resultados);
setImportObservaciones(observaciones); setImportObservaciones(observaciones);
setImportAcidoBase(acidoBase); setImportAcidoBase(acidoBase);
@@ -846,11 +810,11 @@ for (const linea of lineas) {
const handleImportarLaboratorio = () => { const handleImportarLaboratorio = () => {
if (!addAcidoBase) return; if (!addAcidoBase) return;
if (importResultados.length === 0 && !importObservaciones && !importAcidoBase) return; if (importResultados.length === 0 && !importObservaciones && !importAcidoBase) return;
if (importAcidoBase) { if (importAcidoBase) {
addAcidoBase({ ...importAcidoBase, fecha: importFecha, hora: importHora }); addAcidoBase({ ...importAcidoBase, fecha: importFecha, hora: importHora });
} }
add({ add({
pacienteId: patientId, pacienteId: patientId,
fecha: importFecha, fecha: importFecha,
@@ -858,7 +822,7 @@ for (const linea of lineas) {
resultados: importResultados, resultados: importResultados,
observaciones: importObservaciones observaciones: importObservaciones
}); });
setImportDialog(false); setImportDialog(false);
setImportTexto(''); setImportTexto('');
setImportResultados([]); setImportResultados([]);
@@ -1023,17 +987,17 @@ for (const linea of lineas) {
<CartesianGrid strokeDasharray="3 3" className="opacity-30" /> <CartesianGrid strokeDasharray="3 3" className="opacity-30" />
<XAxis dataKey="fecha" tick={{ fontSize: 12 }} /> <XAxis dataKey="fecha" tick={{ fontSize: 12 }} />
<YAxis tick={{ fontSize: 12 }} domain={['auto', 'auto']} /> <YAxis tick={{ fontSize: 12 }} domain={['auto', 'auto']} />
<Tooltip <Tooltip
contentStyle={{ contentStyle={{
backgroundColor: 'hsl(var(--card))', backgroundColor: 'hsl(var(--card))',
border: '1px solid hsl(var(--border))', border: '1px solid hsl(var(--border))',
borderRadius: '8px' borderRadius: '8px'
}} }}
/> />
<Line <Line
type="monotone" type="monotone"
dataKey="valor" dataKey="valor"
stroke="hsl(var(--primary))" stroke="hsl(var(--primary))"
strokeWidth={2} strokeWidth={2}
dot={{ fill: 'hsl(var(--primary))', r: 4 }} dot={{ fill: 'hsl(var(--primary))', r: 4 }}
/> />
@@ -1075,7 +1039,7 @@ for (const linea of lineas) {
</div> </div>
<div> <div>
<Label>Pegar texto del resultado de laboratorio</Label> <Label>Pegar texto del resultado de laboratorio</Label>
<textarea <textarea
className="w-full p-2 border rounded-md text-sm min-h-[200px] font-mono" className="w-full p-2 border rounded-md text-sm min-h-[200px] font-mono"
placeholder="Pegue aquí el texto del resultado de laboratorio..." placeholder="Pegue aquí el texto del resultado de laboratorio..."
value={importTexto} value={importTexto}
@@ -1086,7 +1050,7 @@ for (const linea of lineas) {
<FileText className="h-4 w-4 mr-2" /> <FileText className="h-4 w-4 mr-2" />
Procesar Texto Procesar Texto
</Button> </Button>
{importResultados.length > 0 && ( {importResultados.length > 0 && (
<div className="border rounded-md max-h-48 overflow-y-auto"> <div className="border rounded-md max-h-48 overflow-y-auto">
<Table> <Table>
@@ -1109,7 +1073,7 @@ for (const linea of lineas) {
</Table> </Table>
</div> </div>
)} )}
{importAcidoBase && ( {importAcidoBase && (
<div className="border rounded-md p-3 bg-green-50"> <div className="border rounded-md p-3 bg-green-50">
<p className="text-sm font-medium mb-2 flex items-center gap-2"> <p className="text-sm font-medium mb-2 flex items-center gap-2">
@@ -1128,14 +1092,14 @@ for (const linea of lineas) {
</div> </div>
</div> </div>
)} )}
{importObservaciones && ( {importObservaciones && (
<div className="border rounded-md p-3 bg-muted/50"> <div className="border rounded-md p-3 bg-muted/50">
<p className="text-sm font-medium mb-1">Valores adicionales en observaciones:</p> <p className="text-sm font-medium mb-1">Valores adicionales en observaciones:</p>
<p className="text-sm whitespace-pre-wrap">{importObservaciones}</p> <p className="text-sm whitespace-pre-wrap">{importObservaciones}</p>
</div> </div>
)} )}
{importResultados.length === 0 && !importObservaciones && !importAcidoBase && importTexto && ( {importResultados.length === 0 && !importObservaciones && !importAcidoBase && importTexto && (
<div className="text-center py-4 text-gray-500"> <div className="text-center py-4 text-gray-500">
<p>No se detectaron parámetros. Verifique que el texto contenga los nombres correctos.</p> <p>No se detectaron parámetros. Verifique que el texto contenga los nombres correctos.</p>
@@ -1146,7 +1110,7 @@ for (const linea of lineas) {
<Button variant="outline" onClick={() => setImportDialog(false)}>Cancelar</Button> <Button variant="outline" onClick={() => setImportDialog(false)}>Cancelar</Button>
<Button onClick={handleImportarLaboratorio} disabled={importResultados.length === 0 && !importObservaciones && !importAcidoBase}> <Button onClick={handleImportarLaboratorio} disabled={importResultados.length === 0 && !importObservaciones && !importAcidoBase}>
<Save className="h-4 w-4 mr-2" /> <Save className="h-4 w-4 mr-2" />
{(importAcidoBase ? 'Guardar Gasometría' : 'Guardar Laboratorio')} {(importAcidoBase ? 'Guardar' : 'Guardar Laboratorio')}
</Button> </Button>
</div> </div>
</DialogContent> </DialogContent>
@@ -1156,9 +1120,9 @@ for (const linea of lineas) {
<div className="text-center py-8 text-gray-400"><FlaskConical className="h-12 w-12 mx-auto mb-2 opacity-50" /><p>No hay laboratorios</p></div> <div className="text-center py-8 text-gray-400"><FlaskConical className="h-12 w-12 mx-auto mb-2 opacity-50" /><p>No hay laboratorios</p></div>
) : ( ) : (
<div className="relative w-full overflow-auto grid grid-cols-1"> <div className="relative w-full overflow-auto grid grid-cols-1">
<Table> <Table>
<TableHeader> <TableHeader>
<TableRow> <TableRow>
<TableHead className="cursor-pointer hover:bg-muted" onClick={() => setLabSortAsc(!labSortAsc)}> <TableHead className="cursor-pointer hover:bg-muted" onClick={() => setLabSortAsc(!labSortAsc)}>
Fecha {labSortAsc ? '↑' : '↓'} Fecha {labSortAsc ? '↑' : '↓'}
@@ -1231,8 +1195,8 @@ for (const linea of lineas) {
))} ))}
</TableBody> </TableBody>
</Table> </Table>
</div> </div>
)} )}
</div> </div>
); );
@@ -1567,8 +1531,8 @@ function SeccionAcidosBase({ ab, patientId, add, update, del }: {
<div className="flex items-start justify-between"> <div className="flex items-start justify-between">
<div><p className="font-medium">{a.fecha} {a.hora}</p></div> <div><p className="font-medium">{a.fecha} {a.hora}</p></div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Badge variant="outline" className="text-xs">{a.fio2 && a.po2 &&<span className="mr-1">PaFiO2: {Math.round(a.po2 / a.fio2 * 100) / 100}</span>}</Badge> <Badge variant="outline" className="text-xs">{a.fio2 && a.po2 && <span className="mr-1">PaFiO2: {Math.round(a.po2 / a.fio2 * 100) / 100}</span>}</Badge>
<Badge variant="outline" className="text-xs">{a.fio2 && <span className="mr-1">FiO:{a.fio2}</span>}</Badge> <Badge variant="outline" className="text-xs">{a.fio2 && <span className="mr-1">FiO:{a.fio2}</span>}</Badge>
<Badge className={getColorPh(a.ph)}>pH: {a.ph}</Badge> <Badge className={getColorPh(a.ph)}>pH: {a.ph}</Badge>
<Button size="sm" variant="ghost" className="text-blue-600" onClick={() => loadEdit(a)}><Edit /></Button> <Button size="sm" variant="ghost" className="text-blue-600" onClick={() => loadEdit(a)}><Edit /></Button>
@@ -1583,7 +1547,7 @@ function SeccionAcidosBase({ ab, patientId, add, update, del }: {
<div className="bg-gray-50 p-2 rounded text-center"><p className="text-xs text-gray-500">BE</p><p className="font-bold">{a.be}</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">{a.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">{a.sato2}%</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">{a.sato2}%</p></div>
{a.lactato && <div className="bg-gray-50 p-2 rounded text-center"><p className="text-xs text-gray-500">Lactato</p><p className="font-bold">{a.lactato}</p></div>} {a.lactato && <div className="bg-gray-50 p-2 rounded text-center"><p className="text-xs text-gray-500">Lactato</p><p className="font-bold">{a.lactato}</p></div>}
{a.fio2 && <div className="bg-gray-50 p-2 rounded text-center"><p className="text-xs text-gray-500">FiO2</p><p className="font-bold">{a.fio2}</p></div>} {a.fio2 && <div className="bg-gray-50 p-2 rounded text-center"><p className="text-xs text-gray-500">FiO2</p><p className="font-bold">{a.fio2}</p></div>}
</div> </div>
{a.interpretacion && <div className="bg-teal-50 p-3 rounded-lg border border-teal-200"><p className="text-sm font-medium text-teal-800">Interpretación: {a.interpretacion}</p></div>} {a.interpretacion && <div className="bg-teal-50 p-3 rounded-lg border border-teal-200"><p className="text-sm font-medium text-teal-800">Interpretación: {a.interpretacion}</p></div>}
@@ -1626,7 +1590,7 @@ function SeccionCultivos({ cults, patient, add, update, del }: {
setSelected(null); setSelected(null);
}; };
const resetRes = () => { const resetRes = () => {
setFechaResultado(new Date().toISOString().split('T')[0]); setFechaResultado(new Date().toISOString().split('T')[0]);
setEstadoResultado('Positivo'); setEstadoResultado('Positivo');
setGermen(''); setGermen('');
@@ -1798,73 +1762,73 @@ const resetRes = () => {
<div> <div>
<div className="grid grid-cols-1 gap-4"> <div className="grid grid-cols-1 gap-4">
{cs.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</p></div> : {cs.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</p></div> :
cs.map(c => ( cs.map(c => (
<Card key={c.id} className="hover:shadow-md transition-shadow"><CardContent className="p-4"> <Card key={c.id} className="hover:shadow-md transition-shadow"><CardContent className="p-4">
<div className="flex flex-col gap-3"> <div className="flex flex-col gap-3">
<div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4"> <div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<div className={`h-10 w-10 rounded-full flex items-center justify-center flex-shrink-0 ${c.estado === 'NAF/Pendiente' ? 'bg-amber-100' : c.estado === 'Parcial' ? 'bg-orange-100' : c.estado === 'Positivo' ? 'bg-red-100' : 'bg-green-100'}`}> <div className={`h-10 w-10 rounded-full flex items-center justify-center flex-shrink-0 ${c.estado === 'NAF/Pendiente' ? 'bg-amber-100' : c.estado === 'Parcial' ? 'bg-orange-100' : c.estado === 'Positivo' ? 'bg-red-100' : 'bg-green-100'}`}>
<Microscope className={`h-5 w-5 ${c.estado === 'NAF/Pendiente' ? 'text-amber-600' : c.estado === 'Parcial' ? 'text-orange-600' : c.estado === 'Positivo' ? 'text-red-600' : 'text-green-600'}`} /> <Microscope className={`h-5 w-5 ${c.estado === 'NAF/Pendiente' ? 'text-amber-600' : c.estado === 'Parcial' ? 'text-orange-600' : c.estado === 'Positivo' ? 'text-red-600' : 'text-green-600'}`} />
</div> </div>
<div> <div>
<p className="font-medium">{c.fechaToma}</p> <p className="font-medium">{c.fechaToma}</p>
<div className="flex items-center gap-2 text-sm text-gray-500"> <div className="flex items-center gap-2 text-sm text-gray-500">
<Badge variant="outline">{c.tipoMuestra}</Badge> <Badge variant="outline">{c.tipoMuestra}</Badge>
<Badge className={getEstadoColor(c.estado)}>{getEstadoLabel(c.estado)}</Badge> <Badge className={getEstadoColor(c.estado)}>{getEstadoLabel(c.estado)}</Badge>
</div>
</div>
</div>
<div className="flex flex-wrap items-center gap-2">
{c.estado === 'NAF/Pendiente' && (
<>
<Button size="sm" variant="outline" onClick={() => openParcial(c)}><AlertCircle className="h-4 w-4 mr-1" />Parcial</Button>
<Button size="sm" variant="outline" onClick={() => { openDefinitivo(c); setIsParcialMode(false); }}><CheckCircle2 className="h-4 w-4 mr-1" />Definitivo</Button>
</>
)}
{c.estado === 'Parcial' && (
<>
<Button size="sm" variant="outline" onClick={() => openParcial(c)}><Pencil className="h-4 w-4 mr-1" />Editar Parcial</Button>
<Button size="sm" variant="outline" onClick={() => openDefinitivo(c)}><CheckCircle2 className="h-4 w-4 mr-1" />Definitivo</Button>
</>
)}
{(c.estado === 'Positivo' || c.estado === 'Negativo') && <Button size="sm" variant="outline" onClick={() => openDefinitivo(c)}><Pencil className="h-4 w-4" /></Button>}
<Button size="sm" variant="outline" className="text-red-600" onClick={() => del(c.id)}><Trash2 /></Button>
</div> </div>
</div> </div>
</div> {c.protocolo && <p className="text-xs text-gray-500">Protocolo: {c.protocolo}</p>}
<div className="flex flex-wrap items-center gap-2"> {c.observaciones && <p className="text-sm text-gray-600 bg-gray-50 p-2 rounded">{c.observaciones}</p>}
{c.estado === 'NAF/Pendiente' && ( {c.estado === 'Parcial' && c.germen && (
<> <div className="bg-orange-50 p-3 rounded-lg border border-orange-200">
<Button size="sm" variant="outline" onClick={() => openParcial(c)}><AlertCircle className="h-4 w-4 mr-1" />Parcial</Button> <p className="text-sm font-medium text-orange-800 flex items-center gap-2"><AlertCircle className="h-4 w-4" />PARCIAL - Germen: {c.germen}</p>
<Button size="sm" variant="outline" onClick={() => { openDefinitivo(c); setIsParcialMode(false); }}><CheckCircle2 className="h-4 w-4 mr-1" />Definitivo</Button> {(c.sensible || c.resistente) && (
</> <div className="mt-2 space-y-1">
{c.sensible && <p className="text-xs text-orange-700">Sensible: {c.sensible}</p>}
{c.resistente && <p className="text-xs text-orange-700">Resistente: {c.resistente}</p>}
</div>
)}
</div>
)} )}
{c.estado === 'Parcial' && ( {c.estado === 'Positivo' && c.germen && (
<> <div className="bg-red-50 p-3 rounded-lg border border-red-200">
<Button size="sm" variant="outline" onClick={() => openParcial(c)}><Pencil className="h-4 w-4 mr-1" />Editar Parcial</Button> <p className="text-sm font-medium text-red-800 flex items-center gap-2"><AlertCircle className="h-4 w-4" />Germen: {c.germen}</p>
<Button size="sm" variant="outline" onClick={() => openDefinitivo(c)}><CheckCircle2 className="h-4 w-4 mr-1" />Definitivo</Button> {c.fechaResultado && <p className="text-xs text-red-600 mt-1">Resultado: {c.fechaResultado}</p>}
</> {(c.sensible || c.resistente) && (
<div className="mt-2 space-y-2">
{c.sensible && <div><p className="text-xs font-medium text-green-700 mb-1">Sensible a:</p><p className="text-sm text-green-800">{c.sensible}</p></div>}
{c.resistente && <div><p className="text-xs font-medium text-red-700 mb-1">Resistente a:</p><p className="text-sm text-red-800">{c.resistente}</p></div>}
</div>
)}
</div>
)} )}
{(c.estado === 'Positivo' || c.estado === 'Negativo') && <Button size="sm" variant="outline" onClick={() => openDefinitivo(c)}><Pencil className="h-4 w-4" /></Button>} {c.estado === 'Negativo' && (
<Button size="sm" variant="outline" className="text-red-600" onClick={() => del(c.id)}><Trash2 /></Button> <div className="bg-green-50 dark:bg-green-900/30 p-3 rounded-lg border border-green-200 dark:border-green-700">
</div> <p className="text-sm font-medium text-green-800 flex items-center gap-2"><CheckCircle2 className="h-4 w-4" />Sin crecimiento de microorganismos</p>
</div> {c.fechaResultado && <p className="text-xs text-green-600 mt-1">Resultado: {c.fechaResultado}</p>}
{c.protocolo && <p className="text-xs text-gray-500">Protocolo: {c.protocolo}</p>}
{c.observaciones && <p className="text-sm text-gray-600 bg-gray-50 p-2 rounded">{c.observaciones}</p>}
{c.estado === 'Parcial' && c.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: {c.germen}</p>
{(c.sensible || c.resistente) && (
<div className="mt-2 space-y-1">
{c.sensible && <p className="text-xs text-orange-700">Sensible: {c.sensible}</p>}
{c.resistente && <p className="text-xs text-orange-700">Resistente: {c.resistente}</p>}
</div> </div>
)} )}
</div> </div>
)} </CardContent></Card>
{c.estado === 'Positivo' && c.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: {c.germen}</p>
{c.fechaResultado && <p className="text-xs text-red-600 mt-1">Resultado: {c.fechaResultado}</p>}
{(c.sensible || c.resistente) && (
<div className="mt-2 space-y-2">
{c.sensible && <div><p className="text-xs font-medium text-green-700 mb-1">Sensible a:</p><p className="text-sm text-green-800">{c.sensible}</p></div>}
{c.resistente && <div><p className="text-xs font-medium text-red-700 mb-1">Resistente a:</p><p className="text-sm text-red-800">{c.resistente}</p></div>}
</div>
)}
</div>
)}
{c.estado === 'Negativo' && (
<div className="bg-green-50 dark:bg-green-900/30 p-3 rounded-lg border border-green-200 dark:border-green-700">
<p className="text-sm font-medium text-green-800 flex items-center gap-2"><CheckCircle2 className="h-4 w-4" />Sin crecimiento de microorganismos</p>
{c.fechaResultado && <p className="text-xs text-green-600 mt-1">Resultado: {c.fechaResultado}</p>}
</div>
)}
</div>
</CardContent></Card>
))}
</div> </div>
</div> </div>
</div> </div>
@@ -1884,7 +1848,7 @@ function SeccionEstudiosComplementarios({ estudios, internacionId, pacienteId, a
const [tipo, setTipo] = useState(''); const [tipo, setTipo] = useState('');
const [resultado, setResultado] = useState(''); const [resultado, setResultado] = useState('');
const estudiosFiltrados = filtro === 'internacion' const estudiosFiltrados = filtro === 'internacion'
? estudios.filter(e => e.internacionId === internacionId) ? estudios.filter(e => e.internacionId === internacionId)
: estudios; : estudios;
@@ -1939,15 +1903,15 @@ function SeccionEstudiosComplementarios({ estudios, internacionId, pacienteId, a
</div> </div>
<div> <div>
<Label>Tipo de Estudio</Label> <Label>Tipo de Estudio</Label>
<Input <Input
value={tipo} value={tipo}
onChange={e => setTipo(e.target.value)} onChange={e => setTipo(e.target.value)}
placeholder="Ej: Radiografía de tórax, ECG, Tomografía, etc." placeholder="Ej: Radiografía de tórax, ECG, Tomografía, etc."
/> />
</div> </div>
<div> <div>
<Label>Resultado</Label> <Label>Resultado</Label>
<textarea <textarea
className="w-full p-2 border rounded-md text-sm min-h-[100px]" className="w-full p-2 border rounded-md text-sm min-h-[100px]"
value={resultado} value={resultado}
onChange={e => setResultado(e.target.value)} onChange={e => setResultado(e.target.value)}
+37 -38
View File
@@ -19,10 +19,10 @@ interface InternacionesProps {
cultivos?: Cultivo[]; cultivos?: Cultivo[];
areas: Area[]; areas: Area[];
onIniciarInternacion: (internacion: Omit<Internacion, 'id' | 'activa'>) => void; onIniciarInternacion: (internacion: Omit<Internacion, 'id' | 'activa'>) => void;
onFinalizarInternacion: (internacionId: string, datos: { onFinalizarInternacion: (internacionId: string, datos: {
fechaEgreso: string; fechaEgreso: string;
diagnosticoEgreso: string; diagnosticoEgreso: string;
motivoEgreso: Internacion['motivoEgreso'] motivoEgreso: Internacion['motivoEgreso']
}) => void; }) => void;
getPacienteById: (id: string) => Paciente | undefined; getPacienteById: (id: string) => Paciente | undefined;
getCamaById: (id: string) => Cama | undefined; getCamaById: (id: string) => Cama | undefined;
@@ -30,11 +30,11 @@ interface InternacionesProps {
onNuevoIngreso?: () => void; onNuevoIngreso?: () => void;
} }
export function Internaciones({ export function Internaciones({
internaciones, internaciones,
pacientes, pacientes,
camas, camas,
onIniciarInternacion, onIniciarInternacion,
onFinalizarInternacion, onFinalizarInternacion,
getPacienteById, getPacienteById,
getCamaById, getCamaById,
@@ -54,7 +54,7 @@ export function Internaciones({
const [motivoConsulta, setMotivoConsulta] = useState(''); const [motivoConsulta, setMotivoConsulta] = useState('');
const [antecedentesEnfermedadActual, setAntecedentesEnfermedadActual] = useState(''); const [antecedentesEnfermedadActual, setAntecedentesEnfermedadActual] = useState('');
const [medicoIngresante, setMedicoIngresante] = useState(''); const [medicoIngresante, setMedicoIngresante] = useState('');
// Formulario nueva internación // Formulario nueva internación
const [fechaEgreso, setFechaEgreso] = useState(''); const [fechaEgreso, setFechaEgreso] = useState('');
const [diagnosticoEgreso, setDiagnosticoEgreso] = useState(''); const [diagnosticoEgreso, setDiagnosticoEgreso] = useState('');
@@ -106,17 +106,17 @@ export function Internaciones({
const internacionesFiltradas = internaciones.filter(i => { const internacionesFiltradas = internaciones.filter(i => {
const paciente = getPacienteById(i.pacienteId); const paciente = getPacienteById(i.pacienteId);
const cumpleBusqueda = !busqueda || const cumpleBusqueda = !busqueda ||
(paciente && ( (paciente && (
paciente.nombre.toLowerCase().includes(busqueda.toLowerCase()) || paciente.nombre.toLowerCase().includes(busqueda.toLowerCase()) ||
paciente.apellido.toLowerCase().includes(busqueda.toLowerCase()) || paciente.apellido.toLowerCase().includes(busqueda.toLowerCase()) ||
paciente.dni.includes(busqueda) paciente.dni.includes(busqueda)
)); ));
const cumpleEstado = filtroEstado === 'todas' || const cumpleEstado = filtroEstado === 'todas' ||
(filtroEstado === 'activas' && i.activa) || (filtroEstado === 'activas' && i.activa) ||
(filtroEstado === 'finalizadas' && !i.activa); (filtroEstado === 'finalizadas' && !i.activa);
return cumpleBusqueda && cumpleEstado; return cumpleBusqueda && cumpleEstado;
}).sort((a, b) => new Date(b.fechaIngresoClinica || '').getTime() - new Date(a.fechaIngresoClinica || '').getTime()); }).sort((a, b) => new Date(b.fechaIngresoClinica || '').getTime() - new Date(a.fechaIngresoClinica || '').getTime());
@@ -251,18 +251,18 @@ export function Internaciones({
</div> </div>
<div> <div>
<Label>Médico Ingresante *</Label> <Label>Médico Ingresante *</Label>
<Input <Input
value={medicoIngresante} value={medicoIngresante}
onChange={(e) => setMedicoIngresante(e.target.value)} onChange={(e) => setMedicoIngresante(e.target.value)}
placeholder="Nombre del médico ingresante" placeholder="Nombre del médico ingresante"
/> />
</div> </div>
<Button variant="outline" <Button variant="outline"
className="w-full" className="w-full"
onClick={handleIniciarInternacion} onClick={handleIniciarInternacion}
disabled={!pacienteSeleccionado || !camaSeleccionada || !motivoConsulta || !enfermedadActual || !medicoIngresante} disabled={!pacienteSeleccionado || !camaSeleccionada || !motivoConsulta || !enfermedadActual || !medicoIngresante}
> >
<Plus className="h-4 w-4 mr-2" /> <Plus className="h-4 w-4 mr-2" />
Iniciar Internación Iniciar Internación
</Button> </Button>
</div> </div>
@@ -304,15 +304,14 @@ export function Internaciones({
{internacionesFiltradas.map((internacion) => { {internacionesFiltradas.map((internacion) => {
const paciente = getPacienteById(internacion.pacienteId); const paciente = getPacienteById(internacion.pacienteId);
const cama = getCamaById(internacion.camaId); const cama = getCamaById(internacion.camaId);
return ( return (
<Card key={internacion.id} className="hover:shadow-md transition-shadow"> <Card key={internacion.id} className="hover:shadow-md transition-shadow">
<CardContent className="p-4 dark:bg-gray-800"> <CardContent className="p-4 dark:bg-gray-800">
<div className="flex flex-col lg:flex-row lg:items-start lg:justify-between gap-4"> <div className="flex flex-col lg:flex-row lg:items-start lg:justify-between gap-4">
<div className="flex items-start gap-4"> <div className="flex items-start gap-4">
<div className={`h-12 w-12 rounded-full flex items-center justify-center flex-shrink-0 ${ <div className={`h-12 w-12 rounded-full flex items-center justify-center flex-shrink-0 ${internacion.activa ? 'bg-purple-100' : 'bg-gray-100'
internacion.activa ? 'bg-purple-100' : 'bg-gray-100' }`}>
}`}>
{internacion.activa ? ( {internacion.activa ? (
<ClipboardList className="h-6 w-6 text-purple-600" /> <ClipboardList className="h-6 w-6 text-purple-600" />
) : ( ) : (
@@ -371,8 +370,8 @@ export function Internaciones({
{internacion.activa && ( {internacion.activa && (
<Dialog open={dialogoEgresoAbierto && internacionSeleccionada?.id === internacion.id} onOpenChange={setDialogoEgresoAbierto}> <Dialog open={dialogoEgresoAbierto && internacionSeleccionada?.id === internacion.id} onOpenChange={setDialogoEgresoAbierto}>
<DialogTrigger asChild> <DialogTrigger asChild>
<Button <Button
variant="outline" variant="outline"
className="whitespace-nowrap" className="whitespace-nowrap"
onClick={() => abrirDialogoEgreso(internacion)} onClick={() => abrirDialogoEgreso(internacion)}
> >
@@ -387,14 +386,14 @@ export function Internaciones({
<div className="space-y-4"> <div className="space-y-4">
<div> <div>
<Label>Paciente</Label> <Label>Paciente</Label>
<Input <Input
value={paciente ? `${paciente.apellido}, ${paciente.nombre}` : ''} value={paciente ? `${paciente.apellido}, ${paciente.nombre}` : ''}
disabled disabled
/> />
</div> </div>
<div> <div>
<Label>Fecha de Egreso *</Label> <Label>Fecha de Egreso *</Label>
<Input <Input
type="date" type="date"
value={fechaEgreso} value={fechaEgreso}
onChange={(e) => setFechaEgreso(e.target.value)} onChange={(e) => setFechaEgreso(e.target.value)}
@@ -425,13 +424,13 @@ export function Internaciones({
/> />
</div> </div>
<Button variant="outline" <Button variant="outline"
className="w-full" className="w-full"
onClick={handleFinalizarInternacion} onClick={handleFinalizarInternacion}
disabled={!fechaEgreso || !diagnosticoEgreso || !motivoEgreso} disabled={!fechaEgreso || !diagnosticoEgreso || !motivoEgreso}
> >
<CheckCircle2 className="h-4 w-4 mr-2" /> <CheckCircle2 className="h-4 w-4 mr-2" />
Confirmar Egreso Confirmar Egreso
</Button> </Button>
</div> </div>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
@@ -450,8 +449,8 @@ export function Internaciones({
<div className="text-center py-12 text-gray-400"> <div className="text-center py-12 text-gray-400">
<ClipboardList className="h-16 w-16 mx-auto mb-4 opacity-50" /> <ClipboardList className="h-16 w-16 mx-auto mb-4 opacity-50" />
<p className="text-lg"> <p className="text-lg">
{busqueda || filtroEstado !== 'todas' {busqueda || filtroEstado !== 'todas'
? 'No se encontraron internaciones con esos filtros' ? 'No se encontraron internaciones con esos filtros'
: 'No hay internaciones registradas'} : 'No hay internaciones registradas'}
</p> </p>
</div> </div>
+50 -50
View File
@@ -26,12 +26,12 @@ interface MapaCamasProps {
getInternacionById: (id: string) => Internacion | undefined; getInternacionById: (id: string) => Internacion | undefined;
} }
export function MapaCamas({ export function MapaCamas({
camas, camas,
areas, areas,
pacientes, pacientes,
internaciones, internaciones,
onActualizarCama, onActualizarCama,
onAgregarCama, onAgregarCama,
onEliminarCama, onEliminarCama,
onIniciarInternacion, onIniciarInternacion,
@@ -117,7 +117,7 @@ export function MapaCamas({
const getOrden = (sala: number) => { const getOrden = (sala: number) => {
const grupo = Math.floor(sala / 100); const grupo = Math.floor(sala / 100);
const esPar = sala % 2 === 0; const esPar = sala % 2 === 0;
if (grupo === 2) { if (grupo === 2) {
if (esPar) return { grupo: 2, suborden: 0, sala }; // 2XX pares, menor a mayor if (esPar) return { grupo: 2, suborden: 0, sala }; // 2XX pares, menor a mayor
return { grupo: 1, suborden: 1, sala }; // 2XX impares, mayor a menor return { grupo: 1, suborden: 1, sala }; // 2XX impares, mayor a menor
@@ -173,7 +173,7 @@ export function MapaCamas({
return !internacionActiva; return !internacionActiva;
}); });
return ( return (
<div className="space-y-6 dark:text-white"> <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 className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div> <div>
@@ -187,25 +187,25 @@ return (
<Badge variant="outline" className="bg-red-50 text-red-700"> <Badge variant="outline" className="bg-red-50 text-red-700">
{camas.filter(c => c.estado === 'Ocupada').length} Ocupadas {camas.filter(c => c.estado === 'Ocupada').length} Ocupadas
</Badge> </Badge>
<div className="ml-4 flex items-center gap-2 flex-wrap sm:flex-nowrap"> <div className="ml-4 flex items-center gap-2 flex-wrap sm:flex-nowrap">
<Button variant="outline" onClick={() => { <Button variant="outline" onClick={() => {
setEditingAreaId(null); setEditingAreaId(null);
setAreaNombre(''); setAreaNombre('');
setAreaDialogOpen(true); setAreaDialogOpen(true);
}} className="text-xs px-2 py-1 sm:text-sm sm:px-4 sm:py-2"> }} className="text-xs px-2 py-1 sm:text-sm sm:px-4 sm:py-2">
Administrar Áreas Administrar Áreas
</Button> </Button>
<Button variant="outline" onClick={() => { <Button variant="outline" onClick={() => {
setEditingBed(null); setEditingBed(null);
setBedNumero(''); setBedNumero('');
setBedTipo('General'); setBedTipo('General');
setBedAreaId(areas?.[0]?.id); setBedAreaId(areas?.[0]?.id);
setBedDialogOpen(true); setBedDialogOpen(true);
}} className="text-xs px-2 py-1 sm:text-sm sm:px-4 sm:py-2"> }} 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" /> <Plus className="h-3 w-3 sm:h-4 sm:w-4 sm:mr-1" />
<span className="hidden sm:inline">Agregar Cama</span> <span className="hidden sm:inline">Agregar Cama</span>
</Button> </Button>
</div> </div>
</div> </div>
</div> </div>
@@ -265,11 +265,11 @@ return (
{sortedCamas.map((cama) => { {sortedCamas.map((cama) => {
const paciente = cama.pacienteId ? getPacienteById(cama.pacienteId) : null; const paciente = cama.pacienteId ? getPacienteById(cama.pacienteId) : null;
const internacion = cama.internacionId ? getInternacionById(cama.internacionId) : null; const internacion = cama.internacionId ? getInternacionById(cama.internacionId) : null;
return ( return (
<Dialog key={cama.id}> <Dialog key={cama.id}>
<DialogTrigger asChild> <DialogTrigger asChild>
<Card <Card
className={`cursor-pointer hover:shadow-md transition-shadow border-2 w-full ${getEstadoColor(cama)}`} className={`cursor-pointer hover:shadow-md transition-shadow border-2 w-full ${getEstadoColor(cama)}`}
onClick={() => setCamaSeleccionada(cama)} onClick={() => setCamaSeleccionada(cama)}
> >
@@ -291,12 +291,12 @@ return (
</div> </div>
)} )}
</CardContent> </CardContent>
</Card> </Card>
</DialogTrigger> </DialogTrigger>
<DialogContent className="sm:max-w-md"> <DialogContent className="sm:max-w-md">
<DialogHeader> <DialogHeader>
<DialogTitle className="flex items-center gap-2"> <DialogTitle className="flex items-center gap-2">
<Bed className="h-5 w-5" /> <Bed className="h-5 w-5" />
Cama {cama.numero} - {cama.areaId ? areaById[cama.areaId] ?? 'Área desconocida' : 'Sin área'} Cama {cama.numero} - {cama.areaId ? areaById[cama.areaId] ?? 'Área desconocida' : 'Sin área'}
@@ -309,7 +309,7 @@ return (
</Badge> </Badge>
<Badge variant="outline">{cama.tipo}</Badge> <Badge variant="outline">{cama.tipo}</Badge>
</div> </div>
{cama.estado === 'Ocupada' && paciente && internacion && ( {cama.estado === 'Ocupada' && paciente && internacion && (
<div className="bg-gray-50 p-4 rounded-lg space-y-2"> <div className="bg-gray-50 p-4 rounded-lg space-y-2">
<p className="font-medium">Paciente:</p> <p className="font-medium">Paciente:</p>
@@ -328,7 +328,7 @@ return (
<Dialog open={dialogoAbierto} onOpenChange={setDialogoAbierto}> <Dialog open={dialogoAbierto} onOpenChange={setDialogoAbierto}>
<DialogTrigger asChild> <DialogTrigger asChild>
<Button variant="outline" <Button variant="outline"
className="w-full" className="w-full"
onClick={() => { onClick={() => {
setCamaSeleccionada(cama); setCamaSeleccionada(cama);
setDialogoAbierto(true); setDialogoAbierto(true);
@@ -398,22 +398,22 @@ return (
placeholder="Nombre del médico..." placeholder="Nombre del médico..."
/> />
</div> </div>
<Button variant="outline" <Button variant="outline"
className="w-full" className="w-full"
onClick={handleOcuparCama} onClick={handleOcuparCama}
disabled={!pacienteSeleccionado || !diagnostico || !enfermedadActual || !medico} disabled={!pacienteSeleccionado || !diagnostico || !enfermedadActual || !medico}
> >
<Plus className="h-4 w-4 mr-1" /> <Plus className="h-4 w-4 mr-1" />
Iniciar Internación Iniciar Internación
</Button> </Button>
</div> </div>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
)} )}
{cama.estado !== 'Disponible' && ( {cama.estado !== 'Disponible' && (
<Button <Button
variant="outline" variant="outline"
className="w-full" className="w-full"
onClick={() => handleCambiarEstado(cama, 'Disponible')} onClick={() => handleCambiarEstado(cama, 'Disponible')}
> >
@@ -421,10 +421,10 @@ return (
Disponible Disponible
</Button> </Button>
)} )}
{cama.estado !== 'Reparacion' && ( {cama.estado !== 'Reparacion' && (
<Button <Button
variant="outline" variant="outline"
className="w-full" className="w-full"
onClick={() => handleCambiarEstado(cama, 'Reparacion')} onClick={() => handleCambiarEstado(cama, 'Reparacion')}
> >
@@ -432,10 +432,10 @@ return (
Reparacion Reparacion
</Button> </Button>
)} )}
{cama.estado !== 'Reservada' && ( {cama.estado !== 'Reservada' && (
<Button <Button
variant="outline" variant="outline"
className="w-full" className="w-full"
onClick={() => handleCambiarEstado(cama, 'Reservada')} onClick={() => handleCambiarEstado(cama, 'Reservada')}
> >
@@ -444,7 +444,7 @@ return (
</Button> </Button>
)} )}
<Button variant="outline" onClick={() => { <Button variant="outline" onClick={() => {
setEditingBed(cama); setEditingBed(cama);
setBedNumero(cama.numero); setBedNumero(cama.numero);
@@ -462,9 +462,9 @@ return (
<Trash className="h-4 w-4 mr-1" />Eliminar <Trash className="h-4 w-4 mr-1" />Eliminar
</Button> </Button>
</div> </div>
</div>
</div> </div>
</div>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
); );
+33 -33
View File
@@ -18,17 +18,17 @@ interface PacientesProps {
onEliminar: (id: string) => void; onEliminar: (id: string) => void;
} }
export function Pacientes({ export function Pacientes({
pacientes, pacientes,
internaciones, internaciones,
onAgregar, onAgregar,
onActualizar, onActualizar,
onEliminar onEliminar
}: PacientesProps) { }: PacientesProps) {
const [busqueda, setBusqueda] = useState(''); const [busqueda, setBusqueda] = useState('');
const [dialogoAbierto, setDialogoAbierto] = useState(false); const [dialogoAbierto, setDialogoAbierto] = useState(false);
const [pacienteEditando, setPacienteEditando] = useState<Paciente | null>(null); const [pacienteEditando, setPacienteEditando] = useState<Paciente | null>(null);
// Formulario // Formulario
const [nombre, setNombre] = useState(''); const [nombre, setNombre] = useState('');
const [apellido, setApellido] = useState(''); const [apellido, setApellido] = useState('');
@@ -116,7 +116,7 @@ export function Pacientes({
setDialogoAbierto(false); setDialogoAbierto(false);
}; };
const pacientesFiltrados = pacientes.filter(p => const pacientesFiltrados = pacientes.filter(p =>
p.nombre.toLowerCase().includes(busqueda.toLowerCase()) || p.nombre.toLowerCase().includes(busqueda.toLowerCase()) ||
p.apellido.toLowerCase().includes(busqueda.toLowerCase()) || p.apellido.toLowerCase().includes(busqueda.toLowerCase()) ||
p.dni.includes(busqueda) p.dni.includes(busqueda)
@@ -162,33 +162,33 @@ export function Pacientes({
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4"> <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div> <div>
<Label>Nombre *</Label> <Label>Nombre *</Label>
<Input <Input
value={nombre} value={nombre}
onChange={(e) => setNombre(e.target.value)} onChange={(e) => setNombre(e.target.value)}
placeholder="Nombre del paciente" placeholder="Nombre del paciente"
/> />
</div> </div>
<div> <div>
<Label>Apellido *</Label> <Label>Apellido *</Label>
<Input <Input
value={apellido} value={apellido}
onChange={(e) => setApellido(e.target.value)} onChange={(e) => setApellido(e.target.value)}
placeholder="Apellido del paciente" placeholder="Apellido del paciente"
/> />
</div> </div>
<div> <div>
<Label>DNI *</Label> <Label>DNI *</Label>
<Input <Input
value={dni} value={dni}
onChange={(e) => setDni(e.target.value)} onChange={(e) => setDni(e.target.value)}
placeholder="Número de DNI" placeholder="Número de DNI"
/> />
</div> </div>
<div> <div>
<Label>Fecha de Nacimiento *</Label> <Label>Fecha de Nacimiento *</Label>
<Input <Input
type="date" type="date"
value={fechaNacimiento} value={fechaNacimiento}
onChange={(e) => setFechaNacimiento(e.target.value)} onChange={(e) => setFechaNacimiento(e.target.value)}
/> />
</div> </div>
@@ -215,24 +215,24 @@ export function Pacientes({
</div> </div>
<div> <div>
<Label>Obra Social</Label> <Label>Obra Social</Label>
<Input <Input
value={obraSocial} value={obraSocial}
onChange={(e) => setObraSocial(e.target.value)} onChange={(e) => setObraSocial(e.target.value)}
placeholder="Obra social del paciente" placeholder="Obra social del paciente"
/> />
</div> </div>
<div> <div>
<Label>Nacionalidad</Label> <Label>Nacionalidad</Label>
<Input <Input
value={nacionalidad} value={nacionalidad}
onChange={(e) => setNacionalidad(e.target.value)} onChange={(e) => setNacionalidad(e.target.value)}
placeholder="Nacionalidad del paciente" placeholder="Nacionalidad del paciente"
/> />
</div> </div>
<div> <div>
<Label>Dirección</Label> <Label>Dirección</Label>
<Input <Input
value={direccion} value={direccion}
onChange={(e) => setDireccion(e.target.value)} onChange={(e) => setDireccion(e.target.value)}
placeholder="Dirección del paciente" placeholder="Dirección del paciente"
/> />
@@ -257,8 +257,8 @@ export function Pacientes({
</div> </div>
<div className="sm:col-span-2"> <div className="sm:col-span-2">
<Label>Teléfono Contacto</Label> <Label>Teléfono Contacto</Label>
<Input <Input
value={telefono} value={telefono}
onChange={(e) => setTelefono(e.target.value)} onChange={(e) => setTelefono(e.target.value)}
placeholder="Teléfono de contacto" placeholder="Teléfono de contacto"
/> />
@@ -300,12 +300,12 @@ export function Pacientes({
Cancelar Cancelar
</Button> </Button>
<Button variant="outline" <Button variant="outline"
onClick={handleGuardar} onClick={handleGuardar}
disabled={!nombre || !apellido || !dni || !fechaNacimiento} disabled={!nombre || !apellido || !dni || !fechaNacimiento}
> >
<Save className="h-4 w-4 mr-2" /> <Save className="h-4 w-4 mr-2" />
{pacienteEditando ? 'Guardar Cambios' : 'Crear Paciente'} {pacienteEditando ? 'Guardar Cambios' : 'Crear Paciente'}
</Button> </Button>
</div> </div>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
@@ -330,7 +330,7 @@ export function Pacientes({
<div className="grid grid-cols-1 gap-4"> <div className="grid grid-cols-1 gap-4">
{pacientesFiltrados.map((paciente) => ( {pacientesFiltrados.map((paciente) => (
<Card key={paciente.id} className="hover:shadow-md transition-shadow"> <Card key={paciente.id} className="hover:shadow-md transition-shadow">
<CardContent className="p-4 dark:bg-gray-800"> <CardContent className="p-4 dark:bg-gray-800">
<div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-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="flex items-start gap-4">
<div className="h-12 w-12 bg-blue-100 rounded-full flex items-center justify-center flex-shrink-0"> <div className="h-12 w-12 bg-blue-100 rounded-full flex items-center justify-center flex-shrink-0">
@@ -395,8 +395,8 @@ export function Pacientes({
</div> </div>
</div> </div>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Button <Button
variant="outline" variant="outline"
size="sm" size="sm"
onClick={() => handleEditar(paciente)} onClick={() => handleEditar(paciente)}
> >
@@ -418,7 +418,7 @@ export function Pacientes({
</AlertDialogHeader> </AlertDialogHeader>
<AlertDialogFooter> <AlertDialogFooter>
<AlertDialogCancel>Cancelar</AlertDialogCancel> <AlertDialogCancel>Cancelar</AlertDialogCancel>
<AlertDialogAction <AlertDialogAction
onClick={() => onEliminar(paciente.id)} onClick={() => onEliminar(paciente.id)}
className="bg-red-600 hover:bg-red-700" className="bg-red-600 hover:bg-red-700"
> >