intifact 1.1.1 → 1.2.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
@@ -1,85 +1,93 @@
1
1
  # intifact
2
2
 
3
- SDK TypeScript auto-generado para la **API de Facturación Electrónica SUNAT de Intifact** (Perú).
3
+ SDK TypeScript para la API de Facturación Electrónica SUNAT de [Intifact](https://intifact.com).
4
4
 
5
- Sigue siempre la versión más reciente de la API: los tipos se regeneran desde el `openapi.json` que la API expone en `/docs/json`.
6
-
7
- ## Instalación
5
+ Wrapper tipado sobre `openapi-fetch`: los tipos de request y response se generan
6
+ del OpenAPI de la API, así que el editor te avisa si mandás un campo que no
7
+ existe o te falta uno obligatorio.
8
8
 
9
9
  ```bash
10
10
  npm install intifact
11
11
  ```
12
12
 
13
- ## Uso básico
13
+ ## Uso
14
14
 
15
15
  ```ts
16
16
  import { FacturacionClient } from "intifact";
17
17
 
18
18
  const fact = new FacturacionClient({
19
19
  baseUrl: "https://api-facturacion.intifact.com",
20
- apiKey: process.env.FACTURACION_API_KEY, // tu API key fact_live_/fact_test_
20
+ apiKey: "fact_live_...",
21
21
  });
22
22
 
23
- // Enviar factura → 202 (encolada)
24
- const { data, error } = await fact.sendInvoice({
25
- tipoDoc: "01",
26
- serie: "F001",
27
- correlativo: "1",
28
- empresaRuc: "20553510661",
29
- /* ...resto del payload */
30
- });
23
+ const { data, error } = await fact.sendInvoice({ /* ... */ });
24
+ if (error) throw new Error(error.message);
25
+ console.log("encolado:", data.data?.id);
26
+ ```
27
+
28
+ ## El envío es asíncrono
31
29
 
32
- if (error) throw error;
33
- console.log("Encolada:", data.data.id);
30
+ Ningún `send*` devuelve el CDR. La API responde **202** con
31
+ `{ id, estado, hash, jobId }` y encola el documento; el resultado de SUNAT llega
32
+ después. Tenés dos formas de enterarte:
34
33
 
35
- // Esperar hasta que SUNAT responda
36
- const finalDoc = await fact.waitForDocument(data.data.id);
37
- console.log("Estado:", finalDoc.data.sunat.estado);
34
+ - **Webhook** (recomendado): `createWebhook()` y escuchás `document.accepted` /
35
+ `document.rejected`.
36
+ - **Polling**: `waitForDocument(id)` hace polling hasta un estado final
37
+ (`ACEPTADO`, `RECHAZADO`, `COLA_FALLIDA`, `ANULADO`) o timeout.
38
+
39
+ ```ts
40
+ const { data } = await fact.sendInvoice(payload);
41
+ const doc = await fact.waitForDocument(data.data.id, { timeoutMs: 120_000 });
38
42
  ```
39
43
 
40
- ## Métodos
44
+ ## Qué cubre
41
45
 
42
- ### Emisión
43
- - `sendInvoice(body)` — factura (01) o boleta (03)
44
- - `sendNote(body)` — nota crédito (07) o débito (08)
45
- - `sendDespatch(body)` — guía remisión (09 - GRE REST)
46
- - `sendSummary(body)` — resumen diario boletas
47
- - `sendVoided(body)` — comunicación de baja
46
+ | Área | Métodos |
47
+ |---|---|
48
+ | Comprobantes | `sendInvoice`, `computeInvoice`, `sendNote`, `computeNote` |
49
+ | Guías | `sendDespatch`, `sendDespatchMulti`, `sendDespatchTransportista` |
50
+ | Anulaciones | `cancelInvoice`, `cancelBoleta`, `sendVoided`, `sendSummary` |
51
+ | Documentos | `listDocuments`, `getDocument`, `retryDocument`, `getNextCorrelativo`, `waitForDocument` |
52
+ | Archivos | `getInvoiceXml/Cdr/Pdf`, `getNoteXml/Pdf/Cdr`, `getDespatchXml/Cdr/Pdf` |
53
+ | CDR | `consultarCdr` |
54
+ | Empresas | `listCompanies`, `getCompany`, `getCompanyLogo` |
55
+ | Webhooks | `createWebhook`, `listWebhooks`, `getWebhook`, `updateWebhook`, `deleteWebhook`, `listWebhookDeliveries`, `redeliverWebhook`, `testWebhook`, `rotateWebhookSecret` |
56
+ | Catálogos | `getCatalogs`, `getCatalog` |
57
+ | Consulta pública | `consultarComprobante`, `consultarComprobantePdf`, `consultarComprobanteXml` |
58
+ | Colas | `getQueueStats` |
59
+ | Tickets | `getTicketStatus` |
48
60
 
49
- ### Consultas
50
- - `listDocuments(query?)` — listado paginado con filtros
51
- - `getDocument(id)` — detalle completo
52
- - `getTicketStatus(ticket, ruc)` — estado de ticket asíncrono
61
+ Las operaciones administrativas (crear empresas, subir certificado, gestionar
62
+ API keys, tenants, auditoría, planes, reconciliación con SUNAT) requieren
63
+ `MASTER_API_KEY` y **no** se exponen acá a propósito — las llama el backend
64
+ directo.
53
65
 
54
- ### Archivos
55
- - `getInvoiceXml(id)` → ArrayBuffer
56
- - `getInvoiceCdr(id)` → ArrayBuffer (constancia SUNAT)
57
- - `getInvoicePdf(id)` → ArrayBuffer
66
+ ## PDF de guías en ticket
58
67
 
59
- ### Cola
60
- - `retryDocument(id)` — re-encolar documento fallido
61
- - `getQueueStats()` — estado de BullMQ
62
- - `waitForDocument(id, opts?)` — polling hasta estado final
68
+ `getDespatchPdf(id, format)` acepta `"a4"` (default), `"ticket80"` y
69
+ `"ticket58"`.
63
70
 
64
- ### Empresas (solo lectura)
65
- - `listCompanies()`
66
- - `getCompany(id)`
71
+ ## Regenerar los tipos
67
72
 
68
- > Crear empresas, subir certificado/logo son operaciones administrativas
69
- > (requieren `MASTER_API_KEY`) y no se exponen en el SDK — las gestiona el backend.
73
+ Los tipos salen del OpenAPI de la API, no se escriben a mano:
70
74
 
71
- ## Regenerar tipos
75
+ ```bash
76
+ npm run gen # baja el spec de localhost:3000
77
+ npm run build
78
+ ```
72
79
 
73
- Cada vez que la API agrega o cambia endpoints:
80
+ Si el server no está levantado, la API sabe volcar el spec sin HTTP:
74
81
 
75
82
  ```bash
76
- npm run gen # contra http://localhost:3000
77
- npm run gen -- --url=... # contra producción
83
+ cd ../api-facturacion && npx tsx scripts/dump-openapi.ts spec.json
84
+ cd ../api-facturacion-sdk && SPEC_FILE=../api-facturacion/spec.json npm run gen
78
85
  ```
79
86
 
80
- Esto descarga `openapi.json` y regenera `src/types.ts` con `openapi-typescript`.
87
+ **Ojo:** con `SPEC_URL` el server tiene que estar corriendo con el código ya
88
+ mergeado. Si generás antes de tocar los schemas Zod, sale el spec viejo y los
89
+ campos nuevos no aparecen.
81
90
 
82
- ## Stack
91
+ ## Licencia
83
92
 
84
- - `openapi-typescript` — genera tipos TS desde la spec
85
- - `openapi-fetch` — runtime client liviano (<6kB) con tipado completo
93
+ MIT