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) => { let idUsuario = validar.validarId(body.idUsuario); let idPrograma = validar.validarId(body.idPrograma); let idCarrera = validar.validarId(body.idCarrera); let numeroCuenta = validar.validarNumeroCuenta(body.numeroCuenta); let creditos = validar.validarNumero(body.creditos); let correo = validar.validarCorreo(body.correo); let fechaInicio = validar.validarFecha(body.fechaInicio); let fechaFin = validar.validarFecha(body.fechaFin); let path = `./server/uploads/${validar.validar(file, 'El archivo', 1000)}`; let carpeta = ''; let programaInterno = body.programaInterno ? validar.validarTexto( body.programaInterno, 'El texto programa interno.', 80 ) : ''; let profesor = body.profesor ? validar.validarTexto(body.profesor, 'El texto de profesor.', 50) : ''; 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) => { return Servicio.create({ idUsuario, idPrograma, idCarrera, creditos, correo, fechaInicio, fechaFin, carpeta, cartaAceptacion: res, profesor, programaInterno, }); }) .then((res) => { return { message: `Se Pre-Registro correctamente al alumno.`, }; }); }; module.exports = nuevo;