Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 57 additions & 16 deletions core-v2/mpi/paciente/paciente.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -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();
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -413,21 +465,16 @@ 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) {
// agrego relacion al hijo
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 || [];
Expand All @@ -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);
Expand Down
30 changes: 22 additions & 8 deletions core-v2/mpi/paciente/paciente.events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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))) {
Expand Down
13 changes: 1 addition & 12 deletions core-v2/mpi/paciente/paciente.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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 {
Expand Down
17 changes: 6 additions & 11 deletions core-v2/mpi/paciente/paciente.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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 },
Expand Down
14 changes: 8 additions & 6 deletions modules/mobileApp/routes/paciente.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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);
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down