From 02a71ca8d35820be204a6903d63d0b02224af961 Mon Sep 17 00:00:00 2001 From: nicolasarana <90768149+nicolasarana@users.noreply.github.com> Date: Thu, 22 Jan 2026 14:13:47 -0300 Subject: [PATCH 1/2] feat(MPI):"Cambiar objeto en relaciones por ID" --- core-v2/mpi/paciente/paciente.controller.ts | 38 +++++++++++++-------- core-v2/mpi/paciente/paciente.schema.ts | 14 +++----- 2 files changed, 29 insertions(+), 23 deletions(-) diff --git a/core-v2/mpi/paciente/paciente.controller.ts b/core-v2/mpi/paciente/paciente.controller.ts index 6a75a82e35..5e089ac790 100644 --- a/core-v2/mpi/paciente/paciente.controller.ts +++ b/core-v2/mpi/paciente/paciente.controller.ts @@ -41,6 +41,15 @@ export function set(paciente: IPacienteDoc, body: any) { delete body['documento']; delete body['estado']; } + + if (body.relaciones?.length) { + body.relaciones.forEach(rel => { + if (rel.referencia && typeof rel.referencia === 'object') { + rel.referencia = rel.referencia.id || rel.referencia._id; + } + }); + } + paciente.set(body); if (paciente.foto && !paciente.fotoId) { (paciente as any).fotoId = new Types.ObjectId(); @@ -112,6 +121,10 @@ export async function findById(id: string | String | Types.ObjectId, options = n if (fields) { queryFind.select(fields); } + queryFind.populate({ + path: 'relaciones.referencia', + select: 'nombre apellido documento numeroIdentificacion fechaNacimiento fechaFallecimiento fotoId sexo genero activo' + }); const paciente = await queryFind; EventCore.emitAsync('mpi:pacientes:findById', paciente); return paciente; @@ -218,7 +231,13 @@ export async function multimatch(searchText: string, filter: any, options?: any) }; const skip = parseInt(options.skip || 0, 10); const limit = parseInt(options.limit || 30, 10); - const pacientes = await Paciente.find(query).skip(skip).limit(limit); + const pacientes = await Paciente.find(query) + .skip(skip) + .limit(limit) + .populate({ + path: 'relaciones.referencia', + select: 'nombre apellido documento numeroIdentificacion fechaNacimiento fechaFallecimiento fotoId sexo genero activo' + }); return pacientes; } @@ -413,7 +432,8 @@ export async function agregarHijo(progenitor, hijo, req) { // Familiar ya existe? progenitor.relaciones = progenitor.relaciones || []; const poseeFamiliar = progenitor.relaciones.find(rel => { - return rel.referencia.toString() === hijo._id.toString(); + const refId = rel.referencia?.toString() || rel.referencia?.id?.toString() || rel.referencia?._id?.toString(); + return refId === hijo._id.toString(); }); if (!poseeFamiliar) { @@ -422,12 +442,7 @@ export async function agregarHijo(progenitor, hijo, req) { const progenitorRelacion = { relacion: parentescoProgenitor, referencia: progenitor._id, - nombre: progenitor.nombre, - apellido: progenitor.apellido, - documento: progenitor.documento ? progenitor.documento : null, - numeroIdentificacion: progenitor.numeroIdentificacion ? progenitor.numeroIdentificacion : null, - fotoId: progenitor.fotoId ? progenitor.fotoId : null, - fechaFallecimiento: progenitor.fechaFallecimiento ? progenitor.fechaFallecimiento : null + activo: true }; hijo.relaciones = hijo.relaciones || []; @@ -439,12 +454,7 @@ export async function agregarHijo(progenitor, hijo, req) { const familiarRelacion = { relacion: parentescoHijo, referencia: hijo._id, - nombre: hijo.nombre, - apellido: hijo.apellido, - documento: hijo.documento, - numeroIdentificacion: hijo.numeroIdentificacion ? hijo.numeroIdentificacion : null, - fotoId: hijo.fotoId ? hijo.fotoId : null, - fechaFallecimiento: hijo.fechaFallecimiento ? hijo.fechaFallecimiento : null + activo: true }; progenitor.relaciones.push(familiarRelacion); diff --git a/core-v2/mpi/paciente/paciente.schema.ts b/core-v2/mpi/paciente/paciente.schema.ts index e783b66e1c..bc896a048b 100644 --- a/core-v2/mpi/paciente/paciente.schema.ts +++ b/core-v2/mpi/paciente/paciente.schema.ts @@ -71,7 +71,8 @@ export const PacienteSchema: mongoose.Schema = new mongoose.Schema({ id: mongoose.Schema.Types.ObjectId, nombre: String, apellido: String, - documento: Number }, + documento: Number + }, registradoEn: Date }, estadoCivil: ESTADOCIVIL, @@ -91,19 +92,14 @@ export const PacienteSchema: mongoose.Schema = new mongoose.Schema({ required: false }, // -------------------- + relaciones: [{ relacion: ParentescoSchema, referencia: { type: mongoose.Schema.Types.ObjectId, - ref: 'paciente' + ref: 'paciente_2', + required: true }, - nombre: String, - apellido: String, - documento: String, - fechaNacimiento: Date, - fechaFallecimiento: Date, - numeroIdentificacion: String, - fotoId: mongoose.Schema.Types.ObjectId, activo: Boolean }], financiador: [FinanciadorSchema], From a1c07d074fdf72faada70862188285259957c19c Mon Sep 17 00:00:00 2001 From: nicolasarana <90768149+nicolasarana@users.noreply.github.com> Date: Tue, 3 Mar 2026 15:02:21 -0300 Subject: [PATCH 2/2] =?UTF-8?q?perf(MPI):"Se=20saco=20la=20restricci=C3=B3?= =?UTF-8?q?n=20para=20solucionar=20un=20error"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core-v2/mpi/paciente/paciente.controller.ts | 51 +++++++++++++++++---- core-v2/mpi/paciente/paciente.events.ts | 30 ++++++++---- core-v2/mpi/paciente/paciente.interface.ts | 13 +----- core-v2/mpi/paciente/paciente.schema.ts | 5 +- modules/mobileApp/routes/paciente.ts | 14 +++--- 5 files changed, 74 insertions(+), 39 deletions(-) diff --git a/core-v2/mpi/paciente/paciente.controller.ts b/core-v2/mpi/paciente/paciente.controller.ts index 5e089ac790..f0f73e867d 100644 --- a/core-v2/mpi/paciente/paciente.controller.ts +++ b/core-v2/mpi/paciente/paciente.controller.ts @@ -23,9 +23,39 @@ import { EventCore } from '@andes/event-bus/index'; /** * Crea un objeto paciente */ +function getReferenciaId(ref: any) { + if (!ref) { return null; } + return typeof ref === 'object' ? (ref._id || ref.id) : ref; +} + +/** + * Normaliza el array de relaciones para que siempre tenga solo { relacion, referencia }. + * Limpia campos legacy de pacientes guardados con esquemas viejos. + */ +function normalizeRelaciones(paciente: IPacienteDoc): IPacienteDoc { + if (paciente && paciente.relaciones?.length) { + (paciente as any).relaciones = paciente.relaciones + .filter(rel => rel.referencia) // descartar relaciones sin referencia + .map(rel => ({ + relacion: rel.relacion, + referencia: rel.referencia + })); + } + return paciente; +} export function make(body: IPaciente) { const paciente = new Paciente(); + + if (body.relaciones?.length) { + body.relaciones = body.relaciones + .filter(rel => rel.referencia) + .map(rel => ({ + relacion: rel.relacion, + referencia: getReferenciaId(rel.referencia) + })); + } + paciente.set(body); return paciente; } @@ -42,12 +72,13 @@ export function set(paciente: IPacienteDoc, body: any) { delete body['estado']; } - if (body.relaciones?.length) { - body.relaciones.forEach(rel => { - if (rel.referencia && typeof rel.referencia === 'object') { - rel.referencia = rel.referencia.id || rel.referencia._id; - } - }); + if (body.relaciones) { + body.relaciones = body.relaciones + .filter(rel => rel.referencia) // evita guardar relaciones con referencia null/undefined + .map(rel => ({ + relacion: rel.relacion, + referencia: rel.referencia?._id || rel.referencia?.id || rel.referencia + })); } paciente.set(body); @@ -126,6 +157,7 @@ export async function findById(id: string | String | Types.ObjectId, options = n select: 'nombre apellido documento numeroIdentificacion fechaNacimiento fechaFallecimiento fotoId sexo genero activo' }); const paciente = await queryFind; + if (paciente) { normalizeRelaciones(paciente); } EventCore.emitAsync('mpi:pacientes:findById', paciente); return paciente; } @@ -238,6 +270,7 @@ export async function multimatch(searchText: string, filter: any, options?: any) path: 'relaciones.referencia', select: 'nombre apellido documento numeroIdentificacion fechaNacimiento fechaFallecimiento fotoId sexo genero activo' }); + pacientes.forEach(p => normalizeRelaciones(p)); return pacientes; } @@ -441,8 +474,7 @@ export async function agregarHijo(progenitor, hijo, req) { const parentescoProgenitor = await ParentescoCtr.findOne({ nombre: '^progenitor' }, {}, req); const progenitorRelacion = { relacion: parentescoProgenitor, - referencia: progenitor._id, - activo: true + referencia: progenitor }; hijo.relaciones = hijo.relaciones || []; @@ -453,8 +485,7 @@ export async function agregarHijo(progenitor, hijo, req) { const parentescoHijo = await ParentescoCtr.findOne({ nombre: '^hijo' }, {}, req); const familiarRelacion = { relacion: parentescoHijo, - referencia: hijo._id, - activo: true + referencia: hijo }; progenitor.relaciones.push(familiarRelacion); diff --git a/core-v2/mpi/paciente/paciente.events.ts b/core-v2/mpi/paciente/paciente.events.ts index 84a1580f23..ce64fe6661 100644 --- a/core-v2/mpi/paciente/paciente.events.ts +++ b/core-v2/mpi/paciente/paciente.events.ts @@ -85,19 +85,33 @@ EventCore.on('mpi:pacientes:update', async (paciente: any, changeFields: string[ } } } + function getReferenciaId(ref: any) { + if (!ref) { return null; } + return typeof ref === 'object' ? (ref._id || ref.id) : ref; + } + if (changeFields.includes('activo') && paciente.relaciones) { // Obtenemos todos los pacientes relacionados del paciente desactivado/activado en un array de promesas. - let relacionados = paciente.relaciones.map(r => Paciente.findById(r.referencia)); + let relacionados = paciente.relaciones.map(r => + Paciente.findById(getReferenciaId(r.referencia)) + ); relacionados = await Promise.all(relacionados); // Por cada uno de esos pacientes relacionados buscamos en que posición del array de relaciones del paciente desactivado/activado // se encuentra y luego cambiamos el atributo activo a true/false segun corresponde. - relacionados.map(async pac => { - const index = pac.relaciones.findIndex(rel => rel.referencia.toString() === paciente._id.toString()); - if (index > -1) { - pac.relaciones[index].activo = paciente.activo; - } - await Paciente.findByIdAndUpdate(pac._id, { relaciones: pac.relaciones }); - }); + await Promise.all( + relacionados.map(async pac => { + const index = pac.relaciones.findIndex(rel => { + const refId = getReferenciaId(rel.referencia); + return refId.toString() === paciente._id.toString(); + }); + + if (index > -1) { + pac.relaciones[index].activo = paciente.activo; + } + + await Paciente.findByIdAndUpdate(pac._id, { relaciones: pac.relaciones }); + }) + ); } // Verifica si el paciente esta actualmente internado para replicar los cambios if (['nombre', 'apellido', 'sexo', 'alias', 'genero'].map(field => changeFields.includes(field))) { diff --git a/core-v2/mpi/paciente/paciente.interface.ts b/core-v2/mpi/paciente/paciente.interface.ts index 84d0ad6044..6a2f1e50db 100644 --- a/core-v2/mpi/paciente/paciente.interface.ts +++ b/core-v2/mpi/paciente/paciente.interface.ts @@ -3,7 +3,6 @@ import { Document, Schema, Types } from 'mongoose'; import { IContacto, IContactoDoc, IDireccion, IDireccionDoc } from '../../../shared/interfaces'; import { IFinanciador } from '../financiador/financiador.interface'; import { IParentesco } from '../parentesco/parentesco.interface'; - export interface ICarpetaEfector { organizacion: any; nroCarpeta: String; @@ -22,17 +21,7 @@ export interface IIdentificador { export interface IRelacion { relacion: IParentesco; - referencia: Schema.Types.ObjectId; - financiador: String; - nombre: String; - apellido: String; - documento: String; - foto: String; - fotoId?: Schema.Types.ObjectId; - fechaNacimiento?: Date | moment.Moment; - numeroIdentificacion?: String; - fechaFallecimiento?: Date | moment.Moment; - activo?: Boolean; + referencia: any; // objeto populado: { nombre, apellido, documento, ... } } export interface IPaciente { diff --git a/core-v2/mpi/paciente/paciente.schema.ts b/core-v2/mpi/paciente/paciente.schema.ts index bc896a048b..4c7beaa128 100644 --- a/core-v2/mpi/paciente/paciente.schema.ts +++ b/core-v2/mpi/paciente/paciente.schema.ts @@ -98,9 +98,8 @@ export const PacienteSchema: mongoose.Schema = new mongoose.Schema({ referencia: { type: mongoose.Schema.Types.ObjectId, ref: 'paciente_2', - required: true - }, - activo: Boolean + required: false + } }], financiador: [FinanciadorSchema], claveBlocking: { type: [String], es_indexed: true }, diff --git a/modules/mobileApp/routes/paciente.ts b/modules/mobileApp/routes/paciente.ts index b61285de94..2b9b743676 100644 --- a/modules/mobileApp/routes/paciente.ts +++ b/modules/mobileApp/routes/paciente.ts @@ -39,7 +39,7 @@ router.get('/paciente/:id/relaciones', async (req: any, res, next) => { } const resultado = await findById(req.user.pacientes[0].id); // Verifico que el paciente sea familiar del usuario logueado - const esFamiliar = (resultado.relaciones).find(rel => rel.documento === paciente.documento); + const esFamiliar = (resultado.relaciones as any[])?.find(rel => rel.referencia && rel.referencia.documento === paciente.documento); if (esFamiliar) { return res.json(paciente); } else { @@ -56,7 +56,7 @@ router.get('/relaciones', async (req: any, res, next) => { const arrayRelaciones = []; let pacienteRel; if (paciente.relaciones) { - for (const rel of paciente.relaciones) { + for (const rel of (paciente.relaciones as any[])) { if (rel.relacion) { const objRelacion = rel.toObject(); pacienteRel = await findById(rel.referencia as any); @@ -86,8 +86,9 @@ router.put('/paciente/:id', async (req: any, res, next) => { let esFamiliar; if (index < 0) { const resultado = await findById(req.user.pacientes[0].id); - esFamiliar = resultado.relaciones.find(rel => { - return rel.referencia.toString() === paciente.id.toString(); + esFamiliar = (resultado.relaciones as any[])?.find(rel => { + const refId = rel.referencia?.id || rel.referencia?._id; + return refId && refId.toString() === paciente.id.toString(); }); } if (index >= 0 || esFamiliar) { @@ -141,8 +142,9 @@ router.get('/laboratorios/(:id)', async (req: any, res, next) => { let esFamiliar; if (index < 0) { const resultado = await findById((req as any).user.pacientes[0].id); - esFamiliar = resultado.relaciones.find(rel => { - return rel.referencia.toString() === paciente.id.toString(); + esFamiliar = (resultado.relaciones as any[])?.find(rel => { + const refId = rel.referencia?.id || rel.referencia?._id; + return refId && refId.toString() === paciente.id.toString(); }); } if (index >= 0 || esFamiliar) {