@devly-cl/sii-client 0.5.0 → 0.7.1

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 (50) hide show
  1. package/README.md +96 -219
  2. package/dist/application/document-status.d.ts +13 -0
  3. package/dist/application/document-status.js +50 -0
  4. package/dist/application/invoice-queries.d.ts +23 -0
  5. package/dist/application/invoice-queries.js +55 -0
  6. package/dist/application/issuance.d.ts +40 -0
  7. package/dist/application/issuance.js +79 -0
  8. package/dist/contracts.d.ts +66 -0
  9. package/dist/contracts.js +2 -0
  10. package/dist/domain/company-info.d.ts +13 -0
  11. package/dist/domain/company-info.js +2 -0
  12. package/dist/domain/document-status.d.ts +93 -0
  13. package/dist/domain/document-status.js +69 -0
  14. package/dist/domain/document.d.ts +51 -0
  15. package/dist/domain/document.js +71 -0
  16. package/dist/domain/invoice-xml.d.ts +34 -11
  17. package/dist/domain/invoice-xml.js +0 -170
  18. package/dist/domain/invoicing.d.ts +78 -5
  19. package/dist/domain/invoicing.js +143 -26
  20. package/dist/domain/issued-invoice.d.ts +1 -2
  21. package/dist/domain/issued-invoice.js +4 -43
  22. package/dist/domain/rcv-document.d.ts +17 -0
  23. package/dist/domain/rcv-document.js +2 -0
  24. package/dist/domain/received-invoice.d.ts +1 -3
  25. package/dist/domain/received-invoice.js +0 -10
  26. package/dist/index.d.ts +12 -7
  27. package/dist/index.js +6 -4
  28. package/dist/infrastructure/document-status-gateway.d.ts +13 -0
  29. package/dist/infrastructure/document-status-gateway.js +127 -0
  30. package/dist/infrastructure/document-status-parser.d.ts +12 -0
  31. package/dist/infrastructure/document-status-parser.js +258 -0
  32. package/dist/infrastructure/dte-xml.d.ts +11 -0
  33. package/dist/infrastructure/dte-xml.js +248 -0
  34. package/dist/infrastructure/facturador-gateway.d.ts +31 -0
  35. package/dist/infrastructure/facturador-gateway.js +509 -0
  36. package/dist/infrastructure/facturador.d.ts +13 -3
  37. package/dist/infrastructure/facturador.js +34 -3
  38. package/dist/infrastructure/invoice-pdf.d.ts +9 -0
  39. package/dist/infrastructure/invoice-pdf.js +171 -0
  40. package/dist/infrastructure/rcv-gateway.d.ts +20 -0
  41. package/dist/infrastructure/rcv-gateway.js +109 -0
  42. package/dist/infrastructure/rcv-normalization.d.ts +13 -0
  43. package/dist/infrastructure/rcv-normalization.js +63 -0
  44. package/dist/infrastructure/sii-client.d.ts +31 -121
  45. package/dist/infrastructure/sii-client.js +69 -772
  46. package/dist/infrastructure/sii-http-session.d.ts +29 -0
  47. package/dist/infrastructure/sii-http-session.js +359 -0
  48. package/dist/{domain/sii-error.d.ts → sii-error.d.ts} +3 -3
  49. package/dist/{domain/sii-error.js → sii-error.js} +14 -4
  50. package/package.json +45 -45
@@ -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,13 @@
1
+ /** Datos observados al consultar un receptor en el facturador gratuito. */
2
+ export interface CompanyInfo {
3
+ rut: string;
4
+ legalName: string;
5
+ addresses: {
6
+ address: string;
7
+ commune: string;
8
+ }[];
9
+ /** Descripciones de giro; no se infieren códigos de actividad económica. */
10
+ businessActivities: string[];
11
+ source: 'SII_FACTURADOR';
12
+ observedAt: string;
13
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,93 @@
1
+ export interface DocumentQueryOptions {
2
+ signal?: AbortSignal;
3
+ }
4
+ export type DocumentDirection = 'ISSUED' | 'RECEIVED';
5
+ export interface DocumentIdentity {
6
+ issuerRut: string;
7
+ receiverRut: string;
8
+ documentType: 33 | 34 | 61;
9
+ folio: string;
10
+ }
11
+ export type DocumentStatusQuery = ({
12
+ direction: 'ISSUED';
13
+ documentType: 33 | 34 | 61;
14
+ folio: string;
15
+ receiverRut: string;
16
+ } | {
17
+ direction: 'RECEIVED';
18
+ documentType: 33 | 34;
19
+ folio: string;
20
+ issuerRut: string;
21
+ }) & {
22
+ issuedDate: string;
23
+ totalAmount: number;
24
+ };
25
+ export type RecipientEventsQuery = {
26
+ direction: 'ISSUED';
27
+ documentType: 33 | 34;
28
+ folio: string;
29
+ } | {
30
+ direction: 'RECEIVED';
31
+ documentType: 33 | 34;
32
+ folio: string;
33
+ issuerRut: string;
34
+ };
35
+ export type DocumentVerification = {
36
+ verification: 'RECEIVED_MATCH';
37
+ cancellation: 'REPORTED' | 'NOT_REPORTED';
38
+ } | {
39
+ verification: 'RECEIVED_MISMATCH' | 'DOCUMENT_NOT_AUTHORIZED';
40
+ cancellation: 'UNCONFIRMED';
41
+ };
42
+ export type DocumentStatusResult = DocumentVerification & {
43
+ document: DocumentIdentity;
44
+ fiscalVerdict: 'NOT_OBSERVED';
45
+ source: 'SII_CONTENT_QUERY';
46
+ observedAt: string;
47
+ };
48
+ export interface RecipientEvent {
49
+ code: string;
50
+ kind: 'CONTENT_ACCEPTANCE' | 'GOODS_RECEIPT' | 'CONTENT_CLAIM' | 'PARTIAL_DELIVERY_CLAIM' | 'TOTAL_DELIVERY_CLAIM' | 'CASH_PAYMENT' | 'CREDIT_NOTE_CANCELLATION' | 'UNKNOWN';
51
+ description: string;
52
+ occurredAtLocal: string | null;
53
+ responsibleRut: string | null;
54
+ }
55
+ export interface RecipientEventsResult {
56
+ document: DocumentIdentity & {
57
+ documentType: 33 | 34;
58
+ };
59
+ siiReceivedAtLocal: string | null;
60
+ timeZone: null;
61
+ indicators: {
62
+ paidInCashReported: boolean | null;
63
+ claimsReported: boolean | null;
64
+ acknowledgementsReported: boolean | null;
65
+ };
66
+ events: RecipientEvent[];
67
+ source: 'SII_RECIPIENT_REGISTRY';
68
+ observedAt: string;
69
+ }
70
+ export type BoundDocumentStatusQuery = DocumentIdentity & {
71
+ direction: DocumentDirection;
72
+ issuedDate: string;
73
+ totalAmount: number;
74
+ };
75
+ export interface BoundRecipientEventsQuery {
76
+ direction: DocumentDirection;
77
+ companyRut: string;
78
+ issuerRut: string;
79
+ documentType: 33 | 34;
80
+ folio: string;
81
+ }
82
+ export type RecipientEventsObservation = Omit<RecipientEventsResult, 'source' | 'observedAt'> & {
83
+ accessAsIssuer: boolean;
84
+ accessAsReceiver: boolean;
85
+ };
86
+ export declare class DocumentQueryError extends Error {
87
+ readonly code: 'SII_DOCUMENT_IDENTITY_MISMATCH' | 'SII_DOCUMENT_ACCESS_DENIED';
88
+ constructor(code: 'SII_DOCUMENT_IDENTITY_MISMATCH' | 'SII_DOCUMENT_ACCESS_DENIED');
89
+ }
90
+ export declare function bindDocumentStatusQuery(companyRut: string, query: DocumentStatusQuery): BoundDocumentStatusQuery;
91
+ export declare function bindRecipientEventsQuery(companyRut: string, query: RecipientEventsQuery): BoundRecipientEventsQuery;
92
+ export declare function assertDocumentQueryOptions(options?: DocumentQueryOptions): void;
93
+ export declare function assertRecipientEventsAccess(query: BoundRecipientEventsQuery, observation: RecipientEventsObservation): void;
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DocumentQueryError = void 0;
4
+ exports.bindDocumentStatusQuery = bindDocumentStatusQuery;
5
+ exports.bindRecipientEventsQuery = bindRecipientEventsQuery;
6
+ exports.assertDocumentQueryOptions = assertDocumentQueryOptions;
7
+ exports.assertRecipientEventsAccess = assertRecipientEventsAccess;
8
+ const rut_1 = require("./rut");
9
+ class DocumentQueryError extends Error {
10
+ code;
11
+ constructor(code) {
12
+ super(code);
13
+ this.code = code;
14
+ }
15
+ }
16
+ exports.DocumentQueryError = DocumentQueryError;
17
+ function assertFields(value, allowed, message) {
18
+ if (!value || typeof value !== 'object')
19
+ throw new TypeError(message);
20
+ const prototype = Object.getPrototypeOf(value);
21
+ if (prototype !== Object.prototype && prototype !== null || Reflect.ownKeys(value).some(key => typeof key !== 'string' || !allowed.includes(key) || !Object.hasOwn(Object.getOwnPropertyDescriptor(value, key) ?? {}, 'value')))
22
+ throw new TypeError(message);
23
+ }
24
+ function assertIdentity(direction, documentType, folio, creditNote) {
25
+ if (direction !== 'ISSUED' && direction !== 'RECEIVED' || documentType !== 33 && documentType !== 34 && !(creditNote && direction === 'ISSUED' && documentType === 61))
26
+ throw new TypeError('Dirección o tipo documental inválido');
27
+ if (typeof folio !== 'string' || !/^[1-9]\d{0,9}$/.test(folio))
28
+ throw new TypeError('Folio inválido');
29
+ }
30
+ function bindDocumentStatusQuery(companyRut, query) {
31
+ assertFields(query, ['direction', 'documentType', 'folio', Object.getOwnPropertyDescriptor(query ?? {}, 'direction')?.value === 'RECEIVED' ? 'issuerRut' : 'receiverRut', 'issuedDate', 'totalAmount'], 'Consulta de estado documental inválida');
32
+ assertIdentity(query.direction, query.documentType, query.folio, true);
33
+ const company = (0, rut_1.parseRut)(companyRut).formatted;
34
+ const issuerRut = query.direction === 'ISSUED' ? company : (0, rut_1.parseRut)(query.issuerRut).formatted;
35
+ const receiverRut = query.direction === 'RECEIVED' ? company : (0, rut_1.parseRut)(query.receiverRut).formatted;
36
+ if (typeof query.issuedDate !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(query.issuedDate) || !Number.isFinite(Date.parse(`${query.issuedDate}T00:00:00Z`)) || new Date(`${query.issuedDate}T00:00:00Z`).toISOString().slice(0, 10) !== query.issuedDate)
37
+ throw new TypeError('Fecha de emisión inválida: YYYY-MM-DD');
38
+ if (!Number.isSafeInteger(query.totalAmount) || query.totalAmount < 0)
39
+ throw new TypeError('Monto total inválido: entero CLP no negativo');
40
+ return { direction: query.direction, issuerRut, receiverRut, documentType: query.documentType, folio: query.folio, issuedDate: query.issuedDate, totalAmount: query.totalAmount };
41
+ }
42
+ function bindRecipientEventsQuery(companyRut, query) {
43
+ assertFields(query, Object.getOwnPropertyDescriptor(query ?? {}, 'direction')?.value === 'RECEIVED' ? ['direction', 'documentType', 'folio', 'issuerRut'] : ['direction', 'documentType', 'folio'], 'Consulta de eventos del receptor inválida');
44
+ assertIdentity(query.direction, query.documentType, query.folio, false);
45
+ const company = (0, rut_1.parseRut)(companyRut).formatted;
46
+ return { direction: query.direction, companyRut: company, issuerRut: query.direction === 'ISSUED' ? company : (0, rut_1.parseRut)(query.issuerRut).formatted, documentType: query.documentType, folio: query.folio };
47
+ }
48
+ function assertDocumentQueryOptions(options) {
49
+ if (options === undefined)
50
+ return;
51
+ assertFields(options, ['signal'], 'Opciones de consulta documental inválidas');
52
+ if (options.signal !== undefined && !(options.signal instanceof AbortSignal))
53
+ throw new TypeError('Señal de consulta documental inválida');
54
+ }
55
+ function assertRecipientEventsAccess(query, observation) {
56
+ const document = observation?.document;
57
+ let issuerRut, receiverRut;
58
+ try {
59
+ issuerRut = (0, rut_1.parseRut)(document.issuerRut).formatted;
60
+ receiverRut = (0, rut_1.parseRut)(document.receiverRut).formatted;
61
+ }
62
+ catch {
63
+ throw new DocumentQueryError('SII_DOCUMENT_IDENTITY_MISMATCH');
64
+ }
65
+ if (issuerRut !== query.issuerRut || document.documentType !== query.documentType || document.folio !== query.folio || (query.direction === 'ISSUED' ? issuerRut : receiverRut) !== query.companyRut)
66
+ throw new DocumentQueryError('SII_DOCUMENT_IDENTITY_MISMATCH');
67
+ if ((query.direction === 'ISSUED' ? observation.accessAsIssuer : observation.accessAsReceiver) !== true)
68
+ throw new DocumentQueryError('SII_DOCUMENT_ACCESS_DENIED');
69
+ }
@@ -0,0 +1,51 @@
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 issuerContact?: {
19
+ readonly email: string;
20
+ readonly phone: string;
21
+ };
22
+ readonly originalInvoice?: IssuedDocumentXmlResult['detail'];
23
+ readonly reference?: {
24
+ readonly documentType: 33;
25
+ readonly folio: string;
26
+ readonly issuedDate: string;
27
+ readonly code: 1;
28
+ };
29
+ }
30
+ export interface SignedDocument extends IssuedDocumentXmlResult {
31
+ readonly issuerRut: string;
32
+ readonly receiverRut: string;
33
+ readonly documentType: 33 | 61;
34
+ readonly folio: string;
35
+ readonly issuedDate: string;
36
+ readonly contentHash: string;
37
+ }
38
+ export interface SentDocument extends SignedDocument {
39
+ readonly status: 'ENVIADO';
40
+ }
41
+ export type DocumentContent = Omit<PreparedDocument, 'preparacionId' | 'contentHash' | 'expiresAt'>;
42
+ export declare class DocumentContentMismatchError extends Error {
43
+ constructor();
44
+ }
45
+ export declare function assertApprovedDocument(document: IssuedDocumentXmlResult, approved: PreparedDocument): void;
46
+ /** @deprecated Use PreparedDocument. */
47
+ export type DocumentoPreparado = PreparedDocument;
48
+ /** @deprecated Use SignedDocument. */
49
+ export type DocumentoFirmado = SignedDocument;
50
+ /** @deprecated Use SentDocument. */
51
+ export type DocumentoEnviado = SentDocument;
@@ -0,0 +1,71 @@
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.issuerRut !== approved.issuerRut || d.receiverRut !== approved.receiverRut || d.documentType !== approved.documentType || d.issuedDate !== approved.issuedDate || d.netAmount !== approved.netAmount || d.vatAmount !== approved.vatAmount || d.totalAmount !== approved.totalAmount || Number(d.vatRate) !== 19 || d.exemptAmount || d.fiscalHeader?.noDebitReduction != null || d.fiscalHeader?.unapprovedFiscalFields.length || d.issuanceOptions?.unapprovedFields.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
+ const breakdown = (0, invoicing_1.invoiceBreakdown)(items, i.globalDiscount);
25
+ if (d.lines.length !== items.length || d.lines.some((line, index) => {
26
+ const item = items[index], expected = breakdown.lineAmounts[index];
27
+ return line.lineNumber !== index + 1 || (0, invoicing_1.hashContent)(line.codes) !== (0, invoicing_1.hashContent)(item.productCode ? [item.productCode] : []) || line.name !== item.name || (line.description ?? '') !== (item.description ?? '') || decimal(line.quantity) !== decimal(item.quantity) || decimal(line.unitPrice) !== decimal(item.unitNetPriceClp) || (line.unit ?? '') !== (item.unit ?? '') || line.amount !== expected.amount || decimal(line.discountPercent ?? '0') !== decimal(item.discountPercent ?? '0') || (line.discountAmount ?? 0) !== expected.discountAmount || line.surchargeAmount || line.surchargePercent && Number(line.surchargePercent) || line.exemptIndicator;
28
+ }))
29
+ throw new DocumentContentMismatchError();
30
+ const taxOrder = (taxes) => taxes.map(tax => ({ ...tax, rate: decimal(tax.rate) })).sort((a, b) => a.type - b.type);
31
+ if ((0, invoicing_1.hashContent)(taxOrder(d.taxes)) !== (0, invoicing_1.hashContent)(taxOrder(breakdown.taxes)))
32
+ throw new DocumentContentMismatchError();
33
+ const adjustment = d.adjustments[0];
34
+ const hasDiscount = breakdown.discountAmount > 0 || Number(breakdown.discountPercent) > 0;
35
+ if (hasDiscount) {
36
+ const matches = adjustment?.valueType === '%'
37
+ ? decimal(adjustment.value) === decimal(breakdown.discountPercent) && breakdown.discountAmountFromPercent === breakdown.discountAmount
38
+ : adjustment?.valueType === '$' && breakdown.discountAmount > 0 && decimal(adjustment.value) === String(breakdown.discountAmount);
39
+ if (d.adjustments.length !== 1 || !adjustment || !matches || adjustment.lineNumber !== 1 || adjustment.movement !== 'D' || adjustment.exemptIndicator || adjustment.description !== null && adjustment.description.toLowerCase() !== 'descuento global')
40
+ throw new DocumentContentMismatchError();
41
+ }
42
+ else if (d.adjustments.length)
43
+ throw new DocumentContentMismatchError();
44
+ const references = i.references ?? [];
45
+ if (d.references.length !== references.length || d.references.some((ref, index) => { const expected = references[index]; return ref.lineNumber !== index + 1 || ref.documentType !== expected.documentType || ref.folio !== expected.folio || ref.date !== expected.date || (ref.reason ?? '') !== (expected.reason ?? '') || ref.code !== null; }))
46
+ throw new DocumentContentMismatchError();
47
+ const options = d.issuanceOptions;
48
+ const expectedPayments = (i.payments ?? []).map(payment => ({ date: payment.date, amount: payment.amountClp, description: payment.description ?? null }));
49
+ const expectedTaxCodes = items.flatMap((item, index) => item.additionalTaxCode === undefined ? [] : [{ lineNumber: index + 1, codes: [item.additionalTaxCode] }]);
50
+ const expectedGlobal = references.flatMap((ref, index) => ref.global ? [{ lineNumber: index + 1, indicator: 1 }] : []);
51
+ if (d.hasTransport !== !!i.transport || (0, invoicing_1.hashContent)(options?.transport ?? null) !== (0, invoicing_1.hashContent)(i.transport ?? null) || (options?.requesterRut ?? '') !== (i.requesterRut ?? '') || (0, invoicing_1.hashContent)(options?.payments ?? []) !== (0, invoicing_1.hashContent)(expectedPayments) || (0, invoicing_1.hashContent)(options?.lineTaxCodes ?? []) !== (0, invoicing_1.hashContent)(expectedTaxCodes) || (0, invoicing_1.hashContent)(options?.referenceGlobalIndicators ?? []) !== (0, invoicing_1.hashContent)(expectedGlobal))
52
+ throw new DocumentContentMismatchError();
53
+ const email = approved.issuerContact?.email ?? i.issuer.email ?? '', phone = approved.issuerContact?.phone ?? i.issuer.phone ?? '';
54
+ if ((i.issuer.email !== undefined || options?.issuerEmail != null) && (options?.issuerEmail ?? '') !== email || (i.issuer.phone !== undefined || options?.issuerPhones.length) && (0, invoicing_1.hashContent)(options?.issuerPhones ?? []) !== (0, invoicing_1.hashContent)(phone ? [phone] : []))
55
+ throw new DocumentContentMismatchError();
56
+ }
57
+ else {
58
+ const ref = d.references[0];
59
+ if (!approved.reference || d.references.length !== 1 || ref?.documentType !== '33' || ref.folio !== approved.reference.folio || ref.date !== approved.reference.issuedDate || ref.code !== 1)
60
+ throw new DocumentContentMismatchError();
61
+ const original = approved.originalInvoice;
62
+ const header = d.fiscalHeader;
63
+ const originalHeader = original?.fiscalHeader;
64
+ const lines = (values) => values.map(line => ({ ...line, quantity: decimal(line.quantity), unitPrice: decimal(line.unitPrice), discountPercent: decimal(line.discountPercent), surchargePercent: decimal(line.surchargePercent) }));
65
+ const fiscalOptions = (detail) => ({ issuerEmail: detail.issuanceOptions?.issuerEmail ?? null, issuerPhones: detail.issuanceOptions?.issuerPhones ?? [], requesterRut: detail.issuanceOptions?.requesterRut ?? null, transport: detail.issuanceOptions?.transport ?? null, payments: detail.issuanceOptions?.payments ?? [], lineTaxCodes: detail.issuanceOptions?.lineTaxCodes ?? [] });
66
+ const taxes = (detail) => detail.taxes.map(tax => ({ ...tax, rate: decimal(tax.rate) }));
67
+ const adjustments = (detail) => detail.adjustments.map(adjustment => ({ ...adjustment, value: decimal(adjustment.value) }));
68
+ if (!original || !header || !originalHeader || original.issuanceOptions?.unapprovedFields.length || (0, invoicing_1.hashContent)(lines(d.lines)) !== (0, invoicing_1.hashContent)(lines(original.lines)) || (0, invoicing_1.hashContent)(taxes(d)) !== (0, invoicing_1.hashContent)(taxes(original)) || (0, invoicing_1.hashContent)(adjustments(d)) !== (0, invoicing_1.hashContent)(adjustments(original)) || d.hasTransport !== original.hasTransport || (0, invoicing_1.hashContent)(fiscalOptions(d)) !== (0, invoicing_1.hashContent)(fiscalOptions(original)) || d.issuanceOptions?.referenceGlobalIndicators.length || (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]))
69
+ throw new DocumentContentMismatchError();
70
+ }
71
+ }
@@ -5,6 +5,9 @@ export interface IssuedDocumentXmlQuery {
5
5
  documentType: IssuedDocumentType;
6
6
  folio: string;
7
7
  }
8
+ export interface ReceivedDocumentXmlQuery extends IssuedDocumentXmlQuery {
9
+ issuerRut: string;
10
+ }
8
11
  export interface IssuedInvoiceXmlQuery {
9
12
  documentType: InvoiceDocumentType;
10
13
  folio: string;
@@ -31,6 +34,8 @@ export interface DteInvoiceLine {
31
34
  amount: number;
32
35
  }
33
36
  export interface DteInvoiceDetail {
37
+ /** Present only for MntBruto=1: line amounts/prices include VAT. Original fiscal totals are unchanged. */
38
+ grossAmounts?: boolean;
34
39
  issuerRut: string;
35
40
  documentType: InvoiceDocumentType;
36
41
  folio: string;
@@ -76,6 +81,8 @@ export interface DteDocumentDetail extends Omit<DteInvoiceDetail, 'documentType'
76
81
  hasSignature: boolean;
77
82
  /** Transport data is present; an observed empty Transporte container does not count. */
78
83
  hasTransport: boolean;
84
+ /** Present only when optional issuance data exists. Legacy parseDteXml keeps its shape. */
85
+ issuanceOptions?: DteIssuanceOptions;
79
86
  fiscalHeader?: {
80
87
  issuer: {
81
88
  legalName: string | null;
@@ -98,10 +105,36 @@ export interface DteDocumentDetail extends Omit<DteInvoiceDetail, 'documentType'
98
105
  saleType: number | null;
99
106
  purchaseType: number | null;
100
107
  noDebitReduction: number | null;
101
- /** IdDoc fields outside the supported invoice/annulment issuance command. Reads preserve them. */
108
+ /** Fiscal fields outside the supported invoice/annulment issuance command. Reads preserve them. */
102
109
  unapprovedFiscalFields: string[];
103
110
  };
104
111
  }
112
+ export interface DteIssuanceOptions {
113
+ issuerEmail: string | null;
114
+ issuerPhones: string[];
115
+ requesterRut: string | null;
116
+ transport: {
117
+ carrierRut: string | null;
118
+ licensePlate: string | null;
119
+ driverRut: string | null;
120
+ driverName: string | null;
121
+ } | null;
122
+ payments: {
123
+ date: string;
124
+ amount: number;
125
+ description: string | null;
126
+ }[];
127
+ lineTaxCodes: {
128
+ lineNumber: number;
129
+ codes: number[];
130
+ }[];
131
+ referenceGlobalIndicators: {
132
+ lineNumber: number;
133
+ indicator: number;
134
+ }[];
135
+ /** Optional structures outside the supported form are readable but cannot be issued. */
136
+ unapprovedFields: string[];
137
+ }
105
138
  export interface IssuedDocumentXmlResult extends Omit<InvoiceXmlResult, 'detail'> {
106
139
  detail: DteDocumentDetail;
107
140
  }
@@ -121,13 +154,3 @@ export declare class DteXmlError extends Error {
121
154
  readonly code: 'SII_XML_INVALID' | 'SII_XML_IDENTITY_MISMATCH';
122
155
  constructor(code: 'SII_XML_INVALID' | 'SII_XML_IDENTITY_MISMATCH');
123
156
  }
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
- }