utn-cli 2.1.16 → 2.1.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (21) hide show
  1. package/commands/backend.js +40 -63
  2. package/package.json +1 -1
  3. package/templates/backend/servicios/InformacionDelModulo.js +168 -48
  4. package/templates/backend/servicios/Nucleo/Miscelaneas.js +84 -2433
  5. package/templates/backend/servicios/Nucleo/MiscelaneasMixins/Archivos.js +329 -0
  6. package/templates/backend/servicios/Nucleo/MiscelaneasMixins/Autenticacion.js +388 -0
  7. package/templates/backend/servicios/Nucleo/MiscelaneasMixins/InicializacionDelModulo.js +254 -0
  8. package/templates/backend/servicios/Nucleo/MiscelaneasMixins/Modulos.js +261 -0
  9. package/templates/backend/servicios/Nucleo/MiscelaneasMixins/Notificaciones.js +82 -0
  10. package/templates/backend/servicios/Nucleo/MiscelaneasMixins/Personas.js +93 -0
  11. package/templates/backend/servicios/Nucleo/MiscelaneasMixins/Reportes.js +370 -0
  12. package/templates/backend/servicios/Nucleo/MiscelaneasMixins/TareasProgramadas.js +105 -0
  13. package/templates/frontend/src/app/Componentes/Nucleo/gestion-actividad/gestion-actividad.component.css +16 -1
  14. package/templates/frontend/src/app/Componentes/Nucleo/gestion-actividad/gestion-actividad.component.html +1 -1
  15. package/templates/frontend/src/app/Componentes/Nucleo/manual/manual.component.html +17 -16
  16. package/templates/frontend/src/app/Componentes/Nucleo/manual/manual.component.ts +11 -2
  17. package/templates/frontend/src/app/Componentes/Nucleo/reporte-de-incidencias/reporte-de-incidencias.component.css +0 -1
  18. package/templates/frontend/src/app/Componentes/Nucleo/reporte-de-sugerencias/reporte-de-sugerencias.component.css +0 -1
  19. package/templates/frontend/src/app/Componentes/Nucleo/tabla/tabla.component.css +4 -0
  20. package/templates/frontend/src/app/Componentes/Nucleo/tarjeta-modulo/tarjeta-modulo.component.css +1 -1
  21. package/templates/frontend/src/app/Paginas/Nucleo/contenedor-componentes/contenedor-componentes.component.css +26 -0
@@ -1,7 +1,15 @@
1
1
  const { ejecutarConsulta, ejecutarConsultaSIGU, crearObjetoConexionSIGU } = require('./db.js');
2
2
  const ManejadorDeErrores = require('./ManejadorDeErrores.js');
3
3
  const InformacionDelModulo = require('../InformacionDelModulo.js');
4
- const { envioDeCorreo } = require('./EnvioDeCorreos.js');
4
+
5
+ const MixinAutenticacion = require('./MiscelaneasMixins/Autenticacion.js');
6
+ const MixinNotificaciones = require('./MiscelaneasMixins/Notificaciones.js');
7
+ const MixinTareasProgramadas = require('./MiscelaneasMixins/TareasProgramadas.js');
8
+ const MixinPersonas = require('./MiscelaneasMixins/Personas.js');
9
+ const MixinArchivos = require('./MiscelaneasMixins/Archivos.js');
10
+ const MixinModulos = require('./MiscelaneasMixins/Modulos.js');
11
+ const MixinInicializacion = require('./MiscelaneasMixins/InicializacionDelModulo.js');
12
+ const MixinReportes = require('./MiscelaneasMixins/Reportes.js');
5
13
 
6
14
  class Miscelaneo {
7
15
 
@@ -30,8 +38,6 @@ class Miscelaneo {
30
38
  this.CorreoParaReportes = InformacionDelModulo.getCorreoParaReportes();
31
39
  this.Version = InformacionDelModulo.getVersion();
32
40
 
33
- // Declaración de variables
34
- // A estas variables no es necesario darles un valor inicial
35
41
  this.UUID = 'UUID';
36
42
  this.Enlace = undefined;
37
43
  this.RolId = 0;
@@ -39,49 +45,37 @@ class Miscelaneo {
39
45
  this.EnlaceDePortal = undefined;
40
46
  this.EnlaceDePerfil = undefined;
41
47
  this.EnlaceDeAcceso = undefined;
42
- };
48
+ }
43
49
 
44
50
  async PasosDeFlujoDeAprobacion(Identificador, PasoActual, Accion, Metadatos, Justificacion, LastUser) {
45
51
  const DatosARetornar = {};
46
-
47
- // Determina si la acción es una improbación para manejar el flujo de forma diferente
48
52
  const EsImprobacion = Accion === 'Improbacion';
49
-
50
- // Obtiene el ID del flujo de aprobación configurado para este módulo
51
53
  const idDelFlujoDeAprobacion = await this.idDelFlujoDeAprobacion();
52
54
 
53
- // Consulta cuál es el último paso del flujo, para saber si el detalle queda completamente aprobado
54
55
  const PasoMaximo = await ejecutarConsultaSIGU("SELECT MAX(`NumeroDePaso`) \
55
56
  AS `PasoMaximo` FROM `SIGU`.`SIGU_FlujosDeAprobacionPasos` WHERE \
56
57
  `FlujoDeAprobacionId` = ?"
57
58
  , [idDelFlujoDeAprobacion]);
58
59
 
59
- // En improbación el flujo retrocede, por lo que el paso siguiente se resuelve después;
60
- // en aprobación simplemente avanza al siguiente paso
61
60
  let PasoSiguiente = EsImprobacion ? PasoActual : PasoActual + 1;
62
61
 
63
- // Verifica que el usuario tenga permiso para actuar en el paso correspondiente
64
62
  const TienePermiso = await ejecutarConsultaSIGU("SELECT `NumeroDePasoPorImprobacion` FROM `SIGU`.`SIGU_FlujosDeAprobacionPasos` \
65
63
  WHERE `NumeroDePaso`=? AND (`Identificadores` LIKE '%?%' OR `Identificadores`='Persona usuaria')",
66
64
  [PasoSiguiente, Number(Identificador)]);
67
65
 
68
- // Si el usuario no aparece como firmante autorizado del paso, se corta la ejecución
69
66
  if (TienePermiso.length == 0) {
70
67
  DatosARetornar.Mensaje = 'No tiene permisos para firmar este detalle';
71
68
  DatosARetornar.error = true;
72
69
  return DatosARetornar;
73
70
  }
74
71
 
75
- // Registra el movimiento en el historial del flujo de aprobación
76
72
  await ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_FlujosDeAprobacionMovimientos` VALUES (?, ?, ?, ?, ?, ?, NOW(4), ?)"
77
73
  , [idDelFlujoDeAprobacion, PasoActual
78
74
  , Identificador, Accion
79
75
  , Justificacion, JSON.stringify(Metadatos), LastUser]);
80
76
 
81
- // En improbación, el paso destino viene definido en la configuración del flujo (retroceso configurado)
82
77
  PasoSiguiente = EsImprobacion ? TienePermiso[0].NumeroDePasoPorImprobacion : PasoSiguiente;
83
78
 
84
- // Indica al llamador si el detalle alcanzó el último paso y debe cambiar su estado global
85
79
  DatosARetornar.CambiarEstado = PasoSiguiente === PasoMaximo[0].PasoMaximo;
86
80
  DatosARetornar.Mensaje = EsImprobacion ? 'Detalle firmado como no aprobado' : 'Detalle firmado correctamente';
87
81
  DatosARetornar.PasoSiguiente = PasoSiguiente;
@@ -116,7 +110,7 @@ class Miscelaneo {
116
110
  JSON_VALUE(Solicitud, '$.originalUrl') AS URL,
117
111
  IFNULL(JSON_VALUE(Solicitud, '$.country'), 'Costa Rica') AS Pais,
118
112
  SUBSTRING_INDEX(JSON_VALUE(Solicitud, '$.headers.authorization'), ' ', -1) AS Token,
119
- CASE
113
+ CASE
120
114
  WHEN JSON_VALUE(Solicitud, '$.userAgent') LIKE '%Mobile%' THEN 'Móvil'
121
115
  WHEN JSON_VALUE(Solicitud, '$.userAgent') LIKE '%Android%' AND JSON_VALUE(Solicitud, '$.userAgent') NOT LIKE '%Mobile%' THEN 'Tablet'
122
116
  WHEN JSON_VALUE(Solicitud, '$.userAgent') LIKE '%iPad%' THEN 'Tablet'
@@ -135,11 +129,6 @@ class Miscelaneo {
135
129
  }
136
130
  }
137
131
 
138
- async cerrarSesionPorToken(Token) {
139
- await ejecutarConsultaSIGU("DELETE FROM `SIGU`.`SIGU_Sesiones` WHERE `Token` = ?", [Token]);
140
- return true;
141
- }
142
-
143
132
  async UsuariosActuales() {
144
133
  const ConexionSigu = await crearObjetoConexionSIGU();
145
134
  const Actuales = await ConexionSigu.query("SELECT COUNT(DISTINCT `Identificador`) AS `Total` FROM `SIGU`.`SIGU_Sesiones` WHERE `LastUpdate` >= NOW() - INTERVAL 2 HOUR");
@@ -148,2441 +137,103 @@ class Miscelaneo {
148
137
  return {
149
138
  UsuariosActuales: Actuales[0][0]['Total'],
150
139
  UsuariosActivos: Activos[0][0]['Total']
151
- }
152
- }
153
-
154
- async generarFirmaHTML(Identificador, FechaDeLaFirma) {
155
- const ReporteHTML = require('./ReporteHTML.js');
156
- return await ReporteHTML.generarFirmaHTML(Identificador, FechaDeLaFirma);
157
- }
158
-
159
- GenerarReporteHTMLRegistrosVerticales(ElementosParaLaTabla, ParametrosExcluidos = [], ParametrosExtra = [], MostrarEncabezado = true) {
160
- const ReporteHTML = require('./ReporteHTML.js');
161
- return ReporteHTML.GenerarReporteHTMLRegistrosVerticales(ElementosParaLaTabla, ParametrosExcluidos, ParametrosExtra, MostrarEncabezado);
162
- }
163
-
164
- GenerarReporteHTMLEncabezado(InformacionDeLaDerecha, titulares, marcaDeAgua = '') {
165
- const ReporteHTML = require('./ReporteHTML.js');
166
- return ReporteHTML.GenerarReporteHTMLEncabezado(InformacionDeLaDerecha, titulares, marcaDeAgua);
167
- }
168
-
169
- GenerarReporteHTMLFecha() {
170
- const ReporteHTML = require('./ReporteHTML.js');
171
- return ReporteHTML.GenerarReporteHTMLFecha();
172
- }
173
-
174
- GenerarReporteHTMLTablas(ElementosParaLaTabla, ParametrosExcluidos = [], ParametrosExtra = []) {
175
- const ReporteHTML = require('./ReporteHTML.js');
176
- return ReporteHTML.GenerarReporteHTMLTablas(ElementosParaLaTabla, ParametrosExcluidos, ParametrosExtra);
177
- }
178
-
179
- GenerarReporteHTMLPie() {
180
- const ReporteHTML = require('./ReporteHTML.js');
181
- return ReporteHTML.GenerarReporteHTMLPie();
182
- }
183
-
184
- obtenerNombreLaBaseDeDatos() {
185
- return this.NombreDelRepositorioDeLaBaseDeDatos.slice(0, -3);
186
- }
187
-
188
- async RegistrarPermisoExtra(Permiso, Descripcion) {
189
- await ejecutarConsultaSIGU("SELECT IFNULL(MAX(`PermisoExtraId`), 0) + 1 INTO @`SiguientePermisoId` FROM `SIGU`.`SIGU_PermisosExtraV2`;\
190
- INSERT INTO `SIGU`.`SIGU_PermisosExtraV2` VALUES\
191
- (@`SiguientePermisoId`, ?, ?, ?, NOW(4), USER()) ON DUPLICATE KEY UPDATE `LastUser` = USER(), `Nombre` = ?, `Descripcion` = ?;"
192
- , [Permiso, this.NombreCanonicoDelModulo, Descripcion, Permiso, Descripcion]);
193
-
194
- // Asginación inicial de permisos
195
- if (this.UsuariosConAccesoInicial.length > 0) {
196
- const PermisoExtraIdValor = await this.PermisoExtraId(Permiso);
197
- this.UsuariosConAccesoInicial.forEach(async (dato) => {
198
- await ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_PermisosExtraPersonasV2` VALUES (?,\
199
- (SELECT `Identificador` FROM `SIGU`.`SIGU_Personas` WHERE `Identificacion` = ?), NOW(4), USER())\
200
- ON DUPLICATE KEY UPDATE `LastUpdate` = NOW(4)"
201
- , [PermisoExtraIdValor, dato]);
202
- });
203
- }
204
- }
205
-
206
- async PermisoExtraId(Permiso) {
207
- const PermisoExtraId = await ejecutarConsultaSIGU("SELECT `PermisoExtraId` FROM `SIGU`.`SIGU_PermisosExtraV2` \
208
- WHERE `Nombre` = ? AND `Modulo` = ?"
209
- , [Permiso, this.NombreCanonicoDelModulo]);
210
- return PermisoExtraId[0]['PermisoExtraId'];
211
- }
212
-
213
- obtenerNombreCanonicoDelModulo() {
214
- return this.NombreCanonicoDelModulo;
215
- }
216
-
217
- obtenerVersionDelModulo() {
218
- return this.Version;
140
+ };
219
141
  }
220
142
 
221
- async convertirTextoEnArchivoLocal(Texto, Token, NombreDelArchivo, Etiquetas) {
222
- let EnlaceDelBack = 'http';
223
- EnlaceDelBack = EnlaceDelBack + ((process.env.ENV || 'local') === 'production' ? 's' : '');
224
- EnlaceDelBack = EnlaceDelBack + '://';
225
- EnlaceDelBack = EnlaceDelBack + (['desarrollo', 'calidad', 'pruebas', 'production'].includes(process.env.ENV) ? this.NombreDelRepositorioDelBackend : 'localhost');
226
- EnlaceDelBack = EnlaceDelBack + '/misc/cargarArchivo/' + Etiquetas;
227
- // let EnlaceDelBack = `${Solicitud.protocol}://${Solicitud.get('host')}` + '/misc/cargarArchivo/' + Etiquetas;
143
+ async consumirBackend(URL, Cuerpo = undefined, Tipo = undefined) {
228
144
  const Encabezados = {
229
- 'Authorization': Token,
145
+ 'Content-Type': 'application/json',
146
+ 'Authorization': 'Bearer ' + await this.getUUID(),
230
147
  'Referrer': this.NombreDelRepositorioDelBackend,
231
- 'Origin': EnlaceDelBack
148
+ 'Origin': this.Enlace
232
149
  };
233
- const blob = new Blob([Texto], { type: 'text/plain' });
234
- const formData = new FormData();
235
- formData.append('archivo', blob, NombreDelArchivo);
236
- try {
237
- const response = await fetch(EnlaceDelBack, {
238
- method: 'POST',
239
- headers: Encabezados,
240
- body: formData,
241
- redirect: 'error'
242
- });
243
- if (!response.ok) {
244
- const errorTexto = await response.text();
245
- throw new Error(`Error del servidor (${response.status}): ${errorTexto}`);
246
- }
247
- return await response.json();
248
- } catch (error) {
249
- console.error(error.message);
250
- }
251
- }
252
-
253
- async RegistrarElServicio(Servicio, Tarjetas = null) {
254
- const archivo = this._archivoFuenteActual;
255
- try {
256
- await ejecutarConsultaSIGU("REPLACE INTO `SIGU`.`SIGU_ModulosV2Secciones` (`Modulo`, `Descripcion`) VALUES (?, ?)"
257
- , [this.NombreCanonicoDelModulo, Servicio]);
258
- console.log(`Servicio ${Servicio} registrado correctamente`);
259
- } catch (error) {
260
- console.error(error.message);
261
- }
262
-
263
- if (!Tarjetas) return;
264
-
265
- const listaTarjetas = Array.isArray(Tarjetas) ? Tarjetas : [Tarjetas];
266
-
267
- for (const tarjeta of listaTarjetas) {
268
- try {
269
- const titulo = tarjeta['Título'];
270
- const existentes = await ejecutarConsultaSIGU(
271
- `SELECT CAST(JSON_VALUE(\`Datos\`, '$."Posición"') AS UNSIGNED) AS Posicion, JSON_VALUE(\`Datos\`, '$."Título"') AS Titulo, JSON_VALUE(\`Datos\`, '$."Descripción"') AS Descripcion FROM \`SIGU\`.\`SIGU_ModulosV2Tarjetas\` WHERE \`Modulo\` = ? AND JSON_VALUE(\`Datos\`, '$."Título"') = ?`,
272
- [this.NombreCanonicoDelModulo, titulo]
273
- );
274
-
275
- let datosFinales;
276
- if (existentes.length > 0) {
277
- datosFinales = { ...tarjeta, 'Posición': existentes[0].Posicion, 'Título': existentes[0].Titulo, 'Descripción': existentes[0].Descripcion, 'Archivo': archivo };
278
- await ejecutarConsultaSIGU(
279
- `UPDATE \`SIGU\`.\`SIGU_ModulosV2Tarjetas\` SET \`Datos\` = ?, \`LastUser\` = 'Sistema' WHERE \`Modulo\` = ? AND JSON_VALUE(\`Datos\`, '$."Título"') = ?`,
280
- [JSON.stringify(datosFinales), this.NombreCanonicoDelModulo, titulo]
281
- );
282
- } else {
283
- let posicion = tarjeta['Posición'];
284
- if (posicion === undefined) {
285
- const [{ NuevaPosicion }] = await ejecutarConsultaSIGU(
286
- `SELECT COALESCE(MAX(CAST(JSON_VALUE(\`Datos\`, '$."Posición"') AS UNSIGNED)), 0) + 10 AS NuevaPosicion FROM \`SIGU\`.\`SIGU_ModulosV2Tarjetas\` WHERE \`Modulo\` = ?`,
287
- [this.NombreCanonicoDelModulo]
288
- );
289
- posicion = NuevaPosicion;
290
- }
291
- datosFinales = { ...tarjeta, 'Posición': posicion, 'Archivo': archivo };
292
- await ejecutarConsultaSIGU(
293
- `INSERT INTO \`SIGU\`.\`SIGU_ModulosV2Tarjetas\` (\`Modulo\`, \`Datos\`, \`LastUser\`) VALUES (?, ?, 'Sistema')`,
294
- [this.NombreCanonicoDelModulo, JSON.stringify(datosFinales)]
295
- );
296
- }
297
- console.log(`Tarjeta "${titulo}" registrada correctamente`);
298
- } catch (error) {
299
- console.error(`Error al registrar tarjeta "${tarjeta['Título']}":`, error.message);
300
- }
301
- }
302
- }
303
-
304
- _archivoFuenteActual = null;
305
- _archivoCache = new Map();
306
-
307
- _buscarArchivoRecursivo(dir, nombre) {
308
- if (this._archivoCache.has(nombre)) return this._archivoCache.get(nombre);
309
- const fs = require('fs');
310
- const path = require('path');
311
- const buscar = (directorio) => {
312
- for (const entrada of fs.readdirSync(directorio, { withFileTypes: true })) {
313
- const ruta = path.join(directorio, entrada.name);
314
- if (entrada.isDirectory()) {
315
- const resultado = buscar(ruta);
316
- if (resultado) return resultado;
317
- } else if (entrada.name === nombre) {
318
- return ruta;
319
- }
320
- }
321
- return null;
150
+ let Respuesta = undefined;
151
+ const Opciones = {
152
+ method: Cuerpo ? "POST" : "GET",
153
+ headers: Encabezados,
154
+ redirect: 'error'
322
155
  };
323
- const resultado = buscar(dir);
324
- this._archivoCache.set(nombre, resultado);
325
- return resultado;
326
- }
327
-
328
- async DatosParaReporteCSV() {
329
- return this.convertirACSV(await this.DatosParaGraficoDeBarras());
330
- }
331
-
332
- async DatosParaGraficoDeBarras() {
333
- return await ejecutarConsultaSIGU("SELECT MONTHNAME(`FechaNacimiento`) AS `EjeHorizontal`, `Sexo` AS `Etiqueta`, COUNT(*) AS `Total` FROM `SIGU`.`SIGU_Personas` WHERE MONTH(`FechaNacimiento`) > 0 AND `Sexo` <> '' GROUP BY MONTHNAME(`FechaNacimiento`), `Sexo` ORDER BY MONTH(`FechaNacimiento`)");
334
- }
335
-
336
- async DatosParaGraficoDePie() {
337
- return await ejecutarConsultaSIGU("SELECT `Tipo` AS `Etiqueta`, COUNT(*) AS `Total` FROM `SIGU`.`SIGU_ModulosV2` GROUP BY `Tipo`");
338
- }
339
-
340
- JSONAHTML(input, title = 'Reporte') {
341
- // intentar parsear si es string JSON
342
- let obj = input;
343
- if (typeof input === 'string') {
344
- try { obj = JSON.parse(input); }
345
- catch (e) { /* no es JSON, lo tratamos como texto primitivo */ }
346
- }
347
-
348
- const escapeHtml = (s) =>
349
- String(s)
350
- .replace(/&/g, '&amp;')
351
- .replace(/</g, '&lt;')
352
- .replace(/>/g, '&gt;')
353
- .replace(/"/g, '&quot;')
354
- .replace(/'/g, '&#39;');
355
-
356
- const isPrimitive = v => v === null || v === undefined || typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean';
357
-
358
- const seen = new WeakSet();
359
-
360
- function renderValue(v) {
361
- if (v === null || v === undefined || v === '') return '—';
362
- if (isPrimitive(v)) return escapeHtml(String(v));
363
- if (Array.isArray(v)) return renderArray(v);
364
- return renderObject(v);
365
- }
366
-
367
- function renderObject(o) {
368
- if (seen.has(o)) return '<em>(referencia circular)</em>';
369
- seen.add(o);
370
-
371
- // si es objeto vacío
372
- const keys = Object.keys(o);
373
- if (keys.length === 0) {
374
- seen.delete(o);
375
- return '—';
376
- }
377
-
378
- // construir filas key / value
379
- let rows = '';
380
- for (const k of keys) {
381
- rows += `
382
- <tr>
383
- <th>${escapeHtml(k)}</th>
384
- <td>${renderValue(o[k])}</td>
385
- </tr>
386
- `;
387
- }
388
-
389
- seen.delete(o);
390
- return `<table border='1'><tbody>${rows}</tbody></table>`;
391
- }
392
-
393
- function renderArray(arr) {
394
- if (arr.length === 0) return '—';
395
-
396
- // si todos son primitivos => lista simple
397
- if (arr.every(isPrimitive)) {
398
- return `<div>${arr.map(x => `<span>${escapeHtml(String(x))}</span>`).join(' ')}</div>`;
399
- }
400
-
401
- // si todos son objetos => tabla con columnas (union de keys)
402
- if (arr.every(it => typeof it === 'object' && it !== null && !Array.isArray(it))) {
403
- const columns = Array.from(new Set(arr.flatMap(item => Object.keys(item))));
404
- const header = columns.map(c => `<th>${escapeHtml(c)}</th>`).join('');
405
- const body = arr.map(item => {
406
- const cells = columns.map(c => `<td>${item.hasOwnProperty(c) ? renderValue(item[c]) : ''}</td>`).join('');
407
- return `<tr>${cells}</tr>`;
408
- }).join('');
409
- return `<table border='1'><thead><tr>${header}</tr></thead><tbody>${body}</tbody></table>`;
410
- }
411
-
412
- // mezcla de tipos: render por ítem
413
- return `<div>${arr.map(it => `<div>${renderValue(it)}</div>`).join('')}</div>`;
414
- }
415
-
416
- // construir contenido (una sección por clave del primer nivel)
417
- let content = '';
418
- if (typeof obj === 'object' && obj !== null && !Array.isArray(obj)) {
419
- const topKeys = Object.keys(obj);
420
- for (const k of topKeys) {
421
- content += `
422
- <section>
423
- <h2>${escapeHtml(k)}</h2>
424
- <div>${renderValue(obj[k])}</div>
425
- </section>
426
- `;
427
- }
428
- } else {
429
- // si el input fue un array o primitivo
430
- content = `<section><div>${renderValue(obj)}</div></section>`;
431
- }
432
-
433
- // template HTML + CSS
434
- return `<h1>${escapeHtml(title)}</h1>${content}`;
435
- }
436
-
437
- async generarLastUser(Solicitud) {
438
- const Resultado = await this.obtenerDatosDelUsuario(Solicitud.headers.authorization);
439
- // try {
440
- // Resultado = await this.obtenerDatosDelUsuario(Solicitud.headers.authorization);
441
- // if (!Resultado) {
442
- // throw new ManejadorDeErrores(ManejadorDeErrores.mensajeDeErrorVerificacionDeToken(), ManejadorDeErrores.obtenerNumeroDeLinea());
443
- // }
444
- // } catch (error) {
445
- // console.log(error);
446
- // }
447
- let LastUser = '';
448
- if (Resultado) {
449
- LastUser = Resultado.Identificador;
450
- }
451
- LastUser = LastUser + '@' + Solicitud.headers.host.trim()
452
- + '@' + Solicitud.headers["user-agent"].trim()
453
- + '@' + (Solicitud.ip || Solicitud.headers['x-forwarded-for'] || Solicitud.socket.remoteAddress);
454
- return LastUser;
455
- }
456
-
457
- async validarAccesoDelOrigen(Solicitud) {
458
- if (this.NombresParalocalhost().includes(process.env.HOST) && (typeof process.env.DB_HOST_SIGU === "undefined")) {
459
- return true;
460
- }
461
- const Resultado = await ejecutarConsultaSIGU("SELECT COUNT(*) AS `Total` FROM `SIGU`.`SIGU_RepositoriosAccesos`\
462
- WHERE `RepositorioDestino` = ? AND `RepositorioOrigen` = ?"
463
- , [this.NombreDelRepositorioDelBackend, this.NombreDelRepositorioDelFrontend]);
464
- if (Resultado[0]['Total'] === 1) {
465
- return true;
466
- } else {
467
- console.error('validarAccesoDelOrigen:', Solicitud.headers.origin, 'intentó consumir a:', this.NombreDelRepositorioDelBackend);
468
- const Mensaje = "Error de validarAccesoDelOrigen por fallo de autorización.";
469
- const solicitudCompleta = {
470
- metodo: Solicitud.method,
471
- url: Solicitud.originalUrl,
472
- ip: Solicitud.ip,
473
- headers: Solicitud.headers,
474
- query: Solicitud.query,
475
- params: Solicitud.params,
476
- body: Solicitud.body,
477
- };
478
- const contenidoHTML = `
479
- <h2>Solicitud HTTP completa</h2>
480
- <p><strong>Método:</strong> ${solicitudCompleta.metodo}</p>
481
- <p><strong>URL:</strong> ${solicitudCompleta.url}</p>
482
- <p><strong>IP:</strong> ${solicitudCompleta.ip}</p>
483
- <h3>Headers:</h3>
484
- <pre>${JSON.stringify(solicitudCompleta.headers, null, 2)}</pre>
485
- <h3>Query:</h3>
486
- <pre>${JSON.stringify(solicitudCompleta.query, null, 2)}</pre>
487
- <h3>Params:</h3>
488
- <pre>${JSON.stringify(solicitudCompleta.params, null, 2)}</pre>
489
- <h3>Body:</h3>
490
- <pre>${JSON.stringify(solicitudCompleta.body, null, 2)}</pre>
491
- `;
492
- envioDeCorreo(process.env.DESTINATARIODEINFORMESDEERROR, Mensaje, contenidoHTML);
493
- }
494
- return false;
495
- }
496
-
497
- getNombreDelRepositorioDelBackend() {
498
- return this.NombreDelRepositorioDelBackend;
499
- }
500
-
501
- async ejecucionCadaXMinutos(callback, intervaloMinutos) {
502
- while (true) {
503
- try {
504
- await this.crearTareaProgramada(callback);
505
- break;
506
- } catch (error) {
507
- console.error('Error al ejecutar crearTareaProgramada:', error);
508
- console.log('Reintentando en 5 segundos...');
509
- await new Promise(resolve => setTimeout(resolve, 5000));
510
- }
511
- }
512
- const intervaloMilisegundos = intervaloMinutos * 60 * 1000;
513
- while (true) {
514
- const inicio = Date.now();
515
- try {
516
- await callback();
517
- } catch (error) {
518
- console.error(`Error en la función "${callback.name}":`, error?.message || error);
519
- }
520
- const duracion = Date.now() - inicio;
521
- const tiempoRestante = intervaloMilisegundos - duracion;
522
- if (tiempoRestante > 0) {
523
- await new Promise(resolve => setTimeout(resolve, tiempoRestante));
524
- }
525
- }
526
- }
527
-
528
- async restablecimientoDeClave(Solicitud) {
529
- let Clave = await ejecutarConsultaSIGU("SELECT MD5(NOW(4)) AS `Dato`");
530
- Clave = Clave[0]['Dato'];
531
- console.log("El usuario: " + Solicitud.body.Identificacion + " ha solicitado restablecer su clave de acceso.");
532
- const CorreoElectronico = await ejecutarConsultaSIGU("SELECT `CorreoElectronico`, `Identificador` FROM `SIGU`.`SIGU_CorreosPersona` WHERE `Identificador` = (SELECT `Identificador` FROM `SIGU`.`SIGU_Personas` WHERE `Identificacion` = ?) AND `Principal` = TRUE LIMIT 1"
533
- , [Solicitud.body.Identificacion]);
534
- const LastUser = Solicitud.body.Identificacion
535
- + '@' + Solicitud.headers.host.trim()
536
- + '@' + Solicitud.headers["user-agent"].trim()
537
- + '@' + (Solicitud.ip || Solicitud.headers['x-forwarded-for'] || Solicitud.socket.remoteAddress);
538
- await ejecutarConsultaSIGU("REPLACE INTO `SIGU`.`SIGU_ClavesTemporalesDeLasPersonas` VALUES (?, ?, NOW(4), ?)"
539
- , [CorreoElectronico[0]['Identificador'], Clave, LastUser]);
540
- const SolicitudTextual = JSON.stringify({
541
- timestamp: new Date().toISOString(),
542
- httpVersion: Solicitud.httpVersion,
543
- method: Solicitud.method,
544
- protocol: Solicitud.protocol,
545
- secure: Solicitud.secure,
546
- ip: Solicitud.ip,
547
- ips: Solicitud.ips,
548
- hostname: Solicitud.hostname,
549
- originalUrl: Solicitud.originalUrl,
550
- baseUrl: Solicitud.baseUrl,
551
- path: Solicitud.path,
552
- url: Solicitud.url,
553
- headers: Solicitud.headers,
554
- query: Solicitud.query,
555
- params: Solicitud.params,
556
- body: Solicitud.body,
557
- cookies: Solicitud.cookies,
558
- signedCookies: Solicitud.signedCookies,
559
- userAgent: Solicitud.get('User-Agent'),
560
- authUser: Solicitud.user ?? null,
561
- });
562
- await ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_SolicitudesDeRestablecimientoDeClave` VALUES (?, ?, ?, NOW(4), ?)"
563
- , [CorreoElectronico[0]['Identificador'], Solicitud.body.Identificacion
564
- , SolicitudTextual, LastUser]);
565
- await envioDeCorreo(CorreoElectronico[0]['CorreoElectronico'], "Solicitud de restablecimiento de clave",
566
- "<p>Estimada persona usuaria,<br /><br />"
567
- + "Se ha realizado una solicitud de cambio de clave para su cuenta de acceso a SIGU.</p>"
568
- + "<p>Para continuar con el cambio por favor presione "
569
- + "<a href='" + this.EnlaceDeAcceso + "/?Identificacion=" + Solicitud.body.Identificacion + "'>aquí</a>"
570
- + " de lo contrario omita este mensaje.</p>"
571
- + "<p>Su nueva clave es: " + Clave + " y se le invita a cambiarla lo antes posible haciendo uso del sistema.</p>"
572
- + "<p>La vigencia de la clave generada es de 10 minutos, luego de eso se eliminará la solicitud.</p>"
573
- + "<p>Si usted no solicitó el cambio de contraseña por favor omita este correo.</p>");
574
- return;
575
- }
576
-
577
- async AutenticarConGoogle(Solicitud) {
578
- const { OAuth2Client } = require('google-auth-library');
579
- const jwt = require('jsonwebtoken');
580
- const clientId = await this.googleClientId();
581
- const client = new OAuth2Client(clientId);
582
- const ConexionSigu = await crearObjetoConexionSIGU();
583
- const LastUser = await this.generarLastUser(Solicitud);
584
-
585
- try {
586
- const ticket = await client.verifyIdToken({
587
- idToken: Solicitud.body.token,
588
- audience: clientId,
589
- });
590
- const payload = ticket.getPayload();
591
- const email = payload['email'];
592
-
593
- const resultadosEmail = await ConexionSigu.query("SELECT `Identificador` FROM `SIGU`.`SIGU_CorreosPersona` WHERE `CorreoElectronico` = ? AND `Principal` = TRUE LIMIT 1", [email]);
594
-
595
- if (resultadosEmail[0].length === 0) {
596
- console.log("El correo de Google", email, "no está registrado como principal en SIGU");
597
- return { error: "Su cuenta de Google no está vinculada a ningún usuario de SIGU." };
598
- }
599
-
600
- const Identificador = resultadosEmail[0][0]['Identificador'];
601
- const resultadosUsuario = await ConexionSigu.query("SELECT `Identificacion` FROM `SIGU`.`SIGU_Personas` WHERE `Identificador` = ? AND `Activo` = TRUE", [Identificador]);
602
-
603
- if (resultadosUsuario[0].length === 0) {
604
- return { error: "El usuario asociado a esta cuenta no está activo." };
605
- }
606
-
607
- const Identificacion = resultadosUsuario[0][0]['Identificacion'];
608
-
609
- // Generar Token
610
- const Token = await jwt.sign({ Identificador: Identificador, uid: Identificador }, await this.palabraSecretaParaTokens(), { expiresIn: '2h' });
611
- await ConexionSigu.query("INSERT INTO `SIGU`.`SIGU_Sesiones` VALUES (?, ?, ?, NOW(4), ?) ON DUPLICATE KEY UPDATE `Token` = ?, `LastUser` = ?", [Identificador, Solicitud.headers.host.trim(), Token, LastUser, Token, LastUser]);
612
- await ConexionSigu.query("DELETE FROM `SIGU`.`SIGU_SesionesFallidas` WHERE `Identificador` = ?", [Identificador]);
613
-
614
- // OBTENER IP DEL USUARIO
615
- const ipUsuario = (Solicitud.headers['x-forwarded-for'] || '').split(',').shift() || Solicitud.socket?.remoteAddress || Solicitud.connection?.remoteAddress || '-';
616
-
617
- // SI LA IP YA EXISTE CONTINUA
618
- await ConexionSigu.query("\
619
- INSERT INTO `SIGU`.`SIGU_DireccionesUsadasPorLosUsuarios` \
620
- (`DireccionUsadaPorElUsuario`, `Identificador`, `LastUpdate`, `LastUser`) \
621
- VALUES (?, ?, NOW(4), ?) \
622
- ON DUPLICATE KEY UPDATE `LastUpdate` = NOW(4), `LastUser` = ?;", [
623
- ipUsuario,
624
- Identificador,
625
- LastUser,
626
- LastUser
627
- ]);
628
-
629
- return { Token, Dominio: ((process.env.ENV || 'local') === 'production' ? '.sigu.utn.ac.cr' : '.181.193.85.44.nip.io') };
630
-
631
- } catch (error) {
632
- console.error("Error en AutenticarConGoogle:", error);
633
- return { error: "Error al autenticar con Google" };
634
- } finally {
635
- if (ConexionSigu) await ConexionSigu.end();
636
- }
637
- }
638
-
639
- async Autenticar(Solicitud) {
640
- const crypto = require('crypto');
641
- const bcrypt = require('bcryptjs');
642
- const jwt = require('jsonwebtoken');
643
- const LastUser = await this.generarLastUser(Solicitud);
644
- const ConexionSigu = await crearObjetoConexionSIGU();
645
-
646
- try {
647
- const resultados = await ConexionSigu.query("SELECT `Identificador`, `Clave` FROM `SIGU`.`SIGU_Personas` WHERE `Activo` = TRUE AND `Identificacion` = ?", [Solicitud.body.Identificacion]);
648
- const Identificador = resultados[0][0]['Identificador'];
649
- const Resultado = await bcrypt.compare(crypto.createHash('md5').update(Solicitud.body.Clave).digest("hex"), resultados[0][0]['Clave']);
650
-
651
- if (Resultado) {
652
- console.log("La clave brindada para el usuario", Solicitud.body.Identificacion, "coincide");
653
- const Token = await jwt.sign({ Identificador: Identificador, uid: Identificador }, await this.palabraSecretaParaTokens(), { expiresIn: '2h' });
654
- await ConexionSigu.query("INSERT INTO `SIGU`.`SIGU_Sesiones` VALUES (?, ?, ?, NOW(4), ?) ON DUPLICATE KEY UPDATE `Token` = ?, `LastUser` = ?", [Identificador, Solicitud.headers.host.trim(), Token, LastUser, Token, LastUser]);
655
- await ConexionSigu.query("DELETE FROM `SIGU`.`SIGU_SesionesFallidas` WHERE `Identificador` = ?", [Identificador]);
656
- const permisos = await ConexionSigu.query("\
657
- WITH RECURSIVE`ModulosJerarquia` AS( \
658
- SELECT`Nombre`, `Padre` \
659
- FROM`SIGU`.`SIGU_ModulosV2` \
660
- WHERE`Nombre` COLLATE utf8mb4_spanish_ci IN(\
661
- SELECT`Modulo` \
662
- FROM`SIGU`.`SIGU_PermisosV2` \
663
- WHERE`Nombre` LIKE '%Público%' \
664
- ) \
665
- UNION ALL \
666
- SELECT`m`.`Nombre`, `m`.`Padre` \
667
- FROM`SIGU`.`SIGU_ModulosV2` `m` \
668
- INNER JOIN`ModulosJerarquia` `mj` \
669
- ON`mj`.`Padre` COLLATE utf8mb4_spanish_ci = \
670
- `m`.`Nombre` COLLATE utf8mb4_spanish_ci \
671
- ) \
672
- SELECT DISTINCT \
673
- `p`.`PermisoId` \
674
- FROM`ModulosJerarquia` `mj` \
675
- JOIN`SIGU`.`SIGU_PermisosV2` `p` \
676
- ON`p`.`Modulo` COLLATE utf8mb4_spanish_ci = \
677
- `mj`.`Nombre` COLLATE utf8mb4_spanish_ci; \
678
- ");
679
-
680
- for (const permiso of permisos[0]) {
681
- await ConexionSigu.query(" \
682
- INSERT INTO `SIGU`.`SIGU_PermisosPersonasV2` \
683
- (`PermisoId`, `Identificador`, `LastUpdate`, `LastUser`) \
684
- VALUES (?, ?, NOW(4), USER()) \
685
- ON DUPLICATE KEY UPDATE \
686
- `LastUser` = USER(), \
687
- `LastUpdate` = NOW(4);", [permiso.PermisoId, Identificador]);
688
- }
689
-
690
- // OBTENER IP DEL USUARIO
691
- const ipUsuario = (Solicitud.headers['x-forwarded-for'] || '').split(',').shift() || Solicitud.socket?.remoteAddress || Solicitud.connection?.remoteAddress || '-';
692
-
693
- // VERIFICAR SI LA IP YA EXISTE
694
- const ipExiste = await ConexionSigu.query("\
695
- SELECT COUNT(*) AS Total \
696
- FROM `SIGU`.`SIGU_DireccionesUsadasPorLosUsuarios` \
697
- WHERE `Identificador` = ? AND `DireccionUsadaPorElUsuario` = ?", [Identificador, ipUsuario]);
698
-
699
- // Verificar si la fecha de cambio supera los 2 meses
700
- const fechaUltimoCambio = await ConexionSigu.query(
701
- "SELECT LastUpdate \
702
- FROM `SIGU`.`SIGU_FechaDelUltimoCambioDeClave` \
703
- WHERE `Identificador` = ?",
704
- [Identificador]
705
- );
706
- let fechaBD = fechaUltimoCambio?.[0]?.[0]?.LastUpdate;
707
- const fechaUltimo = new Date(fechaBD);
708
- const fechaActual = new Date();
709
- const diferenciaMs = fechaActual - fechaUltimo;
710
- const diasPasados = diferenciaMs / (1000 * 60 * 60 * 24);
711
- if (!fechaBD || diasPasados >= 60) {
712
- await ConexionSigu.query(
713
- "UPDATE`SIGU_Personas` \
714
- SET`Clave` = '' \
715
- where`Identificador` = ? ;",
716
- [Identificador]
717
- );
718
- return { RequiereCambioContraseña: true };
719
-
720
- }
721
-
722
- if (ipExiste[0][0].Total === 0) {
723
- // GENERAR CODIGO 2FA
724
- let Codigo2FA = await ConexionSigu.query("SELECT UUID() AS `Dato`");
725
- Codigo2FA = Codigo2FA[0][0].Dato;
726
-
727
- // GUARDAR CODIGO 2FA
728
- await ConexionSigu.query(" \
729
- REPLACE INTO `SIGU`.`SIGU_CodigosDe2FAParaLosUsuarios` \
730
- VALUES (?, ?, NOW(4), ?)", [
731
- Identificador,
732
- Codigo2FA,
733
- LastUser
734
- ]);
735
-
736
- // OBTENER CORREO
737
- const CorreoElectronico = await ConexionSigu.query(
738
- "SELECT `CorreoElectronico` \
739
- FROM `SIGU`.`SIGU_CorreosPersona` \
740
- WHERE `Identificador` = ? \
741
- AND `Principal` = TRUE"
742
- , [Identificador]);
743
- // ENVIAR CORREO
744
- await envioDeCorreo(
745
- CorreoElectronico[0][0].CorreoElectronico,
746
- "Código de verificación 2FA",
747
- "<p>Hemos recibido su solicitud de acceso para 2FA.</p>" +
748
- "<p>Para continuar con el proceso, por favor utilice el siguiente código único de verificación:</p>" +
749
- "<p>" + Codigo2FA + "</p>" +
750
- "<p>Si usted no inició este proceso, puede ignorar este mensaje.</p>"
751
- );
752
- return { Requiere2FA: true };
753
-
754
- }
755
-
756
- // SI LA IP YA EXISTE CONTINUA
757
- await ConexionSigu.query("\
758
- INSERT INTO `SIGU`.`SIGU_DireccionesUsadasPorLosUsuarios` \
759
- (`DireccionUsadaPorElUsuario`, `Identificador`, `LastUpdate`, `LastUser`) \
760
- VALUES (?, ?, NOW(4), ?) \
761
- ON DUPLICATE KEY UPDATE `LastUpdate` = NOW(4), `LastUser` = ?;", [
762
- ipUsuario,
763
- Identificador,
764
- LastUser,
765
- LastUser
766
- ]);
767
- return { Token, Dominio: ((process.env.ENV || 'local') === 'production' ? '.sigu.utn.ac.cr' : '.svc.cluster.local') };
768
-
769
- } else {
770
- console.log("La clave brindada para el usuario", Solicitud.body.Identificacion, "no conincide");
771
- const Resultados2 = await ConexionSigu.query("SELECT COUNT(*) AS `Total` FROM `SIGU`.`SIGU_ClavesTemporalesDeLasPersonas` WHERE `Identificador` = ? AND `Clave` = ?", [Identificador, Solicitud.body.Clave]);
772
- if (Resultados2[0][0]['Total'] > 0) {
773
- console.log("La clave brindada para el usuario", Solicitud.body.Identificacion, "no conincide, pero coincide la clave temporal");
774
- await ConexionSigu.query("UPDATE `SIGU`.`SIGU_Personas` SET `Clave` = ?, `LastUpdate` = NOW(4), `LastUser` = ? WHERE `Identificacion` = ?"
775
- , [await bcrypt.hash(require('crypto').createHash('md5').update(Solicitud.body.Clave).digest("hex"), 10), LastUser, Solicitud.body.Identificacion]);
776
- await ConexionSigu.query("REPLACE INTO `SIGU`.`SIGU_FechaDelUltimoCambioDeClave` VALUES (?, NOW(), ?);", [Identificador, LastUser]);
777
- await ConexionSigu.query("DELETE FROM `SIGU`.`SIGU_ClavesTemporalesDeLasPersonas`WHERE `Identificador` = ?", [Identificador]);
778
- return await this.Autenticar(Solicitud);
779
-
780
- } else {
781
- await ConexionSigu.query("INSERT INTO `SIGU`.`SIGU_SesionesFallidas` VALUES (?, ?, NOW(4))"
782
- , [Identificador, Solicitud.headers.host.trim()]);
783
- }
784
- }
785
- } catch (error) {
786
- console.log(error);
787
- return;
788
- } finally {
789
- if (ConexionSigu) await ConexionSigu.end();
790
- }
791
- return;
792
- }
793
-
794
- async Verificar2FA(Solicitud) {
795
- const jwt = require('jsonwebtoken');
796
- const ConexionSigu = await crearObjetoConexionSIGU();
797
- const LastUser = await this.generarLastUser(Solicitud);
798
- try {
799
- const { Identificacion, Codigo } = Solicitud.body;
800
- const resultados = await ConexionSigu.query(
801
- "SELECT `Identificador` FROM `SIGU`.`SIGU_Personas` WHERE `Activo` = TRUE AND `Identificacion` = ?", [Identificacion]);
802
-
803
- if (!resultados[0].length) {
804
- return { error: "Usuario no encontrado" };
805
- }
806
- const Identificador = resultados[0][0]['Identificador'];
807
- // Validar código 2FA
808
- const codigoValido = await ConexionSigu.query(" \
809
- SELECT COUNT(*) AS Total \
810
- FROM `SIGU`.`SIGU_CodigosDe2FAParaLosUsuarios` \
811
- WHERE `Identificador` = ? \
812
- AND `CodigoDe2FAParaElUsuario` = ?", [Identificador, Codigo]);
813
-
814
- if (codigoValido[0][0].Total === 0) {
815
- // Eliminar código usado cuando falle
816
- await ConexionSigu.query(" \
817
- DELETE FROM `SIGU`.`SIGU_CodigosDe2FAParaLosUsuarios` \
818
- WHERE `Identificador` = ? ", [Identificador]);
819
- return { error: "Código inválido" };
820
- }
821
-
822
- // Eliminar código usado
823
- await ConexionSigu.query(" \
824
- DELETE FROM `SIGU`.`SIGU_CodigosDe2FAParaLosUsuarios` WHERE `Identificador` = ?", [Identificador]);
825
-
826
- // Obtener IP del usuario
827
- const ipUsuario = (Solicitud.headers['x-forwarded-for'] || '').split(',').shift() || Solicitud.socket?.remoteAddress || Solicitud.connection?.remoteAddress || '-';
828
-
829
- // Guardar IP autorizada
830
- await ConexionSigu.query(" \
831
- INSERT INTO `SIGU`.`SIGU_DireccionesUsadasPorLosUsuarios` (`DireccionUsadaPorElUsuario`, `Identificador`, `LastUpdate`, `LastUser`) \
832
- VALUES (?, ?, NOW(4), ?) \
833
- ON DUPLICATE KEY UPDATE `LastUpdate` = NOW(4), `LastUser` = ?;", [
834
- ipUsuario,
835
- Identificador,
836
- LastUser,
837
- LastUser
838
- ]);
839
-
840
- // Generar token
841
- const Token = await jwt.sign(
842
- { Identificador: Identificador, uid: Identificador },
843
- await this.palabraSecretaParaTokens(),
844
- { expiresIn: '2h' }
845
- );
846
-
847
- // Registrar sesión
848
- await ConexionSigu.query("INSERT INTO `SIGU`.`SIGU_Sesiones` VALUES (?, ?, ?, NOW(4), ?) ON DUPLICATE KEY UPDATE `Token` = ?, `LastUser` = ?"
849
- , [Identificador, Solicitud.headers.host.trim(), Token, LastUser, Token, LastUser]);
850
- return {
851
- Token,
852
- Dominio: ((process.env.ENV || 'local') === 'production' ? '.sigu.utn.ac.cr' : '-')
853
- };
854
- } catch (error) {
855
- console.log(error);
856
- return { error: "Error verificando 2FA" };
857
- } finally {
858
- if (ConexionSigu) await ConexionSigu.end();
859
- }
860
- }
861
-
862
- async ListadoDePaisesParaCrearCuenta() {
863
- const Resultado = await ejecutarConsultaSIGU("SELECT REPLACE(MID(`COLUMN_TYPE`, 6, CHAR_LENGTH(`COLUMN_TYPE`) - 6), \"'\", '') AS `Datos` FROM `information_schema`.`COLUMNS`\
864
- WHERE `TABLE_SCHEMA` = 'SIGU' AND `TABLE_NAME` = 'SIGU_Personas' AND\
865
- `COLUMN_NAME` = 'Pais'");
866
- return Resultado[0]['Datos'].split(',').sort();
867
- }
868
-
869
- async obtenerDetalleDelModulo() {
870
- const Modulos = await ejecutarConsultaSIGU("SELECT `a`.`Nombre`, `a`.`Padre`, `a`.`Descripcion`, `a`.`Detalle`,\
871
- `a`.`Tipo`, IF(`a`.`Icono` <> '', CONCAT('https://storage.sigu.utn.ac.cr/images/cards/', `a`.`Icono`), '') AS `Icono`, `a`.`Color`, `a`.`Correo`,\
872
- `a`.`Version`, `a`.`FechaDePublicacion`, `a`.`AcuerdoDeNivelDeServicio`, `a`.`DiccionarioDeDatos`, `a`.`Repositorios`,\
873
- `a`.`EnlaceDelVideo`,`a`.`EnlaceDelManual`\
874
- , `a`.`Estado`, REGEXP_SUBSTR(SUBSTRING_INDEX(`a`.`Repositorios`, '/', -1), '[^,]*front[^,]*') AS `Frontend`\
875
- FROM `SIGU`.`SIGU_ModulosV2` `a`\
876
- WHERE `a`.`Nombre` = ?", [this.NombreCanonicoDelModulo]);
877
- return Modulos.map((linea) => {
878
- linea.Enlace = this.generarEnlace(linea.Frontend);
879
- return linea;
880
- });
881
- }
882
-
883
- async registrarVistaDelManual(Token) {
884
- const { uid } = await this.obtenerDatosDelUsuario(Token);
885
- await ejecutarConsulta(
886
- "INSERT INTO `DatosMiscelaneos` (`DatoMiscelaneo`, `Datos`, `LastUser`) VALUES ('VistasDelManual', JSON_OBJECT('Total', 1), ?) ON DUPLICATE KEY UPDATE `Datos` = JSON_SET(`Datos`, '$.Total', CAST(JSON_VALUE(`Datos`, '$.Total') AS UNSIGNED) + 1), `LastUser` = ?",
887
- [uid, uid]
888
- );
889
- }
890
-
891
- async obtenerMensajesModulares() {
892
- return await ejecutarConsultaSIGU("SELECT `MensajeModularId`, `Titulo`, `Texto`, `FechaYHoraDeInicio`, `FechaYHoraDeFinalizacion` FROM `SIGU`.`SIGU_MensajesModulares` WHERE NOW(4) BETWEEN `FechaYHoraDeInicio` AND `FechaYHoraDeFinalizacion` AND `Modulo` = ?"
893
- , [this.NombreCanonicoDelModulo]);
894
- }
895
-
896
- async obtenerMensajesInstitucionales() {
897
- return await ejecutarConsultaSIGU("SELECT `MensajeInstitucionalId`, `Titulo`, `Texto`, `FechaYHoraDeInicio`, `FechaYHoraDeFinalizacion` FROM `SIGU`.`SIGU_MensajesInstitucionales` WHERE NOW(4) BETWEEN `FechaYHoraDeInicio` AND `FechaYHoraDeFinalizacion`");
898
- }
899
-
900
- async obtenerConsentimientoInformado(Modulo = undefined) {
901
- if (Modulo === undefined) {
902
- Modulo = this.NombreCanonicoDelModulo;
903
- }
904
- let Datos = await ejecutarConsultaSIGU("SELECT `ConsentimientoInformadoId`, `Titulo`, `Texto`, `TextoDeAceptacion` FROM `SIGU`.`SIGU_ConsentimientosInformadosV2`\
905
- WHERE `Estado` = 'Activo' AND `Modulo` = ? AND `Titulo` <> 'Versión del módulo'", [Modulo]);
906
- if (Datos.length === 0) {
907
- Datos = await ejecutarConsultaSIGU("SELECT `ConsentimientoInformadoId`, `Titulo`, `Texto`, `TextoDeAceptacion` FROM `SIGU`.`SIGU_ConsentimientosInformadosV2`\
908
- WHERE `Estado` = 'Activo' AND `Modulo` = ? AND `Titulo` <> 'Versión del módulo'", [this.NombreCanonicoDelModulo]);
156
+ if (Tipo === 'stream') {
157
+ Opciones.responseType = 'stream';
909
158
  }
910
- return Datos[0];
911
- }
912
-
913
- async creacionDeConsetimientoInformado(Titulo, Texto, TextoDeAceptacion) {
914
- return await ejecutarConsultaSIGU("UPDATE `SIGU`.`SIGU_ConsentimientosInformadosV2` SET `Estado` = 'Inactivo' WHERE\
915
- `Modulo` = ? AND `Titulo` <> 'Versión del módulo'; \
916
- SELECT MAX(`ConsentimientoInformadoId`) + 1 INTO @`NuevoId` FROM `SIGU`.`SIGU_ConsentimientosInformadosV2`; \
917
- INSERT INTO `SIGU`.`SIGU_ConsentimientosInformadosV2` VALUES\
918
- (@`NuevoId`, ?, ?, ?, 'Activo', ?, NOW(), USER())\
919
- ON DUPLICATE KEY UPDATE `Estado` = 'Activo';"
920
- , [this.NombreCanonicoDelModulo, Titulo, Texto, TextoDeAceptacion, this.NombreCanonicoDelModulo]);
921
- }
922
-
923
- obtenerCorreoParaReportes() {
924
- return this.CorreoParaReportes;
925
- }
926
-
927
- async iniciarSesion() {
928
- return this.EnlaceDeAcceso;
929
- }
930
-
931
- async obtenerModulos(Token, Padre, ModulosFavoritos) {
932
- let Resultado = undefined;
933
- try {
934
- Resultado = await this.obtenerDatosDelUsuario(Token);
935
- if (!Resultado) {
936
- throw new ManejadorDeErrores(ManejadorDeErrores.mensajeDeErrorVerificacionDeToken(), ManejadorDeErrores.obtenerNumeroDeLinea());
937
- }
938
- } catch (error) {
939
- console.log(error);
940
- return;
159
+ if (Cuerpo) {
160
+ Opciones.body = JSON.stringify(Cuerpo);
941
161
  }
942
- const Permisos = await ejecutarConsultaSIGU("SELECT `PermisoId` FROM `SIGU`.`SIGU_PermisosPersonasV2` WHERE `Identificador` = ?"
943
- , [Resultado.Identificador]);
944
- const Modulos = await ejecutarConsultaSIGU("SELECT `a`.`Nombre`, `a`.`Padre`, `a`.`Descripcion`, `a`.`Detalle`,\
945
- `a`.`Tipo`, IF(`a`.`Icono` <> '', CONCAT('https://storage.sigu.utn.ac.cr/images/cards/', `a`.`Icono`), '') AS `Icono`, `a`.`Color`, `a`.`Correo`,\
946
- `a`.`Version`, `a`.`FechaDePublicacion`, `a`.`AcuerdoDeNivelDeServicio`, `a`.`DiccionarioDeDatos`, `a`.`Repositorios`,\
947
- `a`.`EnlaceDelVideo`,`a`.`EnlaceDelManual`\
948
- , `a`.`Estado`, REGEXP_SUBSTR(SUBSTRING_INDEX(`a`.`Repositorios`, '/', -1), '[^,]*front[^,]*') AS `Frontend`\
949
- , `c`.`Etiqueta`, `c`.`ColorDeLaEtiqueta`\
950
- , (SELECT COUNT(*) FROM `SIGU`.`SIGU_ModulosV2` `h`\
951
- JOIN `SIGU`.`SIGU_PermisosV2` `hp` ON (`h`.`Nombre` = `hp`.`Modulo`)\
952
- WHERE `h`.`Estado` = 'Activo' AND `h`.`Padre` = `a`.`Nombre` AND `hp`.`PermisoId` IN (?)) AS `CantidadDeHijos`\
953
- FROM `SIGU`.`SIGU_ModulosV2` `a`\
954
- JOIN `SIGU`.`SIGU_PermisosV2` `b` ON (`a`.`Nombre` = `b`.`Modulo`)\
955
- LEFT JOIN `SIGU`.`SIGU_ModulosV2InformacionExtra` `c` ON (`a`.`Nombre` = `c`.`Modulo`)\
956
- WHERE `a`.`Estado` = 'Activo' AND `a`.`Padre` = ? AND `b`.`PermisoId` IN (?)\
957
- ORDER BY FIELD(a.Nombre, " + ModulosFavoritos + ") DESC, a.Nombre", [Permisos.map(p => p.PermisoId), Padre, Permisos.map(p => p.PermisoId)]);
958
- return Modulos.map((linea) => {
959
- linea.Enlace = this.generarEnlace(linea.Frontend);
960
- return linea;
961
- });
962
- }
963
-
964
- async crearNotificacion(IdentificadorDelUsuario, IdentificadorDelDestinatario, Mensaje) {
965
- return await ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_NotificacionesV2` VALUES (?, ?, 'Sin leer', NOW(4), NOW(4), ?)"
966
- , [IdentificadorDelDestinatario, Mensaje, IdentificadorDelUsuario]);
967
- }
968
-
969
- async actualizarNotificacion(Token, FechaYHoraDeCreacion) {
970
- let Resultado = undefined;
162
+ const ListaDeDominiosPermitidos = [
163
+ "sigu.utn.ac.cr",
164
+ "localhost",
165
+ "svc.cluster.local"
166
+ ];
971
167
  try {
972
- Resultado = await this.obtenerDatosDelUsuario(Token);
973
- if (!Resultado) {
974
- throw new ManejadorDeErrores(ManejadorDeErrores.mensajeDeErrorVerificacionDeToken(), ManejadorDeErrores.obtenerNumeroDeLinea());
168
+ if (ListaDeDominiosPermitidos.some(dominio => URL.includes(dominio))) {
169
+ Respuesta = await fetch(URL, Opciones);
975
170
  }
976
- } catch (error) {
977
- console.log(error);
978
- return;
979
- }
980
- return await ejecutarConsultaSIGU("UPDATE `SIGU`.`SIGU_NotificacionesV2` SET `Estado` = 'Leída' WHERE `Identificador` = ? AND `FechaYHoraDeCreacion` = ?"
981
- , [Resultado.Identificador, FechaYHoraDeCreacion]);
982
- }
983
-
984
- async obtenerNotificaciones(Token) {
985
- let Resultado = undefined;
986
- try {
987
- Resultado = await this.obtenerDatosDelUsuario(Token);
988
- if (!Resultado) {
989
- throw new ManejadorDeErrores(ManejadorDeErrores.mensajeDeErrorVerificacionDeToken(), ManejadorDeErrores.obtenerNumeroDeLinea());
171
+ if (!Respuesta.ok) {
172
+ throw new ManejadorDeErrores(ManejadorDeErrores.mensajeDeErrorAccesoAAPI(Respuesta.error), ManejadorDeErrores.obtenerNumeroDeLinea());
990
173
  }
991
- } catch (error) {
992
- console.log(error);
993
- return;
994
- }
995
- return await ejecutarConsultaSIGU("SELECT `Notificacion` AS `valor`, CONCAT(`FechaYHoraDeCreacion`) AS `llave`, false AS `tachado` FROM `SIGU`.`SIGU_NotificacionesV2` WHERE `Identificador` = ? AND `Estado` = 'Sin leer' ORDER BY `FechaYHoraDeCreacion` DESC LIMIT 10", [Resultado.Identificador]);
996
- }
997
-
998
- async reporteDeIncidencia(Solicitud, Datos) {
999
- const DatosDelArchivo = await this.cargarArchivo(Solicitud, Datos);
1000
- await envioDeCorreo('msavatar@utn.ac.cr', "Reporte de incidencia",
1001
- "<p><b>Sistema: </b>" + this.NombreCanonicoDelModulo + "</p><br />"
1002
- + "<p><b>Asunto: </b>Reporte de incidencia</p><br />"
1003
- + "<p><b>Detalle de la incidencia: </b>" + Datos.detalle + "</p><br />"
1004
- + "<p><b>Resultado esperado: </b>" + Datos.resultado + "</p><br />"
1005
- + "<p><b>Información de contacto: </b>" + Datos.concato + "</p><br />"
1006
- + "<p><b>Información del usuario: </b>" + await this.obtenerDatosDelUsuario(Solicitud.headers.authorization) + "</p><br />"
1007
- , [DatosDelArchivo.rutaDeArchivo]);
1008
- return;
1009
- }
1010
-
1011
- async reporteDeSugerencia(Solicitud, Datos) {
1012
- // const DatosDelArchivo = await this.cargarArchivo(Solicitud, Datos);
1013
- await envioDeCorreo('msavatar@utn.ac.cr', "Reporte de sugerencia",
1014
- "<p><b>Sistema: </b>" + this.NombreCanonicoDelModulo + "</p><br />"
1015
- + "<p><b>Asunto: </b>Reporte de sugerencia</p><br />"
1016
- + "<p><b>Detalle de la sugerencia: </b>" + Datos.detalle + "</p><br />"
1017
- + "<p><b>Información del usuario: </b>" + await this.obtenerDatosDelUsuario(Solicitud.headers.authorization) + "</p><br />");
1018
- return;
1019
- }
1020
-
1021
- async cerrarSesion(Token) {
1022
- let Resultado = undefined;
1023
- try {
1024
- Resultado = await this.obtenerDatosDelUsuario(Token);
1025
- if (!Resultado) {
1026
- throw new ManejadorDeErrores(ManejadorDeErrores.mensajeDeErrorVerificacionDeToken(), ManejadorDeErrores.obtenerNumeroDeLinea());
174
+ if (Tipo === 'stream') {
175
+ return await Respuesta;
1027
176
  }
177
+ return await Respuesta.json();
1028
178
  } catch (error) {
1029
- console.log(error);
1030
- return;
179
+ console.error(error);
180
+ console.error(Respuesta);
181
+ throw new ManejadorDeErrores(error.message, ManejadorDeErrores.obtenerNumeroDeLinea());
1031
182
  }
1032
- await ejecutarConsultaSIGU("DELETE FROM `SIGU`.`SIGU_Sesiones` WHERE `Token` = ?", [Token.split(" ")[1]]);
1033
- return this.EnlaceDeAcceso;
1034
183
  }
1035
184
 
1036
- async permisosDelModuloV2(NombreCanonicoDelModulo) {
1037
- return await ejecutarConsultaSIGU("\
1038
- WITH RECURSIVE `Jerarquia` AS (\
1039
- SELECT\
1040
- `m`.`Padre`,\
1041
- `m`.`Nombre` AS `Modulo`,\
1042
- `p`.`PermisoId`,\
1043
- `p`.`Nombre` AS `Permiso`\
1044
- FROM `SIGU`.`SIGU_ModulosV2` `m`\
1045
- JOIN `SIGU`.`SIGU_PermisosV2` `p` ON `p`.`Modulo` = `m`.`Nombre`\
1046
- WHERE `m`.`Nombre` = ?\
1047
- UNION ALL\
1048
- SELECT \
1049
- `m`.`Padre`,\
1050
- `m`.`Nombre` AS `Modulo`,\
1051
- `p`.`PermisoId`,\
1052
- `p`.`Nombre` AS `Permiso`\
1053
- FROM `SIGU`.`SIGU_ModulosV2` `m`\
1054
- JOIN `SIGU`.`SIGU_PermisosV2` `p` ON `p`.`Modulo` = `m`.`Nombre`\
1055
- JOIN `Jerarquia` `j` ON `j`.`Padre` = `m`.`Nombre`\
1056
- )\
1057
- SELECT DISTINCT * FROM `Jerarquia`"
1058
- , [NombreCanonicoDelModulo]
1059
- );
1060
- }
1061
-
1062
- async modulosV2() {
1063
- return await ejecutarConsultaSIGU("SELECT `Nombre`, `Padre`, `Descripcion`, `Detalle`, `Tipo`, `Icono`, `Color`, `Correo`, `Version`, `FechaDePublicacion`, `AcuerdoDeNivelDeServicio`, `DiccionarioDeDatos`, `Repositorios`, `EnlaceDelVideo`, `EnlaceDelManual`, `Estado` FROM `SIGU`.`SIGU_ModulosV2`");
1064
- }
1065
-
1066
- async permisoIdV2() {
1067
- const Datos = await ejecutarConsultaSIGU("SELECT `PermisoId` FROM `SIGU`.`SIGU_PermisosV2` WHERE `Nombre` = ? AND `Modulo` = ?", [this.NombreDelPermisoV2, this.NombreCanonicoDelModulo]);
1068
- return Datos[0]['PermisoId'];
1069
- }
1070
-
1071
- async permisoIdDelPadreV2() {
1072
- const Datos = await ejecutarConsultaSIGU("SELECT `PermisoId` FROM `SIGU`.`SIGU_PermisosV2` WHERE `Modulo` = ?"
1073
- , [this.MenuPadre]);
1074
- return Datos[0]['PermisoId'];
185
+ // Re-lee todas las propiedades del módulo desde InformacionDelModulo.
186
+ // Se llama después de InformacionDelModulo.initialize() para que los valores
187
+ // de la BD queden reflejados en la instancia.
188
+ _sincronizarConInformacionDelModulo() {
189
+ const Info = require('../InformacionDelModulo.js');
190
+ this.NombreDelModulo = Info.getNombreDelModulo();
191
+ this.DescripcionDelModulo = Info.getDescripcionDelModulo();
192
+ this.DetalleDelModulo = Info.getDetalleDelModulo();
193
+ this.NombreCanonicoDelModulo = Info.getNombreCanonicoDelModulo();
194
+ this.TipoDeCard = Info.getTipoDeCard();
195
+ this.NombreDelRol = this.NombreCanonicoDelModulo + ' - ' + Info.getNombreDelRol();
196
+ this.NombreDelRepositorioDeLaBaseDeDatos = Info.getNombreDelRepositorioDeLaBaseDeDatos();
197
+ this.NombreDelRepositorioDelBackend = Info.getNombreDelRepositorioDelBackend();
198
+ this.NombreDelRepositorioDelFrontend = Info.getNombreDelRepositorioDelFrontend();
199
+ this.UrlDelGrupo = Info.getUrlDelGrupo();
200
+ this.Repositorios = this.UrlDelGrupo + '/' + this.NombreDelRepositorioDeLaBaseDeDatos
201
+ + ',' + this.UrlDelGrupo + '/' + this.NombreDelRepositorioDelBackend
202
+ + ',' + this.UrlDelGrupo + '/' + this.NombreDelRepositorioDelFrontend;
203
+ this.NombreDelPermiso = this.NombreCanonicoDelModulo + ' - ' + Info.getNombreDelPermiso();
204
+ this.NombreDelPermisoV2 = Info.getNombreDelPermiso();
205
+ this.DescripcionDelPermiso = Info.getDescripcionDelPermiso();
206
+ this.MenuPadre = Info.getMenuPadre();
207
+ this.BackEndsQueConsumeEsteModulo = Info.getBackEndsQueConsumeEsteModulo();
208
+ this.PerfilGeneral = Info.getPerfilGeneral();
209
+ this.UsuariosConAccesoInicial = Info.getUsuariosConAccesoInicial();
210
+ this.IconoDelModulo = this.NombreCanonicoDelModulo + '.svg';
211
+ this.ColorDelModulo = Info.getColorDelModulo();
212
+ this.CorreoParaReportes = Info.getCorreoParaReportes();
213
+ this.Version = Info.getVersion();
1075
214
  }
1076
215
 
1077
- async registroDelModuloEnSIGUV2() {
1078
- const Version = this.Version + "$$" + this.versionDelNucleo().split(' ')[0];
1079
- await ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_ModulosV2` VALUES\
1080
- (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(4), ?, 'DiccionarioDeDatos'\
1081
- , ?, '-', '-', 'Activo', NOW(4), USER()) ON DUPLICATE KEY UPDATE `Version` = ?, `Repositorios` = ?"
1082
- , [this.NombreCanonicoDelModulo, this.MenuPadre, this.DescripcionDelModulo, this.DetalleDelModulo
1083
- , this.TipoDeCard, this.IconoDelModulo, this.ColorDelModulo, this.CorreoParaReportes, Version, this.versionDelNucleo().split(' ')[0], this.Repositorios
1084
- , Version, this.Repositorios]);
1085
- await ejecutarConsultaSIGU("SELECT IFNULL(MAX(`PermisoId`), 0) + 1 INTO @`SiguientePermisoId` FROM `SIGU`.`SIGU_PermisosV2`;\
1086
- INSERT INTO `SIGU`.`SIGU_PermisosV2` VALUES\
1087
- (@`SiguientePermisoId`, ?, ?, ?, NOW(4), USER()) ON DUPLICATE KEY UPDATE `LastUser` = USER(), `Nombre` = ?, `Descripcion` = ?;"
1088
- , [this.NombreDelPermisoV2, this.NombreCanonicoDelModulo, this.DescripcionDelPermiso, this.NombreDelPermisoV2, this.DescripcionDelPermiso]);
1089
-
1090
- // Creación de Flujo de aprobaciones predeterminado del módulo
1091
- await ejecutarConsultaSIGU("SELECT COALESCE(MAX(`FlujoDeAprobacionId`), 0) + 1 INTO @`Consecutivo` FROM `SIGU`.`SIGU_FlujosDeAprobacion`;\
1092
- INSERT INTO `SIGU`.`SIGU_FlujosDeAprobacion` VALUES (@`Consecutivo`, ?, CONCAT('Flujo de aprobación predeterminado para:', ' ', ?), TRUE, NOW(4), USER()) ON DUPLICATE KEY UPDATE `LastUpdate` = NOW(4);"
1093
- , [this.NombreCanonicoDelModulo, this.NombreCanonicoDelModulo]);
1094
- await ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_FlujosDeAprobacionPasos` VALUES (\
1095
- (SELECT `FlujoDeAprobacionId` FROM `SIGU`.`SIGU_FlujosDeAprobacion` WHERE `NombreCanonico` = ?)\
1096
- , 0, 'Sin aprobaciones realizadas', (SELECT `Identificador` FROM `SIGU`.`SIGU_Personas` WHERE `Identificacion` = '111050570'), 0, NOW(4), USER()) ON DUPLICATE KEY UPDATE `LastUpdate` = NOW(4)"
1097
- , [this.NombreCanonicoDelModulo]);
1098
-
1099
- // Asignación del permiso a dvillalobos
1100
- await ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_PermisosPersonasV2` VALUES (?,\
1101
- (SELECT `Identificador` FROM `SIGU`.`SIGU_Personas` WHERE `Identificacion` = '111050570'), NOW(4), USER()) ON DUPLICATE KEY UPDATE `LastUser` = USER()"
1102
- , [await this.permisoIdV2()]);
1103
-
1104
- // Asginación inicial de permisos
1105
- if (this.UsuariosConAccesoInicial.length > 0) {
1106
- const permisoId = await this.permisoIdV2();
1107
- const permisoIdDelPadre = await this.permisoIdDelPadreV2();
1108
- this.UsuariosConAccesoInicial.forEach(async (dato) => {
1109
- await ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_PermisosPersonasV2` VALUES (?,\
1110
- (SELECT `Identificador` FROM `SIGU`.`SIGU_Personas` WHERE `Identificacion` = ?), NOW(4), USER())\
1111
- ON DUPLICATE KEY UPDATE `LastUpdate` = NOW(4)"
1112
- , [permisoIdDelPadre, dato]);
1113
- await ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_PermisosPersonasV2` VALUES (?,\
1114
- (SELECT `Identificador` FROM `SIGU`.`SIGU_Personas` WHERE `Identificacion` = ?), NOW(4), USER())\
1115
- ON DUPLICATE KEY UPDATE `LastUpdate` = NOW(4)"
1116
- , [permisoId, dato]);
1117
- });
1118
- }
1119
-
1120
- // Validación de que sólo el front especificado pueda consumir este backend
1121
- const uuidTemporal = await ejecutarConsultaSIGU("SELECT UUID() AS `UUID`");
1122
- await ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_Repositorios` VALUES (?, ?) ON DUPLICATE KEY UPDATE `Identificador` = ?"
1123
- , [this.NombreDelRepositorioDelFrontend, uuidTemporal[0]['UUID'], uuidTemporal[0]['UUID']]);
1124
- await ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_RepositoriosAccesos` VALUES (?, ?)\
1125
- ON DUPLICATE KEY UPDATE `RepositorioDestino` = ?,`RepositorioOrigen` = ?"
1126
- , [this.NombreDelRepositorioDelBackend, this.NombreDelRepositorioDelFrontend, this.NombreDelRepositorioDelBackend, this.NombreDelRepositorioDelFrontend]);
1127
-
1128
- // Impresión de la información de registro
1129
- console.log(new Date());
1130
- console.log(`Módulo registrado correctamente en SIGU. Módulo: ${this.NombreCanonicoDelModulo}`);
1131
- console.log(`Identificador del flujo de aprobación: ${await this.idDelFlujoDeAprobacion()}`);
1132
- console.log(`Enlace del módulo: ${this.Enlace}`);
1133
- console.log(`Permisos: ${JSON.stringify(await this.permisosDelModuloV2(this.NombreCanonicoDelModulo))}`);
1134
- this.creacionDeldirectorioParaElAlmacenamientoDeArchivos();
1135
- console.log(`Versión del núcleo: ${this.versionDelNucleo()}`);
1136
-
1137
- // // Creación de variables de entorno
1138
- // process.env.SERVIDORSMTP = await this.servidorSMTP();
1139
- // process.env.USUARIOSMTP = await this.usuarioSMTP();
1140
- // process.env.PUERTOSMTP = await this.puertoSMTP();
1141
- // process.env.CLAVESMTP = await this.claveSMTP();
1142
- // process.env.DESTINATARIODEINFORMESDEERROR = await this.destinatarioDeInformesDeError();
1143
- // process.env.NOMBRECANONICODELMODULO = this.NombreCanonicoDelModulo;
216
+ obtenerNombreLaBaseDeDatos() {
217
+ return this.NombreDelRepositorioDeLaBaseDeDatos.slice(0, -3);
1144
218
  }
1145
219
 
1146
- generarUUID() {
1147
- return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11)
1148
- .replace(/[018]/g, c =>
1149
- (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
1150
- );
220
+ obtenerNombreCanonicoDelModulo() {
221
+ return this.NombreCanonicoDelModulo;
1151
222
  }
1152
223
 
1153
- async obtenerPersonasFuncionarias() {
1154
- return await ejecutarConsultaSIGU("SELECT `Identificador`, `Identificacion`, `Nombre`, `PrimerApellido`,\
1155
- `SegundoApellido` FROM `SIGU`.`SIGU_Personas` WHERE `Identificador` IN\
1156
- (SELECT `Identificador` FROM `SIGU`.`EstructuraOrganizacional_Instancias`) ORDER BY `Nombre`, `PrimerApellido`,\
1157
- `SegundoApellido`");
224
+ obtenerVersionDelModulo() {
225
+ return this.Version;
1158
226
  }
1159
227
 
1160
- // async rolPermisoIdDelMenuPadre() {
1161
- // const rolPermisoIdDelMenuPadre = await ejecutarConsultaSIGU("SELECT `RolPermisoId` FROM `SIGU`.`SIGU_RolesPermisos` WHERE\
1162
- // `PermisoId` = (SELECT `PermisoId` FROM `SIGU`.`SIGU_Menu` WHERE `Nombre` = ?)", [this.MenuPadre]);
1163
- // return rolPermisoIdDelMenuPadre[0]['RolPermisoId'];
1164
- // }
1165
-
1166
- async getUUID() {
1167
- const Identificador = await ejecutarConsultaSIGU("SELECT `Identificador` FROM `SIGU`.`SIGU_Repositorios` WHERE `Repositorio` = ?", [this.NombreDelRepositorioDelBackend]);
1168
- return Identificador[0]['Identificador'];
1169
- }
228
+ }
1170
229
 
1171
- async perfilGeneralId() {
1172
- const PerfilGeneralId = await ejecutarConsultaSIGU("SELECT `PerfilGeneralId` FROM `SIGU`.`SIGU_PerfilesGenerales` WHERE `Perfil` = ?", [this.PerfilGeneral]);
1173
- return PerfilGeneralId[0]['PerfilGeneralId'];
1174
- }
1175
-
1176
- // async rolIdDelModulo() {
1177
- // const RolId = await ejecutarConsultaSIGU("SELECT `RolId` FROM `SIGU`.`SIGU_Roles` WHERE `Descripcion` = ?", [this.NombreDelRol]);
1178
- // return RolId[0]['RolId'];
1179
- // }
1180
-
1181
- // async permisoIdDelModulo() {
1182
- // const PermisoId = await ejecutarConsultaSIGU("SELECT `PermisoId` FROM `SIGU`.`SIGU_Permisos` WHERE `Nombre` = ?", [this.NombreDelPermiso]);
1183
- // return PermisoId[0]['PermisoId'];
1184
- // }
1185
-
1186
- async rolPermisoIdDelModulo() {
1187
- this.RolId = await this.rolIdDelModulo();
1188
- this.PermisoId = await this.permisoIdDelModulo();
1189
- const RolPermisoId = await ejecutarConsultaSIGU("SELECT `RolPermisoId` FROM `SIGU`.`SIGU_RolesPermisos` WHERE `RolId` = ? AND `PermisoId` = ?"
1190
- , [this.RolId, this.PermisoId]);
1191
- return RolPermisoId[0]['RolPermisoId'];
1192
- }
1193
-
1194
- // async idDelMenuPadre() {
1195
- // const IdDelMenuPadre = await ejecutarConsultaSIGU("SELECT `MenuId` FROM `SIGU`.`SIGU_Menu` WHERE `Nombre` = ?", [this.MenuPadre]);
1196
- // return IdDelMenuPadre[0]['MenuId'];
1197
- // }
1198
-
1199
- // async idDelMenuDelModulo() {
1200
- // const IdDelMenuDelModulo = await ejecutarConsultaSIGU("SELECT `MenuId` FROM `SIGU`.`SIGU_Menu` WHERE `Nombre` = ?", [this.NombreCanonicoDelModulo]);
1201
- // return IdDelMenuDelModulo[0]['MenuId'];
1202
- // }
1203
-
1204
- generarEnlace(Modulo) {
1205
- return ((process.env.ENV || 'local') === 'production' ? 'https' : 'http')
1206
- + '://' + Modulo
1207
- + ((process.env.ENV || 'local') === 'production' ? '' : '-' + (process.env.ENV || 'local'))
1208
- + ((process.env.ENV || 'local') === 'production' ? '.sigu.utn.ac.cr' : '-');
1209
- }
1210
-
1211
- async registroDelModuloEnSIGU() {
1212
-
1213
- // Creación del enlace
1214
- this.Enlace = this.generarEnlace(this.NombreDelRepositorioDelFrontend);
1215
-
1216
- // Creación del enlace a portal
1217
- this.EnlaceDePortal = this.generarEnlace('portalv2-frontend');
1218
-
1219
- // Creación del enlace a perfil
1220
- this.EnlaceDePerfil = this.generarEnlace('perfilv2-frontend');
1221
-
1222
- // Creación del enlace a acceso
1223
- this.EnlaceDeAcceso = this.generarEnlace('accesov2-frontend');
1224
-
1225
- // // Creación del Rol
1226
- // const RolId = await ejecutarConsultaSIGU("SELECT (MAX(`RolId`) + 1) AS `RolId` FROM `SIGU`.`SIGU_Roles` WHERE `RolId` < 1000");
1227
- // await ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_Roles` VALUES (?, ?, NOW(4), USER()) ON DUPLICATE KEY UPDATE `LastUpdate` = NOW(4)", [RolId[0]['RolId'], this.NombreDelRol]);
1228
- // this.RolId = await this.rolIdDelModulo();
1229
-
1230
- // // Creación del Módulo
1231
- // await ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_Modulos` VALUES (?, ?, ?, ?, ?, 1, ?, ?\
1232
- // , (SELECT `Identificador` FROM `SIGU`.`SIGU_Personas` WHERE `Identificacion` = '111050570')\
1233
- // , (SELECT `Identificador` FROM `SIGU`.`SIGU_Personas` WHERE `Identificacion` = '111050570')\
1234
- // , (SELECT `Identificador` FROM `SIGU`.`SIGU_Personas` WHERE `Identificacion` = '111050570')\
1235
- // , ?, '1.0.0', NOW(4), 'ANS', '/', ?, '1', NOW(4), USER()) ON DUPLICATE KEY UPDATE `LastUpdate` = NOW(4)"
1236
- // , [this.NombreDelModulo, this.DescripcionDelModulo, this.NombreCanonicoDelModulo, this.TipoDeCard, this.IconoDelModulo
1237
- // , this.ColorDelModulo, this.RolId, this.CorreoParaReportes, this.Repositorios]);
1238
-
1239
- // // Creación del Permiso
1240
- // await ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_Permisos` VALUES (NULL, ?, ?, NOW(4), USER()) ON DUPLICATE KEY UPDATE `LastUpdate` = NOW(4)"
1241
- // , [this.NombreDelPermiso, this.DescripcionDelPermiso]);
1242
- // this.PermisoId = await this.permisoIdDelModulo();
1243
-
1244
- // // Creación del Rol-Permiso
1245
- // await ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_RolesPermisos` VALUES (NULL, ?, ?, NOW(4), USER()) ON DUPLICATE KEY UPDATE `LastUpdate` = NOW(4)"
1246
- // , [this.RolId, this.PermisoId]);
1247
- // this.RolPermisoId = await this.rolPermisoIdDelModulo();
1248
-
1249
- // // Asignación del permiso a dvillalobos
1250
- // const perfilGeneralId = await this.perfilGeneralId();
1251
- // await ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_RolesPersonas` VALUES (?, ?,\
1252
- // (SELECT `Identificador` FROM `SIGU`.`SIGU_Personas` WHERE `Identificacion` = '111050570'), NOW(4), USER())\
1253
- // ON DUPLICATE KEY UPDATE `LastUpdate` = NOW(4)"
1254
- // , [this.RolPermisoId, perfilGeneralId]);
1255
-
1256
- // // Creación de los menús
1257
- // this.IdDelMenuPadre = await this.idDelMenuPadre();
1258
- // await ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_Menu` VALUES (NULL, ?, ?, ?, 'Módulo', 'opciones', ?\
1259
- // , ?, ?, 0, 1, NOW(4), USER()) ON DUPLICATE KEY UPDATE `LastUpdate` = NOW(4)"
1260
- // , [this.PermisoId, this.NombreCanonicoDelModulo, this.DescripcionDelModulo, this.NombreCanonicoDelModulo, this.Enlace, this.IdDelMenuPadre]);
1261
- // this.IdDelMenuDelModulo = await this.idDelMenuDelModulo();
1262
-
1263
- // let IdDelMenuAreas = await ejecutarConsultaSIGU("SELECT `MenuId` FROM `SIGU`.`SIGU_Menu` WHERE `Nombre` = 'Menú principal de áreas'\
1264
- // AND `Padre` = ?", [this.IdDelMenuDelModulo]);
1265
- // if (IdDelMenuAreas.length === 0) {
1266
- // IdDelMenuAreas = await ejecutarConsultaSIGU("SELECT MAX(`MenuId`) + 1 AS `MenuId` FROM `SIGU`.`SIGU_Menu`");
1267
- // await ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_Menu` VALUES (?, ?, 'Menú principal de áreas', 'Regreso al menú principal de áreas', 'Opción Menú', 'inicio'\
1268
- // , NULL, '/modulos', ?, 0, 1, NOW(4), USER())"
1269
- // , [IdDelMenuAreas[0]['MenuId'], this.PermisoId, this.IdDelMenuDelModulo]);
1270
- // }
1271
-
1272
- // let IdDelMenuRegreso1 = await ejecutarConsultaSIGU("SELECT `MenuId` FROM `SIGU`.`SIGU_Menu` WHERE `Nombre` = CONCAT('Regreso a ', ?)\
1273
- // AND `Padre` = ?", [this.MenuPadre, this.IdDelMenuDelModulo]);
1274
- // if (IdDelMenuRegreso1.length === 0) {
1275
- // IdDelMenuRegreso1 = await ejecutarConsultaSIGU("SELECT MAX(`MenuId`) + 1 AS `MenuId` FROM `SIGU`.`SIGU_Menu`");
1276
- // await ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_Menu` VALUES (?, ?, CONCAT('Regreso a ', ?), CONCAT('Regreso a ', ?), 'Opción Menú', 'opciones'\
1277
- // , NULL, CONCAT('/modulos/', ?), ?, 0, 1, NOW(4), USER())"
1278
- // , [IdDelMenuRegreso1[0]['MenuId'], this.PermisoId, this.MenuPadre, this.MenuPadre, this.IdDelMenuPadre, this.IdDelMenuDelModulo]);
1279
- // }
1280
-
1281
- // let IdDelMenuRegreso2 = await ejecutarConsultaSIGU("SELECT `MenuId` FROM `SIGU`.`SIGU_Menu` WHERE `Nombre` = CONCAT('Regreso a ', ?)\
1282
- // AND `Padre` = ?", [this.NombreCanonicoDelModulo, this.IdDelMenuDelModulo]);
1283
- // if (IdDelMenuRegreso2.length === 0) {
1284
- // IdDelMenuRegreso2 = await ejecutarConsultaSIGU("SELECT MAX(`MenuId`) + 1 AS `MenuId` FROM `SIGU`.`SIGU_Menu`");
1285
- // await ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_Menu` VALUES (?, ?, CONCAT('Regreso a ', ?), CONCAT('Regreso a ', ?), 'Opción Menú', 'menus'\
1286
- // , NULL, CONCAT('/enlace/', ?, '/', ?), ?, 0, 1, NOW(4), USER())"
1287
- // , [IdDelMenuRegreso2[0]['MenuId'], this.PermisoId, this.NombreCanonicoDelModulo, this.NombreCanonicoDelModulo
1288
- // , this.IdDelMenuDelModulo, Buffer.from(this.Enlace.split('//')[1]).toString('base64'), this.IdDelMenuDelModulo]);
1289
- // }
1290
-
1291
- // Creación del UUID del módulo
1292
- const uuidTemporal = await ejecutarConsultaSIGU("SELECT UUID() AS `UUID`");
1293
- this.UUID = uuidTemporal[0]['UUID'];
1294
- await ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_Repositorios` VALUES (?, ?) ON DUPLICATE KEY UPDATE `Identificador` = ?"
1295
- , [this.NombreDelRepositorioDelBackend, this.UUID, this.UUID]);
1296
- process.env.UUID = this.UUID;
1297
- if (this.BackEndsQueConsumeEsteModulo.length > 0) {
1298
- this.BackEndsQueConsumeEsteModulo.forEach(async (dato) => {
1299
- await ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_RepositoriosAccesos` VALUES (?, ?)\
1300
- ON DUPLICATE KEY UPDATE `RepositorioDestino` = ?,`RepositorioOrigen` = ?"
1301
- , [dato, this.NombreDelRepositorioDelBackend, dato, this.NombreDelRepositorioDelBackend]);
1302
- });
1303
- }
1304
-
1305
- // // Asginación inicial de permisos
1306
- // if (this.UsuariosConAccesoInicial.length > 0) {
1307
- // const rolPermisoIdDelPadre = await this.rolPermisoIdDelMenuPadre();
1308
- // this.UsuariosConAccesoInicial.forEach(async (dato) => {
1309
- // await ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_RolesPersonas` VALUES (?, ?,\
1310
- // (SELECT `Identificador` FROM `SIGU`.`SIGU_Personas` WHERE `Identificacion` = ?), NOW(4), USER())\
1311
- // ON DUPLICATE KEY UPDATE `LastUpdate` = NOW(4)"
1312
- // , [this.RolPermisoId, perfilGeneralId, dato]);
1313
- // await ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_RolesPersonas` VALUES (?, ?,\
1314
- // (SELECT `Identificador` FROM `SIGU`.`SIGU_Personas` WHERE `Identificacion` = ?), NOW(4), USER())\
1315
- // ON DUPLICATE KEY UPDATE `LastUpdate` = NOW(4)"
1316
- // , [rolPermisoIdDelPadre, perfilGeneralId, dato]);
1317
- // });
1318
- // }
1319
-
1320
- // // Impresión de la información de registro
1321
- // console.log(new Date());
1322
- // console.log(`Módulo registrado correctamente en SIGU. Módulo: ${this.NombreCanonicoDelModulo}`);
1323
- // console.log(`Identificador de rol a utilizar (RolId): ${this.RolId}`);
1324
- // console.log(`Identificador de permiso a utilizar (PermisoId): ${this.PermisoId}`);
1325
- // console.log(`Identificador de Rol-Permiso a utilizar (RolPermisoId): ${this.RolPermisoId}`);
1326
- // console.log(`Identificador del menú padre (MenuId del padre): ${this.IdDelMenuPadre}`);
1327
- // console.log(`Identificador del menú (MenuId del módulo): ${this.IdDelMenuDelModulo}`);
1328
- // // console.log(`Identificador del flujo de aprobación: ${await this.idDelFlujoDeAprobacion()}`);
1329
- // console.log(`Enlace del módulo: ${this.Enlace}`);
1330
- // this.creacionDeldirectorioParaElAlmacenamientoDeArchivos();
1331
- // console.log(`Versión del núcleo: ${this.versionDelNucleo()}`);
1332
-
1333
- // Creación de variables de entorno
1334
- process.env.SERVIDORSMTP = await this.servidorSMTP();
1335
- process.env.USUARIOSMTP = await this.usuarioSMTP();
1336
- process.env.PUERTOSMTP = await this.puertoSMTP();
1337
- process.env.CLAVESMTP = await this.claveSMTP();
1338
- process.env.DESTINATARIODEINFORMESDEERROR = await this.destinatarioDeInformesDeError();
1339
- process.env.NOMBRECANONICODELMODULO = this.NombreCanonicoDelModulo;
1340
-
1341
- await this.registroDelModuloEnSIGUV2();
1342
- }
1343
-
1344
- enlaceDelFrontend() {
1345
- return this.Enlace;
1346
- }
1347
-
1348
- async idDelFlujoDeAprobacion() {
1349
- const Resultado = await ejecutarConsultaSIGU("SELECT `FlujoDeAprobacionId` FROM `SIGU`.`SIGU_FlujosDeAprobacion` WHERE `NombreCanonico` = ?"
1350
- , [this.NombreCanonicoDelModulo]);
1351
- return Resultado[0]['FlujoDeAprobacionId'];
1352
- }
1353
-
1354
- fechaConFormato() {
1355
- const ahora = new Date(Date.now());
1356
- const anio = ahora.getFullYear();
1357
- const mes = String(ahora.getMonth() + 1).padStart(2, '0');
1358
- const dia = String(ahora.getDate()).padStart(2, '0');
1359
- const hora = String(ahora.getHours()).padStart(2, '0');
1360
- const minutos = String(ahora.getMinutes()).padStart(2, '0');
1361
- const segundos = String(ahora.getSeconds()).padStart(2, '0');
1362
- return `${anio}${mes}${dia}${hora}${minutos}${segundos}`;
1363
- }
1364
- creacionDeldirectorioParaElAlmacenamientoDeArchivos() {
1365
- const fs = require('fs');
1366
- try {
1367
- if (!fs.existsSync(this.directorioParaElAlmacenamientoDeArchivos())) {
1368
- fs.mkdirSync(this.directorioParaElAlmacenamientoDeArchivos(), { recursive: true });
1369
- console.log(`El directorio '${this.directorioParaElAlmacenamientoDeArchivos()}' ha sido creado.`);
1370
- } else {
1371
- console.log(`El directorio '${this.directorioParaElAlmacenamientoDeArchivos()}' ya existe.`);
1372
- }
1373
- } catch (error) {
1374
- console.error(`Se presentó el siguiente problema al interactuar con el sistema de archivos: ${error}`);
1375
- }
1376
- }
1377
-
1378
- directorioParaElAlmacenamientoDeArchivos() {
1379
- return '/var/storage/public/' + this.NombreCanonicoDelModulo;
1380
- }
1381
-
1382
- versionDelNucleo() {
1383
- return "VERSION_DEL_NUCLEO" + " " + this.NombreCanonicoDelModulo;
1384
- }
1385
-
1386
- async destinatarioDeInformesDeError() {
1387
- const destinatarioDeInformesDeError = await ejecutarConsultaSIGU("SELECT `Valor` FROM `SIGU`.`SIGU_VariablesDeSistema` WHERE `Nombre` = 'DestinatarioDeInformesDeError'");
1388
- if (destinatarioDeInformesDeError.length > 0) {
1389
- return destinatarioDeInformesDeError[0]['Valor'];
1390
- } else {
1391
- return '';
1392
- }
1393
- }
1394
-
1395
- async claveSMTP() {
1396
- const claveSMTP = await ejecutarConsultaSIGU("SELECT `Valor` FROM `SIGU`.`SIGU_VariablesDeSistema` WHERE `Nombre` = 'ClaveSMTP'");
1397
- if (claveSMTP.length > 0) {
1398
- return claveSMTP[0]['Valor'];
1399
- } else {
1400
- return '';
1401
- }
1402
- }
1403
-
1404
- async puertoSMTP() {
1405
- const puertoSMTP = await ejecutarConsultaSIGU("SELECT `Valor` FROM `SIGU`.`SIGU_VariablesDeSistema` WHERE `Nombre` = 'PuertoSMTP'");
1406
- if (puertoSMTP.length > 0) {
1407
- return puertoSMTP[0]['Valor'];
1408
- } else {
1409
- return '';
1410
- }
1411
- }
1412
-
1413
- async usuarioSMTP() {
1414
- const usuarioSMTP = await ejecutarConsultaSIGU("SELECT `Valor` FROM `SIGU`.`SIGU_VariablesDeSistema` WHERE `Nombre` = 'UsuarioSMTP'");
1415
- if (usuarioSMTP.length > 0) {
1416
- return usuarioSMTP[0]['Valor'];
1417
- } else {
1418
- return '';
1419
- }
1420
- }
1421
-
1422
- async servidorSMTP() {
1423
- const servidorSMTP = await ejecutarConsultaSIGU("SELECT `Valor` FROM `SIGU`.`SIGU_VariablesDeSistema` WHERE `Nombre` = 'ServidorSMTP'");
1424
- if (servidorSMTP.length > 0) {
1425
- return servidorSMTP[0]['Valor'];
1426
- } else {
1427
- return '';
1428
- }
1429
- }
1430
-
1431
- almacenarCuentaIBAN(Cuerpo) {
1432
- return ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_CuentasBancariasPersonas` VALUES (NULL, ?, ?, TRUE, NOW(4), ?)\
1433
- ON DUPLICATE KEY UPDATE `LastUpdate` = NOW(4), `LastUser` = ?"
1434
- , [Cuerpo.Identificador, Cuerpo.IBAN, Cuerpo.LastUser, Cuerpo.LastUser]);
1435
- }
1436
-
1437
- async obtenerDatosDeLaPersona(Token) {
1438
- let Resultado = undefined;
1439
- try {
1440
- Resultado = await this.obtenerDatosDelUsuario(Token);
1441
- if (!Resultado) {
1442
- throw new ManejadorDeErrores(ManejadorDeErrores.mensajeDeErrorVerificacionDeToken(), ManejadorDeErrores.obtenerNumeroDeLinea());
1443
- }
1444
- } catch (error) {
1445
- console.log(error);
1446
- return;
1447
- }
1448
- return await ejecutarConsultaSIGU("SELECT `a`.`Identificador`, `a`.`Identificacion`\
1449
- , `a`.`Nombre`, `a`.`PrimerApellido`, `a`.`SegundoApellido`\
1450
- , (SELECT GROUP_CONCAT(`b`.`CuentaIBAN`) FROM `SIGU`.`SIGU_CuentasBancariasPersonas` `b` WHERE `b`.`Estado` = TRUE AND `a`.`Identificador` = `b`.`Identificador`) AS `CuentasIBAN`\
1451
- FROM `SIGU`.`SIGU_Personas` `a` WHERE `a`.`Identificador` = ?"
1452
- , [Resultado.Identificador]);
1453
- }
1454
-
1455
- async obtenerDatosDeLaPersonaPorIdentificacion(Identificacion) {
1456
- return await ejecutarConsultaSIGU("SELECT `a`.`Identificador`, `a`.`Identificacion`\
1457
- , `a`.`Nombre`, `a`.`PrimerApellido`, `a`.`SegundoApellido`\
1458
- , (SELECT GROUP_CONCAT(`b`.`CuentaIBAN`) FROM `SIGU`.`SIGU_CuentasBancariasPersonas` `b` WHERE `b`.`Estado` = TRUE AND `a`.`Identificador` = `b`.`Identificador`) AS `CuentasIBAN`\
1459
- FROM `SIGU`.`SIGU_Personas` `a` WHERE `a`.`Identificacion` = ?"
1460
- , [Identificacion]);
1461
- }
1462
-
1463
- async obtenerEstudiantes() {
1464
- return await ejecutarConsultaSIGU("SELECT `Identificador`, `Identificacion`, `Nombre`, `PrimerApellido`,\
1465
- `SegundoApellido` FROM `SIGU`.`SIGU_Personas` WHERE `Identificador` IN\
1466
- (SELECT `Identificador` FROM `SIGU`.`SIGU_RolesPersonas` WHERE `PerfilGeneralId` = 1 /*El perfil 1 parece ser para Estudiantes*/)");
1467
- }
1468
-
1469
- async obtenerBeneficios() {
1470
- return await ejecutarConsultaSIGU("SELECT `BeneficioId`, `Beneficio`, `Estado` FROM `SIGU`.`SIGU_Beneficios`");
1471
- }
1472
-
1473
- async obtenerIdentificacion(Identificador) {
1474
- return await ejecutarConsultaSIGU("SELECT `Identificacion` FROM `SIGU`.`SIGU_Personas` WHERE `Identificador` = ?", [Identificador]);
1475
- }
1476
-
1477
- async obtenerPeriodos() {
1478
- return await ejecutarConsultaSIGU("SELECT `PeriodoId`, `CodigoPeriodo`, `Anio`, `Periodo`, `FechaInicio`, `FechaFinal`, `Tipo`, `Estado` FROM `SIGU`.`SIGU_Periodos` ORDER BY `Anio` DESC, `CodigoPeriodo` DESC");
1479
- }
1480
-
1481
- async obtenerAnios() {
1482
- return await ejecutarConsultaSIGU("SELECT DISTINCT `Anio` FROM `SIGU`.`SIGU_Periodos`");
1483
- }
1484
-
1485
- async obtenerSedes() {
1486
- return await ejecutarConsultaSIGU("SELECT `SedesId`, `CodigoAvatar`, `Descripcion`, `Siglas` FROM `SIGU`.`SIGU_Sedes` ORDER BY `Descripcion`");
1487
- }
1488
-
1489
- async obtenerRecintos() {
1490
- return await ejecutarConsultaSIGU("SELECT `a`.`RecintoId`, CONCAT(`b`.`Descripcion`, '/', `a`.`Recinto`) AS `Recinto` FROM `SIGU`.`SIGU_Recintos` `a` LEFT JOIN `SIGU`.`SIGU_Sedes` `b` ON (`a`.`SedeId` = `b`.`SedesId`) ORDER BY `Recinto`");
1491
- }
1492
-
1493
- async googleClientId() {
1494
- const clientId = await ejecutarConsultaSIGU("SELECT `Valor` FROM `SIGU`.`SIGU_VariablesDeSistema` WHERE `Nombre` = 'Google-ClientId'");
1495
- return clientId[0]?.['Valor'] || '';
1496
- }
1497
-
1498
- async palabraSecretaParaTokens() {
1499
- const palabraSecreta = await ejecutarConsultaSIGU("SELECT `Valor` FROM `SIGU`.`SIGU_VariablesDeSistema` WHERE `Nombre` = 'PalabraSecretaParaLaCreacionDeTokens'");
1500
- return palabraSecreta[0]['Valor'];
1501
- }
1502
-
1503
- comparacionDeCadenas(cadena1, cadena2) {
1504
- const cadenaA = String(cadena1);
1505
- let cadenaB = String(cadena2);
1506
- const tamanioDeCadelaA = cadenaA.length;
1507
- let resultado = 0;
1508
-
1509
- if (tamanioDeCadelaA !== cadenaB.length) {
1510
- cadenaB = cadenaA;
1511
- resultado = 1;
1512
- }
1513
-
1514
- for (let contador = 0; contador < tamanioDeCadelaA; contador++) {
1515
- resultado |= (cadenaA.charCodeAt(contador) ^ cadenaB.charCodeAt(contador));
1516
- }
1517
- return resultado === 0;
1518
- };
1519
-
1520
- async obtenerDatosDelUsuario(encabezadoDeAutorizacion) {
1521
- const jwt = require('jsonwebtoken');
1522
- // Obtención del token
1523
- let token = undefined;
1524
- try {
1525
- token = encabezadoDeAutorizacion.split(" ")[1];
1526
- if (!token) {
1527
- throw new ManejadorDeErrores(ManejadorDeErrores.mensajeDeErrorEncabezadoDeAutorizacion(), ManejadorDeErrores.obtenerNumeroDeLinea(), encabezadoDeAutorizacion);
1528
- }
1529
- } catch (error) {
1530
- console.error(error);
1531
- return false;
1532
- }
1533
-
1534
- // Verificación del token
1535
- let Resultado = undefined;
1536
- try {
1537
- Resultado = await jwt.verify(token, await this.palabraSecretaParaTokens());
1538
- if (!Resultado) {
1539
- throw new ManejadorDeErrores(ManejadorDeErrores.mensajeDeErrorVerificacionDeToken(), ManejadorDeErrores.obtenerNumeroDeLinea(), encabezadoDeAutorizacion);
1540
- }
1541
- Resultado.token = token;
1542
- const DatosDeLaPersona = await ejecutarConsultaSIGU("SELECT `Identificacion`, `Nombre`, `PrimerApellido`,\
1543
- `SegundoApellido`, CONCAT(`FechaNacimiento`) AS `FechaDeNacimiento`\
1544
- FROM `SIGU`.`SIGU_Personas` WHERE `Identificador` = ?", [Resultado.Identificador]);
1545
- Resultado.Identificacion = DatosDeLaPersona[0]['Identificacion'];
1546
- Resultado.Nombre = DatosDeLaPersona[0]['Nombre'];
1547
- Resultado.PrimerApellido = DatosDeLaPersona[0]['PrimerApellido'];
1548
- Resultado.SegundoApellido = DatosDeLaPersona[0]['SegundoApellido'];
1549
- Resultado.FechaDeNacimiento = DatosDeLaPersona[0]['FechaDeNacimiento'];
1550
- return Resultado;
1551
- } catch (error) {
1552
- console.error(error);
1553
- return false;
1554
- }
1555
- }
1556
-
1557
- async validarTokenV2(encabezadoDeAutorizacion, permisoExtraId = undefined) {
1558
- let Resultado = undefined;
1559
- try {
1560
- Resultado = await this.obtenerDatosDelUsuario(encabezadoDeAutorizacion);
1561
- } catch (error) {
1562
- console.error(error);
1563
- }
1564
- // Validación del token para el usuario y authorización
1565
- if (Resultado) {
1566
- try {
1567
- // Validación del token en la sesión
1568
- const tokenAlmacenado = await ejecutarConsultaSIGU("SELECT COUNT(*) AS `Total` FROM `SIGU`.`SIGU_Sesiones`\
1569
- WHERE `Identificador` = ? AND `Token` = ?", [Resultado.Identificador, Resultado.token]);
1570
- if (tokenAlmacenado[0]['Total'] >= 1) {
1571
- // Validación de permisos
1572
- const rolPermisoId = await this.permisoIdV2();
1573
- const permisos = await ejecutarConsultaSIGU("SELECT COUNT(*) AS `Total` FROM `SIGU`.`SIGU_PermisosPersonasV2`\
1574
- WHERE `PermisoId` = ? AND `Identificador` = ?", [rolPermisoId, Resultado.Identificador]);
1575
- if (permisos[0]['Total'] === 1) {
1576
- if (permisoExtraId) {
1577
- const ValidacionPermisoExtra = await ejecutarConsultaSIGU("SELECT COUNT(*) AS `Total` FROM `SIGU`.`SIGU_PermisosExtraPersonasV2`\
1578
- WHERE `PermisoExtraId` = ? AND `Identificador` = ?", [permisoExtraId, Resultado.Identificador]);
1579
- if (ValidacionPermisoExtra[0]['Total'] === 1) {
1580
- return true;
1581
- }
1582
- } else {
1583
- return true;
1584
- }
1585
- } else {
1586
- throw new ManejadorDeErrores(ManejadorDeErrores.mensajeDeErrorPermisosInsuficientes(), ManejadorDeErrores.obtenerNumeroDeLinea());
1587
- }
1588
- } else {
1589
- throw new ManejadorDeErrores(ManejadorDeErrores.mensajeDeErrorTokenInvalido(), ManejadorDeErrores.obtenerNumeroDeLinea());
1590
- }
1591
- } catch (error) {
1592
- console.error(error);
1593
- return false;
1594
- }
1595
- }
1596
- return false;
1597
- }
1598
-
1599
- async validarToken(encabezadoDeAutorizacion) {
1600
- return await this.validarTokenV2(encabezadoDeAutorizacion);
1601
- // const Resultado = undefined;
1602
- // try {
1603
- // Resultado = await this.obtenerDatosDelUsuario(encabezadoDeAutorizacion);
1604
- // } catch (error) {
1605
- // console.error(error);
1606
- // }
1607
- // // Validación del token para el usuario y authorización
1608
- // if (Resultado) {
1609
- // try {
1610
- // // Validación del token en la sesión
1611
- // const tokenAlmacenado = await ejecutarConsultaSIGU("SELECT COUNT(*) AS `Total` FROM `SIGU`.`SIGU_Sesiones`\
1612
- // WHERE `Identificador` = ? AND `Token` = ?", [Resultado.Identificador, Resultado.token]);
1613
- // if (tokenAlmacenado[0]['Total'] >= 1) { // Se compara con >= para preveer multisesiones
1614
- // // Validación de permisos
1615
- // const perfilGeneralId = await this.perfilGeneralId();
1616
- // const rolPermisoId = await this.rolPermisoIdDelModulo();
1617
- // const permisos = await ejecutarConsultaSIGU("SELECT COUNT(*) AS `Total` FROM `SIGU`.`SIGU_RolesPersonas`\
1618
- // WHERE `RolPermisoId` = ? AND `Identificador` = ? AND `PerfilGeneralId` = ?", [rolPermisoId, Resultado.Identificador, perfilGeneralId]);
1619
- // if (permisos[0]['Total'] === 1) {
1620
- // return true;
1621
- // } else {
1622
- // throw new ManejadorDeErrores(ManejadorDeErrores.mensajeDeErrorPermisosInsuficientes(), ManejadorDeErrores.obtenerNumeroDeLinea());
1623
- // }
1624
- // } else {
1625
- // throw new ManejadorDeErrores(ManejadorDeErrores.mensajeDeErrorTokenInvalido(), ManejadorDeErrores.obtenerNumeroDeLinea());
1626
- // }
1627
- // } catch (error) {
1628
- // console.error(error);
1629
- // return false;
1630
- // }
1631
- // }
1632
- // return false;
1633
- }
1634
-
1635
- convertirACSV(ArregloDeJSON) {
1636
- if (!ArregloDeJSON || ArregloDeJSON.length === 0) return '';
1637
- const intentarParsearJSON = (valor) => {
1638
- if (typeof valor === 'object' && valor !== null && !Array.isArray(valor)) return valor;
1639
- if (typeof valor === 'string' && valor.trim().startsWith('{')) {
1640
- try {
1641
- const objeto = JSON.parse(valor);
1642
- if (typeof objeto === 'object' && objeto !== null && !Array.isArray(objeto)) return objeto;
1643
- } catch (e) { }
1644
- }
1645
- return null;
1646
- };
1647
- const columnasOriginales = Object.keys(ArregloDeJSON[0]);
1648
- const mapaColumnasJSON = {};
1649
- columnasOriginales.forEach(col => {
1650
- const todasLasLlaves = new Set();
1651
- let esJSON = false;
1652
- ArregloDeJSON.forEach(fila => {
1653
- const obj = intentarParsearJSON(fila[col]);
1654
- if (obj) {
1655
- esJSON = true;
1656
- Object.keys(obj).forEach(k => todasLasLlaves.add(k));
1657
- }
1658
- });
1659
- if (esJSON) mapaColumnasJSON[col] = Array.from(todasLasLlaves);
1660
- });
1661
-
1662
- const encabezadosFinales = [];
1663
- columnasOriginales.forEach(col => {
1664
- if (mapaColumnasJSON[col]) {
1665
- mapaColumnasJSON[col].forEach(llave => encabezadosFinales.push(`${col}_${llave}`));
1666
- } else {
1667
- encabezadosFinales.push(col);
1668
- }
1669
- });
1670
-
1671
- const filasCSV = ArregloDeJSON.map(fila => {
1672
- const valoresFila = [];
1673
- columnasOriginales.forEach(col => {
1674
- if (mapaColumnasJSON[col]) {
1675
- const obj = intentarParsearJSON(fila[col]) || {};
1676
- mapaColumnasJSON[col].forEach(llave => {
1677
- let valor = obj[llave];
1678
- if (valor === undefined || valor === null || valor === 'null') valor = '';
1679
- valoresFila.push(JSON.stringify(String(valor)).replace(/,/g, ' '));
1680
- });
1681
- } else {
1682
- let valor = fila[col];
1683
- if (valor === null || valor === 'null') valor = '';
1684
- valoresFila.push(JSON.stringify(String(valor)).replace(/,/g, ' '));
1685
- }
1686
- });
1687
- return valoresFila.join(',');
1688
- });
1689
- return [encabezadosFinales.join(','), ...filasCSV].join('\n');
1690
- };
1691
-
1692
- convertirACSVConDetalle(ArregloDeJSON, ColumnaConDetalle) {
1693
- if (!ArregloDeJSON || ArregloDeJSON.length === 0) return '';
1694
- const ejemploConDetalle = ArregloDeJSON.find(e => Array.isArray(e[ColumnaConDetalle]) && e[ColumnaConDetalle].length > 0);
1695
- const camposDetalle = ejemploConDetalle ? Object.keys(ejemploConDetalle[ColumnaConDetalle][0]) : [];
1696
- const columnasBase = Object.keys(ArregloDeJSON[0]).filter(key => key !== ColumnaConDetalle);
1697
- const encabezados = [...columnasBase, ...camposDetalle];
1698
- const filas = ArregloDeJSON.flatMap(fila => {
1699
- const detalles = Array.isArray(fila[ColumnaConDetalle]) ? fila[ColumnaConDetalle] : [];
1700
- if (detalles.length === 0) {
1701
- return [
1702
- encabezados.map(col => {
1703
- const valor = fila[col];
1704
- return formatearValor(valor);
1705
- }).join(',')
1706
- ];
1707
- }
1708
- return detalles.map(detalle => {
1709
- return encabezados.map(col => {
1710
- if (camposDetalle.includes(col)) {
1711
- return formatearValor(detalle[col]);
1712
- } else {
1713
- return formatearValor(fila[col]);
1714
- }
1715
- }).join(',');
1716
- });
1717
- });
1718
- return [encabezados.join(','), ...filas].join('\n');
1719
- function formatearValor(valor) {
1720
- if (valor === null || valor === 'null' || typeof valor === 'undefined') {
1721
- return '""';
1722
- }
1723
- return `"${String(valor).replace(/"/g, '""')}"`; // Escapa comillas
1724
- }
1725
- }
1726
-
1727
- async validarIdentificadorAPI(Encabezados) {
1728
- // Obtención del UUID del repositorio
1729
- let Identificador = undefined;
1730
- try {
1731
- Identificador = Encabezados.authorization.split(" ")[1];
1732
- if (!Identificador) {
1733
- throw new ManejadorDeErrores(ManejadorDeErrores.mensajeDeErrorEncabezadoDeAutorizacion(), ManejadorDeErrores.obtenerNumeroDeLinea());
1734
- }
1735
- } catch (error) {
1736
- console.error(error);
1737
- return false;
1738
- }
1739
-
1740
- // Obtención del Repositorio
1741
- let Repositorio = undefined;
1742
- try {
1743
- Repositorio = Encabezados.referrer;
1744
- if (!Repositorio) {
1745
- throw new ManejadorDeErrores(ManejadorDeErrores.mensajeDeErrorRepositorioOrigen(), ManejadorDeErrores.obtenerNumeroDeLinea());
1746
- }
1747
- } catch (error) {
1748
- console.error(error);
1749
- return false;
1750
- }
1751
-
1752
- // Comprobar el UUID y el repositorio
1753
- let ComprobacionDeRepositorio = undefined;
1754
- try {
1755
- ComprobacionDeRepositorio = await ejecutarConsultaSIGU("SELECT COUNT(*) AS `Total` FROM `SIGU`.`SIGU_Repositorios`\
1756
- WHERE `Repositorio` = ? AND `Identificador` = ?", [Repositorio, Identificador]);
1757
- if (ComprobacionDeRepositorio[0]['Total'] === 0) {
1758
- throw new ManejadorDeErrores(ManejadorDeErrores.mensajeDeErrorRepositorioOrigen(), ManejadorDeErrores.obtenerNumeroDeLinea());
1759
- } else {
1760
- // Comprobar si el repositorio origen tiene derecho a consumir el repositorio destino
1761
- let ComprobacionDeAcceso = undefined;
1762
- try {
1763
- ComprobacionDeAcceso = await ejecutarConsultaSIGU("SELECT COUNT(*) AS `Total` FROM `SIGU`.`SIGU_RepositoriosAccesos`\
1764
- WHERE `RepositorioDestino` = ? AND `RepositorioOrigen` = ?", [this.NombreDelRepositorioDelBackend, Repositorio]);
1765
- if (ComprobacionDeAcceso[0]['Total'] === 1) {
1766
- return true;
1767
- } else {
1768
- throw new ManejadorDeErrores(ManejadorDeErrores.mensajeDeErrorPermisosInsuficientes(), ManejadorDeErrores.obtenerNumeroDeLinea());
1769
- }
1770
- } catch (error) {
1771
- console.error(error);
1772
- return false;
1773
- }
1774
- }
1775
- } catch (error) {
1776
- console.error(error);
1777
- return false;
1778
- }
1779
- }
1780
-
1781
- async validarUsuarioYContrasenia(Cuerpo) {
1782
- // Esta función no es para autenticación, se parte del hecho de que la clave y el usario dada son correctos.
1783
- // Esta función se usa para que APIs de entidades externas debidamente documentadas consuman nuestros servicios.
1784
- // Si la clave no coincide, el usuario se bloquea.
1785
- const crypto = require('crypto');
1786
- const bcrypt = require('bcryptjs');
1787
- const resultados = await ejecutarConsultaSIGU("SELECT `Clave` FROM `SIGU`.`SIGU_Personas` WHERE `Activo` = TRUE AND `Identificacion` = ?"
1788
- , [Cuerpo.body.Identificacion]);
1789
- if (resultados.length != 1) {
1790
- throw new ManejadorDeErrores(ManejadorDeErrores.mensajeDeErrorAccesoAAPI("El usuario " + Cuerpo.body.Identificacion + " no existe"), ManejadorDeErrores.obtenerNumeroDeLinea());
1791
- }
1792
- const Resultado = await bcrypt.compare(crypto.createHash('md5').update(Cuerpo.body.Clave).digest("hex"), resultados[0]['Clave']);
1793
- if (!Resultado) {
1794
- const Mensaje = "Desactivación del usario: " + Cuerpo.body.Identificacion + " por fallo de autenticación.";
1795
- console.log(Mensaje);
1796
- const solicitudCompleta = {
1797
- metodo: Cuerpo.method,
1798
- url: Cuerpo.originalUrl,
1799
- ip: Cuerpo.ip,
1800
- headers: Cuerpo.headers,
1801
- query: Cuerpo.query,
1802
- params: Cuerpo.params,
1803
- body: Cuerpo.body,
1804
- };
1805
- const contenidoHTML = `
1806
- <h2>Solicitud HTTP completa</h2>
1807
- <p><strong>Método:</strong> ${solicitudCompleta.metodo}</p>
1808
- <p><strong>URL:</strong> ${solicitudCompleta.url}</p>
1809
- <p><strong>IP:</strong> ${solicitudCompleta.ip}</p>
1810
- <h3>Headers:</h3>
1811
- <pre>${JSON.stringify(solicitudCompleta.headers, null, 2)}</pre>
1812
- <h3>Query:</h3>
1813
- <pre>${JSON.stringify(solicitudCompleta.query, null, 2)}</pre>
1814
- <h3>Params:</h3>
1815
- <pre>${JSON.stringify(solicitudCompleta.params, null, 2)}</pre>
1816
- <h3>Body:</h3>
1817
- <pre>${JSON.stringify(solicitudCompleta.body, null, 2)}</pre>
1818
- `;
1819
- envioDeCorreo(process.env.DESTINATARIODEINFORMESDEERROR, Mensaje, contenidoHTML);
1820
- await ejecutarConsultaSIGU("UPDATE `SIGU`.`SIGU_Personas` SET `Activo` = FALSE WHERE `Identificacion` = ?"
1821
- , [Cuerpo.body.Identificacion]);
1822
- }
1823
- return Resultado;
1824
- }
1825
-
1826
- async consumirBackend(URL, Cuerpo = undefined, Tipo = undefined) {
1827
- const Encabezados = {
1828
- 'Content-Type': 'application/json',
1829
- 'Authorization': 'Bearer ' + await this.getUUID(),
1830
- 'Referrer': this.NombreDelRepositorioDelBackend,
1831
- 'Origin': this.Enlace
1832
- };
1833
- let Respuesta = undefined;
1834
- const Opciones = {
1835
- method: Cuerpo ? "POST" : "GET",
1836
- headers: Encabezados,
1837
- redirect: 'error'
1838
- };
1839
- if (Tipo === 'stream') {
1840
- Opciones.responseType = 'stream';
1841
- }
1842
- if (Cuerpo) {
1843
- Opciones.body = JSON.stringify(Cuerpo);
1844
- }
1845
- const ListaDeDominiosPermitidos = [
1846
- "sigu.utn.ac.cr",
1847
- "localhost",
1848
- "svc.cluster.local"
1849
- ];
1850
- try {
1851
- if (ListaDeDominiosPermitidos.some(dominio => URL.includes(dominio))) {
1852
- Respuesta = await fetch(URL, Opciones);
1853
- }
1854
- if (!Respuesta.ok) {
1855
- throw new ManejadorDeErrores(ManejadorDeErrores.mensajeDeErrorAccesoAAPI(Respuesta.error), ManejadorDeErrores.obtenerNumeroDeLinea());
1856
- }
1857
- if (Tipo === 'stream') {
1858
- return await Respuesta;
1859
- }
1860
- return await Respuesta.json();
1861
- } catch (error) {
1862
- console.error(error);
1863
- console.error(Respuesta);
1864
- throw new ManejadorDeErrores(error.message, ManejadorDeErrores.obtenerNumeroDeLinea());
1865
- }
1866
- };
1867
-
1868
- async almacenarArchivoEnDisco(Solicitud, UId) {
1869
- const fs = require('fs');
1870
- const trozos = [];
1871
- let tamanioTotal = 0;
1872
- let informacionDelArchivo = {};
1873
-
1874
- await new Promise((resolve, reject) => {
1875
- Solicitud.on('data', (trozo) => {
1876
- trozos.push(trozo);
1877
- tamanioTotal += trozo.length;
1878
- });
1879
-
1880
- Solicitud.on('end', resolve);
1881
- Solicitud.on('error', reject);
1882
- });
1883
-
1884
- try {
1885
- const buffer = Buffer.concat(trozos);
1886
- const limite = Solicitud.headers['content-type'].split('; ')[1].split('=')[1];
1887
- const limiteDelimitador = `--${limite}`;
1888
- const partes = buffer.toString('latin1').split(limiteDelimitador).filter(Boolean);
1889
-
1890
- for (const parte of partes) {
1891
- if (parte.includes('filename=')) {
1892
- const [headers, ...contentParts] = parte.split('\r\n\r\n');
1893
- const contenidoBinario = Buffer.from(contentParts.join('\r\n\r\n'), 'latin1');
1894
- const nombreDeArchivoMatch = headers.match(/filename="([^"]+)"/);
1895
- const tipoDeContenidoMatch = headers.match(/Content-Type: ([^\r\n]+)/);
1896
-
1897
- if (nombreDeArchivoMatch) {
1898
- const nombreDeArchivo = Buffer.from(nombreDeArchivoMatch[1], 'latin1').toString('utf8');
1899
- const tipoDeContenido = tipoDeContenidoMatch ? tipoDeContenidoMatch[1] : 'application/octet-stream';
1900
- const rutaDeArchivo = `${this.directorioParaElAlmacenamientoDeArchivos()}/${UId}-${this.fechaConFormato()}-${nombreDeArchivo}`;
1901
-
1902
- fs.writeFileSync(rutaDeArchivo, contenidoBinario);
1903
-
1904
- informacionDelArchivo = {
1905
- nombreDeArchivo,
1906
- tipoDeContenido,
1907
- tamanioTotal,
1908
- rutaDeArchivo,
1909
- };
1910
- }
1911
- }
1912
- }
1913
- } catch (error) {
1914
- console.error('Error al guardar el archivo:', error);
1915
- throw new ManejadorDeErrores(error.message, ManejadorDeErrores.obtenerNumeroDeLinea());
1916
- }
1917
- return informacionDelArchivo;
1918
- }
1919
-
1920
- async cargarArchivo(Solicitud, Etiquetas) {
1921
- const Partes = Etiquetas.split('--');
1922
- Etiquetas = Partes.slice(0, -1).join("--");
1923
- let Resultado = undefined;
1924
- try {
1925
- Resultado = await this.obtenerDatosDelUsuario(Solicitud.headers.authorization);
1926
- } catch (error) {
1927
- console.error(error);
1928
- }
1929
- // Validación del token para el usuario y authorización
1930
- if (Resultado) {
1931
- const informacionDelArchivo = await this.almacenarArchivoEnDisco(Solicitud, Resultado['uid']);
1932
- const Respuesta = await ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_Adjuntos` (`AdjuntosId`, `Identificador`, `Modulo`, `Seccion`, `Nombre`,\
1933
- `NombreOriginal`, `Ruta`, `Tipo`, `Tamanio`, `Etiqueta`, `LastUpdate`, `LastUser`)\
1934
- VALUES (NULL, ?, ?, 'No aplica', ?, ?, ?, ?, ?, ?, NOW(4), ?)"
1935
- , [Resultado['uid'], this.NombreCanonicoDelModulo, informacionDelArchivo.nombreDeArchivo, informacionDelArchivo.nombreDeArchivo
1936
- , informacionDelArchivo.rutaDeArchivo, informacionDelArchivo.tipoDeContenido, informacionDelArchivo.tamanioTotal
1937
- , Etiquetas, Resultado['uid']]);
1938
- informacionDelArchivo.insertId = Respuesta.insertId;
1939
- informacionDelArchivo.Etiquetas = Etiquetas;
1940
- await ejecutarConsulta("INSERT INTO `" + this.NombreDelRepositorioDeLaBaseDeDatos.slice(0, -3) + "`.`Archivos`\
1941
- VALUES (?, ?, ?, ?, ?, NOW(4), ?)"
1942
- , [Respuesta.insertId, Resultado.Identificador, informacionDelArchivo.rutaDeArchivo, informacionDelArchivo.nombreDeArchivo
1943
- , Etiquetas, Resultado.Identificador]);
1944
- return informacionDelArchivo;
1945
- }
1946
- return;
1947
- }
1948
-
1949
- archivoCSVAJSON(rutaArchivo) {
1950
- const fs = require('fs');
1951
- const path = require('path');
1952
- return new Promise((resolve, reject) => {
1953
- fs.readFile(path.resolve(rutaArchivo), 'utf8', (err, data) => {
1954
- if (err) {
1955
- return reject(err);
1956
- }
1957
- try {
1958
- const lineas = data.trim().split('\n'); // Dividir en líneas
1959
- const encabezados = lineas[0].split(','); // Extraer encabezados de la primera línea
1960
- const resultados = lineas.slice(1).map((linea) => {
1961
- const valores = linea.split(','); // Dividir cada línea en valores
1962
- const objeto = {};
1963
- encabezados.forEach((encabezado, index) => {
1964
- objeto[encabezado.trim()] = valores[index]?.trim(); // Crear clave-valor
1965
- });
1966
- return objeto;
1967
- });
1968
- resolve(resultados);
1969
- } catch (error) {
1970
- reject(error);
1971
- }
1972
- });
1973
- });
1974
- }
1975
-
1976
- jsonATabla(Datos) {
1977
- if (!Array.isArray(Datos) || Datos.length === 0) {
1978
- return 'El arreglo está vacío o no es válido.';
1979
- }
1980
- const columnas = Object.keys(Datos[0]);
1981
- const anchos = columnas.map(columna => {
1982
- return Math.max(
1983
- columna.length,
1984
- ...Datos.map(row => (row[columna] ? row[columna].toString().length : 0))
1985
- );
1986
- });
1987
- const formatearFila = (fila) => '| ' + fila.map((valor, index) => (valor || '').toString().padEnd(anchos[index])).join(' | ') + ' |';
1988
- const separador = '+-' + anchos.map(ancho => '-'.repeat(ancho)).join('-+-') + '-+';
1989
- const encabezado = formatearFila(columnas);
1990
- const filas = Datos.map(row => formatearFila(columnas.map(col => row[col] || '')));
1991
- return [separador, encabezado, separador, ...filas, separador].join('\n');
1992
- }
1993
-
1994
- // async agregarCodigoQR(doc, url, opciones = {}) {
1995
- // const { x = 0, y = 0, size = 100 } = opciones;
1996
-
1997
-
1998
-
1999
- // const urlQR = `https://qrcode.tec-it.com/API/QRCode?data=${encodeURIComponent(url)}&backcolor=%23ffffff&size=small&quietzone=1&errorcorrection=H`;
2000
- // doc.image(urlQR, x, y, { width: size, height: size });
2001
- // }
2002
-
2003
- agregarMarcaDeAgua(doc, texto = 'Borrador', opciones = {}) {
2004
- const {
2005
- color = '#CCCCCC',
2006
- opacity = 0.3,
2007
- } = opciones;
2008
-
2009
- const { width, height } = doc.page; // Tamaño de la página
2010
-
2011
- doc.save(); // Guardar el estado original de la página
2012
-
2013
- // Calcular la posición y el ángulo de la marca de agua
2014
- doc
2015
- .font('Times-Roman', 220)
2016
- .fillColor(color)
2017
- .opacity(opacity)
2018
- .rotate(-55, { origin: [width / 2, height / 2] }) // Rotar el texto en diagonal
2019
- .text(
2020
- texto,
2021
- -width * 0.2, // Ajustar el desplazamiento horizontal
2022
- height * 0.4, // Ajustar el desplazamiento vertical
2023
- {
2024
- align: 'center',
2025
- valign: 'center',
2026
- width: width * 1.5, // Asegurar que el texto abarca toda la diagonal
2027
- }
2028
- );
2029
-
2030
- doc.restore(); // Restaurar el estado original de la página
2031
- }
2032
-
2033
- async generarObjetoInfoDeUnReportePDF() {
2034
-
2035
- // Título: UTN-1-1-2024
2036
- // Autor: Apellido Apellido Nombre + cédula del funcionario
2037
- // Asunto: Boleta de Vacaciones
2038
- // Palabras Clave: Hash documento: asfsadffsdafsdfafggef4455
2039
-
2040
- // Agregarle al doc un QR con el enlace a SIGU y códiigo de verificación
2041
-
2042
- const UUID = await ejecutarConsulta("SELECT UUID() AS `Dato`");
2043
- const PalabrasClave = {
2044
- "Módulo": this.NombreCanonicoDelModulo,
2045
- "UUID": UUID[0]['Dato']
2046
- };
2047
- return {
2048
- Title: 'Nombre del reporte, como por ejemplo: Boleta de Vacaciones',
2049
- Author: 'Universidad Técnica Nacional',
2050
- Subject: 'Reporte PDF',
2051
- Keywords: JSON.stringify(PalabrasClave),
2052
- Creator: 'SIGU',
2053
- Producer: 'SIGU'
2054
- };
2055
- }
2056
-
2057
- agregarTablaElegante(doc, datos, opciones = {}) {
2058
- const { x = 50, y = 50, columnWidth = 100, rowHeight = 20, headerHeight = 25, fontSize = 10 } = opciones;
2059
-
2060
- // Configuración de fuentes
2061
- doc.fontSize(fontSize);
2062
-
2063
- // Obtener las claves del primer objeto como encabezados
2064
- const encabezados = Object.keys(datos[0]);
2065
-
2066
- // Dibujar los encabezados
2067
- encabezados.forEach((encabezado, i) => {
2068
- const posX = x + i * columnWidth;
2069
- doc
2070
- .rect(posX, y, columnWidth, headerHeight)
2071
- .fillAndStroke('#d3d3d3', '#000')
2072
- .fillColor('#000')
2073
- .text(encabezado, posX + 5, y + 5, { width: columnWidth - 10, align: 'left' });
2074
- });
2075
-
2076
- // Dibujar las filas
2077
- datos.forEach((fila, filaIndex) => {
2078
- const filaY = y + headerHeight + filaIndex * rowHeight;
2079
- encabezados.forEach((columna, colIndex) => {
2080
- const posX = x + colIndex * columnWidth;
2081
- const texto = fila[columna] !== undefined ? fila[columna].toString() : '';
2082
- doc
2083
- .rect(posX, filaY, columnWidth, rowHeight)
2084
- .stroke()
2085
- .fillColor('#000')
2086
- .text(texto, posX + 5, filaY + 5, { width: columnWidth - 10, align: 'left' });
2087
- });
2088
- });
2089
-
2090
- return doc;
2091
- }
2092
-
2093
- async reportePDFDeEjemplo(Respuesta) {
2094
-
2095
- Respuesta.setHeader('Content-Type', 'application/pdf');
2096
- Respuesta.setHeader('Content-Disposition', 'inline; filename="reporte.pdf"');
2097
- const PDFDocument = require('pdfkit');
2098
-
2099
- const opciones = {
2100
- font: 'Courier',
2101
- size: 'LETTER',
2102
- info: await this.generarObjetoInfoDeUnReportePDF()
2103
- };
2104
- var doc = new PDFDocument(opciones);
2105
- doc.pipe(Respuesta);
2106
-
2107
- this.agregarMarcaDeAgua(doc, 'Borrador', {
2108
- fontSize: 80,
2109
- opacity: 0.2,
2110
- color: '#FF0000',
2111
- });
2112
-
2113
- doc.fontSize(25).text('Here is some vector graphics...', 100, 80);
2114
-
2115
- doc.save()
2116
- .moveTo(100, 150)
2117
- .lineTo(100, 250)
2118
- .lineTo(200, 250)
2119
- .fill('#FF3300');
2120
-
2121
- doc.circle(280, 200, 50).fill('#6600FF');
2122
-
2123
- doc.scale(0.6)
2124
- .translate(470, 130)
2125
- .path('M 250,75 L 323,301 131,161 369,161 177,301 z')
2126
- .fill('red', 'even-odd')
2127
- .restore();
2128
-
2129
- doc.text('And here is some wrapped text...', 100, 300)
2130
- .font('Times-Roman', 13)
2131
- .moveDown()
2132
- .text("lorem", {
2133
- width: 412,
2134
- align: 'justify',
2135
- indent: 30,
2136
- columns: 2,
2137
- height: 300,
2138
- ellipsis: true
2139
- });
2140
-
2141
- // Datos de ejemplo
2142
- const datos = [
2143
- { Nombre: 'Juan', Edad: 28, Ciudad: 'San José', LugarDeTrabajo: 'UTN' },
2144
- { Nombre: 'Ana', Edad: 34 },
2145
- { Nombre: 'Luis', Edad: 25, Ciudad: 'Alajuela' },
2146
- ];
2147
- this.agregarTablaElegante(doc, datos, { x: 0, y: 400, columnWidth: 150, fontSize: 12 });
2148
- // await this.agregarCodigoQR(doc, 'https://www.utn.ac.cr', { x: doc.page.width - 150, y: doc.page.height - 150, size: 100 });
2149
- doc.end();
2150
- }
2151
-
2152
- async verificarToken(Token) {
2153
- let Resultado = undefined;
2154
- try {
2155
- Resultado = await this.obtenerDatosDelUsuario(`Bearer ${Token}`);
2156
- } catch (error) {
2157
- console.error(error);
2158
- }
2159
- return Resultado;
2160
- }
2161
-
2162
- async crearTareaProgramada(Tarea) {
2163
- const os = require('node:os');
2164
- return await ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_ModulosTareasProgramadas` VALUES\
2165
- (?, ?, 'Ejecutada', NOW(4), ?) ON DUPLICATE KEY UPDATE `NombreDelEquipo` = ?"
2166
- , [this.NombreDelRepositorioDelBackend, Tarea.name, os.hostname(), os.hostname()]);
2167
- }
2168
-
2169
- async pseudoEjecutarTareaProgramada(Tarea) {
2170
- const os = require('node:os');
2171
- const Resultado = await ejecutarConsultaSIGU("UPDATE `SIGU`.`SIGU_ModulosTareasProgramadas` SET `Estado` = 'Procesando'\
2172
- , `NombreDelEquipo` = ?, `FechaYHoraDeLaUltimaEjecucion` = NOW(4)\
2173
- WHERE `Repositorio` = ? AND `TareaProgramada` = ? AND `Estado` IN ('Ejecutada', 'Cancelada', 'Fallida')"
2174
- , [os.hostname(), this.NombreDelRepositorioDelBackend, Tarea]);
2175
- return Resultado['affectedRows'];
2176
- }
2177
-
2178
- async finalizarTareaProgramada(Tarea) {
2179
- const os = require('node:os');
2180
- const Resultado = await ejecutarConsultaSIGU("UPDATE `SIGU`.`SIGU_ModulosTareasProgramadas` SET `Estado` = 'Ejecutada'\
2181
- , `NombreDelEquipo` = ?, `FechaYHoraDeLaUltimaEjecucion` = NOW(4)\
2182
- WHERE `Repositorio` = ? AND `TareaProgramada` = ? AND `Estado` IN ('Procesando')"
2183
- , [os.hostname(), this.NombreDelRepositorioDelBackend, Tarea]);
2184
- return Resultado['affectedRows'];
2185
- }
2186
-
2187
- async ejecutarEnHoraEspecifica(hora, minuto, segundo, callback) {
2188
- while (true) {
2189
- try {
2190
- await this.crearTareaProgramada(callback);
2191
- break;
2192
- } catch (error) {
2193
- console.error('Error al ejecutar crearTareaProgramada:', error);
2194
- console.log('Reintentando en 5 segundos...');
2195
- await new Promise(resolve => setTimeout(resolve, 5000));
2196
- }
2197
- }
2198
-
2199
- function programarEjecucion() {
2200
- const ahora = new Date();
2201
- const proximaEjecucion = new Date(ahora);
2202
- proximaEjecucion.setHours(hora, minuto, segundo, 0);
2203
- let tiempoEspera = proximaEjecucion - ahora;
2204
- if (tiempoEspera < 0) {
2205
- proximaEjecucion.setDate(proximaEjecucion.getDate() + 1);
2206
- tiempoEspera = proximaEjecucion - ahora;
2207
- }
2208
- console.log(`Se ha programado a '${callback.name}' para ejecución a las ${proximaEjecucion.toLocaleTimeString()}`);
2209
-
2210
- setTimeout(() => {
2211
- callback();
2212
- programarEjecucion();
2213
- }, tiempoEspera);
2214
- }
2215
-
2216
- programarEjecucion();
2217
- }
2218
-
2219
- NombresParalocalhost() {
2220
- return ["localhost", "::", "127.0.0.1", "::1"];
2221
- }
2222
-
2223
- async crearToken(Identificador) {
2224
- let Token = undefined;
2225
- if (this.NombresParalocalhost().includes(process.env.HOST) && (typeof process.env.DB_HOST_SIGU === "undefined")) {
2226
- const jwt = require('jsonwebtoken');
2227
- Token = await jwt.sign({ uid: Identificador, Identificador }, await this.palabraSecretaParaTokens(), { expiresIn: '10h' });
2228
- await ejecutarConsultaSIGU("DELETE FROM `SIGU`.`SIGU_Sesiones` WHERE `Identificador` = ?", [Identificador]);
2229
- await ejecutarConsultaSIGU("INSERT INTO `SIGU`.`SIGU_Sesiones` VALUES (?, 'Backend', ?, NOW(4), USER())", [Identificador, Token]);
2230
- }
2231
- const fs = require('fs');
2232
- const ExpresionRegular = new RegExp(/[A-Za-z0-9_-]{30,}\.[A-Za-z0-9_-]{30,}\.[A-Za-z0-9_-]{30,}/, 'g');
2233
- // index.rest
2234
- let ArchivoREST = process.cwd() + '/index.rest';
2235
- let contenido = fs.readFileSync(ArchivoREST, 'utf-8');
2236
- let contenidoActualizado = contenido.replace(ExpresionRegular, Token);
2237
- fs.writeFileSync(ArchivoREST, contenidoActualizado);
2238
- // Módulo.rest
2239
- ArchivoREST = process.cwd() + '/' + this.NombreCanonicoDelModulo + '.rest';
2240
- contenido = fs.readFileSync(ArchivoREST, 'utf-8');
2241
- contenidoActualizado = contenido.replace(ExpresionRegular, Token);
2242
- fs.writeFileSync(ArchivoREST, contenidoActualizado);
2243
- // datos-globales.service.ts
2244
- try {
2245
- const CWD = process.cwd();
2246
- process.chdir('..');
2247
- ArchivoREST = process.cwd() + '/' + this.NombreDelRepositorioDelFrontend + '/src/app/datos-globales.service.ts';
2248
- process.chdir(CWD);
2249
- contenido = fs.readFileSync(ArchivoREST, 'utf-8');
2250
- contenidoActualizado = contenido.replace(ExpresionRegular, Token);
2251
- fs.writeFileSync(ArchivoREST, contenidoActualizado);
2252
- } catch (error) {
2253
- console.warn("No fue posible actualizar el archivo datos-globales.service.ts del front: ", error);
2254
- }
2255
- return Token;
2256
- }
2257
-
2258
- async listarArchivos(Datos) {
2259
- const Partes = Datos.Etiquetas.split('--');
2260
- const Etiquetas = Partes.slice(0, -1).join("--");
2261
- const partes = Datos.Etiquetas.split('--');
2262
- const ultimaParte = partes[partes.length - 1].split('=')[1];
2263
- if (ultimaParte === 'Usuario') {
2264
- let Resultado = undefined;
2265
- try {
2266
- Resultado = await this.obtenerDatosDelUsuario(Datos.Token);
2267
- if (!Resultado) {
2268
- throw new ManejadorDeErrores(ManejadorDeErrores.mensajeDeErrorVerificacionDeToken(), ManejadorDeErrores.obtenerNumeroDeLinea());
2269
- }
2270
- } catch (error) {
2271
- console.log(error);
2272
- return;
2273
- }
2274
- return await ejecutarConsulta("SELECT `ArchivoId`, `Identificador`, `Ruta`, CONCAT(`Nombre`, ' (', DATE_FORMAT(`LastUpdate`, '%Y-%M-%d %H:%i'), ')') AS `Nombre`, `Etiquetas`\
2275
- FROM `" + this.NombreDelRepositorioDeLaBaseDeDatos.slice(0, -3) + "`.`Archivos`\
2276
- WHERE `Identificador` = ? AND `Etiquetas` = ?"
2277
- , [Resultado.Identificador, Etiquetas]);
2278
- }
2279
- if (ultimaParte === 'Servicio') {
2280
- return await ejecutarConsulta("SELECT `ArchivoId`, `Identificador`, `Ruta`, CONCAT(`Nombre`, ' (', DATE_FORMAT(`LastUpdate`, '%Y-%M-%d %H:%i'), ')') AS `Nombre`, `Etiquetas`\
2281
- FROM `" + this.NombreDelRepositorioDeLaBaseDeDatos.slice(0, -3) + "`.`Archivos`\
2282
- WHERE `Etiquetas` = ?"
2283
- , [Etiquetas]);
2284
- }
2285
- if (ultimaParte === 'Proceso') {
2286
- return await ejecutarConsulta("SELECT `ArchivoId`, `Identificador`, `Ruta`, CONCAT(`Nombre`, ' (', DATE_FORMAT(`LastUpdate`, '%Y-%M-%d %H:%i'), ')') AS `Nombre`, `Etiquetas`\
2287
- FROM `" + this.NombreDelRepositorioDeLaBaseDeDatos.slice(0, -3) + "`.`Archivos`\
2288
- WHERE `Etiquetas` = ?"
2289
- , [Etiquetas]);
2290
- }
2291
- if (typeof ultimaParte === "number") {
2292
- if (this.validarTokenV2(Datos.Token, ultimaParte)) {
2293
- return await ejecutarConsulta("SELECT `ArchivoId`, `Identificador`, `Ruta`, CONCAT(`Nombre`, ' (', DATE_FORMAT(`LastUpdate`, '%Y-%M-%d %H:%i'), ')') AS `Nombre`, `Etiquetas`\
2294
- FROM `" + this.NombreDelRepositorioDeLaBaseDeDatos.slice(0, -3) + "`.`Archivos`\
2295
- WHERE `Etiquetas` = ?"
2296
- , [Etiquetas]);
2297
- }
2298
- }
2299
- }
2300
-
2301
- async listarArchivosExterno(Datos) {
2302
- const Partes = Datos.Etiquetas.split('--');
2303
- const Etiquetas = Partes.slice(0, -1).join("--");
2304
- const partes = Datos.Etiquetas.split('--');
2305
- const ultimaParte = partes[partes.length - 1].split('=')[1];
2306
- let Resultado = undefined;
2307
- try {
2308
- Resultado = await this.obtenerDatosDelUsuario(Datos.Token);
2309
- if (!Resultado) {
2310
- throw new ManejadorDeErrores(ManejadorDeErrores.mensajeDeErrorVerificacionDeToken(), ManejadorDeErrores.obtenerNumeroDeLinea());
2311
- }
2312
- } catch (error) {
2313
- console.log(error);
2314
- return;
2315
- }
2316
- return await ejecutarConsulta("SELECT `ArchivoId`, `Identificador`, `Ruta`, CONCAT(`Nombre`, ' (', DATE_FORMAT(`LastUpdate`, '%Y-%M-%d %H:%i'), ')') AS `Nombre`, `Etiquetas`\
2317
- FROM `" + this.NombreDelRepositorioDeLaBaseDeDatos.slice(0, -3) + "`.`Archivos`\
2318
- WHERE `Identificador` = ?"
2319
- , [Etiquetas]);
2320
- }
2321
-
2322
- async borrarArchivo(Datos) {
2323
- let Resultado = undefined;
2324
- try {
2325
- Resultado = await this.obtenerDatosDelUsuario(Datos.Token);
2326
- if (!Resultado) {
2327
- throw new ManejadorDeErrores(ManejadorDeErrores.mensajeDeErrorVerificacionDeToken(), ManejadorDeErrores.obtenerNumeroDeLinea());
2328
- }
2329
- } catch (error) {
2330
- console.log(error);
2331
- return;
2332
- }
2333
- const fs = require('fs');
2334
- const Archivo = await ejecutarConsulta("SELECT `Ruta`\
2335
- FROM `" + this.NombreDelRepositorioDeLaBaseDeDatos.slice(0, -3) + "`.`Archivos`\
2336
- WHERE `Identificador` = ? AND `ArchivoId` = ?"
2337
- , [Resultado.Identificador, Datos.ArchivoId]);
2338
- fs.unlinkSync(Archivo[0]['Ruta']);
2339
- await ejecutarConsulta("DELETE FROM `" + this.NombreDelRepositorioDeLaBaseDeDatos.slice(0, -3) + "`.`Archivos`\
2340
- WHERE `Identificador` = ? AND `ArchivoId` = ?"
2341
- , [Resultado.Identificador, Datos.ArchivoId]);
2342
- await ejecutarConsultaSIGU("DELETE FROM `SIGU`.`SIGU_Adjuntos`\
2343
- WHERE `Identificador` = ? AND `AdjuntosId` = ?"
2344
- , [Resultado.Identificador, Datos.ArchivoId]);
2345
- return;
2346
- }
2347
-
2348
- async descargarArchivo(Respuesta, Datos) {
2349
- let RutaDelArchivo = undefined;
2350
- const ArchivoId = Datos.ArchivoId.split('--')[0];
2351
- const partes = Datos.ArchivoId.split('--');
2352
- const ultimaParte = partes[partes.length - 1].split('=')[1];
2353
- if (ultimaParte === 'Usuario') {
2354
- let Resultado = undefined;
2355
- try {
2356
- Resultado = await this.obtenerDatosDelUsuario(Datos.Token);
2357
- if (!Resultado) {
2358
- throw new ManejadorDeErrores(ManejadorDeErrores.mensajeDeErrorVerificacionDeToken(), ManejadorDeErrores.obtenerNumeroDeLinea());
2359
- }
2360
- } catch (error) {
2361
- console.log(error);
2362
- return;
2363
- }
2364
- RutaDelArchivo = await ejecutarConsulta("SELECT `Ruta`\
2365
- FROM `" + this.NombreDelRepositorioDeLaBaseDeDatos.slice(0, -3) + "`.`Archivos`\
2366
- WHERE `Identificador` = ? AND `ArchivoId` = ?"
2367
- , [Resultado.Identificador, ArchivoId]);
2368
- }
2369
- if (ultimaParte === 'Servicio') {
2370
- RutaDelArchivo = await ejecutarConsulta("SELECT `Ruta`\
2371
- FROM `" + this.NombreDelRepositorioDeLaBaseDeDatos.slice(0, -3) + "`.`Archivos`\
2372
- WHERE `ArchivoId` = ?"
2373
- , [ArchivoId]);
2374
- }
2375
- if (ultimaParte === 'Proceso') {
2376
- RutaDelArchivo = await ejecutarConsulta("SELECT `Ruta`\
2377
- FROM `" + this.NombreDelRepositorioDeLaBaseDeDatos.slice(0, -3) + "`.`Archivos`\
2378
- WHERE `ArchivoId` = ?"
2379
- , [ArchivoId]);
2380
- }
2381
- if (typeof ultimaParte === "number") {
2382
- if (this.validarTokenV2(Datos.Token, ultimaParte)) {
2383
- RutaDelArchivo = await ejecutarConsulta("SELECT `Ruta`\
2384
- FROM `" + this.NombreDelRepositorioDeLaBaseDeDatos.slice(0, -3) + "`.`Archivos`\
2385
- WHERE `ArchivoId` = ?"
2386
- , [ArchivoId]);
2387
- }
2388
- }
2389
- Respuesta.download(RutaDelArchivo[0]['Ruta']);
2390
- return;
2391
- }
2392
-
2393
- async configurarFrontend(Token = undefined) {
2394
- let NombreUsuario = '';
2395
- if (Token) {
2396
- try {
2397
- const datosUsuario = await this.obtenerDatosDelUsuario(Token);
2398
- if (datosUsuario) {
2399
- NombreUsuario = `${datosUsuario.Nombre || ''} ${datosUsuario.PrimerApellido || ''} ${datosUsuario.SegundoApellido || ''}`.trim();
2400
- }
2401
- } catch (e) {
2402
- console.error('Error obteniendo datos de usuario para frontend:', e);
2403
- }
2404
- }
2405
- return {
2406
- "Modulo": this.NombreCanonicoDelModulo,
2407
- "Titulo": this.NombreDelModulo,
2408
- "Version": this.Version + "$$" + this.versionDelNucleo().split(' ')[0],
2409
- "Descripcion": this.DescripcionDelModulo,
2410
- "Detalle": this.DetalleDelModulo,
2411
- "NombreUsuario": NombreUsuario
2412
- };
2413
- // if (this.NombresParalocalhost().includes(process.env.HOST) && (typeof process.env.DB_HOST_SIGU === "undefined")) {
2414
- // try {
2415
- // const fs = require('fs');
2416
- // const Archivo;
2417
- // const CWD = process.cwd();
2418
- // let contenido;
2419
- // let contenidoActualizado;
2420
- // // contenedor-principal.component.html
2421
- // process.chdir('..');
2422
- // Archivo = process.cwd() + '/' + this.NombreDelRepositorioDelFrontend + '/src/app/Paginas/contenedor-principal/contenedor-principal.component.html';
2423
- // contenido = fs.readFileSync(Archivo, 'utf-8');
2424
- // contenidoActualizado = contenido.replace('DESCRIPCION_DEL_PROYECTO', this.DescripcionDelModulo);
2425
- // fs.writeFileSync(Archivo, contenidoActualizado);
2426
- // contenido = fs.readFileSync(Archivo, 'utf-8');
2427
- // contenidoActualizado = contenido.replace('DETALLE_DEL_PROYECTO', this.DetalleDelModulo);
2428
- // fs.writeFileSync(Archivo, contenidoActualizado);
2429
- // process.chdir(CWD);
2430
-
2431
- // // contenedor-componentes.component.html
2432
- // process.chdir('..');
2433
- // Archivo = process.cwd() + '/' + this.NombreDelRepositorioDelFrontend + '/src/app/Paginas/Nucleo/contenedor-componentes/contenedor-componentes.component.html';
2434
- // contenido = fs.readFileSync(Archivo, 'utf-8');
2435
- // contenidoActualizado = contenido.replace('NOMBRE_DEL_PROYECTO', this.NombreDelModulo);
2436
- // fs.writeFileSync(Archivo, contenidoActualizado);
2437
- // contenido = fs.readFileSync(Archivo, 'utf-8');
2438
- // contenidoActualizado = contenido.replace('MODULO', this.NombreCanonicoDelModulo);
2439
- // fs.writeFileSync(Archivo, contenidoActualizado);
2440
- // contenido = fs.readFileSync(Archivo, 'utf-8');
2441
- // contenidoActualizado = contenido.replace('VERSION', '1.0.0');
2442
- // fs.writeFileSync(Archivo, contenidoActualizado);
2443
- // process.chdir(CWD);
2444
-
2445
- // } catch (error) {
2446
- // console.warn("No fue posible actualizar el archivo contenedor-principal.component.html del front: ", error);
2447
- // }
2448
- // }
2449
- // return;
2450
- }
2451
-
2452
- async DatosPersonalesDeUnaPersona(Identificador) {
2453
- const Resultado = {};
2454
- const DatosDeLaPersona = await ejecutarConsultaSIGU("SELECT `Identificacion`, `Nombre`, `PrimerApellido`,\
2455
- `SegundoApellido`, (SELECT `CorreoElectronico` FROM `SIGU`.`SIGU_CorreosPersona` WHERE `Identificador` = ? AND `Principal` = TRUE) AS `CorreoElectronicoPrincipal`\
2456
- FROM `SIGU`.`SIGU_Personas` WHERE `Identificador` = ?", [Identificador, Identificador]);
2457
- Resultado.Identificador = Identificador;
2458
- Resultado.Identificacion = DatosDeLaPersona[0]['Identificacion'];
2459
- Resultado.Nombre = DatosDeLaPersona[0]['Nombre'];
2460
- Resultado.PrimerApellido = DatosDeLaPersona[0]['PrimerApellido'];
2461
- Resultado.SegundoApellido = DatosDeLaPersona[0]['SegundoApellido'];
2462
- Resultado.CorreoElectronicoPrincipal = DatosDeLaPersona[0]['CorreoElectronicoPrincipal'];
2463
- return Resultado;
2464
- }
2465
-
2466
- async ejecucionDiferida(callback) {
2467
- const stackLines = new Error().stack.split('\n');
2468
- const lineaCaller = stackLines[2] ?? '';
2469
- const match = lineaCaller.match(/\((.+?):\d+:\d+\)/) ?? lineaCaller.match(/at (.+?):\d+:\d+/);
2470
- const archivo = match ? require('path').basename(match[1]) : null;
2471
-
2472
- while (true) {
2473
- try {
2474
- this._archivoFuenteActual = archivo;
2475
- await callback();
2476
- break;
2477
- } catch (error) {
2478
- console.error(`Error en la función "${callback.name}": `, error.message);
2479
- console.log('Reintentando en 5 segundos...');
2480
- await new Promise(resolve => setTimeout(resolve, 5000));
2481
- }
2482
- }
2483
- this._archivoFuenteActual = null;
2484
- }
2485
-
2486
- // async obtenerEnlaceDelModuloPadre() {
2487
- // const Ruta = await ejecutarConsultaSIGU("SELECT CONCAT('modulos/', `MenuId`) AS `Ruta` FROM `SIGU`.`SIGU_Menu`\
2488
- // WHERE `MenuId` = (SELECT `Padre` FROM `SIGU`.`SIGU_Menu` WHERE `Nombre` = ?)"
2489
- // , [this.NombreCanonicoDelModulo]);
2490
- // return await this.obtenerEnlaceDePortal() + "/" + Ruta[0]['Ruta'];
2491
- // }
2492
-
2493
- async obtenerEnlaceDePortal() {
2494
- return this.EnlaceDePortal;
2495
- }
2496
-
2497
- async obtenerEnlaceDePerfil() {
2498
- return this.EnlaceDePerfil;
2499
- }
2500
-
2501
- async obtenerTarjetas() {
2502
- const resultados = await ejecutarConsultaSIGU(
2503
- "SELECT `Datos` FROM `SIGU`.`SIGU_ModulosV2Tarjetas` WHERE `Modulo` = ? AND JSON_EXTRACT(`Datos`, '$.Activa') = TRUE",
2504
- [this.NombreCanonicoDelModulo]
2505
- );
2506
- return resultados.map(fila => typeof fila.Datos === 'string' ? JSON.parse(fila.Datos) : fila.Datos);
2507
- }
2508
-
2509
- async inicializar(solicitud) {
2510
- const ConsentimientoInformado = require('./ConsentimientoInformado.js');
2511
- const LastUser = await this.generarLastUser(solicitud);
2512
- const [configuracion, detalleDelModulo, notificaciones, mensajesModulares, consentimiento] = await Promise.all([
2513
- this.configurarFrontend(solicitud.headers.authorization),
2514
- this.obtenerDetalleDelModulo(),
2515
- this.obtenerNotificaciones(solicitud.headers.authorization),
2516
- this.obtenerMensajesModulares(),
2517
- ConsentimientoInformado.ConsentimientoInformado({ LastUser })
2518
- ]);
2519
- return {
2520
- TienePermiso: true,
2521
- ...configuracion,
2522
- Descripcion: detalleDelModulo[0]?.Descripcion ?? configuracion.Descripcion,
2523
- Detalle: detalleDelModulo[0]?.Detalle ?? configuracion.Detalle,
2524
- EnlaceDelManual: detalleDelModulo[0]?.EnlaceDelManual ?? '-',
2525
- EnlaceDelVideo: detalleDelModulo[0]?.EnlaceDelVideo ?? '-',
2526
- Notificaciones: notificaciones,
2527
- MensajesModulares: mensajesModulares,
2528
- Consentimiento: consentimiento
2529
- };
2530
- }
2531
-
2532
- async obtenerTarjetasDelContenedor(token) {
2533
- const ConfiguracionDeTarjetas = require('./ConfiguracionDeTarjetas.js');
2534
- const path = require('path');
2535
- const serviciosDir = path.join(__dirname, '..');
2536
-
2537
- const usuario = await this.obtenerDatosDelUsuario(token);
2538
- const [tarjetas, configuracion] = await Promise.all([
2539
- this.obtenerTarjetas(),
2540
- ConfiguracionDeTarjetas.obtener({ Identificador: usuario.uid })
2541
- ]);
2542
-
2543
- const datosDeServicio = await Promise.all(
2544
- tarjetas
2545
- .filter(t => t.Archivo)
2546
- .map(async t => {
2547
- try {
2548
- const rutaArchivo = this._buscarArchivoRecursivo(serviciosDir, t.Archivo);
2549
- if (!rutaArchivo) return null;
2550
- const servicio = require(rutaArchivo);
2551
- const [cantidades, tienePermisoExtra] = await Promise.all([
2552
- typeof servicio.Cantidades === 'function' ? servicio.Cantidades(token) : null,
2553
- typeof servicio.PermisoExtra === 'function' ? servicio.PermisoExtra(token) : null
2554
- ]);
2555
- return [t['Título'], { cantidades, tienePermisoExtra }];
2556
- } catch { return null; }
2557
- })
2558
- );
2559
-
2560
- const datosPorTitulo = Object.fromEntries(datosDeServicio.filter(Boolean));
2561
-
2562
- const titulosAExcluir = new Set(
2563
- Object.entries(datosPorTitulo)
2564
- .filter(([, { cantidades }]) => cantidades && !(cantidades.cantidadMaxima > 0))
2565
- .map(([titulo]) => titulo)
2566
- );
2567
-
2568
- return tarjetas
2569
- .filter(t => !t.RequierePermisoExtra || datosPorTitulo[t['Título']]?.tienePermisoExtra)
2570
- .filter(t => !titulosAExcluir.has(t['Título']))
2571
- .map(t => {
2572
- const config = configuracion.find(c => c.Titulo === t['Título']);
2573
- if (config) {
2574
- t['Posición'] = config.Posicion;
2575
- if (config.ColorDeBorde) t.ColorDeBorde = config.ColorDeBorde;
2576
- }
2577
- const datos = datosPorTitulo[t['Título']];
2578
- if (datos?.cantidades) {
2579
- t['Cantidad'] = datos.cantidades.cantidad;
2580
- t['CantidadMaxima'] = datos.cantidades.cantidadMaxima;
2581
- }
2582
- return t;
2583
- })
2584
- .sort((a, b) => a['Posición'] - b['Posición']);
2585
- }
2586
- }
230
+ Object.assign(Miscelaneo.prototype, MixinAutenticacion);
231
+ Object.assign(Miscelaneo.prototype, MixinNotificaciones);
232
+ Object.assign(Miscelaneo.prototype, MixinTareasProgramadas);
233
+ Object.assign(Miscelaneo.prototype, MixinPersonas);
234
+ Object.assign(Miscelaneo.prototype, MixinArchivos);
235
+ Object.assign(Miscelaneo.prototype, MixinModulos);
236
+ Object.assign(Miscelaneo.prototype, MixinInicializacion);
237
+ Object.assign(Miscelaneo.prototype, MixinReportes);
2587
238
 
2588
239
  module.exports = new Miscelaneo();