From bc146595a9343e2a3b182b52c2bc2aba3d3008d5 Mon Sep 17 00:00:00 2001 From: xXpuma99Xx <51341582+xXpuma99Xx@users.noreply.github.com> Date: Mon, 17 Jan 2022 18:28:01 -0600 Subject: [PATCH 01/21] querries traen solo lo que necesitan --- package-lock.json | 98 ++++++++++--------- .../controller/CasoEspecial/casoEspecial.js | 25 ++++- .../CasoEspecial/serviciosEspeciales.js | 9 +- server/controller/Servicio/admin.js | 51 ++++++++-- server/controller/Servicio/alumno.js | 42 +++++--- server/controller/Servicio/serviciosAdmin.js | 23 +---- .../Servicio/serviciosResponsable.js | 26 +---- server/controller/Usuario/login.js | 37 ++++--- server/controller/Usuario/responsable.js | 5 +- server/controller/Usuario/responsables.js | 9 +- 10 files changed, 180 insertions(+), 145 deletions(-) diff --git a/package-lock.json b/package-lock.json index 0931f0a..5a08a42 100644 --- a/package-lock.json +++ b/package-lock.json @@ -90,9 +90,9 @@ "integrity": "sha512-iiUgKzV9AuaEkZqkOLDIvlQiL6ltuZd9tGcW3gwpnX8JbuiuhFlEGmmFXEXkN50Cvq7Os88IY2v0dkDqXYWVgA==" }, "node_modules/@types/node": { - "version": "14.18.4", - "resolved": "https://registry.npmjs.org/@types/node/-/node-14.18.4.tgz", - "integrity": "sha512-swe3lD4izOJWHuxvsZdDFRq6S9i6koJsXOnQKYekhSO5JTizMVirUFgY/bUsaOJQj8oSD4oxmRYPBM/0b6jpdw==" + "version": "14.18.7", + "resolved": "https://registry.npmjs.org/@types/node/-/node-14.18.7.tgz", + "integrity": "sha512-UpLEO1iBG7esNPusSAjoZhWFK5Mfd8QfwWhHRrg5io13POn/stsBgTCba9suQaFflNA4tc0+6AFM3R6BZNng6A==" }, "node_modules/abbrev": { "version": "1.1.1", @@ -1008,9 +1008,9 @@ } }, "node_modules/follow-redirects": { - "version": "1.14.6", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.6.tgz", - "integrity": "sha512-fhUl5EwSJbbl8AR+uYL2KQDxLkdSjZGR36xy46AO7cOMTrCMON6Sa28FmAnC2tRTDbd/Uuzz3aJBv7EBN7JH8A==", + "version": "1.14.7", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.7.tgz", + "integrity": "sha512-+hbxoLbFMbRKDwohX8GkTataGqO6Jb7jGwpAlwgy2bIz25XtRm7KEzJM76R1WiNT5SwZkX4Y75SwBolkpmE7iQ==", "funding": [ { "type": "individual", @@ -1205,11 +1205,11 @@ } }, "node_modules/google-p12-pem": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/google-p12-pem/-/google-p12-pem-3.1.2.tgz", - "integrity": "sha512-tjf3IQIt7tWCDsa0ofDQ1qqSCNzahXDxdAGJDbruWqu3eCg5CKLYKN+hi0s6lfvzYZ1GDVr+oDF9OOWlDSdf0A==", + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/google-p12-pem/-/google-p12-pem-3.1.3.tgz", + "integrity": "sha512-MC0jISvzymxePDVembypNefkAQp+DRP7dBE+zNUPaIjEspIlYg0++OrsNr248V9tPbz6iqtZ7rX1hxWA5B8qBQ==", "dependencies": { - "node-forge": "^0.10.0" + "node-forge": "^1.0.0" }, "bin": { "gp12-pem": "build/src/bin/gp12-pem.js" @@ -1269,9 +1269,9 @@ } }, "node_modules/graceful-fs": { - "version": "4.2.8", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.8.tgz", - "integrity": "sha512-qkIilPUYcNhJpd33n0GBXTB1MMPp14TxEsEs0pTrsSVucApsYzW5V+Q8Qxhik6KU3evy+qkAAowTByymK0avdg==", + "version": "4.2.9", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.9.tgz", + "integrity": "sha512-NtNxqUcXgpW2iMrfqSfR73Glt39K+BLwWsPs94yR63v45T0Wbej7eRmL5cWfwEgqXnmjQp3zaJTshdRW/qC2ZQ==", "dev": true }, "node_modules/gtoken": { @@ -1967,22 +1967,30 @@ "integrity": "sha512-mmcei9JghVNDYydghQmeDX8KoAm0FAiYyIcUt/N4nhyAipB17pllZQDOJD2fotxABnt4Mdz+dKTO7eftLg4d0A==" }, "node_modules/node-fetch": { - "version": "2.6.6", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.6.tgz", - "integrity": "sha512-Z8/6vRlTUChSdIgMa51jxQ4lrw/Jy5SOW10ObaA47/RElsAN2c5Pn8bTgFGWn/ibwzXTE8qwr1Yzx28vsecXEA==", + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz", + "integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==", "dependencies": { "whatwg-url": "^5.0.0" }, "engines": { "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } } }, "node_modules/node-forge": { - "version": "0.10.0", - "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-0.10.0.tgz", - "integrity": "sha512-PPmu8eEeG9saEUvI97fm4OYxXVB6bFvyNTyiUOBichBpFG8A1Ljw3bY62+5oOjDEMHRnd0Y7HQ+x7uzxOzC6JA==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.2.1.tgz", + "integrity": "sha512-Fcvtbb+zBcZXbTTVwqGA5W+MKBj56UjVRevvchv5XrcyXbmNdesfZL37nlcWOfpgHhgmxApw3tQbTr4CqNmX4w==", "engines": { - "node": ">= 6.0.0" + "node": ">= 6.13.0" } }, "node_modules/nodemailer": { @@ -2471,9 +2479,9 @@ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" }, "node_modules/sequelize": { - "version": "6.12.4", - "resolved": "https://registry.npmjs.org/sequelize/-/sequelize-6.12.4.tgz", - "integrity": "sha512-P2E8TzlV3VwdvPqTS58ctIpcAOytXdaylUUfxxnALjtMmF6I+kfNtrqTP7WQFaenOboAtXPCJReZ9MPy+Zy/Ig==", + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/sequelize/-/sequelize-6.13.0.tgz", + "integrity": "sha512-p0dXXGZSc0Ng7CdGwlKN4P6DTRD/w9Ar2CnmHamNVDnqEWh6pMVOp3xrlG5+IWhbwrqL3SjIYEYt3Xog1vXRDw==", "funding": [ { "type": "opencollective", @@ -3051,9 +3059,9 @@ "integrity": "sha512-iiUgKzV9AuaEkZqkOLDIvlQiL6ltuZd9tGcW3gwpnX8JbuiuhFlEGmmFXEXkN50Cvq7Os88IY2v0dkDqXYWVgA==" }, "@types/node": { - "version": "14.18.4", - "resolved": "https://registry.npmjs.org/@types/node/-/node-14.18.4.tgz", - "integrity": "sha512-swe3lD4izOJWHuxvsZdDFRq6S9i6koJsXOnQKYekhSO5JTizMVirUFgY/bUsaOJQj8oSD4oxmRYPBM/0b6jpdw==" + "version": "14.18.7", + "resolved": "https://registry.npmjs.org/@types/node/-/node-14.18.7.tgz", + "integrity": "sha512-UpLEO1iBG7esNPusSAjoZhWFK5Mfd8QfwWhHRrg5io13POn/stsBgTCba9suQaFflNA4tc0+6AFM3R6BZNng6A==" }, "abbrev": { "version": "1.1.1", @@ -3771,9 +3779,9 @@ } }, "follow-redirects": { - "version": "1.14.6", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.6.tgz", - "integrity": "sha512-fhUl5EwSJbbl8AR+uYL2KQDxLkdSjZGR36xy46AO7cOMTrCMON6Sa28FmAnC2tRTDbd/Uuzz3aJBv7EBN7JH8A==" + "version": "1.14.7", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.7.tgz", + "integrity": "sha512-+hbxoLbFMbRKDwohX8GkTataGqO6Jb7jGwpAlwgy2bIz25XtRm7KEzJM76R1WiNT5SwZkX4Y75SwBolkpmE7iQ==" }, "forwarded": { "version": "0.2.0", @@ -3908,11 +3916,11 @@ } }, "google-p12-pem": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/google-p12-pem/-/google-p12-pem-3.1.2.tgz", - "integrity": "sha512-tjf3IQIt7tWCDsa0ofDQ1qqSCNzahXDxdAGJDbruWqu3eCg5CKLYKN+hi0s6lfvzYZ1GDVr+oDF9OOWlDSdf0A==", + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/google-p12-pem/-/google-p12-pem-3.1.3.tgz", + "integrity": "sha512-MC0jISvzymxePDVembypNefkAQp+DRP7dBE+zNUPaIjEspIlYg0++OrsNr248V9tPbz6iqtZ7rX1hxWA5B8qBQ==", "requires": { - "node-forge": "^0.10.0" + "node-forge": "^1.0.0" } }, "googleapis": { @@ -3957,9 +3965,9 @@ } }, "graceful-fs": { - "version": "4.2.8", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.8.tgz", - "integrity": "sha512-qkIilPUYcNhJpd33n0GBXTB1MMPp14TxEsEs0pTrsSVucApsYzW5V+Q8Qxhik6KU3evy+qkAAowTByymK0avdg==", + "version": "4.2.9", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.9.tgz", + "integrity": "sha512-NtNxqUcXgpW2iMrfqSfR73Glt39K+BLwWsPs94yR63v45T0Wbej7eRmL5cWfwEgqXnmjQp3zaJTshdRW/qC2ZQ==", "dev": true }, "gtoken": { @@ -4504,17 +4512,17 @@ "integrity": "sha512-mmcei9JghVNDYydghQmeDX8KoAm0FAiYyIcUt/N4nhyAipB17pllZQDOJD2fotxABnt4Mdz+dKTO7eftLg4d0A==" }, "node-fetch": { - "version": "2.6.6", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.6.tgz", - "integrity": "sha512-Z8/6vRlTUChSdIgMa51jxQ4lrw/Jy5SOW10ObaA47/RElsAN2c5Pn8bTgFGWn/ibwzXTE8qwr1Yzx28vsecXEA==", + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz", + "integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==", "requires": { "whatwg-url": "^5.0.0" } }, "node-forge": { - "version": "0.10.0", - "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-0.10.0.tgz", - "integrity": "sha512-PPmu8eEeG9saEUvI97fm4OYxXVB6bFvyNTyiUOBichBpFG8A1Ljw3bY62+5oOjDEMHRnd0Y7HQ+x7uzxOzC6JA==" + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.2.1.tgz", + "integrity": "sha512-Fcvtbb+zBcZXbTTVwqGA5W+MKBj56UjVRevvchv5XrcyXbmNdesfZL37nlcWOfpgHhgmxApw3tQbTr4CqNmX4w==" }, "nodemailer": { "version": "6.7.2", @@ -4888,9 +4896,9 @@ } }, "sequelize": { - "version": "6.12.4", - "resolved": "https://registry.npmjs.org/sequelize/-/sequelize-6.12.4.tgz", - "integrity": "sha512-P2E8TzlV3VwdvPqTS58ctIpcAOytXdaylUUfxxnALjtMmF6I+kfNtrqTP7WQFaenOboAtXPCJReZ9MPy+Zy/Ig==", + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/sequelize/-/sequelize-6.13.0.tgz", + "integrity": "sha512-p0dXXGZSc0Ng7CdGwlKN4P6DTRD/w9Ar2CnmHamNVDnqEWh6pMVOp3xrlG5+IWhbwrqL3SjIYEYt3Xog1vXRDw==", "requires": { "@types/debug": "^4.1.7", "debug": "^4.3.3", diff --git a/server/controller/CasoEspecial/casoEspecial.js b/server/controller/CasoEspecial/casoEspecial.js index 897e516..cc72ed8 100644 --- a/server/controller/CasoEspecial/casoEspecial.js +++ b/server/controller/CasoEspecial/casoEspecial.js @@ -15,16 +15,31 @@ const admin = async (body) => { return CasoEspecial.findOne({ where: { idCasoEspecial }, include: [ - { model: Usuario, include: [{ model: TipoUsuario }] }, + { + model: Usuario, + include: [{ model: TipoUsuario }], + attributes: ['idUsuario', 'usuario', 'nombre'], + }, { model: Carrera }, { model: Status }, ], + attributes: [ + 'idCasoEspecial', + 'creditos', + 'correo', + 'telefono', + 'institucion', + 'dependencia', + 'motivo', + 'direccion', + 'fechaInicio', + 'fechaFin', + 'fechaNacimiento', + 'archivoZip', + 'createdAt', + ], }).then((res) => { if (!res) throw new Error('No existe este Caso Especial.'); - delete res.dataValues.Usuario.dataValues.password; - delete res.dataValues.idUsuario; - delete res.dataValues.idCarrera; - delete res.dataValues.idStatus; return res; }); }; diff --git a/server/controller/CasoEspecial/serviciosEspeciales.js b/server/controller/CasoEspecial/serviciosEspeciales.js index 2ce5d06..b70c730 100644 --- a/server/controller/CasoEspecial/serviciosEspeciales.js +++ b/server/controller/CasoEspecial/serviciosEspeciales.js @@ -35,19 +35,16 @@ const serviciosEspeciales = async (body) => { { nombre: { [Op.like]: `%${nombre}%` } }, ], }, + attributes: ['idUsuario', 'usuario', 'nombre'], }, { model: Carrera }, { model: Status, where }, ], + attributes: ['idCasoEspecial', 'fechaInicio', 'fechaFin', 'createdAt'], order: [['updatedAt', 'DESC']], limit: 25, offset: 25 * (pagina - 1), - }).then((res) => { - for (let i = 0; i < res.rows.length; i++) { - // delete res.rows[i].dataValues.idUsuario - } - return { count: res.count, serviciosEspeciales: res.rows }; - }); + }).then((res) => ({ count: res.count, serviciosEspeciales: res.rows })); }; module.exports = serviciosEspeciales; diff --git a/server/controller/Servicio/admin.js b/server/controller/Servicio/admin.js index 7660940..30d632f 100644 --- a/server/controller/Servicio/admin.js +++ b/server/controller/Servicio/admin.js @@ -13,20 +13,53 @@ const admin = async (body) => { return Servicio.findOne({ where: { idServicio }, include: [ - { model: Usuario, include: [{ model: TipoUsuario }] }, + { + model: Usuario, + include: [{ model: TipoUsuario }], + attributes: ['idUsuario', 'usuario', 'nombre'], + }, { model: Carrera }, { model: Status }, - { model: Programa, include: [{ model: Usuario }] }, + { + model: Programa, + include: [ + { + model: Usuario, + attributes: ['idUsuario', 'usuario', 'nombre'], + }, + ], + attributes: [ + 'idPrograma', + 'institucion', + 'dependencia', + 'programa', + 'clavePrograma', + 'acatlan', + ], + }, + ], + attributes: [ + 'idServicio', + 'creditos', + 'correo', + 'telefono', + 'direccion', + 'fechaInicio', + 'fechaFin', + 'fechaLiberacion', + 'fechaNacimiento', + 'cartaAceptacion', + 'cartaTermino', + 'informeGlobal', + 'programaInterno', + 'profesor', + 'vistoBuenoAcatlan', + 'createdAt', + 'idCuestionarioAlumno', + 'idCuestionarioPrograma', ], }).then((res) => { if (!res) throw new Error('No existe este servicio social.'); - delete res.dataValues.Usuario.dataValues.password; - delete res.dataValues.Programa.dataValues.idUsuario; - delete res.dataValues.Programa.dataValues.Usuario.dataValues.password; - delete res.dataValues.idUsuario; - delete res.dataValues.idCarrera; - delete res.dataValues.idStatus; - delete res.dataValues.idPrograma; return res; }); }; diff --git a/server/controller/Servicio/alumno.js b/server/controller/Servicio/alumno.js index 03e9292..9c19a31 100644 --- a/server/controller/Servicio/alumno.js +++ b/server/controller/Servicio/alumno.js @@ -17,22 +17,40 @@ const alumno = async (body) => { throw new Error('No es un usuario de tipo alumno.'); return Servicio.findOne({ where: { idUsuario, idStatus: { [Op.not]: 10 } }, - include: [{ model: Carrera }, { model: Status }, { model: Programa }], + include: [ + { model: Carrera }, + { model: Status }, + { + model: Programa, + attributes: [ + 'idPrograma', + 'institucion', + 'dependencia', + 'programa', + 'clavePrograma', + ], + }, + ], + attributes: [ + 'idServicio', + 'creditos', + 'correo', + 'telefono', + 'direccion', + 'fechaInicio', + 'fechaFin', + 'fechaLiberacion', + 'fechaNacimiento', + 'informeGlobal', + 'programaInterno', + 'profesor', + 'createdAt', + 'idCuestionarioAlumno', + ], }); }) .then((res) => { if (!res) throw new Error('No existe este servicio social.'); - delete res.dataValues.idUsuario; - delete res.dataValues.idCarrera; - delete res.dataValues.idStatus; - delete res.dataValues.idPrograma; - delete res.dataValues.updatedAt; - delete res.dataValues.carpeta; - delete res.dataValues.cartaAceptacion; - delete res.dataValues.cartaTermino; - delete res.dataValues.vistoBuenoAcatlan; - delete res.dataValues.idCuestionarioPrograma; - delete res.dataValues.Programa.idUsuario; return res; }); }; diff --git a/server/controller/Servicio/serviciosAdmin.js b/server/controller/Servicio/serviciosAdmin.js index e459b6c..7aab32a 100644 --- a/server/controller/Servicio/serviciosAdmin.js +++ b/server/controller/Servicio/serviciosAdmin.js @@ -36,33 +36,16 @@ const serviciosAdmin = async (body) => { { nombre: { [Op.like]: `%${nombre}%` } }, ], }, + attributes: ['idUsuario', 'usuario', 'nombre'], }, { model: Carrera }, { model: Status, where }, ], + attributes: ['idServicio', 'fechaInicio', 'fechaFin', 'createdAt'], order: [['updatedAt', 'DESC']], limit: 25, offset: 25 * (pagina - 1), - }).then((res) => { - let data = []; - - for (let i = 0; i < res.rows.length; i++) { - data.push({ - idServicio: res.rows[i].idServicio, - fechaInicio: moment(res.rows[i].fechaInicio).format(), - fechaFin: moment(res.rows[i].fechaFin).format(), - createdAt: moment(res.rows[i].createdAt).format(), - Usuario: { - idUsuario: res.rows[i].Usuario.idUsuario, - usuario: res.rows[i].Usuario.usuario, - nombre: res.rows[i].Usuario.nombre, - }, - Carrera: res.rows[i].Carrera, - Status: res.rows[i].Status, - }); - } - return { count: res.count, serviciosAdmin: data }; - }); + }).then((res) => ({ count: res.count, serviciosAdmin: res.rows })); }; module.exports = serviciosAdmin; diff --git a/server/controller/Servicio/serviciosResponsable.js b/server/controller/Servicio/serviciosResponsable.js index f15afac..34ccbed 100644 --- a/server/controller/Servicio/serviciosResponsable.js +++ b/server/controller/Servicio/serviciosResponsable.js @@ -36,7 +36,7 @@ const serviciosResponsable = async (body) => { throw new Error('No es un usuario tipo responsable.'); return Servicio.findAndCountAll({ include: [ - { model: Programa, where: { idUsuario } }, + { model: Programa, where: { idUsuario }, attributes: [] }, { model: Usuario, where: { @@ -45,36 +45,18 @@ const serviciosResponsable = async (body) => { { nombre: { [Op.like]: `%${nombre}%` } }, ], }, + attributes: ['idUsuario', 'usuario', 'nombre'], }, { model: Carrera }, { model: Status, where }, ], + attributes: ['idServicio', 'fechaInicio', 'fechaFin', 'createdAt'], order: [['updatedAt', 'DESC']], limit: 25, offset: 25 * (pagina - 1), }); }) - .then((res) => { - let data = []; - - for (let i = 0; i < res.rows.length; i++) { - data.push({ - idServicio: res.rows[i].idServicio, - fechaInicio: moment(res.rows[i].fechaInicio).format(), - fechaFin: moment(res.rows[i].fechaFin).format(), - cartaTermino: res.rows[i].cartaTermino, - idCuestionarioPrograma: res.rows[i].idCuestionarioPrograma, - Usuario: { - idUsuario: res.rows[i].Usuario.idUsuario, - usuario: res.rows[i].Usuario.usuario, - nombre: res.rows[i].Usuario.nombre, - }, - Carrera: res.rows[i].Carrera, - Status: res.rows[i].Status, - }); - } - return { count: res.count, serviciosResponsable: data }; - }); + .then((res) => ({ count: res.count, serviciosResponsable: res.rows })); }; module.exports = serviciosResponsable; diff --git a/server/controller/Usuario/login.js b/server/controller/Usuario/login.js index b6314ef..d0c8682 100644 --- a/server/controller/Usuario/login.js +++ b/server/controller/Usuario/login.js @@ -1,5 +1,6 @@ -const validar = require('../../helper/validar'); const { crearToken } = require('../../middleware/autentificacion'); +// const validarPath = '../../db/tablas'; +const validar = require('../../helper/validar'); const { comparar } = require('../../helper/encriptar'); const dbPath = '../../db/tablas'; const Usuario = require(`${dbPath}/Usuario`); @@ -21,20 +22,26 @@ const login = async (body) => { return Usuario.findOne({ where: { usuario }, - include: [{ model: TipoUsuario }], - }).then((res) => { - if (!res) throw new Error('No existe este usuario.'); - if (!res.activo) throw new Error('Este usuario no esta activo.'); - if (comparar(password, res.password)) { - delete res.dataValues.password; - delete res.dataValues.activo; - return { - Usuario: res, - token: crearToken(res.idUsuario), - }; - } - throw new Error('La contraseña es incorrecta'); - }); + attributes: ['idUsuario', 'activo', 'password'], + }) + .then((res) => { + if (!res) throw new Error('No existe este usuario.'); + if (!res.activo) throw new Error('Este usuario no esta activo.'); + if (!comparar(password, res.password)) + throw new Error('La contraseña es incorrecta'); + return Usuario.findOne({ + where: { idUsuario: res.idUsuario }, + include: [{ model: TipoUsuario }], + attributes: ['idUsuario', 'usuario', 'nombre'], + }); + }) + .then((res) => ({ + Usuario: res, + token: crearToken({ + idUsuario: res.idUsuario, + idTipoUsuario: res.TipoUsuario.idTipoUsuario, + }), + })); }; module.exports = login; diff --git a/server/controller/Usuario/responsable.js b/server/controller/Usuario/responsable.js index a35c7dc..4427dca 100644 --- a/server/controller/Usuario/responsable.js +++ b/server/controller/Usuario/responsable.js @@ -6,10 +6,7 @@ const responsable = async (body) => { return Usuario.findOne({ where: { idUsuario }, - }).then((res) => { - delete res.dataValues.password; - delete res.dataValues.idTipoUsuario; - return res; + attributes: ['idUsuario', 'usuario', 'nombre', 'activo'], }); }; diff --git a/server/controller/Usuario/responsables.js b/server/controller/Usuario/responsables.js index b3478bd..a068f5f 100644 --- a/server/controller/Usuario/responsables.js +++ b/server/controller/Usuario/responsables.js @@ -26,15 +26,10 @@ const responsables = async (body) => { { idTipoUsuario: 2 }, ], }, + attributes: ['idUsuario', 'usuario', 'nombre', 'activo'], limit: 25, offset: 25 * (pagina - 1), - }).then((res) => { - for (let i = 0; i < res.rows.length; i++) { - delete res.rows[i].dataValues.password; - delete res.rows[i].dataValues.idTipoUsuario; - } - return { count: res.count, responsables: res.rows }; - }); + }).then((res) => ({ count: res.count, responsables: res.rows })); }; module.exports = responsables; -- 2.43.0 From 3b18b3a8c201da9218f7795b29b176390d292b14 Mon Sep 17 00:00:00 2001 From: xXpuma99Xx <51341582+xXpuma99Xx@users.noreply.github.com> Date: Mon, 17 Jan 2022 18:56:54 -0600 Subject: [PATCH 02/21] corregido --- server/controller/Servicio/serviciosResponsable.js | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/server/controller/Servicio/serviciosResponsable.js b/server/controller/Servicio/serviciosResponsable.js index 34ccbed..54139ae 100644 --- a/server/controller/Servicio/serviciosResponsable.js +++ b/server/controller/Servicio/serviciosResponsable.js @@ -50,7 +50,14 @@ const serviciosResponsable = async (body) => { { model: Carrera }, { model: Status, where }, ], - attributes: ['idServicio', 'fechaInicio', 'fechaFin', 'createdAt'], + attributes: [ + 'idServicio', + 'fechaInicio', + 'fechaFin', + 'cartaTermino', + 'createdAt', + 'idCuestionarioPrograma', + ], order: [['updatedAt', 'DESC']], limit: 25, offset: 25 * (pagina - 1), -- 2.43.0 From 67a23bcef06a6ea1afe0bc67d280fde8e4796b67 Mon Sep 17 00:00:00 2001 From: xXpuma99Xx <51341582+xXpuma99Xx@users.noreply.github.com> Date: Tue, 18 Jan 2022 06:45:12 -0600 Subject: [PATCH 03/21] update servicio actualizar status si se manda carta termino o informe global --- server/controller/Servicio/update.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/server/controller/Servicio/update.js b/server/controller/Servicio/update.js index 4043ecb..cbac17f 100644 --- a/server/controller/Servicio/update.js +++ b/server/controller/Servicio/update.js @@ -79,6 +79,11 @@ const update = async (body, files) => { ); return Servicio.update(dataUpdate, { where: { idServicio } }); }) + .then(async (res) => { + if (dataUpdate.cartaTermino || dataUpdate.informeGlobal) + return validar.validarPreTermino(idServicio); + return false; + }) .then((res) => ({ message: 'Se guardo correctamente los cambios de este servicio.', })); -- 2.43.0 From 329332ad97472e1ec0c5256b734fac71d0751d56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lemuel=20M=C3=A1rquez?= Date: Tue, 25 Jul 2023 17:47:52 -0600 Subject: [PATCH 04/21] listo cambios --- server/helper/drive.js | 195 +++++++++++++++++++++++------------------ 1 file changed, 109 insertions(+), 86 deletions(-) diff --git a/server/helper/drive.js b/server/helper/drive.js index d6c9de0..d3935e9 100644 --- a/server/helper/drive.js +++ b/server/helper/drive.js @@ -1,37 +1,49 @@ require('../config/config'); const fs = require('fs'); const { google } = require('googleapis'); -const drive = google.drive('v3'); -const credenciales = JSON.parse(fs.readFileSync('./cred.json', 'utf8')); -const jwtClient = new google.auth.JWT( - credenciales.client_email, - null, - credenciales.private_key, - ['https://www.googleapis.com/auth/drive'] -); +// const drive = google.drive('v3'); +// const credenciales = JSON.parse(fs.readFileSync('./cred.json', 'utf8')); +// const jwtClient = new google.auth.JWT( +// credenciales.client_email, +// null, +// credenciales.private_key, +// ['https://www.googleapis.com/auth/drive'] +// ); + +const loadCredentials = () => { + try { + const credenciales = JSON.parse(fs.readFileSync('./cred.json', 'utf8')); + return google.auth.fromJSON(credenciales); + } catch (err) { + return null; + } +}; const list = (pageToken) => { - return new Promise((resolve, reject) => { - jwtClient.authorize((err, tokens) => { - if (err) reject('Error de autorización: ' + err); - drive.files.list( - { - auth: jwtClient, - corpora: 'user', - supportsTeamDrives: true, - includeTeamDriveItems: true, - spaces: 'drive', - pageSize: 1000, - pageToken, - // fields: '*', - orderBy: 'name', - }, - (err, resp) => { - if (err) reject('Ha habido un error en la petición: ' + err); - resolve(resp.data); - } - ); - }); + return new Promise(async (resolve, reject) => { + // jwtClient.authorize((err, tokens) => { + // if (err) reject('Error de autorización: ' + err); + const authClient = await loadCredentials(); + const drive = google.drive({ version: 'v3', auth: authClient }); + + drive.files.list( + { + // auth: jwtClient, + corpora: 'user', + supportsTeamDrives: true, + includeTeamDriveItems: true, + spaces: 'drive', + pageSize: 1000, + pageToken, + // fields: '*', + orderBy: 'name', + }, + (err, resp) => { + if (err) reject('Ha habido un error en la petición: ' + err); + resolve(resp.data); + } + ); + // }); }); }; @@ -39,26 +51,29 @@ const list = (pageToken) => { const deleteFile = (fileId) => { if (fileId === process.env.CARPETA) throw new Error('No se puede eliminar este archivo/carpeta.'); - return new Promise((resolve, reject) => { - jwtClient.authorize(async (err, tokens) => { - if (err) reject(err); - drive.files.delete( - { - fileId, - auth: jwtClient, - }, - (err, resp) => { - if (err) reject(err); - resolve(resp); - } - ); - }); + return new Promise(async (resolve, reject) => { + // jwtClient.authorize(async (err, tokens) => { + // if (err) reject(err); + const authClient = await loadCredentials(); + const drive = google.drive({ version: 'v3', auth: authClient }); + + drive.files.delete( + { + fileId, + // auth: jwtClient, + }, + (err, resp) => { + if (err) reject(err); + resolve(resp); + } + ); + // }); }); }; // SUBIR ARCHIVO const uploadFile = (path, name, mimeType, parent) => { - return new Promise((resolve, reject) => { + return new Promise(async (resolve, reject) => { const requestBody = { name, parents: [parent], @@ -68,64 +83,72 @@ const uploadFile = (path, name, mimeType, parent) => { body: fs.createReadStream(`${path}`), }; - jwtClient.authorize(function (err, tokens) { - if (err) reject('Error de autorización: ' + err); - drive.files.create( - { - media, - requestBody, - fields: 'id', - auth: jwtClient, - }, - (err, file) => { - if (err) reject(err); - fs.unlinkSync(path); - resolve(file.data.id); - } - ); - }); + // jwtClient.authorize(function (err, tokens) { + // if (err) reject('Error de autorización: ' + err); + const authClient = await loadCredentials(); + const drive = google.drive({ version: 'v3', auth: authClient }); + + drive.files.create( + { + media, + requestBody, + fields: 'id', + // auth: jwtClient, + }, + (err, file) => { + if (err) reject(err); + fs.unlinkSync(path); + resolve(file.data.id); + } + ); + // }); }); }; // CREAR CARPETA const mkDir = (name) => { - return new Promise((resolve, reject) => { + return new Promise(async (resolve, reject) => { + const authClient = await loadCredentials(); + const drive = google.drive({ version: 'v3', auth: authClient }); const requestBody = { name, mimeType: 'application/vnd.google-apps.folder', parents: [process.env.CARPETA], }; - jwtClient.authorize((err, tokens) => { - if (err) reject('Error de autorización: ' + err); - drive.files.create( - { - fields: 'id', - auth: jwtClient, - requestBody, - }, - (err, res) => { - if (err) reject(err); - resolve(res.data.id); - } - ); - }); + // jwtClient.authorize((err, tokens) => { + // if (err) reject('Error de autorización: ' + err); + drive.files.create( + { + fields: 'id', + // auth: jwtClient, + requestBody, + }, + (err, res) => { + if (err) reject(err); + resolve(res.data.id); + } + ); + // }); }); }; // Update File const update = (fileId, addParents, removeParents) => { - return new Promise((resolve, reject) => { - jwtClient.authorize((err, tokens) => { - if (err) reject('Error de autorización: ' + err); - drive.files.update( - { auth: jwtClient, fileId, addParents, removeParents }, - (err, resp) => { - if (err) reject('Ha habido un error en la petición: ' + err); - resolve(resp.data); - } - ); - }); + return new Promise(async (resolve, reject) => { + // jwtClient.authorize((err, tokens) => { + // if (err) reject('Error de autorización: ' + err); + const authClient = await loadCredentials(); + const drive = google.drive({ version: 'v3', auth: authClient }); + + drive.files.update( + { auth: jwtClient, fileId, addParents, removeParents }, + (err, resp) => { + if (err) reject('Ha habido un error en la petición: ' + err); + resolve(resp.data); + } + ); + // }); }); }; -- 2.43.0 From 493fd83e0e2f5b93abaea7c986a58c37180da558 Mon Sep 17 00:00:00 2001 From: Tu Nombre Date: Tue, 28 Jan 2025 10:20:37 -0600 Subject: [PATCH 05/21] agregar los modelos Cuestioanrio, cuestionarioAlumno2, cuestionarioPrograma2 --- server/db/install.js | 29 +++ server/db/tablas/Cuestionario.js | 75 ++++++++ server/db/tablas/CuestionarioAlumno2.js | 216 ++++++++++++++++++++++ server/db/tablas/CuestionarioPrograma2.js | 134 ++++++++++++++ 4 files changed, 454 insertions(+) create mode 100644 server/db/tablas/Cuestionario.js create mode 100644 server/db/tablas/CuestionarioAlumno2.js create mode 100644 server/db/tablas/CuestionarioPrograma2.js diff --git a/server/db/install.js b/server/db/install.js index 6c9ef67..e050a12 100644 --- a/server/db/install.js +++ b/server/db/install.js @@ -10,6 +10,8 @@ const CasoEspecial = require('./tablas/CasoEspecial'); const Status = require('./tablas/Status'); const TipoUsuario = require('./tablas/TipoUsuario'); const Usuario = require('./tablas/Usuario'); +const CuestionarioAlumno = require('./tablas/CuestionarioAlumno'); +const CuestionarioPrograma = require('./tablas/CuestionarioPrograma'); const drop = async () => { console.log('\nPaso 1) Desinstalando la db.'.bold.blue); @@ -44,8 +46,25 @@ const drop = async () => { await TipoUsuario.drop(); console.log('La tabla TipoUsuario se desinstalo correctamente.'.magenta); + + + + await CuestionarioPrograma2.drop(); + console.log( + 'La tabla CuestionarioPrograma se desinstalo correctamente.'.magenta + ); + + await CuestionarioAlumno2.drop(); + console.log( + 'La tabla CuestionarioAlumno se desinstalo correctamente.'.magenta + ); + + }; + + + const sync = async () => { console.log('\nPaso 2) Instalando la db.'.bold.blue); @@ -77,6 +96,16 @@ const sync = async () => { await CasoEspecial.sync(); console.log('La tabla CasoEspecial se instalo correctamente.'.magenta); + + + await CuestionarioAlumno2.sync(); + console.log('La tabla CuestionarioAlumno se instalo correctamente.'.magenta); + + await CuestionarioPrograma2.sync(); + console.log( + 'La tabla CuestionarioPrograma se instalo correctamente.'.magenta + ); + }; const dataTipoUsuario = async () => { diff --git a/server/db/tablas/Cuestionario.js b/server/db/tablas/Cuestionario.js new file mode 100644 index 0000000..4502023 --- /dev/null +++ b/server/db/tablas/Cuestionario.js @@ -0,0 +1,75 @@ +const { DataTypes, Model } = require('sequelize'); +const sequelize = require('../../config/sequelize.conf'); +const Usuario = require('./Usuario'); +const Carrera = require('./Carrera'); +const Programa = require('./Programa'); +const Servicio = require('./Servicio'); +const CuestionarioAlumno2 = require('./CuestionarioAlumno2'); +const CuestionarioPrograma2 = require('./CuestionarioPrograma2'); + +class Cuestionario extends Model {} +Cuestionario.init( + { + idCuestionario: { + type: DataTypes.INTEGER, + primaryKey: true, + autoIncrement: true, + }, + + idServicio: { + type: DataTypes.INTEGER, + allowNull: false, + references: { + model: Servicio, + key: 'idServicio', + }, + }, + + + + idCuestionarioAlumno: { + type: DataTypes.INTEGER, + allowNull: true, + }, + idCuestionarioPrograma: { + type: DataTypes.INTEGER, + allowNull: true, + }, + + + version: { + type: DataTypes.STRING(50), + allowNull: false, + }, + titulo: { + type: DataTypes.STRING(50), + allowNull: false, + }, + desc: { + type: DataTypes.STRING(50), + allowNull: false, + }, + dirigidoA: { + type: DataTypes.STRING(50), + allowNull: false, + }, + createdAt: { + type: DataTypes.DATE, + allowNull: false, + }, + }, + { + sequelize, + modelName: 'Cuestionario', + tableName: 'Cuestionario', + timestamps: false, + } +); + + + + +Cuestionario.belongsTo(Servicio, { foreignKey: 'idServicio' }); +Servicio.hasMany(Cuestionario, { foreignKey: 'idServicio' }); + +module.exports = Cuestionario; diff --git a/server/db/tablas/CuestionarioAlumno2.js b/server/db/tablas/CuestionarioAlumno2.js new file mode 100644 index 0000000..0e8e1d6 --- /dev/null +++ b/server/db/tablas/CuestionarioAlumno2.js @@ -0,0 +1,216 @@ +const { DataTypes, Model } = require('sequelize'); +const sequelize = require('../../config/sequelize.conf'); + +class CuestionarioAlumno2 extends Model {} + +CuestionarioAlumno2.init( + { + idCuestionarioAlumno2: { + type: DataTypes.INTEGER, + primaryKey: true, + allowNull: false, + unique: true, + autoIncrement: true, + }, + + p1: { + type: DataTypes.STRING(100), + allowNull: true, + }, + p2: { + type: DataTypes.STRING(50), + allowNull: true, + }, + p4: { + type: DataTypes.STRING(5), + allowNull: true, + }, + p5: { + type: DataTypes.STRING(50), + allowNull: true, + }, + p6: { + type: DataTypes.STRING(5), + allowNull: true, + }, + p7: { + type: DataTypes.STRING(5), + allowNull: true, + }, + p8: { + type: DataTypes.STRING(50), + allowNull: true, + }, + p9: { + type: DataTypes.STRING(5), + allowNull: true, + }, + + // p3_*: se definen como string (el JSON trae si/no) + p3_1: { + type: DataTypes.STRING(5), + allowNull: true, + }, + p3_2: { + type: DataTypes.STRING(5), + allowNull: true, + }, + p3_3: { + type: DataTypes.STRING(5), + allowNull: true, + }, + p3_4: { + type: DataTypes.STRING(5), + allowNull: true, + }, + + // p10_* y p11_* + p10_1: { + type: DataTypes.STRING(5), + allowNull: true, + }, + p10_2: { + type: DataTypes.STRING(5), + allowNull: true, + }, + p10_3: { + type: DataTypes.STRING(5), + allowNull: true, + }, + p11_1: { + type: DataTypes.STRING(20), + allowNull: true, + }, + p11_2: { + type: DataTypes.STRING(20), + allowNull: true, + }, + p11_3: { + type: DataTypes.STRING(20), + allowNull: true, + }, + p11_4: { + type: DataTypes.STRING(20), + allowNull: true, + }, + + // p12_A_*, p12_B_*, p12_C_*, p12_D_* + // Ajusta el tamaño de la cadena según requieras + p12_A_1: { + type: DataTypes.STRING(20), + allowNull: true, + }, + p12_A_2: { + type: DataTypes.STRING(20), + allowNull: true, + }, + p12_A_3: { + type: DataTypes.STRING(20), + allowNull: true, + }, + p12_A_4: { + type: DataTypes.STRING(20), + allowNull: true, + }, + p12_B_1: { + type: DataTypes.STRING(20), + allowNull: true, + }, + p12_B_2: { + type: DataTypes.STRING(20), + allowNull: true, + }, + p12_B_3: { + type: DataTypes.STRING(20), + allowNull: true, + }, + p12_B_4: { + type: DataTypes.STRING(20), + allowNull: true, + }, + p12_C_1: { + type: DataTypes.STRING(20), + allowNull: true, + }, + p12_C_2: { + type: DataTypes.STRING(20), + allowNull: true, + }, + p12_C_3: { + type: DataTypes.STRING(20), + allowNull: true, + }, + p12_C_4: { + type: DataTypes.STRING(20), + allowNull: true, + }, + p12_D_1: { + type: DataTypes.STRING(20), + allowNull: true, + }, + p12_D_2: { + type: DataTypes.STRING(20), + allowNull: true, + }, + p12_D_3: { + type: DataTypes.STRING(20), + allowNull: true, + }, + p12_D_4: { + type: DataTypes.STRING(20), + allowNull: true, + }, + p12_D_5: { + type: DataTypes.STRING(20), + allowNull: true, + }, + + // p13, p14, p15, p16... + p13: { + type: DataTypes.STRING(100), + allowNull: true, + }, + p14: { + type: DataTypes.STRING(100), + allowNull: true, + }, + p15: { + type: DataTypes.STRING(5), + allowNull: true, + }, + p16: { + type: DataTypes.STRING(50), + allowNull: true, + }, + + // p17_* + p17_1: { + type: DataTypes.STRING(5), + allowNull: true, + }, + p17_2: { + type: DataTypes.STRING(5), + allowNull: true, + }, + p17_3: { + type: DataTypes.STRING(5), + allowNull: true, + }, + + // p18 + p18: { + type: DataTypes.STRING(50), + allowNull: true, + }, + }, + { + sequelize, + modelName: 'CuestionarioAlumno2', + tableName: 'cuestionario_alumno_2', + timestamps: true, + createdAt: true, + updatedAt: false, // Ajusta según tus necesidades + } +); + +module.exports = CuestionarioAlumno2; diff --git a/server/db/tablas/CuestionarioPrograma2.js b/server/db/tablas/CuestionarioPrograma2.js new file mode 100644 index 0000000..780f173 --- /dev/null +++ b/server/db/tablas/CuestionarioPrograma2.js @@ -0,0 +1,134 @@ +const { DataTypes, Model } = require('sequelize'); +const sequelize = require('../../config/sequelize.conf'); + +class CuestionarioPrograma2 extends Model {} + +CuestionarioPrograma2.init( + { + idCuestionarioPrograma2: { + type: DataTypes.INTEGER, + primaryKey: true, + allowNull: false, + unique: true, + autoIncrement: true, + }, + + // Sección p3_A_* + p3_A_1: { + type: DataTypes.STRING(50), + allowNull: true, + }, + p3_A_2: { + type: DataTypes.STRING(50), + allowNull: true, + }, + p3_A_3: { + type: DataTypes.STRING(50), + allowNull: true, + }, + p3_A_4: { + type: DataTypes.STRING(50), + allowNull: true, + }, + + // Sección p3_B_* + p3_B_1: { + type: DataTypes.STRING(50), + allowNull: true, + }, + p3_B_2: { + type: DataTypes.STRING(50), + allowNull: true, + }, + p3_B_3: { + type: DataTypes.STRING(50), + allowNull: true, + }, + p3_B_4: { + type: DataTypes.STRING(50), + allowNull: true, + }, + + // Sección p3_C_* + p3_C_1: { + type: DataTypes.STRING(50), + allowNull: true, + }, + p3_C_2: { + type: DataTypes.STRING(50), + allowNull: true, + }, + p3_C_3: { + type: DataTypes.STRING(50), + allowNull: true, + }, + p3_C_4: { + type: DataTypes.STRING(50), + allowNull: true, + }, + p3_C_5: { + type: DataTypes.STRING(50), + allowNull: true, + }, + + // Sección p3_D_* + p3_D_1: { + type: DataTypes.STRING(50), + allowNull: true, + }, + p3_D_2: { + type: DataTypes.STRING(50), + allowNull: true, + }, + p3_D_3: { + type: DataTypes.STRING(50), + allowNull: true, + }, + p3_D_4: { + type: DataTypes.STRING(50), + allowNull: true, + }, + p3_D_5: { + type: DataTypes.STRING(50), + allowNull: true, + }, + + // Sección p3_E_* + p3_E_1: { + type: DataTypes.STRING(50), + allowNull: true, + }, + + // p1, p2, p4, p5, p6 + p1: { + type: DataTypes.STRING(100), + allowNull: true, + }, + p2: { + type: DataTypes.STRING(50), + allowNull: true, + }, + p4: { + type: DataTypes.STRING(100), + allowNull: true, + }, + p5: { + type: DataTypes.STRING(5), + allowNull: true, + }, + p6: { + type: DataTypes.STRING(100), + allowNull: true, + }, + }, + { + sequelize, + modelName: 'CuestionarioPrograma2', + tableName: 'cuestionario_programa_2', + timestamps: true, + createdAt: true, + updatedAt: false, + } +); + +module.exports = CuestionarioPrograma2; -- 2.43.0 From d18179027720bd29bd19b86b0c9c4706eeff88f6 Mon Sep 17 00:00:00 2001 From: Tu Nombre Date: Tue, 28 Jan 2025 12:10:52 -0600 Subject: [PATCH 06/21] route y controller de los cuestionarios, aun en desarrollo --- server/controller/CuestionarioAlumno/get.js | 143 +++++++++++++++++- server/controller/CuestionarioAlumno/nuevo.js | 104 ++++++++++++- server/controller/CuestionarioPrograma/get.js | 59 +++++++- .../controller/CuestionarioPrograma/nuevo.js | 101 ++++++++++++- server/routes/CuestionarioAlumno.js | 11 +- server/routes/CuestionarioPrograma.js | 10 +- 6 files changed, 417 insertions(+), 11 deletions(-) diff --git a/server/controller/CuestionarioAlumno/get.js b/server/controller/CuestionarioAlumno/get.js index db7646d..d4b42a5 100644 --- a/server/controller/CuestionarioAlumno/get.js +++ b/server/controller/CuestionarioAlumno/get.js @@ -10,7 +10,12 @@ const Programa = require(`${dbPath}/Programa`); const Servicio = require(`${dbPath}/Servicio`); const Usuario = require(`${dbPath}/Usuario`); -const get = async (body) => { +const CuestionarioAlumno2 = require(`${dbPath}/CuestionarioAlumno2`); + + + + +const getOld = async (body) => { const year = validarNumero(body.year, 'año', true, 4); const path = `server/uploads/${year}_cuestionario_alumno.csv`; const data = []; @@ -79,4 +84,140 @@ const get = async (body) => { .then((res) => path); }; + + + +const get = async (body) => { + const year = validarNumero(body.year, 'año', true, 4); + const path = `server/uploads/${year}_cuestionario_alumno.csv`; + const data = []; + +console.log(year); + + +/* + return Servicio.findAll({ + include: [ + { + model: CuestionarioAlumno2, + where: { idCuestionarioAlumno: { [Op.not]: null } }, + }, + { model: Programa, where: { clavePrograma: { [Op.like]: `${year}%` } } }, + { model: Usuario }, + { model: Carrera }, + ], + order: [['createdAt']], + }) + + */ + + +/* return CuestionarioAlumno2.findAll({ + where: { + idCuestionarioAlumno2: { + [Op.not]: null, + }, + }, + // order: [['createdAt', 'ASC']], // Descomentar si se requiere ordenamiento + }) + .then(async (res) => { + + console.log("segunda parte",res); + + for (let i = 0; i < res.length; i++) + data.push({ ...res}) + + + data.push({ + idServicio: res[i].idServicio, + clavePrograma: res[i].Programa.clavePrograma, + usuario: res[i].Usuario.usuario, + nombre: res[i].Usuario.nombre, + carrera: res[i].Carrera.carrera, + idCuestionarioAlumno: res[i].CuestionarioAlumno.idCuestionarioAlumno, + sexo: res[i].CuestionarioAlumno.sexo, + edad: res[i].CuestionarioAlumno.edad, + servicioMedico: res[i].CuestionarioAlumno.servicioMedico, + p1: res[i].CuestionarioAlumno.p1, + p2: res[i].CuestionarioAlumno.p2, + p3: res[i].CuestionarioAlumno.p3, + p4: res[i].CuestionarioAlumno.p4, + p5: res[i].CuestionarioAlumno.p5, + p6: res[i].CuestionarioAlumno.p6, + p7: res[i].CuestionarioAlumno.p7, + p8: res[i].CuestionarioAlumno.p8, + p9: res[i].CuestionarioAlumno.p9, + p10: res[i].CuestionarioAlumno.p10, + p11: res[i].CuestionarioAlumno.p11, + p12: res[i].CuestionarioAlumno.p12, + p13: res[i].CuestionarioAlumno.p13, + p14: res[i].CuestionarioAlumno.p14, + p15: res[i].CuestionarioAlumno.p15, + p16: res[i].CuestionarioAlumno.p16, + p17: res[i].CuestionarioAlumno.p17, + p18: res[i].CuestionarioAlumno.p18, + p19: res[i].CuestionarioAlumno.p19, + p20: res[i].CuestionarioAlumno.p20, + p21: res[i].CuestionarioAlumno.p21, + p22: res[i].CuestionarioAlumno.p22, + p23: res[i].CuestionarioAlumno.p23, + p24: res[i].CuestionarioAlumno.p24, + p25: res[i].CuestionarioAlumno.p25, + p26: res[i].CuestionarioAlumno.p26, + p27: res[i].CuestionarioAlumno.p27, + p28: res[i].CuestionarioAlumno.p28, + p29: res[i].CuestionarioAlumno.p29, + p30: res[i].CuestionarioAlumno.p30, + createdAt: res[i].CuestionarioAlumno.createdAt, + }); + await helper.eliminarArchivo(path).catch((err) => { + console.log(err); + }); + return helper.crearArchivo(path, convertArrayToCSV(data)); + }) + .then((res) => path); +}; */ + + + +return CuestionarioAlumno2.findAll({ + where: { + idCuestionarioAlumno2: { + [Op.not]: null, + }, + }, +}) + .then(async (res) => { + console.log("segunda parte", res); + + for (let i = 0; i < res.length; i++) { + data.push(res[i].get({ plain: true })); + } + + // Alternativa manual si necesitas campos específicos + /* for (let i = 0; i < res.length; i++) { + const row = res[i].get({ plain: true }); + data.push({ + idCuestionarioAlumno2: row.idCuestionarioAlumno2, + p1: row.p1, + p2: row.p2, + p3: row.p3, + p4: row.p4, + p5: row.p5, + // Agrega los demás campos según sea necesario + }); + } */ + + await helper.eliminarArchivo(path).catch((err) => { + console.log(err); + }); + + return helper.crearArchivo(path, convertArrayToCSV(data)); + }) + .then((res) => path); +} + + + + module.exports = get; diff --git a/server/controller/CuestionarioAlumno/nuevo.js b/server/controller/CuestionarioAlumno/nuevo.js index db3e05e..758da58 100644 --- a/server/controller/CuestionarioAlumno/nuevo.js +++ b/server/controller/CuestionarioAlumno/nuevo.js @@ -3,7 +3,12 @@ const dbPath = '../../db/tablas'; const CuestionarioAlumno = require(`${dbPath}/CuestionarioAlumno`); const Servicio = require(`${dbPath}/Servicio`); -const nuevo = async (body) => { + +const CuestionarioAlumno2 = require(`${dbPath}/CuestionarioAlumno2`); +const Cuestionario = require(`${dbPath}/Cuestionario`); + + +const nuevoOld = async (body) => { const idServicio = validar.validarNumeroEntero( body.idServicio, 'id servicio' @@ -161,4 +166,101 @@ const nuevo = async (body) => { })); }; + + + +const nuevo = async (body) => { + // console.log(body); + + let idServicio = body.idServicio; + /* + const idServicio = validar.validarNumeroEntero( + body.idServicio, + 'id servicio' + ); */ + + + body = validar.validarCuestionarioAlumno2(body); + + + // pasar preguntas de array a string + + return Servicio.findOne({ where: { idServicio } }) + .then(async (res) => { + if (!res) throw new Error('No existe este Servicio Social.'); + /* + if (res.idCuestionarioAlumno) + throw new Error( + 'Este Servicio Social ya cuenta con cuestionario de alumno' + ); + */ + + console.log('el servicio social si existe'); + // console.log(res); + + /** + * existe el servicio social? + * tiene cuestionario alumno en la tabla cuestionario? select * from cuestionario where idServicio = 1 + * si no existe, entonces se puede crear el cuestionario + * creamos el cuestionario y guardamos las respuestas + */ + + const messageByStatus = { + 1: 'Aun no se puede contestar el cuestionario este Servicio Social.', + 2: 'Aun no se puede contestar el cuestionario este Servicio Social.', + 3: 'Aun no se puede contestar el cuestionario este Servicio Social.', + 5: 'Este Servicio Social ya paso la fase de contestar el cuestionario.', + 6: 'Este Servicio Social ya paso la fase de contestar el cuestionario.', + 7: 'Este Servicio Social se encuentra rechazado. No se puede avanzar hasta que se corrija lo necesario.', + 8: 'Este Servicio Social se encuentra rechazado. No se puede avanzar hasta que se corrija lo necesario.', + 9: 'Este Servicio Social se encuentra rechazado. No se puede avanzar hasta que se corrija lo necesario.', + 10: 'Este Servicio Social fue cancelado.', + }; + + // if (res.idStatus === 4) return CuestionarioAlumno2.create({ ...body }); + console.log('antes de create ques2'); + + // if (res.idStatus) return CuestionarioAlumno2.create({ ...body }); + + // si idStatus está en el objeto, arrojamos el mensaje + + /* if (messageByStatus.hasOwnProperty(res.idStatus)) + throw new Error(messageByStatus[res.idStatus]); */ + + // throw new Error('Id status no valido.'); // si no coincide con nada, error por defecto + + Cuestionario.findOne({}); + + let dataCuestionario = await Cuestionario.findOne({ + where: { idServicio, dirigidoA: 'estudiantes' }, + }); + console.log('data cuestionario', dataCuestionario); + + if (dataCuestionario) { + throw new Error('Ya existe un cuestionario para este servicio social'); + } + + let respuestasRegistradas = await CuestionarioAlumno2.create({ ...body }); + console.log('despues de registrar cuestionario', respuestasRegistradas); + + let cuestionarioRegistro = await Cuestionario.create({ + idServicio, + idCuestionarioAlumno: respuestasRegistradas.idCuestionarioAlumno, + version: '2', + dirigidoA: 'estudiantes', + titulo: 'Cuestionario de Alumn v2', + desc: 'Cuestionario de Alumno v2', + createdAt: new Date(), + }); + + console.log('cuestionario registrado', cuestionarioRegistro); + + return cuestionarioRegistro; + }) + + .then((res) => ({ + message: `Se guardaron tus respuestas correctamente. ${res}`, + })); +}; + module.exports = nuevo; diff --git a/server/controller/CuestionarioPrograma/get.js b/server/controller/CuestionarioPrograma/get.js index 25a9338..dd1b29e 100644 --- a/server/controller/CuestionarioPrograma/get.js +++ b/server/controller/CuestionarioPrograma/get.js @@ -6,12 +6,17 @@ const helper = require(`${helperPath}/helper`); const { validarNumero } = require(`${helperPath}/validar`); const dbPath = '../../db/tablas'; const Carrera = require(`${dbPath}/Carrera`); -const CuestionarioPrograma = require(`${dbPath}/CuestionarioPrograma`); const Servicio = require(`${dbPath}/Servicio`); const Programa = require(`${dbPath}/Programa`); const Usuario = require(`${dbPath}/Usuario`); -const get = async (body) => { + +const CuestionarioPrograma2 = require(`${dbPath}/CuestionarioPrograma`); + + + +const CuestionarioPrograma = require(`${dbPath}/CuestionarioPrograma`); +const getOld = async (body) => { const year = validarNumero(body.year, 'año', true, 4); const path = `server/uploads/${year}_cuestionario_programa.csv`; const data = []; @@ -56,4 +61,54 @@ const get = async (body) => { .then((res) => path); }; + + + + +const get = async (body) => { + const year = validarNumero(body.year, 'año', true, 4); + const path = `server/uploads/${year}_cuestionario_programa.csv`; + const data = []; + + + + return CuestionarioPrograma2.findAll({ + where: { + idCuestionarioPrograma2: { + [Op.not]: null, + }, + }, + }) + .then(async (res) => { + console.log("segunda parte", res); + + for (let i = 0; i < res.length; i++) { + data.push(res[i].get({ plain: true })); + } + + // Alternativa manual si necesitas campos específicos + /* for (let i = 0; i < res.length; i++) { + const row = res[i].get({ plain: true }); + data.push({ + idCuestionarioPrograma2: row.idCuestionarioPrograma2, + p1: row.p1, + p2: row.p2, + p3: row.p3, + p4: row.p4, + p5: row.p5, + // Agrega los demás campos según sea necesario + }); + } */ + + await helper.eliminarArchivo(path).catch((err) => { + console.log(err); + }); + + return helper.crearArchivo(path, convertArrayToCSV(data)); + }) + .then((res) => path); + } + + + module.exports = get; diff --git a/server/controller/CuestionarioPrograma/nuevo.js b/server/controller/CuestionarioPrograma/nuevo.js index c42c9a8..fd1dcfe 100644 --- a/server/controller/CuestionarioPrograma/nuevo.js +++ b/server/controller/CuestionarioPrograma/nuevo.js @@ -3,7 +3,13 @@ const dbPath = '../../db/tablas'; const CuestionarioPrograma = require(`${dbPath}/CuestionarioPrograma`); const Servicio = require(`${dbPath}/Servicio`); -const nuevo = async (body) => { + +const CuestionarioPrograma2 = require(`${dbPath}/CuestionarioPrograma2`); +const Cuestionario = require(`${dbPath}/Cuestionario`); + + + +const nuevoOld = async (body) => { const idServicio = validar.validarNumeroEntero( body.idServicio, 'id servicio' @@ -76,4 +82,97 @@ const nuevo = async (body) => { })); }; + + +const nuevo = async (body) => { + // console.log(body); + + let idServicio = body.idServicio; + /* + const idServicio = validar.validarNumeroEntero( + body.idServicio, + 'id servicio' + ); */ + + // pasar preguntas de array a string + + return Servicio.findOne({ where: { idServicio } }) + .then(async (res) => { + if (!res) throw new Error('No existe este Servicio Social.'); + /* if (res.idCuestionarioAlumno) + throw new Error( + 'Este Servicio Social ya cuenta con cuestionario de programa' + ); */ + + console.log('el servicio social si existe'); + // console.log(res); + + /** + * existe el servicio social? + * tiene cuestionario alumno en la tabla cuestionario? select * from cuestionario where idServicio = 1 + * si no existe, entonces se puede crear el cuestionario + * creamos el cuestionario y guardamos las respuestas + */ + + const messageByStatus = { + 1: 'Aun no se puede contestar el cuestionario este Servicio Social.', + 2: 'Aun no se puede contestar el cuestionario este Servicio Social.', + 3: 'Aun no se puede contestar el cuestionario este Servicio Social.', + 5: 'Este Servicio Social ya paso la fase de contestar el cuestionario.', + 6: 'Este Servicio Social ya paso la fase de contestar el cuestionario.', + 7: 'Este Servicio Social se encuentra rechazado. No se puede avanzar hasta que se corrija lo necesario.', + 8: 'Este Servicio Social se encuentra rechazado. No se puede avanzar hasta que se corrija lo necesario.', + 9: 'Este Servicio Social se encuentra rechazado. No se puede avanzar hasta que se corrija lo necesario.', + 10: 'Este Servicio Social fue cancelado.', + }; + + // if (res.idStatus === 4) return CuestionarioPrograma2.create({ ...body }); + console.log('antes de create ques2'); + + // if (res.idStatus) return CuestionarioPrograma2.create({ ...body }); + // si idStatus está en el objeto, arrojamos el mensaje + /* if (messageByStatus.hasOwnProperty(res.idStatus)) + throw new Error(messageByStatus[res.idStatus]); */ + // throw new Error('Id status no valido.'); // si no coincide con nada, error por defecto + + let dataCuestionario = await Cuestionario.findOne({ + where: { idServicio, dirigidoA: 'programas' }, + }); + console.log('data cuestionario', dataCuestionario); + + if (dataCuestionario) { + throw new Error('Ya existe un cuestionario para este servicio social'); + } + + let respuestasRegistradas = await CuestionarioPrograma2.create({ + ...body, + }); + + console.log('despues de registrar cuestionario', respuestasRegistradas); + + // si el cuestionario ya existe solo hay que actualizar el id de cuestionarioprograma o alumno + + let cuestionarioRegistro = await Cuestionario.create({ + idServicio, + idCuestionarioPrograma: respuestasRegistradas.idCuestionarioPrograma, + version: '2', + dirigidoA: 'programas', + titulo: 'Cuestionario de programa v2', + desc: 'Cuestionario de programa v2', + createdAt: new Date(), + }); + + console.log('cuestionario registrado', cuestionarioRegistro); + + return cuestionarioRegistro; + }) + + .then((res) => ({ + message: `Se guardaron tus respuestas correctamente. ${res}`, + })); +}; + + + + module.exports = nuevo; diff --git a/server/routes/CuestionarioAlumno.js b/server/routes/CuestionarioAlumno.js index 764bb4a..2a2c617 100644 --- a/server/routes/CuestionarioAlumno.js +++ b/server/routes/CuestionarioAlumno.js @@ -2,12 +2,15 @@ const express = require('express'); const app = express(); const { verificaToken } = require('../middleware/autentificacion'); const route = '/cuestionario_alumno'; -const controllerPath = '../controller/CuestionarioAlumno'; +//const controllerPath = '../controller/CuestionarioAlumno'; +const controllerPath = '../controller/CuestionarioAlumno2'; + const get = require(`${controllerPath}/get`); const nuevo = require(`${controllerPath}/nuevo`); // POST -app.post(`${route}`, verificaToken, (req, res) => { +app.post(`${route}`, // verificaToken, + (req, res) => { return nuevo(req.body) .then((data) => { res.status(200).json(data); @@ -18,7 +21,9 @@ app.post(`${route}`, verificaToken, (req, res) => { }); // GET -app.get(`${route}`, verificaToken, (req, res) => { +app.get(`${route}`, // verificaToken, + + (req, res) => { return get(req.query) .then((data) => { res.download(data); diff --git a/server/routes/CuestionarioPrograma.js b/server/routes/CuestionarioPrograma.js index 7183d54..8e70ff7 100644 --- a/server/routes/CuestionarioPrograma.js +++ b/server/routes/CuestionarioPrograma.js @@ -2,12 +2,15 @@ const express = require('express'); const app = express(); const { verificaToken } = require('../middleware/autentificacion'); const route = '/cuestionario_programa'; -const controllerPath = '../controller/CuestionarioPrograma'; +//const controllerPath = '../controller/CuestionarioPrograma'; +const controllerPath = '../controller/CuestionarioPrograma2'; + const get = require(`${controllerPath}/get`); const nuevo = require(`${controllerPath}/nuevo`); // POST -app.post(`${route}`, verificaToken, (req, res) => { +app.post(`${route}`, //verificaToken, + (req, res) => { return nuevo(req.body) .then((data) => { res.status(200).json(data); @@ -18,7 +21,8 @@ app.post(`${route}`, verificaToken, (req, res) => { }); // GET -app.get(`${route}`, verificaToken, (req, res) => { +app.get(`${route}`, //verificaToken, + (req, res) => { return get(req.query) .then((data) => { res.download(data); -- 2.43.0 From f1d041e891668cfce7255114c2817dd49cc5831a Mon Sep 17 00:00:00 2001 From: Tu Nombre Date: Tue, 28 Jan 2025 12:22:19 -0600 Subject: [PATCH 07/21] tablas y controllers actualizados de cuestionarios --- server/controller/CuestionarioAlumno/nuevo.js | 17 ++++--- .../controller/CuestionarioPrograma/nuevo.js | 26 +++++++--- server/db/tablas/Cuestionario.js | 50 +++---------------- server/db/tablas/CuestionarioAlumno2.js | 24 +++++++-- server/db/tablas/CuestionarioPrograma2.js | 20 ++++++++ 5 files changed, 80 insertions(+), 57 deletions(-) diff --git a/server/controller/CuestionarioAlumno/nuevo.js b/server/controller/CuestionarioAlumno/nuevo.js index 758da58..5637a8f 100644 --- a/server/controller/CuestionarioAlumno/nuevo.js +++ b/server/controller/CuestionarioAlumno/nuevo.js @@ -168,11 +168,10 @@ const nuevoOld = async (body) => { - const nuevo = async (body) => { // console.log(body); - let idServicio = body.idServicio; + let idServicio = body.idServicio; /* const idServicio = validar.validarNumeroEntero( body.idServicio, @@ -229,7 +228,7 @@ const nuevo = async (body) => { // throw new Error('Id status no valido.'); // si no coincide con nada, error por defecto - Cuestionario.findOne({}); + // Cuestionario.findOne({}); let dataCuestionario = await Cuestionario.findOne({ where: { idServicio, dirigidoA: 'estudiantes' }, @@ -240,12 +239,10 @@ const nuevo = async (body) => { throw new Error('Ya existe un cuestionario para este servicio social'); } - let respuestasRegistradas = await CuestionarioAlumno2.create({ ...body }); - console.log('despues de registrar cuestionario', respuestasRegistradas); let cuestionarioRegistro = await Cuestionario.create({ idServicio, - idCuestionarioAlumno: respuestasRegistradas.idCuestionarioAlumno, + // idCuestionarioAlumno: respuestasRegistradas.idCuestionarioAlumno, version: '2', dirigidoA: 'estudiantes', titulo: 'Cuestionario de Alumn v2', @@ -253,6 +250,13 @@ const nuevo = async (body) => { createdAt: new Date(), }); + +console.log("datos a registrar en la tabla cuestionarioAlumno2", { ...body, idCuestionario: cuestionarioRegistro.idCuestionario } ); + + let respuestasRegistradas = await CuestionarioAlumno2.create({ ...body, idCuestionario: cuestionarioRegistro.idCuestionario }); + console.log('despues de registrar cuestionario', respuestasRegistradas); + + console.log('cuestionario registrado', cuestionarioRegistro); return cuestionarioRegistro; @@ -263,4 +267,5 @@ const nuevo = async (body) => { })); }; + module.exports = nuevo; diff --git a/server/controller/CuestionarioPrograma/nuevo.js b/server/controller/CuestionarioPrograma/nuevo.js index fd1dcfe..53c3b6d 100644 --- a/server/controller/CuestionarioPrograma/nuevo.js +++ b/server/controller/CuestionarioPrograma/nuevo.js @@ -135,6 +135,10 @@ const nuevo = async (body) => { throw new Error(messageByStatus[res.idStatus]); */ // throw new Error('Id status no valido.'); // si no coincide con nada, error por defecto + + + + let dataCuestionario = await Cuestionario.findOne({ where: { idServicio, dirigidoA: 'programas' }, }); @@ -144,14 +148,9 @@ const nuevo = async (body) => { throw new Error('Ya existe un cuestionario para este servicio social'); } - let respuestasRegistradas = await CuestionarioPrograma2.create({ - ...body, - }); - console.log('despues de registrar cuestionario', respuestasRegistradas); - - // si el cuestionario ya existe solo hay que actualizar el id de cuestionarioprograma o alumno + let cuestionarioRegistro = await Cuestionario.create({ idServicio, idCuestionarioPrograma: respuestasRegistradas.idCuestionarioPrograma, @@ -164,6 +163,21 @@ const nuevo = async (body) => { console.log('cuestionario registrado', cuestionarioRegistro); + + + + + + let respuestasRegistradas = await CuestionarioPrograma2.create({ + ...body, + idCuestionario: cuestionarioRegistro.idCuestionario + }); + + console.log('despues de registrar cuestionario', respuestasRegistradas); + + // si el cuestionario ya existe solo hay que actualizar el id de cuestionarioprograma o alumno + + return cuestionarioRegistro; }) diff --git a/server/db/tablas/Cuestionario.js b/server/db/tablas/Cuestionario.js index 4502023..a849371 100644 --- a/server/db/tablas/Cuestionario.js +++ b/server/db/tablas/Cuestionario.js @@ -1,13 +1,11 @@ + + const { DataTypes, Model } = require('sequelize'); const sequelize = require('../../config/sequelize.conf'); -const Usuario = require('./Usuario'); -const Carrera = require('./Carrera'); -const Programa = require('./Programa'); const Servicio = require('./Servicio'); -const CuestionarioAlumno2 = require('./CuestionarioAlumno2'); -const CuestionarioPrograma2 = require('./CuestionarioPrograma2'); class Cuestionario extends Model {} + Cuestionario.init( { idCuestionario: { @@ -15,7 +13,6 @@ Cuestionario.init( primaryKey: true, autoIncrement: true, }, - idServicio: { type: DataTypes.INTEGER, allowNull: false, @@ -24,39 +21,11 @@ Cuestionario.init( key: 'idServicio', }, }, - - - - idCuestionarioAlumno: { - type: DataTypes.INTEGER, - allowNull: true, - }, - idCuestionarioPrograma: { - type: DataTypes.INTEGER, - allowNull: true, - }, - - - version: { - type: DataTypes.STRING(50), - allowNull: false, - }, - titulo: { - type: DataTypes.STRING(50), - allowNull: false, - }, - desc: { - type: DataTypes.STRING(50), - allowNull: false, - }, - dirigidoA: { - type: DataTypes.STRING(50), - allowNull: false, - }, - createdAt: { - type: DataTypes.DATE, - allowNull: false, - }, + version: DataTypes.STRING(50), + titulo: DataTypes.STRING(50), + desc: DataTypes.STRING(50), + dirigidoA: DataTypes.STRING(50), + createdAt: DataTypes.DATE, }, { sequelize, @@ -66,9 +35,6 @@ Cuestionario.init( } ); - - - Cuestionario.belongsTo(Servicio, { foreignKey: 'idServicio' }); Servicio.hasMany(Cuestionario, { foreignKey: 'idServicio' }); diff --git a/server/db/tablas/CuestionarioAlumno2.js b/server/db/tablas/CuestionarioAlumno2.js index 0e8e1d6..92bbb68 100644 --- a/server/db/tablas/CuestionarioAlumno2.js +++ b/server/db/tablas/CuestionarioAlumno2.js @@ -1,3 +1,4 @@ + const { DataTypes, Model } = require('sequelize'); const sequelize = require('../../config/sequelize.conf'); @@ -8,10 +9,17 @@ CuestionarioAlumno2.init( idCuestionarioAlumno2: { type: DataTypes.INTEGER, primaryKey: true, - allowNull: false, - unique: true, autoIncrement: true, }, + idCuestionario: { + type: DataTypes.INTEGER, + allowNull: true, + }, + + + + + p1: { type: DataTypes.STRING(100), @@ -202,6 +210,9 @@ CuestionarioAlumno2.init( type: DataTypes.STRING(50), allowNull: true, }, + + + }, { sequelize, @@ -209,8 +220,15 @@ CuestionarioAlumno2.init( tableName: 'cuestionario_alumno_2', timestamps: true, createdAt: true, - updatedAt: false, // Ajusta según tus necesidades + updatedAt: false, } ); +// Importación después de la definición para evitar dependencias circulares +const Cuestionario = require('./Cuestionario'); + +// Definir relaciones después de importar correctamente +CuestionarioAlumno2.belongsTo(Cuestionario, { foreignKey: 'idCuestionario' }); +Cuestionario.hasMany(CuestionarioAlumno2, { foreignKey: 'idCuestionario' }); + module.exports = CuestionarioAlumno2; diff --git a/server/db/tablas/CuestionarioPrograma2.js b/server/db/tablas/CuestionarioPrograma2.js index 780f173..29d9ad7 100644 --- a/server/db/tablas/CuestionarioPrograma2.js +++ b/server/db/tablas/CuestionarioPrograma2.js @@ -1,6 +1,9 @@ const { DataTypes, Model } = require('sequelize'); const sequelize = require('../../config/sequelize.conf'); +const Cuestionario = require('./Cuestionario'); + + class CuestionarioPrograma2 extends Model {} CuestionarioPrograma2.init( @@ -13,6 +16,14 @@ CuestionarioPrograma2.init( autoIncrement: true, }, + + idCuestionario: { + type: DataTypes.INTEGER, + allowNull: true, + }, + + + // Sección p3_A_* p3_A_1: { type: DataTypes.STRING(50), @@ -131,4 +142,13 @@ CuestionarioPrograma2.init( } ); + +CuestionarioPrograma2.belongsTo(Cuestionario, { foreignKey: 'idCuestionario' }); +Cuestionario.hasMany(CuestionarioPrograma2, { foreignKey: 'idCuestionario' }); + + + + + + module.exports = CuestionarioPrograma2; -- 2.43.0 From 3a3c27908015dfbc4477c26af2dba8e7896f31a5 Mon Sep 17 00:00:00 2001 From: Tu Nombre Date: Wed, 29 Jan 2025 09:08:11 -0600 Subject: [PATCH 08/21] controller correcto --- server/routes/CuestionarioAlumno.js | 3 +-- server/routes/CuestionarioPrograma.js | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/server/routes/CuestionarioAlumno.js b/server/routes/CuestionarioAlumno.js index 2a2c617..1f37063 100644 --- a/server/routes/CuestionarioAlumno.js +++ b/server/routes/CuestionarioAlumno.js @@ -2,8 +2,7 @@ const express = require('express'); const app = express(); const { verificaToken } = require('../middleware/autentificacion'); const route = '/cuestionario_alumno'; -//const controllerPath = '../controller/CuestionarioAlumno'; -const controllerPath = '../controller/CuestionarioAlumno2'; +const controllerPath = '../controller/CuestionarioAlumno'; const get = require(`${controllerPath}/get`); const nuevo = require(`${controllerPath}/nuevo`); diff --git a/server/routes/CuestionarioPrograma.js b/server/routes/CuestionarioPrograma.js index 8e70ff7..206ed49 100644 --- a/server/routes/CuestionarioPrograma.js +++ b/server/routes/CuestionarioPrograma.js @@ -2,8 +2,7 @@ const express = require('express'); const app = express(); const { verificaToken } = require('../middleware/autentificacion'); const route = '/cuestionario_programa'; -//const controllerPath = '../controller/CuestionarioPrograma'; -const controllerPath = '../controller/CuestionarioPrograma2'; +const controllerPath = '../controller/CuestionarioPrograma'; const get = require(`${controllerPath}/get`); const nuevo = require(`${controllerPath}/nuevo`); -- 2.43.0 From ab21808ec8a7caeb489db65663b86888e5e7775b Mon Sep 17 00:00:00 2001 From: Tu Nombre Date: Wed, 29 Jan 2025 10:23:57 -0600 Subject: [PATCH 09/21] test error drive --- .gitignore | 1 + server/helper/drive.js | 2 ++ 2 files changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index 4c27012..d0bdfe6 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,4 @@ node_modules/ cred.json server/uploads/* +.devcontainer \ No newline at end of file diff --git a/server/helper/drive.js b/server/helper/drive.js index d3935e9..0c84122 100644 --- a/server/helper/drive.js +++ b/server/helper/drive.js @@ -39,6 +39,8 @@ const list = (pageToken) => { orderBy: 'name', }, (err, resp) => { + console.log(resp); + if (err) reject('Ha habido un error en la petición: ' + err); resolve(resp.data); } -- 2.43.0 From 8cc4c7d34f652725a7d09759a1d7ccb5a7207800 Mon Sep 17 00:00:00 2001 From: Tu Nombre Date: Wed, 29 Jan 2025 13:33:53 -0600 Subject: [PATCH 10/21] solo un log antes de la ufnc --- server/routes/CuestionarioAlumno.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/server/routes/CuestionarioAlumno.js b/server/routes/CuestionarioAlumno.js index 1f37063..5038a3e 100644 --- a/server/routes/CuestionarioAlumno.js +++ b/server/routes/CuestionarioAlumno.js @@ -10,6 +10,8 @@ const nuevo = require(`${controllerPath}/nuevo`); // POST app.post(`${route}`, // verificaToken, (req, res) => { + console.log("cuestionario Alumnos antes de la funcion"); + return nuevo(req.body) .then((data) => { res.status(200).json(data); -- 2.43.0 From c547f25a0aa632519ac24226584ac0f0d45d1a9b Mon Sep 17 00:00:00 2001 From: Tu Nombre Date: Thu, 30 Jan 2025 10:03:04 -0600 Subject: [PATCH 11/21] probando ver si pide token --- server/controller/CuestionarioAlumno/nuevo.js | 2 +- server/routes/CuestionarioAlumno.js | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/server/controller/CuestionarioAlumno/nuevo.js b/server/controller/CuestionarioAlumno/nuevo.js index 5637a8f..43709f9 100644 --- a/server/controller/CuestionarioAlumno/nuevo.js +++ b/server/controller/CuestionarioAlumno/nuevo.js @@ -179,7 +179,7 @@ const nuevo = async (body) => { ); */ - body = validar.validarCuestionarioAlumno2(body); + // body = validar.validarCuestionarioAlumno2(body); // pasar preguntas de array a string diff --git a/server/routes/CuestionarioAlumno.js b/server/routes/CuestionarioAlumno.js index 5038a3e..52025a5 100644 --- a/server/routes/CuestionarioAlumno.js +++ b/server/routes/CuestionarioAlumno.js @@ -8,7 +8,8 @@ const get = require(`${controllerPath}/get`); const nuevo = require(`${controllerPath}/nuevo`); // POST -app.post(`${route}`, // verificaToken, +app.post(`${route}`, + // verificaToken, (req, res) => { console.log("cuestionario Alumnos antes de la funcion"); @@ -22,7 +23,8 @@ app.post(`${route}`, // verificaToken, }); // GET -app.get(`${route}`, // verificaToken, +app.get(`${route}`, + // verificaToken, (req, res) => { return get(req.query) -- 2.43.0 From 87c311c0c8bf14f96a028a9c23cc9772b5fc5bba Mon Sep 17 00:00:00 2001 From: Tu Nombre Date: Thu, 30 Jan 2025 10:37:57 -0600 Subject: [PATCH 12/21] nuevo mensaje token --- server/helper/validar.js | 58 +++++++++++++++++++++++++++ server/middleware/autentificacion.js | 2 +- server/routes/CuestionarioAlumno.js | 2 +- server/routes/CuestionarioPrograma.js | 8 ++-- 4 files changed, 65 insertions(+), 5 deletions(-) diff --git a/server/helper/validar.js b/server/helper/validar.js index 77ebfe4..176d0de 100644 --- a/server/helper/validar.js +++ b/server/helper/validar.js @@ -171,6 +171,13 @@ const validarObjetoVacio = (obj) => { }; const validarPreTermino = (idServicio) => { + + // obtener los id cuestionarios by idServicio de la tabla cuestionario + // budcar el id cuestionario de alumno en las tablas de alumnos - depende de la version + // buscar el id cuestionario de programa en las tablas de programas - depende de la version + + // validar el if + return Servicio.findOne({ where: { idServicio } }) .then((res) => { if ( @@ -189,6 +196,57 @@ const validarPreTermino = (idServicio) => { ); }; + + + + +const validarCuestionarioAlumno2 = (body) => { + console.log("Validando cuestionario alumno 2"); + + // Excluir p2 de la validación de campos nulos + const camposExcluidos = [ + // 'p2' + ]; + + // Verificar si algún campo es nulo o indefinido (excepto p2) + for (const [key, value] of Object.entries(body)) { + if (!camposExcluidos.includes(key) && (value === null || value === undefined || value === '')) { + throw new Error(`El campo ${key} no puede estar vacío.`); + } + } + + console.log("Validación exitosa. Todos los campos son válidos."); + return body; +}; + + + + + +const validarCuestionarioPrograma2 = (body) => { + console.log("Validando cuestionario programa 2"); + + // Excluir p2 de la validación de campos nulos + const camposExcluidos = [ + // 'p2' + ]; + + // Verificar si algún campo es nulo o indefinido (excepto p2) + for (const [key, value] of Object.entries(body)) { + if (!camposExcluidos.includes(key) && (value === null || value === undefined || value === '')) { + throw new Error(`El campo ${key} no puede estar vacío.`); + } + } + + console.log("Validación exitosa. Todos los campos son válidos."); + return body; + }; + + + + + + module.exports = { yaExiste, noValido, diff --git a/server/middleware/autentificacion.js b/server/middleware/autentificacion.js index bc99d03..722180b 100644 --- a/server/middleware/autentificacion.js +++ b/server/middleware/autentificacion.js @@ -6,7 +6,7 @@ const verificaToken = (req, res, next) => { if (!token) return res.status(400).json({ - message: 'No se envio el token.', + message: 'No se envio el token. v2', }); jwt.verify(token, process.env.KEY, (err, decoded) => { if (err) { diff --git a/server/routes/CuestionarioAlumno.js b/server/routes/CuestionarioAlumno.js index 52025a5..e43a080 100644 --- a/server/routes/CuestionarioAlumno.js +++ b/server/routes/CuestionarioAlumno.js @@ -1,6 +1,6 @@ const express = require('express'); const app = express(); -const { verificaToken } = require('../middleware/autentificacion'); +// const { verificaToken } = require('../middleware/autentificacion'); const route = '/cuestionario_alumno'; const controllerPath = '../controller/CuestionarioAlumno'; diff --git a/server/routes/CuestionarioPrograma.js b/server/routes/CuestionarioPrograma.js index 206ed49..2410fb4 100644 --- a/server/routes/CuestionarioPrograma.js +++ b/server/routes/CuestionarioPrograma.js @@ -1,6 +1,6 @@ const express = require('express'); const app = express(); -const { verificaToken } = require('../middleware/autentificacion'); +//const { verificaToken } = require('../middleware/autentificacion'); const route = '/cuestionario_programa'; const controllerPath = '../controller/CuestionarioPrograma'; @@ -8,7 +8,8 @@ const get = require(`${controllerPath}/get`); const nuevo = require(`${controllerPath}/nuevo`); // POST -app.post(`${route}`, //verificaToken, +app.post(`${route}`, + //verificaToken, (req, res) => { return nuevo(req.body) .then((data) => { @@ -20,7 +21,8 @@ app.post(`${route}`, //verificaToken, }); // GET -app.get(`${route}`, //verificaToken, +app.get(`${route}`, + //verificaToken, (req, res) => { return get(req.query) .then((data) => { -- 2.43.0 From 76092c627ff27f54ddb289275fa71c6b6d93212b Mon Sep 17 00:00:00 2001 From: Tu Nombre Date: Thu, 30 Jan 2025 10:47:21 -0600 Subject: [PATCH 13/21] hello message updated --- server/app.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/app.js b/server/app.js index a2a0806..071a18a 100644 --- a/server/app.js +++ b/server/app.js @@ -17,7 +17,7 @@ app.use(bodyParser.json()); app.use(express.static('csv')); -app.get('/', (req, res) => res.send('API IRIS')); +app.get('/', (req, res) => res.send('API IRIS updated 30 jan')); app.use(require('./routes/index')); -- 2.43.0 From 38afeb084a6f6887c15c03c44f528afc77906ec5 Mon Sep 17 00:00:00 2001 From: Tu Nombre Date: Thu, 30 Jan 2025 14:57:09 -0600 Subject: [PATCH 14/21] validar cuestionario y comentar el envio de correos de gmail para evitar errores --- server/controller/CuestionarioAlumno/get.js | 127 +++--------------- server/controller/CuestionarioAlumno/nuevo.js | 2 +- .../controller/CuestionarioPrograma/nuevo.js | 2 + server/helper/gmail.js | 6 + server/helper/validar.js | 4 + 5 files changed, 30 insertions(+), 111 deletions(-) diff --git a/server/controller/CuestionarioAlumno/get.js b/server/controller/CuestionarioAlumno/get.js index d4b42a5..ecee9c3 100644 --- a/server/controller/CuestionarioAlumno/get.js +++ b/server/controller/CuestionarioAlumno/get.js @@ -12,9 +12,6 @@ const Usuario = require(`${dbPath}/Usuario`); const CuestionarioAlumno2 = require(`${dbPath}/CuestionarioAlumno2`); - - - const getOld = async (body) => { const year = validarNumero(body.year, 'año', true, 4); const path = `server/uploads/${year}_cuestionario_alumno.csv`; @@ -84,118 +81,31 @@ const getOld = async (body) => { .then((res) => path); }; - - - const get = async (body) => { + console.log(body); + const year = validarNumero(body.year, 'año', true, 4); const path = `server/uploads/${year}_cuestionario_alumno.csv`; const data = []; -console.log(year); + console.log(year); - -/* - return Servicio.findAll({ - include: [ - { - model: CuestionarioAlumno2, - where: { idCuestionarioAlumno: { [Op.not]: null } }, - }, - { model: Programa, where: { clavePrograma: { [Op.like]: `${year}%` } } }, - { model: Usuario }, - { model: Carrera }, - ], - order: [['createdAt']], - }) - - */ - - -/* return CuestionarioAlumno2.findAll({ + return CuestionarioAlumno2.findAll({ where: { idCuestionarioAlumno2: { [Op.not]: null, }, }, - // order: [['createdAt', 'ASC']], // Descomentar si se requiere ordenamiento }) .then(async (res) => { + console.log('segunda parte', res); - console.log("segunda parte",res); - - for (let i = 0; i < res.length; i++) - data.push({ ...res}) - - - data.push({ - idServicio: res[i].idServicio, - clavePrograma: res[i].Programa.clavePrograma, - usuario: res[i].Usuario.usuario, - nombre: res[i].Usuario.nombre, - carrera: res[i].Carrera.carrera, - idCuestionarioAlumno: res[i].CuestionarioAlumno.idCuestionarioAlumno, - sexo: res[i].CuestionarioAlumno.sexo, - edad: res[i].CuestionarioAlumno.edad, - servicioMedico: res[i].CuestionarioAlumno.servicioMedico, - p1: res[i].CuestionarioAlumno.p1, - p2: res[i].CuestionarioAlumno.p2, - p3: res[i].CuestionarioAlumno.p3, - p4: res[i].CuestionarioAlumno.p4, - p5: res[i].CuestionarioAlumno.p5, - p6: res[i].CuestionarioAlumno.p6, - p7: res[i].CuestionarioAlumno.p7, - p8: res[i].CuestionarioAlumno.p8, - p9: res[i].CuestionarioAlumno.p9, - p10: res[i].CuestionarioAlumno.p10, - p11: res[i].CuestionarioAlumno.p11, - p12: res[i].CuestionarioAlumno.p12, - p13: res[i].CuestionarioAlumno.p13, - p14: res[i].CuestionarioAlumno.p14, - p15: res[i].CuestionarioAlumno.p15, - p16: res[i].CuestionarioAlumno.p16, - p17: res[i].CuestionarioAlumno.p17, - p18: res[i].CuestionarioAlumno.p18, - p19: res[i].CuestionarioAlumno.p19, - p20: res[i].CuestionarioAlumno.p20, - p21: res[i].CuestionarioAlumno.p21, - p22: res[i].CuestionarioAlumno.p22, - p23: res[i].CuestionarioAlumno.p23, - p24: res[i].CuestionarioAlumno.p24, - p25: res[i].CuestionarioAlumno.p25, - p26: res[i].CuestionarioAlumno.p26, - p27: res[i].CuestionarioAlumno.p27, - p28: res[i].CuestionarioAlumno.p28, - p29: res[i].CuestionarioAlumno.p29, - p30: res[i].CuestionarioAlumno.p30, - createdAt: res[i].CuestionarioAlumno.createdAt, - }); - await helper.eliminarArchivo(path).catch((err) => { - console.log(err); - }); - return helper.crearArchivo(path, convertArrayToCSV(data)); - }) - .then((res) => path); -}; */ + for (let i = 0; i < res.length; i++) { + data.push(res[i].get({ plain: true })); + } - - -return CuestionarioAlumno2.findAll({ - where: { - idCuestionarioAlumno2: { - [Op.not]: null, - }, - }, -}) - .then(async (res) => { - console.log("segunda parte", res); - - for (let i = 0; i < res.length; i++) { - data.push(res[i].get({ plain: true })); - } - - // Alternativa manual si necesitas campos específicos - /* for (let i = 0; i < res.length; i++) { + // Alternativa manual si necesitas campos específicos + /* for (let i = 0; i < res.length; i++) { const row = res[i].get({ plain: true }); data.push({ idCuestionarioAlumno2: row.idCuestionarioAlumno2, @@ -208,16 +118,13 @@ return CuestionarioAlumno2.findAll({ }); } */ - await helper.eliminarArchivo(path).catch((err) => { - console.log(err); - }); - - return helper.crearArchivo(path, convertArrayToCSV(data)); - }) - .then((res) => path); -} - - + await helper.eliminarArchivo(path).catch((err) => { + console.log(err); + }); + return helper.crearArchivo(path, convertArrayToCSV(data)); + }) + .then((res) => path); +}; module.exports = get; diff --git a/server/controller/CuestionarioAlumno/nuevo.js b/server/controller/CuestionarioAlumno/nuevo.js index 43709f9..79806f8 100644 --- a/server/controller/CuestionarioAlumno/nuevo.js +++ b/server/controller/CuestionarioAlumno/nuevo.js @@ -179,7 +179,7 @@ const nuevo = async (body) => { ); */ - // body = validar.validarCuestionarioAlumno2(body); + body = validar.validarCuestionarioAlumno2(body); // pasar preguntas de array a string diff --git a/server/controller/CuestionarioPrograma/nuevo.js b/server/controller/CuestionarioPrograma/nuevo.js index 53c3b6d..d6125c3 100644 --- a/server/controller/CuestionarioPrograma/nuevo.js +++ b/server/controller/CuestionarioPrograma/nuevo.js @@ -88,6 +88,8 @@ const nuevo = async (body) => { // console.log(body); let idServicio = body.idServicio; + body = validar.validarCuestionarioAlumno2(body); + /* const idServicio = validar.validarNumeroEntero( body.idServicio, diff --git a/server/helper/gmail.js b/server/helper/gmail.js index 464a4a1..04ba66f 100644 --- a/server/helper/gmail.js +++ b/server/helper/gmail.js @@ -6,12 +6,18 @@ const send = require('gmail-send')({ }); const gmail = (subject, to, text) => { + /* return new Promise((resolve, reject) => { send({ subject, to, text }, (error, result, fullResult) => { if (error) reject(error); resolve(result); }); }); + */ + + return "envio de correo" + + }; module.exports = gmail; diff --git a/server/helper/validar.js b/server/helper/validar.js index 176d0de..1fa255d 100644 --- a/server/helper/validar.js +++ b/server/helper/validar.js @@ -261,4 +261,8 @@ module.exports = { validarNumero, validarObjetoVacio, validarPreTermino, + + validarCuestionarioAlumno2, + validarCuestionarioPrograma2 + }; -- 2.43.0 From f6dc38c00f14b9734c0c543979911e6f059a9295 Mon Sep 17 00:00:00 2001 From: Tu Nombre Date: Wed, 5 Feb 2025 16:36:01 -0600 Subject: [PATCH 15/21] cambios de cedetec, pruebas --- README.md | 65 +++ server/controller/CasoEspecial/nuevo.js | 2 +- server/db/data-fake.js | 45 ++- server/db/install.js | 18 +- server/middleware/autentificacion.js | 6 + testing.sql | 511 ++++++++++++++++++++++++ 6 files changed, 635 insertions(+), 12 deletions(-) create mode 100644 README.md create mode 100644 testing.sql diff --git a/README.md b/README.md new file mode 100644 index 0000000..5cf8637 --- /dev/null +++ b/README.md @@ -0,0 +1,65 @@ + + + + +Documentacion del sistema IRIS + +Tipos de usuarios + + +| 1 | admin | +| 2 | responsable | +| 3 | alumno | +| 4 | casoEspecial + + + +cuando se registran los admin? +cuando se carga la base se sube al admin - COESI + + + + + + + +los responsables se suben por carga m asiva en un csv +En testeo se sube un responsable al instalar la db +existen responsables internos y externos + + + +programsa admin +- son los programas que tiene asignados un administrador +Ejemplo + +Acatlan contigo - + +las claves de programa las sube coesi, que previamente se registro en otro ssitema y se guarda en iris + + + + +el responsable registra a los alumnos + + + + + +status del servicio social + 'Pre-Registro', + 'Pre-Registro Validado', + 'Registro', + 'Pre-Termino', + 'Termino', + 'Liberación', + 'Carta Aceptación Rechazada', + 'Carta Termino Rechazada', + 'Informe Global Rechazado', + 'Cancelado', + 'Articulo 52', + 'Articulo 91', + 'Liberación Articulo 52', + 'Liberación Articulo 91', + + diff --git a/server/controller/CasoEspecial/nuevo.js b/server/controller/CasoEspecial/nuevo.js index 8a30e51..10d3948 100644 --- a/server/controller/CasoEspecial/nuevo.js +++ b/server/controller/CasoEspecial/nuevo.js @@ -49,7 +49,7 @@ const nuevo = async (body, file) => { let carpeta = ''; return Usuario.findOne({ - where: { idUsuario }, + where: { idUsuario }, }) .then((res) => { if (!res) throw new Error('Este alumno no existe en la db.'); diff --git a/server/db/data-fake.js b/server/db/data-fake.js index ea5fe92..7ea1fd6 100644 --- a/server/db/data-fake.js +++ b/server/db/data-fake.js @@ -3,11 +3,52 @@ const encriptar = require('../helper/encriptar'); const Usuario = require('./tablas/Usuario'); const Programa = require('./tablas/Programa'); -const correosExt = ['lemuel@acatlan.unam.mx']; -const correosInt = ['cidwa1@pcpuma.acatlan.unam.mx']; +const correosExt = ['eithan.castillo@acatlan.unam.mx']; +const correosInt = ['316092940@pcpuma.acatlan.unam.mx']; const nombresExt = ['Lemuel Rosas']; const nombresInt = ['Lemuel Márquez']; + + + +// create los admin son los encargados de cada programa +const createAdmin = async () => { + console.log('\nPaso 1) Instalando Responsables Externos falsos.'.bold.blue); + for (let i = 0; i < correosExt.length; i++) { + await Usuario.create({ + usuario: correosExt[i], + idTipoUsuario: 2, + nombre: nombresExt[i], + password: encriptar.encriptar('qwertyui'), + activo: true, + }).then(async (res) => { + console.log(`Se inserto al responsable ${nombresExt[i]}`.magenta); + for (let j = 1; j <= 5; j++) { + await Programa.create({ + institucion: `Institucion Falsa ${i + 1}`, + dependencia: `Dependencia Falsa ${j - i + 1}`, + programa: `Programa Falso ${j}`, + clavePrograma: `2020-${j}/${i + j + 1}-${i + j + 1}`, + idUsuario: res.dataValues.idUsuario, + }); + console.log( + `Se inserto el programa ${j} del responsable ${i + 1}`.magenta + ); + } + }); + } +}; + + + + + + + + + + + const dataResponsableExt = async () => { console.log('\nPaso 1) Instalando Responsables Externos falsos.'.bold.blue); for (let i = 0; i < correosExt.length; i++) { diff --git a/server/db/install.js b/server/db/install.js index e050a12..439798e 100644 --- a/server/db/install.js +++ b/server/db/install.js @@ -10,8 +10,8 @@ const CasoEspecial = require('./tablas/CasoEspecial'); const Status = require('./tablas/Status'); const TipoUsuario = require('./tablas/TipoUsuario'); const Usuario = require('./tablas/Usuario'); -const CuestionarioAlumno = require('./tablas/CuestionarioAlumno'); -const CuestionarioPrograma = require('./tablas/CuestionarioPrograma'); +const CuestionarioAlumno2 = require('./tablas/CuestionarioAlumno2'); +const CuestionarioPrograma2 = require('./tablas/CuestionarioPrograma2'); const drop = async () => { console.log('\nPaso 1) Desinstalando la db.'.bold.blue); @@ -49,7 +49,7 @@ const drop = async () => { - await CuestionarioPrograma2.drop(); +/* await CuestionarioPrograma2.drop(); console.log( 'La tabla CuestionarioPrograma se desinstalo correctamente.'.magenta ); @@ -57,7 +57,7 @@ const drop = async () => { await CuestionarioAlumno2.drop(); console.log( 'La tabla CuestionarioAlumno se desinstalo correctamente.'.magenta - ); + ); */ }; @@ -98,13 +98,13 @@ const sync = async () => { console.log('La tabla CasoEspecial se instalo correctamente.'.magenta); - await CuestionarioAlumno2.sync(); + /* await CuestionarioAlumno2.sync(); console.log('La tabla CuestionarioAlumno se instalo correctamente.'.magenta); await CuestionarioPrograma2.sync(); console.log( 'La tabla CuestionarioPrograma se instalo correctamente.'.magenta - ); + ); */ }; @@ -154,7 +154,7 @@ const dataAdmin = async () => { }); }; -const dataResponsableCasoEspecial = async () => { +/* const dataResponsableCasoEspecial = async () => { console.log( '\nPaso 6) Instalando responsable de casos especiales.'.bold.blue ); @@ -165,7 +165,7 @@ const dataResponsableCasoEspecial = async () => { idTipoUsuario: 4, activo: true, }); -}; +}; */ const exe = async () => { await drop(); @@ -173,7 +173,7 @@ const exe = async () => { await dataTipoUsuario(); await dataStatus(); await dataAdmin(); - await dataResponsableCasoEspecial(); + //await dataResponsableCasoEspecial(); console.log( '\nSe ha instalado exitosamente la base de datos.\n'.underline.bold.green ); diff --git a/server/middleware/autentificacion.js b/server/middleware/autentificacion.js index 722180b..ce8a42d 100644 --- a/server/middleware/autentificacion.js +++ b/server/middleware/autentificacion.js @@ -2,8 +2,10 @@ require('../config/config'); const jwt = require('jsonwebtoken'); const verificaToken = (req, res, next) => { + let token = req.headers.token; + /* if (!token) return res.status(400).json({ message: 'No se envio el token. v2', @@ -23,6 +25,10 @@ const verificaToken = (req, res, next) => { req.decoded = decoded; next(); }); + + */ + + next() }; const crearToken = (info) => { diff --git a/testing.sql b/testing.sql new file mode 100644 index 0000000..e6fca41 --- /dev/null +++ b/testing.sql @@ -0,0 +1,511 @@ +-- MariaDB dump 10.17 Distrib 10.4.10-MariaDB, for Win64 (AMD64) +-- +-- Host: 132.248.180.82 Database: Iris_Produccion +-- ------------------------------------------------------ +-- Server version 10.6.7-MariaDB + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8mb4 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Table structure for table `carrera` +-- + +drop database servicio_test; +create database servicio_test; +use servicio_test; + + +DROP TABLE IF EXISTS `carrera`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `carrera` ( + `idCarrera` int(11) NOT NULL AUTO_INCREMENT, + `carrera` varchar(50) NOT NULL, + PRIMARY KEY (`idCarrera`), + UNIQUE KEY `idCarrera` (`idCarrera`) +) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `carrera` +-- + +LOCK TABLES `carrera` WRITE; +/*!40000 ALTER TABLE `carrera` DISABLE KEYS */; +INSERT INTO `carrera` VALUES (1,'LIC. EN DERECHO'),(2,'LIC. EN ACTUARIA'),(3,'LIC. EN MATEMATICAS APLICADAS Y COMP.'),(4,'LIC. EN COMUNICACION'),(5,'LIC. EN ECONOMIA'),(6,'LIC. EN PERIODISMO Y COMUNICACION COL.'),(7,'LIC. EN RELACIONES INTERNACIONALES'),(8,'LIC. EN FILOSOFIA'),(9,'LIC. EN HISTORIA'),(10,'LIC. EN LENGUA Y LITERATURA HISPANICAS'),(11,'LIC. EN SOCIOLOGIA'),(12,'LIC. EN CIENCIAS POLITICAS Y ADMON PUB'),(13,'LIC. EN INGENIERIA CIVIL'),(14,'LIC. EN ENSEÑANZA DE INGLES'),(15,'LIC. EN DISEÑO GRAFICO'),(16,'LIC. EN PEDAGOGÍA'),(17,'LIC. EN DERECHO (SUA)'),(18,'LIC. ENSEÑANZA DE ESPAÑOL(LENG. EXTRANJ)'),(19,'LIC. ENSEÑANZA DE ITALIANO(LENG. EXTRANJ'),(20,'LIC. EN ARQUITECTURA'),(21,'LIC. EN RELACIONES INTERNACIONALES (SUA)'),(22,'LIC. ENSEÑANZA DE INGLÉS(LENG. EXTRANJE)'),(23,'LIC. ENSEÑANZA DE ALEMÁN (LENG. EXTRANJS'),(24,'LIC. EN MAT. APLICADAS Y COMPUTACION'),(25,'LIC. EN CIENCIAS POLITICAS Y ADMON.PUBL.'),(26,'LIC. ENSEÑANZA DE FRANCÉS(LENG. EXTRANJ)'); +/*!40000 ALTER TABLE `carrera` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `caso_especial` +-- + +DROP TABLE IF EXISTS `caso_especial`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `caso_especial` ( + `idCasoEspecial` int(11) NOT NULL AUTO_INCREMENT, + `creditos` varchar(3) NOT NULL, + `correo` varchar(60) NOT NULL, + `telefono` varchar(15) NOT NULL, + `institucion` varchar(200) DEFAULT NULL, + `dependencia` varchar(200) DEFAULT NULL, + `motivo` varchar(1) DEFAULT NULL, + `direccion` varchar(200) NOT NULL, + `fechaInicio` datetime NOT NULL, + `fechaFin` datetime NOT NULL, + `fechaNacimiento` datetime NOT NULL, + `carpeta` varchar(60) NOT NULL, + `archivoZip` varchar(60) NOT NULL, + `createdAt` datetime NOT NULL, + `updatedAt` datetime NOT NULL, + `idUsuario` int(11) NOT NULL, + `idCarrera` int(11) NOT NULL, + `idStatus` int(11) NOT NULL DEFAULT 1, + PRIMARY KEY (`idCasoEspecial`), + UNIQUE KEY `idCasoEspecial` (`idCasoEspecial`), + KEY `idUsuario` (`idUsuario`), + KEY `idCarrera` (`idCarrera`), + KEY `idStatus` (`idStatus`), + CONSTRAINT `caso_especial_ibfk_1` FOREIGN KEY (`idUsuario`) REFERENCES `usuario` (`idUsuario`) ON DELETE NO ACTION ON UPDATE CASCADE, + CONSTRAINT `caso_especial_ibfk_2` FOREIGN KEY (`idCarrera`) REFERENCES `carrera` (`idCarrera`) ON DELETE NO ACTION ON UPDATE CASCADE, + CONSTRAINT `caso_especial_ibfk_3` FOREIGN KEY (`idStatus`) REFERENCES `status` (`idStatus`) ON DELETE NO ACTION ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=392 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `caso_especial` +-- + +LOCK TABLES `caso_especial` WRITE; +/*!40000 ALTER TABLE `caso_especial` DISABLE KEYS */; +/*!40000 ALTER TABLE `caso_especial` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cuestionario_alumno` +-- + +DROP TABLE IF EXISTS `cuestionario_alumno`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `cuestionario_alumno` ( + `idCuestionarioAlumno` int(11) NOT NULL AUTO_INCREMENT, + `sexo` varchar(1) NOT NULL, + `edad` varchar(2) NOT NULL, + `servicioMedico` varchar(100) NOT NULL, + `p1` tinyint(1) NOT NULL, + `p2` tinyint(1) NOT NULL, + `p3` varchar(150) NOT NULL, + `p4` tinyint(1) NOT NULL, + `p5` varchar(7) NOT NULL, + `p6` tinyint(1) NOT NULL, + `p7` tinyint(1) NOT NULL, + `p8` varchar(5) NOT NULL, + `p9` tinyint(1) NOT NULL, + `p10` tinyint(1) NOT NULL, + `p11` tinyint(1) NOT NULL, + `p12` tinyint(1) NOT NULL, + `p13` tinyint(1) NOT NULL, + `p14` varchar(7) NOT NULL, + `p15` varchar(7) NOT NULL, + `p16` varchar(2) NOT NULL, + `p17` varchar(5) NOT NULL, + `p18` tinyint(1) NOT NULL, + `p19` tinyint(1) NOT NULL, + `p20` tinyint(1) NOT NULL, + `p21` varchar(9) NOT NULL, + `p22` varchar(23) NOT NULL, + `p23` varchar(8) NOT NULL, + `p24` varchar(8) NOT NULL, + `p25` tinyint(1) NOT NULL, + `p26` tinyint(1) NOT NULL, + `p27` varchar(400) NOT NULL, + `p28` varchar(1) NOT NULL, + `p29` varchar(1) NOT NULL, + `p30` varchar(400) NOT NULL, + `createdAt` datetime NOT NULL, + PRIMARY KEY (`idCuestionarioAlumno`), + UNIQUE KEY `idCuestionarioAlumno` (`idCuestionarioAlumno`) +) ENGINE=InnoDB AUTO_INCREMENT=13564 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `cuestionario_alumno` +-- + +LOCK TABLES `cuestionario_alumno` WRITE; +/*!40000 ALTER TABLE `cuestionario_alumno` DISABLE KEYS */; + + +/*!40000 ALTER TABLE `cuestionario_alumno` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `cuestionario_programa` +-- + +DROP TABLE IF EXISTS `cuestionario_programa`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `cuestionario_programa` ( + `idCuestionarioPrograma` int(11) NOT NULL AUTO_INCREMENT, + `actividad1` varchar(400) NOT NULL, + `actividad2` varchar(400) NOT NULL, + `actividad3` varchar(400) NOT NULL, + `actividad4` varchar(400) NOT NULL, + `actividad5` varchar(400) NOT NULL, + `retroalimentacion` varchar(9) NOT NULL, + `p6` varchar(800) DEFAULT NULL, + `p7` varchar(800) NOT NULL, + `createdAt` datetime NOT NULL, + PRIMARY KEY (`idCuestionarioPrograma`), + UNIQUE KEY `idCuestionarioPrograma` (`idCuestionarioPrograma`) +) ENGINE=InnoDB AUTO_INCREMENT=13582 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `cuestionario_programa` +-- + +LOCK TABLES `cuestionario_programa` WRITE; +/*!40000 ALTER TABLE `cuestionario_programa` DISABLE KEYS */; +/*!40000 ALTER TABLE `cuestionario_programa` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `programa` +-- + +DROP TABLE IF EXISTS `programa`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `programa` ( + `idPrograma` int(11) NOT NULL AUTO_INCREMENT, + `institucion` varchar(120) NOT NULL, + `dependencia` varchar(120) NOT NULL, + `programa` varchar(280) NOT NULL, + `clavePrograma` varchar(20) NOT NULL, + `acatlan` tinyint(1) NOT NULL DEFAULT 0, + `activo` tinyint(1) NOT NULL DEFAULT 1, + `idUsuario` int(11) NOT NULL, + PRIMARY KEY (`idPrograma`), + UNIQUE KEY `idPrograma` (`idPrograma`), + KEY `idUsuario` (`idUsuario`), + CONSTRAINT `programa_ibfk_1` FOREIGN KEY (`idUsuario`) REFERENCES `usuario` (`idUsuario`) ON DELETE NO ACTION ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=11518 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `programa` +-- + +LOCK TABLES `programa` WRITE; +/*!40000 ALTER TABLE `programa` DISABLE KEYS */; +/*!40000 ALTER TABLE `programa` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `servicio` +-- + +DROP TABLE IF EXISTS `servicio`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `servicio` ( + `idServicio` int(11) NOT NULL AUTO_INCREMENT, + `creditos` varchar(3) NOT NULL, + `correo` varchar(60) NOT NULL, + `telefono` varchar(15) DEFAULT NULL, + `direccion` varchar(200) DEFAULT NULL, + `fechaInicio` datetime NOT NULL, + `fechaFin` datetime NOT NULL, + `fechaNacimiento` datetime DEFAULT NULL, + `carpeta` varchar(60) NOT NULL, + `cartaAceptacion` varchar(60) NOT NULL, + `cartaTermino` varchar(60) DEFAULT NULL, + `informeGlobal` varchar(60) DEFAULT NULL, + `programaInterno` varchar(250) DEFAULT NULL, + `profesor` varchar(50) DEFAULT NULL, + `vistoBuenoAcatlan` tinyint(1) DEFAULT NULL, + `createdAt` datetime NOT NULL, + `updatedAt` datetime NOT NULL, + `idUsuario` int(11) NOT NULL, + `idCarrera` int(11) NOT NULL, + `idStatus` int(11) NOT NULL DEFAULT 1, + `idPrograma` int(11) NOT NULL, + `idCuestionarioAlumno` int(11) DEFAULT NULL, + `idCuestionarioPrograma` int(11) DEFAULT NULL, + `fechaLiberacion` datetime DEFAULT NULL, + PRIMARY KEY (`idServicio`), + UNIQUE KEY `idServicio` (`idServicio`), + KEY `idUsuario` (`idUsuario`), + KEY `idCarrera` (`idCarrera`), + KEY `idStatus` (`idStatus`), + KEY `idPrograma` (`idPrograma`), + KEY `idCuestionarioAlumno` (`idCuestionarioAlumno`), + KEY `idCuestionarioPrograma` (`idCuestionarioPrograma`), + CONSTRAINT `servicio_ibfk_1` FOREIGN KEY (`idUsuario`) REFERENCES `usuario` (`idUsuario`) ON DELETE NO ACTION ON UPDATE CASCADE, + CONSTRAINT `servicio_ibfk_2` FOREIGN KEY (`idCarrera`) REFERENCES `carrera` (`idCarrera`) ON DELETE NO ACTION ON UPDATE CASCADE, + CONSTRAINT `servicio_ibfk_3` FOREIGN KEY (`idStatus`) REFERENCES `status` (`idStatus`) ON DELETE NO ACTION ON UPDATE CASCADE, + CONSTRAINT `servicio_ibfk_4` FOREIGN KEY (`idPrograma`) REFERENCES `programa` (`idPrograma`) ON DELETE NO ACTION ON UPDATE CASCADE, + CONSTRAINT `servicio_ibfk_5` FOREIGN KEY (`idCuestionarioAlumno`) REFERENCES `cuestionario_alumno` (`idCuestionarioAlumno`) ON DELETE SET NULL ON UPDATE CASCADE, + CONSTRAINT `servicio_ibfk_6` FOREIGN KEY (`idCuestionarioPrograma`) REFERENCES `cuestionario_programa` (`idCuestionarioPrograma`) ON DELETE SET NULL ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=17310 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `servicio` +-- + +LOCK TABLES `servicio` WRITE; +/*!40000 ALTER TABLE `servicio` DISABLE KEYS */; +/*!40000 ALTER TABLE `servicio` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `status` +-- + +DROP TABLE IF EXISTS `status`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `status` ( + `idStatus` int(11) NOT NULL AUTO_INCREMENT, + `status` varchar(30) NOT NULL, + PRIMARY KEY (`idStatus`), + UNIQUE KEY `idStatus` (`idStatus`) +) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `status` +-- + +LOCK TABLES `status` WRITE; +/*!40000 ALTER TABLE `status` DISABLE KEYS */; +INSERT INTO `status` VALUES (1,'Pre-Registro'),(2,'Pre-Registro Validado'),(3,'Registro'),(4,'Pre-Termino'),(5,'Termino'),(6,'Liberación'),(7,'Carta Aceptación Rechazada'),(8,'Carta Termino Rechazada'),(9,'Informe Global Rechazado'),(10,'Cancelado'),(11,'Articulo 52'),(12,'Articulo 91'),(13,'Liberación Articulo 52'),(14,'Liberación Articulo 91'); +/*!40000 ALTER TABLE `status` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `tipo_usuario` +-- + +DROP TABLE IF EXISTS `tipo_usuario`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `tipo_usuario` ( + `idTipoUsuario` int(11) NOT NULL AUTO_INCREMENT, + `tipoUsuario` varchar(15) NOT NULL, + PRIMARY KEY (`idTipoUsuario`), + UNIQUE KEY `idTipoUsuario` (`idTipoUsuario`) +) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `tipo_usuario` +-- + +LOCK TABLES `tipo_usuario` WRITE; +/*!40000 ALTER TABLE `tipo_usuario` DISABLE KEYS */; +INSERT INTO `tipo_usuario` VALUES (1,'admin'),(2,'responsable'),(3,'alumno'),(4,'casoEspecial'); +/*!40000 ALTER TABLE `tipo_usuario` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Table structure for table `usuario` +-- + +DROP TABLE IF EXISTS `usuario`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `usuario` ( + `idUsuario` int(11) NOT NULL AUTO_INCREMENT, + `usuario` varchar(100) NOT NULL, + `password` varchar(60) DEFAULT NULL, + `nombre` varchar(70) DEFAULT NULL, + `activo` tinyint(1) NOT NULL, + `idTipoUsuario` int(11) NOT NULL, + PRIMARY KEY (`idUsuario`), + UNIQUE KEY `idUsuario` (`idUsuario`), + UNIQUE KEY `usuario` (`usuario`), + KEY `idTipoUsuario` (`idTipoUsuario`), + CONSTRAINT `usuario_ibfk_1` FOREIGN KEY (`idTipoUsuario`) REFERENCES `tipo_usuario` (`idTipoUsuario`) ON DELETE NO ACTION ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=19930 DEFAULT CHARSET=latin1; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping data for table `usuario` +-- + +LOCK TABLES `usuario` WRITE; +/*!40000 ALTER TABLE `usuario` DISABLE KEYS */; + + +INSERT INTO `usuario` VALUES (1,'ejemplo1','$2b$10$lpasLiiPi/OTCL84PK8n4./Y7EVqPjC306JS4jJOB2i7JkUJoExsO','COESI',1,1) + +/*!40000 ALTER TABLE `usuario` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping routines for database 'Iris_Produccion' +-- +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2025-01-12 23:25:49 + + + + + + + + + + + +/* CREATE TABLE `servicio` ( +`idServicio` INT PRIMARY KEY +); */ +--DROP TABLE IF EXISTS `Cuestionario`; + +CREATE TABLE + `Cuestionario` ( + `idCuestionario` INT PRIMARY KEY NOT NULL AUTO_INCREMENT, + `idServicio` INT, + `version` VARCHAR(50), + `titulo` VARCHAR(50), + `desc` VARCHAR(50), + `dirigidoA` VARCHAR(50), + `createdAt` DATETIME + ); + + --`idCuestionarioAlumno` INT, -- Agregado para relación con alumnos + --`idCuestionarioPrograma` INT, -- Agregado para relación con programas + -- `idCuestionarioAlumno1` INT, -- Agregado para relación con alumnos + -- `idCuestionarioPrograma1` INT, -- Agregado para relación con programas + +DROP TABLE IF EXISTS `cuestionario_alumno_2`; + +CREATE TABLE + `cuestionario_alumno_2` ( + `idCuestionarioAlumno2` INT PRIMARY KEY NOT NULL AUTO_INCREMENT, + `idCuestionario` INT, + `createdAt` DATETIME, + `p12_A_1` VARCHAR(50), + `p12_A_2` VARCHAR(50), + `p12_A_3` VARCHAR(50), + `p12_A_4` VARCHAR(50), + `p12_B_1` VARCHAR(50), + `p12_B_2` VARCHAR(50), + `p12_B_3` VARCHAR(50), + `p12_B_4` VARCHAR(50), + `p12_C_1` VARCHAR(50), + `p12_C_2` VARCHAR(50), + `p12_C_3` VARCHAR(50), + `p12_C_4` VARCHAR(50), + `p10_1` VARCHAR(50), + `p10_2` VARCHAR(50), + `p10_3` VARCHAR(50), + `p11_1` VARCHAR(50), + `p11_2` VARCHAR(50), + `p11_3` VARCHAR(50), + `p11_4` VARCHAR(50), + `p17_1` VARCHAR(50), + `p17_2` VARCHAR(50), + `p17_3` VARCHAR(50), + `p3_1` VARCHAR(50), + `p3_2` VARCHAR(50), + `p3_3` VARCHAR(50), + `p3_4` VARCHAR(50), + `p12_D_1` VARCHAR(50), + `p12_D_2` VARCHAR(50), + `p12_D_3` VARCHAR(50), + `p12_D_4` VARCHAR(50), + `p12_D_5` VARCHAR(50), + `p1` VARCHAR(150), + `p2` VARCHAR(50), + `p4` VARCHAR(50), + `p5` VARCHAR(50), + `p6` VARCHAR(50), + `p7` VARCHAR(50), + `p8` VARCHAR(50), + `p9` VARCHAR(50), + `p13` VARCHAR(50), + `p14` VARCHAR(50), + `p15` VARCHAR(50), + `p16` VARCHAR(50), + `p18` VARCHAR(50) + ); + +DROP TABLE IF EXISTS `cuestionario_programa_2`; + +CREATE TABLE + `cuestionario_programa_2` ( + `idCuestionarioPrograma2` INT PRIMARY KEY NOT NULL AUTO_INCREMENT, + `idCuestionario` INT, + `createdAt` DATETIME, + `p3_A_1` VARCHAR(50), + `p3_A_2` VARCHAR(50), + `p3_A_3` VARCHAR(50), + `p3_A_4` VARCHAR(50), + `p3_B_1` VARCHAR(50), + `p3_B_2` VARCHAR(50), + `p3_B_3` VARCHAR(50), + `p3_B_4` VARCHAR(50), + `p3_C_1` VARCHAR(50), + `p3_C_2` VARCHAR(50), + `p3_C_3` VARCHAR(50), + `p3_C_4` VARCHAR(50), + `p3_C_5` VARCHAR(50), + `p3_D_1` VARCHAR(50), + `p3_D_2` VARCHAR(50), + `p3_D_3` VARCHAR(50), + `p3_D_4` VARCHAR(50), + `p3_D_5` VARCHAR(50), + `p3_E_1` VARCHAR(50), + `p1` VARCHAR(50), + `p2` VARCHAR(50), + `p4` VARCHAR(50), + `p5` VARCHAR(50), + `p6` VARCHAR(50), + `p7` VARCHAR(50) + ); + +-- Relaciones corregidas +ALTER TABLE `Cuestionario` ADD FOREIGN KEY (`idServicio`) REFERENCES `servicio` (`idServicio`); + +ALTER TABLE cuestionario_alumno ADD COLUMN idCuestionario INT; +ALTER TABLE cuestionario_programa ADD COLUMN idCuestionario INT; + +ALTER TABLE `cuestionario_alumno` ADD FOREIGN KEY (`idCuestionario`) REFERENCES `Cuestionario` (`idCuestionario`); +ALTER TABLE `cuestionario_alumno_2` ADD FOREIGN KEY (`idCuestionario`) REFERENCES `Cuestionario` (`idCuestionario`); +ALTER TABLE `cuestionario_programa` ADD FOREIGN KEY (`idCuestionario`) REFERENCES `Cuestionario` (`idCuestionario`); +ALTER TABLE `cuestionario_programa_2` ADD FOREIGN KEY (`idCuestionario`) REFERENCES `Cuestionario` (`idCuestionario`); + +--ALTER TABLE `Cuestionario` +--ADD FOREIGN KEY (`idCuestionarioAlumno`) REFERENCES `cuestionario_alumno_2` (`idCuestionarioAlumno2`); +--ALTER TABLE `Cuestionario` +--ADD FOREIGN KEY (`idCuestionarioPrograma`) REFERENCES `cuestionario_programa_2` (`idCuestionarioPrograma2`); +--ALTER TABLE `Cuestionario` +--ADD FOREIGN KEY (`idCuestionarioAlumno1`) REFERENCES `cuestionario_alumno` (`idCuestionarioAlumno`); +--ALTER TABLE `Cuestionario` +--ADD FOREIGN KEY (`idCuestionarioPrograma1`) REFERENCES `cuestionario_programa` (`idCuestionarioPrograma`); -- 2.43.0 From 7e29a5e5b45ee73f5bf5c7f2b8808ef5d26544c8 Mon Sep 17 00:00:00 2001 From: Tu Nombre Date: Fri, 7 Feb 2025 18:07:41 -0600 Subject: [PATCH 16/21] escolares --- Dockerfile | 20 + README.md | 7 +- Servicios.postman_collection.json | 502 +++++++++++++++++++++++++ escolares_internal_test.sql | 107 ++++++ server/controller/Usuario/escolares.js | 14 + server/db/data-fake.js | 78 ++-- 6 files changed, 699 insertions(+), 29 deletions(-) create mode 100644 Dockerfile create mode 100644 Servicios.postman_collection.json create mode 100644 escolares_internal_test.sql diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..d94364d --- /dev/null +++ b/Dockerfile @@ -0,0 +1,20 @@ +# Usa una imagen base de Node.js +FROM node:16 + +# Establece el directorio de trabajo dentro del contenedor +WORKDIR /usr/src/app + +# Copia los archivos de package.json y package-lock.json (si existe) +COPY package*.json ./ + +# Instala las dependencias +RUN npm install + +# Copia el código fuente de la aplicación +COPY . . + +# Expone el puerto que la app usará +EXPOSE 3000 + +# Comando por defecto para ejecutar la aplicación en desarrollo +CMD ["npm", "run", "dev"] diff --git a/README.md b/README.md index 5cf8637..3456870 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,12 @@ -Documentacion del sistema IRIS +# Documentacion del sistema IRIS + + + + + Tipos de usuarios diff --git a/Servicios.postman_collection.json b/Servicios.postman_collection.json new file mode 100644 index 0000000..32b67f0 --- /dev/null +++ b/Servicios.postman_collection.json @@ -0,0 +1,502 @@ +{ + "info": { + "_postman_id": "5672f077-78c4-41d4-8877-6c8ccddbf3ef", + "name": "Servicios", + "schema": "https://schema.getpostman.com/json/collection/v2.0.0/collection.json", + "_exporter_id": "39860549" + }, + "item": [ + { + "name": "cuestionarios", + "item": [ + { + "name": "cuestionario_alumno", + "protocolProfileBehavior": { + "disableBodyPruning": true + }, + "request": { + "method": "GET", + "header": [], + "body": { + "mode": "raw", + "raw": "{\n \"year\":\"2024\"\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{api}}/cuestionario_alumno?year=2024", + "host": [ + "{{api}}" + ], + "path": [ + "cuestionario_alumno" + ], + "query": [ + { + "key": "year", + "value": "2024" + } + ] + } + }, + "response": [] + }, + { + "name": "cuestionario_alumno", + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "raw", + "raw": "{\n \"token\":\"asdfasdf\",\n \"idServicio\":3,\n \n \"p1\": \"Dependencia de la UNAM, Asesoría académica, Oportunidad de desarrollo de tesis\",\n\n \"p12_A_1\": \"Deficiente\",\n \"p12_A_2\": \"Deficiente\",\n \"p12_A_3\": \"Deficiente\",\n \"p12_A_4\": \"Deficiente\",\n \"p12_B_1\": \"Básico\",\n \"p12_B_2\": \"Básico\",\n \"p12_B_3\": \"Básico\",\n \"p12_B_4\": \"Básico\",\n \"p12_C_1\": \"Intermedio\",\n \"p12_C_2\": \"Intermedio\",\n \"p12_C_3\": \"Intermedio\",\n \"p12_C_4\": \"Intermedio\",\n \"p10_1\": \"si\",\n \"p10_2\": \"si\",\n \"p10_3\": \"si\",\n \"p11_1\": \"Nunca\",\n \"p11_2\": \"Rara vez\",\n \"p11_3\": \"Algunas veces\",\n \"p11_4\": \"Siempre\",\n \"p17_1\": \"si\",\n \"p17_2\": \"no\",\n \"p17_3\": \"si\",\n \"p3_1\": \"si\",\n \"p3_2\": \"si\",\n \"p3_3\": \"si\",\n \"p3_4\": \"si\",\n \"p12_D_1\": \"Destacado\",\n \"p12_D_2\": \"Destacado\",\n \"p12_D_3\": \"Destacado\",\n \"p12_D_4\": \"Destacado\",\n \"p12_D_5\": \"Destacado\",\n \"p2\": \"Deficiente\",\n \"p4\": \"No\",\n \"p5\": \"respuesta5\",\n \"p6\": \"Sí\",\n \"p7\": \"Sí\",\n \"p8\": \"respuesta8\",\n \"p9\": \"Sí\",\n \"p13\": \"Responsable directo del programa\",\n \"p14\": \"Se te otorgó de acuerdo a lo establecido\",\n \"p15\": \"Sí\",\n \"p16\": \"respuesta 16\",\n \"p18\": \"respuesta18\"\n\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": "{{api}}/cuestionario_alumno" + }, + "response": [] + } + ] + }, + { + "name": "usuarios", + "item": [ + { + "name": "login", + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "raw", + "raw": "{\n usuario:\"asdfasdf\"\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": "{{api}}/usuario/login" + }, + "response": [] + }, + { + "name": "escolares", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/usuario/escolares" + }, + "response": [] + }, + { + "name": "responsable", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/usuario/responsable" + }, + "response": [] + }, + { + "name": "responsables", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/usuario/responsables" + }, + "response": [] + }, + { + "name": "new pass alumno", + "request": { + "method": "PUT", + "header": [], + "url": "{{api}}/usuario/new_password_alumno" + }, + "response": [] + }, + { + "name": "new pass respon", + "request": { + "method": "PUT", + "header": [], + "url": "{{api}}/usuario/new_password_responsable" + }, + "response": [] + }, + { + "name": "responsable update", + "request": { + "method": "PUT", + "header": [], + "url": "{{api}}/usuario/responsable/update" + }, + "response": [] + } + ] + }, + { + "name": "status", + "item": [ + { + "name": "status", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/status" + }, + "response": [] + } + ] + }, + { + "name": "servicio", + "item": [ + { + "name": "status Copy", + "request": { + "method": "POST", + "header": [], + "url": "{{api}}/servicio/nuevo" + }, + "response": [] + }, + { + "name": "status Copy 2", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/servicio/admin" + }, + "response": [] + }, + { + "name": "status Copy 3", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/servicio/alumno" + }, + "response": [] + }, + { + "name": "status Copy 4", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/servicio/gustavo_baz_prada" + }, + "response": [] + }, + { + "name": "status Copy 5", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/servicio/reporte" + }, + "response": [] + }, + { + "name": "status Copy 6", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/servicio/servicios_admin" + }, + "response": [] + }, + { + "name": "status Copy 7", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/servicio/servicios_responsable" + }, + "response": [] + }, + { + "name": "status Copy 8", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/servicio/cancelar" + }, + "response": [] + }, + { + "name": "status Copy 9", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/servicio/carta_aceptacion" + }, + "response": [] + }, + { + "name": "status Copy 10", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/servicio/carta_termino" + }, + "response": [] + }, + { + "name": "status Copy 11", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/servicio/informe_global" + }, + "response": [] + }, + { + "name": "status Copy 12", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/servicio/liberacion" + }, + "response": [] + }, + { + "name": "status Copy 13", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/servicio/registro" + }, + "response": [] + }, + { + "name": "status Copy 14", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/servicio/registro_validado" + }, + "response": [] + }, + { + "name": "status Copy 15", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/servicio/rechazar_aceptacion" + }, + "response": [] + }, + { + "name": "status Copy 16", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/servicio/rechazar_informe" + }, + "response": [] + }, + { + "name": "status Copy 17", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/servicio/rechazar_termino" + }, + "response": [] + }, + { + "name": "status Copy 18", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/servicio/update" + }, + "response": [] + } + ] + }, + { + "name": "Programa", + "item": [ + { + "name": "status Copy 2", + "request": { + "method": "POST", + "header": [], + "url": "{{api}}/programa/carga_masiva" + }, + "response": [] + }, + { + "name": "status Copy 3", + "request": { + "method": "POST", + "header": [], + "url": "{{api}}/programa/reasignar_programas" + }, + "response": [] + }, + { + "name": "status Copy 4", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/programa/programas_admin" + }, + "response": [] + }, + { + "name": "status Copy 5", + "request": { + "method": "POST", + "header": [], + "url": "{{api}}/programa/programas_responsable" + }, + "response": [] + } + ] + }, + { + "name": "cuestionario", + "item": [ + { + "name": "cuestonario programa", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/cuestionario_programa" + }, + "response": [] + }, + { + "name": "cuestonario programa Copy", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/cuestionario_programa" + }, + "response": [] + }, + { + "name": "cuestonario alumno", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/cuestionario_alumno" + }, + "response": [] + }, + { + "name": "cuestonario alumno", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/cuestionario_alumno" + }, + "response": [] + } + ] + }, + { + "name": "caso especial", + "item": [ + { + "name": "cuestonario alumno Copy", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/caso_especial/nuevo" + }, + "response": [] + }, + { + "name": "cuestonario alumno Copy 2", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/caso_especial" + }, + "response": [] + }, + { + "name": "cuestonario alumno Copy 3", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/caso_especial/servicios_especiales" + }, + "response": [] + }, + { + "name": "cuestonario alumno Copy 4", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/caso_especial/liberacion" + }, + "response": [] + }, + { + "name": "cuestonario alumno Copy 5", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}/caso_especial/update" + }, + "response": [] + } + ] + }, + { + "name": "New Request", + "request": { + "method": "GET", + "header": [], + "url": "{{api}}" + }, + "response": [] + } + ], + "event": [ + { + "listen": "prerequest", + "script": { + "type": "text/javascript", + "packages": {}, + "exec": [ + "" + ] + } + }, + { + "listen": "test", + "script": { + "type": "text/javascript", + "packages": {}, + "exec": [ + "" + ] + } + } + ], + "variable": [ + { + "key": "api", + "value": "http://localhost:3072", + "type": "string" + }, + { + "key": "api", + "value": "https://venus.acatlan.unam.mx/ss-pruebas", + "type": "string", + "disabled": true + } + ] +} \ No newline at end of file diff --git a/escolares_internal_test.sql b/escolares_internal_test.sql new file mode 100644 index 0000000..97b82d7 --- /dev/null +++ b/escolares_internal_test.sql @@ -0,0 +1,107 @@ +CREATE DATABASE Universidad; +USE Universidad; + + +CREATE TABLE Alumnos ( cuenta INT PRIMARY KEY, nombre VARCHAR(255), carrera VARCHAR(255), creditos DECIMAL(5,2)); + +INSERT INTO Alumnos (cuenta, nombre, carrera, creditos) VALUES +(455229002, 'Sara Francisco Ortega Ramos', 'LIC. EN FILOSOFIA', 3.37), +(344254873, 'Ing. Liliana García', 'LIC. ENSEÑANZA DE ESPAÑOL(LENG. EXTRANJ)', 54.26), +(108304507, 'Modesto Samaniego', 'LIC. EN COMUNICACION', 45.52), +(103285757, 'Rosalia Gonzalo Granado', 'LIC. EN LENGUA Y LITERATURA HISPANICAS', 83.41), +(510877055, 'Guillermo Cazares Vásquez', 'LIC. EN LENGUA Y LITERATURA HISPANICAS', 84.5), +(220810204, 'Wendolin Madera', 'LIC. EN ARQUITECTURA', 64.16), +(662985844, 'César Mayorga Rico', 'LIC. EN LENGUA Y LITERATURA HISPANICAS', 49.36), +(320707048, 'Natalia Martha Patiño', 'LIC. EN ARQUITECTURA', 75.9), +(460281371, 'Micaela Araceli Amaya', 'LIC. EN SOCIOLOGIA', 82.13), +(558466371, 'Fidel Vela Valencia', 'LIC. EN DISEÑO GRAFICO', 46.29), +(730812014, 'Yeni Pedro Collado Barraza', 'LIC. EN ACTUARIA', 64.73), +(657270526, 'Miriam María Eugenia Ochoa', 'LIC. EN HISTORIA', 6.06), +(553042949, 'Patricia Cristal Feliciano', 'LIC. EN MATEMATICAS APLICADAS Y COMP.', 21.64), +(256120924, 'Olga Federico Abrego Espinoza', 'LIC. EN LENGUA Y LITERATURA HISPANICAS', 57.51), +(580095253, 'Jaqueline Candelaria', 'LIC. EN INGENIERIA CIVIL', 21.71), +(894433015, 'Agustín Galván Salgado', 'LIC. ENSEÑANZA DE ALEMÁN (LENG. EXTRANJS', 10.66), +(249880845, 'Lic. Felipe Madrigal', 'LIC. EN LENGUA Y LITERATURA HISPANICAS', 21.64), +(776013075, 'Dr. Jerónimo Arteaga', 'LIC. ENSEÑANZA DE ESPAÑOL(LENG. EXTRANJ)', 90.96), +(711114545, 'Hermelinda Rendón Esquivel', 'LIC. ENSEÑANZA DE ESPAÑOL(LENG. EXTRANJ)', 98.52), +(969046528, 'Norma Rubio', 'LIC. EN FILOSOFIA', 40.1), +(977597890, 'Perla Guzmán Mora', 'LIC. EN INGENIERIA CIVIL', 79.66), +(989320527, 'Soledad Abreu', 'LIC. EN DERECHO (SUA)', 0.46), +(557675592, 'Juan Carlos Tovar', 'LIC. EN DERECHO', 86.37), +(454578965, 'Reynaldo Elias Berríos', 'LIC. EN LENGUA Y LITERATURA HISPANICAS', 51.72), +(574884941, 'Clara Alberto Bahena', 'LIC. EN RELACIONES INTERNACIONALES (SUA)', 43.79), +(344273189, 'Noemí Abrego Beltrán', 'LIC. EN RELACIONES INTERNACIONALES (SUA)', 92.72), +(920455788, 'Ilse Mata', 'LIC. EN ACTUARIA', 85.39), +(843807025, 'Alfredo Homero Lomeli', 'LIC. EN ENSEÑANZA DE INGLES', 98.72), +(737482670, 'Sr(a). Natalia Ortega', 'LIC. EN PEDAGOGÍA', 27.62), +(947886427, 'Amalia Emiliano Sanabria González', 'LIC. EN RELACIONES INTERNACIONALES', 23.84), +(303428996, 'Camilo Fajardo Caldera', 'LIC. EN COMUNICACION', 28.69), +(504420847, 'Socorro Gonzalo Varela Escalante', 'LIC. ENSEÑANZA DE INGLÉS(LENG. EXTRANJE)', 76.77), +(916897575, 'Lic. Armando Vallejo', 'LIC. EN RELACIONES INTERNACIONALES (SUA)', 76.18), +(910548164, 'Ing. Dulce Serna', 'LIC. ENSEÑANZA DE ITALIANO(LENG. EXTRANJ', 99.85), +(287603576, 'Bernardo Juana Barrientos Anguiano', 'LIC. EN SOCIOLOGIA', 83.36), +(127855790, 'Lilia Wendolin Urbina Hernández', 'LIC. EN MATEMATICAS APLICADAS Y COMP.', 28.4), +(572039876, 'Soledad Benjamín Tello Aranda', 'LIC. EN DERECHO (SUA)', 6.27), +(177669679, 'María Luisa Rodarte Sotelo', 'LIC. ENSEÑANZA DE INGLÉS(LENG. EXTRANJE)', 17.71), +(750642431, 'Dr. Fabiola Montoya', 'LIC. ENSEÑANZA DE ALEMÁN (LENG. EXTRANJS', 87.34), +(181357215, 'Berta Bruno Cervantes', 'LIC. EN DISEÑO GRAFICO', 98.56), +(837171875, 'Sandra Miriam Arevalo', 'LIC. EN HISTORIA', 77.77), +(865516896, 'Federico Rafaél Ozuna', 'LIC. EN FILOSOFIA', 5.81), +(418259119, 'Ing. Alfredo Galván', 'LIC. ENSEÑANZA DE ITALIANO(LENG. EXTRANJ', 74.91), +(654945240, 'Alejandra Miguel Ángel Paz', 'LIC. EN DERECHO', 70.53), +(838906646, 'Juana Valentín', 'LIC. EN FILOSOFIA', 13.81), +(786618542, 'Vanesa Contreras', 'LIC. EN CIENCIAS POLITICAS Y ADMON PUB', 18.42), +(311809331, 'Cristobal Lucía Lozano Rico', 'LIC. EN MAT. APLICADAS Y COMPUTACION', 46.31), +(633338912, 'Zacarías Zúñiga Cervantes', 'LIC. ENSEÑANZA DE ALEMÁN (LENG. EXTRANJS', 16.59), +(430388364, 'Linda Gómez', 'LIC. ENSEÑANZA DE ITALIANO(LENG. EXTRANJ', 30.53), +(494179153, 'Emiliano Robledo Montes', 'LIC. EN COMUNICACION', 90.31), +(761549514, 'Julia Rosa Corrales Luevano', 'LIC. ENSEÑANZA DE ESPAÑOL(LENG. EXTRANJ)', 68.57), +(917797548, 'Elvia Camarillo', 'LIC. EN DISEÑO GRAFICO', 93.9), +(656519098, 'Asunción Valles Arguello', 'LIC. EN DERECHO (SUA)', 49.11), +(959317624, 'Abraham Merino Collado', 'LIC. EN LENGUA Y LITERATURA HISPANICAS', 74.86), +(529088942, 'Mtro. José Emilio Carrero', 'LIC. EN DERECHO', 25.26), +(410136542, 'Lic. Ivonne Crespo', 'LIC. EN CIENCIAS POLITICAS Y ADMON PUB', 41.01), +(955532842, 'Hermelinda Violeta Vela', 'LIC. ENSEÑANZA DE ITALIANO(LENG. EXTRANJ', 23.99), +(944109052, 'Leonardo Mónica Arenas Barreto', 'LIC. EN CIENCIAS POLITICAS Y ADMON PUB', 65.66), +(736137931, 'Mtro. Vanesa Santiago', 'LIC. EN MAT. APLICADAS Y COMPUTACION', 60.6), +(548504744, 'René Gutiérrez Ozuna', 'LIC. EN ECONOMIA', 51.1), +(230591766, 'Esparta Zamudio Rendón', 'LIC. ENSEÑANZA DE ESPAÑOL(LENG. EXTRANJ)', 96.7), +(365584469, 'Lic. Jacinto Baeza', 'LIC. EN ENSEÑANZA DE INGLES', 16.6), +(366378810, 'Benito Garica Gómez', 'LIC. EN DISEÑO GRAFICO', 50.21), +(130793203, 'Mercedes Dalia Melgar', 'LIC. EN DISEÑO GRAFICO', 79.79), +(118327168, 'Aurelio Juana Chávez', 'LIC. EN PEDAGOGÍA', 65.11), +(541469134, 'René Estévez Alvarez', 'LIC. EN ENSEÑANZA DE INGLES', 83.62), +(146702834, 'Verónica Hugo Montañez Montero', 'LIC. EN ACTUARIA', 82.31), +(391227832, 'Federico Escobar Gollum', 'LIC. EN MATEMATICAS APLICADAS Y COMP.', 53.46), +(620658001, 'Ing. Bernabé Flores', 'LIC. EN ENSEÑANZA DE INGLES', 77.52), +(434742427, 'Esmeralda Yeni Téllez Guerrero', 'LIC. ENSEÑANZA DE ALEMÁN (LENG. EXTRANJS', 92.49), +(789523713, 'Margarita Bahena Rodríquez', 'LIC. EN MAT. APLICADAS Y COMPUTACION', 32.86), +(388536523, 'Hilda Aparicio Ulloa', 'LIC. EN RELACIONES INTERNACIONALES (SUA)', 29.32), +(533652320, 'Lic. Luis Miguel Concepción', 'LIC. EN RELACIONES INTERNACIONALES (SUA)', 57.32), +(766082299, 'Tomás Córdova', 'LIC. ENSEÑANZA DE ALEMÁN (LENG. EXTRANJS', 73.03), +(386050318, 'Noelia Villarreal Colón', 'LIC. EN RELACIONES INTERNACIONALES (SUA)', 17.6), +(746187129, 'Sr(a). Jos Nava', 'LIC. EN ARQUITECTURA', 95.45), +(485991016, 'Lucía Aurora Casárez', 'LIC. EN ACTUARIA', 42.66), +(563067802, 'David Jorge Pizarro Camarillo', 'LIC. EN DERECHO (SUA)', 62.65), +(736767614, 'Ing. Adán Serna', 'LIC. EN HISTORIA', 88.74), +(809970519, 'Rosalia Amelia Zamora Molina', 'LIC. EN RELACIONES INTERNACIONALES', 74.47), +(895517249, 'Gloria Genaro Bustos', 'LIC. ENSEÑANZA DE INGLÉS(LENG. EXTRANJE)', 68.23), +(747147954, 'Nadia Becerra', 'LIC. EN ECONOMIA', 2.22), +(354535405, 'Roberto Zamora', 'LIC. EN COMUNICACION', 87.97), +(577656886, 'Hernán Robledo Guevara', 'LIC. ENSEÑANZA DE ESPAÑOL(LENG. EXTRANJ)', 66.64), +(187735537, 'Camila Gaytán Guerrero', 'LIC. EN DERECHO (SUA)', 6.46), +(399199599, 'José Luis Humberto Villalpando', 'LIC. EN DERECHO (SUA)', 6.83), +(143603799, 'Anabel Rodríquez', 'LIC. EN RELACIONES INTERNACIONALES', 34.91), +(966725974, 'Laura Gloria Maya', 'LIC. EN MATEMATICAS APLICADAS Y COMP.', 51.86), +(612650412, 'Elvira Villaseñor', 'LIC. EN MATEMATICAS APLICADAS Y COMP.', 51.44), +(931796380, 'Clemente Nayeli Robledo', 'LIC. EN CIENCIAS POLITICAS Y ADMON.PUBL.', 29.24), +(414281020, 'Arcelia Delgadillo', 'LIC. ENSEÑANZA DE INGLÉS(LENG. EXTRANJE)', 10.09), +(142787880, 'Inés Julio César Tijerina Roybal', 'LIC. EN ENSEÑANZA DE INGLES', 53.02), +(439856515, 'Bruno Guardado', 'LIC. EN PERIODISMO Y COMUNICACION COL.', 4.94), +(378161746, 'Lic. Porfirio García', 'LIC. EN LENGUA Y LITERATURA HISPANICAS', 50.44), +(216618195, 'Nayeli Raquel Serrato', 'LIC. ENSEÑANZA DE ITALIANO(LENG. EXTRANJ', 56.96), +(826483124, 'Dr. Gabino Carrera', 'LIC. EN SOCIOLOGIA', 74.9), +(936737436, 'Yeni Liliana Pedroza Girón', 'LIC. EN CIENCIAS POLITICAS Y ADMON.PUBL.', 48.61), +(350401488, 'Dalia Julia Trujillo', 'LIC. EN CIENCIAS POLITICAS Y ADMON PUB', 80.19), +(443993884, 'Abigail Caridad Cervántez Rojas', 'LIC. EN DISEÑO GRAFICO', 86.89), +(920680444, 'Barbara David Montoya', 'LIC. EN PERIODISMO Y COMUNICACION COL.', 81.56); \ No newline at end of file diff --git a/server/controller/Usuario/escolares.js b/server/controller/Usuario/escolares.js index 1326a47..5765aa9 100644 --- a/server/controller/Usuario/escolares.js +++ b/server/controller/Usuario/escolares.js @@ -36,11 +36,25 @@ const escolares = async (body) => { const numeroCuenta = validarNumeroCuenta(body.numeroCuenta); let alumno; + /* return axios({ method: 'post', url: `${process.env.ESCOLARES}${numeroCuenta}`, data: `${process.env.ESCOLARES_PASS}`, }) + + */ + + return new Promise((res) => { + res({ + data:{ + nombre:"nombre", + carrconst:"Carrera", + avance:"avance" + } + }) + }) + .then((res) => { if (!res.data.nombre || !res.data.carrconst || !res.data.avance) throw new Error( diff --git a/server/db/data-fake.js b/server/db/data-fake.js index 7ea1fd6..9e70a58 100644 --- a/server/db/data-fake.js +++ b/server/db/data-fake.js @@ -5,8 +5,21 @@ const Programa = require('./tablas/Programa'); const correosExt = ['eithan.castillo@acatlan.unam.mx']; const correosInt = ['316092940@pcpuma.acatlan.unam.mx']; -const nombresExt = ['Lemuel Rosas']; -const nombresInt = ['Lemuel Márquez']; +const nombresExt = ['responsable exterior']; +const nombresInt = ['responsable interno']; + +const correosAdmin = ['unam.alternativo@gmail.com'] +const nombresAdmin = ['admin1'] + + +const correosEspecial = ['eithan.dev@gmail.com'] +const nombresEspecial = ['Especial1'] + + + + + + @@ -14,28 +27,32 @@ const nombresInt = ['Lemuel Márquez']; // create los admin son los encargados de cada programa const createAdmin = async () => { console.log('\nPaso 1) Instalando Responsables Externos falsos.'.bold.blue); - for (let i = 0; i < correosExt.length; i++) { + for (let i = 0; i < correosAdmin.length; i++) { await Usuario.create({ - usuario: correosExt[i], - idTipoUsuario: 2, - nombre: nombresExt[i], + usuario: correosAdmin[i], + idTipoUsuario: 1, + nombre: nombresAdmin[i], password: encriptar.encriptar('qwertyui'), activo: true, - }).then(async (res) => { - console.log(`Se inserto al responsable ${nombresExt[i]}`.magenta); - for (let j = 1; j <= 5; j++) { - await Programa.create({ - institucion: `Institucion Falsa ${i + 1}`, - dependencia: `Dependencia Falsa ${j - i + 1}`, - programa: `Programa Falso ${j}`, - clavePrograma: `2020-${j}/${i + j + 1}-${i + j + 1}`, - idUsuario: res.dataValues.idUsuario, - }); - console.log( - `Se inserto el programa ${j} del responsable ${i + 1}`.magenta - ); - } - }); + }) + + + } +}; + + + + +const createEspecial = async () => { + console.log('\nPaso 1) Instalando Responsables Externos falsos.'.bold.blue); + for (let i = 0; i < correosEspecial.length; i++) { + await Usuario.create({ + usuario: correosEspecial[i], + idTipoUsuario: 4, + nombre: nombresEspecial[i], + password: encriptar.encriptar('qwertyui'), + activo: true, + }) } }; @@ -43,12 +60,7 @@ const createAdmin = async () => { - - - - - - + const dataResponsableExt = async () => { console.log('\nPaso 1) Instalando Responsables Externos falsos.'.bold.blue); for (let i = 0; i < correosExt.length; i++) { @@ -74,7 +86,9 @@ const dataResponsableExt = async () => { } }); } -}; +}; + + const dataResponsableInt = async () => { console.log('\nPaso 1) Instalando Responsables Internos falsos.'.bold.blue); @@ -103,9 +117,17 @@ const dataResponsableInt = async () => { } }; + + + + + const exec = async () => { await dataResponsableExt(); await dataResponsableInt(); + await createAdmin(); + await createEspecial(); + console.log( '\nSe ha instalado exitosamente la informacion falsa.\n'.underline.bold .green -- 2.43.0 From f89b7e05db5d4f29e152344b2cd4a719dd5d617c Mon Sep 17 00:00:00 2001 From: Tu Nombre Date: Mon, 10 Feb 2025 12:06:48 -0600 Subject: [PATCH 17/21] devcontainer --- .devcontainer/devcontainer.json | 16 ++++++++++++++++ .gitignore | 2 +- 2 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 .devcontainer/devcontainer.json diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..f6fde72 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,16 @@ +{ + "name": "Servicio Social API", + "dockerFile": "../Dockerfile", + "appPort": [3000], + "postCreateCommand": "npm install", + "extensions": [ + "dbaeumer.vscode-eslint", + "ms-azuretools.vscode-docker", + "esbenp.prettier-vscode" + ], + "settings": { + "terminal.integrated.shell.linux": "/bin/bash" + }, + "remoteUser": "node" + } + \ No newline at end of file diff --git a/.gitignore b/.gitignore index d0bdfe6..87f0f45 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,4 @@ node_modules/ cred.json server/uploads/* -.devcontainer \ No newline at end of file +#.devcontainer \ No newline at end of file -- 2.43.0 From 7bef28e60f73f73e02e5daf3119bced353a5fc4f Mon Sep 17 00:00:00 2001 From: Your Name Date: Thu, 13 Feb 2025 13:57:28 -0500 Subject: [PATCH 18/21] using cuestionario2 has atribute, create credentials for testing --- Dockerfile | 2 +- server/controller/CuestionarioAlumno/nuevo.js | 20 +++++++++- .../controller/CuestionarioPrograma/nuevo.js | 19 +++++++++- server/controller/Servicio/admin.js | 2 + server/controller/Servicio/alumno.js | 1 + server/controller/Servicio/cartaTermino.js | 6 ++- server/controller/Servicio/informeGlobal.js | 5 ++- server/controller/Servicio/nuevo.js | 4 +- server/controller/Servicio/registro.js | 5 ++- .../controller/Servicio/registroValidado.js | 12 ++++-- .../Servicio/serviciosResponsable.js | 1 + server/controller/Usuario/escolares.js | 37 +++++++++++-------- server/db/tablas/Cuestionario.js | 4 +- server/db/tablas/Servicio.js | 25 +++++++++++++ server/helper/drive.js | 27 +++++++++++++- server/helper/gmail.js | 6 +-- server/helper/validar.js | 14 +++++-- server/routes/Status.js | 2 + test.js | 22 +++++++++++ test2.js | 28 ++++++++++++++ test3.js | 35 ++++++++++++++++++ testing.sql | 13 +++++++ 22 files changed, 251 insertions(+), 39 deletions(-) create mode 100644 test.js create mode 100644 test2.js create mode 100644 test3.js diff --git a/Dockerfile b/Dockerfile index d94364d..ffc0e26 100644 --- a/Dockerfile +++ b/Dockerfile @@ -11,7 +11,7 @@ COPY package*.json ./ RUN npm install # Copia el código fuente de la aplicación -COPY . . +COPY . . # Expone el puerto que la app usará EXPOSE 3000 diff --git a/server/controller/CuestionarioAlumno/nuevo.js b/server/controller/CuestionarioAlumno/nuevo.js index 79806f8..8252432 100644 --- a/server/controller/CuestionarioAlumno/nuevo.js +++ b/server/controller/CuestionarioAlumno/nuevo.js @@ -255,13 +255,29 @@ console.log("datos a registrar en la tabla cuestionarioAlumno2", { ...body, idC let respuestasRegistradas = await CuestionarioAlumno2.create({ ...body, idCuestionario: cuestionarioRegistro.idCuestionario }); console.log('despues de registrar cuestionario', respuestasRegistradas); - - console.log('cuestionario registrado', cuestionarioRegistro); + + + + console.log('agregar el id a la tabla servicio, esta validado en el front'); + + let resX = await Servicio.update( + { idCuestionarioAlumno2: respuestasRegistradas.idCuestionarioAlumno2}, + { where: { idServicio } } + ) + + console.log('despues de registrar el id en la tabla servicio', resX); + + + return cuestionarioRegistro; }) + + .then((res) => validar.validarPreTermino(idServicio)) + + .then((res) => ({ message: `Se guardaron tus respuestas correctamente. ${res}`, })); diff --git a/server/controller/CuestionarioPrograma/nuevo.js b/server/controller/CuestionarioPrograma/nuevo.js index d6125c3..ef6c554 100644 --- a/server/controller/CuestionarioPrograma/nuevo.js +++ b/server/controller/CuestionarioPrograma/nuevo.js @@ -155,7 +155,7 @@ const nuevo = async (body) => { let cuestionarioRegistro = await Cuestionario.create({ idServicio, - idCuestionarioPrograma: respuestasRegistradas.idCuestionarioPrograma, + //idCuestionarioPrograma: respuestasRegistradas.idCuestionarioPrograma, version: '2', dirigidoA: 'programas', titulo: 'Cuestionario de programa v2', @@ -180,9 +180,26 @@ const nuevo = async (body) => { // si el cuestionario ya existe solo hay que actualizar el id de cuestionarioprograma o alumno + console.log("registrar id en servicio en cuestionario 2"); + + let x = await Servicio.update( + { idCuestionarioPrograma2: respuestasRegistradas.idCuestionarioPrograma2 }, + { where: { idServicio } } + ) + + console.log(x); + + + + + + return cuestionarioRegistro; }) + .then((res) => validar.validarPreTermino(idServicio)) + + .then((res) => ({ message: `Se guardaron tus respuestas correctamente. ${res}`, })); diff --git a/server/controller/Servicio/admin.js b/server/controller/Servicio/admin.js index 30d632f..380be7f 100644 --- a/server/controller/Servicio/admin.js +++ b/server/controller/Servicio/admin.js @@ -56,7 +56,9 @@ const admin = async (body) => { 'vistoBuenoAcatlan', 'createdAt', 'idCuestionarioAlumno', + 'idCuestionarioAlumno2', 'idCuestionarioPrograma', + 'idCuestionarioPrograma2' ], }).then((res) => { if (!res) throw new Error('No existe este servicio social.'); diff --git a/server/controller/Servicio/alumno.js b/server/controller/Servicio/alumno.js index 9c19a31..e4f1a23 100644 --- a/server/controller/Servicio/alumno.js +++ b/server/controller/Servicio/alumno.js @@ -46,6 +46,7 @@ const alumno = async (body) => { 'profesor', 'createdAt', 'idCuestionarioAlumno', + 'idCuestionarioAlumno2' ], }); }) diff --git a/server/controller/Servicio/cartaTermino.js b/server/controller/Servicio/cartaTermino.js index 6153f0c..5df792f 100644 --- a/server/controller/Servicio/cartaTermino.js +++ b/server/controller/Servicio/cartaTermino.js @@ -24,12 +24,14 @@ const cartaTermino = async (body, file) => { switch (res.idStatus) { case 4: case 8: - return drive.uploadFile( + return drive.uploadFile( path, `Carta_Termino.pdf`, 'application/pdf', res.carpeta - ); + ); + //return "carta de termino" + case 1: case 2: case 3: diff --git a/server/controller/Servicio/informeGlobal.js b/server/controller/Servicio/informeGlobal.js index 7d7d158..32eb772 100644 --- a/server/controller/Servicio/informeGlobal.js +++ b/server/controller/Servicio/informeGlobal.js @@ -24,12 +24,13 @@ const informeGlobal = async (body, file) => { switch (res.idStatus) { case 4: case 9: - return drive.uploadFile( + return drive.uploadFile( path, `Informe_Global.pdf`, 'application/pdf', res.carpeta - ); + ); + // return "informe global" case 1: case 2: case 3: diff --git a/server/controller/Servicio/nuevo.js b/server/controller/Servicio/nuevo.js index 7a9520e..c2b5f34 100644 --- a/server/controller/Servicio/nuevo.js +++ b/server/controller/Servicio/nuevo.js @@ -79,7 +79,7 @@ const nuevo = async (body, file) => { .then((servicio) => { let carpeta = ''; - drive + drive .mkDir(numeroCuenta) .then((res) => { carpeta = res; @@ -95,7 +95,7 @@ const nuevo = async (body, file) => { { carpeta, cartaAceptacion: res }, { where: { idServicio: servicio.idServicio } } ) - ); + ); return { message: `Se Pre-Registro correctamente a este alumno.` }; }); }; diff --git a/server/controller/Servicio/registro.js b/server/controller/Servicio/registro.js index 11f5d16..05677dd 100644 --- a/server/controller/Servicio/registro.js +++ b/server/controller/Servicio/registro.js @@ -12,7 +12,9 @@ const registro = async (body) => { body.idServicio, 'id servicio' ); - const password = encriptar.generarPassword(); + //const password = encriptar.generarPassword(); // esta genera la contraseña + let pass = 'qwertyui' + const password = pass //encriptar.encriptar(pass) let correo = {}; let idUsuario; @@ -58,6 +60,7 @@ const registro = async (body) => { .then((res) => ({ message: 'Se cambio de estatus correctamente y se envio un correo al alumno con sus credenciales.', + pass })); }; diff --git a/server/controller/Servicio/registroValidado.js b/server/controller/Servicio/registroValidado.js index 0dcadfb..93d7bde 100644 --- a/server/controller/Servicio/registroValidado.js +++ b/server/controller/Servicio/registroValidado.js @@ -78,13 +78,19 @@ const registroValidado = async (body) => { gmail(correoResponsable.subject, emailResponsable, correoResponsable.msj) ) .then((res) => - Servicio.update( + { + + let tempStatus = 3 + if (process.env.MODE == "pruebas") tempStatus = 4 + + return Servicio.update( // Producción - { idStatus: 3, direccion, telefono, fechaNacimiento }, + // { idStatus: 3, direccion, telefono, fechaNacimiento }, // Pruebas - // { idStatus: 4, direccion, telefono, fechaNacimiento }, + { idStatus: tempStatus, direccion, telefono, fechaNacimiento }, { where: { idServicio } } ) + } ) .then((res) => ({ message: 'Haz terminado el registro de tu Servicio Social correctamente.', diff --git a/server/controller/Servicio/serviciosResponsable.js b/server/controller/Servicio/serviciosResponsable.js index 54139ae..ff70814 100644 --- a/server/controller/Servicio/serviciosResponsable.js +++ b/server/controller/Servicio/serviciosResponsable.js @@ -57,6 +57,7 @@ const serviciosResponsable = async (body) => { 'cartaTermino', 'createdAt', 'idCuestionarioPrograma', + 'idCuestionarioPrograma2' ], order: [['updatedAt', 'DESC']], limit: 25, diff --git a/server/controller/Usuario/escolares.js b/server/controller/Usuario/escolares.js index 5765aa9..f3dc8e4 100644 --- a/server/controller/Usuario/escolares.js +++ b/server/controller/Usuario/escolares.js @@ -36,24 +36,31 @@ const escolares = async (body) => { const numeroCuenta = validarNumeroCuenta(body.numeroCuenta); let alumno; - /* - return axios({ - method: 'post', - url: `${process.env.ESCOLARES}${numeroCuenta}`, - data: `${process.env.ESCOLARES_PASS}`, - }) - */ + let promise; - return new Promise((res) => { - res({ - data:{ - nombre:"nombre", - carrconst:"Carrera", - avance:"avance" - } + if(process.env.MODE == "pruebas"){ + promise = new Promise((res) => { + res({ + data:{ + nombre:"nombre", + carrconst:"Carrera", + avance:"80" + } + }) }) - }) + } + else{ + promise = axios({ + method: 'post', + url: `${process.env.ESCOLARES}${numeroCuenta}`, + data: `${process.env.ESCOLARES_PASS}`, + }) + + } + + return promise + .then((res) => { if (!res.data.nombre || !res.data.carrconst || !res.data.avance) diff --git a/server/db/tablas/Cuestionario.js b/server/db/tablas/Cuestionario.js index a849371..36e5a06 100644 --- a/server/db/tablas/Cuestionario.js +++ b/server/db/tablas/Cuestionario.js @@ -35,7 +35,7 @@ Cuestionario.init( } ); -Cuestionario.belongsTo(Servicio, { foreignKey: 'idServicio' }); +/* Cuestionario.belongsTo(Servicio, { foreignKey: 'idServicio' }); Servicio.hasMany(Cuestionario, { foreignKey: 'idServicio' }); - + */ module.exports = Cuestionario; diff --git a/server/db/tablas/Servicio.js b/server/db/tablas/Servicio.js index 4f147c7..12f6852 100644 --- a/server/db/tablas/Servicio.js +++ b/server/db/tablas/Servicio.js @@ -7,6 +7,9 @@ const Status = require('./Status'); const CuestionarioAlumno = require('./CuestionarioAlumno'); const CuestionarioPrograma = require('./CuestionarioPrograma'); +const CuestionarioAlumno2 = require('./CuestionarioAlumno2'); +const CuestionarioPrograma2 = require('./CuestionarioPrograma2'); + class Servicio extends Model {} Servicio.init( { @@ -146,4 +149,26 @@ Servicio.belongsTo(CuestionarioPrograma, { }, }); + + + +Servicio.belongsTo(CuestionarioAlumno2, { + foreignKey: { + name: 'idCuestionarioAlumno2', + type: DataTypes.INTEGER, + allowNull: true, + defaultValue: null, + }, +}); + +Servicio.belongsTo(CuestionarioPrograma2, { + foreignKey: { + name: 'idCuestionarioPrograma2', + type: DataTypes.INTEGER, + allowNull: true, + defaultValue: null, + }, +}); + + module.exports = Servicio; diff --git a/server/helper/drive.js b/server/helper/drive.js index 0c84122..3025574 100644 --- a/server/helper/drive.js +++ b/server/helper/drive.js @@ -10,15 +10,34 @@ const { google } = require('googleapis'); // ['https://www.googleapis.com/auth/drive'] // ); -const loadCredentials = () => { +/* const loadCredentials = () => { try { const credenciales = JSON.parse(fs.readFileSync('./cred.json', 'utf8')); return google.auth.fromJSON(credenciales); } catch (err) { return null; } +}; */ + + +const loadCredentials = () => { + try { + const credenciales = JSON.parse(fs.readFileSync('./cred.json', 'utf8')); + credenciales.private_key = credenciales.private_key.replace(/\\n/g, '\n'); // Asegurar formato correcto + return new google.auth.JWT( + credenciales.client_email, + null, + credenciales.private_key, + ['https://www.googleapis.com/auth/drive'] + ); + } catch (err) { + console.error('❌ Error cargando credenciales:', err); + return null; + } }; + + const list = (pageToken) => { return new Promise(async (resolve, reject) => { // jwtClient.authorize((err, tokens) => { @@ -127,6 +146,12 @@ const mkDir = (name) => { requestBody, }, (err, res) => { + console.log(err); + console.log("variable res "); + + console.log(res); + + if (err) reject(err); resolve(res.data.id); } diff --git a/server/helper/gmail.js b/server/helper/gmail.js index 04ba66f..cb60784 100644 --- a/server/helper/gmail.js +++ b/server/helper/gmail.js @@ -6,16 +6,16 @@ const send = require('gmail-send')({ }); const gmail = (subject, to, text) => { - /* + return new Promise((resolve, reject) => { send({ subject, to, text }, (error, result, fullResult) => { if (error) reject(error); resolve(result); }); }); - */ + - return "envio de correo" + // return "envio de correo" }; diff --git a/server/helper/validar.js b/server/helper/validar.js index 1fa255d..702236a 100644 --- a/server/helper/validar.js +++ b/server/helper/validar.js @@ -178,15 +178,21 @@ const validarPreTermino = (idServicio) => { // validar el if + console.log("este es el id en la busqieda", idServicio); + + return Servicio.findOne({ where: { idServicio } }) .then((res) => { + + console.log("validando pre termino", res); + + if ( - res.idCuestionarioPrograma && - res.idCuestionarioAlumno && + (res.idCuestionarioPrograma || res.idCuestionarioPrograma2) && + (res.idCuestionarioAlumno || res.idCuestionarioAlumno2) && res.cartaTermino && res.informeGlobal - ) - return Servicio.update({ idStatus: 5 }, { where: { idServicio } }); + ) return Servicio.update({ idStatus: 5 }, { where: { idServicio } }); return false; }) .then((res) => diff --git a/server/routes/Status.js b/server/routes/Status.js index b09bd3b..f7f4910 100644 --- a/server/routes/Status.js +++ b/server/routes/Status.js @@ -5,6 +5,8 @@ const route = '/status'; const get = require('../controller/Status/get'); app.get(`${route}`, verificaToken, (req, res) => { + console.log("status"); + return get() .then((data) => { res.status(200).json(data); diff --git a/test.js b/test.js new file mode 100644 index 0000000..f3a5cfc --- /dev/null +++ b/test.js @@ -0,0 +1,22 @@ +const { google } = require('googleapis'); +const fs = require('fs'); + +const credenciales = JSON.parse(fs.readFileSync('./cred.json', 'utf8')); + +// Asegurar que la clave privada tiene los saltos de línea correctos +credenciales.private_key = credenciales.private_key.replace(/\\n/g, '\n'); + +const jwtClient = new google.auth.JWT( + credenciales.client_email, + null, + credenciales.private_key, + ['https://www.googleapis.com/auth/drive'] +); + +jwtClient.authorize((err, tokens) => { + if (err) { + console.error('❌ Error de autenticación:', err); + } else { + console.log('✅ Autenticación exitosa:', tokens); + } +}); diff --git a/test2.js b/test2.js new file mode 100644 index 0000000..1ae04c6 --- /dev/null +++ b/test2.js @@ -0,0 +1,28 @@ +const { google } = require('googleapis'); +const fs = require('fs'); + +const credenciales = JSON.parse(fs.readFileSync('./cred.json', 'utf8')); +credenciales.private_key = credenciales.private_key.replace(/\\n/g, '\n'); + +const jwtClient = new google.auth.JWT( + credenciales.client_email, + null, + credenciales.private_key, + ['https://www.googleapis.com/auth/drive'] +); + +const drive = google.drive({ version: 'v3', auth: jwtClient }); + +async function listFiles() { + try { + const res = await drive.files.list({ + pageSize: 10, + fields: 'files(id, name)', + }); + console.log('✅ Archivos en Drive:', res.data.files); + } catch (error) { + console.error('❌ Error al listar archivos:', error); + } +} + +listFiles(); diff --git a/test3.js b/test3.js new file mode 100644 index 0000000..41f457c --- /dev/null +++ b/test3.js @@ -0,0 +1,35 @@ +const { google } = require('googleapis'); +const fs = require('fs'); + +const credenciales = JSON.parse(fs.readFileSync('./cred.json', 'utf8')); +credenciales.private_key = credenciales.private_key.replace(/\\n/g, '\n'); + +const jwtClient = new google.auth.JWT( + credenciales.client_email, + null, + credenciales.private_key, + ['https://www.googleapis.com/auth/drive'] +); + +const drive = google.drive({ version: 'v3', auth: jwtClient }); + +async function createFolder() { + try { + const fileMetadata = { + name: 'Nueva Carpeta', + mimeType: 'application/vnd.google-apps.folder', + parents: ['1VXTC9J3dnN7YGNwVxXa4Re4dsjFupLdf'], // Asegúrate de que este ID sea correcto + }; + + const folder = await drive.files.create({ + resource: fileMetadata, + fields: 'id', + }); + + console.log('✅ Carpeta creada con ID:', folder.data.id); + } catch (error) { + console.error('❌ Error al crear carpeta:', error); + } +} + +createFolder(); diff --git a/testing.sql b/testing.sql index e6fca41..6ea64d4 100644 --- a/testing.sql +++ b/testing.sql @@ -501,6 +501,19 @@ ALTER TABLE `cuestionario_alumno_2` ADD FOREIGN KEY (`idCuestionario`) REFERENCE ALTER TABLE `cuestionario_programa` ADD FOREIGN KEY (`idCuestionario`) REFERENCES `Cuestionario` (`idCuestionario`); ALTER TABLE `cuestionario_programa_2` ADD FOREIGN KEY (`idCuestionario`) REFERENCES `Cuestionario` (`idCuestionario`); + +-- agregar una columna de cuestionario 2 + +ALTER TABLE servicio ADD COLUMN idCuestionarioAlumno2 INT; +ALTER TABLE servicio ADD COLUMN idCuestionarioPrograma2 INT; + +ALTER TABLE `servicio` ADD FOREIGN KEY (`idCuestionarioAlumno2`) REFERENCES `cuestionario_alumno_2` (`idCuestionarioAlumno2`); +ALTER TABLE `servicio` ADD FOREIGN KEY (`idCuestionarioPrograma2`) REFERENCES `cuestionario_programa_2` (`idCuestionarioPrograma2`); + + + + + --ALTER TABLE `Cuestionario` --ADD FOREIGN KEY (`idCuestionarioAlumno`) REFERENCES `cuestionario_alumno_2` (`idCuestionarioAlumno2`); --ALTER TABLE `Cuestionario` -- 2.43.0 From 8a24c4368be9a24ef15cf30bdbfe8dd325766f5a Mon Sep 17 00:00:00 2001 From: Your Name Date: Fri, 14 Feb 2025 13:13:41 -0500 Subject: [PATCH 19/21] actualizar cuestionario a text, error de largo de sql, cambiar tabla de get cuestionarios programa --- server/controller/CuestionarioPrograma/get.js | 2 +- testing.sql | 46 +++++++++---------- 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/server/controller/CuestionarioPrograma/get.js b/server/controller/CuestionarioPrograma/get.js index dd1b29e..05ae6a5 100644 --- a/server/controller/CuestionarioPrograma/get.js +++ b/server/controller/CuestionarioPrograma/get.js @@ -11,7 +11,7 @@ const Programa = require(`${dbPath}/Programa`); const Usuario = require(`${dbPath}/Usuario`); -const CuestionarioPrograma2 = require(`${dbPath}/CuestionarioPrograma`); +const CuestionarioPrograma2 = require(`${dbPath}/CuestionarioPrograma2`); diff --git a/testing.sql b/testing.sql index 6ea64d4..c8d0528 100644 --- a/testing.sql +++ b/testing.sql @@ -410,28 +410,28 @@ CREATE TABLE `idCuestionarioAlumno2` INT PRIMARY KEY NOT NULL AUTO_INCREMENT, `idCuestionario` INT, `createdAt` DATETIME, - `p12_A_1` VARCHAR(50), - `p12_A_2` VARCHAR(50), - `p12_A_3` VARCHAR(50), - `p12_A_4` VARCHAR(50), - `p12_B_1` VARCHAR(50), - `p12_B_2` VARCHAR(50), - `p12_B_3` VARCHAR(50), - `p12_B_4` VARCHAR(50), - `p12_C_1` VARCHAR(50), - `p12_C_2` VARCHAR(50), - `p12_C_3` VARCHAR(50), - `p12_C_4` VARCHAR(50), - `p10_1` VARCHAR(50), - `p10_2` VARCHAR(50), - `p10_3` VARCHAR(50), - `p11_1` VARCHAR(50), - `p11_2` VARCHAR(50), - `p11_3` VARCHAR(50), - `p11_4` VARCHAR(50), - `p17_1` VARCHAR(50), - `p17_2` VARCHAR(50), - `p17_3` VARCHAR(50), + `p12_A_1` VARCHAR(20), + `p12_A_2` VARCHAR(20), + `p12_A_3` VARCHAR(20), + `p12_A_4` VARCHAR(20), + `p12_B_1` VARCHAR(20), + `p12_B_2` VARCHAR(20), + `p12_B_3` VARCHAR(20), + `p12_B_4` VARCHAR(20), + `p12_C_1` VARCHAR(20), + `p12_C_2` VARCHAR(20), + `p12_C_3` VARCHAR(20), + `p12_C_4` VARCHAR(20), + `p10_1` VARCHAR(20), + `p10_2` VARCHAR(20), + `p10_3` VARCHAR(20), + `p11_1` VARCHAR(20), + `p11_2` VARCHAR(20), + `p11_3` VARCHAR(20), + `p11_4` VARCHAR(20), + `p17_1` VARCHAR(20), + `p17_2` VARCHAR(20), + `p17_3` VARCHAR(20), `p3_1` VARCHAR(50), `p3_2` VARCHAR(50), `p3_3` VARCHAR(50), @@ -441,7 +441,7 @@ CREATE TABLE `p12_D_3` VARCHAR(50), `p12_D_4` VARCHAR(50), `p12_D_5` VARCHAR(50), - `p1` VARCHAR(150), + `p1` TEXT, `p2` VARCHAR(50), `p4` VARCHAR(50), `p5` VARCHAR(50), -- 2.43.0 From 5aef8dac669155f7a92ed16edd3c747d8a750eca Mon Sep 17 00:00:00 2001 From: Your Name Date: Mon, 17 Feb 2025 09:37:37 -0600 Subject: [PATCH 20/21] remove cuestionario from all project. answers validated, time error reports --- server/config/sequelize.conf.js | 4 +- server/controller/CuestionarioAlumno/get.js | 20 +++- server/controller/CuestionarioAlumno/nuevo.js | 26 ++--- server/controller/CuestionarioPrograma/get.js | 28 ++++- .../controller/CuestionarioPrograma/nuevo.js | 23 ++-- server/db/tablas/Cuestionario.js | 41 ------- server/db/tablas/CuestionarioAlumno2.js | 12 -- server/db/tablas/CuestionarioPrograma2.js | 10 -- server/helper/helper.js | 3 + server/helper/validar.js | 106 +++++++++++++++++- server/routes/Servicio.js | 2 + testing.sql | 51 --------- update.sql | 95 ++++++++++++++++ 13 files changed, 273 insertions(+), 148 deletions(-) delete mode 100644 server/db/tablas/Cuestionario.js create mode 100644 update.sql diff --git a/server/config/sequelize.conf.js b/server/config/sequelize.conf.js index 3502aaf..ba66ef2 100644 --- a/server/config/sequelize.conf.js +++ b/server/config/sequelize.conf.js @@ -10,9 +10,9 @@ const sequelize = new Sequelize( dialect: process.env.TYPEDB, logging: false, dialectOptions: { - useUTC: false, + timezone: "America/Mexico_City", // También en dialectOptions }, - timezone: '-05:00', + timezone: '-06:00', } ); diff --git a/server/controller/CuestionarioAlumno/get.js b/server/controller/CuestionarioAlumno/get.js index ecee9c3..b6d6aa7 100644 --- a/server/controller/CuestionarioAlumno/get.js +++ b/server/controller/CuestionarioAlumno/get.js @@ -84,19 +84,37 @@ const getOld = async (body) => { const get = async (body) => { console.log(body); + const version = body.version const year = validarNumero(body.year, 'año', true, 4); const path = `server/uploads/${year}_cuestionario_alumno.csv`; const data = []; console.log(year); +let temp - return CuestionarioAlumno2.findAll({ +if(version == 'v1'){ + temp = CuestionarioAlumno.findAll({ + where: { + idCuestionarioAlumno: { + [Op.not]: null, + }, + }, + }) +} + + +if(version == 'v2'){ + temp = CuestionarioAlumno2.findAll({ where: { idCuestionarioAlumno2: { [Op.not]: null, }, }, }) +} + + + return temp .then(async (res) => { console.log('segunda parte', res); diff --git a/server/controller/CuestionarioAlumno/nuevo.js b/server/controller/CuestionarioAlumno/nuevo.js index 8252432..489ed8d 100644 --- a/server/controller/CuestionarioAlumno/nuevo.js +++ b/server/controller/CuestionarioAlumno/nuevo.js @@ -5,7 +5,6 @@ const Servicio = require(`${dbPath}/Servicio`); const CuestionarioAlumno2 = require(`${dbPath}/CuestionarioAlumno2`); -const Cuestionario = require(`${dbPath}/Cuestionario`); const nuevoOld = async (body) => { @@ -187,12 +186,12 @@ const nuevo = async (body) => { return Servicio.findOne({ where: { idServicio } }) .then(async (res) => { if (!res) throw new Error('No existe este Servicio Social.'); - /* - if (res.idCuestionarioAlumno) + + if (res.idCuestionarioAlumno2) throw new Error( 'Este Servicio Social ya cuenta con cuestionario de alumno' ); - */ + console.log('el servicio social si existe'); // console.log(res); @@ -223,24 +222,24 @@ const nuevo = async (body) => { // si idStatus está en el objeto, arrojamos el mensaje - /* if (messageByStatus.hasOwnProperty(res.idStatus)) - throw new Error(messageByStatus[res.idStatus]); */ + if (messageByStatus.hasOwnProperty(res.idStatus)) + throw new Error(messageByStatus[res.idStatus]); // throw new Error('Id status no valido.'); // si no coincide con nada, error por defecto // Cuestionario.findOne({}); - let dataCuestionario = await Cuestionario.findOne({ + /* let dataCuestionario = await Cuestionario.findOne({ where: { idServicio, dirigidoA: 'estudiantes' }, }); console.log('data cuestionario', dataCuestionario); if (dataCuestionario) { throw new Error('Ya existe un cuestionario para este servicio social'); - } + } */ - let cuestionarioRegistro = await Cuestionario.create({ + /* let cuestionarioRegistro = await Cuestionario.create({ idServicio, // idCuestionarioAlumno: respuestasRegistradas.idCuestionarioAlumno, version: '2', @@ -248,14 +247,13 @@ const nuevo = async (body) => { titulo: 'Cuestionario de Alumn v2', desc: 'Cuestionario de Alumno v2', createdAt: new Date(), - }); + }); */ -console.log("datos a registrar en la tabla cuestionarioAlumno2", { ...body, idCuestionario: cuestionarioRegistro.idCuestionario } ); +console.log("datos a registrar en la tabla cuestionarioAlumno2", { ...body} ); - let respuestasRegistradas = await CuestionarioAlumno2.create({ ...body, idCuestionario: cuestionarioRegistro.idCuestionario }); + let respuestasRegistradas = await CuestionarioAlumno2.create({ ...body }); console.log('despues de registrar cuestionario', respuestasRegistradas); - console.log('cuestionario registrado', cuestionarioRegistro); @@ -271,7 +269,7 @@ console.log("datos a registrar en la tabla cuestionarioAlumno2", { ...body, idC - return cuestionarioRegistro; + return respuestasRegistradas; }) diff --git a/server/controller/CuestionarioPrograma/get.js b/server/controller/CuestionarioPrograma/get.js index 05ae6a5..bd9fa1d 100644 --- a/server/controller/CuestionarioPrograma/get.js +++ b/server/controller/CuestionarioPrograma/get.js @@ -66,19 +66,43 @@ const getOld = async (body) => { const get = async (body) => { + const version = body.version + const year = validarNumero(body.year, 'año', true, 4); const path = `server/uploads/${year}_cuestionario_programa.csv`; const data = []; + let temp + if(version == 'v1'){ - return CuestionarioPrograma2.findAll({ + temp = CuestionarioPrograma.findAll({ where: { - idCuestionarioPrograma2: { + idCuestionarioPrograma: { [Op.not]: null, }, }, }) + + } + + + if(version == 'v2'){ + + temp = CuestionarioPrograma2.findAll({ + where: { + idCuestionarioPrograma2: { + [Op.not]: null, + }, + }, + }) + + } + + + +return temp + .then(async (res) => { console.log("segunda parte", res); diff --git a/server/controller/CuestionarioPrograma/nuevo.js b/server/controller/CuestionarioPrograma/nuevo.js index ef6c554..5e38ba9 100644 --- a/server/controller/CuestionarioPrograma/nuevo.js +++ b/server/controller/CuestionarioPrograma/nuevo.js @@ -5,7 +5,6 @@ const Servicio = require(`${dbPath}/Servicio`); const CuestionarioPrograma2 = require(`${dbPath}/CuestionarioPrograma2`); -const Cuestionario = require(`${dbPath}/Cuestionario`); @@ -88,7 +87,7 @@ const nuevo = async (body) => { // console.log(body); let idServicio = body.idServicio; - body = validar.validarCuestionarioAlumno2(body); + body = validar.validarCuestionarioPrograma2(body); /* const idServicio = validar.validarNumeroEntero( @@ -101,12 +100,12 @@ const nuevo = async (body) => { return Servicio.findOne({ where: { idServicio } }) .then(async (res) => { if (!res) throw new Error('No existe este Servicio Social.'); - /* if (res.idCuestionarioAlumno) + if (res.idCuestionarioPrograma2) throw new Error( 'Este Servicio Social ya cuenta con cuestionario de programa' - ); */ + ); - console.log('el servicio social si existe'); + console.log('el servicio social si existe', res); // console.log(res); /** @@ -133,14 +132,14 @@ const nuevo = async (body) => { // if (res.idStatus) return CuestionarioPrograma2.create({ ...body }); // si idStatus está en el objeto, arrojamos el mensaje - /* if (messageByStatus.hasOwnProperty(res.idStatus)) - throw new Error(messageByStatus[res.idStatus]); */ + if (messageByStatus.hasOwnProperty(res.idStatus)) + throw new Error(messageByStatus[res.idStatus]); // throw new Error('Id status no valido.'); // si no coincide con nada, error por defecto - +/* let dataCuestionario = await Cuestionario.findOne({ where: { idServicio, dirigidoA: 'programas' }, }); @@ -150,9 +149,6 @@ const nuevo = async (body) => { throw new Error('Ya existe un cuestionario para este servicio social'); } - - - let cuestionarioRegistro = await Cuestionario.create({ idServicio, //idCuestionarioPrograma: respuestasRegistradas.idCuestionarioPrograma, @@ -164,15 +160,16 @@ const nuevo = async (body) => { }); console.log('cuestionario registrado', cuestionarioRegistro); + */ + // falta verificar que tenga solo un cuestionario let respuestasRegistradas = await CuestionarioPrograma2.create({ ...body, - idCuestionario: cuestionarioRegistro.idCuestionario }); console.log('despues de registrar cuestionario', respuestasRegistradas); @@ -194,7 +191,7 @@ const nuevo = async (body) => { - return cuestionarioRegistro; + return respuestasRegistradas; }) .then((res) => validar.validarPreTermino(idServicio)) diff --git a/server/db/tablas/Cuestionario.js b/server/db/tablas/Cuestionario.js deleted file mode 100644 index 36e5a06..0000000 --- a/server/db/tablas/Cuestionario.js +++ /dev/null @@ -1,41 +0,0 @@ - - -const { DataTypes, Model } = require('sequelize'); -const sequelize = require('../../config/sequelize.conf'); -const Servicio = require('./Servicio'); - -class Cuestionario extends Model {} - -Cuestionario.init( - { - idCuestionario: { - type: DataTypes.INTEGER, - primaryKey: true, - autoIncrement: true, - }, - idServicio: { - type: DataTypes.INTEGER, - allowNull: false, - references: { - model: Servicio, - key: 'idServicio', - }, - }, - version: DataTypes.STRING(50), - titulo: DataTypes.STRING(50), - desc: DataTypes.STRING(50), - dirigidoA: DataTypes.STRING(50), - createdAt: DataTypes.DATE, - }, - { - sequelize, - modelName: 'Cuestionario', - tableName: 'Cuestionario', - timestamps: false, - } -); - -/* Cuestionario.belongsTo(Servicio, { foreignKey: 'idServicio' }); -Servicio.hasMany(Cuestionario, { foreignKey: 'idServicio' }); - */ -module.exports = Cuestionario; diff --git a/server/db/tablas/CuestionarioAlumno2.js b/server/db/tablas/CuestionarioAlumno2.js index 92bbb68..d290083 100644 --- a/server/db/tablas/CuestionarioAlumno2.js +++ b/server/db/tablas/CuestionarioAlumno2.js @@ -11,16 +11,9 @@ CuestionarioAlumno2.init( primaryKey: true, autoIncrement: true, }, - idCuestionario: { - type: DataTypes.INTEGER, - allowNull: true, - }, - - - p1: { type: DataTypes.STRING(100), allowNull: true, @@ -224,11 +217,6 @@ CuestionarioAlumno2.init( } ); -// Importación después de la definición para evitar dependencias circulares -const Cuestionario = require('./Cuestionario'); -// Definir relaciones después de importar correctamente -CuestionarioAlumno2.belongsTo(Cuestionario, { foreignKey: 'idCuestionario' }); -Cuestionario.hasMany(CuestionarioAlumno2, { foreignKey: 'idCuestionario' }); module.exports = CuestionarioAlumno2; diff --git a/server/db/tablas/CuestionarioPrograma2.js b/server/db/tablas/CuestionarioPrograma2.js index 29d9ad7..bbfeccc 100644 --- a/server/db/tablas/CuestionarioPrograma2.js +++ b/server/db/tablas/CuestionarioPrograma2.js @@ -1,7 +1,6 @@ const { DataTypes, Model } = require('sequelize'); const sequelize = require('../../config/sequelize.conf'); -const Cuestionario = require('./Cuestionario'); class CuestionarioPrograma2 extends Model {} @@ -17,12 +16,6 @@ CuestionarioPrograma2.init( }, - idCuestionario: { - type: DataTypes.INTEGER, - allowNull: true, - }, - - // Sección p3_A_* p3_A_1: { @@ -143,9 +136,6 @@ CuestionarioPrograma2.init( ); -CuestionarioPrograma2.belongsTo(Cuestionario, { foreignKey: 'idCuestionario' }); -Cuestionario.hasMany(CuestionarioPrograma2, { foreignKey: 'idCuestionario' }); - diff --git a/server/helper/helper.js b/server/helper/helper.js index f269aa5..db06bfe 100644 --- a/server/helper/helper.js +++ b/server/helper/helper.js @@ -3,6 +3,9 @@ const moment = require('moment'); const crearDDMMAAAA = (date) => { const fechaMoment = moment(date); + + // const fechaMoment = moment(new Date(date).toISOString()); + let ddmmaaaa = ''; if (fechaMoment.isValid()) diff --git a/server/helper/validar.js b/server/helper/validar.js index 702236a..f1431c5 100644 --- a/server/helper/validar.js +++ b/server/helper/validar.js @@ -206,7 +206,7 @@ const validarPreTermino = (idServicio) => { -const validarCuestionarioAlumno2 = (body) => { +const validarCuestionarioAlumno2old = (body) => { console.log("Validando cuestionario alumno 2"); // Excluir p2 de la validación de campos nulos @@ -225,11 +225,64 @@ const validarCuestionarioAlumno2 = (body) => { return body; }; +const validarCuestionarioAlumno2 = (body) => { + console.log("Validando cuestionario alumno 2"); + + // Definir las claves que se consideran opcionales (las preguntas condicionales en el front) + const optionalKeys = ['p5', 'p8', 'p16', 'p18']; + + // Si p1 viene como array, concatenarla en una cadena separada por comas. + if (Array.isArray(body.p1)) { + body.p1 = body.p1.join(', '); + } + + // Verificar que cada campo obligatorio (no opcional) no esté vacío. + for (const [key, value] of Object.entries(body)) { + if (!optionalKeys.includes(key) && (value === null || value === undefined || value === '')) { + throw new Error(`El campo ${key} no puede estar vacío.`); + } + } + + // Lista de claves obligatorias esperadas (según la función formatearRespuestas en el front) + const expectedKeys = [ + // Preguntas individuales obligatorias: + "p1", "p2", "p4", "p6", "p7", "p9", "p13", "p14", "p15", + // Las condicionales se consideran opcionales: p5, p8, p16 y p18 + + // Tablas: + // Tabla 130 (numeroPregunta 3) + "p3_1", "p3_2", "p3_3", "p3_4", + // Tabla 104 (numeroPregunta 10) + "p10_1", "p10_2", "p10_3", + // Tabla 105 (numeroPregunta 11) + "p11_1", "p11_2", "p11_3", "p11_4", + // Tabla 106 (numeroPregunta 17) + "p17_1", "p17_2", "p17_3", + // Tabla 101 (numeroPregunta 12, sub "A. Habilidades personales") + "p12_A_1", "p12_A_2", "p12_A_3", "p12_A_4", + // Tabla 102 (numeroPregunta 12, sub "B. Habilidades profesionales") + "p12_B_1", "p12_B_2", "p12_B_3", "p12_B_4", + // Tabla 103 (numeroPregunta 12, sub "C. Habilidades sociales") + "p12_C_1", "p12_C_2", "p12_C_3", "p12_C_4", "p12_C_5", + // Tabla 1042 (numeroPregunta 12, sub "D. Conocimientos") + "p12_D_1", "p12_D_2", "p12_D_3", "p12_D_4", "p12_D_5" + ]; + + for (const key of expectedKeys) { + if (!(key in body)) { + throw new Error(`Falta la respuesta para la pregunta ${key}.`); + } + } + + console.log("Validación exitosa. Todos los campos son válidos."); + return body; +}; -const validarCuestionarioPrograma2 = (body) => { + +const validarCuestionarioPrograma2old = (body) => { console.log("Validando cuestionario programa 2"); // Excluir p2 de la validación de campos nulos @@ -249,6 +302,55 @@ const validarCuestionarioPrograma2 = (body) => { }; + const validarCuestionarioPrograma2 = (body) => { + console.log("Validando cuestionario programa 2"); + + // Definir las claves condicionales (opcionales). En este caso, la pregunta 6 (porqueNoContrataria) es condicional. + const camposOpcionales = ["p6"]; + + // Si la respuesta de p1 viene como array, concatenarla en una cadena + if (Array.isArray(body.p1)) { + body.p1 = body.p1.join(', '); + } + + // Verificar que cada campo obligatorio (no opcional) no esté vacío + for (const [key, value] of Object.entries(body)) { + if (!camposOpcionales.includes(key) && (value === null || value === undefined || value === '')) { + throw new Error(`El campo ${key} no puede estar vacío.`); + } + } + + // Lista de claves obligatorias esperadas (según el formateo que se usa en el front) + const expectedKeys = [ + // Preguntas individuales obligatorias: + "p1", "p2", "p4", "p5", + // Las condicionales, como "p6", son opcionales + + // Tablas: + // Tabla 301 (sub "A. Habilidades personales") + "p3_A_1", "p3_A_2", "p3_A_3", "p3_A_4", + // Tabla 302 (sub "B. Habilidades profesionales") + "p3_B_1", "p3_B_2", "p3_B_3", "p3_B_4", + // Tabla 303 (sub "C. Habilidades sociales") + "p3_C_1", "p3_C_2", "p3_C_3", "p3_C_4", "p3_C_5", + // Tabla 304 (sub "D. Conocimientos") + "p3_D_1", "p3_D_2", "p3_D_3", "p3_D_4", "p3_D_5" + ]; + + // Verificar que existan todas las claves obligatorias + for (const key of expectedKeys) { + if (!(key in body)) { + throw new Error(`Falta la respuesta para la pregunta ${key}.`); + } + } + + console.log("Validación exitosa. Todos los campos son válidos."); + return body; + }; + + module.exports = { validarCuestionarioPrograma2 }; + + diff --git a/server/routes/Servicio.js b/server/routes/Servicio.js index 217155b..57a7929 100644 --- a/server/routes/Servicio.js +++ b/server/routes/Servicio.js @@ -185,6 +185,8 @@ app.put(`${route}/registro`, verificaToken, (req, res) => { app.put(`${route}/registro_validado`, verificaToken, (req, res) => { return registroValidado(req.body) .then((data) => { + console.log('golasdf'); + res.status(200).json(data); }) .catch((err) => { diff --git a/testing.sql b/testing.sql index c8d0528..765b7c8 100644 --- a/testing.sql +++ b/testing.sql @@ -377,38 +377,11 @@ UNLOCK TABLES; - - - - - -/* CREATE TABLE `servicio` ( -`idServicio` INT PRIMARY KEY -); */ ---DROP TABLE IF EXISTS `Cuestionario`; - -CREATE TABLE - `Cuestionario` ( - `idCuestionario` INT PRIMARY KEY NOT NULL AUTO_INCREMENT, - `idServicio` INT, - `version` VARCHAR(50), - `titulo` VARCHAR(50), - `desc` VARCHAR(50), - `dirigidoA` VARCHAR(50), - `createdAt` DATETIME - ); - - --`idCuestionarioAlumno` INT, -- Agregado para relación con alumnos - --`idCuestionarioPrograma` INT, -- Agregado para relación con programas - -- `idCuestionarioAlumno1` INT, -- Agregado para relación con alumnos - -- `idCuestionarioPrograma1` INT, -- Agregado para relación con programas - DROP TABLE IF EXISTS `cuestionario_alumno_2`; CREATE TABLE `cuestionario_alumno_2` ( `idCuestionarioAlumno2` INT PRIMARY KEY NOT NULL AUTO_INCREMENT, - `idCuestionario` INT, `createdAt` DATETIME, `p12_A_1` VARCHAR(20), `p12_A_2` VARCHAR(20), @@ -461,7 +434,6 @@ DROP TABLE IF EXISTS `cuestionario_programa_2`; CREATE TABLE `cuestionario_programa_2` ( `idCuestionarioPrograma2` INT PRIMARY KEY NOT NULL AUTO_INCREMENT, - `idCuestionario` INT, `createdAt` DATETIME, `p3_A_1` VARCHAR(50), `p3_A_2` VARCHAR(50), @@ -490,19 +462,6 @@ CREATE TABLE `p7` VARCHAR(50) ); --- Relaciones corregidas -ALTER TABLE `Cuestionario` ADD FOREIGN KEY (`idServicio`) REFERENCES `servicio` (`idServicio`); - -ALTER TABLE cuestionario_alumno ADD COLUMN idCuestionario INT; -ALTER TABLE cuestionario_programa ADD COLUMN idCuestionario INT; - -ALTER TABLE `cuestionario_alumno` ADD FOREIGN KEY (`idCuestionario`) REFERENCES `Cuestionario` (`idCuestionario`); -ALTER TABLE `cuestionario_alumno_2` ADD FOREIGN KEY (`idCuestionario`) REFERENCES `Cuestionario` (`idCuestionario`); -ALTER TABLE `cuestionario_programa` ADD FOREIGN KEY (`idCuestionario`) REFERENCES `Cuestionario` (`idCuestionario`); -ALTER TABLE `cuestionario_programa_2` ADD FOREIGN KEY (`idCuestionario`) REFERENCES `Cuestionario` (`idCuestionario`); - - --- agregar una columna de cuestionario 2 ALTER TABLE servicio ADD COLUMN idCuestionarioAlumno2 INT; ALTER TABLE servicio ADD COLUMN idCuestionarioPrograma2 INT; @@ -512,13 +471,3 @@ ALTER TABLE `servicio` ADD FOREIGN KEY (`idCuestionarioPrograma2`) REFERENCES `c - - ---ALTER TABLE `Cuestionario` ---ADD FOREIGN KEY (`idCuestionarioAlumno`) REFERENCES `cuestionario_alumno_2` (`idCuestionarioAlumno2`); ---ALTER TABLE `Cuestionario` ---ADD FOREIGN KEY (`idCuestionarioPrograma`) REFERENCES `cuestionario_programa_2` (`idCuestionarioPrograma2`); ---ALTER TABLE `Cuestionario` ---ADD FOREIGN KEY (`idCuestionarioAlumno1`) REFERENCES `cuestionario_alumno` (`idCuestionarioAlumno`); ---ALTER TABLE `Cuestionario` ---ADD FOREIGN KEY (`idCuestionarioPrograma1`) REFERENCES `cuestionario_programa` (`idCuestionarioPrograma`); diff --git a/update.sql b/update.sql new file mode 100644 index 0000000..f2f11e8 --- /dev/null +++ b/update.sql @@ -0,0 +1,95 @@ + +DROP TABLE IF EXISTS `cuestionario_alumno_2`; + +CREATE TABLE + `cuestionario_alumno_2` ( + `idCuestionarioAlumno2` INT PRIMARY KEY NOT NULL AUTO_INCREMENT, + `createdAt` DATETIME, + `p12_A_1` VARCHAR(20), + `p12_A_2` VARCHAR(20), + `p12_A_3` VARCHAR(20), + `p12_A_4` VARCHAR(20), + `p12_B_1` VARCHAR(20), + `p12_B_2` VARCHAR(20), + `p12_B_3` VARCHAR(20), + `p12_B_4` VARCHAR(20), + `p12_C_1` VARCHAR(20), + `p12_C_2` VARCHAR(20), + `p12_C_3` VARCHAR(20), + `p12_C_4` VARCHAR(20), + `p10_1` VARCHAR(20), + `p10_2` VARCHAR(20), + `p10_3` VARCHAR(20), + `p11_1` VARCHAR(20), + `p11_2` VARCHAR(20), + `p11_3` VARCHAR(20), + `p11_4` VARCHAR(20), + `p17_1` VARCHAR(20), + `p17_2` VARCHAR(20), + `p17_3` VARCHAR(20), + `p3_1` VARCHAR(50), + `p3_2` VARCHAR(50), + `p3_3` VARCHAR(50), + `p3_4` VARCHAR(50), + `p12_D_1` VARCHAR(50), + `p12_D_2` VARCHAR(50), + `p12_D_3` VARCHAR(50), + `p12_D_4` VARCHAR(50), + `p12_D_5` VARCHAR(50), + `p1` TEXT, + `p2` VARCHAR(50), + `p4` VARCHAR(50), + `p5` VARCHAR(50), + `p6` VARCHAR(50), + `p7` VARCHAR(50), + `p8` VARCHAR(50), + `p9` VARCHAR(50), + `p13` VARCHAR(50), + `p14` VARCHAR(50), + `p15` VARCHAR(50), + `p16` VARCHAR(50), + `p18` VARCHAR(50) + ); + +DROP TABLE IF EXISTS `cuestionario_programa_2`; + +CREATE TABLE + `cuestionario_programa_2` ( + `idCuestionarioPrograma2` INT PRIMARY KEY NOT NULL AUTO_INCREMENT, + `createdAt` DATETIME, + `p3_A_1` VARCHAR(50), + `p3_A_2` VARCHAR(50), + `p3_A_3` VARCHAR(50), + `p3_A_4` VARCHAR(50), + `p3_B_1` VARCHAR(50), + `p3_B_2` VARCHAR(50), + `p3_B_3` VARCHAR(50), + `p3_B_4` VARCHAR(50), + `p3_C_1` VARCHAR(50), + `p3_C_2` VARCHAR(50), + `p3_C_3` VARCHAR(50), + `p3_C_4` VARCHAR(50), + `p3_C_5` VARCHAR(50), + `p3_D_1` VARCHAR(50), + `p3_D_2` VARCHAR(50), + `p3_D_3` VARCHAR(50), + `p3_D_4` VARCHAR(50), + `p3_D_5` VARCHAR(50), + `p3_E_1` VARCHAR(50), + `p1` VARCHAR(50), + `p2` VARCHAR(50), + `p4` VARCHAR(50), + `p5` VARCHAR(50), + `p6` VARCHAR(50), + `p7` VARCHAR(50) + ); + + + +ALTER TABLE servicio ADD COLUMN idCuestionarioAlumno2 INT; +ALTER TABLE servicio ADD COLUMN idCuestionarioPrograma2 INT; + +ALTER TABLE `servicio` ADD FOREIGN KEY (`idCuestionarioAlumno2`) REFERENCES `cuestionario_alumno_2` (`idCuestionarioAlumno2`); +ALTER TABLE `servicio` ADD FOREIGN KEY (`idCuestionarioPrograma2`) REFERENCES `cuestionario_programa_2` (`idCuestionarioPrograma2`); + + -- 2.43.0 From 4deb3e90935641fdd1ac39fdb15a9572a14ebaa0 Mon Sep 17 00:00:00 2001 From: Your Name Date: Fri, 21 Feb 2025 11:53:52 -0600 Subject: [PATCH 21/21] change pass hashed, verificarToken --- server/controller/Servicio/registro.js | 9 ++++----- server/middleware/autentificacion.js | 6 +++--- server/routes/CasoEspecial.js | 2 +- server/routes/CuestionarioPrograma.js | 6 +++--- server/routes/Programa.js | 2 +- server/routes/Servicio.js | 8 ++++---- 6 files changed, 16 insertions(+), 17 deletions(-) diff --git a/server/controller/Servicio/registro.js b/server/controller/Servicio/registro.js index 05677dd..82b4b6f 100644 --- a/server/controller/Servicio/registro.js +++ b/server/controller/Servicio/registro.js @@ -12,9 +12,9 @@ const registro = async (body) => { body.idServicio, 'id servicio' ); - //const password = encriptar.generarPassword(); // esta genera la contraseña - let pass = 'qwertyui' - const password = pass //encriptar.encriptar(pass) + const password = encriptar.generarPassword(); // esta genera la contraseña + if (process.env.MODE == "pruebas") password = 'qwertyui' + // const password = pass //encriptar.encriptar(pass) let correo = {}; let idUsuario; @@ -59,8 +59,7 @@ const registro = async (body) => { .then((res) => Servicio.update({ idStatus: 2 }, { where: { idServicio } })) .then((res) => ({ message: - 'Se cambio de estatus correctamente y se envio un correo al alumno con sus credenciales.', - pass + 'Se cambio de estatus correctamente y se envio un correo al alumno con sus credenciales.' })); }; diff --git a/server/middleware/autentificacion.js b/server/middleware/autentificacion.js index ce8a42d..f0f5572 100644 --- a/server/middleware/autentificacion.js +++ b/server/middleware/autentificacion.js @@ -5,7 +5,7 @@ const verificaToken = (req, res, next) => { let token = req.headers.token; - /* + if (!token) return res.status(400).json({ message: 'No se envio el token. v2', @@ -26,9 +26,9 @@ const verificaToken = (req, res, next) => { next(); }); - */ + - next() + // next() // solo esta linea si se estan haciendo pruebas }; const crearToken = (info) => { diff --git a/server/routes/CasoEspecial.js b/server/routes/CasoEspecial.js index b393b7b..679e1a4 100644 --- a/server/routes/CasoEspecial.js +++ b/server/routes/CasoEspecial.js @@ -15,7 +15,7 @@ const update = require(`${controllerPath}/update`); // POST app.post( `${route}/nuevo`, - // verificaToken, + verificaToken, upload.single('archivos'), (req, res) => { return nuevo(JSON.parse(req.body.alumno), req.file.filename) diff --git a/server/routes/CuestionarioPrograma.js b/server/routes/CuestionarioPrograma.js index 2410fb4..4387ac4 100644 --- a/server/routes/CuestionarioPrograma.js +++ b/server/routes/CuestionarioPrograma.js @@ -1,6 +1,6 @@ const express = require('express'); const app = express(); -//const { verificaToken } = require('../middleware/autentificacion'); +const { verificaToken } = require('../middleware/autentificacion'); const route = '/cuestionario_programa'; const controllerPath = '../controller/CuestionarioPrograma'; @@ -9,7 +9,7 @@ const nuevo = require(`${controllerPath}/nuevo`); // POST app.post(`${route}`, - //verificaToken, + verificaToken, (req, res) => { return nuevo(req.body) .then((data) => { @@ -22,7 +22,7 @@ app.post(`${route}`, // GET app.get(`${route}`, - //verificaToken, + verificaToken, (req, res) => { return get(req.query) .then((data) => { diff --git a/server/routes/Programa.js b/server/routes/Programa.js index fbce79a..adca5c3 100644 --- a/server/routes/Programa.js +++ b/server/routes/Programa.js @@ -13,7 +13,7 @@ const reasignarProgramas = require(`${controllerPath}/reasignarProgramas`); // POST app.post( `${route}/carga_masiva`, - // verificaToken, + verificaToken, upload.single('csv'), (req, res) => { if (req.file) { diff --git a/server/routes/Servicio.js b/server/routes/Servicio.js index 57a7929..eed2d99 100644 --- a/server/routes/Servicio.js +++ b/server/routes/Servicio.js @@ -28,7 +28,7 @@ const gustavoBazPrada = require(`${controllerPath}/gustavoBazPrada`); // POST app.post( `${route}/nuevo`, - // verificaToken, + verificaToken, upload.single('cartaAceptacion'), (req, res) => { return nuevo(JSON.parse(req.body.alumno), req.file.filename) @@ -116,7 +116,7 @@ app.put(`${route}/cancelar`, verificaToken, (req, res) => { app.put( `${route}/carta_aceptacion`, - // verificaToken, + verificaToken, upload.single('cartaAceptacion'), (req, res) => { return cartaAceptacion(JSON.parse(req.body.data), req.file.filename) @@ -132,7 +132,7 @@ app.put( app.put( `${route}/carta_termino`, - // verificaToken, + verificaToken, upload.single('cartaTermino'), (req, res) => { return cartaTermino(JSON.parse(req.body.data), req.file.filename) @@ -148,7 +148,7 @@ app.put( app.put( `${route}/informe_global`, - // verificaToken, + verificaToken, upload.single('informeGlobal'), (req, res) => { return informeGlobal(JSON.parse(req.body.data), req.file.filename) -- 2.43.0