@devly-cl/sii-client 0.4.4 → 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.
- package/README.md +118 -26
- package/dist/application/invoice-queries.d.ts +17 -0
- package/dist/application/invoice-queries.js +51 -0
- package/dist/application/issuance.d.ts +40 -0
- package/dist/application/issuance.js +79 -0
- package/dist/contracts.d.ts +66 -0
- package/dist/contracts.js +2 -0
- package/dist/domain/document.d.ts +47 -0
- package/dist/domain/document.js +38 -0
- package/dist/domain/invoice-xml.d.ts +58 -11
- package/dist/domain/invoice-xml.js +0 -138
- package/dist/domain/invoicing.d.ts +52 -0
- package/dist/domain/invoicing.js +157 -0
- package/dist/domain/issued-invoice.d.ts +16 -9
- package/dist/domain/issued-invoice.js +4 -43
- package/dist/domain/received-invoice.d.ts +11 -7
- package/dist/domain/received-invoice.js +0 -10
- package/dist/domain/sii-error.d.ts +3 -3
- package/dist/domain/sii-error.js +10 -4
- package/dist/index.d.ts +13 -3
- package/dist/index.js +12 -3
- package/dist/infrastructure/dte-xml.d.ts +11 -0
- package/dist/infrastructure/dte-xml.js +173 -0
- package/dist/infrastructure/facturador-gateway.d.ts +28 -0
- package/dist/infrastructure/facturador-gateway.js +411 -0
- package/dist/infrastructure/facturador.d.ts +18 -0
- package/dist/infrastructure/facturador.js +231 -0
- package/dist/infrastructure/invoice-pdf.d.ts +9 -0
- package/dist/infrastructure/invoice-pdf.js +171 -0
- package/dist/infrastructure/rcv-gateway.d.ts +17 -0
- package/dist/infrastructure/rcv-gateway.js +105 -0
- package/dist/infrastructure/rcv-normalization.d.ts +6 -0
- package/dist/infrastructure/rcv-normalization.js +55 -0
- package/dist/infrastructure/sii-client.d.ts +52 -54
- package/dist/infrastructure/sii-client.js +66 -487
- package/dist/infrastructure/sii-http-session.d.ts +25 -0
- package/dist/infrastructure/sii-http-session.js +344 -0
- package/dist/sii-error.d.ts +27 -0
- package/dist/sii-error.js +86 -0
- package/package.json +4 -4
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.FacturadorGateway = void 0;
|
|
4
|
+
const rut_1 = require("../domain/rut");
|
|
5
|
+
const invoicing_1 = require("../domain/invoicing");
|
|
6
|
+
const document_1 = require("../domain/document");
|
|
7
|
+
const invoice_xml_1 = require("../domain/invoice-xml");
|
|
8
|
+
const sii_error_1 = require("../sii-error");
|
|
9
|
+
const dte_xml_1 = require("./dte-xml");
|
|
10
|
+
const sii_http_session_1 = require("./sii-http-session");
|
|
11
|
+
const facturador_1 = require("./facturador");
|
|
12
|
+
const invoice_pdf_1 = require("./invoice-pdf");
|
|
13
|
+
const DESTINATION = 'OPCION=2&TIPO=4';
|
|
14
|
+
const htmlElements = (root) => [...(0, facturador_1.nodes)(root)].filter(facturador_1.element);
|
|
15
|
+
class FacturadorGateway {
|
|
16
|
+
session;
|
|
17
|
+
closeSession;
|
|
18
|
+
#ready = false;
|
|
19
|
+
#preparation;
|
|
20
|
+
#signing;
|
|
21
|
+
constructor(session, closeSession) {
|
|
22
|
+
this.session = session;
|
|
23
|
+
this.closeSession = closeSession;
|
|
24
|
+
}
|
|
25
|
+
assertReady() { this.session.assertReady(); }
|
|
26
|
+
close() { return this.closeSession(); }
|
|
27
|
+
clearPreparation() { this.#ready = false; this.#preparation = undefined; this.#signing = undefined; }
|
|
28
|
+
async prepareInvoice(input) {
|
|
29
|
+
this.session.assertReady();
|
|
30
|
+
const invoice = input;
|
|
31
|
+
await this.#ensurePortal('OPCION=33&TIPO=4');
|
|
32
|
+
let page = await this.#portal('mipeGenFacEx.cgi', undefined, '?PTDC_CODIGO=33');
|
|
33
|
+
let fields = this.#form(page, 'VIEW_EFXP', 'mipeDisplayPreView.cgi');
|
|
34
|
+
this.#assertNewInvoice(fields);
|
|
35
|
+
const issuerAddress = this.#assertOption(page, 'emisorDir', invoice.issuer.address, invoice.issuer.commune);
|
|
36
|
+
this.#assertOption(page, 'emisorActEco', invoice.issuer.activityCode);
|
|
37
|
+
const receiver = (0, rut_1.parseRut)(invoice.receiver.rut);
|
|
38
|
+
fields.set('EFXP_RUT_RECEP', receiver.rut);
|
|
39
|
+
fields.set('EFXP_DV_RECEP', receiver.dv);
|
|
40
|
+
page = await this.#portal('mipeGenFacEx.cgi', fields);
|
|
41
|
+
fields = this.#form(page, 'VIEW_EFXP', 'mipeDisplayPreView.cgi');
|
|
42
|
+
this.#assertNewInvoice(fields);
|
|
43
|
+
this.#assertOption(page, 'recptorDir', invoice.receiver.address, invoice.receiver.commune);
|
|
44
|
+
this.#assertOption(page, 'recptoActEco', invoice.receiver.businessActivity, undefined, 1);
|
|
45
|
+
if (fields.get('EFXP_RZN_SOC_RECEP')?.trim() && fields.get('EFXP_RZN_SOC_RECEP')?.trim() !== invoice.receiver.legalName)
|
|
46
|
+
throw this.session.failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeGenFacEx.cgi', 'DOCUMENT_CONTENT_MISMATCH');
|
|
47
|
+
const totals = (0, invoicing_1.calculateInvoiceTotals)(invoice.items);
|
|
48
|
+
const values = {
|
|
49
|
+
PTDC_CODIGO: '33', EFXP_FCH_EMIS: invoice.issuedDate, CANT_DET: String(invoice.items.length), ES_BORR: 'FALSE',
|
|
50
|
+
EFXP_DIR_ORIGEN: invoice.issuer.address, EFXP_CMNA_ORIGEN: invoice.issuer.commune, EFXP_CIUDAD_ORIGEN: invoice.issuer.city,
|
|
51
|
+
EFXP_CDG_SII_SUCUR: issuerAddress[3]?.trim() === '0' ? '' : issuerAddress[3]?.trim() ?? '', EFXP_FONO_EMISOR: issuerAddress[4]?.trim() ?? '',
|
|
52
|
+
EFXP_ACTECO: invoice.issuer.activityCode, EFXP_ACTECO_SELECT: invoice.issuer.activityCode, EFXP_TIPOVENTA_SELECT: String(invoice.saleType),
|
|
53
|
+
EFXP_RUT_RECEP: receiver.rut, EFXP_DV_RECEP: receiver.dv, EFXP_RZN_SOC_RECEP: invoice.receiver.legalName,
|
|
54
|
+
EFXP_DIR_RECEP: invoice.receiver.address, EFXP_CMNA_RECEP: invoice.receiver.commune, EFXP_CIUDAD_RECEP: invoice.receiver.city,
|
|
55
|
+
EFXP_GIRO_RECEP: invoice.receiver.businessActivity, EFXP_CONTACTO: invoice.receiver.contact ?? '', EFXP_TIPOCOMPRA_SELECT: String(invoice.purchaseType),
|
|
56
|
+
EFXP_RUT_SOLICITA: '', EFXP_DV_SOLICITA: '', EFXP_FMA_PAGO: String(invoice.paymentForm),
|
|
57
|
+
EFXP_SUBTOTAL: String(totals.netAmount), EFXP_PCT_DESC: '0', EFXP_MNT_DESC: '0', MNT_NETO_TEMP: String(totals.netAmount), IVA_TEMP: String(totals.vatAmount),
|
|
58
|
+
EFXP_MNT_NETO: String(totals.netAmount), EFXP_TASA_IVA: '19', EFXP_IVA: String(totals.vatAmount), EFXP_MNT_TOTAL: String(totals.totalAmount), EFXP_OTRO_IMP_TOTAL: '0',
|
|
59
|
+
};
|
|
60
|
+
for (const [key, value] of Object.entries(values))
|
|
61
|
+
fields.set(key, value);
|
|
62
|
+
for (const key of [...fields.keys()])
|
|
63
|
+
if (/^(?:EFXP_(?:TPO_COD|COD|NMB|QTY|UNMD|PRC|OTRO_IMP|PCTD|SUBT|DSC_ITEM)_\d{2}|DESCRIP_\d{2}|.*_SI_NO)$/.test(key))
|
|
64
|
+
fields.delete(key);
|
|
65
|
+
for (const [index, item] of invoice.items.entries()) {
|
|
66
|
+
const suffix = String(index + 1).padStart(2, '0');
|
|
67
|
+
for (const [field, value] of Object.entries({ NMB: item.name, QTY: item.quantity, PRC: item.unitNetPriceClp, UNMD: item.unit ?? '', DSC_ITEM: item.description ?? '', PCTD: '', SUBT: String((0, invoicing_1.calculateInvoiceTotals)([item]).netAmount) }))
|
|
68
|
+
fields.set(`EFXP_${field}_${suffix}`, value);
|
|
69
|
+
if (item.description)
|
|
70
|
+
fields.set(`DESCRIP_${suffix}`, 'SiChecked');
|
|
71
|
+
}
|
|
72
|
+
page = await this.#portal('mipeDisplayPreView.cgi', fields);
|
|
73
|
+
const preview = this.#form(page, 'PreViewDTE', 'mipeGenXMLFirma.cgi', 'mipeGenFacEx.cgi');
|
|
74
|
+
this.#assertFields(preview, { PTDC_CODIGO: '33', EFXP_FCH_EMIS: invoice.issuedDate, EFXP_RUT_RECEP: receiver.rut, EFXP_DV_RECEP: receiver.dv, EFXP_MNT_NETO: String(totals.netAmount), EFXP_IVA: String(totals.vatAmount), EFXP_MNT_TOTAL: String(totals.totalAmount) });
|
|
75
|
+
this.#preparation = preview;
|
|
76
|
+
return { issuerRut: this.session.company.formatted, receiverRut: receiver.formatted, documentType: 33, issuedDate: invoice.issuedDate, ...totals, invoice, issuerLegalName: fields.get('EFXP_RZN_SOC')?.trim() ?? '', issuerBusinessActivity: fields.get('EFXP_GIRO_EMIS')?.trim() ?? '', issuerBranchCode: fields.get('EFXP_CDG_SII_SUCUR') ?? '' };
|
|
77
|
+
}
|
|
78
|
+
async prepareCancellationCreditNote({ factura, issuedDate }) {
|
|
79
|
+
this.session.assertReady();
|
|
80
|
+
const original = await this.issuedDocumentXml(factura);
|
|
81
|
+
const query = new URLSearchParams({ RUT_RECP: '', FOLIO: factura.folio, RZN_SOC: '', FEC_DESDE: '', FEC_HASTA: '', TPO_DOC: '33', ESTADO: '', ORDEN: '', NUM_PAG: '1' });
|
|
82
|
+
const history = await this.#portal('mipeAdminDocsEmi.cgi', undefined, `?${query}`);
|
|
83
|
+
const codes = new Set();
|
|
84
|
+
for (const element of htmlElements(history.document))
|
|
85
|
+
if (element.tagName === 'a') {
|
|
86
|
+
const href = element.attrs.find(a => a.name === 'href')?.value;
|
|
87
|
+
if (!href)
|
|
88
|
+
continue;
|
|
89
|
+
try {
|
|
90
|
+
const link = new URL(href, sii_http_session_1.FACTURADOR);
|
|
91
|
+
if (link.origin === 'https://www1.sii.cl' && link.pathname === '/cgi-bin/Portal001/mipeGesDocEmi.cgi' && /^\d{1,20}$/.test(link.searchParams.get('CODIGO') ?? ''))
|
|
92
|
+
codes.add(link.searchParams.get('CODIGO'));
|
|
93
|
+
}
|
|
94
|
+
catch { /* Non-document links are ignored. */ }
|
|
95
|
+
}
|
|
96
|
+
if (codes.size !== 1)
|
|
97
|
+
throw this.session.failure('SII_DOCUMENT_RECOVERY_FAILED', 'mipeAdminDocsEmi.cgi', codes.size === 0 ? 'DOCUMENT_NOT_FOUND' : 'INVALID_RESPONSE');
|
|
98
|
+
const page = await this.#portal('mipeDisplayPreView.cgi', undefined, `?EHDR_CODIGO=${[...codes][0]}&TIPO_NOTA=61`);
|
|
99
|
+
const fields = this.#form(page, 'PreViewDTE', 'mipeGenXMLFirma.cgi', 'mipeGenFacEx.cgi');
|
|
100
|
+
const d = original.detail;
|
|
101
|
+
this.#assertFields(fields, { PTDC_CODIGO: '61', EFXP_FCH_EMIS: issuedDate, EFXP_RUT_RECEP: (0, rut_1.parseRut)(d.receiverRut).rut, EFXP_DV_RECEP: (0, rut_1.parseRut)(d.receiverRut).dv, EFXP_TPO_DOC_REF_001: '33', EFXP_FOLIO_REF_001: d.folio, EFXP_FCH_REF_001: d.issuedDate, EFXP_CODIGO_REF_001: '1', EFXP_MNT_NETO: String(d.netAmount), EFXP_IVA: String(d.vatAmount), EFXP_MNT_TOTAL: String(d.totalAmount) });
|
|
102
|
+
if (fields.get('EFXP_FOLIO_REF_002')?.trim() || fields.get('EFXP_FOLIO_REF_003')?.trim() || d.netAmount === null || d.vatAmount === null)
|
|
103
|
+
throw this.session.failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeDisplayPreView.cgi', 'DOCUMENT_CONTENT_MISMATCH');
|
|
104
|
+
this.#preparation = fields;
|
|
105
|
+
return { issuerRut: d.issuerRut, receiverRut: d.receiverRut, documentType: 61, issuedDate, netAmount: d.netAmount, vatAmount: d.vatAmount, totalAmount: d.totalAmount, originalInvoice: d, reference: { documentType: 33, folio: d.folio, issuedDate: d.issuedDate, code: 1 } };
|
|
106
|
+
}
|
|
107
|
+
async unsignedDocument(approved) {
|
|
108
|
+
if (!this.#preparation)
|
|
109
|
+
throw this.session.failure('SII_PREPARATION_UNAVAILABLE', 'mipeGenXMLFirma.cgi', 'INVALID_RESPONSE');
|
|
110
|
+
const page = await this.#portal('mipeGenXMLFirma.cgi', this.#preparation);
|
|
111
|
+
const fields = this.#form(page, 'frmSign', 'mipeSendXML.cgi');
|
|
112
|
+
const folio = fields.get('EFXP_FOLIO') ?? '';
|
|
113
|
+
if (!/^[1-9]\d{0,19}$/.test(folio))
|
|
114
|
+
throw this.session.failure('SII_SIGNATURE_INVALID', 'mipeGenXMLFirma.cgi', 'INVALID_RESPONSE');
|
|
115
|
+
const plain = fields.get('txtPlainText') ?? '';
|
|
116
|
+
const expected = { issuerRut: approved.issuerRut, receiverRut: approved.receiverRut, documentType: approved.documentType, folio };
|
|
117
|
+
let unsigned;
|
|
118
|
+
try {
|
|
119
|
+
unsigned = (0, dte_xml_1.parseDteDocumentXml)((0, facturador_1.encodeUnsignedDteXml)(plain), expected);
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
throw this.session.failure('SII_SIGNATURE_INVALID', 'mipeGenXMLFirma.cgi', 'INVALID_XML');
|
|
123
|
+
}
|
|
124
|
+
this.#signing = { fields, plain, expected };
|
|
125
|
+
return unsigned;
|
|
126
|
+
}
|
|
127
|
+
async signDocument(approved, password) {
|
|
128
|
+
const signing = this.#signing;
|
|
129
|
+
if (!signing)
|
|
130
|
+
throw this.session.failure('SII_SIGNATURE_INVALID', 'postFirmaDigital.cgi', 'INVALID_RESPONSE');
|
|
131
|
+
const identity = this.session.assertReady();
|
|
132
|
+
const certificatePage = await this.#portal('getCertDigital.cgi', undefined, `?rut=${identity.rut}&dv=${identity.dv}`);
|
|
133
|
+
let certs;
|
|
134
|
+
try {
|
|
135
|
+
certs = JSON.parse(certificatePage.text);
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
throw this.session.failure('SII_CERTIFICATE_UNAVAILABLE', 'getCertDigital.cgi', 'CERTIFICATE_UNAVAILABLE');
|
|
139
|
+
}
|
|
140
|
+
if (!Array.isArray(certs) || certs.length !== 1 || !(0, sii_http_session_1.isRecord)(certs[0]) || typeof certs[0].nombre !== 'string' || !certs[0].nombre || certs[0].nombre.length > 256)
|
|
141
|
+
throw this.session.failure('SII_CERTIFICATE_UNAVAILABLE', 'getCertDigital.cgi', 'CERTIFICATE_UNAVAILABLE');
|
|
142
|
+
const name = certs[0].nombre;
|
|
143
|
+
const fields = new URLSearchParams({ nombre: name, dato: signing.plain, rut: identity.rut, dv: identity.dv, clave: password, nodo: 'dte:DTE', nodoId: 'dte:Documento', nameSpace: 'http://www.sii.cl/SiiDte' });
|
|
144
|
+
return this.session.request(`${sii_http_session_1.FACTURADOR}postFirmaDigital.cgi`, async (response) => {
|
|
145
|
+
const signedBytes = await this.session.readBounded(response, 'postFirmaDigital.cgi');
|
|
146
|
+
if (!signedBytes.length)
|
|
147
|
+
throw this.session.failure('SII_SIGNATURE_INVALID', 'postFirmaDigital.cgi', 'EMPTY_RESPONSE', response);
|
|
148
|
+
let signed;
|
|
149
|
+
try {
|
|
150
|
+
signed = (0, dte_xml_1.parseDteDocumentXml)(signedBytes, signing.expected);
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
const text = (0, facturador_1.readPortalHtml)(signedBytes);
|
|
154
|
+
const reason = /clave no corresponde/i.test(text) ? 'CERTIFICATE_PASSWORD_INVALID' : /expirado/i.test(text) ? 'CERTIFICATE_EXPIRED' : /revocado/i.test(text) ? 'CERTIFICATE_REVOKED' : 'SIGNATURE_INVALID';
|
|
155
|
+
throw this.session.failure('SII_SIGNATURE_INVALID', 'postFirmaDigital.cgi', reason, response);
|
|
156
|
+
}
|
|
157
|
+
// Preserve fiscal mismatch precedence over a missing signature at the HTTP boundary.
|
|
158
|
+
(0, document_1.assertApprovedDocument)(signed, approved);
|
|
159
|
+
if (!signed.detail.hasSignature)
|
|
160
|
+
throw this.session.failure('SII_SIGNATURE_INVALID', 'postFirmaDigital.cgi', 'SIGNATURE_INVALID', response);
|
|
161
|
+
signing.certificate = name;
|
|
162
|
+
return { ...signed, ...signing.expected, issuedDate: approved.issuedDate, contentHash: approved.contentHash };
|
|
163
|
+
}, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', Referer: `${sii_http_session_1.FACTURADOR}mipeGenXMLFirma.cgi` }, body: fields.toString() });
|
|
164
|
+
}
|
|
165
|
+
async sendDocument(document, password) {
|
|
166
|
+
const signing = this.#signing;
|
|
167
|
+
if (!signing?.certificate)
|
|
168
|
+
throw this.session.failure('SII_SIGNATURE_INVALID', 'mipeSendXML.cgi', 'INVALID_RESPONSE');
|
|
169
|
+
const fields = signing.fields;
|
|
170
|
+
fields.set('txtSignText', Buffer.from(document.xml).toString(document.encoding === 'UTF-8' ? 'utf8' : 'latin1'));
|
|
171
|
+
fields.set('nombre', signing.certificate);
|
|
172
|
+
fields.set('clave', password);
|
|
173
|
+
fields.set('nodo', 'dte:DTE');
|
|
174
|
+
fields.set('nodoId', 'dte:Documento');
|
|
175
|
+
fields.set('nameSpace', 'http://www.sii.cl/SiiDte');
|
|
176
|
+
const body = (0, facturador_1.encodePortalForm)(fields);
|
|
177
|
+
try {
|
|
178
|
+
const sent = await this.#portal('mipeSendXML.cgi', body);
|
|
179
|
+
if (!/DOCUMENTO\s+TRIBUTARIO\s+ELECTR[ÓO]NICO\s+ENVIADO\s+EXITOSAMENTE/i.test((0, facturador_1.readVisiblePortalText)(sent.document)))
|
|
180
|
+
throw this.session.failure('SII_ISSUANCE_OUTCOME_UNKNOWN', 'mipeSendXML.cgi', 'ISSUANCE_OUTCOME_UNKNOWN');
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
throw this.session.failure('SII_ISSUANCE_OUTCOME_UNKNOWN', 'mipeSendXML.cgi', 'ISSUANCE_OUTCOME_UNKNOWN');
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
issuedInvoiceXml(input) {
|
|
187
|
+
if (![33, 34].includes(input.documentType))
|
|
188
|
+
return Promise.reject(new TypeError('Identidad de factura inválida'));
|
|
189
|
+
return this.#documentXml(input, undefined, true);
|
|
190
|
+
}
|
|
191
|
+
receivedInvoiceXml(input) {
|
|
192
|
+
if (![33, 34].includes(input.documentType))
|
|
193
|
+
return Promise.reject(new TypeError('Identidad de factura inválida'));
|
|
194
|
+
return this.#documentXml(input, (0, rut_1.parseRut)(input.issuerRut), true);
|
|
195
|
+
}
|
|
196
|
+
issuedDocumentXml(input) { return this.#documentXml(input); }
|
|
197
|
+
issuedInvoicePdf(input, options) { return this.#documentPdf(input, undefined, options); }
|
|
198
|
+
async receivedInvoicePdf(input, options) { return this.#documentPdf(input, (0, rut_1.parseRut)(input.issuerRut), options); }
|
|
199
|
+
async #documentPdf({ documentType, folio }, supplier, options = {}) {
|
|
200
|
+
this.session.assertReady();
|
|
201
|
+
if (![33, 34].includes(documentType) || typeof folio !== 'string' || !/^[1-9]\d{0,19}$/.test(folio))
|
|
202
|
+
throw new TypeError('Identidad de factura inválida');
|
|
203
|
+
const endpoint = supplier ? 'mipeShowPdf.cgi' : 'mipeDisplayPDF.cgi';
|
|
204
|
+
const historyEndpoint = supplier ? 'mipeAdminDocsRcp.cgi' : 'mipeAdminDocsEmi.cgi';
|
|
205
|
+
return this.session.pdfOperation(endpoint, async (signal, trackStream) => {
|
|
206
|
+
await this.#ensurePortal(supplier ? 'OPCION=1&TIPO=4' : DESTINATION, signal, true);
|
|
207
|
+
const query = new URLSearchParams({ ...(supplier ? { RUT_EMI: supplier.rut } : { RUT_RECP: '' }), FOLIO: folio, RZN_SOC: '', FEC_DESDE: '', FEC_HASTA: '', TPO_DOC: String(documentType), ESTADO: '', ORDEN: '', NUM_PAG: '1' });
|
|
208
|
+
const history = await this.#portal(historyEndpoint, undefined, `?${query}`, signal);
|
|
209
|
+
await this.#assertCompany(historyEndpoint);
|
|
210
|
+
let code;
|
|
211
|
+
try {
|
|
212
|
+
code = (0, invoice_pdf_1.invoicePdfCode)(history.document, { documentType, folio }, supplier?.formatted);
|
|
213
|
+
}
|
|
214
|
+
catch (error) {
|
|
215
|
+
const failureCode = error instanceof sii_error_1.SiiError ? error.code : 'SII_PROTOCOL_CHANGED';
|
|
216
|
+
const reason = failureCode === 'SII_PDF_UNAVAILABLE' ? 'DOCUMENT_NOT_FOUND' : failureCode === 'SII_PDF_IDENTITY_MISMATCH' ? 'PDF_IDENTITY_MISMATCH' : 'INVALID_RESPONSE';
|
|
217
|
+
throw this.session.failure(failureCode, historyEndpoint, reason, undefined, { stage: 'PDF_HISTORY' });
|
|
218
|
+
}
|
|
219
|
+
const pdfQuery = new URLSearchParams(supplier ? { CODIGO: code } : { DHDR_CODIGO: code });
|
|
220
|
+
const stream = await this.session.request(`${sii_http_session_1.FACTURADOR}${endpoint}?${pdfQuery}`, async (response) => {
|
|
221
|
+
await this.#assertCompany(endpoint);
|
|
222
|
+
return (0, invoice_pdf_1.readInvoicePdfStream)(response, this.session, endpoint, signal, trackStream);
|
|
223
|
+
}, { signal }, true);
|
|
224
|
+
return { stream, contentType: 'application/pdf', filename: `factura-${documentType}-${folio}.pdf` };
|
|
225
|
+
}, options.signal);
|
|
226
|
+
}
|
|
227
|
+
async #documentXml({ documentType, folio }, supplier, legacy = false) {
|
|
228
|
+
this.session.assertReady();
|
|
229
|
+
if (![33, 34, 61].includes(documentType) || typeof folio !== 'string' || !/^[1-9]\d{0,19}$/.test(folio))
|
|
230
|
+
throw new TypeError('Identidad de documento inválida');
|
|
231
|
+
await this.#ensurePortal();
|
|
232
|
+
const query = new URLSearchParams({ ORIGEN: supplier ? 'RCP' : 'ENV', ...(supplier ? { RUT_EMI: supplier.rut } : { RUT_RECP: '' }), FOLIO: folio, RZN_SOC: '', FEC_DESDE: '', FEC_HASTA: '', TPO_DOC: String(documentType), ESTADO: '', ORDEN: '', DOWNLOAD: 'XML' });
|
|
233
|
+
return this.session.request(`${sii_http_session_1.FACTURADOR}mipeDownLoad.cgi?${query}`, async (response) => {
|
|
234
|
+
const bytes = await this.session.readBounded(response, 'mipeDownLoad.cgi');
|
|
235
|
+
const format = (0, sii_http_session_1.responseFormat)(response, bytes);
|
|
236
|
+
if (format.responseType === 'EMPTY')
|
|
237
|
+
throw this.session.failure('SII_SERVICE_ERROR', 'mipeDownLoad.cgi', 'EMPTY_RESPONSE', response, format);
|
|
238
|
+
if (format.responseType === 'PDF' || format.responseType === 'ZIP')
|
|
239
|
+
throw this.session.failure('SII_SERVICE_ERROR', 'mipeDownLoad.cgi', format.responseType === 'PDF' ? 'UNEXPECTED_PDF' : 'UNEXPECTED_ARCHIVE', response, format);
|
|
240
|
+
if (format.responseType !== 'XML' && !(format.responseType === 'UNKNOWN' && format.contentType === 'application/octet-stream')) {
|
|
241
|
+
const page = Buffer.from(bytes).toString('latin1');
|
|
242
|
+
const siiMessageCode = page.match(/\b\d{2}\.\d{2}\.\d{3}\.\d{3}\.\d{3}\.\d{2}\b/)?.[0];
|
|
243
|
+
const evidence = { ...format, ...(siiMessageCode ? { siiMessageCode } : {}) };
|
|
244
|
+
if (/recaptcha-response|g-recaptcha|captcha/i.test(page))
|
|
245
|
+
throw this.session.failure('CAPTCHA_INTERACTION_REQUIRED', 'mipeDownLoad.cgi', 'CAPTCHA_REQUIRED', response, evidence);
|
|
246
|
+
const reason = /demasiados\s+documentos/i.test(page) ? 'DOCUMENT_LIMIT_EXCEEDED'
|
|
247
|
+
: /no\s+se\s+encontraron\s+documentos/i.test(page) ? 'DOCUMENT_NOT_FOUND'
|
|
248
|
+
: /error\s+al\s+contribuyente/i.test(page) ? 'PROVIDER_ERROR_PAGE'
|
|
249
|
+
: format.responseType === 'HTML' ? 'HTML_RESPONSE' : 'UNEXPECTED_FORMAT';
|
|
250
|
+
throw this.session.failure(reason === 'DOCUMENT_NOT_FOUND' ? 'SII_XML_UNAVAILABLE' : 'SII_SERVICE_ERROR', 'mipeDownLoad.cgi', reason, response, evidence);
|
|
251
|
+
}
|
|
252
|
+
try {
|
|
253
|
+
const identity = { issuerRut: supplier?.formatted ?? this.session.company.formatted, ...(supplier ? { receiverRut: this.session.company.formatted } : {}), folio };
|
|
254
|
+
if (legacy) {
|
|
255
|
+
if (documentType !== 33 && documentType !== 34)
|
|
256
|
+
throw new invoice_xml_1.DteXmlError('SII_XML_INVALID');
|
|
257
|
+
return (0, dte_xml_1.parseDteXml)(bytes, { ...identity, documentType });
|
|
258
|
+
}
|
|
259
|
+
return (0, dte_xml_1.parseDteDocumentXml)(bytes, { ...identity, documentType });
|
|
260
|
+
}
|
|
261
|
+
catch (error) {
|
|
262
|
+
const code = error instanceof invoice_xml_1.DteXmlError ? error.code : 'SII_XML_INVALID';
|
|
263
|
+
throw this.session.failure(code, 'mipeDownLoad.cgi', code === 'SII_XML_IDENTITY_MISMATCH' ? 'XML_IDENTITY_MISMATCH' : 'INVALID_XML', response, { ...format, stage: 'XML_PARSE' });
|
|
264
|
+
}
|
|
265
|
+
}, {}, true);
|
|
266
|
+
}
|
|
267
|
+
async #ensurePortal(destination = DESTINATION, signal, refresh = false) {
|
|
268
|
+
if (this.#ready && destination === DESTINATION && !refresh)
|
|
269
|
+
return;
|
|
270
|
+
let url = `${sii_http_session_1.FACTURADOR}mipeSelEmpresa.cgi?DESDE_DONDE_URL=${encodeURIComponent(destination)}`;
|
|
271
|
+
let options = {}, submitted = false;
|
|
272
|
+
for (let hop = 0;; hop++) {
|
|
273
|
+
const result = await this.session.request(url, async (response) => {
|
|
274
|
+
const location = response.headers.get('location');
|
|
275
|
+
if (response.status >= 300 && response.status < 400) {
|
|
276
|
+
await response.body?.cancel();
|
|
277
|
+
if (!location || hop >= 4)
|
|
278
|
+
throw this.session.failure('SII_XML_COMPANY_SELECTION_REQUIRED', (0, sii_http_session_1.endpointFor)(url), 'COMPANY_SELECTION_REQUIRED', response);
|
|
279
|
+
let next;
|
|
280
|
+
try {
|
|
281
|
+
next = new URL(location, url);
|
|
282
|
+
}
|
|
283
|
+
catch {
|
|
284
|
+
throw this.session.failure('SESSION_OR_INTERACTIVE_AUTH_REQUIRED', (0, sii_http_session_1.endpointFor)(url), 'SESSION_REQUIRED', response);
|
|
285
|
+
}
|
|
286
|
+
const paths = signal ? ['mipeSelEmpresa.cgi', 'mipeLaunchPage.cgi', destination === DESTINATION ? 'mipeAdminDocsEmi.cgi' : 'mipeAdminDocsRcp.cgi'] : ['mipeSelEmpresa.cgi', 'mipeLaunchPage.cgi', 'mipeGenFacEx.cgi', 'mipeAdminDocsEmi.cgi'];
|
|
287
|
+
if (next.origin !== 'https://www1.sii.cl' || next.username || next.password || !paths.some(path => next.pathname === `/cgi-bin/Portal001/${path}`))
|
|
288
|
+
throw this.session.failure('SESSION_OR_INTERACTIVE_AUTH_REQUIRED', (0, sii_http_session_1.endpointFor)(url), 'SESSION_REQUIRED', response);
|
|
289
|
+
return { next: next.href };
|
|
290
|
+
}
|
|
291
|
+
const page = response.body ? Buffer.from(await this.session.readBounded(response, (0, sii_http_session_1.endpointFor)(url), undefined, undefined, signal)).toString('latin1') : '';
|
|
292
|
+
const document = (0, facturador_1.parsePortalPage)(page);
|
|
293
|
+
if ((0, facturador_1.hasInteractiveCaptcha)(document))
|
|
294
|
+
throw this.session.failure('CAPTCHA_INTERACTION_REQUIRED', (0, sii_http_session_1.endpointFor)(url), 'CAPTCHA_REQUIRED', response);
|
|
295
|
+
const selection = companySelection(document, this.session.company.formatted, destination);
|
|
296
|
+
if (typeof selection === 'string')
|
|
297
|
+
throw this.session.failure('SII_XML_COMPANY_SELECTION_REQUIRED', (0, sii_http_session_1.endpointFor)(url), selection, response);
|
|
298
|
+
if (selection && (submitted || hop >= 4))
|
|
299
|
+
throw this.session.failure('SII_XML_COMPANY_SELECTION_REQUIRED', (0, sii_http_session_1.endpointFor)(url), 'COMPANY_SELECTION_REQUIRED', response);
|
|
300
|
+
return { selection };
|
|
301
|
+
}, { ...options, signal }, (destination === DESTINATION || Boolean(signal)) && options.method !== 'POST', true);
|
|
302
|
+
if (result.next) {
|
|
303
|
+
url = result.next;
|
|
304
|
+
options = {};
|
|
305
|
+
continue;
|
|
306
|
+
}
|
|
307
|
+
if (result.selection) {
|
|
308
|
+
submitted = true;
|
|
309
|
+
url = `${sii_http_session_1.FACTURADOR}mipeSelEmpresa.cgi`;
|
|
310
|
+
options = { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: result.selection.toString() };
|
|
311
|
+
continue;
|
|
312
|
+
}
|
|
313
|
+
break;
|
|
314
|
+
}
|
|
315
|
+
await this.#assertCompany('mipeSelEmpresa.cgi');
|
|
316
|
+
this.#ready = destination !== 'OPCION=1&TIPO=4';
|
|
317
|
+
}
|
|
318
|
+
async #assertCompany(endpoint) {
|
|
319
|
+
const cookies = await this.session.cookies(sii_http_session_1.FACTURADOR);
|
|
320
|
+
if (cookies.find(c => c.key === 'NETSCAPE_LIVEWIRE.rcmp')?.value !== this.session.company.rut || cookies.find(c => c.key === 'NETSCAPE_LIVEWIRE.dcmp')?.value.toUpperCase() !== this.session.company.dv)
|
|
321
|
+
throw this.session.failure('SII_XML_COMPANY_SELECTION_REQUIRED', endpoint, 'COMPANY_SELECTION_REQUIRED');
|
|
322
|
+
}
|
|
323
|
+
async #portal(endpoint, fields, query = '', signal) {
|
|
324
|
+
return this.session.request(`${sii_http_session_1.FACTURADOR}${endpoint}${query}`, async (response) => {
|
|
325
|
+
const bytes = await this.session.readBounded(response, endpoint, undefined, undefined, signal);
|
|
326
|
+
if (!bytes.length && endpoint !== 'mipeSelEmpresa.cgi')
|
|
327
|
+
throw this.session.failure('SII_INVALID_RESPONSE', endpoint, 'EMPTY_RESPONSE', response);
|
|
328
|
+
const text = (0, facturador_1.readPortalHtml)(bytes);
|
|
329
|
+
const document = (0, facturador_1.parsePortalPage)(text);
|
|
330
|
+
if (signal && (0, facturador_1.hasInteractiveCaptcha)(document))
|
|
331
|
+
throw this.session.failure('CAPTCHA_INTERACTION_REQUIRED', endpoint, 'CAPTCHA_REQUIRED', response, { stage: 'PDF_HISTORY' });
|
|
332
|
+
if (endpoint === 'mipeDisplayPreView.cgi' && /Redireccionando/i.test(text) && /\balert\s*\(/.test(text) && /(?:window\.)?history\.go\(\s*-1\s*\)/.test(text))
|
|
333
|
+
throw this.session.failure('SII_DOCUMENT_VALIDATION_REJECTED', endpoint, 'PROVIDER_REJECTED', response);
|
|
334
|
+
const loginForm = htmlElements(document).some(element => element.tagName === 'form' && /(?:^|\/)CAutInicio\.cgi(?:[?#]|$)/i.test((0, facturador_1.attr)(element, 'action') ?? '') && htmlElements(element).some(control => control.tagName === 'input' && (0, facturador_1.attr)(control, 'name')?.toLowerCase() === 'clave'));
|
|
335
|
+
if (loginForm)
|
|
336
|
+
throw this.session.failure('SESSION_REQUIRED', endpoint, 'SESSION_REQUIRED', response);
|
|
337
|
+
if (/Error\s+al\s+Contribuyente/i.test(text)) {
|
|
338
|
+
const code = text.match(/\b\d{2}\.\d{2}\.\d{3}\.\d{3}\.\d{3}\.\d{2}\b/)?.[0];
|
|
339
|
+
throw this.session.failure('SII_SERVICE_ERROR', endpoint, 'PROVIDER_ERROR_PAGE', response, code ? { siiMessageCode: code } : {});
|
|
340
|
+
}
|
|
341
|
+
return { text, document };
|
|
342
|
+
}, fields === undefined ? { signal } : { method: 'POST', signal, headers: { 'Content-Type': 'application/x-www-form-urlencoded', Referer: `${sii_http_session_1.FACTURADOR}${endpoint}` }, body: typeof fields === 'string' ? fields : (0, facturador_1.encodePortalForm)(fields) }, Boolean(signal) && fields === undefined);
|
|
343
|
+
}
|
|
344
|
+
#form(page, name, endpoint, alternative) {
|
|
345
|
+
try {
|
|
346
|
+
return (0, facturador_1.readForm)(page.document, name, endpoint);
|
|
347
|
+
}
|
|
348
|
+
catch {
|
|
349
|
+
if (alternative) {
|
|
350
|
+
try {
|
|
351
|
+
return (0, facturador_1.readForm)(page.document, name, alternative);
|
|
352
|
+
}
|
|
353
|
+
catch { /* Only known form actions are allowed. */ }
|
|
354
|
+
}
|
|
355
|
+
const source = name === 'VIEW_EFXP' ? 'mipeGenFacEx.cgi' : name === 'PreViewDTE' ? 'mipeDisplayPreView.cgi' : 'mipeGenXMLFirma.cgi';
|
|
356
|
+
throw this.session.failure('SII_PROTOCOL_CHANGED', source, 'INVALID_RESPONSE');
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
#assertOption(page, variable, value, commune, column = 0) {
|
|
360
|
+
try {
|
|
361
|
+
const rows = (0, facturador_1.readLiteralRows)(page.document, variable).filter(row => row[column]?.trim() === value && (commune === undefined || row[1]?.trim() === commune));
|
|
362
|
+
if (rows.length === 1 && rows[0])
|
|
363
|
+
return rows[0];
|
|
364
|
+
}
|
|
365
|
+
catch { /* No provider scripts execute. */ }
|
|
366
|
+
throw this.session.failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeGenFacEx.cgi', 'DOCUMENT_CONTENT_MISMATCH');
|
|
367
|
+
}
|
|
368
|
+
#assertFields(fields, expected) {
|
|
369
|
+
for (const [key, value] of Object.entries(expected))
|
|
370
|
+
if (fields.get(key)?.trim() !== value)
|
|
371
|
+
throw this.session.failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeDisplayPreView.cgi', 'DOCUMENT_CONTENT_MISMATCH');
|
|
372
|
+
}
|
|
373
|
+
#assertNewInvoice(fields) {
|
|
374
|
+
if (fields.get('PTDC_CODIGO') !== '33' || fields.get('EHDR_CODIGO')?.trim() || fields.get('EFXP_FOLIO')?.trim() || fields.get('ES_BORR')?.toUpperCase() !== 'FALSE' || fields.get('esCRED_EC')?.toUpperCase() !== 'FALSE' || fields.get('esFACT_TUR')?.toUpperCase() !== 'FALSE')
|
|
375
|
+
throw this.session.failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeGenFacEx.cgi', 'DOCUMENT_CONTENT_MISMATCH');
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
exports.FacturadorGateway = FacturadorGateway;
|
|
379
|
+
/** Read the observed selector inertly; never execute scripts or forward arbitrary form fields. */
|
|
380
|
+
function companySelection(page, company, expectedDestination = DESTINATION) {
|
|
381
|
+
const forms = htmlElements(page).filter(e => e.tagName === 'form' && (0, facturador_1.attr)(e, 'name') === 'fPrmEmpPOP');
|
|
382
|
+
const form = forms[0];
|
|
383
|
+
if (!form)
|
|
384
|
+
return undefined;
|
|
385
|
+
if (forms.length !== 1 || (0, facturador_1.attr)(form, 'method')?.toLowerCase() !== 'post')
|
|
386
|
+
return 'INVALID_RESPONSE';
|
|
387
|
+
try {
|
|
388
|
+
if (new URL((0, facturador_1.attr)(form, 'action') ?? '', sii_http_session_1.FACTURADOR).href !== `${sii_http_session_1.FACTURADOR}mipeSelEmpresa.cgi`)
|
|
389
|
+
return 'INVALID_RESPONSE';
|
|
390
|
+
}
|
|
391
|
+
catch {
|
|
392
|
+
return 'INVALID_RESPONSE';
|
|
393
|
+
}
|
|
394
|
+
const controls = htmlElements(form);
|
|
395
|
+
const selects = controls.filter(e => e.tagName === 'select' && (0, facturador_1.attr)(e, 'name') === 'RUT_EMP');
|
|
396
|
+
const destinations = controls.filter(e => e.tagName === 'input' && (0, facturador_1.attr)(e, 'name') === 'DESDE_DONDE_URL');
|
|
397
|
+
const select = selects[0], destination = destinations[0];
|
|
398
|
+
if (selects.length !== 1 || destinations.length !== 1 || !select || !destination
|
|
399
|
+
|| (0, facturador_1.attr)(select, 'disabled') !== undefined || (0, facturador_1.attr)(select, 'multiple') !== undefined || (0, facturador_1.attr)(select, 'form') !== undefined
|
|
400
|
+
|| (0, facturador_1.attr)(destination, 'type')?.toLowerCase() !== 'hidden' || (0, facturador_1.attr)(destination, 'disabled') !== undefined || (0, facturador_1.attr)(destination, 'form') !== undefined
|
|
401
|
+
|| (0, facturador_1.attr)(destination, 'value') !== expectedDestination)
|
|
402
|
+
return 'INVALID_RESPONSE';
|
|
403
|
+
const options = htmlElements(select).filter(e => e.tagName === 'option' && (0, facturador_1.attr)(e, 'value')?.replace(/\./g, '').toUpperCase() === company);
|
|
404
|
+
if (options.length > 1)
|
|
405
|
+
return 'INVALID_RESPONSE';
|
|
406
|
+
const option = options[0];
|
|
407
|
+
if (!option || (0, facturador_1.attr)(option, 'disabled') !== undefined
|
|
408
|
+
|| (option.parentNode && 'tagName' in option.parentNode && option.parentNode.tagName === 'optgroup' && (0, facturador_1.attr)(option.parentNode, 'disabled') !== undefined))
|
|
409
|
+
return 'COMPANY_NOT_AUTHORIZED';
|
|
410
|
+
return new URLSearchParams({ DESDE_DONDE_URL: expectedDestination, RUT_EMP: company });
|
|
411
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type DefaultTreeAdapterTypes as Html } from 'parse5';
|
|
2
|
+
export declare function attr(element: Html.Element, name: string): string | undefined;
|
|
3
|
+
export declare function nodes(root: Html.Node): Generator<Html.Node>;
|
|
4
|
+
export declare function element(node: Html.Node): node is Html.Element;
|
|
5
|
+
export declare function parsePortalPage(html: string): Html.Document;
|
|
6
|
+
/** Serialize only inert successful controls; provider scripts are never executed. */
|
|
7
|
+
export declare function readForm(html: string | Html.Document, name: string, endpoint: string): URLSearchParams;
|
|
8
|
+
/** Decode only the observed small JSON array declarations, never JavaScript expressions. */
|
|
9
|
+
export declare function readLiteralRows(html: string | Html.Document, variable: string): string[][];
|
|
10
|
+
/** Browser legacy form encoding differs from UTF-8 URLSearchParams for accents and € . */
|
|
11
|
+
export declare function encodePortalForm(fields: URLSearchParams): string;
|
|
12
|
+
export declare function readPortalHtml(bytes: Uint8Array): string;
|
|
13
|
+
/** Encode unsigned XML as declared, without changing its text or silently truncating Unicode. */
|
|
14
|
+
export declare function encodeUnsignedDteXml(value: string): Uint8Array;
|
|
15
|
+
/** Read confirmation text after entity decoding; scripts and hidden payloads are not evidence. */
|
|
16
|
+
export declare function readVisiblePortalText(html: string | Html.Node): string;
|
|
17
|
+
/** A shared script or hidden v3 token field does not prove an interactive challenge. */
|
|
18
|
+
export declare function hasInteractiveCaptcha(document: Html.Document): boolean;
|