@devly-cl/sii-client 0.4.3 → 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 +86 -26
- 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 +411 -39
- package/package.json +5 -4
|
@@ -4,6 +4,7 @@ exports.SiiClient = exports.SiiError = void 0;
|
|
|
4
4
|
const node_crypto_1 = require("node:crypto");
|
|
5
5
|
const promises_1 = require("node:timers/promises");
|
|
6
6
|
const tough_cookie_1 = require("tough-cookie");
|
|
7
|
+
const parse5_1 = require("parse5");
|
|
7
8
|
const rut_1 = require("../domain/rut");
|
|
8
9
|
const sii_error_1 = require("../domain/sii-error");
|
|
9
10
|
var sii_error_2 = require("../domain/sii-error");
|
|
@@ -11,6 +12,9 @@ Object.defineProperty(exports, "SiiError", { enumerable: true, get: function ()
|
|
|
11
12
|
const issued_invoice_1 = require("../domain/issued-invoice");
|
|
12
13
|
const received_invoice_1 = require("../domain/received-invoice");
|
|
13
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");
|
|
14
18
|
const AUTH = 'https://zeusr.sii.cl/cgi_AUT2000/CAutInicio.cgi';
|
|
15
19
|
const LOGOUT = 'https://zeusr.sii.cl/cgi_AUT2000/autTermino.cgi';
|
|
16
20
|
const RCV = 'https://www4.sii.cl/consdcvinternetui/';
|
|
@@ -19,10 +23,12 @@ const NAMESPACE = 'cl.sii.sdi.lob.diii.consdcv.data.api.interfaces.FacadeService
|
|
|
19
23
|
const RETRYABLE = new Set([429, 502, 503, 504]);
|
|
20
24
|
const STATES = new Set(['REGISTRO', 'PENDIENTE', 'NO_INCLUIR', 'RECLAMADO']);
|
|
21
25
|
const FACTURADOR = 'https://www1.sii.cl/cgi-bin/Portal001/';
|
|
26
|
+
const FACTURADOR_DESTINATION = 'OPCION=2&TIPO=4';
|
|
22
27
|
const ENDPOINT_STAGES = {
|
|
23
28
|
'CAutInicio.cgi': 'AUTHENTICATION', 'aaSessionService/load': 'SESSION_CHECK', getDcvEmpresasAutorizadas: 'COMPANY_AUTHORIZATION',
|
|
24
29
|
getDatosInicio: 'RCV_INITIALIZATION', getResumen: 'RCV_SUMMARY', getDetalleCompra: 'RCV_DETAIL', getDetalleVenta: 'RCV_DETAIL',
|
|
25
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',
|
|
26
32
|
};
|
|
27
33
|
function endpointFor(url) {
|
|
28
34
|
const path = new URL(url).pathname;
|
|
@@ -53,6 +59,52 @@ function assertPeriod(periodo) {
|
|
|
53
59
|
if (typeof periodo !== 'string' || !/^\d{4}(0[1-9]|1[0-2])$/.test(periodo) || Number(periodo.slice(0, 4)) < 2017)
|
|
54
60
|
throw new TypeError('Periodo inválido: YYYYMM');
|
|
55
61
|
}
|
|
62
|
+
function htmlElements(root) {
|
|
63
|
+
const pending = [root];
|
|
64
|
+
const elements = [];
|
|
65
|
+
for (let node = pending.pop(); node; node = pending.pop()) {
|
|
66
|
+
if ('tagName' in node && node.namespaceURI === 'http://www.w3.org/1999/xhtml')
|
|
67
|
+
elements.push(node);
|
|
68
|
+
if ('childNodes' in node)
|
|
69
|
+
for (const child of node.childNodes)
|
|
70
|
+
pending.push(child);
|
|
71
|
+
}
|
|
72
|
+
return elements;
|
|
73
|
+
}
|
|
74
|
+
/** Read the observed selector inertly; never execute scripts or forward arbitrary form fields. */
|
|
75
|
+
function companySelection(page, company, expectedDestination = FACTURADOR_DESTINATION) {
|
|
76
|
+
const attr = (element, name) => element.attrs.find(a => a.name === name)?.value;
|
|
77
|
+
const forms = htmlElements((0, parse5_1.parse)(page)).filter(e => e.tagName === 'form' && attr(e, 'name') === 'fPrmEmpPOP');
|
|
78
|
+
const form = forms[0];
|
|
79
|
+
if (!form)
|
|
80
|
+
return undefined;
|
|
81
|
+
if (forms.length !== 1 || attr(form, 'method')?.toLowerCase() !== 'post')
|
|
82
|
+
return 'INVALID_RESPONSE';
|
|
83
|
+
try {
|
|
84
|
+
if (new URL(attr(form, 'action') ?? '', FACTURADOR).href !== `${FACTURADOR}mipeSelEmpresa.cgi`)
|
|
85
|
+
return 'INVALID_RESPONSE';
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
return 'INVALID_RESPONSE';
|
|
89
|
+
}
|
|
90
|
+
const controls = htmlElements(form);
|
|
91
|
+
const selects = controls.filter(e => e.tagName === 'select' && attr(e, 'name') === 'RUT_EMP');
|
|
92
|
+
const destinations = controls.filter(e => e.tagName === 'input' && attr(e, 'name') === 'DESDE_DONDE_URL');
|
|
93
|
+
const select = selects[0], destination = destinations[0];
|
|
94
|
+
if (selects.length !== 1 || destinations.length !== 1 || !select || !destination
|
|
95
|
+
|| attr(select, 'disabled') !== undefined || attr(select, 'multiple') !== undefined || attr(select, 'form') !== undefined
|
|
96
|
+
|| attr(destination, 'type')?.toLowerCase() !== 'hidden' || attr(destination, 'disabled') !== undefined || attr(destination, 'form') !== undefined
|
|
97
|
+
|| attr(destination, 'value') !== expectedDestination)
|
|
98
|
+
return 'INVALID_RESPONSE';
|
|
99
|
+
const options = htmlElements(select).filter(e => e.tagName === 'option' && attr(e, 'value')?.replace(/\./g, '').toUpperCase() === company);
|
|
100
|
+
if (options.length > 1)
|
|
101
|
+
return 'INVALID_RESPONSE';
|
|
102
|
+
const option = options[0];
|
|
103
|
+
if (!option || attr(option, 'disabled') !== undefined
|
|
104
|
+
|| (option.parentNode && 'tagName' in option.parentNode && option.parentNode.tagName === 'optgroup' && attr(option.parentNode, 'disabled') !== undefined))
|
|
105
|
+
return 'COMPANY_NOT_AUTHORIZED';
|
|
106
|
+
return new URLSearchParams({ DESDE_DONDE_URL: expectedDestination, RUT_EMP: company });
|
|
107
|
+
}
|
|
56
108
|
/** Una instancia = una empresa y una sesión personal. Nunca comparte cookies. */
|
|
57
109
|
class SiiClient {
|
|
58
110
|
#jar = new tough_cookie_1.CookieJar();
|
|
@@ -68,6 +120,8 @@ class SiiClient {
|
|
|
68
120
|
#requests = new Set();
|
|
69
121
|
#disposal;
|
|
70
122
|
#traceId = (0, node_crypto_1.randomUUID)();
|
|
123
|
+
#write;
|
|
124
|
+
#prepared;
|
|
71
125
|
#failure(code, endpoint, reason, response, extra = {}) {
|
|
72
126
|
return new sii_error_1.SiiError(code, response?.status, { traceId: this.#traceId, stage: ENDPOINT_STAGES[endpoint], endpoint, reason,
|
|
73
127
|
...(response ? { httpStatus: response.status, ...responseFormat(response) } : {}), ...extra });
|
|
@@ -124,11 +178,11 @@ class SiiClient {
|
|
|
124
178
|
throw error;
|
|
125
179
|
}
|
|
126
180
|
}
|
|
127
|
-
async
|
|
181
|
+
async getAuthorizedCompanies() {
|
|
128
182
|
const identity = this.#assertReady();
|
|
129
183
|
return this.#call('getDcvEmpresasAutorizadas', { rutAutenticado: identity.rut, dvAutenticado: identity.dv });
|
|
130
184
|
}
|
|
131
|
-
async
|
|
185
|
+
async getSummary({ periodo, operacion, estado = 'REGISTRO' }) {
|
|
132
186
|
this.#assertReady();
|
|
133
187
|
assertPeriod(periodo);
|
|
134
188
|
if (!['COMPRA', 'VENTA'].includes(operacion))
|
|
@@ -137,14 +191,276 @@ class SiiClient {
|
|
|
137
191
|
throw new TypeError('Estado inválido');
|
|
138
192
|
return this.#call('getResumen', { rutEmisor: this.#company.rut, dvEmisor: this.#company.dv, ptributario: periodo, estadoContab: estado, operacion });
|
|
139
193
|
}
|
|
140
|
-
|
|
141
|
-
return this.#
|
|
194
|
+
getIssuedInvoices(input) {
|
|
195
|
+
return this.#getInvoices('VENTA', input, issued_invoice_1.normalizeIssuedInvoice);
|
|
142
196
|
}
|
|
143
197
|
/** Facturas 33/34 in the official purchase register. Does not accept, claim or move documents. */
|
|
144
|
-
|
|
145
|
-
return this.#
|
|
198
|
+
getReceivedInvoices(input) {
|
|
199
|
+
return this.#getInvoices('COMPRA', input, received_invoice_1.normalizeReceivedInvoice);
|
|
200
|
+
}
|
|
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');
|
|
146
433
|
}
|
|
147
|
-
|
|
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) {
|
|
148
464
|
this.#assertReady();
|
|
149
465
|
assertPeriod(periodo);
|
|
150
466
|
if (typeof tokenRecaptcha !== 'string' || !tokenRecaptcha.trim())
|
|
@@ -152,7 +468,7 @@ class SiiClient {
|
|
|
152
468
|
const initial = await this.#call('getDatosInicio', {});
|
|
153
469
|
if (typeof initial.limiteDtes !== 'number' || !Number.isSafeInteger(initial.limiteDtes) || initial.limiteDtes < 1)
|
|
154
470
|
throw this.#failure('SII_INVALID_RESPONSE', 'getDatosInicio', 'INVALID_RESPONSE');
|
|
155
|
-
const summary = await this.
|
|
471
|
+
const summary = await this.getSummary({ periodo, operacion });
|
|
156
472
|
const expected = new Map();
|
|
157
473
|
let expectedCount = 0;
|
|
158
474
|
for (const row of summary.data) {
|
|
@@ -204,38 +520,47 @@ class SiiClient {
|
|
|
204
520
|
return { data: [...invoices.values()], complete: incompleteDocumentTypes.length === 0, expectedCount, observedAt: new Date().toISOString(), incompleteDocumentTypes };
|
|
205
521
|
}
|
|
206
522
|
/** Original DTE from the free SII facturador; RCV membership alone does not guarantee XML availability. */
|
|
207
|
-
|
|
208
|
-
|
|
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);
|
|
209
527
|
}
|
|
210
|
-
|
|
211
|
-
|
|
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));
|
|
212
532
|
}
|
|
213
|
-
|
|
533
|
+
getIssuedDocumentXml(input) {
|
|
534
|
+
return this.#getDocumentXml(input);
|
|
535
|
+
}
|
|
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) {
|
|
214
560
|
this.#assertReady();
|
|
215
|
-
if (![33, 34].includes(documentType) || typeof folio !== 'string' || !/^[1-9]\d{0,19}$/.test(folio))
|
|
216
|
-
throw new TypeError('Identidad de
|
|
217
|
-
|
|
218
|
-
let url = `${FACTURADOR}mipeSelEmpresa.cgi?DESDE_DONDE_URL=OPCION%3D2%26TIPO%3D4`;
|
|
219
|
-
for (let hop = 0;; hop++) {
|
|
220
|
-
const response = await this.#request(url, {}, true, true);
|
|
221
|
-
const location = response.headers.get('location');
|
|
222
|
-
await response.body?.cancel();
|
|
223
|
-
if (response.status >= 300 && response.status < 400) {
|
|
224
|
-
if (!location || hop >= 4)
|
|
225
|
-
throw this.#failure('SII_XML_COMPANY_SELECTION_REQUIRED', endpointFor(url), 'COMPANY_SELECTION_REQUIRED', response);
|
|
226
|
-
const next = new URL(location, url);
|
|
227
|
-
if (next.origin !== 'https://www1.sii.cl' || !['mipeSelEmpresa.cgi', 'mipeLaunchPage.cgi'].some(path => next.pathname === `/cgi-bin/Portal001/${path}`))
|
|
228
|
-
throw this.#failure('SESSION_OR_INTERACTIVE_AUTH_REQUIRED', endpointFor(url), 'SESSION_REQUIRED', response);
|
|
229
|
-
url = next.href;
|
|
230
|
-
continue;
|
|
231
|
-
}
|
|
232
|
-
break;
|
|
233
|
-
}
|
|
234
|
-
const cookies = await this.#jar.getCookies(FACTURADOR);
|
|
235
|
-
if (cookies.find(c => c.key === 'NETSCAPE_LIVEWIRE.rcmp')?.value !== this.#company.rut || cookies.find(c => c.key === 'NETSCAPE_LIVEWIRE.dcmp')?.value.toUpperCase() !== this.#company.dv)
|
|
236
|
-
throw this.#failure('SII_XML_COMPANY_SELECTION_REQUIRED', 'mipeSelEmpresa.cgi', 'COMPANY_SELECTION_REQUIRED');
|
|
237
|
-
this.#facturadorReady = true;
|
|
238
|
-
}
|
|
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();
|
|
239
564
|
// A filtered backup is a read: no emission, cancellation or representation endpoint is called.
|
|
240
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' });
|
|
241
566
|
const response = await this.#request(`${FACTURADOR}mipeDownLoad.cgi?${query}`, {}, true);
|
|
@@ -258,13 +583,59 @@ class SiiClient {
|
|
|
258
583
|
throw this.#failure(reason === 'DOCUMENT_NOT_FOUND' ? 'SII_XML_UNAVAILABLE' : 'SII_SERVICE_ERROR', 'mipeDownLoad.cgi', reason, response, evidence);
|
|
259
584
|
}
|
|
260
585
|
try {
|
|
261
|
-
|
|
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 });
|
|
262
593
|
}
|
|
263
594
|
catch (error) {
|
|
264
595
|
const code = error instanceof invoice_xml_1.DteXmlError ? error.code : 'SII_XML_INVALID';
|
|
265
596
|
throw this.#failure(code, 'mipeDownLoad.cgi', code === 'SII_XML_IDENTITY_MISMATCH' ? 'XML_IDENTITY_MISMATCH' : 'INVALID_XML', response, { ...format, stage: 'XML_PARSE' });
|
|
266
597
|
}
|
|
267
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)}`;
|
|
602
|
+
let options = {}, submitted = false;
|
|
603
|
+
for (let hop = 0;; hop++) {
|
|
604
|
+
const response = await this.#request(url, options, destination === FACTURADOR_DESTINATION && options.method !== 'POST', true);
|
|
605
|
+
const location = response.headers.get('location');
|
|
606
|
+
if (response.status >= 300 && response.status < 400) {
|
|
607
|
+
await response.body?.cancel();
|
|
608
|
+
if (!location || hop >= 4)
|
|
609
|
+
throw this.#failure('SII_XML_COMPANY_SELECTION_REQUIRED', endpointFor(url), 'COMPANY_SELECTION_REQUIRED', response);
|
|
610
|
+
const next = new URL(location, url);
|
|
611
|
+
if (next.origin !== 'https://www1.sii.cl' || !['mipeSelEmpresa.cgi', 'mipeLaunchPage.cgi', 'mipeGenFacEx.cgi', 'mipeAdminDocsEmi.cgi'].some(path => next.pathname === `/cgi-bin/Portal001/${path}`))
|
|
612
|
+
throw this.#failure('SESSION_OR_INTERACTIVE_AUTH_REQUIRED', endpointFor(url), 'SESSION_REQUIRED', response);
|
|
613
|
+
url = next.href;
|
|
614
|
+
options = {};
|
|
615
|
+
continue;
|
|
616
|
+
}
|
|
617
|
+
const page = response.body ? Buffer.from(await this.#readBounded(response, endpointFor(url))).toString('latin1') : '';
|
|
618
|
+
if (/recaptcha-response|g-recaptcha|captcha/i.test(page))
|
|
619
|
+
throw this.#failure('CAPTCHA_INTERACTION_REQUIRED', endpointFor(url), 'CAPTCHA_REQUIRED', response);
|
|
620
|
+
const selection = companySelection(page, this.#company.formatted, destination);
|
|
621
|
+
if (typeof selection === 'string')
|
|
622
|
+
throw this.#failure('SII_XML_COMPANY_SELECTION_REQUIRED', endpointFor(url), selection, response);
|
|
623
|
+
if (selection) {
|
|
624
|
+
if (submitted || hop >= 4)
|
|
625
|
+
throw this.#failure('SII_XML_COMPANY_SELECTION_REQUIRED', endpointFor(url), 'COMPANY_SELECTION_REQUIRED', response);
|
|
626
|
+
submitted = true;
|
|
627
|
+
url = `${FACTURADOR}mipeSelEmpresa.cgi`;
|
|
628
|
+
options = { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: selection.toString() };
|
|
629
|
+
continue;
|
|
630
|
+
}
|
|
631
|
+
break;
|
|
632
|
+
}
|
|
633
|
+
const cookies = await this.#jar.getCookies(FACTURADOR);
|
|
634
|
+
if (cookies.find(c => c.key === 'NETSCAPE_LIVEWIRE.rcmp')?.value !== this.#company.rut || cookies.find(c => c.key === 'NETSCAPE_LIVEWIRE.dcmp')?.value.toUpperCase() !== this.#company.dv)
|
|
635
|
+
throw this.#failure('SII_XML_COMPANY_SELECTION_REQUIRED', 'mipeSelEmpresa.cgi', 'COMPANY_SELECTION_REQUIRED');
|
|
636
|
+
this.#facturadorReady = true;
|
|
637
|
+
}
|
|
638
|
+
}
|
|
268
639
|
/** Cierra esta sesión remota antes de descartar cookies; siempre esperar en finally. */
|
|
269
640
|
dispose() {
|
|
270
641
|
if (this.#disposal)
|
|
@@ -273,10 +644,11 @@ class SiiClient {
|
|
|
273
644
|
this.#ready = false;
|
|
274
645
|
this.#identity = undefined;
|
|
275
646
|
this.#facturadorReady = false;
|
|
647
|
+
this.#prepared = undefined;
|
|
276
648
|
this.#disposal = (async () => {
|
|
277
649
|
try {
|
|
278
650
|
// An in-flight login can still issue session cookies after local closure.
|
|
279
|
-
await Promise.allSettled(this.#requests);
|
|
651
|
+
await Promise.allSettled([...this.#requests, ...(this.#write ? [this.#write] : [])]);
|
|
280
652
|
const cookies = await this.#jar.getCookies(LOGOUT);
|
|
281
653
|
if (!cookies.some(c => c.value && ['TOKEN', 'NETSCAPE_LIVEWIRE.mac'].includes(c.key)))
|
|
282
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,13 +27,14 @@
|
|
|
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"
|
|
35
35
|
},
|
|
36
36
|
"dependencies": {
|
|
37
|
+
"parse5": "7.3.0",
|
|
37
38
|
"saxes": "^6.0.0",
|
|
38
39
|
"tough-cookie": "6.0.2"
|
|
39
40
|
},
|