const moment = require('moment'); const { Op } = require('sequelize'); const validar = require('../../helper/validar'); const dbPath = '../../db/tablas'; const Infraccion = require(`${dbPath}/Infraccion`); const Multa = require(`${dbPath}/Multa`); const Operador = require(`${dbPath}/Operador`); const Prestamo = require(`${dbPath}/Prestamo`); const Usuario = require(`${dbPath}/Usuario`); const multar = async (body) => { const ahora = moment(); const idOperadorMulta = validar.validarNumeroEntero( body.idOperadorMulta, 'id operador multa', true ); const idInfraccion = validar.validarNumeroEntero( body.idInfraccion, 'id infracción', true ); const idPrestamo = validar.validarNumeroEntero( body.idPrestamo, 'id préstamo', true ); const descripcion = validar.validarAlfanumerico( body.descripcion, 'descripción', false, 500 ); let fechaFin = moment(); let prestamo = {}; let gravedad = ''; return Operador.findOne({ where: { idOperador: idOperadorMulta } }) .then((res) => { if (!res) throw new Error('No existe este operador.'); return Infraccion.findOne({ where: { idInfraccion } }); }) .then((res) => { if (!res) throw new Error('No existe esta infracción.'); // Checar si tiene una multa activa, agragar días a multa gravedad = res.gravedad; return Prestamo.findOne({ where: { idPrestamo }, include: [{ model: Usuario }], }); }) .then((res) => { if (!res) throw new Error('No existe este préstamo.'); if (res.canceladoUsuario || res.canceladoOperador) throw new Error( 'No se puede usar un préstamo cancelado para multar a un usuario.' ); prestamo = res; return Prestamo.findOne({ where: { idUsuario: prestamo.idUsuario, activo: true }, }); }) .then((res) => { if (res) throw new Error( 'No se puede multar a un usuario mientras tenga un préstamo activo.' ); return Multa.findOne({ where: { idPrestamo, idInfraccion: { [Op.ne]: 1 } }, }); }) .then(async (res) => { if (res) throw new Error( 'Este préstamo ya ha sido usado para multar a un usuario.' ); if (prestamo.Usuario.multa) { await Multa.findOne({ where: { createdAt: { [Op.gte]: ahora }, fechaFin: { [Op.lte]: ahora }, }, include: [ { model: Prestamo, include: [ { model: Usuario, where: { idUsuario: prestamo.idUsuario } }, ], }, ], }).then((res) => { if (!res) throw new Error( 'El usuario esta multado pero no se encontro una multa activa. Favor de comunicarse con los desarrolladores.' ); fechaFin.moment(res.fechaFin); }); } if (gravedad === '1') fechaFin.add(7, 'd'); else fechaFin.add(100, 'y'); return Usuario.update( { multa: true }, { where: { idUsuario: prestamo.idUsuario } } ); }) .then(() => Multa.create({ idPrestamo, idOperadorMulta, idInfraccion, descripcion, fechaFin: fechaFin.format('YYYY-MM-DD'), }) ) .then(() => ({ message: `Se levantó correctamente el reporte de multa.`, })); }; module.exports = multar;