const { Op } = require('sequelize'); const helperPath = '../../helper'; const drive = require(`${helperPath}/drive`); const validar = require(`${helperPath}/validar`); const dbPath = '../../db/tablas'; const Carrera = require(`${dbPath}/Carrera`); const Programa = require(`${dbPath}/Programa`); const Servicio = require(`${dbPath}/Servicio`); const Usuario = require(`${dbPath}/Usuario`); const nuevo = async (body, file) => { const idUsuario = validar.validarNumeroEntero(body.idUsuario, 'id usuario'); const idPrograma = validar.validarNumeroEntero( body.idPrograma, 'id programa' ); const idCarrera = validar.validarNumeroEntero(body.idCarrera, 'id carrera'); const numeroCuenta = validar.validarNumeroCuenta(body.numeroCuenta); const creditos = validar.validarNumero(body.creditos, 'créditos', true); const correo = validar.validarCorreo(body.correo); const fechaInicio = validar.validarFecha( body.fechaInicio, 'fecha de inicio', false ); const fechaFin = validar.validarFecha(body.fechaFin, 'fecha fin', false); const path = `./server/uploads/${validar.validacionBasicaStr( file, 'archivo', true, 1000 )}`; const programaInterno = body.programaInterno ? validar.validarAlfanumerico( body.programaInterno, 'programa interno', true, 250 ) : ''; const profesor = body.profesor ? validar.validarTexto(body.profesor, 'profesor', true, 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 Servicio.create({ idUsuario, idPrograma, idCarrera, creditos, correo, fechaInicio: fechaInicio.format(), fechaFin: fechaFin.format(), carpeta: '', cartaAceptacion: '', profesor, programaInterno, }); }) .then((servicio) => { let carpeta = ''; drive .mkDir(numeroCuenta) .then((res) => { carpeta = res; return drive.uploadFile( path, `Carta_Aceptacion.pdf`, 'application/pdf', carpeta ); }) .then((res) => Servicio.update( { carpeta, cartaAceptacion: res }, { where: { idServicio: servicio.idServicio } } ) ); return { message: `Se Pre-Registro correctamente a este alumno.` }; }); }; module.exports = nuevo;