apiempresas 1.4.0 → 1.6.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
@@ -83,13 +83,14 @@ Requiere Node.js 18 o superior (usa `fetch` nativo).
83
83
  const v = await api.companies.verify('A46103834', {
84
84
  name: 'Mercadona SA', // se compara con la razón social
85
85
  person: 'Juan Roig Alfonso', // ¿es administrador vigente?
86
- vat: true // NIF-IVA en VIES
86
+ vat: true, // NIF-IVA en VIES
87
+ iban: 'ES9121000418450200051332' // (1.5.0) ¿está bien formado? No dice de quién es la cuenta
87
88
  });
88
89
  console.log(v.decision_hint); // 'pass' | 'review' | 'fail'
89
90
  console.log(v.flags); // alertas con code, severity y message
90
91
  ```
91
92
 
92
- Cada empresa trae además `status_code` (ACTIVE, INSOLVENCY, EXTINCT...), `status_source`, `status_date` y, en Pro/Business, `financials` (tramo de tamaño y último año de cuentas). Los administradores traen `since`. Desde la 1.3.0 la respuesta lleva también `identifiers` (código LEI) y `legal_form` (forma jurídica con su código ISO 20275) en todos los planes, y en Pro/Business `group` (matriz directa y última según GLEIF) y `ownership` (socio único según el BORME). En `verify`, con `person`, `checks.person.is_sole_shareholder` dice si quien firma es el socio único.
93
+ Cada empresa trae además `status_code` (ACTIVE, INSOLVENCY, EXTINCT...), `status_source`, `status_date` y, en Pro/Business, `financials` (tramo de tamaño y último año de cuentas). Los administradores traen `since`. Desde la 1.3.0 la respuesta lleva también `identifiers` (código LEI) y `legal_form` (forma jurídica con su código ISO 20275) en todos los planes, y en Pro/Business `group` (matriz directa y última según GLEIF) y `ownership` (socio único según el BORME). En `verify`, con `person`, `checks.person.is_sole_shareholder` dice si quien firma es el socio único. Desde la 1.5.0, en Pro/Business, `size` (tramo de empleados con su fuente: Kit Digital, TED o PLACSP; null si no consta) y `address_density` (cuántas sociedades activas comparten la dirección exacta), y en `verify` con `iban`, `checks.iban` (si no es válido, alerta `IBAN_INVALID` y `decision_hint` review). `filter()` admite `size_category` (micro, small, medium, large).
93
94
 
94
95
  ### Nombre a CIF (Pro)
95
96
 
@@ -98,6 +99,21 @@ const { data, meta } = await api.companies.reconcile(['Mercadona', { name: 'Tall
98
99
  // data[i].status: match (con company.cif) | ambiguous (candidates) | no_match. Solo se cobran los match.
99
100
  ```
100
101
 
102
+ ### Validar el NIF de tus clientes antes de facturar (Pro, Business o saldo; desde 1.6.0)
103
+
104
+ ```typescript
105
+ const { data, meta } = await api.companies.verifyBatch([
106
+ { cif: 'A46103834', name: 'Mercadona', ref: 'cliente-0001' }, // name: la razón social que tienes guardada
107
+ { cif: 'A15075062', name: 'Inditex', ref: 'cliente-0002' }, // ref: tu identificador, vuelve tal cual
108
+ 'B12345674', // o el NIF suelto
109
+ ]);
110
+ data.forEach((fila) => console.log(fila.input, fila.invoice_hint)); // 'ok' | 'revisar' | 'no_facturar'
111
+ // await api.companies.verifyBatch(['A46103834'], { vat: true }); // también VIES
112
+ ```
113
+
114
+ Por cada NIF, en el mismo orden: `valid_format`, `exists`, `legal_name`, `address`, `status_code`, `name_check` (si das `name`) e `invoice_hint` (`ok`, `revisar` o `no_facturar`) con sus motivos en `flags`. `meta` trae `requested`, `found`, `cost`, `truncated` y `summary`. Hasta 1.000 NIF por llamada; con `vat` (lotes de hasta 20) comprueba también el NIF-IVA en VIES. Cobra 1 consulta por sociedad encontrada: los NIF inválidos, de personas o que no constan no se cobran; si no te llega el saldo, las filas que no caben vuelven con `processed: false`. No sustituye la comprobación contra el censo de la AEAT.
115
+ Los tipos `VerifyBatchItem`, `VerifyBatchRow` y `VerifyBatchMeta` se exportan desde el paquete.
116
+
101
117
  ### Segmentos de empresas
102
118
 
103
119
  ```typescript
@@ -119,6 +135,13 @@ await api.watchlist.remove('A28015865');
119
135
 
120
136
  ```typescript
121
137
  const hook = await api.webhooks.create({ url: 'https://tu-servidor.com/apiempresas', event: 'watchlist.*' });
138
+
139
+ // (1.5.0) Sociedades nuevas del BORME del día, con filtros opcionales
140
+ const nuevas = await api.webhooks.create({
141
+ url: 'https://tu-servidor.com/nuevas',
142
+ event: 'company.created',
143
+ filters: { province: ['MADRID', 'BARCELONA'], keywords: ['software', 'informática'], min_capital: 3000 }
144
+ });
122
145
  // Guarda hook.secret: con él se comprueba la firma.
123
146
  await api.webhooks.test(hook.id); // envía un test.ping y devuelve lo que respondió tu servidor
124
147
 
@@ -135,7 +158,7 @@ import { constructWebhookEvent } from 'apiempresas';
135
158
  app.post('/apiempresas', express.raw({ type: 'application/json' }), (req, res) => {
136
159
  try {
137
160
  const evento = constructWebhookEvent(req.body, req.header('X-ApiEmpresas-Signature'), process.env.APIEMPRESAS_WEBHOOK_SECRET!);
138
- // evento.event: company.borme_act | company.status_changed | company.risk_level_changed | test.ping
161
+ // evento.event: company.created | company.borme_act | company.status_changed | company.risk_level_changed | test.ping
139
162
  // Usa evento.id (o la cabecera X-ApiEmpresas-Delivery) para no procesar dos veces el mismo envío.
140
163
  res.sendStatus(200);
141
164
  } catch {
@@ -171,9 +194,43 @@ const p = await api.sanctions.screen({ name: 'Vladimir Putin', type: 'person' })
171
194
 
172
195
  En `companies.verify()` con Business, el resultado incluye `checks.sanctions`.
173
196
 
197
+ ### 10. Subvenciones y ayudas públicas (Business, desde 1.5.0) — 1 consulta
198
+
199
+ ```typescript
200
+ // Concesiones de la BDNS desde 2022 (Kit Digital incluido)
201
+ const s = await api.companies.subsidies('B12345678', { year: 2025, limit: 50 });
202
+ console.log(s.summary.total_grants, s.summary.total_amount); // importes en texto con dos decimales
203
+ console.log(s.summary.by_year, s.summary.top_calls);
204
+ for (const g of s.grants) console.log(g.grant_date, g.amount, g.call);
205
+ ```
206
+
207
+ ### 11. Feed de cambios (Business, desde 1.5.0) — 1 consulta por página
208
+
209
+ ```typescript
210
+ // Todas las sociedades con un acto en el BORME desde una fecha (hasta 30 días atrás)
211
+ const { data, meta } = await api.companies.changes({ since: '2026-10-19', types: ['address', 'officers'], province: 'MADRID' });
212
+ // Siguiente página: api.companies.changes({ ...mismosFiltros, cursor: meta.next_cursor })
213
+
214
+ // O recorre todas las páginas
215
+ for await (const c of api.companies.iterateChanges({ since: '2026-10-19' })) {
216
+ console.log(c.id, c.cif, c.change_types, c.status_code); // usa c.id para no procesar dos veces el mismo cambio
217
+ }
218
+ ```
219
+
220
+ Solo salen sociedades con CIF: las recién constituidas todavía no lo tienen y llegan por el webhook `company.created`. Los tipos de cambio están en `catalog().change_types`.
221
+
222
+ ### 12. Estadísticas del BORME (todos los planes, desde 1.5.0) — 1 consulta
223
+
224
+ ```typescript
225
+ const st = await api.stats({ metrics: ['incorporations', 'dissolutions'], province: 'MADRID', from: '2025-01', to: '2025-12' });
226
+ console.log(st.totals.incorporations);
227
+ for (const fila of st.series) console.log(fila.period, fila.incorporations);
228
+ // Por años: api.stats({ group: 'year', from: '2015', to: '2025' })
229
+ ```
230
+
174
231
  ## Entorno de Pruebas (Sandbox)
175
232
 
176
- 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).
233
+ 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). Tiene también `subsidies()` y `changes()`; `stats()` y `usage()` no.
177
234
 
178
235
  ```typescript
179
236
  const api = new ApiEmpresas({
@@ -193,7 +250,7 @@ console.log(u.stats.remaining_calls, u.stats.wallet_balance, u.stats.quota_reset
193
250
 
194
251
  ```typescript
195
252
  const cat = await api.catalog(); // no gasta consultas; también en el Sandbox
196
- console.log(cat.province, cat.size_band, cat.radar.priority, cat.webhook_events);
253
+ console.log(cat.province, cat.size_band, cat.radar.priority, cat.webhook_events, cat.change_types);
197
254
  ```
198
255
 
199
256
  ## Manejo de Errores
@@ -1,4 +1,4 @@
1
- import { ApiEmpresasOptions, UsageData, CatalogData } from './types';
1
+ import { ApiEmpresasOptions, UsageData, CatalogData, StatsOptions, StatsResult } from './types';
2
2
  import { Companies } from './resources/Companies';
3
3
  import { Watchlist } from './resources/Watchlist';
4
4
  import { Webhooks } from './resources/Webhooks';
@@ -6,7 +6,7 @@ import { Tenders } from './resources/Tenders';
6
6
  import { Sanctions } from './resources/Sanctions';
7
7
  import { verifyWebhookSignature, constructWebhookEvent } from './webhooks/signature';
8
8
  /** Versión del SDK, enviada en el User-Agent. */
9
- export declare const SDK_VERSION = "1.4.0";
9
+ export declare const SDK_VERSION = "1.6.0";
10
10
  export declare class ApiEmpresas {
11
11
  private apiKey;
12
12
  private baseURL;
@@ -34,5 +34,11 @@ export declare class ApiEmpresas {
34
34
  * prioridades y eventos de webhook. No gasta consultas. También está en el Sandbox.
35
35
  */
36
36
  catalog(): Promise<CatalogData>;
37
+ /**
38
+ * (Todos los planes, desde 1.5.0) Estadísticas del BORME por mes o año, para España o una
39
+ * provincia: constituciones, disoluciones, extinciones, concursos, cambios de capital y de
40
+ * domicilio y fusiones, desde 2009. 1 consulta. No está en el Sandbox.
41
+ */
42
+ stats(options?: StatsOptions): Promise<StatsResult>;
37
43
  request<T>(endpoint: string, options?: RequestInit): Promise<T>;
38
44
  }
@@ -9,7 +9,7 @@ const Tenders_1 = require("./resources/Tenders");
9
9
  const Sanctions_1 = require("./resources/Sanctions");
10
10
  const signature_1 = require("./webhooks/signature");
11
11
  /** Versión del SDK, enviada en el User-Agent. */
12
- exports.SDK_VERSION = '1.4.0';
12
+ exports.SDK_VERSION = '1.6.0';
13
13
  /**
14
14
  * Mensaje legible del cuerpo de error. Según el error, la API lo pone en
15
15
  * message, detail, error (texto) o messages (errores de validación).
@@ -75,6 +75,22 @@ class ApiEmpresas {
75
75
  const res = await this.request('/catalog');
76
76
  return res.data;
77
77
  }
78
+ /**
79
+ * (Todos los planes, desde 1.5.0) Estadísticas del BORME por mes o año, para España o una
80
+ * provincia: constituciones, disoluciones, extinciones, concursos, cambios de capital y de
81
+ * domicilio y fusiones, desde 2009. 1 consulta. No está en el Sandbox.
82
+ */
83
+ async stats(options = {}) {
84
+ const params = new URLSearchParams();
85
+ for (const [k, v] of Object.entries(options)) {
86
+ if (v === undefined || v === null || v === '')
87
+ continue;
88
+ params.set(k, Array.isArray(v) ? v.join(',') : String(v));
89
+ }
90
+ const qs = params.toString();
91
+ const res = await this.request(`/stats${qs ? '?' + qs : ''}`);
92
+ return { ...res.data, meta: res.meta };
93
+ }
78
94
  async request(endpoint, options = {}) {
79
95
  const url = `${this.baseURL}${endpoint}`;
80
96
  const headers = new Headers(options.headers || {});
@@ -1,5 +1,5 @@
1
1
  import { ApiEmpresas } from '../ApiEmpresas';
2
- import { Company, BatchRequest, BatchResponse, ScoreData, BormeData, SignalsData, VerifyOptions, VerifyResult, FilterOptions, SegmentRow, SegmentMeta, ReconcileItem, ReconcileResult, ReconcileMeta } from '../types';
2
+ import { Company, BatchRequest, BatchResponse, ScoreData, BormeData, SignalsData, VerifyOptions, VerifyResult, FilterOptions, SegmentRow, SegmentMeta, ReconcileItem, ReconcileResult, ReconcileMeta, SubsidiesOptions, SubsidiesResult, ChangesOptions, ChangesResult, CompanyChange, VerifyBatchItem, VerifyBatchOptions, VerifyBatchRow, VerifyBatchMeta } from '../types';
3
3
  /** Opciones de get(): admin=true añade administradores y cargos (Pro/Business). */
4
4
  export interface GetOptions {
5
5
  admin?: boolean;
@@ -36,6 +36,19 @@ export declare class Companies {
36
36
  * alertas, con decision_hint pass / review / fail. Coste: 2 consultas.
37
37
  */
38
38
  verify(cif: string, options?: VerifyOptions): Promise<VerifyResult>;
39
+ /**
40
+ * (Pro, Business o saldo; desde 1.6.0) Valida en lote el NIF de los receptores de tus facturas
41
+ * (Verifactu, factura electrónica): hasta 1.000 por petición. Cada elemento puede ser un NIF o
42
+ * { cif, name?, ref? }: name es la razón social que tienes guardada y ref tu identificador (vuelve
43
+ * tal cual). Por cada NIF, en el mismo orden: valid_format, exists, legal_name, address,
44
+ * status_code, name_check e invoice_hint ('ok', 'revisar' o 'no_facturar') con sus motivos en flags.
45
+ * Cobro: 1 consulta por sociedad encontrada; NIF inválidos, de personas o que no constan, gratis.
46
+ * No sustituye la comprobación contra el censo de la AEAT.
47
+ */
48
+ verifyBatch(items: Array<string | VerifyBatchItem>, options?: VerifyBatchOptions): Promise<{
49
+ data: VerifyBatchRow[];
50
+ meta: VerifyBatchMeta;
51
+ }>;
39
52
  /**
40
53
  * (Pro) Nombre a CIF, hasta 100 por petición. 1 consulta por cada "match";
41
54
  * ambiguous y no_match no se cobran.
@@ -112,6 +125,23 @@ export declare class Companies {
112
125
  * (Business) Obtiene los contratos públicos y licitaciones adjudicadas a una empresa.
113
126
  */
114
127
  contracts(cif: string, page?: number, limit?: number): Promise<any>;
128
+ /**
129
+ * (Business, desde 1.5.0) Subvenciones y ayudas públicas de la BDNS desde 2022 (Kit Digital incluido):
130
+ * resumen por año, instrumento y convocatoria, y las concesiones paginadas. 1 consulta.
131
+ * En Free y Pro, ApiError 403 con el número y el importe en raw.upsell_opportunities.
132
+ */
133
+ subsidies(cif: string, options?: SubsidiesOptions): Promise<SubsidiesResult>;
134
+ /**
135
+ * (Business, desde 1.5.0) Feed de cambios: todas las sociedades con un acto en el BORME desde una
136
+ * fecha (hasta 30 días atrás), con qué ha cambiado y su estado actual. 1 consulta por página.
137
+ * Solo sociedades con CIF: las recién constituidas llegan por el webhook company.created.
138
+ */
139
+ changes(options?: ChangesOptions): Promise<ChangesResult>;
140
+ /**
141
+ * (Business, desde 1.5.0) Recorre todas las páginas del feed de cambios (1 consulta por página).
142
+ * for await (const c of api.companies.iterateChanges({ since: '2026-10-19' })) { ... }
143
+ */
144
+ iterateChanges(options?: ChangesOptions): AsyncGenerator<CompanyChange, void, unknown>;
115
145
  /**
116
146
  * (Business) Obtiene el perfil de riesgo corporativo y solvencia de una empresa.
117
147
  */
@@ -42,9 +42,32 @@ class Companies {
42
42
  params.set('person', options.person);
43
43
  if (options.vat)
44
44
  params.set('vat', 'true');
45
+ if (options.iban)
46
+ params.set('iban', options.iban);
45
47
  const response = await this.client.request(`/companies/verify?${params.toString()}`);
46
48
  return response.data;
47
49
  }
50
+ /**
51
+ * (Pro, Business o saldo; desde 1.6.0) Valida en lote el NIF de los receptores de tus facturas
52
+ * (Verifactu, factura electrónica): hasta 1.000 por petición. Cada elemento puede ser un NIF o
53
+ * { cif, name?, ref? }: name es la razón social que tienes guardada y ref tu identificador (vuelve
54
+ * tal cual). Por cada NIF, en el mismo orden: valid_format, exists, legal_name, address,
55
+ * status_code, name_check e invoice_hint ('ok', 'revisar' o 'no_facturar') con sus motivos en flags.
56
+ * Cobro: 1 consulta por sociedad encontrada; NIF inválidos, de personas o que no constan, gratis.
57
+ * No sustituye la comprobación contra el censo de la AEAT.
58
+ */
59
+ async verifyBatch(items, options = {}) {
60
+ const body = {
61
+ items: items.map((i) => (typeof i === 'string' ? { cif: i } : i)),
62
+ };
63
+ if (options.vat)
64
+ body.vat = true;
65
+ const response = await this.client.request('/companies/verify/batch', {
66
+ method: 'POST',
67
+ body: JSON.stringify(body)
68
+ });
69
+ return { data: response.data, meta: response.meta };
70
+ }
48
71
  /**
49
72
  * (Pro) Nombre a CIF, hasta 100 por petición. 1 consulta por cada "match";
50
73
  * ambiguous y no_match no se cobran.
@@ -195,6 +218,44 @@ class Companies {
195
218
  const response = await this.client.request(`/companies/contracts?${params.toString()}`);
196
219
  return response.data;
197
220
  }
221
+ /**
222
+ * (Business, desde 1.5.0) Subvenciones y ayudas públicas de la BDNS desde 2022 (Kit Digital incluido):
223
+ * resumen por año, instrumento y convocatoria, y las concesiones paginadas. 1 consulta.
224
+ * En Free y Pro, ApiError 403 con el número y el importe en raw.upsell_opportunities.
225
+ */
226
+ async subsidies(cif, options = {}) {
227
+ const params = new URLSearchParams({ cif });
228
+ if (options.year)
229
+ params.set('year', String(options.year));
230
+ if (options.page)
231
+ params.set('page', String(options.page));
232
+ if (options.limit)
233
+ params.set('limit', String(options.limit));
234
+ const response = await this.client.request(`/companies/subsidies?${params.toString()}`);
235
+ return response.data;
236
+ }
237
+ /**
238
+ * (Business, desde 1.5.0) Feed de cambios: todas las sociedades con un acto en el BORME desde una
239
+ * fecha (hasta 30 días atrás), con qué ha cambiado y su estado actual. 1 consulta por página.
240
+ * Solo sociedades con CIF: las recién constituidas llegan por el webhook company.created.
241
+ */
242
+ async changes(options = {}) {
243
+ const r = await this.client.request(`/companies/changes${(() => { const q = filterParams(options).toString(); return q ? '?' + q : ''; })()}`);
244
+ return { data: r.data, meta: r.meta };
245
+ }
246
+ /**
247
+ * (Business, desde 1.5.0) Recorre todas las páginas del feed de cambios (1 consulta por página).
248
+ * for await (const c of api.companies.iterateChanges({ since: '2026-10-19' })) { ... }
249
+ */
250
+ async *iterateChanges(options = {}) {
251
+ let cursor = options.cursor;
252
+ do {
253
+ const page = await this.changes({ ...options, cursor });
254
+ for (const c of page.data)
255
+ yield c;
256
+ cursor = page.meta.next_cursor || undefined;
257
+ } while (cursor);
258
+ }
198
259
  /**
199
260
  * (Business) Obtiene el perfil de riesgo corporativo y solvencia de una empresa.
200
261
  */
@@ -5,7 +5,10 @@ export declare class Webhooks {
5
5
  private client;
6
6
  constructor(client: ApiEmpresas);
7
7
  list(): Promise<any[]>;
8
- /** Guarda el secret que devuelve: con él se comprueba la firma (verifyWebhookSignature). */
8
+ /**
9
+ * Guarda el secret que devuelve: con él se comprueba la firma (verifyWebhookSignature).
10
+ * Con event 'company.created' puedes pasar filters (provincia, palabras del objeto social, capital...).
11
+ */
9
12
  create(options: WebhookCreateOptions): Promise<WebhookCreated>;
10
13
  remove(id: number): Promise<boolean>;
11
14
  /**
@@ -12,13 +12,19 @@ class Webhooks {
12
12
  const r = await this.client.request('/webhooks');
13
13
  return r.data;
14
14
  }
15
- /** Guarda el secret que devuelve: con él se comprueba la firma (verifyWebhookSignature). */
15
+ /**
16
+ * Guarda el secret que devuelve: con él se comprueba la firma (verifyWebhookSignature).
17
+ * Con event 'company.created' puedes pasar filters (provincia, palabras del objeto social, capital...).
18
+ */
16
19
  async create(options) {
17
20
  const r = await this.client.request('/webhooks', {
18
21
  method: 'POST',
19
22
  body: JSON.stringify(options)
20
23
  });
21
- return { id: r.id, event: r.event, secret: r.secret, message: r.message };
24
+ const out = { id: r.id, event: r.event, secret: r.secret, message: r.message };
25
+ if (r.filters)
26
+ out.filters = r.filters;
27
+ return out;
22
28
  }
23
29
  async remove(id) {
24
30
  const r = await this.client.request(`/webhooks/${encodeURIComponent(String(id))}`, { method: 'DELETE' });
package/dist/types.d.ts CHANGED
@@ -56,6 +56,12 @@ export interface Company {
56
56
  group?: CompanyGroup | null;
57
57
  /** Pro/Business (desde 1.3.0): socio único según el BORME. */
58
58
  ownership?: CompanyOwnership;
59
+ /** Pro/Business (desde 1.5.0): tramo de empleados con su fuente. null si no consta (nunca se estima). */
60
+ size?: CompanySize | null;
61
+ /** Pro/Business (desde 1.5.0): cuántas sociedades activas tienen la misma dirección exacta. */
62
+ address_density?: CompanyAddressDensity | null;
63
+ /** Todos los planes: fuente y fecha de cada bloque de datos. */
64
+ sources?: Record<string, any>;
59
65
  /** Solo con get(cif, { admin: true }) en Pro/Business. since: fecha del nombramiento. */
60
66
  administrators?: Array<{
61
67
  name: string;
@@ -114,6 +120,25 @@ export interface CompanyOwnership {
114
120
  source: 'borme' | 'name' | null;
115
121
  as_of: string | null;
116
122
  }
123
+ /** Tamaño por plantilla (desde 1.5.0). */
124
+ export interface CompanySize {
125
+ employees_min: number | null;
126
+ employees_max: number | null;
127
+ label: string | null;
128
+ /** micro (<10), small (10-49), medium (50-249) o large (250 o más, o no pyme). */
129
+ category: 'micro' | 'small' | 'medium' | 'large' | null;
130
+ /** kit_digital, kit_consulting, ted o placsp. */
131
+ source: string | null;
132
+ as_of: string | null;
133
+ }
134
+ /** Domicilio compartido (desde 1.5.0). */
135
+ export interface CompanyAddressDensity {
136
+ active_companies_at_address: number;
137
+ /** normal (menos de 10), shared (10-49) o mass (50 o más). */
138
+ level: 'normal' | 'shared' | 'mass';
139
+ match: string;
140
+ as_of: string | null;
141
+ }
117
142
  export interface CompanyFinancials {
118
143
  size_band?: string | null;
119
144
  size_band_label?: string | null;
@@ -126,6 +151,21 @@ export interface VerifyOptions {
126
151
  person?: string;
127
152
  /** true: comprueba el NIF-IVA intracomunitario en VIES. */
128
153
  vat?: boolean;
154
+ /** (desde 1.5.0) IBAN que te han dado: se comprueba que está bien formado. No dice de quién es la cuenta. */
155
+ iban?: string;
156
+ }
157
+ /** Comprobación del IBAN en verify (desde 1.5.0). */
158
+ export interface IbanCheck {
159
+ /** Enmascarado: ES91****************1332. */
160
+ provided: string;
161
+ valid: boolean;
162
+ country: string | null;
163
+ sepa: boolean;
164
+ /** Solo IBAN españoles: entidad (4 cifras) y oficina. */
165
+ bank_code: string | null;
166
+ branch_code: string | null;
167
+ /** Si no es válido: FORMAT, LENGTH, CHECKSUM o NATIONAL_CHECK_DIGITS. */
168
+ reason: 'FORMAT' | 'LENGTH' | 'CHECKSUM' | 'NATIONAL_CHECK_DIGITS' | null;
129
169
  }
130
170
  export interface VerifyFlag {
131
171
  code: string;
@@ -144,6 +184,10 @@ export interface VerifyResult {
144
184
  legal_form?: CompanyLegalForm;
145
185
  group?: CompanyGroup | null;
146
186
  ownership?: CompanyOwnership;
187
+ /** (desde 1.5.0) */
188
+ size?: CompanySize | null;
189
+ /** (desde 1.5.0) Con 10 o más sociedades sale la alerta SHARED_ADDRESS; con 50, MASS_ADDRESS. */
190
+ address_density?: CompanyAddressDensity | null;
147
191
  checks: {
148
192
  name?: {
149
193
  provided: string;
@@ -168,6 +212,8 @@ export interface VerifyResult {
168
212
  accounts?: {
169
213
  last_accounts_year: number | null;
170
214
  };
215
+ /** (desde 1.5.0) Solo si pasas iban. Si no es válido, alerta IBAN_INVALID y decision_hint review. */
216
+ iban?: IbanCheck;
171
217
  /** Solo en Business: listas de sanciones (UE, ONU, OFAC) de la empresa y sus administradores. */
172
218
  sanctions?: {
173
219
  result: SanctionsResultCode;
@@ -237,6 +283,8 @@ export interface FilterOptions {
237
283
  founded_to?: string;
238
284
  has_phone?: boolean;
239
285
  size_band?: Array<'NO_REVENUE' | 'LT_500K' | '500K_1M' | 'GT_1M'> | string;
286
+ /** (desde 1.5.0) Tamaño por plantilla: micro, small, medium, large. */
287
+ size_category?: Array<'micro' | 'small' | 'medium' | 'large'> | string;
240
288
  min_accounts_year?: number;
241
289
  /** Filas por página (1-1000). */
242
290
  limit?: number;
@@ -254,6 +302,8 @@ export interface SegmentRow {
254
302
  status_code: StatusCode | null;
255
303
  status_source: string | null;
256
304
  financials: CompanyFinancials | null;
305
+ /** (desde 1.5.0) */
306
+ size?: CompanySize | null;
257
307
  has_phone: boolean;
258
308
  }
259
309
  export interface SegmentMeta {
@@ -301,18 +351,37 @@ export interface WatchlistEventsOptions {
301
351
  page?: number;
302
352
  limit?: number;
303
353
  }
304
- export type WebhookEvent = 'company.borme_act' | 'company.status_changed' | 'company.risk_level_changed' | 'watchlist.*' | 'test.ping' | string;
354
+ export type WebhookEvent = 'company.created' | 'company.borme_act' | 'company.status_changed' | 'company.risk_level_changed' | 'watchlist.*' | 'test.ping' | string;
355
+ /** Filtros del evento company.created (desde 1.5.0). Sin filtros llegan todas las sociedades nuevas. */
356
+ export interface CompanyCreatedFilters {
357
+ /** Provincias del Registro Mercantil (hasta 10). Valores en catalog(). */
358
+ province?: string[];
359
+ /** Municipios (hasta 20). */
360
+ municipality?: string[];
361
+ /** Palabras del objeto social o del nombre; basta con una (hasta 20, de 3 caracteres o más). */
362
+ keywords?: string[];
363
+ /** Prefijos CNAE (hasta 20). Las recién constituidas casi nunca lo tienen: mejor keywords. */
364
+ cnae?: string[];
365
+ /** Capital social mínimo en euros. */
366
+ min_capital?: number;
367
+ /** SL, SA, SLP, SLL, SCOOP... */
368
+ legal_form?: string[];
369
+ }
305
370
  export interface WebhookCreateOptions {
306
371
  url: string;
307
372
  event: WebhookEvent;
308
373
  /** Si no lo pasas, la API genera uno y lo devuelve. */
309
374
  secret?: string;
375
+ /** (desde 1.5.0) Solo con event 'company.created'. */
376
+ filters?: CompanyCreatedFilters;
310
377
  }
311
378
  export interface WebhookCreated {
312
379
  id: number;
313
380
  event: string;
314
381
  secret: string;
315
382
  message?: string;
383
+ /** (desde 1.5.0) Los filtros tal como los ha guardado la API (en mayúsculas). */
384
+ filters?: CompanyCreatedFilters;
316
385
  }
317
386
  export interface WebhookTestResult {
318
387
  delivered: boolean;
@@ -378,6 +447,11 @@ export interface CatalogData {
378
447
  score_priority: string[];
379
448
  webhook_events: string[];
380
449
  watchlist_event_types: string[];
450
+ /** (desde 1.5.0) Tipos de cambio del feed companies.changes(). */
451
+ change_types?: Array<{
452
+ value: string;
453
+ label: string;
454
+ } | string>;
381
455
  [key: string]: any;
382
456
  }
383
457
  /** Cuerpo que recibe tu servidor. */
@@ -599,3 +673,213 @@ export interface SanctionsResult {
599
673
  checked_at: string;
600
674
  note: string;
601
675
  }
676
+ export interface SubsidiesOptions {
677
+ /** Solo las concesiones de ese año. */
678
+ year?: number;
679
+ page?: number;
680
+ /** 1-100 (20 por defecto). */
681
+ limit?: number;
682
+ }
683
+ export interface Subsidy {
684
+ grant_date: string | null;
685
+ /** Texto con dos decimales, como en contracts(). */
686
+ amount: string | null;
687
+ currency: 'EUR';
688
+ call: string | null;
689
+ instrument: string | null;
690
+ grant_code: string | null;
691
+ }
692
+ export interface SubsidiesSummary {
693
+ total_grants: number;
694
+ total_amount: string;
695
+ currency: 'EUR';
696
+ first_grant_date: string | null;
697
+ last_grant_date: string | null;
698
+ by_year: Array<{
699
+ year: number | null;
700
+ grants: number;
701
+ amount: string;
702
+ }>;
703
+ by_instrument: Array<{
704
+ instrument: string | null;
705
+ grants: number;
706
+ amount: string;
707
+ }>;
708
+ top_calls: Array<{
709
+ call: string | null;
710
+ grants: number;
711
+ amount: string;
712
+ last_grant_date: string | null;
713
+ }>;
714
+ }
715
+ export interface SubsidiesResult {
716
+ cif: string;
717
+ company_name: string | null;
718
+ year: number | null;
719
+ summary: SubsidiesSummary;
720
+ grants: Subsidy[];
721
+ pagination: {
722
+ total: number;
723
+ page: number;
724
+ limit: number;
725
+ total_pages: number;
726
+ has_more: boolean;
727
+ };
728
+ sources: {
729
+ subsidies: {
730
+ source: 'bdns';
731
+ as_of: string | null;
732
+ from: string;
733
+ };
734
+ };
735
+ previous_cif_match?: any;
736
+ }
737
+ export type ChangeType = 'incorporation' | 'officers' | 'address' | 'name' | 'purpose' | 'capital' | 'sole_shareholder' | 'dissolution' | 'insolvency' | 'structural' | 'registry_closure' | 'other';
738
+ export interface ChangesOptions {
739
+ /** AAAA-MM-DD (incluida). Por defecto, ayer. Como mucho 30 días atrás. */
740
+ since?: string;
741
+ /** AAAA-MM-DD (incluida). */
742
+ until?: string;
743
+ types?: ChangeType[] | string;
744
+ province?: string;
745
+ /** Prefijos CNAE. */
746
+ cnae?: string[] | string;
747
+ /** 1-1000 (500 por defecto). */
748
+ limit?: number;
749
+ /** meta.next_cursor de la página anterior. */
750
+ cursor?: string;
751
+ }
752
+ export interface CompanyChange {
753
+ /** Estable: úsalo para no procesar dos veces el mismo cambio. */
754
+ id: string;
755
+ date: string;
756
+ cif: string;
757
+ company_name: string | null;
758
+ change_types: ChangeType[];
759
+ /** Tipos de acto tal como los publica el BORME (en español). */
760
+ act_types: string[];
761
+ status_code: StatusCode | null;
762
+ province: string | null;
763
+ cnae: string | null;
764
+ borme_pdf: string | null;
765
+ }
766
+ export interface ChangesMeta {
767
+ since: string;
768
+ until: string | null;
769
+ filters: Record<string, any>;
770
+ count: number;
771
+ limit: number;
772
+ has_more: boolean;
773
+ next_cursor: string | null;
774
+ last_borme_date: string | null;
775
+ }
776
+ export interface ChangesResult {
777
+ data: CompanyChange[];
778
+ meta: ChangesMeta;
779
+ }
780
+ export type StatsMetric = 'incorporations' | 'dissolutions' | 'extinctions' | 'insolvencies' | 'capital_increases' | 'capital_reductions' | 'address_changes' | 'mergers';
781
+ export interface StatsOptions {
782
+ /** Por defecto, todas. */
783
+ metrics?: StatsMetric[] | string;
784
+ /** Nombre de catalog() (MADRID) o código INE (28). Sin ella, toda España. */
785
+ province?: string;
786
+ /** AAAA-MM o AAAA. Por defecto, 11 meses antes de to. */
787
+ from?: string;
788
+ /** AAAA-MM o AAAA. Por defecto, el mes actual. */
789
+ to?: string;
790
+ group?: 'month' | 'year';
791
+ }
792
+ export interface StatsResult {
793
+ province: string | null;
794
+ province_code: string | null;
795
+ group: 'month' | 'year';
796
+ from: string;
797
+ to: string;
798
+ totals: Partial<Record<StatsMetric, number>>;
799
+ /** Una fila por periodo (sin huecos: 0 si no hubo actos). */
800
+ series: Array<{
801
+ period: string;
802
+ } & Partial<Record<StatsMetric, number>>>;
803
+ meta?: {
804
+ source: 'borme';
805
+ last_borme_date: string | null;
806
+ computed_at: string | null;
807
+ notes: string;
808
+ };
809
+ }
810
+ export interface VerifyBatchItem {
811
+ /** NIF del cliente (CIF, DNI o NIE). */
812
+ cif: string;
813
+ /** Razón social que tienes guardada: se compara con la oficial (name_check). */
814
+ name?: string;
815
+ /** Tu identificador (id de cliente...): se devuelve tal cual. */
816
+ ref?: string;
817
+ }
818
+ export interface VerifyBatchOptions {
819
+ /** Comprobar también el NIF-IVA en VIES (solo lotes de hasta 20). */
820
+ vat?: boolean;
821
+ }
822
+ export type InvoiceHint = 'ok' | 'revisar' | 'no_facturar';
823
+ export interface VerifyBatchFlag {
824
+ /** EXTINCT, MERGED, INSOLVENCY, DISSOLVED, IN_LIQUIDATION, REGISTRY_CLOSED, INACTIVE, STATUS_UNKNOWN,
825
+ * NAME_MISMATCH, VAT_NOT_IN_VIES, PERSON_NIF, FAKE_CIF, NOT_FOUND, INVALID_FORMAT, NOT_PROCESSED_QUOTA. */
826
+ code: string;
827
+ severity: 'info' | 'low' | 'medium' | 'high';
828
+ message: string;
829
+ }
830
+ export interface VerifyBatchRow {
831
+ /** Lo que enviaste, sin tocar. */
832
+ input: string;
833
+ /** NIF normalizado (sin espacios, guiones ni prefijo ES); null si no se reconoce. */
834
+ cif: string | null;
835
+ ref?: string;
836
+ /** Dígito o letra de control correctos (CIF, DNI y NIE). */
837
+ valid_format: boolean;
838
+ /** false si no se ha comprobado por falta de cupo o saldo (flag NOT_PROCESSED_QUOTA; no se cobra). */
839
+ processed: boolean;
840
+ /** true/false si es una sociedad; null si es una persona física, el formato no es válido o no se ha procesado. */
841
+ exists: boolean | null;
842
+ legal_name?: string | null;
843
+ address?: {
844
+ street: string | null;
845
+ postal_code: string | null;
846
+ municipality: string | null;
847
+ province: string | null;
848
+ };
849
+ /** ACTIVE, INSOLVENCY, DISSOLVED, IN_LIQUIDATION, EXTINCT, MERGED, REGISTRY_CLOSED, INACTIVE, UNKNOWN... */
850
+ status_code?: string;
851
+ status_date?: string | null;
852
+ /** Solo si enviaste name: parecido 0-100 y si coincide (desde 80). */
853
+ name_check?: {
854
+ provided: string;
855
+ score: number;
856
+ match: boolean;
857
+ };
858
+ /** Solo con vat: true. */
859
+ vat?: {
860
+ vat_number: string;
861
+ checked: boolean;
862
+ valid: boolean | null;
863
+ [k: string]: any;
864
+ };
865
+ /** null si no se ha procesado. */
866
+ invoice_hint: InvoiceHint | null;
867
+ flags: VerifyBatchFlag[];
868
+ }
869
+ export interface VerifyBatchMeta {
870
+ requested: number;
871
+ /** Sociedades encontradas (cada NIF distinto cuenta una vez). */
872
+ found: number;
873
+ /** Consultas (o créditos) cobradas. */
874
+ cost: number;
875
+ /** true si no llegó el cupo para todas: las que faltan van con processed: false. */
876
+ truncated: boolean;
877
+ summary: {
878
+ ok: number;
879
+ revisar: number;
880
+ no_facturar: number;
881
+ not_processed: number;
882
+ };
883
+ checked_at: string;
884
+ note: string;
885
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "apiempresas",
3
- "version": "1.4.0",
3
+ "version": "1.6.0",
4
4
  "description": "SDK oficial de APIEmpresas.es para Node.js y TypeScript",
5
5
  "main": "dist/index.js",
6
6
  "files": [