apacuana-sdk-core 0.10.0 → 0.12.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.
Files changed (58) hide show
  1. package/README.md +305 -286
  2. package/coverage/clover.xml +345 -248
  3. package/coverage/coverage-final.json +9 -7
  4. package/coverage/lcov-report/index.html +41 -26
  5. package/coverage/lcov-report/src/api/certs.js.html +162 -87
  6. package/coverage/lcov-report/src/api/faceLiveness.js.html +523 -0
  7. package/coverage/lcov-report/src/api/index.html +43 -28
  8. package/coverage/lcov-report/src/api/revocations.js.html +132 -90
  9. package/coverage/lcov-report/src/api/signatures.js.html +25 -253
  10. package/coverage/lcov-report/src/api/users.js.html +23 -14
  11. package/coverage/lcov-report/src/config/index.html +1 -1
  12. package/coverage/lcov-report/src/config/index.js.html +1 -1
  13. package/coverage/lcov-report/src/errors/index.html +1 -1
  14. package/coverage/lcov-report/src/errors/index.js.html +8 -8
  15. package/coverage/lcov-report/src/index.html +13 -13
  16. package/coverage/lcov-report/src/index.js.html +96 -12
  17. package/coverage/lcov-report/src/success/index.html +116 -0
  18. package/coverage/lcov-report/src/success/index.js.html +106 -0
  19. package/coverage/lcov-report/src/utils/constant.js.html +4 -4
  20. package/coverage/lcov-report/src/utils/helpers.js.html +1 -1
  21. package/coverage/lcov-report/src/utils/httpClient.js.html +1 -1
  22. package/coverage/lcov-report/src/utils/index.html +1 -1
  23. package/coverage/lcov.info +597 -414
  24. package/dist/api/certs.d.ts +9 -70
  25. package/dist/api/faceLiveness.d.ts +6 -0
  26. package/dist/api/revocations.d.ts +6 -42
  27. package/dist/api/signatures.d.ts +11 -153
  28. package/dist/api/users.d.ts +16 -6
  29. package/dist/index.d.ts +6 -0
  30. package/dist/index.js +513 -259
  31. package/dist/index.js.map +1 -1
  32. package/dist/index.mjs +513 -259
  33. package/dist/index.mjs.map +1 -1
  34. package/dist/success/index.d.ts +7 -0
  35. package/dist/types/certs.d.ts +97 -0
  36. package/dist/types/faceLiveness.d.ts +11 -0
  37. package/dist/types/revocations.d.ts +51 -0
  38. package/dist/types/signatures.d.ts +147 -0
  39. package/dist/types/users.d.ts +260 -0
  40. package/package.json +1 -1
  41. package/src/api/certs.js +74 -49
  42. package/src/api/faceLiveness.js +146 -0
  43. package/src/api/revocations.js +76 -62
  44. package/src/api/signatures.js +21 -97
  45. package/src/api/users.js +12 -9
  46. package/src/index.js +33 -5
  47. package/src/success/index.js +8 -0
  48. package/src/types/certs.js +56 -0
  49. package/src/types/faceLiveness.js +16 -0
  50. package/src/types/revocations.js +45 -0
  51. package/src/types/signatures.js +91 -0
  52. package/src/types/users.js +73 -0
  53. package/tests/api/certs.test.js +99 -6
  54. package/tests/api/faceLiveness.test.js +170 -0
  55. package/tests/api/revocations.test.js +35 -35
  56. package/tests/api/signatures.test.js +11 -5
  57. package/tests/api/users.test.js +3 -2
  58. package/tests/index.test.js +16 -8
package/src/api/users.js CHANGED
@@ -1,12 +1,18 @@
1
1
  import { httpRequest } from "../utils/httpClient";
2
2
  import { ApacuanaAPIError } from "../errors/index";
3
3
  import { getConfig } from "../config/index";
4
+ import ApacuanaSuccess from "../success";
4
5
 
5
6
  /**
6
- * @typedef {object} GetCustomerResponse
7
+ * @typedef {object} GetCustomerData
7
8
  * @property {string} token - El token de sesión del usuario.
8
9
  * @property {object} userData - Los datos del usuario obtenidos.
9
- * @property {boolean} success - Indica si la operación fue exitosa.
10
+ */
11
+
12
+ /**
13
+ * @typedef {object} GetCustomerResponse
14
+ * @property {true} success - Indica que la operación fue exitosa.
15
+ * @property {GetCustomerData} data - El payload de la respuesta.
10
16
  */
11
17
 
12
18
  /**
@@ -14,7 +20,7 @@ import { getConfig } from "../config/index";
14
20
  * Este método es útil para endpoints que requieren datos en el cuerpo de la petición
15
21
  * para buscar un usuario, como un ID de sesión o un token de acceso.
16
22
  *
17
- * @returns {Promise<GetCustomerResponse>} Objeto con el token de sesión, los datos del usuario y un indicador de éxito.
23
+ * @returns {Promise<GetCustomerResponse>} Una promesa que resuelve a un objeto con la respuesta exitosa.
18
24
  * @throws {Error} Si los parámetros de entrada son inválidos.
19
25
  * @throws {ApacuanaAPIError} Si ocurre un error en la API de Apacuana.
20
26
  */
@@ -49,19 +55,16 @@ const getCustomer = async () => {
49
55
  );
50
56
  }
51
57
 
52
- return {
58
+ return new ApacuanaSuccess({
53
59
  token: response.sessionid,
54
60
  userData: response.entry,
55
- success: true,
56
- };
61
+ });
57
62
  } catch (error) {
58
63
  if (error instanceof ApacuanaAPIError) {
59
64
  throw error;
60
65
  }
61
66
  throw new ApacuanaAPIError(
62
- `Unexpected failure getting token: ${
63
- error.message || "Unknown error"
64
- }`
67
+ `Unexpected failure getting token: ${error.message || "Unknown error"}`
65
68
  );
66
69
  }
67
70
  };
package/src/index.js CHANGED
@@ -7,6 +7,7 @@ import {
7
7
  getCertStatus,
8
8
  getCertTypes,
9
9
  getRequerimentsByTypeUser,
10
+ requestCertificate,
10
11
  } from "./api/certs";
11
12
  import {
12
13
  addSigner,
@@ -17,6 +18,12 @@ import {
17
18
  signDocument,
18
19
  uploadSignatureVariant,
19
20
  } from "./api/signatures";
21
+ import {
22
+ createFaceLivenessSession,
23
+ validateFaceLiveness,
24
+ } from "./api/faceLiveness";
25
+ import ApacuanaSuccess from "./success/index";
26
+ import { ApacuanaAPIError } from "./errors/index";
20
27
 
21
28
  const apacuana = {
22
29
  /**
@@ -37,21 +44,39 @@ const apacuana = {
37
44
  initHttpClient();
38
45
  const currentConfig = getConfig();
39
46
  if (!currentConfig.customerId) {
40
- throw new Error(
47
+ throw new ApacuanaAPIError(
41
48
  "Apacuana SDK: La configuración de CustomerId no se ha guardado" +
42
- " correctamente."
49
+ " correctamente.",
50
+ 400,
51
+ { code: "CONFIG_ERROR" }
43
52
  );
44
53
  }
45
- const { token, userData } = await getCustomer();
54
+
55
+ const customer = await getCustomer();
56
+ const { token, userData } = customer.data;
46
57
  setConfig({ ...currentConfig, token, userData });
47
58
  setAuthToken(token);
48
- return true;
59
+ return new ApacuanaSuccess({
60
+ initialized: true,
61
+ message: "SDK inicializado correctamente.",
62
+ });
49
63
  } catch (error) {
50
64
  // eslint-disable-next-line no-console
51
65
  console.error("Error durante la inicialización del SDK:", error);
52
- throw error;
66
+ if (error instanceof ApacuanaAPIError) {
67
+ throw error;
68
+ }
69
+ throw new ApacuanaAPIError(
70
+ error.message || "Error desconocido durante la inicialización.",
71
+ 500,
72
+ error
73
+ );
53
74
  }
54
75
  },
76
+
77
+ /**
78
+ * Permite obtener la configuración actual del SDK.
79
+ */
55
80
  close: () => close(),
56
81
  getConfig,
57
82
  requestRevocation,
@@ -68,6 +93,9 @@ const apacuana = {
68
93
  deleteSignatureVariant,
69
94
  getCertTypes,
70
95
  getRequerimentsByTypeUser,
96
+ createFaceLivenessSession,
97
+ validateFaceLiveness,
98
+ requestCertificate,
71
99
  };
72
100
 
73
101
  export default apacuana;
@@ -0,0 +1,8 @@
1
+ export default class ApacuanaSuccess {
2
+ constructor(data, statusCode = 200) {
3
+ this.success = true;
4
+ this.statusCode = statusCode;
5
+ this.name = "ApacuanaSuccess";
6
+ this.data = data;
7
+ }
8
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * @typedef {object} GenerateCertResponse
3
+ * @property {string} cert - El certificado generado en formato string.
4
+ * @property {string} certifiedid - El ID del certificado generado.
5
+ * @property {boolean} success - Indica si la operación fue exitosa.
6
+ */
7
+
8
+ /**
9
+ * @typedef {object} GetCertStatusResponse
10
+ * @property {string} status - El estado actual del certificado del usuario.
11
+ * @property {boolean} success - Indica si la operación fue exitosa.
12
+ */
13
+
14
+ /**
15
+ * @typedef {object} EncryptedCSRObject
16
+ * @property {string} csr - The encrypted Certificate Signing Request.
17
+ */
18
+
19
+ /**
20
+ * @typedef {object} CertType
21
+ * @property {string} id - The ID of the certificate type.
22
+ * @property {string} name - The name of the certificate type.
23
+ */
24
+
25
+ /**
26
+ * @typedef {object} GetCertTypesResponse
27
+ * @property {Array<CertType>} types - A list of available certificate types.
28
+ * @property {boolean} success - Indicates if the operation was successful.
29
+ */
30
+
31
+ /**
32
+ * @typedef {object} Requirement
33
+ * @property {string} id - The ID of the requirement.
34
+ * @property {string} description - The description of the requirement.
35
+ */
36
+
37
+ /**
38
+ * @typedef {object} GetRequirementsResponse
39
+ * @property {Array<Requirement>} requirements - A list of requirements for the user type.
40
+ * @property {boolean} success - Indicates if the operation was successful.
41
+ */
42
+
43
+ /**
44
+ * @typedef {object} CertificateRequestParams
45
+ * @property {number} type - The user type to get requirements for.
46
+ * @property {string} [observation] - An optional observation for the certificate request.
47
+ * @property {Array<{id: string, file: string}>} documents - The documents required for the certificate.
48
+ */
49
+
50
+ /**
51
+ * @typedef {object} RequestCertificateResponse
52
+ * @property {string} message - A message confirming the request.
53
+ * @property {boolean} success - Indicates if the operation was successful.
54
+ */
55
+
56
+ export {};
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @typedef {import('../success').ApacuanaSuccess} ApacuanaSuccess
3
+ */
4
+
5
+ /**
6
+ * @typedef {object} CreateFaceLivenessSessionData
7
+ * @property {string} sessionId - The session ID for the face liveness check.
8
+ */
9
+
10
+ /**
11
+ * @typedef {object} CreateFaceLivenessSessionResponse
12
+ * @property {true} success
13
+ * @property {CreateFaceLivenessSessionData} data
14
+ */
15
+
16
+ export {};
@@ -0,0 +1,45 @@
1
+ /**
2
+ * @typedef {import('../success').ApacuanaSuccess} ApacuanaSuccess
3
+ */
4
+
5
+ /**
6
+ * @typedef {object} RevocationReason
7
+ * @property {string} code - The code for the revocation reason.
8
+ * @property {string} description - The description of the revocation reason.
9
+ */
10
+
11
+ /**
12
+ * @typedef {object} RequestRevocationData
13
+ * @property {string} message - A message providing details about the outcome.
14
+ */
15
+
16
+ /**
17
+ * @typedef {object} RequestRevocationResponse
18
+ * @property {true} success
19
+ * @property {RequestRevocationData} data
20
+ */
21
+
22
+ /**
23
+ * @typedef {object} GetRevocationReasonsData
24
+ * @property {RevocationReason[]} reasons - A list of revocation reasons.
25
+ */
26
+
27
+ /**
28
+ * @typedef {object} GetRevocationReasonsResponse
29
+ * @property {true} success
30
+ * @property {GetRevocationReasonsData} data
31
+ */
32
+
33
+ /**
34
+ * @typedef {object} RevocationResponse
35
+ * @property {boolean} success - Indicates if the revocation request was successful.
36
+ * @property {string} [message] - A message providing details about the outcome.
37
+ */
38
+
39
+ /**
40
+ * @typedef {object} RevocationReasonsResponse
41
+ * @property {boolean} success - Indicates if the request was successful.
42
+ * @property {RevocationReason[]} reasons - A list of revocation reasons.
43
+ */
44
+
45
+ export {};
@@ -0,0 +1,91 @@
1
+ /**
2
+ * @typedef {import('../success').ApacuanaSuccess} ApacuanaSuccess
3
+ */
4
+
5
+ /**
6
+ * Define la estructura de un objeto Firmante.
7
+ * @typedef {object} Signer
8
+ * @property {string} name - Nombre completo del firmante.
9
+ * @property {string} email - Correo electrónico del firmante.
10
+ * @property {string} document - Documento de identidad del firmante.
11
+ */
12
+
13
+ /**
14
+ * @typedef {object} AddSignerData
15
+ * @property {string} signer - Identificador de confirmación del firmante añadido.
16
+ */
17
+
18
+ /**
19
+ * Define la estructura de la respuesta al añadir un firmante.
20
+ * @typedef {object} AddSignerResponse
21
+ * @property {true} success
22
+ * @property {AddSignerData} data
23
+ */
24
+
25
+ /**
26
+ * Define la estructura de datos para obtener el digest de un documento.
27
+ * @typedef {object} GetDigestData
28
+ * @property {string} cert - Certificado del firmante en formato base64.
29
+ * @property {string} signatureId - Identificador único de la firma.
30
+ */
31
+
32
+ /**
33
+ * @typedef {object} SignaturePlacement
34
+ * @property {number} page - Página donde se estampará la firma.
35
+ * @property {number} x - Coordenada X de la firma.
36
+ * @property {number} y - Coordenada Y de la firma.
37
+ */
38
+
39
+ /**
40
+ * Define la estructura de datos para añadir un firmante.
41
+ * @typedef {object} SignerData
42
+ * @property {string} name - Nombre del firmante.
43
+ * @property {string} reference - Referencia o identificador del firmante.
44
+ * @property {string} typedoc - Tipo de documento de identidad del firmante.
45
+ * @property {string} doc - Número de documento de identidad del firmante.
46
+ * @property {Array<SignaturePlacement>} signature - Array con las coordenadas donde se estampará la firma.
47
+ */
48
+
49
+ /**
50
+ * @typedef {object} GetDigestResponseData
51
+ * @property {string} digest - El digest del documento que se va a firmar.
52
+ */
53
+
54
+ /**
55
+ * Define la estructura de la respuesta al obtener el digest.
56
+ * @typedef {object} GetDigestResponse
57
+ * @property {true} success
58
+ * @property {GetDigestResponseData} data
59
+ */
60
+
61
+ /**
62
+ * Define la estructura de los parámetros para obtener documentos.
63
+ * @typedef {object} GetDocsParams
64
+ * @property {number} page - Número de página para la paginación.
65
+ * @property {number} size - Cantidad de registros por página.
66
+ * @property {string} [status] - (Opcional) Estado para filtrar los documentos.
67
+ */
68
+
69
+ /**
70
+ * @typedef {object} GetDocsResponseData
71
+ * @property {number} totalRecords - El número total de registros encontrados.
72
+ * @property {Array<object>} records - Un arreglo con los registros de los documentos.
73
+ */
74
+
75
+ /**
76
+ * Define la estructura de la respuesta al obtener documentos.
77
+ * @typedef {object} GetDocsResponse
78
+ * @property {true} success
79
+ * @property {GetDocsResponseData} data
80
+ */
81
+
82
+ /**
83
+ * @typedef {object} SignDocumentData
84
+ * @property {object} signature - Objeto con información de la firma.
85
+ * @property {string} signature.id - ID de la firma.
86
+ * @property {Array<object>} signature.positions - Posiciones de la firma.
87
+ * @property {string} cert - Certificado en base64.
88
+ * @property {string} signedDigest - Digest firmado.
89
+ */
90
+
91
+ export {};
@@ -0,0 +1,73 @@
1
+ /**
2
+ * @typedef {object} UserData
3
+ * @property {string} email - Correo electrónico. No puede contener espacios y tiene un máximo de 128 caracteres.
4
+ * @property {number} typeuser - Tipo de usuario. Debe ser un ID valido.
5
+ * @property {string} name - Nombre de la persona.
6
+ * @property {string} lastname - Apellido de la persona.
7
+ * @property {'V' | 'P' | 'E'} kinddoc - Tipo de documento de identidad. Puede ser 'V' (Venezolano), 'P' (Pasaporte) o 'E' (Extranjero).
8
+ * @property {number} doc - Número de documento de identidad. Debe ser un número entero.
9
+ * @property {string} birthdate - Fecha de nacimiento. Debe ser una fecha válida en formato ISO y no puede ser una fecha futura.
10
+ * @property {'J' | 'G' | 'V' | 'P' | 'E'} kindrif - Tipo de RIF (Registro de Información Fiscal). Puede ser 'J', 'G', 'V', 'P' o 'E'.
11
+ * @property {'M' | 'F' | 'Sin especificar'} gender - Género. Puede ser 'M' (Masculino), 'F' (Femenino) o 'Sin especificar'.
12
+ * @property {number} rif - Número de RIF. Debe ser un número entero.
13
+ * @property {number} phone - Número de teléfono. Debe ser un número entero.
14
+ * @property {string} kindphone - Código de área del teléfono. Ej. 0424.
15
+ * @property {string} state - Nombre del estado.
16
+ * @property {string} municipality - Nombre del municipio.
17
+ * @property {string} parish - Nombre de la parroquia.
18
+ * @property {string} postalcode - Código postal.
19
+ * @property {string} address - Dirección.
20
+ * @property {string} fiscaladdress - Dirección fiscal.
21
+ * @property {string} fiscalkindphone - Código de área del teléfono fiscal. Ej. 0424.
22
+ * @property {number} fiscalphone - Número de teléfono fiscal. Debe ser un número entero.
23
+ * @property {string} occupation - Ocupacion de la persona.
24
+ * @property {string} degree - Título universitario.
25
+ * @property {string} university - Universidad.
26
+ * @property {string} graduationyear - Año de graduación.
27
+ * @property {string} collegiatenumber - Número de colegiado.
28
+ * @property {string} collegiateyear - Año de colegiatura.
29
+ * @property {string} companyname - Nombre de la empresa.
30
+ * @property {'J' | 'G' | 'V' | 'P' | 'E'} companykindrif - Tipo de RIF de la empresa. Puede ser 'J', 'G', 'V', 'P' o 'E'.
31
+ * @property {string} companyrif - Número de RIF de la empresa.
32
+ * @property {string} companystate - Estado de la empresa.
33
+ * @property {string} companymunicipality - Municipio de la empresa.
34
+ * @property {string} companyparish - Parroquia de la empresa.
35
+ * @property {string} companyaddress - Dirección de la empresa.
36
+ * @property {string} companykindphone - Código de área del teléfono de la empresa. Ej. 0212.
37
+ * @property {string} companyphone - Número de teléfono de la empresa.
38
+ * @property {string} companypostalcode - Código postal de la empresa.
39
+ * @property {string} companywebpage - Página web de la empresa.
40
+ * @property {string} companycommercialregister - Registro comercial de la empresa.
41
+ * @property {string} companyregisterdate - Fecha de registro de la empresa en formato ISO.
42
+ * @property {string} companyregisternumber - Número de registro de la empresa.
43
+ * @property {string} companyconstitutiondate - Fecha de constitución de la empresa en formato ISO.
44
+ * @property {string} companypublishdate - Fecha de publicación del decreto de constitución. Debe ser una fecha válida en formato ISO y no puede ser una fecha futura.
45
+ * @property {string} companyconstitutiondecree - Decreto de constitución de la empresa. Máximo 32 caracteres.
46
+ * @property {string} companynumberdecree - Número de decreto de la empresa. Máximo 16 caracteres.
47
+ * @property {string} positionprivate - Cargo empleado empresa privada.
48
+ * @property {string} departmentprivate - Departamento empleado empresa privada.
49
+ * @property {string} authorizedprivate - Autorizado de por empleado empresa privada.
50
+ * @property {string} functionsprivate - Funciones empleado empresa privada.
51
+ * @property {string} publishprivate - Fecha de publicación de la gaceta de la empresa privada.
52
+ * @property {string} issuedateprivate - Fecha de registro de la empresa privada. Debe ser una fecha válida en formato ISO.
53
+ * @property {string} kindphoneprivate - Código de área del teléfono de la empresa privada. ej. 0424.
54
+ * @property {number} phoneprivate - Número de teléfono privado. Debe ser un número entero.
55
+ * @property {string} positionpublic - Cargo empleado empresa publica.
56
+ * @property {string} departmentpublic - Departamento empleado empresa publica.
57
+ * @property {string} authorizedpublic - Autorizado empleado empresa publica.
58
+ * @property {string} functionspublic - Funciones de empleado empresa publica.
59
+ * @property {string} publishpublic - Fecha de publicación de la gaceta de la empresa pública.
60
+ * @property {string} issuedatepublic - Fecha de registro de la empresa pública. Debe ser una fecha válida en formato ISO.
61
+ * @property {string} kindphonepublic - Código de área del teléfono de la empresa publica. ej 0424.
62
+ * @property {number} phonepublic - Número de teléfono público. Debe ser un número entero.
63
+ * @property {string} companyid - ID de la empresa. Debe ser un UUID para la creacion de empleados.
64
+ */
65
+
66
+ /**
67
+ * @typedef {object} GetCustomerResponse
68
+ * @property {string} token - El token de sesión del usuario.
69
+ * @property {UserData} userData - Los datos del usuario obtenidos.
70
+ * @property {boolean} success - Indica si la operación fue exitosa.
71
+ */
72
+
73
+ export {};
@@ -2,11 +2,13 @@ import { getConfig } from "../../src/config/index";
2
2
  import { httpRequest } from "../../src/utils/httpClient";
3
3
  import helpers from "../../src/utils/helpers";
4
4
  import { ApacuanaAPIError } from "../../src/errors";
5
+ import ApacuanaSuccess from "../../src/success";
5
6
  import {
6
7
  generateCert,
7
8
  getCertStatus,
8
9
  getCertTypes,
9
10
  getRequerimentsByTypeUser,
11
+ requestCertificate,
10
12
  } from "../../src/api/certs";
11
13
  import { INTEGRATION_TYPE } from "../../src/utils/constant";
12
14
 
@@ -43,10 +45,10 @@ describe("Certificate API - certs.js", () => {
43
45
  mockEncryptedCsr,
44
46
  "POST"
45
47
  );
46
- expect(result).toEqual({
48
+ expect(result).toBeInstanceOf(ApacuanaSuccess);
49
+ expect(result.data).toEqual({
47
50
  cert: "onboarding-cert",
48
51
  certifiedid: "onboarding-certified-id",
49
- success: true,
50
52
  });
51
53
  });
52
54
 
@@ -93,7 +95,8 @@ describe("Certificate API - certs.js", () => {
93
95
  mockUserData,
94
96
  true
95
97
  );
96
- expect(result).toEqual({ status: "VALID", success: true });
98
+ expect(result).toBeInstanceOf(ApacuanaSuccess);
99
+ expect(result.data).toEqual({ status: "VALID" });
97
100
  });
98
101
  });
99
102
 
@@ -112,7 +115,8 @@ describe("Certificate API - certs.js", () => {
112
115
  {},
113
116
  "GET"
114
117
  );
115
- expect(result).toEqual({ types: mockApiResponse.types, success: true });
118
+ expect(result).toBeInstanceOf(ApacuanaSuccess);
119
+ expect(result.data).toEqual({ types: mockApiResponse.types });
116
120
  });
117
121
 
118
122
  it("should throw an error for ONPREMISE integration", async () => {
@@ -159,9 +163,9 @@ describe("Certificate API - certs.js", () => {
159
163
  {},
160
164
  "GET"
161
165
  );
162
- expect(result).toEqual({
166
+ expect(result).toBeInstanceOf(ApacuanaSuccess);
167
+ expect(result.data).toEqual({
163
168
  requirements: mockApiResponse.requirements,
164
- success: true,
165
169
  });
166
170
  });
167
171
 
@@ -202,5 +206,94 @@ describe("Certificate API - certs.js", () => {
202
206
  'The "params" object with a numeric "type" property is required.'
203
207
  );
204
208
  });
209
+ it("should throw a generic error for other failures", async () => {
210
+ getConfig.mockReturnValue({
211
+ integrationType: INTEGRATION_TYPE.ONBOARDING,
212
+ });
213
+ const genericError = new Error("Network failure");
214
+ httpRequest.mockRejectedValue(genericError);
215
+
216
+ await expect(getRequerimentsByTypeUser({ type: 1 })).rejects.toThrow(
217
+ `Failed to get requirements: ${genericError.message}`
218
+ );
219
+ });
220
+ });
221
+ });
222
+
223
+ describe("requestCertificate", () => {
224
+ const validParams = { type: 1, documents: [] };
225
+
226
+ afterEach(() => {
227
+ jest.clearAllMocks();
228
+ });
229
+
230
+ it("should throw an error if params are invalid", async () => {
231
+ await expect(requestCertificate()).rejects.toThrow(
232
+ 'The "params" object with a numeric "type" property and a "documents" array is required.'
233
+ );
234
+ await expect(requestCertificate({ type: 1 })).rejects.toThrow(
235
+ 'The "params" object with a numeric "type" property and a "documents" array is required.'
236
+ );
237
+ await expect(requestCertificate({ documents: [] })).rejects.toThrow(
238
+ 'The "params" object with a numeric "type" property and a "documents" array is required.'
239
+ );
240
+ });
241
+
242
+ it("should request a certificate for ONBOARDING integration", async () => {
243
+ getConfig.mockReturnValue({ integrationType: INTEGRATION_TYPE.ONBOARDING });
244
+ const mockResponse = { message: "Certificate requested" };
245
+ httpRequest.mockResolvedValue(mockResponse);
246
+
247
+ const result = await requestCertificate(validParams);
248
+
249
+ expect(result).toBeInstanceOf(ApacuanaSuccess);
250
+ expect(result.data).toEqual(mockResponse);
251
+ expect(httpRequest).toHaveBeenCalledWith(
252
+ "services/api/customer/request-certificate",
253
+ validParams,
254
+ "POST"
255
+ );
256
+ });
257
+
258
+ it("should throw a NOT_IMPLEMENTED error for ONPREMISE integration", async () => {
259
+ getConfig.mockReturnValue({ integrationType: INTEGRATION_TYPE.ONPREMISE });
260
+
261
+ await expect(requestCertificate(validParams)).rejects.toThrow(
262
+ new ApacuanaAPIError(
263
+ "Requesting a certificate is not supported for integration type: ONPREMISE",
264
+ 501,
265
+ "NOT_IMPLEMENTED"
266
+ )
267
+ );
268
+ });
269
+
270
+ it("should throw an UNSUPPORTED_INTEGRATION_TYPE error for unsupported integration types", async () => {
271
+ getConfig.mockReturnValue({ integrationType: "unsupported-type" });
272
+
273
+ await expect(requestCertificate(validParams)).rejects.toThrow(
274
+ new ApacuanaAPIError(
275
+ "Unsupported integration type: unsupported-type",
276
+ 400,
277
+ "UNSUPPORTED_INTEGRATION_TYPE"
278
+ )
279
+ );
280
+ });
281
+
282
+ it("should re-throw ApacuanaAPIError if caught", async () => {
283
+ getConfig.mockReturnValue({ integrationType: INTEGRATION_TYPE.ONBOARDING });
284
+ const apiError = new ApacuanaAPIError("API Error", 500, "API_ERROR");
285
+ httpRequest.mockRejectedValue(apiError);
286
+
287
+ await expect(requestCertificate(validParams)).rejects.toThrow(apiError);
288
+ });
289
+
290
+ it("should throw a generic error for other failures", async () => {
291
+ getConfig.mockReturnValue({ integrationType: INTEGRATION_TYPE.ONBOARDING });
292
+ const genericError = new Error("Network failure");
293
+ httpRequest.mockRejectedValue(genericError);
294
+
295
+ await expect(requestCertificate(validParams)).rejects.toThrow(
296
+ `Failed to request certificate: ${genericError.message}`
297
+ );
205
298
  });
206
299
  });