const moment = require('moment'); const io = require('../../socket'); const { validarNumeroEntero } = require('../../helper/validar'); const dbPath = '../../db/tablas'; const Carrito = require(`${dbPath}/Carrito`); const Equipo = require(`${dbPath}/Equipo`); const Modulo = require(`${dbPath}/Modulo`); const Operador = require(`${dbPath}/Operador`); const Prestamo = require(`${dbPath}/Prestamo`); const TipoCarrito = require(`${dbPath}/TipoCarrito`); const entregar = async (body) => { const ahora = moment(); const idPrestamo = validarNumeroEntero(body.idPrestamo, 'id prestamo', true); const idOperadorEntrega = validarNumeroEntero( body.idOperadorEntrega, 'id operador entrega', true ); let idEquipo; return Operador.findOne({ where: { idOperador: idOperadorEntrega } }) .then((res) => { if (!res) throw new Error('No existe este operador.'); return Prestamo.findOne({ where: { idPrestamo }, include: [{ model: Equipo }], }); }) .then(async (res) => { if (!res) throw new Error('No existe este prestamo.'); idEquipo = res.Equipo.idEquipo; if (!res.activo) throw new Error('Este prestamo ya no esta activo.'); else if (res.Equipo.idStatus === 2) throw new Error('Ya se entrego el equipo al usuario.'); else if (moment(res.horaMaxRecoger) < ahora) await Equipo.update({ idStatus: 4 }, { where: { idEquipo } }) .then(() => Prestamo.update({ activo: false }, { where: { idPrestamo } }) ) .then(() => { throw new Error( 'Ya paso el tiempo límite para recoger el equipo de cómputo.' ); }); return Equipo.update({ idStatus: 2 }, { where: { idEquipo } }); }) .then(() => { Prestamo.update( { idOperadorEntrega, horaInicio: ahora.format(), horaFin: ahora.add(2, 'h').format(), }, { where: { idPrestamo } } ); }) .then(() => Equipo.findOne({ where: { idEquipo }, include: [ { model: Carrito, include: [{ model: TipoCarrito }, { model: Modulo }], attributes: ['idCarrito', 'sobrenombre'], }, ], attributes: [ 'idEquipo', 'numeroSerie', 'numeroInventario', 'sobrenombre', ], }) ) .then((res) => { io.getIO().emit('actualizar'); return res; }); }; module.exports = entregar;