apiempresas 1.0.1 → 1.1.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/README.md CHANGED
@@ -25,7 +25,7 @@ const api = new ApiEmpresas({
25
25
  ```typescript
26
26
  async function fetchCompany() {
27
27
  try {
28
- const company = await api.companies.get('B12345678');
28
+ const company = await api.companies.get('A15075062');
29
29
  console.log(company.name);
30
30
  } catch (error) {
31
31
  console.error('Error fetching company:', error.message);
@@ -37,7 +37,7 @@ async function fetchCompany() {
37
37
 
38
38
  ```typescript
39
39
  async function fetchBorme() {
40
- const bormeData = await api.companies.borme('B12345678');
40
+ const bormeData = await api.companies.borme('A15075062');
41
41
  console.log(bormeData.events);
42
42
  }
43
43
  ```
@@ -47,20 +47,41 @@ async function fetchBorme() {
47
47
  ```typescript
48
48
  async function fetchBatch() {
49
49
  const response = await api.companies.batch({
50
- cifs: ['B12345678', 'A15075062']
50
+ cifs: ['A15075062', 'A46103834']
51
51
  });
52
52
  console.log('Resultados:', response.data);
53
53
  console.log('Coste:', response.meta.cost);
54
54
  }
55
55
  ```
56
56
 
57
+ ### 4. Administradores, búsqueda con varios resultados, Match y Radar
58
+
59
+ ```typescript
60
+ // Administradores y cargos (Pro/Business)
61
+ const conAdmins = await api.companies.get('A15075062', { admin: true });
62
+
63
+ // Varias empresas por nombre, con paginación
64
+ let pagina = await api.companies.searchMultiple('software', { limit: 20 });
65
+ while (pagina.meta.next_cursor) {
66
+ pagina = await api.companies.searchMultiple('software', { cursor: pagina.meta.next_cursor });
67
+ }
68
+
69
+ // Match (Business): el sector del vendedor es obligatorio
70
+ const match = await api.companies.match('A15075062', 'software');
71
+
72
+ // Radar de empresas nuevas (Business)
73
+ const nuevas = await api.companies.radar({ province: 'Madrid', range: 'semana' });
74
+ ```
75
+
76
+ Requiere Node.js 18 o superior (usa `fetch` nativo).
77
+
57
78
  ## Entorno de Pruebas (Sandbox)
58
79
 
59
- Para probar la integración sin consumir saldo, puedes apuntar a la URL del Sandbox:
80
+ Para probar la integración sin consumir saldo, apunta a la URL del Sandbox con tu misma API Key. Devuelve datos simulados: `A15075062` (empresa encontrada) y `B00000000` (no encontrada).
60
81
 
61
82
  ```typescript
62
83
  const api = new ApiEmpresas({
63
- apiKey: 'sandbox_api_key',
84
+ apiKey: 'TU_API_KEY',
64
85
  baseURL: 'https://apiempresas.es/api/sandbox/v1'
65
86
  });
66
87
  ```
@@ -78,10 +99,12 @@ try {
78
99
  if (error instanceof ApiError) {
79
100
  console.error(`Status: ${error.status}`);
80
101
  console.error(`Message: ${error.message}`);
81
- console.error(`Code: ${error.errorCode}`);
102
+ console.error(`Code: ${error.code}`); // p. ej. QUOTA_EXCEEDED, TOO_MANY_REQUESTS, API_KEY_INVALID
82
103
  }
83
104
  }
84
105
  ```
85
106
 
107
+ Un `429` con `code: 'TOO_MANY_REQUESTS'` se resuelve esperando y reintentando; con `code: 'QUOTA_EXCEEDED'` no: hay que recargar saldo o cambiar de plan. `errorCode` sigue devolviendo el campo `error` de la respuesta, como en versiones anteriores.
108
+
86
109
  ## Licencia
87
110
  MIT
@@ -1,5 +1,7 @@
1
1
  import { ApiEmpresasOptions } from './types';
2
2
  import { Companies } from './resources/Companies';
3
+ /** Versión del SDK, enviada en el User-Agent. */
4
+ export declare const SDK_VERSION = "1.1.0";
3
5
  export declare class ApiEmpresas {
4
6
  private apiKey;
5
7
  private baseURL;
@@ -1,8 +1,30 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ApiEmpresas = void 0;
3
+ exports.ApiEmpresas = exports.SDK_VERSION = void 0;
4
4
  const ApiError_1 = require("./errors/ApiError");
5
5
  const Companies_1 = require("./resources/Companies");
6
+ /** Versión del SDK, enviada en el User-Agent. */
7
+ exports.SDK_VERSION = '1.1.0';
8
+ /**
9
+ * Mensaje legible del cuerpo de error. Según el error, la API lo pone en
10
+ * message, detail, error (texto) o messages (errores de validación).
11
+ */
12
+ function extractErrorMessage(data) {
13
+ if (!data || typeof data !== 'object')
14
+ return undefined;
15
+ for (const key of ['message', 'detail']) {
16
+ if (typeof data[key] === 'string' && data[key] !== '')
17
+ return data[key];
18
+ }
19
+ if (typeof data.error === 'string' && data.error !== '')
20
+ return data.error;
21
+ if (data.messages && typeof data.messages === 'object') {
22
+ const first = Object.values(data.messages)[0];
23
+ if (typeof first === 'string' && first !== '')
24
+ return first;
25
+ }
26
+ return undefined;
27
+ }
6
28
  class ApiEmpresas {
7
29
  apiKey;
8
30
  baseURL;
@@ -22,6 +44,7 @@ class ApiEmpresas {
22
44
  const headers = new Headers(options.headers || {});
23
45
  headers.set('X-API-KEY', this.apiKey);
24
46
  headers.set('Accept', 'application/json');
47
+ headers.set('User-Agent', `apiempresas-node/${exports.SDK_VERSION}`);
25
48
  if (!headers.has('Content-Type') && options.method && options.method.toUpperCase() !== 'GET') {
26
49
  headers.set('Content-Type', 'application/json');
27
50
  }
@@ -37,7 +60,7 @@ class ApiEmpresas {
37
60
  const isJson = response.headers.get('content-type')?.includes('application/json');
38
61
  const data = isJson ? await response.json() : await response.text();
39
62
  if (!response.ok) {
40
- throw new ApiError_1.ApiError(response.status, data?.message || response.statusText || 'Error desconocido en la API', data?.error || undefined, data);
63
+ throw new ApiError_1.ApiError(response.status, extractErrorMessage(data) || response.statusText || 'Error desconocido en la API', data?.error || undefined, data);
41
64
  }
42
65
  return data;
43
66
  }
@@ -1,6 +1,8 @@
1
1
  export declare class ApiError extends Error {
2
2
  status: number;
3
3
  errorCode?: string;
4
+ /** Identificador estable del error (QUOTA_EXCEEDED, TOO_MANY_REQUESTS, API_KEY_INVALID...). */
5
+ code?: string;
4
6
  rawData?: any;
5
7
  constructor(status: number, message: string, errorCode?: string, rawData?: any);
6
8
  }
@@ -4,6 +4,8 @@ exports.ApiError = void 0;
4
4
  class ApiError extends Error {
5
5
  status;
6
6
  errorCode;
7
+ /** Identificador estable del error (QUOTA_EXCEEDED, TOO_MANY_REQUESTS, API_KEY_INVALID...). */
8
+ code;
7
9
  rawData;
8
10
  constructor(status, message, errorCode, rawData) {
9
11
  super(message);
@@ -11,6 +13,7 @@ class ApiError extends Error {
11
13
  this.status = status;
12
14
  this.errorCode = errorCode;
13
15
  this.rawData = rawData;
16
+ this.code = rawData && typeof rawData.code === 'string' ? rawData.code : undefined;
14
17
  // Fix prototype chain for built-in classes in TS
15
18
  Object.setPrototypeOf(this, ApiError.prototype);
16
19
  }
@@ -1,16 +1,40 @@
1
1
  import { ApiEmpresas } from '../ApiEmpresas';
2
2
  import { Company, BatchRequest, BatchResponse, ScoreData, BormeData, SignalsData } from '../types';
3
+ /** Opciones de get(): admin=true añade administradores y cargos (Pro/Business). */
4
+ export interface GetOptions {
5
+ admin?: boolean;
6
+ }
7
+ /** Opciones de searchMultiple(): paginación por página o por cursor (meta.next_cursor). */
8
+ export interface SearchMultipleOptions {
9
+ limit?: number;
10
+ page?: number;
11
+ cursor?: string;
12
+ }
13
+ /** Filtros del Radar de empresas nuevas. */
14
+ export interface RadarOptions {
15
+ province?: string;
16
+ priority?: string;
17
+ range?: string;
18
+ }
3
19
  export declare class Companies {
4
20
  private client;
5
21
  constructor(client: ApiEmpresas);
6
22
  /**
7
23
  * Obtiene los datos básicos de una empresa por su CIF.
8
24
  */
9
- get(cif: string): Promise<Company>;
25
+ get(cif: string, options?: GetOptions): Promise<Company>;
10
26
  /**
11
27
  * Busca empresas por nombre o razón social.
12
28
  */
13
29
  search(q: string): Promise<Company>;
30
+ /**
31
+ * Búsqueda con varios resultados (multiple=true). Devuelve data y meta;
32
+ * para la página siguiente, pasa meta.next_cursor como cursor.
33
+ */
34
+ searchMultiple(q: string, options?: SearchMultipleOptions): Promise<{
35
+ data: Company[];
36
+ meta: any;
37
+ }>;
14
38
  /**
15
39
  * Consulta múltiple de CIFs en una sola petición.
16
40
  */
@@ -41,13 +65,21 @@ export declare class Companies {
41
65
  /**
42
66
  * (Business) Obtiene la información del Radar de empresas.
43
67
  */
44
- radar(cif: string): Promise<any>;
68
+ radar(cifOrOptions?: string | RadarOptions): Promise<any>;
45
69
  /**
46
70
  * (Business) Realiza un match avanzado con los datos de una empresa.
47
71
  */
48
- match(cif: string): Promise<any>;
72
+ match(cif: string, sellerSector?: string): Promise<any>;
49
73
  /**
50
74
  * (Business) Obtiene la red o entramado societario (Network) de una empresa.
51
75
  */
52
76
  network(cif: string): Promise<any>;
77
+ /**
78
+ * (Business) Obtiene los contratos públicos y licitaciones adjudicadas a una empresa.
79
+ */
80
+ contracts(cif: string, page?: number, limit?: number): Promise<any>;
81
+ /**
82
+ * (Business) Obtiene el perfil de riesgo corporativo y solvencia de una empresa.
83
+ */
84
+ riskProfile(cif: string): Promise<any>;
53
85
  }
@@ -9,8 +9,10 @@ class Companies {
9
9
  /**
10
10
  * Obtiene los datos básicos de una empresa por su CIF.
11
11
  */
12
- async get(cif) {
12
+ async get(cif, options = {}) {
13
13
  const params = new URLSearchParams({ cif });
14
+ if (options.admin)
15
+ params.set('admin', 'true');
14
16
  const response = await this.client.request(`/companies?${params.toString()}`);
15
17
  return response.data;
16
18
  }
@@ -22,6 +24,21 @@ class Companies {
22
24
  const response = await this.client.request(`/companies/search?${params.toString()}`);
23
25
  return response.data;
24
26
  }
27
+ /**
28
+ * Búsqueda con varios resultados (multiple=true). Devuelve data y meta;
29
+ * para la página siguiente, pasa meta.next_cursor como cursor.
30
+ */
31
+ async searchMultiple(q, options = {}) {
32
+ const params = new URLSearchParams({ q, multiple: 'true' });
33
+ if (options.limit !== undefined)
34
+ params.set('limit', String(options.limit));
35
+ if (options.page !== undefined)
36
+ params.set('page', String(options.page));
37
+ if (options.cursor !== undefined)
38
+ params.set('cursor', options.cursor);
39
+ const response = await this.client.request(`/companies/search?${params.toString()}`);
40
+ return { data: response.data, meta: response.meta };
41
+ }
25
42
  /**
26
43
  * Consulta múltiple de CIFs en una sola petición.
27
44
  */
@@ -75,16 +92,30 @@ class Companies {
75
92
  /**
76
93
  * (Business) Obtiene la información del Radar de empresas.
77
94
  */
78
- async radar(cif) {
79
- const params = new URLSearchParams({ cif });
95
+ async radar(cifOrOptions = {}) {
96
+ // Compatibilidad: antes se pasaba un CIF, que el Radar no usa. Ahora se pasan
97
+ // los filtros (province, priority, range).
98
+ const params = new URLSearchParams();
99
+ if (typeof cifOrOptions === 'string') {
100
+ params.set('cif', cifOrOptions);
101
+ }
102
+ else {
103
+ for (const [k, v] of Object.entries(cifOrOptions)) {
104
+ if (v !== undefined && v !== null)
105
+ params.set(k, String(v));
106
+ }
107
+ }
80
108
  const response = await this.client.request(`/companies/radar?${params.toString()}`);
81
109
  return response.data;
82
110
  }
83
111
  /**
84
112
  * (Business) Realiza un match avanzado con los datos de una empresa.
85
113
  */
86
- async match(cif) {
114
+ async match(cif, sellerSector) {
115
+ // seller_sector es obligatorio en la API: sin él responde 400.
87
116
  const params = new URLSearchParams({ cif });
117
+ if (sellerSector)
118
+ params.set('seller_sector', sellerSector);
88
119
  const response = await this.client.request(`/companies/match?${params.toString()}`);
89
120
  return response.data;
90
121
  }
@@ -96,5 +127,21 @@ class Companies {
96
127
  const response = await this.client.request(`/companies/network?${params.toString()}`);
97
128
  return response.data;
98
129
  }
130
+ /**
131
+ * (Business) Obtiene los contratos públicos y licitaciones adjudicadas a una empresa.
132
+ */
133
+ async contracts(cif, page = 1, limit = 20) {
134
+ const params = new URLSearchParams({ cif, page: page.toString(), limit: limit.toString() });
135
+ const response = await this.client.request(`/companies/contracts?${params.toString()}`);
136
+ return response.data;
137
+ }
138
+ /**
139
+ * (Business) Obtiene el perfil de riesgo corporativo y solvencia de una empresa.
140
+ */
141
+ async riskProfile(cif) {
142
+ const params = new URLSearchParams({ cif });
143
+ const response = await this.client.request(`/companies/risk-profile?${params.toString()}`);
144
+ return response.data;
145
+ }
99
146
  }
100
147
  exports.Companies = Companies;
package/dist/types.d.ts CHANGED
@@ -5,7 +5,7 @@ export interface ApiEmpresasOptions {
5
5
  apiKey: string;
6
6
  /**
7
7
  * Base URL de la API. Por defecto es https://apiempresas.es/api/v1
8
- * Puedes sobreescribirla para apuntar al sandbox: https://apiempresas.es/api/sandbox/v1
8
+ * Puedes sobreescribirla para apuntar al sandbox (gratis, datos simulados, misma API Key): https://apiempresas.es/api/sandbox/v1
9
9
  */
10
10
  baseURL?: string;
11
11
  /**
@@ -31,6 +31,23 @@ export interface Company {
31
31
  address?: string;
32
32
  status?: string;
33
33
  score?: number;
34
+ cnae_2025?: string;
35
+ cnae_2025_label?: string;
36
+ corporate_purpose?: string;
37
+ capital_social_raw?: string;
38
+ lat?: number;
39
+ lng?: number;
40
+ /** Solo con get(cif, { admin: true }) en Pro/Business. */
41
+ administrators?: Array<{
42
+ name: string;
43
+ position: string;
44
+ [key: string]: any;
45
+ }>;
46
+ /** Solo en el plan Free: indica que la respuesta viene recortada. */
47
+ upsell_opportunities?: {
48
+ campos_ocultos: string[];
49
+ mensaje: string;
50
+ };
34
51
  }
35
52
  export interface BatchRequest {
36
53
  cifs: string[];
package/package.json CHANGED
@@ -1,29 +1,36 @@
1
- {
2
- "name": "apiempresas",
3
- "version": "1.0.1",
4
- "description": "SDK oficial de APIEmpresas.es para Node.js y TypeScript",
5
- "main": "dist/index.js",
6
- "types": "dist/index.d.ts",
7
- "scripts": {
8
- "build": "tsc",
9
- "test": "jest",
10
- "prepublishOnly": "npm run build"
11
- },
12
- "keywords": [
13
- "apiempresas",
14
- "empresas",
15
- "cif",
16
- "borme",
17
- "registro mercantil",
18
- "españa"
19
- ],
20
- "author": "APIEmpresas",
21
- "license": "MIT",
22
- "devDependencies": {
23
- "@types/jest": "^29.5.12",
24
- "@types/node": "^20.11.19",
25
- "jest": "^29.7.0",
26
- "ts-jest": "^29.1.2",
27
- "typescript": "^5.3.3"
28
- }
29
- }
1
+ {
2
+ "name": "apiempresas",
3
+ "version": "1.1.0",
4
+ "description": "SDK oficial de APIEmpresas.es para Node.js y TypeScript",
5
+ "main": "dist/index.js",
6
+ "files": [
7
+ "dist",
8
+ "README.md"
9
+ ],
10
+ "engines": {
11
+ "node": ">=18"
12
+ },
13
+ "types": "dist/index.d.ts",
14
+ "scripts": {
15
+ "build": "tsc",
16
+ "test": "jest",
17
+ "prepublishOnly": "npm run build"
18
+ },
19
+ "keywords": [
20
+ "apiempresas",
21
+ "empresas",
22
+ "cif",
23
+ "borme",
24
+ "registro mercantil",
25
+ "españa"
26
+ ],
27
+ "author": "APIEmpresas",
28
+ "license": "MIT",
29
+ "devDependencies": {
30
+ "@types/jest": "^29.5.12",
31
+ "@types/node": "^20.11.19",
32
+ "jest": "^29.7.0",
33
+ "ts-jest": "^29.1.2",
34
+ "typescript": "^5.3.3"
35
+ }
36
+ }