@devly-cl/sii-client 0.5.0 → 0.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.
Files changed (36) hide show
  1. package/README.md +36 -4
  2. package/dist/application/invoice-queries.d.ts +17 -0
  3. package/dist/application/invoice-queries.js +51 -0
  4. package/dist/application/issuance.d.ts +40 -0
  5. package/dist/application/issuance.js +79 -0
  6. package/dist/contracts.d.ts +66 -0
  7. package/dist/contracts.js +2 -0
  8. package/dist/domain/document.d.ts +47 -0
  9. package/dist/domain/document.js +38 -0
  10. package/dist/domain/invoice-xml.d.ts +0 -10
  11. package/dist/domain/invoice-xml.js +0 -170
  12. package/dist/domain/issued-invoice.d.ts +1 -2
  13. package/dist/domain/issued-invoice.js +4 -43
  14. package/dist/domain/received-invoice.d.ts +1 -3
  15. package/dist/domain/received-invoice.js +0 -10
  16. package/dist/index.d.ts +5 -3
  17. package/dist/index.js +4 -3
  18. package/dist/infrastructure/dte-xml.d.ts +11 -0
  19. package/dist/infrastructure/dte-xml.js +173 -0
  20. package/dist/infrastructure/facturador-gateway.d.ts +28 -0
  21. package/dist/infrastructure/facturador-gateway.js +411 -0
  22. package/dist/infrastructure/facturador.d.ts +10 -3
  23. package/dist/infrastructure/facturador.js +16 -2
  24. package/dist/infrastructure/invoice-pdf.d.ts +9 -0
  25. package/dist/infrastructure/invoice-pdf.js +171 -0
  26. package/dist/infrastructure/rcv-gateway.d.ts +17 -0
  27. package/dist/infrastructure/rcv-gateway.js +105 -0
  28. package/dist/infrastructure/rcv-normalization.d.ts +6 -0
  29. package/dist/infrastructure/rcv-normalization.js +55 -0
  30. package/dist/infrastructure/sii-client.d.ts +22 -121
  31. package/dist/infrastructure/sii-client.js +45 -774
  32. package/dist/infrastructure/sii-http-session.d.ts +25 -0
  33. package/dist/infrastructure/sii-http-session.js +344 -0
  34. package/dist/sii-error.d.ts +27 -0
  35. package/dist/sii-error.js +86 -0
  36. package/package.json +4 -4
package/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # SII Client
2
2
 
3
- `@devly-cl/sii-client` es una biblioteca TypeScript independiente de framework. Inicia sesión personal en SII, comprueba autorización sobre una empresa y consulta resúmenes del Registro de Compras y Ventas y facturas emitidas y recibidas 33/34 mediante HTTP/JSON. La ampliación de este repositorio incorpora preparación, firma y envío de facturas 33 y notas de crédito 61 de anulación total mediante el facturador gratuito. Credenciales por parámetros; sin variables de entorno para login o firma.
3
+ `@devly-cl/sii-client` es una biblioteca TypeScript independiente de framework. Inicia sesión personal en SII, comprueba autorización sobre una empresa y consulta resúmenes del Registro de Compras y Ventas y facturas emitidas y recibidas 33/34 mediante HTTP/JSON. La ampliación de este repositorio incorpora PDF originales por streaming y preparación, firma y envío de facturas 33 y notas de crédito 61 de anulación total mediante el facturador gratuito. Credenciales por parámetros; sin variables de entorno para login o firma.
4
4
 
5
- Basado en los servicios internos observados del portal. No es una API pública oficial ni una integración certificada. La versión 0.5.0 incorpora emisión y nombres canónicos en inglés; la publicación se verifica por separado de las pruebas fiscales reales. La prueba real del prototipo de lectura se realizó el 30-09-2026; el análisis, contrato observado y evidencia HTTP están en `docs/sii/` del repositorio, fuera del paquete npm.
5
+ Basado en los servicios internos observados del portal. No es una API pública oficial ni una integración certificada. La versión 0.6.0 agrega PDF por streaming y conserva emisión, XML y aliases; la publicación se verifica por separado de las pruebas fiscales reales. La prueba real del prototipo de lectura se realizó el 30-09-2026; el análisis, contrato observado y evidencia HTTP están en `docs/sii/` del repositorio, fuera del paquete npm.
6
6
 
7
7
  ## Desarrollo
8
8
 
@@ -16,6 +16,14 @@ npm pack
16
16
 
17
17
  `check` verifica tipos, genera `dist`, ejecuta checks de integración HTTP simulada/autorización y facturas emitidas, y compila el ejemplo. `npm pack` vuelve a validar antes de crear el tarball. `dist` y `node_modules` no se versionan. El paquete contiene sólo `dist` y este README.
18
18
 
19
+ ## Arquitectura y límites de lectura
20
+
21
+ `SiiClient` conserva la API pública y compone sesión/transporte, RCV y facturador. `domain` contiene modelos y políticas fiscales; `application` controla cobertura, aprobación y envío mediante puertos tipados; `infrastructure` implementa HTTP, normalización del proveedor, HTML y XML. Las políticas y casos de uso se prueban también sin servidor ni parsers externos. Los adaptadores internos no forman una API adicional del paquete.
22
+
23
+ Las lecturas JSON/XML permanecen activas hasta consumir y procesar su body. Si `dispose()` comienza durante una de estas lecturas, espera su finalización y rechaza su resultado con `CLIENT_CLOSED` antes del logout. También espera escrituras activas; la limpieza queda fuera del trabajo que espera para evitar bloqueos. Los PDF pendientes se cancelan y se espera el cierre de su origen antes del logout, incluso si el consumidor todavía no leyó el stream. Repetir el cierre mantiene un único logout.
24
+
25
+ JSON tiene un límite interno de 16 MiB medido durante la lectura, independiente de `Content-Length`. Al excederlo, cancela el stream y devuelve `SII_PROTOCOL_CHANGED` con diagnóstico `RESPONSE_TOO_LARGE`, sin reintentar ni devolver datos parciales. XML y respuestas HTTP del portal mantienen su límite de 1 MiB. Una falla del stream devuelve `SII_TRANSPORT_ERROR`; JSON malformado mantiene `SII_PROTOCOL_CHANGED`.
26
+
19
27
  ## Integración NestJS u otro backend
20
28
 
21
29
  Instalar desde npm:
@@ -60,11 +68,13 @@ No registrar un cliente autenticado como singleton NestJS. Puede inyectarse un s
60
68
  | `getReceivedInvoices({ periodo, tokenRecaptcha? })` | Facturas 33/34 del registro de compras, con proveedor como emisor, empresa como receptor y cobertura explícita. |
61
69
  | `getIssuedInvoiceXml({ documentType, folio })` | Bytes originales y detalle normalizado de un DTE emitido en el facturador gratuito del SII. |
62
70
  | `getReceivedInvoiceXml({ issuerRut, documentType, folio })` | Original del DTE recibido; valida proveedor y receptor contra la empresa autorizada. |
71
+ | `getIssuedInvoicePdf({ documentType, folio }, { signal }?)` | PDF original emitido 33/34 como `Readable`, sin persistirlo ni acumular el documento completo. |
72
+ | `getReceivedInvoicePdf({ documentType, folio, issuerRut }, { signal }?)` | PDF original recibido 33/34; resuelve tipo, folio y proveedor en el historial de recibidos. |
63
73
  | `getIssuedDocumentXml({ documentType, folio })` | Respaldo y detalle de documentos emitidos 33/34/61; conserva los métodos de XML de facturas existentes. |
64
74
  | `prepareInvoice(input)` | Contenido fiscal revisable, huella SHA256, identificador opaco y vencimiento; todavía no firma ni envía. |
65
75
  | `prepareCancellationCreditNote({ factura, issuedDate })` | Prepara una NC 61 contra una factura 33 resuelta en el historial; mismos receptor y montos, referencia única `CodRef=1`. |
66
76
  | `signAndSend({ preparacionId, approvedHash, claveFirma, beforeSend })` | Firma el contenido aprobado, exige guardar XML e identidad antes del envío y devuelve `status: 'ENVIADO'` cuando observa confirmación del portal. |
67
- | `dispose()` | Cierra la sesión remota propia con `autTermino.cgi`, descarta cookies y bloquea reutilización. Esperar siempre en `finally`. |
77
+ | `dispose()` | Cancela PDF pendientes, espera su cierre y el trabajo JSON/XML/escrituras, cierra la sesión propia con `autTermino.cgi`, descarta cookies y bloquea reutilización. Esperar siempre en `finally`. |
68
78
 
69
79
  ## Nombres canónicos y migración
70
80
 
@@ -138,10 +148,28 @@ La descarga usa HTTP del facturador gratuito; no scrapea filas ni usa un navegad
138
148
 
139
149
  El consumidor debe cotejar además receptor, fecha y total con su referencia autorizada antes de guardar; almacenar el original, hash y fecha de obtención; y reutilizar lo guardado ante reintentos. No iniciar descargas desde SSR ni desde usuarios con permiso sólo de lectura.
140
150
 
151
+ ## PDF de facturas por streaming
152
+
153
+ `getIssuedInvoicePdf` y `getReceivedInvoicePdf` devuelven `Promise<InvoicePdfResult>` con `{ stream: Readable, contentType: 'application/pdf', filename }`. Se exportan `IssuedInvoicePdfQuery`, `ReceivedInvoicePdfQuery`, `PdfDownloadOptions` e `InvoicePdfResult`. El nombre es `factura-<tipo>-<folio>.pdf`, derivado de la identidad validada, sin nombres ni URLs del proveedor. Sólo se admiten facturas 33/34.
154
+
155
+ Se consulta el historial del facturador con `OPCION=2` para emitidas y `OPCION=1` para recibidas. El tipo y folio deben coincidir con una única fila; en recibidas también se verifica el RUT del proveedor. Se confirma la empresa en la sesión antes y después del historial y al abrir el PDF. El código interno se resuelve desde enlaces conocidos del SII: no forma parte de los argumentos públicos, no se aceptan URLs del consumidor ni se ejecuta JavaScript. La identidad se confirma mediante historial y sesión; el SDK no interpreta campos fiscales dentro del PDF ni genera una representación desde el XML.
156
+
157
+ Se exige MIME `application/pdf` o `application/octet-stream` y firma binaria exacta `%PDF-`, incluso fragmentada. Todos los bytes originales se conservan. El stream usa backpressure y `highWaterMark` de 64 KiB; el límite interno de 20 MiB se mide durante la transferencia, aunque falte `Content-Length` o declare menos bytes. No utiliza base64, archivos temporales, caché ni un buffer del documento completo. Los GET conocidos pueden reintentarse antes de entregar el stream; login, POST de selección y transferencias parciales no se reintentan.
158
+
159
+ `timeoutMs` también limita la operación PDF completa, desde apertura del historial hasta cierre de la transferencia. `{ signal }` permite cancelar antes de abrir o durante la lectura. Fin, error, `destroy()`, abort, timeout y `dispose()` cancelan o cierran el origen y liberan lectores, listeners y seguimiento del SDK. Consumir o destruir siempre el stream; mantener la instancia hasta que termine `await pipeline(...)` y después ejecutar `await dispose()` en `finally`. Devolver el stream desde un `try` cuyo `finally` cierra inmediatamente el cliente lo cancelaría antes de que el consumidor pueda leerlo.
160
+
161
+ El [ejemplo HTTP](examples/consulta-pdf.ts) recibe una factura ya autorizada por el backend, inicia sesión y transmite con `Content-Disposition: inline` y `Cache-Control: private, no-store`. Desconectar la respuesta cancela la descarga; una falla después de enviar headers cierra la respuesta sin anexar JSON al PDF. El backend mantiene autorización por actor, tenant, empresa, recurso y sucursal.
162
+
163
+ Liberar estos recursos permite al GC recuperar memoria; no garantiza borrado inmediato de bytes ni elimina referencias o buffers conservados por el consumidor. La [evidencia de QA](docs/sii/QA-PDF-STREAMING.md) distingue pruebas locales de la verificación HTTP real del 09-10-2026: PDF emitido y recibido 33, ejemplo HTTP y cancelación/cierre sin consumir. Tipo 34 sigue pendiente de una muestra real. El botón de Devly Management y los PDF de notas de crédito quedan fuera de este cambio.
164
+
141
165
  ## Emisión y anulación total
142
166
 
143
167
  Esta ampliación usa HTTP contra el facturador gratuito, con certificado digital centralizado del usuario. No utiliza navegador, CAF propios ni un certificado local. `credenciales: { rut, clave }` y `claveFirma` llegan por argumentos y permanecen en memoria; no escribirlas en configuración, historial de comandos, variables de entorno, registros de operación ni logs.
144
168
 
169
+ `prepareInvoice` entra por `mipeSelEmpresa.cgi?DESDE_DONDE_URL=OPCION%3D33%26TIPO%3D4`. Con una sola empresa admite el acceso directo; si aparece el selector, envía un único POST con `RUT_EMP` igual a `empresaRut` y `DESDE_DONDE_URL=OPCION=33&TIPO=4`. Nunca usa la primera opción como fallback. Comparte las validaciones del selector de XML, cuyo destino sigue siendo `OPCION=2&TIPO=4`: empresa autorizada, formulario/destino correctos, cookies de empresa confirmadas y ausencia de reintentos del POST. No requiere una opción adicional del consumidor para detectar estos casos.
170
+
171
+ `prepareCancellationCreditNote` admite los mismos caminos directo/selector. Entra por el historial (`OPCION=2&TIPO=4`) al obtener el XML de la factura original; confirma que pertenece a `empresaRut`, resuelve su código interno y prepara la anulación tipo 61 con referencia única a esa factura y `CodRef=1`. Reutiliza el contexto de empresa ya confirmado, también después de preparar una factura. Este método anula una factura del portal; no abre la nota en blanco (`OPCION=61`) para documentos externos. Preparación y firma/envío permanecen separadas; el POST de selección no se reintenta.
172
+
145
173
  `InvoiceInput` exige `issuedDate` como fecha civil `YYYY-MM-DD`, `issuer: { address, commune, city, activityCode }`, `receiver: { rut, legalName, address, commune, city, businessActivity, contact? }`, `paymentForm: 1 | 2`, `saleType: 1 | 2`, `purchaseType: 1 | 2 | 3 | 4 | 5 | 6 | 7` e `items: { name, description?, quantity, unitNetPriceClp, unit? }[]`. Direcciones, actividad y datos del receptor deben coincidir con las opciones autorizadas devueltas por el portal; la empresa continúa fijada por instancia. Contacto no confirma entrega de correo.
146
174
 
147
175
  Alcance: factura afecta 33, IVA 19%, una a diez líneas, sin descuentos, exenciones, otros impuestos ni transporte. Cantidad y precio son strings decimales positivos con punto, hasta dos decimales, diez dígitos enteros y doce caracteres. Se redondea cada línea a CLP y luego el IVA con aritmética entera exacta; cada línea debe resultar en al menos $1 CLP y el total no puede exceder $9.999.999.999. Campos desconocidos y opciones fuera del alcance se rechazan. Fechas reales desde 2017; el SII determina si acepta la fecha solicitada.
@@ -197,6 +225,10 @@ try {
197
225
  - `SII_XML_UNAVAILABLE`: el servicio no entregó un XML para esa factura.
198
226
  - `SII_XML_COMPANY_SELECTION_REQUIRED`: selección del facturador no confirmada. `diagnostics.reason` distingue empresa ausente/no autorizada (`COMPANY_NOT_AUTHORIZED`), formulario inválido (`INVALID_RESPONSE`) o falta de confirmación/cookies incorrectas (`COMPANY_SELECTION_REQUIRED`).
199
227
  - `SII_XML_INVALID` / `SII_XML_IDENTITY_MISMATCH`: XML inseguro/incorrecto o identidad distinta; no guardar.
228
+ - `SII_PDF_UNAVAILABLE`: el historial indica explícitamente que no encontró el documento.
229
+ - `SII_PDF_INVALID`: MIME, firma binaria o tamaño del PDF inválido; puede aparecer durante la lectura del stream.
230
+ - `SII_PDF_IDENTITY_MISMATCH`: tipo, folio o proveedor distintos, enlace no permitido o historial ambiguo; no descargar.
231
+ - `SII_OPERATION_ABORTED`: el consumidor canceló una operación PDF. Timeout conserva `SII_TRANSPORT_ERROR` con motivo `TIMEOUT`; cierre de instancia conserva `CLIENT_CLOSED`.
200
232
  - `SII_OPERATION_IN_PROGRESS` / `SII_PREPARATION_UNAVAILABLE`: otra escritura en curso o preparación ausente, consumida o vencida; no reutilizar ni duplicar una operación ya enviada.
201
233
  - `SII_APPROVAL_MISMATCH` / `SII_DOCUMENT_CONTENT_MISMATCH`: huella no aprobada o contenido fiscal distinto del esperado; detener el envío y revisar.
202
234
  - `SII_DOCUMENT_VALIDATION_REJECTED`: el portal rechazó la vista previa, incluso con HTTP 200 y una redirección por script; no continuar a firma. El diagnóstico conserva etapa y motivo sin revelar el texto privado del proveedor.
@@ -204,7 +236,7 @@ try {
204
236
  - `SII_DOCUMENT_RECOVERY_FAILED`: no fue posible resolver inequívocamente el documento original para la anulación; no sustituirlo por otro folio.
205
237
  - `SII_ISSUANCE_OUTCOME_UNKNOWN`: envío iniciado sin confirmación; reconciliar con el candidato respaldado antes de cualquier decisión posterior.
206
238
 
207
- Timeout por solicitud: 15 segundos por defecto, rango 1 a 30 segundos. Login nunca se reintenta automáticamente. Lecturas conocidas admiten 0 a 2 reintentos por transporte o HTTP 429/502/503/504; por defecto, uno. TLS conserva validación normal. Sólo la selección del facturador sigue redirecciones HTTPS entre sus dos rutas conocidas en `www1.sii.cl`, hasta cinco solicitudes; otras redirecciones se rechazan.
239
+ Timeout por solicitud: 15 segundos por defecto, rango 1 a 30 segundos; PDF aplica también ese límite a toda la operación. Login nunca se reintenta automáticamente. Lecturas conocidas admiten 0 a 2 reintentos por transporte o HTTP 429/502/503/504; por defecto, uno. TLS conserva validación normal. La entrada al facturador sigue sólo redirecciones HTTPS a selección, lanzamiento y la ruta conocida correspondiente de `www1.sii.cl`, hasta cinco solicitudes; otras redirecciones se rechazan. La descarga del PDF no sigue redirecciones.
208
240
 
209
241
  El contrato observado del RCV exige `conversationId` igual a la cookie secreta `TOKEN` y `Accept: application/json, text/plain, */*`. Ambos tienen checks de regresión. No se implementa resolución de CAPTCHA. Login, selección de empresa, preparación, firma y envío no se reintentan automáticamente.
210
242
 
@@ -0,0 +1,17 @@
1
+ import { type IssuedInvoice, type IssuedInvoicesQuery, type IssuedInvoicesResult, type InvoiceDocumentType } from '../domain/issued-invoice';
2
+ export interface InvoiceReadPort<T extends IssuedInvoice> {
3
+ initialLimit(): Promise<number>;
4
+ counts(): Promise<{
5
+ documentType: InvoiceDocumentType;
6
+ count: number;
7
+ }[]>;
8
+ details(type: InvoiceDocumentType, tokenRecaptcha: string): Promise<T[]>;
9
+ }
10
+ export declare class InvoiceQueryError extends Error {
11
+ readonly section: 'SUMMARY' | 'DETAIL';
12
+ constructor(section: 'SUMMARY' | 'DETAIL');
13
+ }
14
+ /** Coverage and identity reconciliation operate on normalized invoices, never provider rows. */
15
+ export declare function readInvoices<T extends IssuedInvoice>(port: InvoiceReadPort<T>, { periodo, tokenRecaptcha }: IssuedInvoicesQuery): Promise<Omit<IssuedInvoicesResult, 'data'> & {
16
+ data: T[];
17
+ }>;
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InvoiceQueryError = void 0;
4
+ exports.readInvoices = readInvoices;
5
+ const issued_invoice_1 = require("../domain/issued-invoice");
6
+ class InvoiceQueryError extends Error {
7
+ section;
8
+ constructor(section) {
9
+ super('SII_INVALID_RESPONSE');
10
+ this.section = section;
11
+ }
12
+ }
13
+ exports.InvoiceQueryError = InvoiceQueryError;
14
+ /** Coverage and identity reconciliation operate on normalized invoices, never provider rows. */
15
+ async function readInvoices(port, { periodo, tokenRecaptcha = 't-o-k-e-n-web' }) {
16
+ (0, issued_invoice_1.assertPeriod)(periodo);
17
+ if (typeof tokenRecaptcha !== 'string' || !tokenRecaptcha.trim())
18
+ throw new TypeError('tokenRecaptcha inválido');
19
+ const limit = await port.initialLimit();
20
+ const expected = new Map();
21
+ let expectedCount = 0;
22
+ for (const { documentType: type, count } of await port.counts()) {
23
+ if (expected.has(type) && expected.get(type) !== count)
24
+ throw new InvoiceQueryError('SUMMARY');
25
+ if (!expected.has(type))
26
+ expectedCount += count;
27
+ if (!Number.isSafeInteger(expectedCount))
28
+ throw new InvoiceQueryError('SUMMARY');
29
+ expected.set(type, count);
30
+ }
31
+ const invoices = new Map();
32
+ const incompleteDocumentTypes = [];
33
+ for (const [type, count] of expected) {
34
+ if (count === 0)
35
+ continue;
36
+ let uniqueCount = 0;
37
+ for (const invoice of await port.details(type, tokenRecaptcha)) {
38
+ const key = `${invoice.issuerRut}:${invoice.documentType}:${invoice.folio}`;
39
+ const previous = invoices.get(key);
40
+ if (previous && JSON.stringify(previous) !== JSON.stringify(invoice))
41
+ throw new InvoiceQueryError('DETAIL');
42
+ if (!previous) {
43
+ invoices.set(key, invoice);
44
+ uniqueCount++;
45
+ }
46
+ }
47
+ if (count > limit || uniqueCount !== count)
48
+ incompleteDocumentTypes.push(type);
49
+ }
50
+ return { data: [...invoices.values()], complete: incompleteDocumentTypes.length === 0, expectedCount, observedAt: new Date().toISOString(), incompleteDocumentTypes };
51
+ }
@@ -0,0 +1,40 @@
1
+ import { type InvoiceInput } from '../domain/invoicing';
2
+ import { type PreparedDocument, type DocumentContent, type SignedDocument, type SentDocument } from '../domain/document';
3
+ import type { IssuedInvoiceXmlQuery, IssuedDocumentXmlResult } from '../domain/invoice-xml';
4
+ export interface SignDocumentInput {
5
+ preparacionId: string;
6
+ approvedHash: string;
7
+ claveFirma: string;
8
+ /** Persistir XML e identidad antes del envío. Si falla, no se envía. Sin guardar secretos. */
9
+ beforeSend: (document: SignedDocument) => Promise<void>;
10
+ }
11
+ /** @deprecated Use SignDocumentInput. */
12
+ export type FirmaDocumento = SignDocumentInput;
13
+ export interface CancellationInput {
14
+ factura: IssuedInvoiceXmlQuery;
15
+ issuedDate: string;
16
+ }
17
+ export interface InvoicingPort {
18
+ assertReady(): void;
19
+ prepareInvoice(input: InvoiceInput): Promise<DocumentContent>;
20
+ prepareCancellationCreditNote(input: CancellationInput): Promise<DocumentContent>;
21
+ unsignedDocument(approved: PreparedDocument): Promise<IssuedDocumentXmlResult>;
22
+ signDocument(approved: PreparedDocument, password: string): Promise<SignedDocument>;
23
+ sendDocument(document: SignedDocument, password: string): Promise<void>;
24
+ close(): Promise<void>;
25
+ }
26
+ export declare class IssuanceError extends Error {
27
+ readonly code: string;
28
+ constructor(code: string);
29
+ }
30
+ /** Approval, single use and durable pre-send persistence are independent of SII's wire protocol. */
31
+ export declare class DocumentIssuance {
32
+ #private;
33
+ private readonly port;
34
+ constructor(port: InvoicingPort);
35
+ get pendingWrite(): Promise<unknown> | undefined;
36
+ clearPreparation(): void;
37
+ prepareInvoice(input: InvoiceInput): Promise<PreparedDocument>;
38
+ prepareCancellationCreditNote(input: CancellationInput): Promise<PreparedDocument>;
39
+ signAndSend(input: SignDocumentInput): Promise<SentDocument>;
40
+ }
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DocumentIssuance = exports.IssuanceError = void 0;
4
+ const node_crypto_1 = require("node:crypto");
5
+ const invoicing_1 = require("../domain/invoicing");
6
+ const document_1 = require("../domain/document");
7
+ class IssuanceError extends Error {
8
+ code;
9
+ constructor(code) {
10
+ super(code);
11
+ this.code = code;
12
+ }
13
+ }
14
+ exports.IssuanceError = IssuanceError;
15
+ /** Approval, single use and durable pre-send persistence are independent of SII's wire protocol. */
16
+ class DocumentIssuance {
17
+ port;
18
+ #write;
19
+ #prepared;
20
+ constructor(port) {
21
+ this.port = port;
22
+ }
23
+ get pendingWrite() { return this.#write; }
24
+ clearPreparation() { this.#prepared = undefined; }
25
+ async prepareInvoice(input) {
26
+ this.port.assertReady();
27
+ const invoice = (0, invoicing_1.validateInvoice)(input);
28
+ return this.#writeOperation(async () => this.#keepPreparation(await this.port.prepareInvoice(invoice)));
29
+ }
30
+ async prepareCancellationCreditNote(input) {
31
+ this.port.assertReady();
32
+ const { factura, issuedDate } = input;
33
+ if (factura.documentType !== 33 || !/^[1-9]\d{0,19}$/.test(factura.folio) || !/^\d{4}-\d{2}-\d{2}$/.test(issuedDate) || new Date(`${issuedDate}T00:00:00Z`).toISOString().slice(0, 10) !== issuedDate)
34
+ throw new TypeError('Referencia o fecha de anulación inválida');
35
+ return this.#writeOperation(async () => this.#keepPreparation(await this.port.prepareCancellationCreditNote(input)));
36
+ }
37
+ signAndSend(input) {
38
+ if (this.#write)
39
+ return Promise.reject(new IssuanceError('SII_OPERATION_IN_PROGRESS'));
40
+ const prepared = this.#prepared;
41
+ if (!prepared || input.preparacionId !== prepared.preparacionId || Date.now() >= Date.parse(prepared.expiresAt))
42
+ return Promise.reject(new IssuanceError('SII_PREPARATION_UNAVAILABLE'));
43
+ if (input.approvedHash !== prepared.contentHash)
44
+ return Promise.reject(new IssuanceError('SII_APPROVAL_MISMATCH'));
45
+ if (typeof input.claveFirma !== 'string' || !input.claveFirma || input.claveFirma.length > 256 || typeof input.beforeSend !== 'function')
46
+ return Promise.reject(new TypeError('Clave de firma o persistencia previa inválida'));
47
+ this.port.assertReady();
48
+ return this.#writeOperation(async () => {
49
+ this.#prepared = undefined;
50
+ const unsigned = await this.port.unsignedDocument(prepared);
51
+ (0, document_1.assertApprovedDocument)(unsigned, prepared);
52
+ const document = await this.port.signDocument(prepared, input.claveFirma);
53
+ (0, document_1.assertApprovedDocument)(document, prepared);
54
+ await input.beforeSend(structuredClone(document));
55
+ await this.port.sendDocument(document, input.claveFirma);
56
+ return { ...document, status: 'ENVIADO' };
57
+ }).finally(() => this.port.close());
58
+ }
59
+ #writeOperation(action) {
60
+ if (this.#write)
61
+ return Promise.reject(new IssuanceError('SII_OPERATION_IN_PROGRESS'));
62
+ const promise = action();
63
+ this.#write = promise;
64
+ void promise.then(() => { this.#write = undefined; }, () => { this.#write = undefined; });
65
+ return promise;
66
+ }
67
+ #keepPreparation(content) {
68
+ const result = Object.freeze({ ...content, preparacionId: (0, node_crypto_1.randomUUID)(), contentHash: (0, invoicing_1.hashContent)(content), expiresAt: new Date(Date.now() + 300_000).toISOString() });
69
+ const freeze = (value) => { if (value && typeof value === 'object') {
70
+ for (const child of Object.values(value))
71
+ freeze(child);
72
+ Object.freeze(value);
73
+ } };
74
+ freeze(result);
75
+ this.#prepared = result;
76
+ return result;
77
+ }
78
+ }
79
+ exports.DocumentIssuance = DocumentIssuance;
@@ -0,0 +1,66 @@
1
+ import type { Readable } from 'node:stream';
2
+ import type { IssuedInvoiceXmlQuery, ReceivedInvoiceXmlQuery } from './domain/invoice-xml';
3
+ export type IssuedInvoicePdfQuery = IssuedInvoiceXmlQuery;
4
+ export type ReceivedInvoicePdfQuery = ReceivedInvoiceXmlQuery;
5
+ export interface PdfDownloadOptions {
6
+ signal?: AbortSignal;
7
+ }
8
+ export interface InvoicePdfResult {
9
+ stream: Readable;
10
+ contentType: 'application/pdf';
11
+ filename: string;
12
+ }
13
+ export type Operation = 'COMPRA' | 'VENTA';
14
+ export type PurchaseStatus = 'REGISTRO' | 'PENDIENTE' | 'NO_INCLUIR' | 'RECLAMADO';
15
+ export type SiiRecord = Record<string, unknown>;
16
+ export interface SiiResponse<T = SiiRecord> {
17
+ data: T[];
18
+ metaData: Record<string, unknown>;
19
+ respEstado: {
20
+ codRespuesta: number;
21
+ msgeRespuesta: string | null;
22
+ codError: unknown;
23
+ };
24
+ [key: string]: unknown;
25
+ }
26
+ export interface AuthorizedCompany extends SiiRecord {
27
+ usrEmpRut: number;
28
+ usrEmpDv: string;
29
+ usrEmpRutDv: string;
30
+ }
31
+ export interface SiiClientOptions {
32
+ empresaRut: string;
33
+ timeoutMs?: number;
34
+ retries?: number;
35
+ fetchImpl?: typeof globalThis.fetch;
36
+ }
37
+ export interface SiiCredentials {
38
+ rut: string;
39
+ clave: string;
40
+ }
41
+ export interface SummaryQuery {
42
+ periodo: string;
43
+ operacion: Operation;
44
+ estado?: PurchaseStatus;
45
+ }
46
+ export interface SiiSession {
47
+ usuarioRut: string;
48
+ empresaRut: string;
49
+ representacion: false;
50
+ }
51
+ /** @deprecated Use Operation. */
52
+ export type Operacion = Operation;
53
+ /** @deprecated Use PurchaseStatus. */
54
+ export type EstadoCompra = PurchaseStatus;
55
+ /** @deprecated Use SiiRecord. */
56
+ export type RegistroSii = SiiRecord;
57
+ /** @deprecated Use SiiResponse. */
58
+ export type RespuestaSii<T = SiiRecord> = SiiResponse<T>;
59
+ /** @deprecated Use AuthorizedCompany. */
60
+ export type EmpresaAutorizada = AuthorizedCompany;
61
+ /** @deprecated Use SiiCredentials. */
62
+ export type CredencialesSii = SiiCredentials;
63
+ /** @deprecated Use SummaryQuery. */
64
+ export type ConsultaResumen = SummaryQuery;
65
+ /** @deprecated Use SiiSession. */
66
+ export type SesionSii = SiiSession;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,47 @@
1
+ import { type InvoiceInput } from './invoicing';
2
+ import type { IssuedDocumentXmlResult } from './invoice-xml';
3
+ export interface PreparedDocument {
4
+ readonly preparacionId: string;
5
+ readonly contentHash: string;
6
+ readonly expiresAt: string;
7
+ readonly issuerRut: string;
8
+ readonly receiverRut: string;
9
+ readonly documentType: 33 | 61;
10
+ readonly issuedDate: string;
11
+ readonly netAmount: number;
12
+ readonly vatAmount: number;
13
+ readonly totalAmount: number;
14
+ readonly invoice?: InvoiceInput;
15
+ readonly issuerLegalName?: string;
16
+ readonly issuerBusinessActivity?: string;
17
+ readonly issuerBranchCode?: string;
18
+ readonly originalInvoice?: IssuedDocumentXmlResult['detail'];
19
+ readonly reference?: {
20
+ readonly documentType: 33;
21
+ readonly folio: string;
22
+ readonly issuedDate: string;
23
+ readonly code: 1;
24
+ };
25
+ }
26
+ export interface SignedDocument extends IssuedDocumentXmlResult {
27
+ readonly issuerRut: string;
28
+ readonly receiverRut: string;
29
+ readonly documentType: 33 | 61;
30
+ readonly folio: string;
31
+ readonly issuedDate: string;
32
+ readonly contentHash: string;
33
+ }
34
+ export interface SentDocument extends SignedDocument {
35
+ readonly status: 'ENVIADO';
36
+ }
37
+ export type DocumentContent = Omit<PreparedDocument, 'preparacionId' | 'contentHash' | 'expiresAt'>;
38
+ export declare class DocumentContentMismatchError extends Error {
39
+ constructor();
40
+ }
41
+ export declare function assertApprovedDocument(document: IssuedDocumentXmlResult, approved: PreparedDocument): void;
42
+ /** @deprecated Use PreparedDocument. */
43
+ export type DocumentoPreparado = PreparedDocument;
44
+ /** @deprecated Use SignedDocument. */
45
+ export type DocumentoFirmado = SignedDocument;
46
+ /** @deprecated Use SentDocument. */
47
+ export type DocumentoEnviado = SentDocument;
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DocumentContentMismatchError = void 0;
4
+ exports.assertApprovedDocument = assertApprovedDocument;
5
+ const invoicing_1 = require("./invoicing");
6
+ class DocumentContentMismatchError extends Error {
7
+ constructor() { super('SII_DOCUMENT_CONTENT_MISMATCH'); }
8
+ }
9
+ exports.DocumentContentMismatchError = DocumentContentMismatchError;
10
+ function assertApprovedDocument(document, approved) {
11
+ const d = document.detail;
12
+ const decimal = (value) => value == null ? null : value.replace(/^0+(?=\d)/, '').replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '');
13
+ if (d.issuedDate !== approved.issuedDate || d.netAmount !== approved.netAmount || d.vatAmount !== approved.vatAmount || d.totalAmount !== approved.totalAmount || Number(d.vatRate) !== 19 || d.taxes.length || d.adjustments.length || d.exemptAmount || d.fiscalHeader?.noDebitReduction != null || d.fiscalHeader?.unapprovedFiscalFields.length)
14
+ throw new DocumentContentMismatchError();
15
+ if (approved.invoice) {
16
+ const items = approved.invoice.items;
17
+ const header = d.fiscalHeader;
18
+ const i = approved.invoice;
19
+ const branch = (value) => (value ?? '').replace(/^0+(?=\d)/, '');
20
+ if (branch(header?.issuer.branchCode) !== branch(approved.issuerBranchCode))
21
+ throw new DocumentContentMismatchError();
22
+ if (!header || header.issuer.legalName !== approved.issuerLegalName || header.issuer.businessActivity !== approved.issuerBusinessActivity || header.issuer.address !== i.issuer.address || header.issuer.commune !== i.issuer.commune || header.issuer.city !== i.issuer.city || header.issuer.activityCode !== i.issuer.activityCode || header.receiver.legalName !== i.receiver.legalName || header.receiver.businessActivity !== i.receiver.businessActivity || header.receiver.address !== i.receiver.address || header.receiver.commune !== i.receiver.commune || header.receiver.city !== i.receiver.city || (header.receiver.contact ?? '') !== (i.receiver.contact ?? '') || header.paymentForm !== i.paymentForm || header.saleType !== i.saleType || header.purchaseType !== i.purchaseType)
23
+ throw new DocumentContentMismatchError();
24
+ if (d.hasTransport || d.lines.length !== items.length || d.references.length || d.lines.some((line, i) => line.codes.length || line.name !== items[i]?.name || (line.description ?? '') !== (items[i]?.description ?? '') || decimal(line.quantity) !== decimal(items[i]?.quantity ?? null) || decimal(line.unitPrice) !== decimal(items[i]?.unitNetPriceClp ?? null) || (line.unit ?? '') !== (items[i]?.unit ?? '') || line.amount !== (0, invoicing_1.calculateInvoiceTotals)([items[i]]).netAmount || line.discountAmount || line.surchargeAmount || line.discountPercent && Number(line.discountPercent) || line.surchargePercent && Number(line.surchargePercent) || line.exemptIndicator))
25
+ throw new DocumentContentMismatchError();
26
+ }
27
+ else {
28
+ const ref = d.references[0];
29
+ if (!approved.reference || d.references.length !== 1 || ref?.documentType !== '33' || ref.folio !== approved.reference.folio || ref.date !== approved.reference.issuedDate || ref.code !== 1)
30
+ throw new DocumentContentMismatchError();
31
+ const original = approved.originalInvoice;
32
+ const header = d.fiscalHeader;
33
+ const originalHeader = original?.fiscalHeader;
34
+ const lines = (values) => values.map(line => ({ ...line, quantity: decimal(line.quantity), unitPrice: decimal(line.unitPrice), discountPercent: decimal(line.discountPercent), surchargePercent: decimal(line.surchargePercent) }));
35
+ if (!original || !header || !originalHeader || (0, invoicing_1.hashContent)(lines(d.lines)) !== (0, invoicing_1.hashContent)(lines(original.lines)) || (0, invoicing_1.hashContent)(header.issuer) !== (0, invoicing_1.hashContent)(originalHeader.issuer) || (0, invoicing_1.hashContent)(header.receiver) !== (0, invoicing_1.hashContent)(originalHeader.receiver) || ['paymentForm', 'saleType', 'purchaseType'].some(field => header[field] !== null && header[field] !== originalHeader[field]))
36
+ throw new DocumentContentMismatchError();
37
+ }
38
+ }
@@ -121,13 +121,3 @@ export declare class DteXmlError extends Error {
121
121
  readonly code: 'SII_XML_INVALID' | 'SII_XML_IDENTITY_MISMATCH';
122
122
  constructor(code: 'SII_XML_INVALID' | 'SII_XML_IDENTITY_MISMATCH');
123
123
  }
124
- /** Bounded, namespace-aware parsing; no DTD, external entities or network I/O. */
125
- export declare function parseDteXml(xml: Uint8Array, expected: IssuedInvoiceXmlQuery & {
126
- issuerRut: string;
127
- receiverRut?: string;
128
- }): InvoiceXmlResult;
129
- /** Issued invoices and credit notes; preserves original bytes and validates fiscal references. */
130
- export declare function parseDteDocumentXml(xml: Uint8Array, expected: IssuedDocumentXmlQuery & {
131
- issuerRut: string;
132
- receiverRut?: string;
133
- }): IssuedDocumentXmlResult;
@@ -1,10 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DteXmlError = exports.MAX_DTE_XML_BYTES = void 0;
4
- exports.parseDteXml = parseDteXml;
5
- exports.parseDteDocumentXml = parseDteDocumentXml;
6
- const saxes_1 = require("saxes");
7
- const rut_1 = require("./rut");
8
4
  exports.MAX_DTE_XML_BYTES = 1_048_576;
9
5
  class DteXmlError extends Error {
10
6
  code;
@@ -14,169 +10,3 @@ class DteXmlError extends Error {
14
10
  }
15
11
  }
16
12
  exports.DteXmlError = DteXmlError;
17
- function invalid() { throw new DteXmlError('SII_XML_INVALID'); }
18
- const children = (node, name) => node.children.filter(n => n.name === name && n.uri === node.uri);
19
- function one(node, name) {
20
- const values = children(node, name);
21
- return values.length === 1 ? values[0] : invalid();
22
- }
23
- function text(node, name, required = false, limit = 1000) {
24
- const values = children(node, name);
25
- if (values.length > 1 || (required && values.length !== 1))
26
- invalid();
27
- if (!values.length)
28
- return null;
29
- const value = values[0];
30
- if (value.children.length || value.text.length > limit || (required && !value.text.trim()))
31
- invalid();
32
- return value.text.trim() || null;
33
- }
34
- function integer(node, name, required = false) {
35
- const value = text(node, name, required, 20);
36
- if (value === null)
37
- return null;
38
- const number = Number(value);
39
- if (!/^\d+$/.test(value) || !Number.isSafeInteger(number))
40
- invalid();
41
- return number;
42
- }
43
- function decimal(node, name, required = false) {
44
- const value = text(node, name, required, 40);
45
- if (value !== null && !/^\d+(?:\.\d+)?$/.test(value))
46
- invalid();
47
- return value;
48
- }
49
- function date(node, name) {
50
- const value = text(node, name, true, 10);
51
- const parsed = new Date(`${value}T00:00:00Z`);
52
- if (!/^\d{4}-\d{2}-\d{2}$/.test(value) || !Number.isFinite(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== value)
53
- invalid();
54
- return value;
55
- }
56
- function lineNumber(node, name) {
57
- const value = integer(node, name, true);
58
- return value > 0 ? value : invalid();
59
- }
60
- function uniqueLines(items) {
61
- if (new Set(items.map(item => item.lineNumber)).size !== items.length)
62
- invalid();
63
- }
64
- /** Bounded, namespace-aware parsing; no DTD, external entities or network I/O. */
65
- function parseDteXml(xml, expected) {
66
- const parsed = parseDocumentXml(xml, expected, false);
67
- const documentType = parsed.detail.documentType;
68
- if (documentType !== 33 && documentType !== 34)
69
- invalid();
70
- const { fiscalHeader: _header, hasSignature: _signature, hasTransport: _transport, ...detail } = parsed.detail;
71
- return { ...parsed, detail: { ...detail, documentType } };
72
- }
73
- /** Issued invoices and credit notes; preserves original bytes and validates fiscal references. */
74
- function parseDteDocumentXml(xml, expected) {
75
- if (!expected || ![33, 34, 61].includes(expected.documentType))
76
- invalid();
77
- return parseDocumentXml(xml, expected, true);
78
- }
79
- function parseDocumentXml(xml, expected, allowCreditNotes) {
80
- if (!(xml instanceof Uint8Array) || !xml.byteLength || xml.byteLength > exports.MAX_DTE_XML_BYTES)
81
- invalid();
82
- let root;
83
- const stack = [];
84
- let nodes = 0;
85
- const header = Buffer.from(xml.subarray(0, 200)).toString('latin1');
86
- const declared = /<\?xml\b[^?]*\bencoding\s*=\s*['"]([^'"]+)['"]/i.exec(header)?.[1]?.toUpperCase() ?? 'UTF-8';
87
- const encoding = declared === 'UTF-8' || declared === 'UTF8' ? 'UTF-8' : declared === 'ISO-8859-1' ? 'ISO-8859-1' : invalid();
88
- try {
89
- const source = encoding === 'ISO-8859-1' ? Buffer.from(xml).toString('latin1') : new TextDecoder('utf-8', { fatal: true }).decode(xml);
90
- const parser = new saxes_1.SaxesParser({ xmlns: true });
91
- parser.on('error', invalid);
92
- parser.on('doctype', invalid);
93
- parser.on('processinginstruction', invalid);
94
- parser.on('opentag', tag => {
95
- if (++nodes > 10000 || stack.length >= 32)
96
- invalid();
97
- const node = { name: tag.local, uri: tag.uri, text: '', attributeCount: Object.values(tag.attributes).filter(attribute => attribute.uri !== 'http://www.w3.org/2000/xmlns/').length, children: [] };
98
- if (stack.length)
99
- stack[stack.length - 1].children.push(node);
100
- else if (root)
101
- invalid();
102
- else
103
- root = node;
104
- stack.push(node);
105
- });
106
- const append = (value) => { if (stack.length)
107
- stack[stack.length - 1].text += value; };
108
- parser.on('text', append);
109
- parser.on('cdata', append);
110
- parser.on('closetag', () => { stack.pop(); });
111
- parser.write(source).close();
112
- }
113
- catch {
114
- invalid();
115
- }
116
- if (!root || !['', 'http://www.sii.cl/SiiDte'].includes(root.uri))
117
- invalid();
118
- const dtes = root.name === 'DTE' ? [root] : root.name === 'SetDTE' ? children(root, 'DTE') : root.name === 'EnvioDTE' ? children(one(root, 'SetDTE'), 'DTE') : [];
119
- if (dtes.length !== 1)
120
- invalid();
121
- const document = one(dtes[0], 'Documento');
122
- const headerNode = one(document, 'Encabezado');
123
- const identity = one(headerNode, 'IdDoc');
124
- const totals = one(headerNode, 'Totales');
125
- const issuer = one(headerNode, 'Emisor'), receiver = one(headerNode, 'Receptor');
126
- const documentType = integer(identity, 'TipoDTE', true);
127
- const folio = text(identity, 'Folio', true, 20);
128
- let issuerRut, receiverRut;
129
- try {
130
- issuerRut = (0, rut_1.parseRut)(text(issuer, 'RUTEmisor', true, 12)).formatted;
131
- receiverRut = (0, rut_1.parseRut)(text(receiver, 'RUTRecep', true, 12)).formatted;
132
- }
133
- catch {
134
- return invalid();
135
- }
136
- if ((documentType !== 33 && documentType !== 34 && (!allowCreditNotes || documentType !== 61)) || !/^[1-9]\d{0,19}$/.test(folio))
137
- invalid();
138
- if (issuerRut !== (0, rut_1.parseRut)(expected.issuerRut).formatted || documentType !== expected.documentType || folio !== expected.folio || (expected.receiverRut !== undefined && receiverRut !== (0, rut_1.parseRut)(expected.receiverRut).formatted))
139
- throw new DteXmlError('SII_XML_IDENTITY_MISMATCH');
140
- const lines = children(document, 'Detalle').map(line => ({
141
- lineNumber: lineNumber(line, 'NroLinDet'), name: text(line, 'NmbItem', true, 80), description: text(line, 'DscItem'),
142
- codes: children(line, 'CdgItem').map(code => ({ type: text(code, 'TpoCodigo', true, 10), value: text(code, 'VlrCodigo', true, 35) })),
143
- quantity: decimal(line, 'QtyItem'), unit: text(line, 'UnmdItem', false, 4), unitPrice: decimal(line, 'PrcItem'),
144
- discountPercent: decimal(line, 'DescuentoPct'), discountAmount: integer(line, 'DescuentoMonto'),
145
- surchargePercent: decimal(line, 'RecargoPct'), surchargeAmount: integer(line, 'RecargoMonto'), exemptIndicator: integer(line, 'IndExe'), amount: integer(line, 'MontoItem', true),
146
- }));
147
- if (!lines.length || lines.length > 1000)
148
- invalid();
149
- const adjustments = children(document, 'DscRcgGlobal').map(node => {
150
- const movement = text(node, 'TpoMov', true), valueType = text(node, 'TpoValor', true);
151
- if ((movement !== 'D' && movement !== 'R') || (valueType !== '%' && valueType !== '$'))
152
- invalid();
153
- return { lineNumber: lineNumber(node, 'NroLinDR'), movement: movement, description: text(node, 'GlosaDR'), valueType: valueType, value: decimal(node, 'ValorDR', true), exemptIndicator: integer(node, 'IndExeDR') };
154
- });
155
- const references = children(document, 'Referencia').map(node => ({
156
- lineNumber: lineNumber(node, 'NroLinRef'), documentType: text(node, 'TpoDocRef', true, 3), folio: text(node, 'FolioRef', true, 18), date: date(node, 'FchRef'), code: integer(node, 'CodRef'), reason: text(node, 'RazonRef', false, 90),
157
- }));
158
- uniqueLines(lines);
159
- uniqueLines(adjustments);
160
- uniqueLines(references);
161
- if (documentType === 61 && (!references.length
162
- || references.some(reference => reference.code === null || ![1, 2, 3].includes(reference.code))
163
- || (references.some(reference => reference.code === 1 || reference.code === 2) && references.length !== 1)))
164
- invalid();
165
- const signatures = dtes[0].children.filter(node => node.name === 'Signature' && node.uri === 'http://www.w3.org/2000/09/xmldsig#');
166
- if (allowCreditNotes && signatures.length > 1)
167
- invalid();
168
- return { xml: new Uint8Array(xml), encoding, detail: {
169
- issuerRut, documentType: expected.documentType, folio, issuedDate: date(identity, 'FchEmis'), receiverRut,
170
- hasSignature: signatures.length === 1,
171
- hasTransport: children(headerNode, 'Transporte').some(node => node.children.length > 0 || node.text.trim().length > 0 || node.attributeCount > 0),
172
- ...(allowCreditNotes ? { fiscalHeader: {
173
- issuer: { legalName: text(issuer, 'RznSoc'), businessActivity: text(issuer, 'GiroEmis'), activityCode: text(issuer, 'Acteco'), branchCode: text(issuer, 'CdgSIISucur', false, 9), address: text(issuer, 'DirOrigen'), commune: text(issuer, 'CmnaOrigen'), city: text(issuer, 'CiudadOrigen') },
174
- receiver: { legalName: text(receiver, 'RznSocRecep'), address: text(receiver, 'DirRecep'), commune: text(receiver, 'CmnaRecep'), city: text(receiver, 'CiudadRecep'), businessActivity: text(receiver, 'GiroRecep'), contact: text(receiver, 'Contacto') },
175
- paymentForm: integer(identity, 'FmaPago'), saleType: integer(identity, 'TpoTranVenta'), purchaseType: integer(identity, 'TpoTranCompra'),
176
- noDebitReduction: integer(identity, 'IndNoRebaja', children(identity, 'IndNoRebaja').length > 0),
177
- unapprovedFiscalFields: identity.children.filter(node => node.uri === identity.uri && !['TipoDTE', 'Folio', 'FchEmis', 'FmaPago', 'TpoTranVenta', 'TpoTranCompra', 'IndNoRebaja'].includes(node.name)).map(node => node.name),
178
- } } : {}),
179
- netAmount: integer(totals, 'MntNeto'), exemptAmount: integer(totals, 'MntExe'), vatRate: decimal(totals, 'TasaIVA'), vatAmount: integer(totals, 'IVA'), totalAmount: integer(totals, 'MntTotal', true), lines,
180
- taxes: children(totals, 'ImptoReten').map(node => ({ type: integer(node, 'TipoImp', true), rate: decimal(node, 'TasaImp'), amount: integer(node, 'MontoImp', true) })), adjustments, references,
181
- } };
182
- }