fpavon-ee-shared 1.0.46 → 1.0.49

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.
@@ -9,4 +9,5 @@ export declare class DocumentosUseCase {
9
9
  getDocumentoAdjunto: (uuid: string) => Promise<DocumentoFTP>;
10
10
  deleteDocumento: (uuid: any) => Promise<Boolean>;
11
11
  generarPinDeFirmaUseCase: (registrosDeFirma: any) => Promise<any>;
12
+ firmarDocumentoUseCase: (registrosDeFirma: any, documento: any) => Promise<void>;
12
13
  }
@@ -57,6 +57,11 @@ class DocumentosUseCase {
57
57
  yield this.documentosRepository.insertPinDeFirma(registrosDeFirma);
58
58
  return registrosDeFirma;
59
59
  });
60
+ this.firmarDocumentoUseCase = (registrosDeFirma, documento) => __awaiter(this, void 0, void 0, function* () {
61
+ const file = documento.upload[0];
62
+ const doc = yield this.documentosRepository.createDocumento(new documentoFTP_1.DocumentoFTP(file));
63
+ return yield this.documentosRepository.firmarDocumentoEvent(registrosDeFirma, doc.uuid);
64
+ });
60
65
  }
61
66
  bufferToStream(buffer) {
62
67
  return new stream_1.Readable({
@@ -9,5 +9,6 @@ export interface IDocumentosRepository {
9
9
  modifyDocumento(documentoModificado: IDocumentoFTP): Promise<IDocumentoFTP>;
10
10
  ver(params: any): any;
11
11
  buscarPinesActivosPorUsuario(firmanteUid: string): Promise<any>;
12
- insertPinDeFirma(pin: any): Promise<IDocumentoFTP>;
12
+ insertPinDeFirma(pin: any): Promise<any>;
13
+ firmarDocumentoEvent(registrosDeFirma: any, uuid_firmado: string): Promise<void>;
13
14
  }
@@ -11,7 +11,7 @@ export declare class DocumentosFTPRepository implements IDocumentosRepository {
11
11
  deleteDocumento(uuid: any): Promise<Boolean>;
12
12
  modifyDocumento(documentoModificado: IDocumentoFTP): Promise<IDocumentoFTP>;
13
13
  ver(params: any): Promise<void>;
14
- insertPinDeFirma(pin: any): Promise<IDocumentoFTP>;
14
+ insertPinDeFirma(pin: any): Promise<any>;
15
15
  /**
16
16
  * Verifica si un PIN específico ya está activo (DocumentoUuidFirmado IS NULL)
17
17
  * para el usuario dado.
@@ -20,4 +20,12 @@ export declare class DocumentosFTPRepository implements IDocumentosRepository {
20
20
  * @returns {Promise<IRegistroDeFirma | undefined>} El registro si existe un conflicto, o undefined.
21
21
  */
22
22
  buscarPinesActivosPorUsuario(firmanteUid: string): Promise<any>;
23
+ /**
24
+ * Actualiza el registro de PIN activo a un estado 'Firmado'.
25
+ *
26
+ * @param registrosDeFirma Es el objeto registro de firma local.
27
+ * @param uuid_firmado Nuevo UUID generado para el documento firmado (campo 'UUID_FIRMADO').
28
+ * @returns {Promise<void>}
29
+ */
30
+ firmarDocumentoEvent(registrosDeFirma: any, uuid_firmado: any): Promise<void>;
23
31
  }
@@ -18,6 +18,7 @@ const documentoFTP_1 = require("../../domain/documentoFTP");
18
18
  const fs_1 = require("fs");
19
19
  const connection_sql_1 = require("../../../infrastructure/bd/connection.sql");
20
20
  const mssql_1 = __importDefault(require("mssql"));
21
+ const axios_1 = __importDefault(require("axios"));
21
22
  class DocumentosFTPRepository {
22
23
  constructor(fptClient) {
23
24
  this.fptClient = fptClient;
@@ -190,6 +191,7 @@ class DocumentosFTPRepository {
190
191
  request.input("UUID_FIRMADO", mssql_1.default.UniqueIdentifier, pin.UUID_FIRMADO);
191
192
  request.input("FECHA_FIRMA", mssql_1.default.Date, pin.FECHA_FIRMA);
192
193
  request.input("USUARIO", mssql_1.default.VarChar(10), pin.USUARIO);
194
+ request.input("TOKEN", mssql_1.default.VarChar(), pin.TOKEN);
193
195
  // 2. Ejecutar la consulta INSERT adaptada a la nueva tabla
194
196
  const insertResult = yield request.query(`
195
197
  INSERT INTO dbo.FirmaCertificadoLocal (
@@ -199,7 +201,8 @@ class DocumentosFTPRepository {
199
201
  FIRMADO,
200
202
  UUID_FIRMADO,
201
203
  FECHA_FIRMA,
202
- USUARIO
204
+ USUARIO,
205
+ TOKEN
203
206
  )
204
207
  VALUES (
205
208
  @PIN,
@@ -208,7 +211,8 @@ class DocumentosFTPRepository {
208
211
  @FIRMADO,
209
212
  @UUID_FIRMADO,
210
213
  @FECHA_FIRMA,
211
- @USUARIO
214
+ @USUARIO,
215
+ @TOKEN
212
216
  )`);
213
217
  // MUY IMPORTANTE: Verifica que la inserción afecte 1 fila.
214
218
  if (insertResult.rowsAffected[0] === 0) {
@@ -264,5 +268,83 @@ class DocumentosFTPRepository {
264
268
  }
265
269
  });
266
270
  }
271
+ /**
272
+ * Actualiza el registro de PIN activo a un estado 'Firmado'.
273
+ *
274
+ * @param registrosDeFirma Es el objeto registro de firma local.
275
+ * @param uuid_firmado Nuevo UUID generado para el documento firmado (campo 'UUID_FIRMADO').
276
+ * @returns {Promise<void>}
277
+ */
278
+ firmarDocumentoEvent(registrosDeFirma, uuid_firmado) {
279
+ return __awaiter(this, void 0, void 0, function* () {
280
+ let started = false;
281
+ // 💡 Usamos getDbPool() (Singleton) para garantizar la conexión única y estable.
282
+ const pool = yield (0, connection_sql_1.getConnectionForTransaction)();
283
+ const transaction = new mssql_1.default.Transaction(pool);
284
+ try {
285
+ const codigoInterno = registrosDeFirma.CODIGO_INTERNO;
286
+ let endpoint = '';
287
+ const URL_CC = process.env.URL_CC;
288
+ if (codigoInterno && codigoInterno.endsWith('CC') || codigoInterno.endsWith('CO')) {
289
+ endpoint = `${URL_CC}/solicitudes/codigoInterno/${codigoInterno}/firmar`;
290
+ }
291
+ else if (codigoInterno && codigoInterno.endsWith('PR')) {
292
+ endpoint = `${URL_CC}/solicitudes/codigoInterno/${codigoInterno}/firmar`;
293
+ }
294
+ else {
295
+ console.error(`Código Interno '${codigoInterno}' no coincide con patrón de notificación. Llamada a API omitida.`);
296
+ throw new Error(`Error DocumentosFTPRepository.firmarDocumentoEvent Código Interno '${codigoInterno}' no coincide con patrón de notificación. Llamada a API omitida.`);
297
+ }
298
+ const apiBody = {
299
+ uuidDocumentoFirmado: registrosDeFirma.UUID_FIRMADO,
300
+ };
301
+ // 6. Realizar la Llamada Axios
302
+ const apiResponse = yield axios_1.default.post(endpoint, apiBody, {
303
+ headers: {
304
+ // Formato estándar: 'Bearer ' + token
305
+ 'Authorization': `Bearer ${registrosDeFirma.token}`,
306
+ 'Content-Type': 'application/json'
307
+ }
308
+ });
309
+ if (apiResponse.status !== 200)
310
+ throw new Error("Ocurrió un errror al firmar el documento.");
311
+ yield transaction.begin();
312
+ started = true;
313
+ const request = transaction.request();
314
+ // 1. Definición de Parámetros (Inputs)
315
+ request.input("UuidOriginal", mssql_1.default.UniqueIdentifier, registrosDeFirma.UUID);
316
+ request.input("NewUuidFirmado", mssql_1.default.UniqueIdentifier, registrosDeFirma.UUID_FIRMADO);
317
+ request.input("FechaFirmaActual", mssql_1.default.DateTime2, new Date()); // Fecha y hora actual
318
+ // 2. Consulta UPDATE adaptada a dbo.FirmaCertificadoLocal
319
+ const updateResult = yield request.query(`
320
+ UPDATE dbo.FirmaCertificadoLocal
321
+ SET
322
+ FIRMADO = 1, -- Marca el documento como firmado (True)
323
+ UUID_FIRMADO = @NewUuidFirmado, -- Asigna el nuevo UUID al documento firmado
324
+ FECHA_FIRMA = @FechaFirmaActual -- Registra la fecha y hora de la firma
325
+ WHERE
326
+ UUID = @UuidOriginal -- Busca el registro por el UUID original del documento
327
+ AND UUID_FIRMADO IS NULL; -- Y solo actualiza si el registro aún está pendiente
328
+ `);
329
+ if (updateResult.rowsAffected[0] === 0) {
330
+ yield transaction.rollback();
331
+ throw new Error(`No se encontró un registro activo (UUID: ${registrosDeFirma.UUID}) o ya estaba firmado.`);
332
+ }
333
+ yield transaction.commit();
334
+ }
335
+ catch (error) {
336
+ if (started) {
337
+ try {
338
+ yield transaction.rollback();
339
+ }
340
+ catch (rollbackError) {
341
+ console.error("Error en rollback:", rollbackError);
342
+ }
343
+ }
344
+ console.error(`Error DocumentosSqlRepository.firmarDocumentoEvent: ${error.message}`);
345
+ throw error;
346
+ }
347
+ });
348
+ }
267
349
  }
268
350
  exports.DocumentosFTPRepository = DocumentosFTPRepository;
@@ -1,6 +1,7 @@
1
1
  import { Readable } from "stream";
2
2
  import { IDocumentosRepository } from "../domain/documento.repository";
3
3
  import { DocumentoFTP } from "../domain/documentoFTP";
4
+ import { Documento } from "../domain/documento.class";
4
5
 
5
6
  export class DocumentosUseCase{
6
7
  constructor(private readonly documentosRepository: IDocumentosRepository) {}
@@ -66,4 +67,10 @@ export class DocumentosUseCase{
66
67
  return registrosDeFirma;
67
68
  }
68
69
 
70
+ firmarDocumentoUseCase = async (registrosDeFirma:any, documento)=>{
71
+ const file = documento.upload[0];
72
+ const doc = await this.documentosRepository.createDocumento(new DocumentoFTP(file));
73
+ return await this.documentosRepository.firmarDocumentoEvent(registrosDeFirma, doc.uuid);
74
+ }
75
+
69
76
  }
@@ -10,6 +10,7 @@ export interface IDocumentosRepository {
10
10
  modifyDocumento(documentoModificado: IDocumentoFTP):Promise<IDocumentoFTP>;
11
11
  ver(params):any;
12
12
  buscarPinesActivosPorUsuario(firmanteUid: string): Promise<any>;
13
- insertPinDeFirma(pin:any): Promise<IDocumentoFTP>;
14
-
13
+ insertPinDeFirma(pin:any): Promise<any>;
14
+ firmarDocumentoEvent(registrosDeFirma:any, uuid_firmado:string): Promise<void>
15
+
15
16
  }
@@ -6,6 +6,7 @@ import { DocumentoFTP, IDocumentoFTP } from "../../domain/documentoFTP";
6
6
  import { createReadStream } from "fs";
7
7
  import { getConnectionForTransaction } from "../../../infrastructure/bd/connection.sql";
8
8
  import sql from "mssql";
9
+ import axios from "axios";
9
10
 
10
11
 
11
12
  export class DocumentosFTPRepository implements IDocumentosRepository{
@@ -169,7 +170,7 @@ export class DocumentosFTPRepository implements IDocumentosRepository{
169
170
  }
170
171
  }
171
172
 
172
- async insertPinDeFirma(pin: any): Promise<IDocumentoFTP> {
173
+ async insertPinDeFirma(pin: any): Promise<any> {
173
174
  let started = false;
174
175
 
175
176
  // NOTA: Usar getDbPool() (Singleton) es lo más recomendable para estabilidad.
@@ -191,6 +192,8 @@ export class DocumentosFTPRepository implements IDocumentosRepository{
191
192
  request.input("UUID_FIRMADO", sql.UniqueIdentifier, pin.UUID_FIRMADO);
192
193
  request.input("FECHA_FIRMA", sql.Date, pin.FECHA_FIRMA);
193
194
  request.input("USUARIO", sql.VarChar(10), pin.USUARIO);
195
+ request.input("TOKEN", sql.VarChar(), pin.TOKEN);
196
+
194
197
 
195
198
  // 2. Ejecutar la consulta INSERT adaptada a la nueva tabla
196
199
  const insertResult = await request.query(`
@@ -201,7 +204,8 @@ export class DocumentosFTPRepository implements IDocumentosRepository{
201
204
  FIRMADO,
202
205
  UUID_FIRMADO,
203
206
  FECHA_FIRMA,
204
- USUARIO
207
+ USUARIO,
208
+ TOKEN
205
209
  )
206
210
  VALUES (
207
211
  @PIN,
@@ -210,7 +214,8 @@ export class DocumentosFTPRepository implements IDocumentosRepository{
210
214
  @FIRMADO,
211
215
  @UUID_FIRMADO,
212
216
  @FECHA_FIRMA,
213
- @USUARIO
217
+ @USUARIO,
218
+ @TOKEN
214
219
  )`);
215
220
 
216
221
  // MUY IMPORTANTE: Verifica que la inserción afecte 1 fila.
@@ -272,4 +277,91 @@ export class DocumentosFTPRepository implements IDocumentosRepository{
272
277
  }
273
278
  }
274
279
 
280
+ /**
281
+ * Actualiza el registro de PIN activo a un estado 'Firmado'.
282
+ *
283
+ * @param registrosDeFirma Es el objeto registro de firma local.
284
+ * @param uuid_firmado Nuevo UUID generado para el documento firmado (campo 'UUID_FIRMADO').
285
+ * @returns {Promise<void>}
286
+ */
287
+ public async firmarDocumentoEvent(registrosDeFirma:any, uuid_firmado:any): Promise<void> {
288
+ let started = false;
289
+
290
+ // 💡 Usamos getDbPool() (Singleton) para garantizar la conexión única y estable.
291
+ const pool = await getConnectionForTransaction();
292
+
293
+ const transaction = new sql.Transaction(pool);
294
+
295
+ try {
296
+ const codigoInterno = registrosDeFirma.CODIGO_INTERNO as string;
297
+ let endpoint = '';
298
+ const URL_CC = process.env.URL_CC;
299
+ if (codigoInterno && codigoInterno.endsWith('CC') || codigoInterno.endsWith('CO')) {
300
+ endpoint = `${URL_CC}/solicitudes/codigoInterno/${codigoInterno}/firmar`;
301
+ } else if (codigoInterno && codigoInterno.endsWith('PR')) {
302
+ endpoint = `${URL_CC}/solicitudes/codigoInterno/${codigoInterno}/firmar`;
303
+
304
+ }else {
305
+ console.error(`Código Interno '${codigoInterno}' no coincide con patrón de notificación. Llamada a API omitida.`);
306
+ throw new Error(`Error DocumentosFTPRepository.firmarDocumentoEvent Código Interno '${codigoInterno}' no coincide con patrón de notificación. Llamada a API omitida.`)
307
+ }
308
+
309
+ const apiBody = {
310
+ uuidDocumentoFirmado: registrosDeFirma.UUID_FIRMADO,
311
+ };
312
+
313
+ // 6. Realizar la Llamada Axios
314
+ const apiResponse = await axios.post(endpoint, apiBody,
315
+ {
316
+ headers: {
317
+ // Formato estándar: 'Bearer ' + token
318
+ 'Authorization': `Bearer ${registrosDeFirma.token}`,
319
+ 'Content-Type': 'application/json'
320
+ }
321
+ }
322
+ );
323
+
324
+ if(apiResponse.status !== 200) throw new Error("Ocurrió un errror al firmar el documento.")
325
+
326
+ await transaction.begin();
327
+ started = true;
328
+
329
+ const request = transaction.request();
330
+
331
+ // 1. Definición de Parámetros (Inputs)
332
+ request.input("UuidOriginal", sql.UniqueIdentifier, registrosDeFirma.UUID);
333
+ request.input("NewUuidFirmado", sql.UniqueIdentifier, registrosDeFirma.UUID_FIRMADO);
334
+ request.input("FechaFirmaActual", sql.DateTime2, new Date()); // Fecha y hora actual
335
+
336
+ // 2. Consulta UPDATE adaptada a dbo.FirmaCertificadoLocal
337
+ const updateResult = await request.query(`
338
+ UPDATE dbo.FirmaCertificadoLocal
339
+ SET
340
+ FIRMADO = 1, -- Marca el documento como firmado (True)
341
+ UUID_FIRMADO = @NewUuidFirmado, -- Asigna el nuevo UUID al documento firmado
342
+ FECHA_FIRMA = @FechaFirmaActual -- Registra la fecha y hora de la firma
343
+ WHERE
344
+ UUID = @UuidOriginal -- Busca el registro por el UUID original del documento
345
+ AND UUID_FIRMADO IS NULL; -- Y solo actualiza si el registro aún está pendiente
346
+ `);
347
+
348
+ if (updateResult.rowsAffected[0] === 0) {
349
+ await transaction.rollback();
350
+ throw new Error(`No se encontró un registro activo (UUID: ${registrosDeFirma.UUID}) o ya estaba firmado.`);
351
+ }
352
+
353
+ await transaction.commit();
354
+
355
+ } catch (error: any) {
356
+ if (started) {
357
+ try {
358
+ await transaction.rollback();
359
+ } catch (rollbackError) {
360
+ console.error("Error en rollback:", rollbackError);
361
+ }
362
+ }
363
+ console.error(`Error DocumentosSqlRepository.firmarDocumentoEvent: ${error.message}`);
364
+ throw error;
365
+ }
366
+ }
275
367
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fpavon-ee-shared",
3
- "version": "1.0.46",
3
+ "version": "1.0.49",
4
4
  "description": "Carpeta compartida entre servicios de Expediente Electronico",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",