const moment = require('moment'); const { Op } = require('sequelize'); const io = require('../../socket'); const validar = require('../../helper/validar'); const dbPath = '../../db/tablas'; const Equipo = require(`${dbPath}/Equipo`); const Multa = require(`${dbPath}/Multa`); const Operador = require(`${dbPath}/Operador`); const Prestamo = require(`${dbPath}/Prestamo`); const regresarNumeroInventario = async (body) => { const ahora = moment(); const ahoraAux = moment(); const numeroInventario = validar.validarAlfanumerico( body.numeroInventario, 'numero de inventario', true, 20 ); const idOperadorRegreso = validar.validarNumeroEntero( body.idOperadorRegreso, 'id operador regreso', true ); let diferencia = null; let idPrestamo = null; return Operador.findOne({ where: { idOperador: idOperadorRegreso } }) .then((res) => { if (!res) throw new Error('No existe este operador.'); return Prestamo.findOne({ where: { [Op.or]: [ { [Op.and]: [ { regresoInmediato: true }, { idOperadorRegreso: null }, ], }, { activo: true }, ], }, include: [{ model: Equipo, where: { numeroInventario } }], }); }) .then(async (res) => { if (!res) throw new Error('No existe un prestamo activo con este equipo.'); if (!res.Equipo.idStatus === 1) throw new Error('Aun no se ha entregado el equipo al usuario.'); idPrestamo = res.idPrestamo; diferencia = parseInt((ahora - moment(res.horaFin)) / 60000); if (diferencia >= 15) await Multa.create({ idPrestamo, idInfraccion: 1, idOperadorMulta: idOperadorRegreso, descripcion: `Se paso por ${diferencia} minutos para entregar el equipo.`, fechaFin: ahoraAux.add(parseInt(diferencia / 15) * 7, 'd').format(), }); return Equipo.update( { idStatus: 4 }, { where: { idEquipo: res.idEquipo } } ); }) .then(() => { Prestamo.update( { idOperadorRegreso, horaEntrega: ahora.format(), activo: false }, { where: { idPrestamo } } ); }) .then(() => { io.getIO().emit('actualizar'); return { message: 'Se ha regresado correctamente el equipo de cómputo.', }; }); }; module.exports = regresarNumeroInventario;