const validar = require('../../helper/validar'); const dbPath = '../../db/tablas'; const Carrito = require(`${dbPath}/Carrito`); const Equipo = require(`${dbPath}/Equipo`); const Motivo = require(`${dbPath}/Motivo`); const Programa = require(`${dbPath}/Programa`); const Status = require(`${dbPath}/Status`); const update = async (body) => { const idEquipo = validar.validarNumeroEntero( body.idEquipo, 'id equipo', true ); const idStatus = body.idStatus ? validar.validarNumeroEntero(body.idStatus, 'id status', true) : ''; const idCarrito = body.idCarrito ? validar.validarNumeroEntero(body.idCarrito, 'id carrito', true) : ''; const idPrograma = body.idPrograma ? validar.validarNumeroEntero(body.idPrograma, 'id programa', true) : ''; const motivo = body.motivo ? validar.validarAlfanumerico(body.motivo, 'motivo', true, 500) : ''; let update = {}; return Status.findOne({ where: { idStatus } }) .then((res) => { if (idStatus) { if (!res) throw new Error('No existe este status.'); if (!motivo) throw new Error('No se mando el motivo de cambio de status.'); update.idStatus = idStatus; } return Carrito.findOne({ where: { idCarrito } }); }) .then((res) => { if (idCarrito) { if (!res) throw new Error('No existe este carrito.'); update.idCarrito = idCarrito; } return Programa.findOne({ where: { idPrograma } }); }) .then((res) => { if (idPrograma) { if (!res) throw new Error('No existe este programa.'); update.idPrograma = idPrograma; } if (validar.validarObjetoVacio(update)) throw new Error('No se envió nada para actualizar.'); return Equipo.findOne({ where: { idEquipo } }); }) .then(async (res) => { if (!res) throw new Error('No existe este equipo.'); if (idStatus) await Motivo.create({ motivo, idEquipo, idStatus }); return Equipo.update(update, { where: { idEquipo } }); }) .then(() => ({ message: 'Se actualizó correctamente el equipo.' })); }; module.exports = update;