Skip to content

Commit

Permalink
INT - Agregar logs en api (#1837)
Browse files Browse the repository at this point in the history
* ref(in): agrega logs en rutas y controller de internacion

* correcciones
  • Loading branch information
negro89 authored Nov 28, 2023
1 parent fed44c9 commit 34245da
Show file tree
Hide file tree
Showing 6 changed files with 48 additions and 16 deletions.
6 changes: 3 additions & 3 deletions modules/rup/internacion/camas.controller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ describe('Internacion - camas', () => {
fecha: moment().subtract(3, 'minute').toDate()
}, REQMock);

let camaEncontrada = await findById({ organizacion: organizacion._id, capa, ambito }, idCama, moment().subtract(1, 'minutes').toDate());
let camaEncontrada: any = await findById({ organizacion: organizacion._id, capa, ambito }, idCama, moment().subtract(1, 'minutes').toDate());
expect(camaEncontrada.estado).toBe('inactiva');

const resultNull = await patchEstados({
Expand Down Expand Up @@ -313,14 +313,14 @@ describe('Internacion - camas', () => {
term: 'servicio de adicciones',
conceptId: '4561000013103',
semanticTag: 'medio ambiente'
}
},
idInternacion: '57f67a7ad86d9f64130a138d'
}, REQMock);


const fechaNuevaIngreso = moment().add(4, 'hour').toDate();
const mustBeNull = await changeTime({ organizacion, capa, ambito }, idCama, fechaIngreso, fechaNuevaIngreso, '57f67a7ad86d9f64130a138d', REQMock);
expect(mustBeNull).toBe(false);

});

test('Fallo de integridad en cama - Inactiva > Ocupada', async () => {
Expand Down
5 changes: 4 additions & 1 deletion modules/rup/internacion/camas.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { ISnomedConcept } from '../schemas/snomed-concept';
import { EventCore } from '@andes/event-bus';
import { Auth } from '../../../auth/auth.class';
import { Organizacion } from '../../../core/tm/schemas/organizacion';
import { internacionCamaEstadosLog as logger } from './internacion.log';

interface INombre {
_id: ObjectId;
Expand Down Expand Up @@ -217,7 +218,8 @@ export async function patchEstados(data: Partial<ICama>, req: Request) {

if (data.esMovimiento) {
const maquinaEstado = await EstadosCtr.encontrar(data.organizacion._id, data.ambito, data.capa);
cambioPermitido = await maquinaEstado.check(estadoCama.estado, data.estado);
cambioPermitido = await maquinaEstado.check(estadoCama.estado, data.estado, estadoCama?.idInternacion, data?.idInternacion);

} else {
// Datos que no deberian cambiar
delete data['idInternacion'];
Expand Down Expand Up @@ -251,6 +253,7 @@ export async function patchEstados(data: Partial<ICama>, req: Request) {
}
return nuevoEstado;
}
logger.info('patchEstados', { info: 'cambio no permitido', fecha: moment().toDate(), estadoAnterior: estadoCama, nuevoEstado: data }, req);

return null;
}
Expand Down
27 changes: 24 additions & 3 deletions modules/rup/internacion/camas.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import moment = require('moment');
import { Types } from 'mongoose';
import { CamaEstados } from './cama-estados.schema';
import { Camas } from './camas.schema';
import { internacionCamaEstadosLog as logger } from './internacion.log';

const router = express.Router();

Expand All @@ -28,11 +29,12 @@ router.get('/camas', Auth.authenticate(), capaMiddleware, asyncHandler(async (re
const { capa, fecha } = req.query;

let salas = [];
if (capa !== 'estadistica' && !req.query.cama && !req.query.idInternacion) {
if (capa !== 'estadistica' && !req.query.idInternacion) {
salas = await SalaComunController.listarSalaComun({
organizacion: organizacion._id,
fecha: moment(fecha).toDate(),
ambito: req.query.ambito
ambito: req.query.ambito,
id: req.query.cama
});
salas = populateSalaComun(salas);
}
Expand Down Expand Up @@ -136,7 +138,18 @@ router.patch('/camaEstados/:idCama', Auth.authenticate(), capaMiddleware, asyncH
nombre: Auth.getOrganization(req, 'nombre')
};
const data = { ...req.body, organizacion, id: req.params.idCama };
const result = await CamasController.patchEstados(data, req);
let result;
try {
result = await CamasController.patchEstados(data, req);
} catch (err) {
const dataErr = {
ruta: '/camaEstados/:idCama',
idCama: req.params.idCama,
fecha: moment().toDate(),
nuevoEstado: req.body
};
await logger.error('patchCamaEstados', dataErr, err, req);
}

if (result) {
return res.json(result);
Expand Down Expand Up @@ -211,9 +224,17 @@ router.patch('/camas/changeTime/:id', Auth.authenticate(), capaMiddleware, async
}
);
} else {
await logger.info('/camas/changeTime/:id', { info: 'cambio no realizado', fecha: moment().toDate(), nuevoEstado: req.body }, req);
return next('No se puede realizar el cambio de estado');
}
} catch (err) {
const dataErr = {
ruta: '/camas/changeTime/:id',
idCama: req.params.id,
fecha: moment().toDate(),
nuevoEstado: req.body
};
await logger.error('patchCamaEstados', dataErr, err, req);
return next(err);
}
});
Expand Down
5 changes: 3 additions & 2 deletions modules/rup/internacion/estados.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,10 @@ const EstadoSchema = new Schema({
}
});

EstadoSchema.methods.check = function (origen, destino) {
EstadoSchema.methods.check = function (origen, destino, idInternacionOrigen, idInternacionDestino) {
if (origen === destino) {
return true;
// true en caso de cambio de UO o cama (no)censable. De lo contrario debería tratarse de estados (y camas) distintos.
return (!idInternacionOrigen && !idInternacionDestino) || idInternacionOrigen && idInternacionDestino && idInternacionOrigen.toString() === idInternacionDestino.toString();
}

for (const relacion of this.relaciones) {
Expand Down
11 changes: 11 additions & 0 deletions modules/rup/internacion/internacion.log.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Connections } from '../../../connections';
import { Logger } from '@andes/log';

export const internacionCamaEstadosLog = new Logger({
connection: Connections.logs,
module: 'internacion',
type: 'cama-estados',
application: 'andes',
bucketBy: 'd',
bucketSize: 100
});
10 changes: 3 additions & 7 deletions packages/unit-testing/index.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,15 @@
import { Request } from '@andes/api-tool';
import { MongoMemoryServer } from 'mongodb-memory-server-global';
import * as mongoose from 'mongoose';
import { Types } from 'mongoose';
import { Connections } from '../../connections';


const sha1 = require('sha1');

export const getObjectId = (name: string): Types.ObjectId => {
export const getObjectId = (name: string): mongoose.Types.ObjectId => {
if (name === '') {
throw new Error('Name cannot be empty');
}
const hash = sha1(name);
return new Types.ObjectId(hash.substring(0, 24));
return new mongoose.Types.ObjectId(hash.substring(0, 24));
};

export function getFakeRequest(): Request {
Expand All @@ -33,8 +30,7 @@ export function setupUpMongo() {
beforeAll(async () => {
mongoServer = await MongoMemoryServer.create();
const mongoUri = mongoServer.getUri();
mongoose.connect(mongoUri);
Connections.logs = mongoose.connection;
await mongoose.connect(mongoUri);
});

afterAll(async () => {
Expand Down

0 comments on commit 34245da

Please sign in to comment.