api completa

This commit is contained in:
2022-05-13 22:10:54 -05:00
parent f9fa0ac0ca
commit 2015de3729
31 changed files with 366 additions and 89 deletions
+33 -12
View File
@@ -1,26 +1,44 @@
const Invitado = require('../../db/tablas/Invitado');
const Profesor = require('../../db/tablas/Profesor');
const Premiacion = require('../../db/tablas/Premiacion');
const validar = require('../../helper/validar');
const { correo } = require('../../helper/correos');
const gmail = require('../../helper/gmail');
const ProfesorPremiacion = require('../../db/tablas/ProfesorPremiacion');
const infoInvitados = async (body) => {
const idProfesor = validar.validarNumeroEntero(body.idProfesor, 'idProfesor');
const idPremiacion = validar.validarNumeroEntero(
body.idPremiacion,
'idPremiacion'
);
const invitados = body.invitados;
const numeroInvitados = invitados.length;
const premiacion = await Premiacion.findOne({ where: idPremiacion });
if (!premiacion)
throw new Error('No existe ninguna premiación con este id con este id.');
invitados.forEach((invitado) => {
if (invitado.edad < 18)
throw new Error('Los invitados deben de ser mayores de edad.');
if (invitado.edad < 12)
throw new Error(
'Alguno de sus invitados no cuenta con la edad suficiente.'
);
});
if (numeroInvitados > 3)
throw new Error('El número de invitados no puede ser mayor que 3.');
const prof = await Profesor.findOne({ where: idProfesor });
if (prof.numeroInvitados)
const profPrem = await ProfesorPremiacion.findOne({
where: { idProfesor, idPremiacion },
});
if (!profPrem)
throw new Error(
'No existe ningún profesor con este id en esta premiación.'
);
if (profPrem.numeroInvitados)
throw new Error('A este profesor ya se le han guardado sus invitados.');
prof.update({ numeroInvitados: numeroInvitados });
profPrem.update({ numeroInvitados: numeroInvitados });
const respuesta = [];
for (let i = 0; i < numeroInvitados; i++) {
@@ -40,23 +58,26 @@ const infoInvitados = async (body) => {
nombreCompleto: nombre,
edad: edad,
idProfesor: idProfesor,
idPremiacion: idPremiacion,
});
if (!res)
throw new Error('No se ha podido ingresar los datos del invitado');
respuesta.push(res);
}
const dataProf = await Profesor.findOne({ where: idProfesor });
const Mail = correo(
dataProf.nombre,
dataProf.numeroTrabajador,
dataProf.numeroInvitados
profPrem.idProfesor,
profPrem.idPremiacion,
premiacion.premiacion,
premiacion.fecha,
premiacion.hora
);
const dataProf = await Profesor.findOne({ where: idProfesor });
gmail(
Mail.subject,
`yosoymarco3@gmail.com`,
// `${dataProf.numeroTrabajador}@pcpuma.acatlan.unam.mx`,
// `jeremy@acatlan.unam.mx`,
`${dataProf.numeroTrabajador}@pcpuma.acatlan.unam.mx`,
Mail.message
);
return {
+17 -3
View File
@@ -1,6 +1,20 @@
const Invitado = require('../../db/tablas/Invitado');
const Profesor = require('../../db/tablas/Profesor')
const Profesor = require('../../db/tablas/Profesor');
const { validarNumeroEntero } = require('../../helper/validar');
const get = () => Invitado.findAll({include: [{ model: Profesor }],});
const get = async (query) => {
const idPremiacion = validarNumeroEntero(
query.idPremiacion,
'idPremiacion',
true
);
module.exports = get;
const invitados = await Invitado.findAll({
where: { idPremiacion },
include: [{ model: Profesor }],
});
if (!invitados) throw new Error('No se ha podido traer a los invitados');
return invitados;
};
module.exports = get;
@@ -0,0 +1,21 @@
const Premiacion = require('../../db/tablas/Premiacion');
const { validarNumeroEntero, validarFecha } = require('../../helper/validar');
const activarDesactivar = async (body) => {
if (!body.activa)
throw new Error('Se necesita saber si se quiere activar o desactivar.');
const idPremiacion = validarNumeroEntero(
body.idPremiacion,
'idPremiacion',
true
);
const activa = body.activa;
const premiacion = await Premiacion.findOne({ where: idPremiacion });
if (!premiacion) throw new Error('No existe esta premiación.');
return premiacion.update({ activa });
};
module.exports = activarDesactivar;
+21
View File
@@ -0,0 +1,21 @@
const Premiacion = require('../../db/tablas/Premiacion');
const { validarNumeroEntero, validarFecha } = require('../../helper/validar');
const editar = async (body) => {
let fecha;
let hora;
if (body.fecha) fecha = validarFecha(body.fecha);
if (body.hora) hora = body.hora;
const idPremiacion = validarNumeroEntero(
body.idPremiacion,
'idPremiacion',
true
);
const premiacion = await Premiacion.findOne({ where: idPremiacion });
if (!premiacion) throw new Error('No existe esta premiación.');
return premiacion.update({ fecha, hora});
};
module.exports = editar;
+18
View File
@@ -0,0 +1,18 @@
const Premiacion = require('../../db/tablas/Premiacion');
const validar = require('../../helper/validar');
const nueva = async (body) => {
const premiacion = validar.validacionBasicaStr(
body.premiacion,
'premiacion',
true
);
const fecha = validar.validarFecha(body.fecha, 'fecha', true);
if (!body.hora) throw new Error('Falta la hora.');
const hora = body.hora;
const res = await Premiacion.create({ premiacion, fecha, hora, activa: true });
return res;
};
module.exports = nueva;
@@ -0,0 +1,5 @@
const Premiacion = require('../../db/tablas/Premiacion');
const get = () => Premiacion.findAll();
module.exports = get;
+2 -1
View File
@@ -10,7 +10,8 @@ const adscripciones = async () => {
result.push(item.adscripcion);
}
});
return result
return result;
});
};
module.exports = adscripciones;
+14 -5
View File
@@ -1,8 +1,11 @@
const csv = require('csvtojson');
const { eliminarArchivo } = require('../../helper/helper');
const Profesor = require('../../db/tablas/Profesor');
const { validarNumeroEntero } = require('../../helper/validar');
const ProfesorPremiacion = require('../../db/tablas/profesorPremiacion');
const cargaMasiva = async (file) => {
const cargaMasiva = async (file, body) => {
const idPremiacion = validarNumeroEntero(body.idPremiacion);
const path = `server/uploads/${file}`;
let res = [];
@@ -15,15 +18,21 @@ const cargaMasiva = async (file) => {
nombre: profesores[i].nombre,
correo: `${profesores[i].numeroTrabajador}@pcpuma.acatlan.unam.mx`,
adscripcion: profesores[i].adscripcion,
})
res.push(resp)
});
res.push(resp);
await ProfesorPremiacion.create({
idPremiacion,
idProfesor: resp.idProfesor,
numeroInvitados: null,
numeroInvitadosDentro: null,
});
}
await eliminarArchivo(path);
});
return {
message: 'Se subió correctamente el archivo csv.',
res
res,
};
};
module.exports = cargaMasiva;
module.exports = cargaMasiva;
+22 -6
View File
@@ -1,21 +1,37 @@
const Profesor = require('../../db/tablas/Profesor');
const ProfesorPremiacion = require('../../db/tablas/ProfesorPremiacion');
const validar = require('../../helper/validar');
const entradaInvitado = async (body) => {
const idProfesor = validar.validarNumeroEntero(body.idProfesor, 'idProfesor');
const idPremiacion = validar.validarNumeroEntero(
body.idPremiacion,
'idPremiacion'
);
const profesor = await Profesor.findOne({ where: idProfesor });
if (!profesor) throw new Error('Este profesor no existe');
if (!profesor.noInvitados) throw new Error('Este profesor no registró a ninún invitado.')
let noInvDentro = profesor.dataValues.numeroInvitadosDentro;
let noInv = profesor.dataValues.numeroInvitados;
if (!profesor) throw new Error('Este profesor no existe.');
const profPrem = await ProfesorPremiacion.findOne({
where: { idPremiacion, idProfesor },
});
if (!profPrem)
throw new Error(
'Este profesor no está registrado en esta entrega de medallas.'
);
if (!profPrem.numeroInvitados)
throw new Error('Este profesor no registró a ninún invitado.');
let noInvDentro = profPrem.dataValues.numeroInvitadosDentro;
let noInv = profPrem.dataValues.numeroInvitados;
if (noInvDentro && noInvDentro >= noInv)
throw new Error('Este profesor ya ingreso a todos sus invitados.');
const res = await profesor.update({ numeroInvitadosDentro: noInvDentro + 1 });
const res = await profPrem.update({ numeroInvitadosDentro: noInvDentro + 1 });
if (!res)
throw new Error(
'Ha ocurrido un error al actualizar los datos del profesor.'
'Ha ocurrido un error al registrar los invitados del profesor.'
);
return res;
};
+9 -7
View File
@@ -8,15 +8,17 @@ const login = async (body) => {
'numero de trabajador',
true
);
const adscripcion = validar.validacionBasicaStr(
body.adscripcion,
'adscripcion',
false,
150
);
// const adscripcion = validar.validacionBasicaStr(
// body.adscripcion,
// 'adscripcion',
// false,
// 150
// );
return Profesor.findOne({
where: { numeroTrabajador, adscripcion },
where: { numeroTrabajador
// , adscripcion
},
}).then((res) => {
if (!res) throw new Error('No existe este profesor en la base de datos.');
return {
+22 -4
View File
@@ -1,10 +1,11 @@
const Usuario = require('./tablas/Usuario');
const Profesor = require('./tablas/Profesor');
const Premiacion = require('./tablas/Premiacion');
const { encriptar } = require('../helper/encriptar');
const dataUsuarios = async () => {
let usuario = ['416313221', '111111111', '222222222'];
let nombre = ['Adriana De Luna Ramirez', 'Nombre Falso 1', 'Nombre Falso 2'];
let usuario = ['416313221', '111111111'];
let nombre = ['Adriana De Luna Ramirez', 'Nombre Falso 1'];
for (let i = 0; i < usuario.length; i++) {
await Usuario.create({
@@ -17,6 +18,23 @@ const dataUsuarios = async () => {
}
};
const dataPremiaciones = async () => {
let premiacion = ['premiacion 1', 'premiacion 2', 'premiacion 3'];
let fecha = ['2022-06-10', '2023-06-10', '2024-06-10'];
let hora = ['12:00', '13:00', '14:00'];
for (let i = 0; i < premiacion.length; i++) {
await Premiacion.create({
premiacion: premiacion[i],
fecha: fecha[i],
hora: hora[i],
activa: true,
});
console.log(`Se insertó la premiacion ${premiacion[i]}.`.magenta);
}
};
const dataProfesores = async () => {
let usuario = ['4163132', '123456778', '1234567890'];
let adscripcion = ['Adscripcion 1', 'Adscripcion 2', 'Adscripcion 3'];
@@ -28,8 +46,7 @@ const dataProfesores = async () => {
numeroTrabajador: usuario[i],
adscripcion: adscripcion[i],
nombre: nombre[i],
correo: correo[i],
numeroInvitados: null,
correo: correo[i]
});
console.log(`Se insertó el profesor ${usuario[i]}.`.magenta);
}
@@ -38,6 +55,7 @@ const dataProfesores = async () => {
const exec = async () => {
await dataUsuarios();
await dataProfesores();
await dataPremiaciones();
console.log(
'\nSe ha instalado exitosamente la información falsa en la base de datos.\n'
.underline.bold.green
+15 -1
View File
@@ -5,6 +5,8 @@ const TipoUsuario = require('./tablas/TipoUsuario');
const Usuario = require('./tablas/Usuario');
const Profesor = require('./tablas/Profesor');
const Invitado = require('./tablas/Invitado');
const Premiacion = require('./tablas/Premiacion');
const ProfesorPremiacion = require('./tablas/ProfesorPremiacion');
const drop = async () => {
console.log('\nPaso 1) Desinstalando la db.'.bold.blue);
@@ -18,15 +20,27 @@ const drop = async () => {
await TipoUsuario.drop();
console.log('La tabla TipoUsuario se desinstalo correctamente.'.magenta);
await ProfesorPremiacion.drop();
console.log('La tabla ProfesorPremiacion se desinstalo correctamente.'.magenta);
await Profesor.drop();
console.log('La tabla Profesor se desinstalo correctamente.'.magenta);
await Premiacion.drop();
console.log('La tabla Premiacion se desinstalo correctamente.'.magenta);
};
const sync = async () => {
console.log('\nPaso 2) Instalando la db.'.bold.blue);
await Premiacion.sync();
console.log('La tabla Premiacion se instalo correctamente.'.magenta);
await Profesor.sync();
console.log('La tabla Profesor se instalo correctamente.'.magenta);
await ProfesorPremiacion.sync();
console.log('La tabla ProfesorPremiacion se instalo correctamente.'.magenta);
await TipoUsuario.sync();
console.log('La tabla TipoUsuario se instalo correctamente.'.magenta);
@@ -39,7 +53,7 @@ const sync = async () => {
};
const dataTipoUsuario = async () => {
const data = ['admin', 'operador', 'profesor'];
const data = ['admin', 'operador'];
console.log('\nPaso 3) Instalando catalogo tipo usuario.'.bold.blue);
for (let i = 0; i < data.length; i++)
+8
View File
@@ -15,10 +15,18 @@ Premiacion.init(
type: DataTypes.STRING(50),
allowNull: false,
},
hora: {
type: DataTypes.STRING(5),
allowNull: false,
},
fecha: {
type: DataTypes.DATEONLY,
allowNull: false,
},
activa: {
type: DataTypes.BOOLEAN,
allowNull: false
}
},
{
sequelize,
-10
View File
@@ -8,13 +8,11 @@ Profesor.init(
type: DataTypes.INTEGER,
primaryKey: true,
allowNull: false,
unique: true,
autoIncrement: true,
},
numeroTrabajador: {
type: DataTypes.STRING(10),
allowNull: false,
unique: true,
},
nombre: {
type: DataTypes.STRING(50),
@@ -29,14 +27,6 @@ Profesor.init(
allowNull: true,
defaultValue: null,
},
numeroInvitados: {
type: DataTypes.INTEGER,
allowNull: true,
},
numeroInvitadosDentro: {
type: DataTypes.INTEGER,
allowNull: true,
},
},
{
sequelize,
+48
View File
@@ -0,0 +1,48 @@
const { DataTypes, Model } = require('sequelize');
const sequelize = require('../../config/sequelize.conf');
const Premiacion = require('./Premiacion');
const Profesor = require('./Profesor');
class ProfesorPremiacion extends Model {}
ProfesorPremiacion.init(
{
idProfesorPremiacion: {
type: DataTypes.INTEGER,
primaryKey: true,
allowNull: false,
autoIncrement: true,
},
numeroInvitados: {
type: DataTypes.INTEGER,
allowNull: true,
},
numeroInvitadosDentro: {
type: DataTypes.INTEGER,
allowNull: true,
},
},
{
sequelize,
modelName: 'ProfesorPremiacion',
tableName: 'profesor_premiacion',
timestamps: false,
}
);
ProfesorPremiacion.belongsTo(Profesor, {
foreignKey: {
name: 'idProfesor',
type: DataTypes.INTEGER,
allowNull: false,
},
});
ProfesorPremiacion.belongsTo(Premiacion, {
foreignKey: {
name: 'idPremiacion',
type: DataTypes.INTEGER,
allowNull: false,
},
});
module.exports = ProfesorPremiacion;
+12 -18
View File
@@ -1,45 +1,39 @@
const moment = require('moment');
const correo = (nombre, numeroTrabajador, numeroInvitados) => {
const correo = (idProfesor, idPremiacion, premiacion, fecha, hora) => {
// const fecha = moment(date);
return {
subject: `Comprobante de registro invitados.`,
message: `<h2>Estimada(o) profesor(o) </h2>
message: `<h2>Distinguido(a) galardonado(a): </h2>
<div style="font-size: 15px;">
<p>
Gracias por registrarte para participar en este recorrido por la FES Acatlán, tu Facultad. La cita es en
la entrada peatonal (sobre Av. San Juan Totoltepec), el próximo <b>h</b>. Te pedimos
asistir en la fecha y horarios elegidos (no puedes modificarlos).
¡El registro de sus invitados para la ceremonia de ${premiacion}, programada para el ${fecha} a las ${hora} hrs. ha sido exitoso!
</p>
<p>Te solicitamos atender las siguientes medidas:</p>
<p>Le pedimos compartir el siguiente código QR con las personas registradas, pues será su acceso al Teatro Javier Barros Sierra. Podrán presentarlo impreso, o digital en su celular. Será importante atender las siguientes consideraciones:</p>
<ul>
<li>Programa tu llegada 10 min. antes de la hora de tu cita.</li>
<li>Se dará acceso a sus invitados 30 min. previos al inicio del evento, y podrán ocupar los asientos no reservados que les sean indicados por el personal logístico.</li>
<li>El uso de cubrebocas es obligatorio en todo momento.</li>
<li>Para el ingreso y permanencia en el recinto, será obligatorio portar de manera correcta el cubrebocas en todo momento.</li>
<li>Presenta al ingreso este “Comprobante de registro para recorrido”, puede ser en formato impreso o digital.</li>
<li>Usted deberá compartir el código QR únicamente con sus invitados registrados, sólo se dará acceso a las tres primeras personas que lo presenten en la puerta de ingreso.</li>
<li>No se permitirán acompañantes durante el recorrido.</li>
<li>Las fotografías tomadas durante el evento por la Coordinación de Comunicación Social estarán disponibles en el perfil institucional de Facebook.</li>
<li>Acude con ropa cómoda y agua para estar bien hidratada(o).</li>
<img src="https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=https://api.qrserver.com/v1/create-qr-code/?size=200x200&data={%idProfesor%22:%22${idProfesor}%22,%22idPremiacion%22:${idPremiacion}}" alt="qr_img" />
<li>Si acudes en auto, sólo se permitirá tu ingreso (sin acompañantes) por el acceso vehicular sobre la avenida San Juan Totoltepec, junto a la Plaza San Mateo.</li>
</ul>
<p>¡Estaremos felices de recibirte!</p>
<p>¡Será un gusto contar con su puntual asistencia!</p>
<p><i>"Por mi raza hablará el espíritu"</i></p>
<p><i>"Por mi raza hablará el espíritu"</i></p>
<p><b><i>Facultad de Estudios Superiores Acatlán</i></b></p>
<p><b><i>Facultad de Estudios Superiores Acatlán</i></b></p>
</div>
`,
};
};
// <img src="https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=https://api.qrserver.com/v1/create-qr-code/?size=200x200&data={%22numeroCuenta%22:%22${numeroCuenta}%22,%22idAlumno%22:${idAlumno}}" alt="qr_img" />
module.exports = { correo };
+1 -11
View File
@@ -7,7 +7,7 @@ const get = require(`${controllerPath}/invitados`);
const infoInvitados = require(`${controllerPath}/infoInvitados`);
app.get(`${route}/get`, (req, res) => {
return get()
return get(req.query)
.then((data) => {
res.status(200).json(data);
})
@@ -26,14 +26,4 @@ app.post(`${route}/infoInvitados`, (req, res) => {
});
});
// app.post(`${route}/entradaInvitado`, (req, res) => {
// return entradaInvitado(req.body)
// .then((data) => {
// res.status(200).json(data);
// })
// .catch((err) => {
// res.status(400).json({ message: err.message });
// });
// });
module.exports = app;
+51
View File
@@ -0,0 +1,51 @@
const express = require('express');
const app = express();
// const { verificaToken } = require('../middleware/autentificacion');
const route = '/premiacion';
const controllerPath = '../controller/Premiacion';
const get = require(`${controllerPath}/premiaciones`);
const editar = require(`${controllerPath}/editar`);
const nueva = require(`${controllerPath}/nueva`);
const activarDesactivar = require(`${controllerPath}/activarDesactivar`);
app.get(`${route}/get`, (req, res) => {
return get()
.then((data) => {
res.status(200).json(data);
})
.catch((err) => {
res.status(400).json({ message: err.message });
});
});
app.post(`${route}/nueva`, (req, res) => {
return nueva(req.body)
.then((data) => {
res.status(200).json(data);
})
.catch((err) => {
res.status(400).json({ message: err.message });
});
});
app.put(`${route}/editar`, (req, res) => {
return editar(req.body)
.then((data) => {
res.status(200).json(data);
})
.catch((err) => {
res.status(400).json({ message: err.message });
});
});
app.put(`${route}/activarDesactivar`, (req, res) => {
return activarDesactivar(req.body)
.then((data) => {
res.status(200).json(data);
})
.catch((err) => {
res.status(400).json({ message: err.message });
});
});
module.exports = app;
+1 -1
View File
@@ -46,7 +46,7 @@ app.post(
upload.single('file'),
(req, res) => {
if (req.file) {
return cargarDatos(req.file.filename)
return cargarDatos(req.file.filename, req.body)
.then((data) => {
res.status(201).json(data);
})
-10
View File
@@ -27,14 +27,4 @@ app.post(`${route}/loginOperador`, (req, res) => {
});
});
// app.post(`${route}/entradaInvitado`, (req, res) => {
// return entradaInvitado(req.body)
// .then((data) => {
// res.status(200).json(data);
// })
// .catch((err) => {
// res.status(400).json({ message: err.message });
// });
// });
module.exports = app;
+1
View File
@@ -4,5 +4,6 @@ const app = express();
app.use(require("./Usuario"));
app.use(require("./Profesor"));
app.use(require("./Invitado"));
app.use(require("./Premiacion"));
module.exports = app;
@@ -0,0 +1,5 @@
numeroTrabajador,nombre,adscripcion
3910347492,Marco Antonio Romero,Adscripcion 1
8414319744,Jeremy Carreras,Adscripcion 2
3916067492,Marco Antonio Romero,Adscripcion 1
8414519004,Jeremy Carreras,Adscripcion 2
@@ -0,0 +1,5 @@
numeroTrabajador,nombre,adscripcion
3910347492,Marco Antonio Romero,Adscripcion 1
8414319744,Jeremy Carreras,Adscripcion 2
3916067492,Marco Antonio Romero,Adscripcion 1
8414519004,Jeremy Carreras,Adscripcion 2
@@ -0,0 +1,5 @@
numeroTrabajador,nombre,adscripcion
3910347492,Marco Antonio Romero,Adscripcion 1
8414319744,Jeremy Carreras,Adscripcion 2
3916067492,Marco Antonio Romero,Adscripcion 1
8414519004,Jeremy Carreras,Adscripcion 2
@@ -0,0 +1,5 @@
numeroTrabajador,nombre,adscripcion
3910347492,Marco Antonio Romero,Adscripcion 1
8414319744,Jeremy Carreras,Adscripcion 2
3916067492,Marco Antonio Romero,Adscripcion 1
8414519004,Jeremy Carreras,Adscripcion 2
@@ -0,0 +1,5 @@
numeroTrabajador,nombre,adscripcion
3910347492,Marco Antonio Romero,Adscripcion 1
8414319744,Jeremy Carreras,Adscripcion 2
3916067492,Marco Antonio Romero,Adscripcion 1
8414519004,Jeremy Carreras,Adscripcion 2
@@ -0,0 +1,5 @@
numeroTrabajador,nombre,adscripcion
3910347492,Marco Antonio Romero,Adscripcion 1
8414319744,Jeremy Carreras,Adscripcion 2
3916067492,Marco Antonio Romero,Adscripcion 1
8414519004,Jeremy Carreras,Adscripcion 2
@@ -0,0 +1,5 @@
numeroTrabajador,nombre,adscripcion
3910347492,Marco Antonio Romero,Adscripcion 1
8414319744,Jeremy Carreras,Adscripcion 2
3916067492,Marco Antonio Romero,Adscripcion 1
8414519004,Jeremy Carreras,Adscripcion 2
@@ -0,0 +1,5 @@
numeroTrabajador,nombre,adscripcion
3910347492,Marco Antonio Romero,Adscripcion 1
8414319744,Jeremy Carreras,Adscripcion 2
3916067492,Marco Antonio Romero,Adscripcion 1
8414519004,Jeremy Carreras,Adscripcion 2
@@ -0,0 +1,5 @@
numeroTrabajador,nombre,adscripcion
3910347492,Marco Antonio Romero,Adscripcion 1
8414319744,Jeremy Carreras,Adscripcion 2
3916067492,Marco Antonio Romero,Adscripcion 1
8414519004,Jeremy Carreras,Adscripcion 2