fpavon-ee-shared 1.0.0
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.
- package/dependency-injection/dependency-injection.ts +56 -0
- package/digitalSignature/application/digitalSignature.useCase.ts +171 -0
- package/digitalSignature/domain/PDFArrayCustom.ts +60 -0
- package/digitalSignature/domain/SignPDF.ts +112 -0
- package/digitalSignature/infrastructure/routes/digitalSignature.routes.ts +3 -0
- package/digitalSignature/infrastructure/template/marco.pdf +0 -0
- package/dist/dependency-injection/dependency-injection.js +46 -0
- package/dist/digitalSignature/application/digitalSignature.useCase.js +180 -0
- package/dist/digitalSignature/domain/PDFArrayCustom.js +59 -0
- package/dist/digitalSignature/domain/SignPDF.js +100 -0
- package/dist/digitalSignature/infrastructure/routes/digitalSignature.routes.js +1 -0
- package/dist/documentos/application/documentos.useCase.js +49 -0
- package/dist/documentos/application/streamConversor.js +14 -0
- package/dist/documentos/domain/documento.class.js +60 -0
- package/dist/documentos/domain/documento.interface.js +2 -0
- package/dist/documentos/domain/documento.repository.js +2 -0
- package/dist/documentos/domain/documentoFTP.js +11 -0
- package/dist/documentos/domain/value-object/uuid.js +21 -0
- package/dist/documentos/infrastructure/repository/documentos.ftp.repository.js +172 -0
- package/dist/estados/application/flujos.useCase.js +21 -0
- package/dist/estados/domain/estado.class.js +150 -0
- package/dist/estados/domain/flujos.repository.js +2 -0
- package/dist/estados/infrastructure/controller/flujos.controller.js +34 -0
- package/dist/estados/infrastructure/repositories/flujos.sql.repository.js +36 -0
- package/dist/estados/infrastructure/routes/flujo.route.js +50 -0
- package/dist/expediente-electronico/application/expediente-electronico.useCase.js +171 -0
- package/dist/expediente-electronico/domain/expediente-electronico.class.js +190 -0
- package/dist/expediente-electronico/domain/expediente-electronico.interface.js +2 -0
- package/dist/expediente-electronico/domain/expediente-electronico.repository.js +2 -0
- package/dist/expediente-electronico/domain/value-object/limited-string.class.js +19 -0
- package/dist/expediente-electronico/domain/value-object/notas.class.js +41 -0
- package/dist/expediente-electronico/infrastructure/controller/expediente-electronico.controller.js +306 -0
- package/dist/expediente-electronico/infrastructure/repositories/expediente-electronico.sql.repository.js +775 -0
- package/dist/expediente-electronico/infrastructure/routes/expediente-electronico.route.js +46 -0
- package/dist/infrastructure/bd/connection.sql.js +64 -0
- package/dist/infrastructure/bd/pagination.sql.js +15 -0
- package/dist/infrastructure/docs/swagger.js +37 -0
- package/dist/infrastructure/fileServer/fileServer.basic-ftp.js +220 -0
- package/dist/infrastructure/fileServer/fileServer.connection.js +94 -0
- package/dist/infrastructure/middlewares/middleware.apikey.js +15 -0
- package/dist/infrastructure/middlewares/middleware.auth.js +372 -0
- package/dist/infrastructure/middlewares/middleware.deslogueo.js +1 -0
- package/dist/infrastructure/middlewares/middleware.validarCampos.js +15 -0
- package/dist/infrastructure/middlewares/middleware.validarRol.js +19 -0
- package/dist/infrastructure/middlewares/validarNivel.js +37 -0
- package/dist/infrastructure/server/httpsServer.class.js +59 -0
- package/dist/infrastructure/server/server.class.js +54 -0
- package/dist/infrastructure/socket/socketIO.js +23 -0
- package/dist/infrastructure/stream-handler/stream-handler.js +137 -0
- package/dist/notificaciones/domain/datosNotificacion.class.js +11 -0
- package/dist/notificaciones/domain/datosNotificacion.interface.js +2 -0
- package/dist/notificaciones/domain/notificacion.class.js +19 -0
- package/dist/notificaciones/domain/notificacion.interface.js +2 -0
- package/dist/notificaciones/domain/notificacion.repository.js +2 -0
- package/dist/notificaciones/infrastructure/notificacion.controller.js +31 -0
- package/dist/usuarios/application/usuarios.useCase.js +22 -0
- package/dist/usuarios/domain/usuario.class.js +24 -0
- package/dist/usuarios/domain/usuario.interface.js +2 -0
- package/dist/usuarios/domain/usuarios.repository.js +2 -0
- package/dist/usuarios/infrastructure/controller/usuarios.controller.js +28 -0
- package/dist/usuarios/infrastructure/repository/usuarios.sql.repository.js +17 -0
- package/dist/usuarios/infrastructure/routes/usuarios.routes.js +19 -0
- package/documentos/application/documentos.useCase.ts +41 -0
- package/documentos/domain/documento.class.ts +101 -0
- package/documentos/domain/documento.interface.ts +9 -0
- package/documentos/domain/documento.repository.ts +12 -0
- package/documentos/domain/documentoFTP.ts +17 -0
- package/documentos/domain/value-object/uuid.ts +23 -0
- package/documentos/infrastructure/repository/documentos.ftp.repository.ts +169 -0
- package/estados/application/flujos.useCase.ts +13 -0
- package/estados/domain/estado.class.ts +213 -0
- package/estados/domain/flujos.repository.ts +8 -0
- package/estados/infrastructure/controller/flujos.controller.ts +21 -0
- package/estados/infrastructure/repositories/flujos.sql.repository.ts +29 -0
- package/estados/infrastructure/routes/flujo.route.ts +56 -0
- package/expediente-electronico/application/expediente-electronico.useCase.ts +154 -0
- package/expediente-electronico/domain/expediente-electronico.class.ts +223 -0
- package/expediente-electronico/domain/expediente-electronico.interface.ts +19 -0
- package/expediente-electronico/domain/expediente-electronico.repository.ts +22 -0
- package/expediente-electronico/domain/value-object/limited-string.class.ts +19 -0
- package/expediente-electronico/domain/value-object/notas.class.ts +51 -0
- package/expediente-electronico/infrastructure/controller/expediente-electronico.controller.ts +308 -0
- package/expediente-electronico/infrastructure/repositories/expediente-electronico.sql.repository.ts +799 -0
- package/expediente-electronico/infrastructure/routes/expediente-electronico.route.ts +64 -0
- package/infrastructure/bd/connection.sql.ts +49 -0
- package/infrastructure/bd/pagination.sql.ts +11 -0
- package/infrastructure/docs/swagger.ts +38 -0
- package/infrastructure/fileServer/fileServer.basic-ftp.ts +196 -0
- package/infrastructure/fileServer/fileServer.connection.ts +78 -0
- package/infrastructure/middlewares/middleware.apikey.ts +17 -0
- package/infrastructure/middlewares/middleware.auth.ts +409 -0
- package/infrastructure/middlewares/middleware.deslogueo.ts +0 -0
- package/infrastructure/middlewares/middleware.validarCampos.ts +15 -0
- package/infrastructure/middlewares/middleware.validarRol.ts +15 -0
- package/infrastructure/middlewares/validarNivel.ts +37 -0
- package/infrastructure/server/httpsServer.class.ts +69 -0
- package/infrastructure/server/server.class.ts +66 -0
- package/infrastructure/socket/socketIO.ts +22 -0
- package/infrastructure/stream-handler/stream-handler.ts +161 -0
- package/jest.config.js +8 -0
- package/notificaciones/domain/datosNotificacion.class.ts +13 -0
- package/notificaciones/domain/datosNotificacion.interface.ts +5 -0
- package/notificaciones/domain/notificacion.class.ts +23 -0
- package/notificaciones/domain/notificacion.interface.ts +15 -0
- package/notificaciones/domain/notificacion.repository.ts +8 -0
- package/notificaciones/infrastructure/notificacion.controller.ts +16 -0
- package/package.json +42 -0
- package/script.js +135 -0
- package/test/expediente-electronico/domain/expediente-electronico.class.test.ts +186 -0
- package/tsconfig.json +73 -0
- package/usuarios/application/usuarios.useCase.ts +12 -0
- package/usuarios/domain/usuario.class.ts +40 -0
- package/usuarios/domain/usuario.interface.ts +18 -0
- package/usuarios/domain/usuarios.repository.ts +3 -0
- package/usuarios/infrastructure/controller/usuarios.controller.ts +19 -0
- package/usuarios/infrastructure/repository/usuarios.sql.repository.ts +19 -0
- package/usuarios/infrastructure/routes/usuarios.routes.ts +20 -0
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
12
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
13
|
+
};
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.obtenerUnidadPadre = exports.unidadesJoinFuncion = exports.getChildrenUnitIds = exports.getGerencia = exports.getChildrenLabelNumbers = exports.descifrarToken = exports.cifrado = exports.extraerNivel = exports.validarToken = void 0;
|
|
16
|
+
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
|
|
17
|
+
const connection_sql_1 = require("../bd/connection.sql"); // Asegúrate de ajustar la ruta a tu configuración de base de datos
|
|
18
|
+
const axios_1 = __importDefault(require("axios"));
|
|
19
|
+
const validarToken = (req, res, next) => __awaiter(void 0, void 0, void 0, function* () {
|
|
20
|
+
try {
|
|
21
|
+
const bearerHeader = req.header('Authorization') || "";
|
|
22
|
+
if (bearerHeader !== "") {
|
|
23
|
+
const bearer = bearerHeader.split(" ");
|
|
24
|
+
let token = bearer[1];
|
|
25
|
+
// Limpio el token de comillas por las dudas
|
|
26
|
+
token = token.replace(/['"]+/g, '');
|
|
27
|
+
let data = jsonwebtoken_1.default.verify(token, (process.env.SECRET || ''));
|
|
28
|
+
const { afiliado, idNavegador } = data;
|
|
29
|
+
// Verificar si el usuario está deslogueado
|
|
30
|
+
const queryVerificar = `SELECT logueado, idNavegador FROM Usuarios WHERE afiliado = '${data.afiliado}'`;
|
|
31
|
+
const result = yield (0, connection_sql_1.getConnection)(queryVerificar);
|
|
32
|
+
if (result.recordset.length === 0) {
|
|
33
|
+
res.status(401).json({ status: false, mensaje: "Usuario no encontrado" });
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
const usuario = result.recordset[0];
|
|
37
|
+
if (usuario.logueado === 0) {
|
|
38
|
+
res.status(401).json({ status: false, mensaje: "Usuario deslogueado por inactividad" });
|
|
39
|
+
return; // Terminar ejecución pero sin retornar res
|
|
40
|
+
}
|
|
41
|
+
//ACTIVAR LO SIGUIENTE PARA DESLOGUEO POR MISMO USUARIO EN DISTINTOS DISPOSITIVOS
|
|
42
|
+
// if (!usuario.idNavegador || usuario.idNavegador !== idNavegador) {
|
|
43
|
+
// res.status(401).json({ status: false, mensaje: "Sesión inválida. Posible login desde otro dispositivo." });
|
|
44
|
+
// return;
|
|
45
|
+
// }
|
|
46
|
+
req.body.token = token;
|
|
47
|
+
req.body.nombreGerencia = data.nombreGerencia;
|
|
48
|
+
req.body.uid = data.afiliado;
|
|
49
|
+
req.body.nivel = data.grupoAD;
|
|
50
|
+
req.body.nombreCompleto = data.apellido + ", " + data.nombre;
|
|
51
|
+
req.body.cargo = data.cargo;
|
|
52
|
+
req.body.unidad = data.unidad;
|
|
53
|
+
req.body.unidadSuperior = data.unidadSuperior;
|
|
54
|
+
req.body.gerencia = data.gerencia;
|
|
55
|
+
req.body.nombreUnidad = data.nombreUnidad;
|
|
56
|
+
req.body.documento = data.documento;
|
|
57
|
+
req.body.usuario = {
|
|
58
|
+
uid: data.afiliado,
|
|
59
|
+
nivel: data.grupoAD,
|
|
60
|
+
nombreCompleto: data.apellido + ", " + data.nombre,
|
|
61
|
+
cargo: data.cargo,
|
|
62
|
+
unidad: data.unidad,
|
|
63
|
+
unidadSuperior: data.unidadSuperior,
|
|
64
|
+
gerencia: data.gerencia,
|
|
65
|
+
nombreUnidad: data.nombreUnidad,
|
|
66
|
+
nombreGerencia: data.nombreGerencia,
|
|
67
|
+
roles: data.roles,
|
|
68
|
+
grupos: data.grupos,
|
|
69
|
+
documento: data.documento,
|
|
70
|
+
mail: data.mail
|
|
71
|
+
};
|
|
72
|
+
// Esto bloque está porque la gente de PAI no agregó la gerencia donde corresponde
|
|
73
|
+
if (data.gerencia != 0) {
|
|
74
|
+
req.body.gerencia = data.gerencia;
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
req.body.gerencia = data.unidad;
|
|
78
|
+
}
|
|
79
|
+
// Esto bloque está porque la gente de PAI no agregó la gerencia donde corresponde
|
|
80
|
+
// Actualizar lastActivity
|
|
81
|
+
const queryActualizar = `UPDATE Usuarios SET lastActivity = CURRENT_TIMESTAMP WHERE afiliado = '${data.afiliado}'`;
|
|
82
|
+
yield (0, connection_sql_1.getConnection)(queryActualizar);
|
|
83
|
+
next();
|
|
84
|
+
}
|
|
85
|
+
else {
|
|
86
|
+
res.status(401).json({ status: false, mensaje: "no se encontró el token en la cabecera" });
|
|
87
|
+
return; // Terminar ejecución pero sin retornar res
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
res.status(401).json({ status: false, mensaje: "token inválido" });
|
|
92
|
+
return; // Terminar ejecución pero sin retornar res
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
exports.validarToken = validarToken;
|
|
96
|
+
const extraerNivel = (data) => {
|
|
97
|
+
let nivel = 0;
|
|
98
|
+
data.forEach(element => {
|
|
99
|
+
if (element.indexOf(1) > 0)
|
|
100
|
+
nivel = 1;
|
|
101
|
+
else if (element.indexOf(2) > 0)
|
|
102
|
+
nivel = 2;
|
|
103
|
+
else if (element.indexOf(3) > 0)
|
|
104
|
+
nivel = 3;
|
|
105
|
+
});
|
|
106
|
+
return nivel;
|
|
107
|
+
};
|
|
108
|
+
exports.extraerNivel = extraerNivel;
|
|
109
|
+
//Para generar token que se usará en el front end
|
|
110
|
+
const cifrado = (usuario) => {
|
|
111
|
+
return new Promise((resolve, reject) => {
|
|
112
|
+
let secreto = process.env.SECRET;
|
|
113
|
+
jsonwebtoken_1.default.sign(usuario, secreto, { expiresIn: '12h' }, (err, token) => {
|
|
114
|
+
return err ? reject("no se pudo generar el JWT") : resolve(token);
|
|
115
|
+
});
|
|
116
|
+
});
|
|
117
|
+
};
|
|
118
|
+
exports.cifrado = cifrado;
|
|
119
|
+
const descifrarToken = (token) => {
|
|
120
|
+
token = token.replace(/['"]+/g, '');
|
|
121
|
+
try {
|
|
122
|
+
let data = jsonwebtoken_1.default.verify(token, (process.env.SECRET || ''));
|
|
123
|
+
return data;
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
return 'ERROR';
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
exports.descifrarToken = descifrarToken;
|
|
130
|
+
// NOTA: Asume que la función getGerencia y las dependencias (axios, etc.) están definidas e importadas.
|
|
131
|
+
// Si estás usando TypeScript, considera definir la interfaz 'Unidad' para 'gerencia' para un mejor tipado.
|
|
132
|
+
const getChildrenLabelNumbers = (searchNumber) => __awaiter(void 0, void 0, void 0, function* () {
|
|
133
|
+
let gerencia;
|
|
134
|
+
const searchUnitId = searchNumber;
|
|
135
|
+
try {
|
|
136
|
+
// 1. Obtener la gerencia COMPLETA (nodo raíz 1187 en el ejemplo)
|
|
137
|
+
const rawData = yield getGerencia(searchNumber);
|
|
138
|
+
gerencia = (typeof rawData === 'string') ? JSON.parse(rawData) : rawData;
|
|
139
|
+
}
|
|
140
|
+
catch (error) {
|
|
141
|
+
console.error("Error al obtener la gerencia:", error);
|
|
142
|
+
// En caso de fallo, devolvemos solo la unidad buscada
|
|
143
|
+
return [searchNumber];
|
|
144
|
+
}
|
|
145
|
+
// --- Funciones Auxiliares ---
|
|
146
|
+
/**
|
|
147
|
+
* Función recursiva para encontrar el nodo específico (e.g., 1238) dentro de la jerarquía.
|
|
148
|
+
* @param nodo El nodo actual en la búsqueda.
|
|
149
|
+
* @returns El nodo encontrado o null.
|
|
150
|
+
*/
|
|
151
|
+
function findTargetNode(nodo) {
|
|
152
|
+
// 1. Si el nodo actual es el nodo buscado, lo retornamos.
|
|
153
|
+
if (nodo.C_ID_UNIDAD === searchUnitId) {
|
|
154
|
+
return nodo;
|
|
155
|
+
}
|
|
156
|
+
// 2. Si tiene hijas, buscamos recursivamente en ellas.
|
|
157
|
+
if (nodo.Hijas && Array.isArray(nodo.Hijas)) {
|
|
158
|
+
for (const hija of nodo.Hijas) {
|
|
159
|
+
const found = findTargetNode(hija);
|
|
160
|
+
if (found) {
|
|
161
|
+
return found; // Retornar inmediatamente si se encuentra
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
// 3. No encontrado en este subárbol.
|
|
166
|
+
return null;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Función recursiva para extraer los IDs A PARTIR de un nodo.
|
|
170
|
+
* Esta es tu función original, ajustada.
|
|
171
|
+
* @param nodo El objeto de la unidad actual.
|
|
172
|
+
* @param unitsArray El array donde se almacenan los IDs.
|
|
173
|
+
*/
|
|
174
|
+
function extractUnitsFromNode(nodo, unitsArray) {
|
|
175
|
+
if (nodo.C_ID_UNIDAD) {
|
|
176
|
+
unitsArray.push(nodo.C_ID_UNIDAD);
|
|
177
|
+
}
|
|
178
|
+
if (nodo.Hijas && Array.isArray(nodo.Hijas)) {
|
|
179
|
+
for (const hija of nodo.Hijas) {
|
|
180
|
+
extractUnitsFromNode(hija, unitsArray);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
// --- Lógica Principal de Extracción ---
|
|
185
|
+
// 1. Encontrar el nodo raíz deseado (e.g., el objeto de la unidad 1238)
|
|
186
|
+
const targetNode = findTargetNode(gerencia);
|
|
187
|
+
if (!targetNode) {
|
|
188
|
+
// Si por alguna razón la unidad de búsqueda no está en la jerarquía retornada
|
|
189
|
+
console.warn(`Unidad ${searchUnitId} no encontrada en la jerarquía de la gerencia.`);
|
|
190
|
+
return [searchUnitId];
|
|
191
|
+
}
|
|
192
|
+
// 2. Extraer TODAS las unidades (incluyendo la 1238) A PARTIR del nodo encontrado.
|
|
193
|
+
const unidades = [];
|
|
194
|
+
extractUnitsFromNode(targetNode, unidades);
|
|
195
|
+
// 3. Devolver el array final sin duplicados.
|
|
196
|
+
return [...new Set(unidades)];
|
|
197
|
+
});
|
|
198
|
+
exports.getChildrenLabelNumbers = getChildrenLabelNumbers;
|
|
199
|
+
// Caché en memoria para unidades
|
|
200
|
+
const unidadesCache = {};
|
|
201
|
+
const CACHE_TTL = 1000 * 60 * 60; // 1 hora en milisegundos
|
|
202
|
+
/**
|
|
203
|
+
* Obtiene la estructura jerárquica de una unidad
|
|
204
|
+
*/
|
|
205
|
+
/**
|
|
206
|
+
* Obtiene la estructura jerárquica de una unidad
|
|
207
|
+
*/
|
|
208
|
+
function getGerencia(unidad) {
|
|
209
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
210
|
+
console.log("UNIDAD: ", unidad);
|
|
211
|
+
try {
|
|
212
|
+
// URL del endpoint de la API de unidades
|
|
213
|
+
const url = 'http://10.5.12.245:9095/api/Unidades/GetGerencia';
|
|
214
|
+
// Configuración explícita para la petición GET
|
|
215
|
+
const options = {
|
|
216
|
+
method: 'get', // Asegurar que esté en minúsculas y sea 'get'
|
|
217
|
+
url: `${url}?idUnidad=${unidad}`,
|
|
218
|
+
headers: {
|
|
219
|
+
'Api_Key': 'a8778df88c4c7d781bbef56220e16417',
|
|
220
|
+
'Accept': 'application/json'
|
|
221
|
+
},
|
|
222
|
+
timeout: 10000, // Reducimos a 10 segundos
|
|
223
|
+
transformRequest: [(data) => data], // Evitar transformación automática
|
|
224
|
+
proxy: false // Desactivar proxy si está causando problemas
|
|
225
|
+
};
|
|
226
|
+
console.log("Enviando petición GET a:", options.url);
|
|
227
|
+
// Realizar la petición a la API usando axios explícitamente como GET
|
|
228
|
+
const response = yield axios_1.default.get(`${url}?idUnidad=${unidad}`, {
|
|
229
|
+
headers: options.headers,
|
|
230
|
+
timeout: options.timeout,
|
|
231
|
+
proxy: false
|
|
232
|
+
});
|
|
233
|
+
if (response.status === 200) {
|
|
234
|
+
// console.log("Respuesta exitosa de GetGerencia", response.data);
|
|
235
|
+
return response.data;
|
|
236
|
+
}
|
|
237
|
+
else {
|
|
238
|
+
console.error("Error en getGerencia: Respuesta no exitosa", response.status);
|
|
239
|
+
// Si hay error, devolver un objeto con la unidad original
|
|
240
|
+
return { C_ID_UNIDAD: unidad, Hijas: [] };
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
catch (error) {
|
|
244
|
+
console.error("Error en getGerencia:", error);
|
|
245
|
+
// Si hay error, devolver un objeto con la unidad original
|
|
246
|
+
return { C_ID_UNIDAD: unidad, Hijas: [] };
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
exports.getGerencia = getGerencia;
|
|
251
|
+
/**
|
|
252
|
+
* Obtiene los IDs de todas las unidades subordinadas
|
|
253
|
+
*/
|
|
254
|
+
function getChildrenUnitIds(searchUnitId) {
|
|
255
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
256
|
+
if (!searchUnitId) {
|
|
257
|
+
return [];
|
|
258
|
+
}
|
|
259
|
+
// Verificar caché
|
|
260
|
+
const cacheKey = `unidades_${searchUnitId}`;
|
|
261
|
+
if (unidadesCache[cacheKey] && unidadesCache[cacheKey].timestamp > Date.now() - CACHE_TTL) {
|
|
262
|
+
return [...unidadesCache[cacheKey].unidades];
|
|
263
|
+
}
|
|
264
|
+
try {
|
|
265
|
+
// Para manejar el timeout, seguimos necesitando Promise.race
|
|
266
|
+
const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error("Timeout obteniendo unidades")), 30000));
|
|
267
|
+
// Función para obtener las unidades
|
|
268
|
+
function getUnidades() {
|
|
269
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
270
|
+
try {
|
|
271
|
+
// Obtener la gerencia
|
|
272
|
+
const gerencia = yield getGerencia(searchUnitId);
|
|
273
|
+
// Array para almacenar todos los IDs de unidades
|
|
274
|
+
const unidades = [searchUnitId];
|
|
275
|
+
// Función recursiva para extraer IDs de la estructura jerárquica
|
|
276
|
+
function extraerUnidades(nodo) {
|
|
277
|
+
if (nodo.C_ID_UNIDAD && nodo.C_ID_UNIDAD !== searchUnitId) {
|
|
278
|
+
unidades.push(nodo.C_ID_UNIDAD);
|
|
279
|
+
}
|
|
280
|
+
// Procesar unidades hijas recursivamente
|
|
281
|
+
if (nodo.Hijas && Array.isArray(nodo.Hijas)) {
|
|
282
|
+
for (const hija of nodo.Hijas) {
|
|
283
|
+
extraerUnidades(hija);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
// Procesar la estructura jerárquica
|
|
288
|
+
extraerUnidades(gerencia);
|
|
289
|
+
// Eliminar duplicados
|
|
290
|
+
return [...new Set(unidades)];
|
|
291
|
+
}
|
|
292
|
+
catch (error) {
|
|
293
|
+
console.warn(`Error procesando gerencia para ${searchUnitId}:`, error);
|
|
294
|
+
return [searchUnitId];
|
|
295
|
+
}
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
// Seguimos necesitando Promise.race para el timeout
|
|
299
|
+
let unidades;
|
|
300
|
+
try {
|
|
301
|
+
unidades = yield Promise.race([getUnidades(), timeoutPromise]);
|
|
302
|
+
}
|
|
303
|
+
catch (error) {
|
|
304
|
+
console.warn(`Error o timeout obteniendo unidades para ${searchUnitId}:`, error);
|
|
305
|
+
unidades = [searchUnitId];
|
|
306
|
+
}
|
|
307
|
+
// Guardar en caché
|
|
308
|
+
unidadesCache[cacheKey] = {
|
|
309
|
+
timestamp: Date.now(),
|
|
310
|
+
unidades: unidades
|
|
311
|
+
};
|
|
312
|
+
return unidades;
|
|
313
|
+
}
|
|
314
|
+
catch (error) {
|
|
315
|
+
console.warn(`Error en getChildrenUnitIds para ${searchUnitId}:`, error);
|
|
316
|
+
return [searchUnitId];
|
|
317
|
+
}
|
|
318
|
+
});
|
|
319
|
+
}
|
|
320
|
+
exports.getChildrenUnitIds = getChildrenUnitIds;
|
|
321
|
+
const unidadesJoinFuncion = (unidad) => __awaiter(void 0, void 0, void 0, function* () {
|
|
322
|
+
let unidades = [];
|
|
323
|
+
try {
|
|
324
|
+
yield (0, connection_sql_1.getConnection)(`select * from CodigosDeUbicacion where hijos like '%${unidad}%'`).then(resp => {
|
|
325
|
+
let hijos = JSON.parse(resp.recordset[0].hijos);
|
|
326
|
+
for (let i of hijos) {
|
|
327
|
+
let label = i.label.split('-')[1];
|
|
328
|
+
unidades.push(label.trim());
|
|
329
|
+
if (i.children) {
|
|
330
|
+
for (let o of i.children) {
|
|
331
|
+
let label = o.label.split('-')[1];
|
|
332
|
+
unidades.push(label.trim());
|
|
333
|
+
if (o.children) {
|
|
334
|
+
for (let u of o.children) {
|
|
335
|
+
let label = u.label.split('-')[1];
|
|
336
|
+
unidades.push(label.trim());
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
catch (error) {
|
|
345
|
+
console.error("Error unidadesJoinFuncion", error);
|
|
346
|
+
}
|
|
347
|
+
return unidades;
|
|
348
|
+
});
|
|
349
|
+
exports.unidadesJoinFuncion = unidadesJoinFuncion;
|
|
350
|
+
const obtenerUnidadPadre = (unidadABuscar) => __awaiter(void 0, void 0, void 0, function* () {
|
|
351
|
+
function findParent(organigrama, codigoUnidad, parent) {
|
|
352
|
+
for (const unidad of organigrama) {
|
|
353
|
+
const codigo = unidad.label.split(' - ').pop(); // Extrae el código de la unidad
|
|
354
|
+
if (codigo === codigoUnidad) {
|
|
355
|
+
return parent ? parent.label.split(' - ').pop() : null;
|
|
356
|
+
}
|
|
357
|
+
// Si tiene hijos, los recorremos recursivamente
|
|
358
|
+
if (unidad.children.length > 0) {
|
|
359
|
+
const result = findParent(unidad.children, codigoUnidad, unidad);
|
|
360
|
+
if (result) {
|
|
361
|
+
return result;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
return null;
|
|
366
|
+
}
|
|
367
|
+
const queryResp = yield (0, connection_sql_1.getConnection)(`select * from CodigosDeUbicacion where hijos like '%${unidadABuscar}%'`);
|
|
368
|
+
const organigrama = JSON.parse(queryResp.recordset[0].hijos);
|
|
369
|
+
console.log(organigrama);
|
|
370
|
+
return findParent(organigrama, unidadABuscar);
|
|
371
|
+
});
|
|
372
|
+
exports.obtenerUnidadPadre = obtenerUnidadPadre;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.validarCampos = void 0;
|
|
4
|
+
const express_validator_1 = require("express-validator");
|
|
5
|
+
const validarCampos = (req, res, next) => {
|
|
6
|
+
let errores = (0, express_validator_1.validationResult)(req);
|
|
7
|
+
if (!errores.isEmpty()) {
|
|
8
|
+
return res.status(400).json({
|
|
9
|
+
status: "error en los parametros",
|
|
10
|
+
mensaje: errores.mapped()
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
next();
|
|
14
|
+
};
|
|
15
|
+
exports.validarCampos = validarCampos;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.validarRol = void 0;
|
|
4
|
+
function validarRol(rolRequerido) {
|
|
5
|
+
if (typeof rolRequerido != 'string')
|
|
6
|
+
throw new Error("Debe enviar un rol requerido");
|
|
7
|
+
return function (req, res, next) {
|
|
8
|
+
try {
|
|
9
|
+
if (!req.body.usuario.roles.includes(rolRequerido)) {
|
|
10
|
+
return res.status(401).json({ "error": "No tiene permisos para usar esta funcionalidad" });
|
|
11
|
+
}
|
|
12
|
+
next();
|
|
13
|
+
}
|
|
14
|
+
catch (error) {
|
|
15
|
+
return res.status(500).json({ "error": `${error}` });
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
exports.validarRol = validarRol;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.validarGerencia = exports.validarNivel = void 0;
|
|
4
|
+
function validarNivel(nivelRequerido) {
|
|
5
|
+
return function (req, res, next) {
|
|
6
|
+
// Aquí podrías validar el nivel de usuario
|
|
7
|
+
try {
|
|
8
|
+
if (req.body.nivelNumero < nivelRequerido) {
|
|
9
|
+
// Si el usuario no tiene el nivel de acceso necesario, devuelve un error
|
|
10
|
+
return res.status(401).json({ "error": "No tiene permisos para usar esta funcionalidad" });
|
|
11
|
+
}
|
|
12
|
+
// Si el usuario tiene el nivel de acceso necesario, llama al siguiente middleware o al controlador final
|
|
13
|
+
next();
|
|
14
|
+
}
|
|
15
|
+
catch (error) {
|
|
16
|
+
return res.status(500).json({ "error": `${error}` });
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
exports.validarNivel = validarNivel;
|
|
21
|
+
function validarGerencia(gerenciaRequerido) {
|
|
22
|
+
return function (req, res, next) {
|
|
23
|
+
// Aquí podrías validar gerencia de usuario
|
|
24
|
+
try {
|
|
25
|
+
if (req.body.usuario.nombreGerencia != gerenciaRequerido) {
|
|
26
|
+
// Si el usuario no tiene el nivel de acceso necesario, devuelve un error
|
|
27
|
+
return res.status(401).json({ "error": "No tiene permisos para usar esta funcionalidad" });
|
|
28
|
+
}
|
|
29
|
+
// Si el usuario tiene el nivel de acceso necesario, llama al siguiente middleware o al controlador final
|
|
30
|
+
next();
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
return res.status(500).json({ "error": `${error}` });
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
exports.validarGerencia = validarGerencia;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.HttpsServidor = void 0;
|
|
7
|
+
const cors_1 = __importDefault(require("cors"));
|
|
8
|
+
const express_1 = __importDefault(require("express"));
|
|
9
|
+
const morgan_body_1 = __importDefault(require("morgan-body"));
|
|
10
|
+
const fs_1 = __importDefault(require("fs"));
|
|
11
|
+
const path_1 = __importDefault(require("path"));
|
|
12
|
+
const https_1 = __importDefault(require("https"));
|
|
13
|
+
require('dotenv').config({ path: './.env' });
|
|
14
|
+
const swagger_1 = __importDefault(require("../docs/swagger"));
|
|
15
|
+
class HttpsServidor {
|
|
16
|
+
constructor() {
|
|
17
|
+
this.expressApp = (0, express_1.default)();
|
|
18
|
+
this.port = process.env.PORT;
|
|
19
|
+
this.httpsServer = this.createHttpsServer();
|
|
20
|
+
this.useCors();
|
|
21
|
+
this.useJson();
|
|
22
|
+
this.srvio = this.start();
|
|
23
|
+
}
|
|
24
|
+
useLogger() {
|
|
25
|
+
const log = fs_1.default.createWriteStream(path_1.default.join(__dirname, "logs", "express.log"), { flags: "a" });
|
|
26
|
+
(0, morgan_body_1.default)(this.expressApp, {
|
|
27
|
+
// .. other settings
|
|
28
|
+
noColors: true,
|
|
29
|
+
stream: log,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
useRoutes(router) {
|
|
33
|
+
this.expressApp.use("/", router);
|
|
34
|
+
}
|
|
35
|
+
useCors() {
|
|
36
|
+
this.expressApp.use(express_1.default.urlencoded({ extended: true }));
|
|
37
|
+
this.expressApp.use((0, cors_1.default)());
|
|
38
|
+
}
|
|
39
|
+
useJson() {
|
|
40
|
+
this.expressApp.use(express_1.default.json());
|
|
41
|
+
}
|
|
42
|
+
start() {
|
|
43
|
+
if (process.env.NODE_ENV !== 'test') {
|
|
44
|
+
return this.httpsServer.listen(this.port, () => {
|
|
45
|
+
(0, swagger_1.default)(this.expressApp, this.port);
|
|
46
|
+
console.log("Servidor levantado en :", this.port);
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
createHttpsServer() {
|
|
51
|
+
const privateKeyBase64 = process.env.SSL_PRIVATE_KEY_BASE64;
|
|
52
|
+
const certificateBase64 = process.env.SSL_CERTIFICATE_BASE64;
|
|
53
|
+
const privateKey = Buffer.from(privateKeyBase64, 'base64').toString('utf8');
|
|
54
|
+
const certificate = Buffer.from(certificateBase64, 'base64').toString('utf8');
|
|
55
|
+
const credentials = { key: privateKey, cert: certificate };
|
|
56
|
+
return https_1.default.createServer(credentials, this.expressApp);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
exports.HttpsServidor = HttpsServidor;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.Servidor = void 0;
|
|
7
|
+
const cors_1 = __importDefault(require("cors"));
|
|
8
|
+
const express_1 = __importDefault(require("express"));
|
|
9
|
+
const morgan_body_1 = __importDefault(require("morgan-body"));
|
|
10
|
+
const fs_1 = __importDefault(require("fs"));
|
|
11
|
+
const path_1 = __importDefault(require("path"));
|
|
12
|
+
const http_1 = __importDefault(require("http"));
|
|
13
|
+
require('dotenv').config({ path: './.env' });
|
|
14
|
+
const swagger_1 = __importDefault(require("../docs/swagger"));
|
|
15
|
+
class Servidor {
|
|
16
|
+
constructor() {
|
|
17
|
+
this.expressApp = (0, express_1.default)();
|
|
18
|
+
this.port = process.env.PORT;
|
|
19
|
+
this.httpServer = new http_1.default.Server(this.expressApp);
|
|
20
|
+
this.useCors();
|
|
21
|
+
this.useJson();
|
|
22
|
+
this.srvio = this.start();
|
|
23
|
+
}
|
|
24
|
+
useLogger() {
|
|
25
|
+
const log = fs_1.default.createWriteStream(path_1.default.join(__dirname, "logs", "express.log"), { flags: "a" });
|
|
26
|
+
(0, morgan_body_1.default)(this.expressApp, {
|
|
27
|
+
// .. other settings
|
|
28
|
+
noColors: true,
|
|
29
|
+
stream: log,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
useRoutes(router) {
|
|
33
|
+
this.expressApp.use("/", router);
|
|
34
|
+
}
|
|
35
|
+
useCors() {
|
|
36
|
+
this.expressApp.use(express_1.default.urlencoded({ extended: true }));
|
|
37
|
+
// this.expressApp.use(cors({origin:true, credentials:true}));
|
|
38
|
+
this.expressApp.use((0, cors_1.default)());
|
|
39
|
+
}
|
|
40
|
+
useJson() {
|
|
41
|
+
this.expressApp.use(express_1.default.json());
|
|
42
|
+
}
|
|
43
|
+
start() {
|
|
44
|
+
let srv;
|
|
45
|
+
if (process.env.NODE_ENV !== 'test') {
|
|
46
|
+
return srv = this.httpServer.listen(this.port, () => {
|
|
47
|
+
(0, swagger_1.default)(this.expressApp, this.port);
|
|
48
|
+
console.log("Servidor levantado en :", this.port);
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
return srv;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
exports.Servidor = Servidor;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.SocketClient = void 0;
|
|
7
|
+
const socket_io_client_1 = __importDefault(require("socket.io-client"));
|
|
8
|
+
class SocketClient {
|
|
9
|
+
constructor(url) {
|
|
10
|
+
this.url = url;
|
|
11
|
+
this.socket = (0, socket_io_client_1.default)(this.url);
|
|
12
|
+
this.setupListeners();
|
|
13
|
+
}
|
|
14
|
+
setupListeners() {
|
|
15
|
+
this.socket.on('connect', () => {
|
|
16
|
+
console.log('Conectado al servidor');
|
|
17
|
+
});
|
|
18
|
+
this.socket.on('disconnect', () => {
|
|
19
|
+
console.log('Desconectado del servidor');
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
exports.SocketClient = SocketClient;
|