@devly-cl/sii-client 0.7.9 → 0.7.11
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 +68 -2
- package/dist/application/document-status.d.ts +5 -5
- package/dist/application/document-status.js +14 -9
- package/dist/application/dte-import-mapper.d.ts +8 -0
- package/dist/application/dte-import-mapper.js +25 -0
- package/dist/application/dte-import-model.d.ts +28 -0
- package/dist/application/dte-import-model.js +2 -0
- package/dist/application/dte-import.d.ts +37 -0
- package/dist/application/dte-import.js +352 -0
- package/dist/application/invoice-queries.d.ts +12 -6
- package/dist/application/invoice-queries.js +9 -5
- package/dist/application/issuance.d.ts +2 -2
- package/dist/application/issuance.js +26 -10
- package/dist/contracts.d.ts +32 -0
- package/dist/contracts.js +17 -0
- package/dist/domain/civil-date.d.ts +2 -0
- package/dist/domain/civil-date.js +10 -0
- package/dist/domain/document-status.d.ts +0 -4
- package/dist/domain/document-status.js +18 -11
- package/dist/domain/document.js +47 -9
- package/dist/domain/dte-arithmetic.d.ts +35 -0
- package/dist/domain/dte-arithmetic.js +78 -0
- package/dist/domain/dte-components.d.ts +9 -0
- package/dist/domain/dte-components.js +37 -0
- package/dist/domain/dte-detail.d.ts +111 -0
- package/dist/domain/dte-detail.js +2 -0
- package/dist/domain/dte-identity.d.ts +19 -0
- package/dist/domain/dte-identity.js +52 -0
- package/dist/domain/dte-money.d.ts +41 -0
- package/dist/domain/dte-money.js +81 -0
- package/dist/domain/dte-reconciliation-model.d.ts +87 -0
- package/dist/domain/dte-reconciliation-model.js +2 -0
- package/dist/domain/dte-reconciliation.d.ts +14 -4
- package/dist/domain/dte-reconciliation.js +211 -172
- package/dist/domain/dte-validation.d.ts +7 -0
- package/dist/domain/dte-validation.js +84 -0
- package/dist/domain/invoice-xml.d.ts +12 -151
- package/dist/domain/invoice-xml.js +0 -10
- package/dist/domain/invoicing.d.ts +30 -4
- package/dist/domain/invoicing.js +75 -21
- package/dist/domain/issued-invoice.d.ts +0 -6
- package/dist/domain/rcv-document.d.ts +0 -4
- package/dist/domain/received-invoice.d.ts +1 -4
- package/dist/index.d.ts +18 -10
- package/dist/index.js +18 -5
- package/dist/infrastructure/document-status-gateway.d.ts +6 -4
- package/dist/infrastructure/document-status-gateway.js +34 -13
- package/dist/infrastructure/document-status-parser.js +38 -12
- package/dist/infrastructure/dte-xml-mapper.d.ts +16 -0
- package/dist/infrastructure/dte-xml-mapper.js +381 -0
- package/dist/infrastructure/dte-xml.d.ts +40 -4
- package/dist/infrastructure/dte-xml.js +116 -238
- package/dist/infrastructure/facturador-gateway.d.ts +10 -7
- package/dist/infrastructure/facturador-gateway.js +256 -56
- package/dist/infrastructure/facturador.js +14 -7
- package/dist/infrastructure/invoice-pdf.js +10 -3
- package/dist/infrastructure/rcv-gateway.d.ts +7 -4
- package/dist/infrastructure/rcv-gateway.js +53 -12
- package/dist/infrastructure/rcv-normalization.d.ts +8 -1
- package/dist/infrastructure/rcv-normalization.js +54 -12
- package/dist/infrastructure/read-options.d.ts +3 -0
- package/dist/infrastructure/read-options.js +25 -0
- package/dist/infrastructure/sii-client.d.ts +98 -13
- package/dist/infrastructure/sii-client.js +182 -31
- package/dist/infrastructure/sii-http-session.d.ts +2 -2
- package/dist/infrastructure/sii-http-session.js +83 -19
- package/dist/sii-error.d.ts +4 -0
- package/dist/sii-error.js +38 -13
- package/package.json +2 -2
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.FacturadorGateway = void 0;
|
|
4
|
+
const contracts_1 = require("../contracts");
|
|
4
5
|
const rut_1 = require("../domain/rut");
|
|
5
6
|
const invoicing_1 = require("../domain/invoicing");
|
|
6
7
|
const document_1 = require("../domain/document");
|
|
7
|
-
const invoice_xml_1 = require("../domain/invoice-xml");
|
|
8
8
|
const sii_error_1 = require("../sii-error");
|
|
9
9
|
const dte_xml_1 = require("./dte-xml");
|
|
10
|
+
const read_options_1 = require("./read-options");
|
|
10
11
|
const sii_http_session_1 = require("./sii-http-session");
|
|
11
12
|
const facturador_1 = require("./facturador");
|
|
12
13
|
const invoice_pdf_1 = require("./invoice-pdf");
|
|
@@ -22,16 +23,31 @@ class FacturadorGateway {
|
|
|
22
23
|
this.session = session;
|
|
23
24
|
this.closeSession = closeSession;
|
|
24
25
|
}
|
|
25
|
-
assertReady() {
|
|
26
|
-
|
|
27
|
-
|
|
26
|
+
assertReady() {
|
|
27
|
+
this.session.assertReady();
|
|
28
|
+
}
|
|
29
|
+
close() {
|
|
30
|
+
return this.closeSession();
|
|
31
|
+
}
|
|
32
|
+
clearPreparation() {
|
|
33
|
+
this.#ready = false;
|
|
34
|
+
this.#preparation = undefined;
|
|
35
|
+
this.#signing = undefined;
|
|
36
|
+
}
|
|
28
37
|
async companyInfo(rut) {
|
|
29
38
|
this.session.assertReady();
|
|
30
39
|
const receiver = (0, rut_1.parseRut)(rut);
|
|
31
40
|
if (this.#preparation || this.#signing)
|
|
32
41
|
throw new sii_error_1.SiiError('SII_OPERATION_IN_PROGRESS');
|
|
33
42
|
await this.#ensurePortal(DESTINATION, undefined, true);
|
|
34
|
-
const fields = new URLSearchParams({
|
|
43
|
+
const fields = new URLSearchParams({
|
|
44
|
+
PTDC_CODIGO: '33',
|
|
45
|
+
EHDR_CODIGO: '',
|
|
46
|
+
EFXP_FOLIO: '',
|
|
47
|
+
ES_BORR: 'FALSE',
|
|
48
|
+
esCRED_EC: 'FALSE',
|
|
49
|
+
esFACT_TUR: 'FALSE'
|
|
50
|
+
});
|
|
35
51
|
const lookup = await this.#lookupReceiver(fields, receiver);
|
|
36
52
|
let returnedRut;
|
|
37
53
|
try {
|
|
@@ -55,7 +71,12 @@ class FacturadorGateway {
|
|
|
55
71
|
throw this.session.failure('SII_PROTOCOL_CHANGED', 'mipeGenFacEx.cgi', 'INVALID_RESPONSE', undefined, { stage: 'COMPANY_LOOKUP' });
|
|
56
72
|
}
|
|
57
73
|
this.session.assertReady();
|
|
58
|
-
return {
|
|
74
|
+
return {
|
|
75
|
+
rut: returnedRut,
|
|
76
|
+
legalName, ...options,
|
|
77
|
+
source: 'SII_FACTURADOR',
|
|
78
|
+
observedAt: new Date().toISOString()
|
|
79
|
+
};
|
|
59
80
|
}
|
|
60
81
|
async prepareInvoice(input) {
|
|
61
82
|
this.session.assertReady();
|
|
@@ -79,25 +100,56 @@ class FacturadorGateway {
|
|
|
79
100
|
const requester = invoice.requesterRut ? (0, rut_1.parseRut)(invoice.requesterRut) : undefined;
|
|
80
101
|
const carrier = invoice.transport ? (0, rut_1.parseRut)(invoice.transport.carrierRut) : undefined, driver = invoice.transport ? (0, rut_1.parseRut)(invoice.transport.driverRut) : undefined;
|
|
81
102
|
const values = {
|
|
82
|
-
PTDC_CODIGO: '33',
|
|
83
|
-
|
|
84
|
-
|
|
103
|
+
PTDC_CODIGO: '33',
|
|
104
|
+
EFXP_FCH_EMIS: invoice.issuedDate,
|
|
105
|
+
CANT_DET: String(invoice.items.length),
|
|
106
|
+
ES_BORR: 'FALSE',
|
|
107
|
+
EFXP_DIR_ORIGEN: invoice.issuer.address,
|
|
108
|
+
EFXP_CMNA_ORIGEN: invoice.issuer.commune,
|
|
109
|
+
EFXP_CIUDAD_ORIGEN: invoice.issuer.city,
|
|
110
|
+
EFXP_CDG_SII_SUCUR: issuerAddress[3]?.trim() === '0' ? '' : issuerAddress[3]?.trim() ?? '',
|
|
111
|
+
EFXP_FONO_EMISOR: invoice.issuer.phone ?? issuerAddress[4]?.trim() ?? '',
|
|
85
112
|
EFXP_EMAIL_EMISOR: invoice.issuer.email ?? fields.get('EFXP_EMAIL_EMISOR')?.trim() ?? '',
|
|
86
|
-
EFXP_ACTECO: invoice.issuer.activityCode,
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
113
|
+
EFXP_ACTECO: invoice.issuer.activityCode,
|
|
114
|
+
EFXP_ACTECO_SELECT: invoice.issuer.activityCode,
|
|
115
|
+
EFXP_TIPOVENTA_SELECT: String(invoice.saleType),
|
|
116
|
+
EFXP_RUT_RECEP: receiver.rut,
|
|
117
|
+
EFXP_DV_RECEP: receiver.dv,
|
|
118
|
+
EFXP_RZN_SOC_RECEP: invoice.receiver.legalName,
|
|
119
|
+
EFXP_DIR_RECEP: invoice.receiver.address,
|
|
120
|
+
EFXP_CMNA_RECEP: invoice.receiver.commune,
|
|
121
|
+
EFXP_CIUDAD_RECEP: invoice.receiver.city,
|
|
122
|
+
EFXP_GIRO_RECEP: invoice.receiver.businessActivity,
|
|
123
|
+
EFXP_CONTACTO: invoice.receiver.contact ?? '',
|
|
124
|
+
EFXP_TIPOCOMPRA_SELECT: String(invoice.purchaseType),
|
|
125
|
+
EFXP_RUT_SOLICITA: requester?.rut ?? '',
|
|
126
|
+
EFXP_DV_SOLICITA: requester?.dv ?? '',
|
|
127
|
+
EFXP_FMA_PAGO: String(invoice.paymentForm),
|
|
128
|
+
EFXP_RUT_TRANSPORTE: carrier?.rut ?? '',
|
|
129
|
+
EFXP_DV_TRANSPORTE: carrier?.dv ?? '',
|
|
130
|
+
EFXP_PATENTE: invoice.transport?.licensePlate ?? '',
|
|
131
|
+
EFXP_RUT_CHOFER: driver?.rut ?? '',
|
|
132
|
+
EFXP_DV_CHOFER: driver?.dv ?? '',
|
|
133
|
+
EFXP_NOMBRE_CHOFER: invoice.transport?.driverName ?? '',
|
|
134
|
+
EFXP_SUBTOTAL: String(breakdown.subtotal),
|
|
135
|
+
EFXP_PCT_DESC: breakdown.discountPercent,
|
|
136
|
+
EFXP_MNT_DESC: String(breakdown.discountAmount),
|
|
137
|
+
MNT_NETO_TEMP: String(totals.netAmount),
|
|
138
|
+
IVA_TEMP: String(totals.vatAmount),
|
|
139
|
+
EFXP_MNT_NETO: String(totals.netAmount),
|
|
140
|
+
EFXP_TASA_IVA: '19',
|
|
141
|
+
EFXP_IVA: String(totals.vatAmount),
|
|
142
|
+
EFXP_MNT_TOTAL: String(totals.totalAmount),
|
|
143
|
+
EFXP_OTRO_IMP_TOTAL: String(breakdown.additionalTaxAmount),
|
|
95
144
|
};
|
|
96
145
|
for (const [key, value] of Object.entries(values))
|
|
97
146
|
fields.set(key, value);
|
|
98
147
|
const optionalPreview = {};
|
|
99
|
-
const optionalField = (key, value) => {
|
|
100
|
-
|
|
148
|
+
const optionalField = (key, value) => {
|
|
149
|
+
fields.set(key, value);
|
|
150
|
+
if (value)
|
|
151
|
+
optionalPreview[key] = value;
|
|
152
|
+
};
|
|
101
153
|
if (invoice.items.some(item => item.productCode))
|
|
102
154
|
fields.set('COD_SI_NO', 'SiChecked');
|
|
103
155
|
if (invoice.items.some(item => item.additionalTaxCode !== undefined))
|
|
@@ -116,7 +168,15 @@ class FacturadorGateway {
|
|
|
116
168
|
optionalPreview.EFXP_FONO_EMISOR = invoice.issuer.phone;
|
|
117
169
|
for (const [index, item] of invoice.items.entries()) {
|
|
118
170
|
const suffix = String(index + 1).padStart(2, '0');
|
|
119
|
-
for (const [field, value] of Object.entries({
|
|
171
|
+
for (const [field, value] of Object.entries({
|
|
172
|
+
NMB: item.name,
|
|
173
|
+
QTY: item.quantity,
|
|
174
|
+
PRC: item.unitNetPriceClp,
|
|
175
|
+
UNMD: item.unit ?? '',
|
|
176
|
+
DSC_ITEM: item.description ?? '',
|
|
177
|
+
PCTD: item.discountPercent ?? '',
|
|
178
|
+
SUBT: String(breakdown.lineAmounts[index].amount)
|
|
179
|
+
}))
|
|
120
180
|
fields.set(`EFXP_${field}_${suffix}`, value);
|
|
121
181
|
if (item.productCode) {
|
|
122
182
|
optionalField(`EFXP_TPO_COD_${suffix}`, item.productCode.type);
|
|
@@ -138,7 +198,14 @@ class FacturadorGateway {
|
|
|
138
198
|
fields.set('REF_SI_NO', 'SiChecked');
|
|
139
199
|
invoice.references.forEach((ref, index) => {
|
|
140
200
|
const suffix = String(index + 1).padStart(3, '0');
|
|
141
|
-
for (const [key, value] of Object.entries({
|
|
201
|
+
for (const [key, value] of Object.entries({
|
|
202
|
+
TPO_DOC_REF: ref.documentType,
|
|
203
|
+
IND_GLOBAL: ref.global ? '1' : '',
|
|
204
|
+
FOLIO_REF: ref.folio,
|
|
205
|
+
FCH_REF: ref.date,
|
|
206
|
+
CODIGO_REF: '',
|
|
207
|
+
RAZON_REF: ref.reason ?? ''
|
|
208
|
+
}))
|
|
142
209
|
optionalField(`EFXP_${key}_${suffix}`, value);
|
|
143
210
|
scheduleDate('ref', index, ref.date);
|
|
144
211
|
});
|
|
@@ -147,24 +214,56 @@ class FacturadorGateway {
|
|
|
147
214
|
fields.set('PAGO_SI_NO', 'SiChecked');
|
|
148
215
|
invoice.payments.forEach((payment, index) => {
|
|
149
216
|
const suffix = String(index + 1).padStart(3, '0');
|
|
150
|
-
for (const [key, value] of Object.entries({
|
|
217
|
+
for (const [key, value] of Object.entries({
|
|
218
|
+
FCH_PAGO: payment.date,
|
|
219
|
+
MNT_PAGO: String(payment.amountClp),
|
|
220
|
+
GLOSA_PAGOS: payment.description ?? ''
|
|
221
|
+
}))
|
|
151
222
|
optionalField(`EFXP_${key}_${suffix}`, value);
|
|
152
223
|
scheduleDate('pago', index, payment.date);
|
|
153
224
|
});
|
|
154
225
|
}
|
|
155
226
|
page = await this.#portal('mipeDisplayPreView.cgi', fields);
|
|
156
227
|
const preview = this.#form(page, 'PreViewDTE', 'mipeGenXMLFirma.cgi', 'mipeGenFacEx.cgi');
|
|
157
|
-
this.#assertFields(preview, {
|
|
228
|
+
this.#assertFields(preview, {
|
|
229
|
+
PTDC_CODIGO: '33',
|
|
230
|
+
EFXP_FCH_EMIS: invoice.issuedDate,
|
|
231
|
+
EFXP_RUT_RECEP: receiver.rut,
|
|
232
|
+
EFXP_DV_RECEP: receiver.dv,
|
|
233
|
+
EFXP_MNT_NETO: String(totals.netAmount),
|
|
234
|
+
EFXP_IVA: String(totals.vatAmount),
|
|
235
|
+
EFXP_MNT_TOTAL: String(totals.totalAmount)
|
|
236
|
+
});
|
|
158
237
|
this.#assertFields(preview, optionalPreview);
|
|
159
238
|
if (!invoice.smallBusiness && preview.get('EMP_MENOR_TAMANO') === 'SiChecked')
|
|
160
239
|
throw this.session.failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeDisplayPreView.cgi', 'DOCUMENT_CONTENT_MISMATCH');
|
|
161
240
|
this.#preparation = preview;
|
|
162
|
-
return {
|
|
241
|
+
return {
|
|
242
|
+
issuerRut: this.session.company.formatted,
|
|
243
|
+
receiverRut: receiver.formatted,
|
|
244
|
+
documentType: 33,
|
|
245
|
+
issuedDate: invoice.issuedDate, ...totals,
|
|
246
|
+
invoice,
|
|
247
|
+
issuerLegalName: fields.get('EFXP_RZN_SOC')?.trim() ?? '',
|
|
248
|
+
issuerBusinessActivity: fields.get('EFXP_GIRO_EMIS')?.trim() ?? '',
|
|
249
|
+
issuerBranchCode: fields.get('EFXP_CDG_SII_SUCUR') ?? '',
|
|
250
|
+
issuerContact: { email: values.EFXP_EMAIL_EMISOR, phone: values.EFXP_FONO_EMISOR }
|
|
251
|
+
};
|
|
163
252
|
}
|
|
164
253
|
async prepareCancellationCreditNote({ factura, issuedDate }) {
|
|
165
254
|
this.session.assertReady();
|
|
166
255
|
const original = await this.issuedDocumentXml(factura);
|
|
167
|
-
const query = new URLSearchParams({
|
|
256
|
+
const query = new URLSearchParams({
|
|
257
|
+
RUT_RECP: '',
|
|
258
|
+
FOLIO: factura.folio,
|
|
259
|
+
RZN_SOC: '',
|
|
260
|
+
FEC_DESDE: '',
|
|
261
|
+
FEC_HASTA: '',
|
|
262
|
+
TPO_DOC: '33',
|
|
263
|
+
ESTADO: '',
|
|
264
|
+
ORDEN: '',
|
|
265
|
+
NUM_PAG: '1'
|
|
266
|
+
});
|
|
168
267
|
const history = await this.#portal('mipeAdminDocsEmi.cgi', undefined, `?${query}`);
|
|
169
268
|
const codes = new Set();
|
|
170
269
|
for (const element of htmlElements(history.document))
|
|
@@ -177,18 +276,41 @@ class FacturadorGateway {
|
|
|
177
276
|
if (link.origin === 'https://www1.sii.cl' && link.pathname === '/cgi-bin/Portal001/mipeGesDocEmi.cgi' && /^\d{1,20}$/.test(link.searchParams.get('CODIGO') ?? ''))
|
|
178
277
|
codes.add(link.searchParams.get('CODIGO'));
|
|
179
278
|
}
|
|
180
|
-
catch { /* Non-document links are ignored. */
|
|
279
|
+
catch { /* Non-document links are ignored. */
|
|
280
|
+
}
|
|
181
281
|
}
|
|
182
282
|
if (codes.size !== 1)
|
|
183
283
|
throw this.session.failure('SII_DOCUMENT_RECOVERY_FAILED', 'mipeAdminDocsEmi.cgi', codes.size === 0 ? 'DOCUMENT_NOT_FOUND' : 'INVALID_RESPONSE');
|
|
184
284
|
const page = await this.#portal('mipeDisplayPreView.cgi', undefined, `?EHDR_CODIGO=${[...codes][0]}&TIPO_NOTA=61`);
|
|
185
285
|
const fields = this.#form(page, 'PreViewDTE', 'mipeGenXMLFirma.cgi', 'mipeGenFacEx.cgi');
|
|
186
286
|
const d = original.detail;
|
|
187
|
-
this.#assertFields(fields, {
|
|
287
|
+
this.#assertFields(fields, {
|
|
288
|
+
PTDC_CODIGO: '61',
|
|
289
|
+
EFXP_FCH_EMIS: issuedDate,
|
|
290
|
+
EFXP_RUT_RECEP: (0, rut_1.parseRut)(d.receiverRut).rut,
|
|
291
|
+
EFXP_DV_RECEP: (0, rut_1.parseRut)(d.receiverRut).dv,
|
|
292
|
+
EFXP_TPO_DOC_REF_001: '33',
|
|
293
|
+
EFXP_FOLIO_REF_001: d.folio,
|
|
294
|
+
EFXP_FCH_REF_001: d.issuedDate,
|
|
295
|
+
EFXP_CODIGO_REF_001: '1',
|
|
296
|
+
EFXP_MNT_NETO: String(d.netAmount),
|
|
297
|
+
EFXP_IVA: String(d.vatAmount),
|
|
298
|
+
EFXP_MNT_TOTAL: String(d.totalAmount)
|
|
299
|
+
});
|
|
188
300
|
if (fields.get('EFXP_FOLIO_REF_002')?.trim() || fields.get('EFXP_FOLIO_REF_003')?.trim() || d.netAmount === null || d.vatAmount === null)
|
|
189
301
|
throw this.session.failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeDisplayPreView.cgi', 'DOCUMENT_CONTENT_MISMATCH');
|
|
190
302
|
this.#preparation = fields;
|
|
191
|
-
return {
|
|
303
|
+
return {
|
|
304
|
+
issuerRut: d.issuerRut,
|
|
305
|
+
receiverRut: d.receiverRut,
|
|
306
|
+
documentType: 61,
|
|
307
|
+
issuedDate,
|
|
308
|
+
netAmount: d.netAmount,
|
|
309
|
+
vatAmount: d.vatAmount,
|
|
310
|
+
totalAmount: d.totalAmount,
|
|
311
|
+
originalInvoice: d,
|
|
312
|
+
reference: { documentType: 33, folio: d.folio, issuedDate: d.issuedDate, code: 1 }
|
|
313
|
+
};
|
|
192
314
|
}
|
|
193
315
|
async unsignedDocument(approved) {
|
|
194
316
|
if (!this.#preparation)
|
|
@@ -199,10 +321,15 @@ class FacturadorGateway {
|
|
|
199
321
|
if (!/^[1-9]\d{0,19}$/.test(folio))
|
|
200
322
|
throw this.session.failure('SII_SIGNATURE_INVALID', 'mipeGenXMLFirma.cgi', 'INVALID_RESPONSE');
|
|
201
323
|
const plain = fields.get('txtPlainText') ?? '';
|
|
202
|
-
const expected = {
|
|
324
|
+
const expected = {
|
|
325
|
+
issuerRut: approved.issuerRut,
|
|
326
|
+
receiverRut: approved.receiverRut,
|
|
327
|
+
documentType: approved.documentType,
|
|
328
|
+
folio
|
|
329
|
+
};
|
|
203
330
|
let unsigned;
|
|
204
331
|
try {
|
|
205
|
-
unsigned = (0, dte_xml_1.
|
|
332
|
+
unsigned = (0, dte_xml_1.parseDteDocumentXmlForIssuance)((0, facturador_1.encodeUnsignedDteXml)(plain), expected);
|
|
206
333
|
}
|
|
207
334
|
catch {
|
|
208
335
|
throw this.session.failure('SII_SIGNATURE_INVALID', 'mipeGenXMLFirma.cgi', 'INVALID_XML');
|
|
@@ -226,14 +353,23 @@ class FacturadorGateway {
|
|
|
226
353
|
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)
|
|
227
354
|
throw this.session.failure('SII_CERTIFICATE_UNAVAILABLE', 'getCertDigital.cgi', 'CERTIFICATE_UNAVAILABLE');
|
|
228
355
|
const name = certs[0].nombre;
|
|
229
|
-
const fields = new URLSearchParams({
|
|
356
|
+
const fields = new URLSearchParams({
|
|
357
|
+
nombre: name,
|
|
358
|
+
dato: signing.plain,
|
|
359
|
+
rut: identity.rut,
|
|
360
|
+
dv: identity.dv,
|
|
361
|
+
clave: password,
|
|
362
|
+
nodo: 'dte:DTE',
|
|
363
|
+
nodoId: 'dte:Documento',
|
|
364
|
+
nameSpace: 'http://www.sii.cl/SiiDte'
|
|
365
|
+
});
|
|
230
366
|
return this.session.request(`${sii_http_session_1.FACTURADOR}postFirmaDigital.cgi`, async (response) => {
|
|
231
367
|
const signedBytes = await this.session.readBounded(response, 'postFirmaDigital.cgi');
|
|
232
368
|
if (!signedBytes.length)
|
|
233
369
|
throw this.session.failure('SII_SIGNATURE_INVALID', 'postFirmaDigital.cgi', 'EMPTY_RESPONSE', response);
|
|
234
370
|
let signed;
|
|
235
371
|
try {
|
|
236
|
-
signed = (0, dte_xml_1.
|
|
372
|
+
signed = (0, dte_xml_1.parseDteDocumentXmlForIssuance)(signedBytes, signing.expected);
|
|
237
373
|
}
|
|
238
374
|
catch {
|
|
239
375
|
const text = (0, facturador_1.readPortalHtml)(signedBytes);
|
|
@@ -246,7 +382,14 @@ class FacturadorGateway {
|
|
|
246
382
|
throw this.session.failure('SII_SIGNATURE_INVALID', 'postFirmaDigital.cgi', 'SIGNATURE_INVALID', response);
|
|
247
383
|
signing.certificate = name;
|
|
248
384
|
return { ...signed, ...signing.expected, issuedDate: approved.issuedDate, contentHash: approved.contentHash };
|
|
249
|
-
}, {
|
|
385
|
+
}, {
|
|
386
|
+
method: 'POST',
|
|
387
|
+
headers: {
|
|
388
|
+
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
|
|
389
|
+
Referer: `${sii_http_session_1.FACTURADOR}mipeGenXMLFirma.cgi`
|
|
390
|
+
},
|
|
391
|
+
body: fields.toString()
|
|
392
|
+
});
|
|
250
393
|
}
|
|
251
394
|
async sendDocument(document, password) {
|
|
252
395
|
const signing = this.#signing;
|
|
@@ -269,20 +412,34 @@ class FacturadorGateway {
|
|
|
269
412
|
throw this.session.failure('SII_ISSUANCE_OUTCOME_UNKNOWN', 'mipeSendXML.cgi', 'ISSUANCE_OUTCOME_UNKNOWN');
|
|
270
413
|
}
|
|
271
414
|
}
|
|
272
|
-
issuedInvoiceXml(input) {
|
|
415
|
+
issuedInvoiceXml(input, options) {
|
|
273
416
|
if (![33, 34].includes(input.documentType))
|
|
274
417
|
return Promise.reject(new TypeError('Identidad de factura inválida'));
|
|
275
|
-
return this.#documentXml(input, undefined, true);
|
|
418
|
+
return this.#documentXml(input, undefined, true, false, options);
|
|
276
419
|
}
|
|
277
|
-
receivedInvoiceXml(input) {
|
|
420
|
+
receivedInvoiceXml(input, options) {
|
|
278
421
|
if (![33, 34].includes(input.documentType))
|
|
279
422
|
return Promise.reject(new TypeError('Identidad de factura inválida'));
|
|
280
|
-
return this.#documentXml(input, (0, rut_1.parseRut)(input.issuerRut), true);
|
|
423
|
+
return this.#documentXml(input, (0, rut_1.parseRut)(input.issuerRut), true, false, options);
|
|
424
|
+
}
|
|
425
|
+
issuedDocumentXml(input, options) {
|
|
426
|
+
return this.#documentXml(input, undefined, false, false, options);
|
|
427
|
+
}
|
|
428
|
+
async receivedDocumentXml(input, options) {
|
|
429
|
+
return this.#documentXml(input, (0, rut_1.parseRut)(input.issuerRut), false, false, options);
|
|
430
|
+
}
|
|
431
|
+
issuedDocumentXmlExact(input, options) {
|
|
432
|
+
return this.#documentXml(input, undefined, false, true, options);
|
|
433
|
+
}
|
|
434
|
+
receivedDocumentXmlExact(input, options) {
|
|
435
|
+
return this.#documentXml(input, (0, rut_1.parseRut)(input.issuerRut), false, true, options);
|
|
436
|
+
}
|
|
437
|
+
issuedInvoicePdf(input, options) {
|
|
438
|
+
return this.#documentPdf(input, undefined, options);
|
|
439
|
+
}
|
|
440
|
+
async receivedInvoicePdf(input, options) {
|
|
441
|
+
return this.#documentPdf(input, (0, rut_1.parseRut)(input.issuerRut), options);
|
|
281
442
|
}
|
|
282
|
-
issuedDocumentXml(input) { return this.#documentXml(input); }
|
|
283
|
-
async receivedDocumentXml(input) { return this.#documentXml(input, (0, rut_1.parseRut)(input.issuerRut)); }
|
|
284
|
-
issuedInvoicePdf(input, options) { return this.#documentPdf(input, undefined, options); }
|
|
285
|
-
async receivedInvoicePdf(input, options) { return this.#documentPdf(input, (0, rut_1.parseRut)(input.issuerRut), options); }
|
|
286
443
|
async #documentPdf({ documentType, folio }, supplier, options = {}) {
|
|
287
444
|
this.session.assertReady();
|
|
288
445
|
if (![33, 34].includes(documentType) || typeof folio !== 'string' || !/^[1-9]\d{0,19}$/.test(folio))
|
|
@@ -291,7 +448,17 @@ class FacturadorGateway {
|
|
|
291
448
|
const historyEndpoint = supplier ? 'mipeAdminDocsRcp.cgi' : 'mipeAdminDocsEmi.cgi';
|
|
292
449
|
return this.session.pdfOperation(endpoint, async (signal, trackStream) => {
|
|
293
450
|
await this.#ensurePortal(supplier ? 'OPCION=1&TIPO=4' : DESTINATION, signal, true);
|
|
294
|
-
const query = new URLSearchParams({
|
|
451
|
+
const query = new URLSearchParams({
|
|
452
|
+
...(supplier ? { RUT_EMI: supplier.rut } : { RUT_RECP: '' }),
|
|
453
|
+
FOLIO: folio,
|
|
454
|
+
RZN_SOC: '',
|
|
455
|
+
FEC_DESDE: '',
|
|
456
|
+
FEC_HASTA: '',
|
|
457
|
+
TPO_DOC: String(documentType),
|
|
458
|
+
ESTADO: '',
|
|
459
|
+
ORDEN: '',
|
|
460
|
+
NUM_PAG: '1'
|
|
461
|
+
});
|
|
295
462
|
const history = await this.#portal(historyEndpoint, undefined, `?${query}`, signal);
|
|
296
463
|
await this.#assertCompany(historyEndpoint);
|
|
297
464
|
let code;
|
|
@@ -311,12 +478,23 @@ class FacturadorGateway {
|
|
|
311
478
|
return { stream, contentType: 'application/pdf', filename: `factura-${documentType}-${folio}.pdf` };
|
|
312
479
|
}, options.signal);
|
|
313
480
|
}
|
|
314
|
-
async #documentXml({ documentType, folio }, supplier, legacy = false) {
|
|
481
|
+
async #documentXml({ documentType, folio }, supplier, legacy = false, exact = false, options) {
|
|
315
482
|
this.session.assertReady();
|
|
316
483
|
if (![33, 34, 61].includes(documentType) || typeof folio !== 'string' || !/^[1-9]\d{0,19}$/.test(folio))
|
|
317
484
|
throw new TypeError('Identidad de documento inválida');
|
|
485
|
+
(0, read_options_1.assertDteXmlReadOptions)(options);
|
|
318
486
|
await this.#ensurePortal();
|
|
319
|
-
const query = new URLSearchParams({
|
|
487
|
+
const query = new URLSearchParams({
|
|
488
|
+
ORIGEN: supplier ? 'RCP' : 'ENV', ...(supplier ? { RUT_EMI: supplier.rut } : { RUT_RECP: '' }),
|
|
489
|
+
FOLIO: folio,
|
|
490
|
+
RZN_SOC: '',
|
|
491
|
+
FEC_DESDE: '',
|
|
492
|
+
FEC_HASTA: '',
|
|
493
|
+
TPO_DOC: String(documentType),
|
|
494
|
+
ESTADO: '',
|
|
495
|
+
ORDEN: '',
|
|
496
|
+
DOWNLOAD: 'XML'
|
|
497
|
+
});
|
|
320
498
|
return this.session.request(`${sii_http_session_1.FACTURADOR}mipeDownLoad.cgi?${query}`, async (response) => {
|
|
321
499
|
const bytes = await this.session.readBounded(response, 'mipeDownLoad.cgi');
|
|
322
500
|
const format = (0, sii_http_session_1.responseFormat)(response, bytes);
|
|
@@ -337,17 +515,25 @@ class FacturadorGateway {
|
|
|
337
515
|
throw this.session.failure(reason === 'DOCUMENT_NOT_FOUND' ? 'SII_XML_UNAVAILABLE' : 'SII_SERVICE_ERROR', 'mipeDownLoad.cgi', reason, response, evidence);
|
|
338
516
|
}
|
|
339
517
|
try {
|
|
340
|
-
const identity = {
|
|
518
|
+
const identity = {
|
|
519
|
+
issuerRut: supplier?.formatted ?? this.session.company.formatted, ...(supplier ? { receiverRut: this.session.company.formatted } : {}),
|
|
520
|
+
folio
|
|
521
|
+
};
|
|
522
|
+
if (exact)
|
|
523
|
+
return (0, dte_xml_1.parseDteDocumentXmlExact)(bytes, { ...identity, documentType }, options);
|
|
341
524
|
if (legacy) {
|
|
342
525
|
if (documentType !== 33 && documentType !== 34)
|
|
343
|
-
throw new
|
|
344
|
-
return (0, dte_xml_1.parseDteXml)(bytes, { ...identity, documentType });
|
|
526
|
+
throw new contracts_1.DteXmlError('SII_XML_INVALID');
|
|
527
|
+
return (0, dte_xml_1.parseDteXml)(bytes, { ...identity, documentType }, options);
|
|
345
528
|
}
|
|
346
|
-
return (0, dte_xml_1.parseDteDocumentXml)(bytes, { ...identity, documentType });
|
|
529
|
+
return (0, dte_xml_1.parseDteDocumentXml)(bytes, { ...identity, documentType }, options);
|
|
347
530
|
}
|
|
348
531
|
catch (error) {
|
|
349
|
-
const code = error instanceof
|
|
350
|
-
throw this.session.failure(code, 'mipeDownLoad.cgi', code === 'SII_XML_IDENTITY_MISMATCH' ? 'XML_IDENTITY_MISMATCH' : 'INVALID_XML', response, {
|
|
532
|
+
const code = error instanceof contracts_1.DteXmlError ? error.code : 'SII_XML_INVALID';
|
|
533
|
+
throw this.session.failure(code, 'mipeDownLoad.cgi', code === 'SII_XML_IDENTITY_MISMATCH' ? 'XML_IDENTITY_MISMATCH' : 'INVALID_XML', response, {
|
|
534
|
+
...format,
|
|
535
|
+
stage: 'XML_PARSE'
|
|
536
|
+
});
|
|
351
537
|
}
|
|
352
538
|
}, {}, true);
|
|
353
539
|
}
|
|
@@ -385,7 +571,10 @@ class FacturadorGateway {
|
|
|
385
571
|
if (selection && (submitted || hop >= 4))
|
|
386
572
|
throw this.session.failure('SII_XML_COMPANY_SELECTION_REQUIRED', (0, sii_http_session_1.endpointFor)(url), 'COMPANY_SELECTION_REQUIRED', response);
|
|
387
573
|
return { selection };
|
|
388
|
-
}, {
|
|
574
|
+
}, {
|
|
575
|
+
...options,
|
|
576
|
+
signal
|
|
577
|
+
}, (destination === DESTINATION || Boolean(signal)) && options.method !== 'POST', true);
|
|
389
578
|
if (result.next) {
|
|
390
579
|
url = result.next;
|
|
391
580
|
options = {};
|
|
@@ -394,7 +583,11 @@ class FacturadorGateway {
|
|
|
394
583
|
if (result.selection) {
|
|
395
584
|
submitted = true;
|
|
396
585
|
url = `${sii_http_session_1.FACTURADOR}mipeSelEmpresa.cgi`;
|
|
397
|
-
options = {
|
|
586
|
+
options = {
|
|
587
|
+
method: 'POST',
|
|
588
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
589
|
+
body: result.selection.toString()
|
|
590
|
+
};
|
|
398
591
|
continue;
|
|
399
592
|
}
|
|
400
593
|
break;
|
|
@@ -426,7 +619,12 @@ class FacturadorGateway {
|
|
|
426
619
|
throw this.session.failure('SII_SERVICE_ERROR', endpoint, 'PROVIDER_ERROR_PAGE', response, code ? { siiMessageCode: code } : {});
|
|
427
620
|
}
|
|
428
621
|
return { text, document };
|
|
429
|
-
}, fields === undefined ? { signal } : {
|
|
622
|
+
}, fields === undefined ? { signal } : {
|
|
623
|
+
method: 'POST',
|
|
624
|
+
signal,
|
|
625
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Referer: `${sii_http_session_1.FACTURADOR}${endpoint}` },
|
|
626
|
+
body: typeof fields === 'string' ? fields : (0, facturador_1.encodePortalForm)(fields)
|
|
627
|
+
}, Boolean(signal) && fields === undefined);
|
|
430
628
|
}
|
|
431
629
|
#form(page, name, endpoint, alternative) {
|
|
432
630
|
try {
|
|
@@ -437,7 +635,8 @@ class FacturadorGateway {
|
|
|
437
635
|
try {
|
|
438
636
|
return (0, facturador_1.readForm)(page.document, name, alternative);
|
|
439
637
|
}
|
|
440
|
-
catch { /* Only known form actions are allowed. */
|
|
638
|
+
catch { /* Only known form actions are allowed. */
|
|
639
|
+
}
|
|
441
640
|
}
|
|
442
641
|
const source = name === 'VIEW_EFXP' ? 'mipeGenFacEx.cgi' : name === 'PreViewDTE' ? 'mipeDisplayPreView.cgi' : 'mipeGenXMLFirma.cgi';
|
|
443
642
|
throw this.session.failure('SII_PROTOCOL_CHANGED', source, 'INVALID_RESPONSE');
|
|
@@ -460,7 +659,8 @@ class FacturadorGateway {
|
|
|
460
659
|
if (rows.length === 1 && rows[0])
|
|
461
660
|
return rows[0];
|
|
462
661
|
}
|
|
463
|
-
catch { /* No provider scripts execute. */
|
|
662
|
+
catch { /* No provider scripts execute. */
|
|
663
|
+
}
|
|
464
664
|
throw this.session.failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeGenFacEx.cgi', 'DOCUMENT_CONTENT_MISMATCH');
|
|
465
665
|
}
|
|
466
666
|
#assertFields(fields, expected) {
|
|
@@ -13,13 +13,15 @@ exports.encodeUnsignedDteXml = encodeUnsignedDteXml;
|
|
|
13
13
|
exports.readVisiblePortalText = readVisiblePortalText;
|
|
14
14
|
exports.hasInteractiveCaptcha = hasInteractiveCaptcha;
|
|
15
15
|
const parse5_1 = require("parse5");
|
|
16
|
-
const
|
|
16
|
+
const contracts_1 = require("../contracts");
|
|
17
17
|
const PORTAL = 'https://www1.sii.cl/cgi-bin/Portal001/';
|
|
18
18
|
const MAX_HTML_BYTES = 2 * 1024 * 1024;
|
|
19
19
|
const ROW_VARIABLES = new Set(['emisorDir', 'emisorActEco', 'recptorDir', 'recptoActEco']);
|
|
20
20
|
const decoder = new TextDecoder('windows-1252', { fatal: true });
|
|
21
21
|
const cp1252 = new Map(Array.from({ length: 256 }, (_, byte) => [decoder.decode(Uint8Array.of(byte)), byte]));
|
|
22
|
-
function invalid(reason = 'INVALID_RESPONSE') {
|
|
22
|
+
function invalid(reason = 'INVALID_RESPONSE') {
|
|
23
|
+
throw new TypeError(`Formulario del facturador inválido: ${reason}`);
|
|
24
|
+
}
|
|
23
25
|
function attr(element, name) {
|
|
24
26
|
return element.attrs.find(attribute => attribute.name === name)?.value;
|
|
25
27
|
}
|
|
@@ -158,8 +160,11 @@ function readLiteralRows(html, variable) {
|
|
|
158
160
|
function readCompanyOptions(html) {
|
|
159
161
|
const rows = (variable, widths) => readLiteralRows(html, variable)
|
|
160
162
|
.map(row => row.map(value => value.trim()))
|
|
161
|
-
.filter(row => {
|
|
162
|
-
|
|
163
|
+
.filter(row => {
|
|
164
|
+
if (!widths.includes(row.length))
|
|
165
|
+
invalid();
|
|
166
|
+
return !row.every(value => value === '0');
|
|
167
|
+
})
|
|
163
168
|
.map(row => {
|
|
164
169
|
if (!row[0] || !row[1] || row.some(value => /[\u0000-\u001f\u007f]/u.test(value)))
|
|
165
170
|
invalid();
|
|
@@ -191,8 +196,10 @@ function readPortalHtml(bytes) {
|
|
|
191
196
|
}
|
|
192
197
|
/** Encode unsigned XML as declared, without changing its text or silently truncating Unicode. */
|
|
193
198
|
function encodeUnsignedDteXml(value) {
|
|
194
|
-
const invalidXml = () => {
|
|
195
|
-
|
|
199
|
+
const invalidXml = () => {
|
|
200
|
+
throw new TypeError('XML sin firmar inválido');
|
|
201
|
+
};
|
|
202
|
+
if (typeof value !== 'string' || !value.length || value.length > contracts_1.MAX_DTE_XML_BYTES)
|
|
196
203
|
invalidXml();
|
|
197
204
|
const declared = /<\?xml\b[^?]*\bencoding\s*=\s*['"]([^'"]+)['"]/i.exec(value.slice(0, 200))?.[1]?.toUpperCase() ?? 'UTF-8';
|
|
198
205
|
if (declared === 'ISO-8859-1') {
|
|
@@ -201,7 +208,7 @@ function encodeUnsignedDteXml(value) {
|
|
|
201
208
|
return Buffer.from(value, 'latin1');
|
|
202
209
|
}
|
|
203
210
|
if (declared === 'UTF-8' || declared === 'UTF8') {
|
|
204
|
-
if (Buffer.byteLength(value, 'utf8') >
|
|
211
|
+
if (Buffer.byteLength(value, 'utf8') > contracts_1.MAX_DTE_XML_BYTES)
|
|
205
212
|
invalidXml();
|
|
206
213
|
const bytes = Buffer.from(value, 'utf8');
|
|
207
214
|
if (bytes.toString('utf8') !== value)
|
|
@@ -80,7 +80,8 @@ async function readInvoicePdfStream(response, session, endpoint, signal, trackSt
|
|
|
80
80
|
const prefix = new Uint8Array(5);
|
|
81
81
|
let prefixSize = 0, size = 0, reading = false;
|
|
82
82
|
let cancellation;
|
|
83
|
-
const cancelSource = () => cancellation ??= reader.cancel().catch(() => {
|
|
83
|
+
const cancelSource = () => cancellation ??= reader.cancel().catch(() => {
|
|
84
|
+
});
|
|
84
85
|
const onAbort = () => {
|
|
85
86
|
void cancelSource();
|
|
86
87
|
stream?.destroy(session.abortFailure(signal, endpoint));
|
|
@@ -149,12 +150,18 @@ async function readInvoicePdfStream(response, session, endpoint, signal, trackSt
|
|
|
149
150
|
this.push(value);
|
|
150
151
|
return;
|
|
151
152
|
}
|
|
152
|
-
})().catch(error => {
|
|
153
|
+
})().catch(error => {
|
|
154
|
+
reading = false;
|
|
155
|
+
this.destroy(error instanceof sii_error_1.SiiError ? error : session.failure('SII_TRANSPORT_ERROR', endpoint, 'TRANSPORT_ERROR', response));
|
|
156
|
+
});
|
|
153
157
|
},
|
|
154
158
|
destroy(error, callback) {
|
|
155
159
|
signal.removeEventListener('abort', onAbort);
|
|
156
160
|
prefixChunks.length = 0;
|
|
157
|
-
void cancelSource().then(() => {
|
|
161
|
+
void cancelSource().then(() => {
|
|
162
|
+
reader.releaseLock();
|
|
163
|
+
callback(error);
|
|
164
|
+
});
|
|
158
165
|
},
|
|
159
166
|
});
|
|
160
167
|
// Track before yielding: abort can happen between creation and public handoff.
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import { type
|
|
2
|
-
import type {
|
|
3
|
-
import type {
|
|
4
|
-
import type { AuthorizedCompany,
|
|
1
|
+
import { type IssuedInvoicesResult } from '../domain/issued-invoice';
|
|
2
|
+
import type { ReceivedInvoicesResult } from '../domain/received-invoice';
|
|
3
|
+
import type { RcvDocumentsResult } from '../domain/rcv-document';
|
|
4
|
+
import type { AuthorizedCompany, IssuedInvoicesQuery, RcvDocumentsQuery, ReceivedInvoicesQuery, SiiResponse, SummaryQuery } from '../contracts';
|
|
5
|
+
import type { ExactDte } from '../domain/dte-money';
|
|
5
6
|
import { SiiHttpSession } from './sii-http-session';
|
|
6
7
|
export declare class RcvGateway {
|
|
7
8
|
#private;
|
|
@@ -17,4 +18,6 @@ export declare class RcvGateway {
|
|
|
17
18
|
receivedInvoices(input: ReceivedInvoicesQuery): Promise<ReceivedInvoicesResult>;
|
|
18
19
|
issuedDocuments(input: RcvDocumentsQuery): Promise<RcvDocumentsResult>;
|
|
19
20
|
receivedDocuments(input: RcvDocumentsQuery): Promise<RcvDocumentsResult>;
|
|
21
|
+
issuedDocumentsExact(input: RcvDocumentsQuery): Promise<ExactDte<RcvDocumentsResult>>;
|
|
22
|
+
receivedDocumentsExact(input: RcvDocumentsQuery): Promise<ExactDte<RcvDocumentsResult>>;
|
|
20
23
|
}
|