Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Plan de indicaciones - Control de hs (frecuencia) para ejecución de una indicación #1772

Merged
merged 1 commit into from
Mar 3, 2023
Merged
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
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { MongoQuery, ResourceBase } from '@andes/core';
import { EventCore } from '@andes/event-bus/index';
import { Auth } from '../../../../auth/auth.class';
import { PlanIndicacionesEventos } from './plan-indicaciones.schema';

class PlanIndicacionesEventosController extends ResourceBase {
Model = PlanIndicacionesEventos;
resourceName = 'plan-indicaciones-eventos';
resourceModule = 'internacion';
middlewares = [Auth.authenticate()];
searchFileds = {
fecha: MongoQuery.matchDate,
Expand All @@ -13,9 +15,17 @@ class PlanIndicacionesEventosController extends ResourceBase {
indicacion: MongoQuery.equalMatch.withField('idIndicacion'),
estado: MongoQuery.equalMatch
};
eventBus = EventCore;

async deleteByIndicacion(idIndicacion: String) {
await PlanIndicacionesEventos.deleteMany({ idIndicacion });
async deleteByIndicacion(idIndicacion: String, desde?: Date, estado?: String) {
const query = PlanIndicacionesEventos.deleteMany({ idIndicacion });
if (desde) {
query.where({ fecha: { $gte: desde } });
}
if (estado) {
query.where({ estado });
}
await query;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,50 @@ EventCore.on('mapa-camas:plan-indicacion:create', async (prestacion) => {
await Promise.all(savePromises);
});

EventCore.on('internacion:plan-indicaciones-eventos:create', async (evento) => {
if (evento.estado === 'realizado' && !evento.updatedAt) {
/* Por cada nuevo evento NO PLANIFICADO en estado REALIZADO debe ajustarse el horario de los proximos.
Un evento es no planificado cuando es creado manualmente por el usuario en lugar de generarse automáticamente
al momento de guardar una nueva indicación.
*/
const [indicacion, indicacionEventos] = await Promise.all([
PlanIndicacionesCtr.findById(evento.idIndicacion),
PlanIndicacionesEventosCtr.search({ indicacion: evento.idIndicacion })
]);
const configOrganizacion = await getConfiguracion(indicacion.organizacion.id);
const horaInicioEfector = configOrganizacion.planIndicaciones.horaInicio;

if (indicacion.valor.unicaVez) {
return;
}
const eventos = indicacionEventos.sort((ev1, ev2) => moment(ev1.fecha).diff(moment(ev2.fecha)));
const index = eventos.findIndex(ev => ev.id === evento.id);
const eventosPosteriores = eventos.slice(index + 1, eventos.length);

if (!eventosPosteriores.some(ev => ev.estado !== 'on-hold')) {
const proximoEvento = eventosPosteriores.shift();
await PlanIndicacionesEventosCtr.deleteByIndicacion(indicacion.id, proximoEvento.fecha);

if (eventosPosteriores.length) {
/* Calculamos la diferencia en horas entre el nuevo evento y el siguiente planificado, luego restamos esta
diferencia a los eventos proximos para ajustar la planificacion.
*/
const diferenciaAlProximo = moment(proximoEvento.fecha).diff(moment(evento.fecha), 'hours');
const nuevosHorarios = eventosPosteriores.map(ev => moment(ev.fecha).subtract(diferenciaAlProximo, 'hours'));

// Una indicacion puede tener mas de una frecuencia
const ultimaFrecuenciaIndicacion = indicacion.valor.frecuencias[indicacion.valor.frecuencias.length - 1].frecuencia.key; // ultima frecuencia
const ultimoHorario = nuevosHorarios[nuevosHorarios.length - 1];

// Si el adelanto de los horarios genera una franja horaria donde hay lugar para otra toma, se agrega.
if (moment(ultimoHorario).add(ultimaFrecuenciaIndicacion, 'hours').isBefore(moment().startOf('day').add(horaInicioEfector + 24, 'hours'))) {
nuevosHorarios.push(moment(ultimoHorario).add(ultimaFrecuenciaIndicacion, 'hours'));
}
await crearEventos(nuevosHorarios, indicacion);
}
}
}
});

EventCore.on('internacion:plan-indicaciones:create', async (indicacion) => {
await crearEventosSegunPrescripcion(indicacion);
Expand Down