From e996f92d71471fba816f10335cb55f2ad2a7d0d1 Mon Sep 17 00:00:00 2001 From: Sergio Nicolas Lavaise Date: Thu, 23 Apr 2026 23:44:28 -0300 Subject: [PATCH] Fix: actualiza estado de cama en tabla camas al cambiar internacion - Agrega endpoint PUT /api/camas/:id en servidor - Corrige nombre de tabla SQL de cama a camas - Actualiza estado de camas en memoria al cambiar internacion - Agrega retry logic para evitar SQLITE_BUSY - Mejora delay entre actualizaciones de cama --- server/db.js | 23 ++++++++++++++ server/index.js | 21 +++++++++++++ server/server.js | 10 ++++--- src/hooks/useHospitalStore.ts | 56 ++++++++++++++++++++++++----------- 4 files changed, 88 insertions(+), 22 deletions(-) diff --git a/server/db.js b/server/db.js index e2ef807..6ebd05c 100644 --- a/server/db.js +++ b/server/db.js @@ -154,6 +154,29 @@ export async function getAllCamas() { return rows; } +export async function updateCama(id, updates) { + const db = await openDb(); + const fields = []; + const values = []; + if (updates.estado !== undefined) { + fields.push('estado = ?'); + values.push(updates.estado); + } + if (updates.pacienteId !== undefined) { + fields.push('pacienteId = ?'); + values.push(updates.pacienteId); + } + if (updates.internacionId !== undefined) { + fields.push('internacionId = ?'); + values.push(updates.internacionId); + } + if (fields.length > 0) { + values.push(id); + await db.run(`UPDATE camas SET ${fields.join(', ')} WHERE id = ?`, values); + } + await db.close(); +} + export async function getAllInternaciones() { const db = await openDb(); const rows = await db.all('SELECT * FROM internaciones'); diff --git a/server/index.js b/server/index.js index 2af24e3..f25b38d 100644 --- a/server/index.js +++ b/server/index.js @@ -342,6 +342,27 @@ app.delete('/api/usuarios/:id', async (req, res) => { } }); +app.put('/api/camas/:id', async (req, res) => { + let retries = 3; + while (retries > 0) { + try { + const { id } = req.params; + const { estado } = req.body; + const db = await openDb(); + await db.run('UPDATE camaS SET estado = ? WHERE id = ?', [estado, id]); + await db.close(); + return res.json({ ok: true }); + } catch (err) { + console.error('Error updating cama (retry', retries, '):', err.message); + retries--; + if (retries === 0) { + return res.status(500).json({ error: err.message }); + } + await new Promise(r => setTimeout(r, 200)); + } + } +}); + // Helper para actualizar por DNI async function updateUsuarioByDni(dni, datos) { const { getUsuarioByDni, updateUsuario } = await import('./db.js'); diff --git a/server/server.js b/server/server.js index dbc9d73..3273eb2 100644 --- a/server/server.js +++ b/server/server.js @@ -41,8 +41,7 @@ db.exec(` grupoSanguineo TEXT ); - CREATE TABLE IF NOT EXISTS areas ( - id TEXT PRIMARY KEY, +CREATE TABLE IF NOT EXISTS areas ( nombre TEXT NOT NULL UNIQUE ); @@ -51,7 +50,9 @@ db.exec(` numero TEXT NOT NULL, areaId TEXT, tipo TEXT DEFAULT 'Estándar', - estado TEXT DEFAULT 'Disponible' + estado TEXT DEFAULT 'Disponible', + pacienteId TEXT, + internacionId TEXT ); CREATE TABLE IF NOT EXISTS internaciones ( @@ -384,12 +385,13 @@ app.put('/api/state', (req, res) => { } } - if (state.camas?.length) { +if (state.camas?.length) { const stmt = db.prepare('INSERT OR IGNORE INTO camas (id, numero, areaId, tipo, estado) VALUES (?, ?, ?, ?, ?)'); for (const c of state.camas) { stmt.run(c.id, c.numero, c.areaId, c.tipo, c.estado); } } + } if (state.internaciones?.length) { const stmt = db.prepare('INSERT OR IGNORE INTO internaciones (id, pacienteId, camaId, areaId, fechaIngresoHospital, fechaIngresoClinica, fechaEgreso, diagnosticoIngreso, motivoConsulta, enfermedadActual, antecedentesEnfermedadActual, diagnosticoEgreso, medicoIngresante, motivoEgreso, activa, apache, derivacion) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'); diff --git a/src/hooks/useHospitalStore.ts b/src/hooks/useHospitalStore.ts index cc1c8a6..facd4d9 100644 --- a/src/hooks/useHospitalStore.ts +++ b/src/hooks/useHospitalStore.ts @@ -275,26 +275,46 @@ const finalizarInternacion = useCallback((internacionId: string, datos: { } const oldCamaId = internacion.camaId; - const newCamaId = datos.camaId; +const newCamaId = datos.camaId; const pacienteId = datos.pacienteId || internacion.pacienteId; - setState(prev => ({ - ...prev, - internaciones: prev.internaciones.map(i => - i.id === internacionId - ? { ...i, ...datos } - : i - ), - cams: prev.camas.map(c => { - if (c.id === newCamaId && newCamaId !== oldCamaId) { - return { ...c, estado: 'Ocupada', pacienteId, internacionId }; - } - if (c.id === oldCamaId && oldCamaId !== newCamaId) { - return { ...c, estado: 'Disponible', pacienteId: undefined, internacionId: undefined }; - } - return c; - }), - })); + setState(prev => { + const result = { + ...prev, + internaciones: prev.internaciones.map(i => + i.id === internacionId + ? { ...i, ...datos } + : i + ), + camas: prev.camas.map(c => { + if (c.id === newCamaId && newCamaId !== oldCamaId) { + return { ...c, estado: 'Ocupada' as const, pacienteId, internacionId }; + } + if (c.id === oldCamaId && oldCamaId !== newCamaId) { + return { ...c, estado: 'Disponible' as const, pacienteId: undefined, internacionId: undefined }; + } + return c; + }), + }; + return result; + }); + + if (oldCamaId !== newCamaId && newCamaId && oldCamaId) { + setTimeout(() => { + fetch(`${API_BASE}/camas/${newCamaId}`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ estado: 'Ocupada' }), + }).catch(() => {}); + }, 500); + setTimeout(() => { + fetch(`${API_BASE}/camas/${oldCamaId}`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ estado: 'Disponible' }), + }).catch(() => {}); + }, 1000); + } }, [state.internaciones, state.currentUser]); // Acciones de evoluciones