diff --git a/core-v2/mpi/paciente/paciente.controller.ts b/core-v2/mpi/paciente/paciente.controller.ts index 6a75a82e3..f0f73e867 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; } @@ -41,6 +71,16 @@ export function set(paciente: IPacienteDoc, body: any) { delete body['documento']; delete body['estado']; } + + 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); if (paciente.foto && !paciente.fotoId) { (paciente as any).fotoId = new Types.ObjectId(); @@ -112,7 +152,12 @@ 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; + if (paciente) { normalizeRelaciones(paciente); } EventCore.emitAsync('mpi:pacientes:findById', paciente); return paciente; } @@ -218,7 +263,14 @@ 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' + }); + pacientes.forEach(p => normalizeRelaciones(p)); return pacientes; } @@ -413,7 +465,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) { @@ -421,13 +474,7 @@ export async function agregarHijo(progenitor, hijo, req) { const parentescoProgenitor = await ParentescoCtr.findOne({ nombre: '^progenitor' }, {}, 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 + referencia: progenitor }; hijo.relaciones = hijo.relaciones || []; @@ -438,13 +485,7 @@ export async function agregarHijo(progenitor, hijo, req) { const parentescoHijo = await ParentescoCtr.findOne({ nombre: '^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 + 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 84a1580f2..ce64fe666 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 84d0ad604..6a2f1e50d 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 e783b66e1..4c7beaa12 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,20 +92,14 @@ export const PacienteSchema: mongoose.Schema = new mongoose.Schema({ required: false }, // -------------------- + relaciones: [{ relacion: ParentescoSchema, referencia: { type: mongoose.Schema.Types.ObjectId, - ref: 'paciente' - }, - nombre: String, - apellido: String, - documento: String, - fechaNacimiento: Date, - fechaFallecimiento: Date, - numeroIdentificacion: String, - fotoId: mongoose.Schema.Types.ObjectId, - activo: Boolean + ref: 'paciente_2', + 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 b61285de9..2b9b74367 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) {