apiempresas 1.4.0 → 1.5.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
 
@@ -119,6 +120,13 @@ await api.watchlist.remove('A28015865');
119
120
 
120
121
  ```typescript
121
122
  const hook = await api.webhooks.create({ url: 'https://tu-servidor.com/apiempresas', event: 'watchlist.*' });
123
+
124
+ // (1.5.0) Sociedades nuevas del BORME del día, con filtros opcionales
125
+ const nuevas = await api.webhooks.create({
126
+ url: 'https://tu-servidor.com/nuevas',
127
+ event: 'company.created',
128
+ filters: { province: ['MADRID', 'BARCELONA'], keywords: ['software', 'informática'], min_capital: 3000 }
129
+ });
122
130
  // Guarda hook.secret: con él se comprueba la firma.
123
131
  await api.webhooks.test(hook.id); // envía un test.ping y devuelve lo que respondió tu servidor
124
132
 
@@ -135,7 +143,7 @@ import { constructWebhookEvent } from 'apiempresas';
135
143
  app.post('/apiempresas', express.raw({ type: 'application/json' }), (req, res) => {
136
144
  try {
137
145
  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
146
+ // evento.event: company.created | company.borme_act | company.status_changed | company.risk_level_changed | test.ping
139
147
  // Usa evento.id (o la cabecera X-ApiEmpresas-Delivery) para no procesar dos veces el mismo envío.
140
148
  res.sendStatus(200);
141
149
  } catch {
@@ -171,9 +179,43 @@ const p = await api.sanctions.screen({ name: 'Vladimir Putin', type: 'person' })
171
179
 
172
180
  En `companies.verify()` con Business, el resultado incluye `checks.sanctions`.
173
181
 
182
+ ### 10. Subvenciones y ayudas públicas (Business, desde 1.5.0) — 1 consulta
183
+
184
+ ```typescript
185
+ // Concesiones de la BDNS desde 2022 (Kit Digital incluido)
186
+ const s = await api.companies.subsidies('B12345678', { year: 2025, limit: 50 });
187
+ console.log(s.summary.total_grants, s.summary.total_amount); // importes en texto con dos decimales
188
+ console.log(s.summary.by_year, s.summary.top_calls);
189
+ for (const g of s.grants) console.log(g.grant_date, g.amount, g.call);
190
+ ```
191
+
192
+ ### 11. Feed de cambios (Business, desde 1.5.0) — 1 consulta por página
193
+
194
+ ```typescript
195
+ // Todas las sociedades con un acto en el BORME desde una fecha (hasta 30 días atrás)
196
+ const { data, meta } = await api.companies.changes({ since: '2026-10-19', types: ['address', 'officers'], province: 'MADRID' });
197
+ // Siguiente página: api.companies.changes({ ...mismosFiltros, cursor: meta.next_cursor })
198
+
199
+ // O recorre todas las páginas
200
+ for await (const c of api.companies.iterateChanges({ since: '2026-10-19' })) {
201
+ console.log(c.id, c.cif, c.change_types, c.status_code); // usa c.id para no procesar dos veces el mismo cambio
202
+ }
203
+ ```
204
+
205
+ 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`.
206
+
207
+ ### 12. Estadísticas del BORME (todos los planes, desde 1.5.0) — 1 consulta
208
+
209
+ ```typescript
210
+ const st = await api.stats({ metrics: ['incorporations', 'dissolutions'], province: 'MADRID', from: '2025-01', to: '2025-12' });
211
+ console.log(st.totals.incorporations);
212
+ for (const fila of st.series) console.log(fila.period, fila.incorporations);
213
+ // Por años: api.stats({ group: 'year', from: '2015', to: '2025' })
214
+ ```
215
+
174
216
  ## Entorno de Pruebas (Sandbox)
175
217
 
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).
218
+ 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
219
 
178
220
  ```typescript
179
221
  const api = new ApiEmpresas({
@@ -193,7 +235,7 @@ console.log(u.stats.remaining_calls, u.stats.wallet_balance, u.stats.quota_reset
193
235
 
194
236
  ```typescript
195
237
  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);
238
+ console.log(cat.province, cat.size_band, cat.radar.priority, cat.webhook_events, cat.change_types);
197
239
  ```
198
240
 
199
241
  ## 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.5.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.5.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 } 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;
@@ -112,6 +112,23 @@ export declare class Companies {
112
112
  * (Business) Obtiene los contratos públicos y licitaciones adjudicadas a una empresa.
113
113
  */
114
114
  contracts(cif: string, page?: number, limit?: number): Promise<any>;
115
+ /**
116
+ * (Business, desde 1.5.0) Subvenciones y ayudas públicas de la BDNS desde 2022 (Kit Digital incluido):
117
+ * resumen por año, instrumento y convocatoria, y las concesiones paginadas. 1 consulta.
118
+ * En Free y Pro, ApiError 403 con el número y el importe en raw.upsell_opportunities.
119
+ */
120
+ subsidies(cif: string, options?: SubsidiesOptions): Promise<SubsidiesResult>;
121
+ /**
122
+ * (Business, desde 1.5.0) Feed de cambios: todas las sociedades con un acto en el BORME desde una
123
+ * fecha (hasta 30 días atrás), con qué ha cambiado y su estado actual. 1 consulta por página.
124
+ * Solo sociedades con CIF: las recién constituidas llegan por el webhook company.created.
125
+ */
126
+ changes(options?: ChangesOptions): Promise<ChangesResult>;
127
+ /**
128
+ * (Business, desde 1.5.0) Recorre todas las páginas del feed de cambios (1 consulta por página).
129
+ * for await (const c of api.companies.iterateChanges({ since: '2026-10-19' })) { ... }
130
+ */
131
+ iterateChanges(options?: ChangesOptions): AsyncGenerator<CompanyChange, void, unknown>;
115
132
  /**
116
133
  * (Business) Obtiene el perfil de riesgo corporativo y solvencia de una empresa.
117
134
  */
@@ -42,6 +42,8 @@ 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
  }
@@ -195,6 +197,44 @@ class Companies {
195
197
  const response = await this.client.request(`/companies/contracts?${params.toString()}`);
196
198
  return response.data;
197
199
  }
200
+ /**
201
+ * (Business, desde 1.5.0) Subvenciones y ayudas públicas de la BDNS desde 2022 (Kit Digital incluido):
202
+ * resumen por año, instrumento y convocatoria, y las concesiones paginadas. 1 consulta.
203
+ * En Free y Pro, ApiError 403 con el número y el importe en raw.upsell_opportunities.
204
+ */
205
+ async subsidies(cif, options = {}) {
206
+ const params = new URLSearchParams({ cif });
207
+ if (options.year)
208
+ params.set('year', String(options.year));
209
+ if (options.page)
210
+ params.set('page', String(options.page));
211
+ if (options.limit)
212
+ params.set('limit', String(options.limit));
213
+ const response = await this.client.request(`/companies/subsidies?${params.toString()}`);
214
+ return response.data;
215
+ }
216
+ /**
217
+ * (Business, desde 1.5.0) Feed de cambios: todas las sociedades con un acto en el BORME desde una
218
+ * fecha (hasta 30 días atrás), con qué ha cambiado y su estado actual. 1 consulta por página.
219
+ * Solo sociedades con CIF: las recién constituidas llegan por el webhook company.created.
220
+ */
221
+ async changes(options = {}) {
222
+ const r = await this.client.request(`/companies/changes${(() => { const q = filterParams(options).toString(); return q ? '?' + q : ''; })()}`);
223
+ return { data: r.data, meta: r.meta };
224
+ }
225
+ /**
226
+ * (Business, desde 1.5.0) Recorre todas las páginas del feed de cambios (1 consulta por página).
227
+ * for await (const c of api.companies.iterateChanges({ since: '2026-10-19' })) { ... }
228
+ */
229
+ async *iterateChanges(options = {}) {
230
+ let cursor = options.cursor;
231
+ do {
232
+ const page = await this.changes({ ...options, cursor });
233
+ for (const c of page.data)
234
+ yield c;
235
+ cursor = page.meta.next_cursor || undefined;
236
+ } while (cursor);
237
+ }
198
238
  /**
199
239
  * (Business) Obtiene el perfil de riesgo corporativo y solvencia de una empresa.
200
240
  */
@@ -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,137 @@ 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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "apiempresas",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "description": "SDK oficial de APIEmpresas.es para Node.js y TypeScript",
5
5
  "main": "dist/index.js",
6
6
  "files": [