Files
pcpuma_acatlan_api/server/controller/Prestamo/entregar.js
T
Lemuel Marquez b84c1312fc listo
2021-06-29 09:55:18 -05:00

72 lines
2.3 KiB
JavaScript

const moment = require('moment');
const { validarId } = 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 = validarId(body.idPrestamo);
const idOperadorEntrega = validarId(body.idOperadorEntrega);
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.enUso)
throw new Error('Ya se entrego el equipo al usuario.');
else if (moment(res.horaMaxRecoger) < ahora) {
await Equipo.update({ apartado: false }, { where: { idEquipo } });
await Prestamo.update({ activo: false }, { where: { idPrestamo } });
throw new Error(
'Ya paso el tiempo limite para recoger el dispositivo.'
);
}
return Equipo.update({ enUso: true }, { where: { idEquipo } });
})
.then((res) => {
Prestamo.update(
{
idOperadorEntrega,
horaInicio: ahora.format(),
horaFin: ahora.add(2, 'h').format(),
},
{ where: { idPrestamo } }
);
})
.then((res) => {
return Equipo.findOne({
where: { idEquipo },
include: [
{
model: Carrito,
include: [{ model: TipoCarrito }, { model: Modulo }],
},
],
});
})
.then((res) => {
delete res.dataValues.idCarrito;
delete res.dataValues.idStatus;
delete res.dataValues.idPrograma;
delete res.dataValues.Carrito.dataValues.idTipoCarrito;
delete res.dataValues.Carrito.dataValues.idModulo;
return res;
});
};
module.exports = entregar;