@devly-cl/sii-client 0.4.4 → 0.5.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 +84 -24
- package/dist/domain/invoice-xml.d.ts +65 -8
- package/dist/domain/invoice-xml.js +37 -5
- package/dist/domain/invoicing.d.ts +52 -0
- package/dist/domain/invoicing.js +157 -0
- package/dist/domain/issued-invoice.d.ts +16 -8
- package/dist/domain/received-invoice.d.ts +12 -6
- package/dist/domain/sii-error.d.ts +3 -3
- package/dist/domain/sii-error.js +10 -4
- package/dist/index.d.ts +9 -1
- package/dist/index.js +9 -1
- package/dist/infrastructure/facturador.d.ts +11 -0
- package/dist/infrastructure/facturador.js +217 -0
- package/dist/infrastructure/sii-client.d.ts +117 -20
- package/dist/infrastructure/sii-client.js +360 -52
- package/package.json +4 -4
|
@@ -12,6 +12,9 @@ Object.defineProperty(exports, "SiiError", { enumerable: true, get: function ()
|
|
|
12
12
|
const issued_invoice_1 = require("../domain/issued-invoice");
|
|
13
13
|
const received_invoice_1 = require("../domain/received-invoice");
|
|
14
14
|
const invoice_xml_1 = require("../domain/invoice-xml");
|
|
15
|
+
const invoice_xml_2 = require("../domain/invoice-xml");
|
|
16
|
+
const invoicing_1 = require("../domain/invoicing");
|
|
17
|
+
const facturador_1 = require("./facturador");
|
|
15
18
|
const AUTH = 'https://zeusr.sii.cl/cgi_AUT2000/CAutInicio.cgi';
|
|
16
19
|
const LOGOUT = 'https://zeusr.sii.cl/cgi_AUT2000/autTermino.cgi';
|
|
17
20
|
const RCV = 'https://www4.sii.cl/consdcvinternetui/';
|
|
@@ -25,6 +28,7 @@ const ENDPOINT_STAGES = {
|
|
|
25
28
|
'CAutInicio.cgi': 'AUTHENTICATION', 'aaSessionService/load': 'SESSION_CHECK', getDcvEmpresasAutorizadas: 'COMPANY_AUTHORIZATION',
|
|
26
29
|
getDatosInicio: 'RCV_INITIALIZATION', getResumen: 'RCV_SUMMARY', getDetalleCompra: 'RCV_DETAIL', getDetalleVenta: 'RCV_DETAIL',
|
|
27
30
|
'mipeSelEmpresa.cgi': 'XML_COMPANY_SELECTION', 'mipeLaunchPage.cgi': 'XML_COMPANY_SELECTION', 'mipeDownLoad.cgi': 'XML_DOWNLOAD', 'autTermino.cgi': 'LOGOUT',
|
|
31
|
+
'mipeGenFacEx.cgi': 'DOCUMENT_PREPARATION', 'mipeDisplayPreView.cgi': 'DOCUMENT_REVIEW', 'mipeGenXMLFirma.cgi': 'DOCUMENT_SIGNING', 'getCertDigital.cgi': 'DOCUMENT_SIGNING', 'postFirmaDigital.cgi': 'DOCUMENT_SIGNING', 'mipeSendXML.cgi': 'DOCUMENT_SEND', 'mipeAdminDocsEmi.cgi': 'DOCUMENT_RECOVERY', 'mipeGesDocEmi.cgi': 'DOCUMENT_RECOVERY', 'mipeDisplayPDF.cgi': 'DOCUMENT_RECOVERY',
|
|
28
32
|
};
|
|
29
33
|
function endpointFor(url) {
|
|
30
34
|
const path = new URL(url).pathname;
|
|
@@ -68,7 +72,7 @@ function htmlElements(root) {
|
|
|
68
72
|
return elements;
|
|
69
73
|
}
|
|
70
74
|
/** Read the observed selector inertly; never execute scripts or forward arbitrary form fields. */
|
|
71
|
-
function companySelection(page, company) {
|
|
75
|
+
function companySelection(page, company, expectedDestination = FACTURADOR_DESTINATION) {
|
|
72
76
|
const attr = (element, name) => element.attrs.find(a => a.name === name)?.value;
|
|
73
77
|
const forms = htmlElements((0, parse5_1.parse)(page)).filter(e => e.tagName === 'form' && attr(e, 'name') === 'fPrmEmpPOP');
|
|
74
78
|
const form = forms[0];
|
|
@@ -90,7 +94,7 @@ function companySelection(page, company) {
|
|
|
90
94
|
if (selects.length !== 1 || destinations.length !== 1 || !select || !destination
|
|
91
95
|
|| attr(select, 'disabled') !== undefined || attr(select, 'multiple') !== undefined || attr(select, 'form') !== undefined
|
|
92
96
|
|| attr(destination, 'type')?.toLowerCase() !== 'hidden' || attr(destination, 'disabled') !== undefined || attr(destination, 'form') !== undefined
|
|
93
|
-
|| attr(destination, 'value') !==
|
|
97
|
+
|| attr(destination, 'value') !== expectedDestination)
|
|
94
98
|
return 'INVALID_RESPONSE';
|
|
95
99
|
const options = htmlElements(select).filter(e => e.tagName === 'option' && attr(e, 'value')?.replace(/\./g, '').toUpperCase() === company);
|
|
96
100
|
if (options.length > 1)
|
|
@@ -99,7 +103,7 @@ function companySelection(page, company) {
|
|
|
99
103
|
if (!option || attr(option, 'disabled') !== undefined
|
|
100
104
|
|| (option.parentNode && 'tagName' in option.parentNode && option.parentNode.tagName === 'optgroup' && attr(option.parentNode, 'disabled') !== undefined))
|
|
101
105
|
return 'COMPANY_NOT_AUTHORIZED';
|
|
102
|
-
return new URLSearchParams({ DESDE_DONDE_URL:
|
|
106
|
+
return new URLSearchParams({ DESDE_DONDE_URL: expectedDestination, RUT_EMP: company });
|
|
103
107
|
}
|
|
104
108
|
/** Una instancia = una empresa y una sesión personal. Nunca comparte cookies. */
|
|
105
109
|
class SiiClient {
|
|
@@ -116,6 +120,8 @@ class SiiClient {
|
|
|
116
120
|
#requests = new Set();
|
|
117
121
|
#disposal;
|
|
118
122
|
#traceId = (0, node_crypto_1.randomUUID)();
|
|
123
|
+
#write;
|
|
124
|
+
#prepared;
|
|
119
125
|
#failure(code, endpoint, reason, response, extra = {}) {
|
|
120
126
|
return new sii_error_1.SiiError(code, response?.status, { traceId: this.#traceId, stage: ENDPOINT_STAGES[endpoint], endpoint, reason,
|
|
121
127
|
...(response ? { httpStatus: response.status, ...responseFormat(response) } : {}), ...extra });
|
|
@@ -172,11 +178,11 @@ class SiiClient {
|
|
|
172
178
|
throw error;
|
|
173
179
|
}
|
|
174
180
|
}
|
|
175
|
-
async
|
|
181
|
+
async getAuthorizedCompanies() {
|
|
176
182
|
const identity = this.#assertReady();
|
|
177
183
|
return this.#call('getDcvEmpresasAutorizadas', { rutAutenticado: identity.rut, dvAutenticado: identity.dv });
|
|
178
184
|
}
|
|
179
|
-
async
|
|
185
|
+
async getSummary({ periodo, operacion, estado = 'REGISTRO' }) {
|
|
180
186
|
this.#assertReady();
|
|
181
187
|
assertPeriod(periodo);
|
|
182
188
|
if (!['COMPRA', 'VENTA'].includes(operacion))
|
|
@@ -185,14 +191,276 @@ class SiiClient {
|
|
|
185
191
|
throw new TypeError('Estado inválido');
|
|
186
192
|
return this.#call('getResumen', { rutEmisor: this.#company.rut, dvEmisor: this.#company.dv, ptributario: periodo, estadoContab: estado, operacion });
|
|
187
193
|
}
|
|
188
|
-
|
|
189
|
-
return this.#
|
|
194
|
+
getIssuedInvoices(input) {
|
|
195
|
+
return this.#getInvoices('VENTA', input, issued_invoice_1.normalizeIssuedInvoice);
|
|
190
196
|
}
|
|
191
197
|
/** Facturas 33/34 in the official purchase register. Does not accept, claim or move documents. */
|
|
192
|
-
|
|
193
|
-
return this.#
|
|
198
|
+
getReceivedInvoices(input) {
|
|
199
|
+
return this.#getInvoices('COMPRA', input, received_invoice_1.normalizeReceivedInvoice);
|
|
194
200
|
}
|
|
195
|
-
async
|
|
201
|
+
async prepareInvoice(input) {
|
|
202
|
+
this.#assertReady();
|
|
203
|
+
const invoice = (0, invoicing_1.validateInvoice)(input);
|
|
204
|
+
return this.#writeOperation(async () => {
|
|
205
|
+
await this.#ensureInvoicingPortal('OPCION=33&TIPO=4');
|
|
206
|
+
let page = await this.#portal('mipeGenFacEx.cgi', undefined, '?PTDC_CODIGO=33');
|
|
207
|
+
let fields = this.#form(page, 'VIEW_EFXP', 'mipeDisplayPreView.cgi');
|
|
208
|
+
this.#assertNewInvoice(fields);
|
|
209
|
+
const issuerAddress = this.#assertOption(page, 'emisorDir', invoice.issuer.address, invoice.issuer.commune);
|
|
210
|
+
this.#assertOption(page, 'emisorActEco', invoice.issuer.activityCode);
|
|
211
|
+
const receiver = (0, rut_1.parseRut)(invoice.receiver.rut);
|
|
212
|
+
fields.set('EFXP_RUT_RECEP', receiver.rut);
|
|
213
|
+
fields.set('EFXP_DV_RECEP', receiver.dv);
|
|
214
|
+
page = await this.#portal('mipeGenFacEx.cgi', fields);
|
|
215
|
+
fields = this.#form(page, 'VIEW_EFXP', 'mipeDisplayPreView.cgi');
|
|
216
|
+
this.#assertNewInvoice(fields);
|
|
217
|
+
this.#assertOption(page, 'recptorDir', invoice.receiver.address, invoice.receiver.commune);
|
|
218
|
+
this.#assertOption(page, 'recptoActEco', invoice.receiver.businessActivity, undefined, 1);
|
|
219
|
+
if (fields.get('EFXP_RZN_SOC_RECEP')?.trim() && fields.get('EFXP_RZN_SOC_RECEP')?.trim() !== invoice.receiver.legalName)
|
|
220
|
+
throw this.#failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeGenFacEx.cgi', 'DOCUMENT_CONTENT_MISMATCH');
|
|
221
|
+
const totals = (0, invoicing_1.calculateInvoiceTotals)(invoice.items);
|
|
222
|
+
const values = {
|
|
223
|
+
PTDC_CODIGO: '33', EFXP_FCH_EMIS: invoice.issuedDate, CANT_DET: String(invoice.items.length), ES_BORR: 'FALSE',
|
|
224
|
+
EFXP_DIR_ORIGEN: invoice.issuer.address, EFXP_CMNA_ORIGEN: invoice.issuer.commune, EFXP_CIUDAD_ORIGEN: invoice.issuer.city,
|
|
225
|
+
EFXP_CDG_SII_SUCUR: issuerAddress[3]?.trim() === '0' ? '' : issuerAddress[3]?.trim() ?? '', EFXP_FONO_EMISOR: issuerAddress[4]?.trim() ?? '',
|
|
226
|
+
EFXP_ACTECO: invoice.issuer.activityCode, EFXP_ACTECO_SELECT: invoice.issuer.activityCode, EFXP_TIPOVENTA_SELECT: String(invoice.saleType),
|
|
227
|
+
EFXP_RUT_RECEP: receiver.rut, EFXP_DV_RECEP: receiver.dv, EFXP_RZN_SOC_RECEP: invoice.receiver.legalName,
|
|
228
|
+
EFXP_DIR_RECEP: invoice.receiver.address, EFXP_CMNA_RECEP: invoice.receiver.commune, EFXP_CIUDAD_RECEP: invoice.receiver.city,
|
|
229
|
+
EFXP_GIRO_RECEP: invoice.receiver.businessActivity, EFXP_CONTACTO: invoice.receiver.contact ?? '', EFXP_TIPOCOMPRA_SELECT: String(invoice.purchaseType),
|
|
230
|
+
EFXP_RUT_SOLICITA: '', EFXP_DV_SOLICITA: '', EFXP_FMA_PAGO: String(invoice.paymentForm),
|
|
231
|
+
EFXP_SUBTOTAL: String(totals.netAmount), EFXP_PCT_DESC: '0', EFXP_MNT_DESC: '0', MNT_NETO_TEMP: String(totals.netAmount), IVA_TEMP: String(totals.vatAmount),
|
|
232
|
+
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',
|
|
233
|
+
};
|
|
234
|
+
for (const [key, value] of Object.entries(values))
|
|
235
|
+
fields.set(key, value);
|
|
236
|
+
for (const key of [...fields.keys()])
|
|
237
|
+
if (/^(?:EFXP_(?:TPO_COD|COD|NMB|QTY|UNMD|PRC|OTRO_IMP|PCTD|SUBT|DSC_ITEM)_\d{2}|DESCRIP_\d{2}|.*_SI_NO)$/.test(key))
|
|
238
|
+
fields.delete(key);
|
|
239
|
+
for (const [index, item] of invoice.items.entries()) {
|
|
240
|
+
const suffix = String(index + 1).padStart(2, '0');
|
|
241
|
+
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) }))
|
|
242
|
+
fields.set(`EFXP_${field}_${suffix}`, value);
|
|
243
|
+
if (item.description)
|
|
244
|
+
fields.set(`DESCRIP_${suffix}`, 'SiChecked');
|
|
245
|
+
}
|
|
246
|
+
page = await this.#portal('mipeDisplayPreView.cgi', fields);
|
|
247
|
+
const preview = this.#form(page, 'PreViewDTE', 'mipeGenXMLFirma.cgi', 'mipeGenFacEx.cgi');
|
|
248
|
+
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) });
|
|
249
|
+
return this.#keepPreparation({ issuerRut: this.#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') ?? '' }, preview);
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
async prepareCancellationCreditNote({ factura, issuedDate }) {
|
|
253
|
+
this.#assertReady();
|
|
254
|
+
if (factura.documentType !== 33 || !/^[1-9]\d{0,19}$/.test(factura.folio) || !/^\d{4}-\d{2}-\d{2}$/.test(issuedDate) || new Date(`${issuedDate}T00:00:00Z`).toISOString().slice(0, 10) !== issuedDate)
|
|
255
|
+
throw new TypeError('Referencia o fecha de anulación inválida');
|
|
256
|
+
return this.#writeOperation(async () => {
|
|
257
|
+
const original = await this.getIssuedDocumentXml(factura);
|
|
258
|
+
const query = new URLSearchParams({ RUT_RECP: '', FOLIO: factura.folio, RZN_SOC: '', FEC_DESDE: '', FEC_HASTA: '', TPO_DOC: '33', ESTADO: '', ORDEN: '', NUM_PAG: '1' });
|
|
259
|
+
const history = await this.#portal('mipeAdminDocsEmi.cgi', undefined, `?${query}`);
|
|
260
|
+
const codes = new Set();
|
|
261
|
+
for (const element of htmlElements((0, parse5_1.parse)(history)))
|
|
262
|
+
if (element.tagName === 'a') {
|
|
263
|
+
const href = element.attrs.find(a => a.name === 'href')?.value;
|
|
264
|
+
if (!href)
|
|
265
|
+
continue;
|
|
266
|
+
try {
|
|
267
|
+
const link = new URL(href, FACTURADOR);
|
|
268
|
+
if (link.origin === 'https://www1.sii.cl' && link.pathname === '/cgi-bin/Portal001/mipeGesDocEmi.cgi' && /^\d{1,20}$/.test(link.searchParams.get('CODIGO') ?? ''))
|
|
269
|
+
codes.add(link.searchParams.get('CODIGO'));
|
|
270
|
+
}
|
|
271
|
+
catch { /* Non-document links are ignored. */ }
|
|
272
|
+
}
|
|
273
|
+
if (codes.size !== 1)
|
|
274
|
+
throw this.#failure('SII_DOCUMENT_RECOVERY_FAILED', 'mipeAdminDocsEmi.cgi', codes.size === 0 ? 'DOCUMENT_NOT_FOUND' : 'INVALID_RESPONSE');
|
|
275
|
+
const page = await this.#portal('mipeDisplayPreView.cgi', undefined, `?EHDR_CODIGO=${[...codes][0]}&TIPO_NOTA=61`);
|
|
276
|
+
const fields = this.#form(page, 'PreViewDTE', 'mipeGenXMLFirma.cgi', 'mipeGenFacEx.cgi');
|
|
277
|
+
const d = original.detail;
|
|
278
|
+
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) });
|
|
279
|
+
if (fields.get('EFXP_FOLIO_REF_002')?.trim() || fields.get('EFXP_FOLIO_REF_003')?.trim() || d.netAmount === null || d.vatAmount === null)
|
|
280
|
+
throw this.#failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeDisplayPreView.cgi', 'DOCUMENT_CONTENT_MISMATCH');
|
|
281
|
+
return this.#keepPreparation({ 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 } }, fields);
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
signAndSend(input) {
|
|
285
|
+
if (this.#write)
|
|
286
|
+
return Promise.reject(new sii_error_1.SiiError('SII_OPERATION_IN_PROGRESS'));
|
|
287
|
+
const prepared = this.#prepared;
|
|
288
|
+
if (!prepared || input.preparacionId !== prepared.public.preparacionId || Date.now() >= Date.parse(prepared.public.expiresAt))
|
|
289
|
+
return Promise.reject(new sii_error_1.SiiError('SII_PREPARATION_UNAVAILABLE'));
|
|
290
|
+
if (input.approvedHash !== prepared.public.contentHash)
|
|
291
|
+
return Promise.reject(new sii_error_1.SiiError('SII_APPROVAL_MISMATCH'));
|
|
292
|
+
if (typeof input.claveFirma !== 'string' || !input.claveFirma || input.claveFirma.length > 256 || typeof input.beforeSend !== 'function')
|
|
293
|
+
return Promise.reject(new TypeError('Clave de firma o persistencia previa inválida'));
|
|
294
|
+
this.#assertReady();
|
|
295
|
+
return this.#writeOperation(async () => {
|
|
296
|
+
this.#prepared = undefined;
|
|
297
|
+
let sendStarted = false;
|
|
298
|
+
try {
|
|
299
|
+
const page = await this.#portal('mipeGenXMLFirma.cgi', prepared.fields);
|
|
300
|
+
const fields = this.#form(page, 'frmSign', 'mipeSendXML.cgi');
|
|
301
|
+
const folio = fields.get('EFXP_FOLIO') ?? '';
|
|
302
|
+
if (!/^[1-9]\d{0,19}$/.test(folio))
|
|
303
|
+
throw this.#failure('SII_SIGNATURE_INVALID', 'mipeGenXMLFirma.cgi', 'INVALID_RESPONSE');
|
|
304
|
+
const plain = fields.get('txtPlainText') ?? '';
|
|
305
|
+
const expected = { issuerRut: prepared.public.issuerRut, receiverRut: prepared.public.receiverRut, documentType: prepared.public.documentType, folio };
|
|
306
|
+
let unsigned;
|
|
307
|
+
try {
|
|
308
|
+
unsigned = (0, invoice_xml_2.parseDteDocumentXml)((0, facturador_1.encodeUnsignedDteXml)(plain), expected);
|
|
309
|
+
}
|
|
310
|
+
catch {
|
|
311
|
+
throw this.#failure('SII_SIGNATURE_INVALID', 'mipeGenXMLFirma.cgi', 'INVALID_XML');
|
|
312
|
+
}
|
|
313
|
+
this.#assertDocument(unsigned, prepared.public);
|
|
314
|
+
const identity = this.#assertReady();
|
|
315
|
+
const certificatePage = await this.#portal('getCertDigital.cgi', undefined, `?rut=${identity.rut}&dv=${identity.dv}`);
|
|
316
|
+
let certs;
|
|
317
|
+
try {
|
|
318
|
+
certs = JSON.parse(certificatePage);
|
|
319
|
+
}
|
|
320
|
+
catch {
|
|
321
|
+
throw this.#failure('SII_CERTIFICATE_UNAVAILABLE', 'getCertDigital.cgi', 'CERTIFICATE_UNAVAILABLE');
|
|
322
|
+
}
|
|
323
|
+
if (!Array.isArray(certs) || certs.length !== 1 || !isRecord(certs[0]) || typeof certs[0].nombre !== 'string' || !certs[0].nombre || certs[0].nombre.length > 256)
|
|
324
|
+
throw this.#failure('SII_CERTIFICATE_UNAVAILABLE', 'getCertDigital.cgi', 'CERTIFICATE_UNAVAILABLE');
|
|
325
|
+
const signing = new URLSearchParams({ nombre: certs[0].nombre, dato: plain, rut: identity.rut, dv: identity.dv, clave: input.claveFirma, nodo: 'dte:DTE', nodoId: 'dte:Documento', nameSpace: 'http://www.sii.cl/SiiDte' });
|
|
326
|
+
const response = await this.#request(`${FACTURADOR}postFirmaDigital.cgi`, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', Referer: `${FACTURADOR}mipeGenXMLFirma.cgi` }, body: signing.toString() });
|
|
327
|
+
const signedBytes = await this.#readBounded(response, 'postFirmaDigital.cgi');
|
|
328
|
+
if (!signedBytes.length)
|
|
329
|
+
throw this.#failure('SII_SIGNATURE_INVALID', 'postFirmaDigital.cgi', 'EMPTY_RESPONSE', response);
|
|
330
|
+
let signed;
|
|
331
|
+
try {
|
|
332
|
+
signed = (0, invoice_xml_2.parseDteDocumentXml)(signedBytes, expected);
|
|
333
|
+
}
|
|
334
|
+
catch {
|
|
335
|
+
const text = (0, facturador_1.readPortalHtml)(signedBytes);
|
|
336
|
+
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';
|
|
337
|
+
throw this.#failure('SII_SIGNATURE_INVALID', 'postFirmaDigital.cgi', reason, response);
|
|
338
|
+
}
|
|
339
|
+
this.#assertDocument(signed, prepared.public);
|
|
340
|
+
if (!signed.detail.hasSignature)
|
|
341
|
+
throw this.#failure('SII_SIGNATURE_INVALID', 'postFirmaDigital.cgi', 'SIGNATURE_INVALID', response);
|
|
342
|
+
const document = { ...signed, ...expected, issuedDate: prepared.public.issuedDate, contentHash: prepared.public.contentHash };
|
|
343
|
+
await input.beforeSend(structuredClone(document));
|
|
344
|
+
fields.set('txtSignText', Buffer.from(signed.xml).toString(signed.encoding === 'UTF-8' ? 'utf8' : 'latin1'));
|
|
345
|
+
fields.set('nombre', certs[0].nombre);
|
|
346
|
+
fields.set('clave', input.claveFirma);
|
|
347
|
+
fields.set('nodo', 'dte:DTE');
|
|
348
|
+
fields.set('nodoId', 'dte:Documento');
|
|
349
|
+
fields.set('nameSpace', 'http://www.sii.cl/SiiDte');
|
|
350
|
+
const body = (0, facturador_1.encodePortalForm)(fields);
|
|
351
|
+
sendStarted = true;
|
|
352
|
+
const sent = await this.#portal('mipeSendXML.cgi', body);
|
|
353
|
+
if (!/DOCUMENTO\s+TRIBUTARIO\s+ELECTR[ÓO]NICO\s+ENVIADO\s+EXITOSAMENTE/i.test((0, facturador_1.readVisiblePortalText)(sent)))
|
|
354
|
+
throw this.#failure('SII_ISSUANCE_OUTCOME_UNKNOWN', 'mipeSendXML.cgi', 'ISSUANCE_OUTCOME_UNKNOWN');
|
|
355
|
+
return { ...document, status: 'ENVIADO' };
|
|
356
|
+
}
|
|
357
|
+
catch (error) {
|
|
358
|
+
if (sendStarted)
|
|
359
|
+
throw this.#failure('SII_ISSUANCE_OUTCOME_UNKNOWN', 'mipeSendXML.cgi', 'ISSUANCE_OUTCOME_UNKNOWN');
|
|
360
|
+
throw error;
|
|
361
|
+
}
|
|
362
|
+
}).finally(() => this.dispose());
|
|
363
|
+
}
|
|
364
|
+
#writeOperation(action) {
|
|
365
|
+
if (this.#write)
|
|
366
|
+
return Promise.reject(new sii_error_1.SiiError('SII_OPERATION_IN_PROGRESS'));
|
|
367
|
+
const promise = action();
|
|
368
|
+
this.#write = promise;
|
|
369
|
+
void promise.then(() => { this.#write = undefined; }, () => { this.#write = undefined; });
|
|
370
|
+
return promise;
|
|
371
|
+
}
|
|
372
|
+
#keepPreparation(content, fields) {
|
|
373
|
+
const result = Object.freeze({ ...content, preparacionId: (0, node_crypto_1.randomUUID)(), contentHash: (0, invoicing_1.hashContent)(content), expiresAt: new Date(Date.now() + 300_000).toISOString() });
|
|
374
|
+
const freeze = (value) => { if (value && typeof value === 'object') {
|
|
375
|
+
for (const child of Object.values(value))
|
|
376
|
+
freeze(child);
|
|
377
|
+
Object.freeze(value);
|
|
378
|
+
} };
|
|
379
|
+
freeze(result);
|
|
380
|
+
this.#prepared = { public: result, fields };
|
|
381
|
+
return result;
|
|
382
|
+
}
|
|
383
|
+
async #portal(endpoint, fields, query = '') {
|
|
384
|
+
const response = await this.#request(`${FACTURADOR}${endpoint}${query}`, fields === undefined ? {} : { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', Referer: `${FACTURADOR}${endpoint}` }, body: typeof fields === 'string' ? fields : (0, facturador_1.encodePortalForm)(fields) });
|
|
385
|
+
const bytes = await this.#readBounded(response, endpoint);
|
|
386
|
+
if (!bytes.length) {
|
|
387
|
+
if (endpoint === 'mipeSelEmpresa.cgi')
|
|
388
|
+
return '';
|
|
389
|
+
throw this.#failure('SII_INVALID_RESPONSE', endpoint, 'EMPTY_RESPONSE', response);
|
|
390
|
+
}
|
|
391
|
+
const page = (0, facturador_1.readPortalHtml)(bytes);
|
|
392
|
+
if (endpoint === 'mipeDisplayPreView.cgi' && /Redireccionando/i.test(page) && /\balert\s*\(/.test(page) && /(?:window\.)?history\.go\(\s*-1\s*\)/.test(page))
|
|
393
|
+
throw this.#failure('SII_DOCUMENT_VALIDATION_REJECTED', endpoint, 'PROVIDER_REJECTED', response);
|
|
394
|
+
const loginForm = htmlElements((0, parse5_1.parse)(page)).some(element => element.tagName === 'form' && /(?:^|\/)CAutInicio\.cgi(?:[?#]|$)/i.test(element.attrs.find(a => a.name === 'action')?.value ?? '') && htmlElements(element).some(control => control.tagName === 'input' && control.attrs.some(a => a.name === 'name' && a.value.toLowerCase() === 'clave')));
|
|
395
|
+
if (loginForm)
|
|
396
|
+
throw this.#failure('SESSION_REQUIRED', endpoint, 'SESSION_REQUIRED', response);
|
|
397
|
+
if (/Error\s+al\s+Contribuyente/i.test(page))
|
|
398
|
+
throw this.#failure('SII_SERVICE_ERROR', endpoint, 'PROVIDER_ERROR_PAGE', response, { ...(page.match(/\b\d{2}\.\d{2}\.\d{3}\.\d{3}\.\d{3}\.\d{2}\b/)?.[0] ? { siiMessageCode: page.match(/\b\d{2}\.\d{2}\.\d{3}\.\d{3}\.\d{3}\.\d{2}\b/)[0] } : {}) });
|
|
399
|
+
return page;
|
|
400
|
+
}
|
|
401
|
+
#form(page, name, endpoint, alternative) {
|
|
402
|
+
try {
|
|
403
|
+
return (0, facturador_1.readForm)(page, name, endpoint);
|
|
404
|
+
}
|
|
405
|
+
catch {
|
|
406
|
+
if (alternative) {
|
|
407
|
+
try {
|
|
408
|
+
return (0, facturador_1.readForm)(page, name, alternative);
|
|
409
|
+
}
|
|
410
|
+
catch { /* Only known form actions are allowed. */ }
|
|
411
|
+
}
|
|
412
|
+
const source = name === 'VIEW_EFXP' ? 'mipeGenFacEx.cgi' : name === 'PreViewDTE' ? 'mipeDisplayPreView.cgi' : 'mipeGenXMLFirma.cgi';
|
|
413
|
+
throw this.#failure('SII_PROTOCOL_CHANGED', source, 'INVALID_RESPONSE');
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
#assertOption(page, variable, value, commune, column = 0) {
|
|
417
|
+
try {
|
|
418
|
+
const rows = (0, facturador_1.readLiteralRows)(page, variable).filter(row => row[column]?.trim() === value && (commune === undefined || row[1]?.trim() === commune));
|
|
419
|
+
if (rows.length === 1 && rows[0])
|
|
420
|
+
return rows[0];
|
|
421
|
+
}
|
|
422
|
+
catch { /* No provider scripts execute. */ }
|
|
423
|
+
throw this.#failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeGenFacEx.cgi', 'DOCUMENT_CONTENT_MISMATCH');
|
|
424
|
+
}
|
|
425
|
+
#assertFields(fields, expected) {
|
|
426
|
+
for (const [key, value] of Object.entries(expected))
|
|
427
|
+
if (fields.get(key)?.trim() !== value)
|
|
428
|
+
throw this.#failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeDisplayPreView.cgi', 'DOCUMENT_CONTENT_MISMATCH');
|
|
429
|
+
}
|
|
430
|
+
#assertNewInvoice(fields) {
|
|
431
|
+
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')
|
|
432
|
+
throw this.#failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeGenFacEx.cgi', 'DOCUMENT_CONTENT_MISMATCH');
|
|
433
|
+
}
|
|
434
|
+
#assertDocument(document, approved) {
|
|
435
|
+
const d = document.detail;
|
|
436
|
+
const decimal = (value) => value == null ? null : value.replace(/^0+(?=\d)/, '').replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '');
|
|
437
|
+
if (d.issuedDate !== approved.issuedDate || d.netAmount !== approved.netAmount || d.vatAmount !== approved.vatAmount || d.totalAmount !== approved.totalAmount || Number(d.vatRate) !== 19 || d.taxes.length || d.adjustments.length || d.exemptAmount || d.fiscalHeader?.noDebitReduction != null || d.fiscalHeader?.unapprovedFiscalFields.length)
|
|
438
|
+
throw this.#failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeGenXMLFirma.cgi', 'DOCUMENT_CONTENT_MISMATCH');
|
|
439
|
+
if (approved.invoice) {
|
|
440
|
+
const items = approved.invoice.items;
|
|
441
|
+
const header = d.fiscalHeader;
|
|
442
|
+
const i = approved.invoice;
|
|
443
|
+
const branch = (value) => (value ?? '').replace(/^0+(?=\d)/, '');
|
|
444
|
+
if (branch(header?.issuer.branchCode) !== branch(approved.issuerBranchCode))
|
|
445
|
+
throw this.#failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeGenXMLFirma.cgi', 'DOCUMENT_CONTENT_MISMATCH');
|
|
446
|
+
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)
|
|
447
|
+
throw this.#failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeGenXMLFirma.cgi', 'DOCUMENT_CONTENT_MISMATCH');
|
|
448
|
+
if (d.hasTransport || d.lines.length !== items.length || d.references.length || d.lines.some((line, i) => line.codes.length || line.name !== items[i]?.name || (line.description ?? '') !== (items[i]?.description ?? '') || decimal(line.quantity) !== decimal(items[i]?.quantity ?? null) || decimal(line.unitPrice) !== decimal(items[i]?.unitNetPriceClp ?? null) || (line.unit ?? '') !== (items[i]?.unit ?? '') || line.amount !== (0, invoicing_1.calculateInvoiceTotals)([items[i]]).netAmount || line.discountAmount || line.surchargeAmount || line.discountPercent && Number(line.discountPercent) || line.surchargePercent && Number(line.surchargePercent) || line.exemptIndicator))
|
|
449
|
+
throw this.#failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeGenXMLFirma.cgi', 'DOCUMENT_CONTENT_MISMATCH');
|
|
450
|
+
}
|
|
451
|
+
else {
|
|
452
|
+
const ref = d.references[0];
|
|
453
|
+
if (!approved.reference || d.references.length !== 1 || ref?.documentType !== '33' || ref.folio !== approved.reference.folio || ref.date !== approved.reference.issuedDate || ref.code !== 1)
|
|
454
|
+
throw this.#failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeGenXMLFirma.cgi', 'DOCUMENT_CONTENT_MISMATCH');
|
|
455
|
+
const original = approved.originalInvoice;
|
|
456
|
+
const header = d.fiscalHeader;
|
|
457
|
+
const originalHeader = original?.fiscalHeader;
|
|
458
|
+
const lines = (values) => values.map(line => ({ ...line, quantity: decimal(line.quantity), unitPrice: decimal(line.unitPrice), discountPercent: decimal(line.discountPercent), surchargePercent: decimal(line.surchargePercent) }));
|
|
459
|
+
if (!original || !header || !originalHeader || (0, invoicing_1.hashContent)(lines(d.lines)) !== (0, invoicing_1.hashContent)(lines(original.lines)) || (0, invoicing_1.hashContent)(header.issuer) !== (0, invoicing_1.hashContent)(originalHeader.issuer) || (0, invoicing_1.hashContent)(header.receiver) !== (0, invoicing_1.hashContent)(originalHeader.receiver) || ['paymentForm', 'saleType', 'purchaseType'].some(field => header[field] !== null && header[field] !== originalHeader[field]))
|
|
460
|
+
throw this.#failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeGenXMLFirma.cgi', 'DOCUMENT_CONTENT_MISMATCH');
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
async #getInvoices(operacion, { periodo, tokenRecaptcha = 't-o-k-e-n-web' }, normalize) {
|
|
196
464
|
this.#assertReady();
|
|
197
465
|
assertPeriod(periodo);
|
|
198
466
|
if (typeof tokenRecaptcha !== 'string' || !tokenRecaptcha.trim())
|
|
@@ -200,7 +468,7 @@ class SiiClient {
|
|
|
200
468
|
const initial = await this.#call('getDatosInicio', {});
|
|
201
469
|
if (typeof initial.limiteDtes !== 'number' || !Number.isSafeInteger(initial.limiteDtes) || initial.limiteDtes < 1)
|
|
202
470
|
throw this.#failure('SII_INVALID_RESPONSE', 'getDatosInicio', 'INVALID_RESPONSE');
|
|
203
|
-
const summary = await this.
|
|
471
|
+
const summary = await this.getSummary({ periodo, operacion });
|
|
204
472
|
const expected = new Map();
|
|
205
473
|
let expectedCount = 0;
|
|
206
474
|
for (const row of summary.data) {
|
|
@@ -252,28 +520,95 @@ class SiiClient {
|
|
|
252
520
|
return { data: [...invoices.values()], complete: incompleteDocumentTypes.length === 0, expectedCount, observedAt: new Date().toISOString(), incompleteDocumentTypes };
|
|
253
521
|
}
|
|
254
522
|
/** Original DTE from the free SII facturador; RCV membership alone does not guarantee XML availability. */
|
|
255
|
-
|
|
256
|
-
|
|
523
|
+
getIssuedInvoiceXml(input) {
|
|
524
|
+
if (![33, 34].includes(input.documentType))
|
|
525
|
+
return Promise.reject(new TypeError('Identidad de factura inválida'));
|
|
526
|
+
return this.#getInvoiceXml(input);
|
|
527
|
+
}
|
|
528
|
+
getReceivedInvoiceXml(input) {
|
|
529
|
+
if (![33, 34].includes(input.documentType))
|
|
530
|
+
return Promise.reject(new TypeError('Identidad de factura inválida'));
|
|
531
|
+
return this.#getInvoiceXml(input, (0, rut_1.parseRut)(input.issuerRut));
|
|
257
532
|
}
|
|
258
|
-
|
|
259
|
-
return this.#
|
|
533
|
+
getIssuedDocumentXml(input) {
|
|
534
|
+
return this.#getDocumentXml(input);
|
|
260
535
|
}
|
|
261
|
-
|
|
536
|
+
/** @deprecated Use getAuthorizedCompanies. */
|
|
537
|
+
getEmpresasAutorizadas() { return this.getAuthorizedCompanies(); }
|
|
538
|
+
/** @deprecated Use getSummary. */
|
|
539
|
+
getResumen(input) { return this.getSummary(input); }
|
|
540
|
+
/** @deprecated Use getIssuedInvoices. */
|
|
541
|
+
getFacturasEmitidas(input) { return this.getIssuedInvoices(input); }
|
|
542
|
+
/** @deprecated Use getReceivedInvoices. */
|
|
543
|
+
getFacturasRecibidas(input) { return this.getReceivedInvoices(input); }
|
|
544
|
+
/** @deprecated Use getIssuedInvoiceXml. */
|
|
545
|
+
getXmlFacturaEmitida(input) { return this.getIssuedInvoiceXml(input); }
|
|
546
|
+
/** @deprecated Use getReceivedInvoiceXml. */
|
|
547
|
+
getXmlFacturaRecibida(input) { return this.getReceivedInvoiceXml(input); }
|
|
548
|
+
/** @deprecated Use getIssuedDocumentXml. */
|
|
549
|
+
getXmlDocumentoEmitido(input) { return this.getIssuedDocumentXml(input); }
|
|
550
|
+
/** @deprecated Use prepareInvoice. */
|
|
551
|
+
prepararFactura(input) { return this.prepareInvoice(input); }
|
|
552
|
+
/** @deprecated Use prepareCancellationCreditNote. */
|
|
553
|
+
prepararNotaCreditoAnulacion(input) { return this.prepareCancellationCreditNote(input); }
|
|
554
|
+
/** @deprecated Use signAndSend. */
|
|
555
|
+
firmarYEnviar(input) { return this.signAndSend(input); }
|
|
556
|
+
#getInvoiceXml(input, supplier) {
|
|
557
|
+
return this.#getDocumentXml(input, supplier, true);
|
|
558
|
+
}
|
|
559
|
+
async #getDocumentXml({ documentType, folio }, supplier, legacy = false) {
|
|
262
560
|
this.#assertReady();
|
|
263
|
-
if (![33, 34].includes(documentType) || typeof folio !== 'string' || !/^[1-9]\d{0,19}$/.test(folio))
|
|
264
|
-
throw new TypeError('Identidad de
|
|
265
|
-
|
|
266
|
-
|
|
561
|
+
if (![33, 34, 61].includes(documentType) || typeof folio !== 'string' || !/^[1-9]\d{0,19}$/.test(folio))
|
|
562
|
+
throw new TypeError('Identidad de documento inválida');
|
|
563
|
+
await this.#ensureInvoicingPortal();
|
|
564
|
+
// A filtered backup is a read: no emission, cancellation or representation endpoint is called.
|
|
565
|
+
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' });
|
|
566
|
+
const response = await this.#request(`${FACTURADOR}mipeDownLoad.cgi?${query}`, {}, true);
|
|
567
|
+
const bytes = await this.#readBounded(response, 'mipeDownLoad.cgi');
|
|
568
|
+
const format = responseFormat(response, bytes);
|
|
569
|
+
if (format.responseType === 'EMPTY')
|
|
570
|
+
throw this.#failure('SII_SERVICE_ERROR', 'mipeDownLoad.cgi', 'EMPTY_RESPONSE', response, format);
|
|
571
|
+
if (format.responseType === 'PDF' || format.responseType === 'ZIP')
|
|
572
|
+
throw this.#failure('SII_SERVICE_ERROR', 'mipeDownLoad.cgi', format.responseType === 'PDF' ? 'UNEXPECTED_PDF' : 'UNEXPECTED_ARCHIVE', response, format);
|
|
573
|
+
if (format.responseType !== 'XML' && !(format.responseType === 'UNKNOWN' && format.contentType === 'application/octet-stream')) {
|
|
574
|
+
const page = Buffer.from(bytes).toString('latin1');
|
|
575
|
+
const siiMessageCode = page.match(/\b\d{2}\.\d{2}\.\d{3}\.\d{3}\.\d{3}\.\d{2}\b/)?.[0];
|
|
576
|
+
const evidence = { ...format, ...(siiMessageCode ? { siiMessageCode } : {}) };
|
|
577
|
+
if (/recaptcha-response|g-recaptcha|captcha/i.test(page))
|
|
578
|
+
throw this.#failure('CAPTCHA_INTERACTION_REQUIRED', 'mipeDownLoad.cgi', 'CAPTCHA_REQUIRED', response, evidence);
|
|
579
|
+
const reason = /demasiados\s+documentos/i.test(page) ? 'DOCUMENT_LIMIT_EXCEEDED'
|
|
580
|
+
: /no\s+se\s+encontraron\s+documentos/i.test(page) ? 'DOCUMENT_NOT_FOUND'
|
|
581
|
+
: /error\s+al\s+contribuyente/i.test(page) ? 'PROVIDER_ERROR_PAGE'
|
|
582
|
+
: format.responseType === 'HTML' ? 'HTML_RESPONSE' : 'UNEXPECTED_FORMAT';
|
|
583
|
+
throw this.#failure(reason === 'DOCUMENT_NOT_FOUND' ? 'SII_XML_UNAVAILABLE' : 'SII_SERVICE_ERROR', 'mipeDownLoad.cgi', reason, response, evidence);
|
|
584
|
+
}
|
|
585
|
+
try {
|
|
586
|
+
const identity = { issuerRut: supplier?.formatted ?? this.#company.formatted, ...(supplier ? { receiverRut: this.#company.formatted } : {}), folio };
|
|
587
|
+
if (legacy) {
|
|
588
|
+
if (documentType !== 33 && documentType !== 34)
|
|
589
|
+
throw new invoice_xml_1.DteXmlError('SII_XML_INVALID');
|
|
590
|
+
return (0, invoice_xml_1.parseDteXml)(bytes, { ...identity, documentType });
|
|
591
|
+
}
|
|
592
|
+
return (0, invoice_xml_2.parseDteDocumentXml)(bytes, { ...identity, documentType });
|
|
593
|
+
}
|
|
594
|
+
catch (error) {
|
|
595
|
+
const code = error instanceof invoice_xml_1.DteXmlError ? error.code : 'SII_XML_INVALID';
|
|
596
|
+
throw this.#failure(code, 'mipeDownLoad.cgi', code === 'SII_XML_IDENTITY_MISMATCH' ? 'XML_IDENTITY_MISMATCH' : 'INVALID_XML', response, { ...format, stage: 'XML_PARSE' });
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
async #ensureInvoicingPortal(destination = FACTURADOR_DESTINATION) {
|
|
600
|
+
if (!this.#facturadorReady || destination !== FACTURADOR_DESTINATION) {
|
|
601
|
+
let url = `${FACTURADOR}mipeSelEmpresa.cgi?DESDE_DONDE_URL=${encodeURIComponent(destination)}`;
|
|
267
602
|
let options = {}, submitted = false;
|
|
268
603
|
for (let hop = 0;; hop++) {
|
|
269
|
-
const response = await this.#request(url, options, options.method !== 'POST', true);
|
|
604
|
+
const response = await this.#request(url, options, destination === FACTURADOR_DESTINATION && options.method !== 'POST', true);
|
|
270
605
|
const location = response.headers.get('location');
|
|
271
606
|
if (response.status >= 300 && response.status < 400) {
|
|
272
607
|
await response.body?.cancel();
|
|
273
608
|
if (!location || hop >= 4)
|
|
274
609
|
throw this.#failure('SII_XML_COMPANY_SELECTION_REQUIRED', endpointFor(url), 'COMPANY_SELECTION_REQUIRED', response);
|
|
275
610
|
const next = new URL(location, url);
|
|
276
|
-
if (next.origin !== 'https://www1.sii.cl' || !['mipeSelEmpresa.cgi', 'mipeLaunchPage.cgi'].some(path => next.pathname === `/cgi-bin/Portal001/${path}`))
|
|
611
|
+
if (next.origin !== 'https://www1.sii.cl' || !['mipeSelEmpresa.cgi', 'mipeLaunchPage.cgi', 'mipeGenFacEx.cgi', 'mipeAdminDocsEmi.cgi'].some(path => next.pathname === `/cgi-bin/Portal001/${path}`))
|
|
277
612
|
throw this.#failure('SESSION_OR_INTERACTIVE_AUTH_REQUIRED', endpointFor(url), 'SESSION_REQUIRED', response);
|
|
278
613
|
url = next.href;
|
|
279
614
|
options = {};
|
|
@@ -282,7 +617,7 @@ class SiiClient {
|
|
|
282
617
|
const page = response.body ? Buffer.from(await this.#readBounded(response, endpointFor(url))).toString('latin1') : '';
|
|
283
618
|
if (/recaptcha-response|g-recaptcha|captcha/i.test(page))
|
|
284
619
|
throw this.#failure('CAPTCHA_INTERACTION_REQUIRED', endpointFor(url), 'CAPTCHA_REQUIRED', response);
|
|
285
|
-
const selection = companySelection(page, this.#company.formatted);
|
|
620
|
+
const selection = companySelection(page, this.#company.formatted, destination);
|
|
286
621
|
if (typeof selection === 'string')
|
|
287
622
|
throw this.#failure('SII_XML_COMPANY_SELECTION_REQUIRED', endpointFor(url), selection, response);
|
|
288
623
|
if (selection) {
|
|
@@ -300,34 +635,6 @@ class SiiClient {
|
|
|
300
635
|
throw this.#failure('SII_XML_COMPANY_SELECTION_REQUIRED', 'mipeSelEmpresa.cgi', 'COMPANY_SELECTION_REQUIRED');
|
|
301
636
|
this.#facturadorReady = true;
|
|
302
637
|
}
|
|
303
|
-
// A filtered backup is a read: no emission, cancellation or representation endpoint is called.
|
|
304
|
-
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' });
|
|
305
|
-
const response = await this.#request(`${FACTURADOR}mipeDownLoad.cgi?${query}`, {}, true);
|
|
306
|
-
const bytes = await this.#readBounded(response, 'mipeDownLoad.cgi');
|
|
307
|
-
const format = responseFormat(response, bytes);
|
|
308
|
-
if (format.responseType === 'EMPTY')
|
|
309
|
-
throw this.#failure('SII_SERVICE_ERROR', 'mipeDownLoad.cgi', 'EMPTY_RESPONSE', response, format);
|
|
310
|
-
if (format.responseType === 'PDF' || format.responseType === 'ZIP')
|
|
311
|
-
throw this.#failure('SII_SERVICE_ERROR', 'mipeDownLoad.cgi', format.responseType === 'PDF' ? 'UNEXPECTED_PDF' : 'UNEXPECTED_ARCHIVE', response, format);
|
|
312
|
-
if (format.responseType !== 'XML' && !(format.responseType === 'UNKNOWN' && format.contentType === 'application/octet-stream')) {
|
|
313
|
-
const page = Buffer.from(bytes).toString('latin1');
|
|
314
|
-
const siiMessageCode = page.match(/\b\d{2}\.\d{2}\.\d{3}\.\d{3}\.\d{3}\.\d{2}\b/)?.[0];
|
|
315
|
-
const evidence = { ...format, ...(siiMessageCode ? { siiMessageCode } : {}) };
|
|
316
|
-
if (/recaptcha-response|g-recaptcha|captcha/i.test(page))
|
|
317
|
-
throw this.#failure('CAPTCHA_INTERACTION_REQUIRED', 'mipeDownLoad.cgi', 'CAPTCHA_REQUIRED', response, evidence);
|
|
318
|
-
const reason = /demasiados\s+documentos/i.test(page) ? 'DOCUMENT_LIMIT_EXCEEDED'
|
|
319
|
-
: /no\s+se\s+encontraron\s+documentos/i.test(page) ? 'DOCUMENT_NOT_FOUND'
|
|
320
|
-
: /error\s+al\s+contribuyente/i.test(page) ? 'PROVIDER_ERROR_PAGE'
|
|
321
|
-
: format.responseType === 'HTML' ? 'HTML_RESPONSE' : 'UNEXPECTED_FORMAT';
|
|
322
|
-
throw this.#failure(reason === 'DOCUMENT_NOT_FOUND' ? 'SII_XML_UNAVAILABLE' : 'SII_SERVICE_ERROR', 'mipeDownLoad.cgi', reason, response, evidence);
|
|
323
|
-
}
|
|
324
|
-
try {
|
|
325
|
-
return (0, invoice_xml_1.parseDteXml)(bytes, { issuerRut: supplier?.formatted ?? this.#company.formatted, ...(supplier ? { receiverRut: this.#company.formatted } : {}), documentType, folio });
|
|
326
|
-
}
|
|
327
|
-
catch (error) {
|
|
328
|
-
const code = error instanceof invoice_xml_1.DteXmlError ? error.code : 'SII_XML_INVALID';
|
|
329
|
-
throw this.#failure(code, 'mipeDownLoad.cgi', code === 'SII_XML_IDENTITY_MISMATCH' ? 'XML_IDENTITY_MISMATCH' : 'INVALID_XML', response, { ...format, stage: 'XML_PARSE' });
|
|
330
|
-
}
|
|
331
638
|
}
|
|
332
639
|
/** Cierra esta sesión remota antes de descartar cookies; siempre esperar en finally. */
|
|
333
640
|
dispose() {
|
|
@@ -337,10 +644,11 @@ class SiiClient {
|
|
|
337
644
|
this.#ready = false;
|
|
338
645
|
this.#identity = undefined;
|
|
339
646
|
this.#facturadorReady = false;
|
|
647
|
+
this.#prepared = undefined;
|
|
340
648
|
this.#disposal = (async () => {
|
|
341
649
|
try {
|
|
342
650
|
// An in-flight login can still issue session cookies after local closure.
|
|
343
|
-
await Promise.allSettled(this.#requests);
|
|
651
|
+
await Promise.allSettled([...this.#requests, ...(this.#write ? [this.#write] : [])]);
|
|
344
652
|
const cookies = await this.#jar.getCookies(LOGOUT);
|
|
345
653
|
if (!cookies.some(c => c.value && ['TOKEN', 'NETSCAPE_LIVEWIRE.mac'].includes(c.key)))
|
|
346
654
|
return;
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@devly-cl/sii-client",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Cliente HTTP del SII para acceso personal,
|
|
3
|
+
"version": "0.5.0",
|
|
4
|
+
"description": "Cliente HTTP del SII para acceso personal, RCV, XML y emisión de facturas y notas de crédito, independiente de framework.",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"type": "commonjs",
|
|
7
7
|
"engines": {
|
|
@@ -27,8 +27,8 @@
|
|
|
27
27
|
"scripts": {
|
|
28
28
|
"build": "tsc -p tsconfig.json",
|
|
29
29
|
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
30
|
-
"test": "npm run build && node test/check.mjs && node test/invoices.mjs && node test/xml.mjs && node test/logout.mjs",
|
|
31
|
-
"check:example": "tsc --strict --noEmit --target ES2022 --module Node16 --moduleResolution Node16 --types node examples/consulta-rcv.ts",
|
|
30
|
+
"test": "npm run build && node test/check.mjs && node test/invoices.mjs && node test/xml.mjs && node test/logout.mjs && node test/credit-note-xml.mjs && node test/facturador.mjs && node test/invoicing.mjs && node test/issuance.mjs && node test/issuance-edges.mjs && node test/api-naming.mjs",
|
|
31
|
+
"check:example": "tsc --strict --noEmit --target ES2022 --module Node16 --moduleResolution Node16 --types node examples/consulta-rcv.ts examples/facturacion.ts",
|
|
32
32
|
"check": "npm run typecheck && npm test && npm run check:example",
|
|
33
33
|
"test:live": "npm run build && node scripts/live-check.mjs",
|
|
34
34
|
"prepack": "npm run check"
|