@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,248 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseDteXml = parseDteXml;
4
+ exports.parseDteDocumentXml = parseDteDocumentXml;
5
+ const saxes_1 = require("saxes");
6
+ const rut_1 = require("../domain/rut");
7
+ const invoice_xml_1 = require("../domain/invoice-xml");
8
+ function invalid() { throw new invoice_xml_1.DteXmlError('SII_XML_INVALID'); }
9
+ const children = (node, name) => node.children.filter(n => n.name === name && n.uri === node.uri);
10
+ function one(node, name) {
11
+ const values = children(node, name);
12
+ return values.length === 1 ? values[0] : invalid();
13
+ }
14
+ function text(node, name, required = false, limit = 1000) {
15
+ const values = children(node, name);
16
+ if (values.length > 1 || (required && values.length !== 1))
17
+ invalid();
18
+ if (!values.length)
19
+ return null;
20
+ return nodeText(values[0], required, limit);
21
+ }
22
+ function nodeText(node, required = false, limit = 1000) {
23
+ if (node.children.length || node.text.length > limit || (required && !node.text.trim()))
24
+ invalid();
25
+ return node.text.trim() || null;
26
+ }
27
+ function integer(node, name, required = false) {
28
+ const value = text(node, name, required, 20);
29
+ if (value === null)
30
+ return null;
31
+ const number = Number(value);
32
+ if (!/^\d+$/.test(value) || !Number.isSafeInteger(number))
33
+ invalid();
34
+ return number;
35
+ }
36
+ function decimal(node, name, required = false) {
37
+ const value = text(node, name, required, 40);
38
+ if (value !== null && !/^\d+(?:\.\d+)?$/.test(value))
39
+ invalid();
40
+ return value;
41
+ }
42
+ function date(node, name) {
43
+ const value = text(node, name, true, 10);
44
+ const parsed = new Date(`${value}T00:00:00Z`);
45
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value) || !Number.isFinite(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== value)
46
+ invalid();
47
+ return value;
48
+ }
49
+ function lineNumber(node, name) {
50
+ const value = integer(node, name, true);
51
+ return value > 0 ? value : invalid();
52
+ }
53
+ function uniqueLines(items) {
54
+ if (new Set(items.map(item => item.lineNumber)).size !== items.length)
55
+ invalid();
56
+ }
57
+ /** Bounded, namespace-aware parsing; no DTD, external entities or network I/O. */
58
+ function parseDteXml(xml, expected) {
59
+ const parsed = parseDocumentXml(xml, expected, false);
60
+ const documentType = parsed.detail.documentType;
61
+ if (documentType !== 33 && documentType !== 34)
62
+ invalid();
63
+ const { fiscalHeader: _header, hasSignature: _signature, hasTransport: _transport, issuanceOptions: _options, ...detail } = parsed.detail;
64
+ return { ...parsed, detail: { ...detail, documentType } };
65
+ }
66
+ /** Issued invoices and credit notes; preserves original bytes and validates fiscal references. */
67
+ function parseDteDocumentXml(xml, expected) {
68
+ if (!expected || ![33, 34, 61].includes(expected.documentType))
69
+ invalid();
70
+ return parseDocumentXml(xml, expected, true);
71
+ }
72
+ function parseDocumentXml(xml, expected, allowCreditNotes) {
73
+ if (!(xml instanceof Uint8Array) || !xml.byteLength || xml.byteLength > invoice_xml_1.MAX_DTE_XML_BYTES)
74
+ invalid();
75
+ let root;
76
+ const stack = [];
77
+ let nodes = 0;
78
+ const header = Buffer.from(xml.subarray(0, 200)).toString('latin1');
79
+ const declared = /<\?xml\b[^?]*\bencoding\s*=\s*['"]([^'"]+)['"]/i.exec(header)?.[1]?.toUpperCase() ?? 'UTF-8';
80
+ const encoding = declared === 'UTF-8' || declared === 'UTF8' ? 'UTF-8' : declared === 'ISO-8859-1' ? 'ISO-8859-1' : invalid();
81
+ try {
82
+ const source = encoding === 'ISO-8859-1' ? Buffer.from(xml).toString('latin1') : new TextDecoder('utf-8', { fatal: true }).decode(xml);
83
+ const parser = new saxes_1.SaxesParser({ xmlns: true });
84
+ parser.on('error', invalid);
85
+ parser.on('doctype', invalid);
86
+ parser.on('processinginstruction', invalid);
87
+ parser.on('opentag', tag => {
88
+ if (++nodes > 10000 || stack.length >= 32)
89
+ invalid();
90
+ 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: [] };
91
+ if (stack.length)
92
+ stack[stack.length - 1].children.push(node);
93
+ else if (root)
94
+ invalid();
95
+ else
96
+ root = node;
97
+ stack.push(node);
98
+ });
99
+ const append = (value) => { if (stack.length)
100
+ stack[stack.length - 1].text += value; };
101
+ parser.on('text', append);
102
+ parser.on('cdata', append);
103
+ parser.on('closetag', () => { stack.pop(); });
104
+ parser.write(source).close();
105
+ }
106
+ catch {
107
+ invalid();
108
+ }
109
+ if (!root || !['', 'http://www.sii.cl/SiiDte'].includes(root.uri))
110
+ invalid();
111
+ const dtes = root.name === 'DTE' ? [root] : root.name === 'SetDTE' ? children(root, 'DTE') : root.name === 'EnvioDTE' ? children(one(root, 'SetDTE'), 'DTE') : [];
112
+ if (dtes.length !== 1)
113
+ invalid();
114
+ const document = one(dtes[0], 'Documento');
115
+ const headerNode = one(document, 'Encabezado');
116
+ const identity = one(headerNode, 'IdDoc');
117
+ const totals = one(headerNode, 'Totales');
118
+ const issuer = one(headerNode, 'Emisor'), receiver = one(headerNode, 'Receptor');
119
+ const documentType = integer(identity, 'TipoDTE', true);
120
+ const grossAmounts = integer(identity, 'MntBruto');
121
+ if (grossAmounts !== null && grossAmounts !== 1)
122
+ invalid();
123
+ const folio = text(identity, 'Folio', true, 20);
124
+ let issuerRut, receiverRut;
125
+ try {
126
+ issuerRut = (0, rut_1.parseRut)(text(issuer, 'RUTEmisor', true, 12)).formatted;
127
+ receiverRut = (0, rut_1.parseRut)(text(receiver, 'RUTRecep', true, 12)).formatted;
128
+ }
129
+ catch {
130
+ return invalid();
131
+ }
132
+ if ((documentType !== 33 && documentType !== 34 && (!allowCreditNotes || documentType !== 61)) || !/^[1-9]\d{0,19}$/.test(folio))
133
+ invalid();
134
+ 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))
135
+ throw new invoice_xml_1.DteXmlError('SII_XML_IDENTITY_MISMATCH');
136
+ const lines = children(document, 'Detalle').map(line => ({
137
+ lineNumber: lineNumber(line, 'NroLinDet'), name: text(line, 'NmbItem', true, 80), description: text(line, 'DscItem'),
138
+ codes: children(line, 'CdgItem').map(code => ({ type: text(code, 'TpoCodigo', true, 10), value: text(code, 'VlrCodigo', true, 35) })),
139
+ quantity: decimal(line, 'QtyItem'), unit: text(line, 'UnmdItem', false, 4), unitPrice: decimal(line, 'PrcItem'),
140
+ discountPercent: decimal(line, 'DescuentoPct'), discountAmount: integer(line, 'DescuentoMonto'),
141
+ surchargePercent: decimal(line, 'RecargoPct'), surchargeAmount: integer(line, 'RecargoMonto'), exemptIndicator: integer(line, 'IndExe'), amount: integer(line, 'MontoItem', true),
142
+ }));
143
+ if (!lines.length || lines.length > 1000)
144
+ invalid();
145
+ const adjustments = children(document, 'DscRcgGlobal').map(node => {
146
+ const movement = text(node, 'TpoMov', true), valueType = text(node, 'TpoValor', true);
147
+ if ((movement !== 'D' && movement !== 'R') || (valueType !== '%' && valueType !== '$'))
148
+ invalid();
149
+ return { lineNumber: lineNumber(node, 'NroLinDR'), movement: movement, description: text(node, 'GlosaDR'), valueType: valueType, value: decimal(node, 'ValorDR', true), exemptIndicator: integer(node, 'IndExeDR') };
150
+ });
151
+ const references = children(document, 'Referencia').map(node => ({
152
+ 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),
153
+ }));
154
+ uniqueLines(lines);
155
+ uniqueLines(adjustments);
156
+ uniqueLines(references);
157
+ if (documentType === 61 && (!references.length
158
+ || references.some(reference => reference.code === null || ![1, 2, 3].includes(reference.code))
159
+ || (references.some(reference => reference.code === 1 || reference.code === 2) && references.length !== 1)))
160
+ invalid();
161
+ const signatures = dtes[0].children.filter(node => node.name === 'Signature' && node.uri === 'http://www.w3.org/2000/09/xmldsig#');
162
+ if (allowCreditNotes && signatures.length > 1)
163
+ invalid();
164
+ const options = allowCreditNotes ? issuanceOptions(headerNode, identity, issuer, document) : undefined;
165
+ const issuerActivities = allowCreditNotes ? children(issuer, 'Acteco').map(node => nodeText(node)) : [];
166
+ return { xml: new Uint8Array(xml), encoding, detail: {
167
+ ...(grossAmounts === 1 ? { grossAmounts: true } : {}),
168
+ issuerRut, documentType: expected.documentType, folio, issuedDate: date(identity, 'FchEmis'), receiverRut,
169
+ hasSignature: signatures.length === 1,
170
+ hasTransport: children(headerNode, 'Transporte').some(node => node.children.length > 0 || node.text.trim().length > 0 || node.attributeCount > 0),
171
+ ...(options ? { issuanceOptions: options } : {}),
172
+ ...(allowCreditNotes ? { fiscalHeader: {
173
+ issuer: { legalName: text(issuer, 'RznSoc'), businessActivity: text(issuer, 'GiroEmis'), activityCode: issuerActivities.length === 1 ? issuerActivities[0] : null, 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', 'MntPagos'].includes(node.name)).map(node => node.name), ...(issuerActivities.length > 1 ? ['Acteco'] : [])],
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
+ }
183
+ function issuanceOptions(header, identity, issuer, document) {
184
+ const unsupported = [];
185
+ const inspect = (node, allowed, path) => {
186
+ if (node.attributeCount || node.text.trim())
187
+ unsupported.push(path);
188
+ for (const child of node.children) {
189
+ if (child.uri !== node.uri || !allowed.includes(child.name) || child.attributeCount)
190
+ unsupported.push(`${path}/${child.name}`);
191
+ }
192
+ };
193
+ const optionalRut = (node, name) => {
194
+ const value = text(node, name, false, 15);
195
+ if (value === null)
196
+ return null;
197
+ try {
198
+ return (0, rut_1.parseRut)(value).formatted;
199
+ }
200
+ catch {
201
+ return invalid();
202
+ }
203
+ };
204
+ const transports = children(header, 'Transporte');
205
+ if (transports.length > 1)
206
+ invalid();
207
+ const transportNode = transports[0];
208
+ let transport = null;
209
+ if (transportNode) {
210
+ inspect(transportNode, ['Patente', 'RUTTrans', 'Chofer'], 'Transporte');
211
+ const drivers = children(transportNode, 'Chofer');
212
+ if (drivers.length > 1)
213
+ invalid();
214
+ const driver = drivers[0];
215
+ if (driver)
216
+ inspect(driver, ['RUTChofer', 'NombreChofer'], 'Transporte/Chofer');
217
+ const value = { carrierRut: optionalRut(transportNode, 'RUTTrans'), licensePlate: text(transportNode, 'Patente', false, 8), driverRut: driver ? optionalRut(driver, 'RUTChofer') : null, driverName: driver ? text(driver, 'NombreChofer', false, 30) : null };
218
+ if (Object.values(value).some(part => part !== null))
219
+ transport = value;
220
+ }
221
+ const payments = children(identity, 'MntPagos').map(node => {
222
+ inspect(node, ['FchPago', 'MntPago', 'GlosaPagos'], 'IdDoc/MntPagos');
223
+ return { date: date(node, 'FchPago'), amount: integer(node, 'MntPago', true), description: text(node, 'GlosaPagos', false, 40) };
224
+ });
225
+ const lineTaxCodes = children(document, 'Detalle').flatMap(line => {
226
+ const codes = children(line, 'CodImpAdic').map(node => {
227
+ if (node.children.length || node.attributeCount)
228
+ unsupported.push('Detalle/CodImpAdic');
229
+ const value = node.text.trim();
230
+ if (!/^\d{1,6}$/.test(value))
231
+ invalid();
232
+ return Number(value);
233
+ });
234
+ return codes.length ? [{ lineNumber: lineNumber(line, 'NroLinDet'), codes }] : [];
235
+ });
236
+ const referenceGlobalIndicators = children(document, 'Referencia').flatMap(ref => {
237
+ const indicator = integer(ref, 'IndGlobal');
238
+ return indicator === null ? [] : [{ lineNumber: lineNumber(ref, 'NroLinRef'), indicator }];
239
+ });
240
+ const issuerPhones = children(issuer, 'Telefono').map(node => {
241
+ if (node.children.length || node.text.length > 20 || !node.text.trim())
242
+ invalid();
243
+ return node.text.trim();
244
+ });
245
+ const issuerEmail = text(issuer, 'CorreoEmisor', false, 80), requesterRut = optionalRut(header, 'RUTSolicita');
246
+ const result = { issuerEmail, issuerPhones, requesterRut, transport, payments, lineTaxCodes, referenceGlobalIndicators, unapprovedFields: unsupported };
247
+ return issuerEmail !== null || issuerPhones.length || requesterRut !== null || transport !== null || payments.length || lineTaxCodes.length || referenceGlobalIndicators.length || unsupported.length ? result : undefined;
248
+ }
@@ -0,0 +1,31 @@
1
+ import type { CompanyInfo } from '../domain/company-info';
2
+ import { type InvoiceInput } from '../domain/invoicing';
3
+ import { type PreparedDocument, type DocumentContent, type SignedDocument } from '../domain/document';
4
+ import { type IssuedInvoiceXmlQuery, type ReceivedInvoiceXmlQuery, type InvoiceXmlResult, type IssuedDocumentXmlQuery, type ReceivedDocumentXmlQuery, type IssuedDocumentXmlResult } from '../domain/invoice-xml';
5
+ import type { InvoicingPort } from '../application/issuance';
6
+ import type { IssuedInvoicePdfQuery, ReceivedInvoicePdfQuery, PdfDownloadOptions, InvoicePdfResult } from '../contracts';
7
+ import { SiiHttpSession } from './sii-http-session';
8
+ export declare class FacturadorGateway implements InvoicingPort {
9
+ #private;
10
+ private readonly session;
11
+ private readonly closeSession;
12
+ constructor(session: SiiHttpSession, closeSession: () => Promise<void>);
13
+ assertReady(): void;
14
+ close(): Promise<void>;
15
+ clearPreparation(): void;
16
+ companyInfo(rut: string): Promise<CompanyInfo>;
17
+ prepareInvoice(input: InvoiceInput): Promise<DocumentContent>;
18
+ prepareCancellationCreditNote({ factura, issuedDate }: {
19
+ factura: IssuedInvoiceXmlQuery;
20
+ issuedDate: string;
21
+ }): Promise<DocumentContent>;
22
+ unsignedDocument(approved: PreparedDocument): Promise<IssuedDocumentXmlResult>;
23
+ signDocument(approved: PreparedDocument, password: string): Promise<SignedDocument>;
24
+ sendDocument(document: SignedDocument, password: string): Promise<void>;
25
+ issuedInvoiceXml(input: IssuedInvoiceXmlQuery): Promise<InvoiceXmlResult>;
26
+ receivedInvoiceXml(input: ReceivedInvoiceXmlQuery): Promise<InvoiceXmlResult>;
27
+ issuedDocumentXml(input: IssuedDocumentXmlQuery): Promise<IssuedDocumentXmlResult>;
28
+ receivedDocumentXml(input: ReceivedDocumentXmlQuery): Promise<IssuedDocumentXmlResult>;
29
+ issuedInvoicePdf(input: IssuedInvoicePdfQuery, options?: PdfDownloadOptions): Promise<InvoicePdfResult>;
30
+ receivedInvoicePdf(input: ReceivedInvoicePdfQuery, options?: PdfDownloadOptions): Promise<InvoicePdfResult>;
31
+ }