const { Op } = require('sequelize'); const drive = require('../../helper/drive'); const Servicio = require('../../db/tablas/Servicio'); const Usuario = require('../../db/tablas/Usuario'); const Programa = require('../../db/tablas/Programa'); const Carrera = require('../../db/tablas/Carrera'); const validar = require('../../helper/validar'); const nuevo = async (body, file) => { const idUsuario = validar.validarId(body.idUsuario); const idPrograma = validar.validarId(body.idPrograma); const idCarrera = validar.validarId(body.idCarrera); const numeroCuenta = validar.validarNumeroCuenta(body.numeroCuenta); const creditos = validar.validarNumero(body.creditos); const correo = validar.validarCorreo(body.correo); const fechaInicio = validar.validarFecha(body.fechaInicio); const fechaFin = validar.validarFecha(body.fechaFin); const path = `./server/uploads/${validar.validar(file, 'El archivo', 1000)}`; const programaInterno = body.programaInterno ? validar.validarTexto( body.programaInterno, 'El texto programa interno.', 80 ) : ''; const profesor = body.profesor ? validar.validarTexto(body.profesor, 'El texto de profesor.', 50) : ''; let carpeta = ''; return Usuario.findOne({ where: { idUsuario }, }) .then((res) => { if (!res) throw new Error('Este alumno no existe en la db.'); if (res.idTipoUsuario !== 3) throw new Error('Este usuario no es de tipo Alumno.'); return Programa.findOne({ where: { idPrograma } }); }) .then((res) => { if (!res) throw new Error('Este programa no existe en la db.'); return Carrera.findOne({ where: { idCarrera } }); }) .then((res) => { if (!res) throw new Error('Esta carrera no existe en la db.'); return Servicio.findOne({ where: { idUsuario, idStatus: { [Op.ne]: 10 } }, }); }) .then(async (res) => { if (res) throw new Error('Este alumno ya tienen un Servicio Social activo.'); return drive.folder(numeroCuenta); }) .then((res) => { carpeta = res; return drive.uploadFile( path, `Carta_Aceptacion.pdf`, 'application/pdf', carpeta ); }) .then((res) => Servicio.create({ idUsuario, idPrograma, idCarrera, creditos, correo, fechaInicio, fechaFin, carpeta, cartaAceptacion: res, profesor, programaInterno, }) ) .then((res) => ({ message: `Se Pre-Registro correctamente al alumno.`, })); }; module.exports = nuevo;