@devly-cl/sii-client 0.6.0 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +96 -251
- package/dist/application/document-status.d.ts +13 -0
- package/dist/application/document-status.js +50 -0
- package/dist/application/invoice-queries.d.ts +11 -5
- package/dist/application/invoice-queries.js +13 -9
- package/dist/domain/company-info.d.ts +13 -0
- package/dist/domain/company-info.js +2 -0
- package/dist/domain/document-status.d.ts +93 -0
- package/dist/domain/document-status.js +69 -0
- package/dist/domain/document.d.ts +4 -0
- package/dist/domain/document.js +36 -3
- package/dist/domain/invoice-xml.d.ts +34 -1
- package/dist/domain/invoicing.d.ts +78 -5
- package/dist/domain/invoicing.js +143 -26
- package/dist/domain/rcv-document.d.ts +17 -0
- package/dist/domain/rcv-document.js +2 -0
- package/dist/index.d.ts +7 -4
- package/dist/index.js +2 -1
- package/dist/infrastructure/document-status-gateway.d.ts +13 -0
- package/dist/infrastructure/document-status-gateway.js +127 -0
- package/dist/infrastructure/document-status-parser.d.ts +12 -0
- package/dist/infrastructure/document-status-parser.js +258 -0
- package/dist/infrastructure/dte-xml.js +81 -6
- package/dist/infrastructure/facturador-gateway.d.ts +4 -1
- package/dist/infrastructure/facturador-gateway.js +113 -15
- package/dist/infrastructure/facturador.d.ts +3 -0
- package/dist/infrastructure/facturador.js +18 -1
- package/dist/infrastructure/rcv-gateway.d.ts +3 -0
- package/dist/infrastructure/rcv-gateway.js +9 -5
- package/dist/infrastructure/rcv-normalization.d.ts +7 -0
- package/dist/infrastructure/rcv-normalization.js +9 -1
- package/dist/infrastructure/sii-client.d.ts +10 -1
- package/dist/infrastructure/sii-client.js +29 -3
- package/dist/infrastructure/sii-http-session.d.ts +5 -1
- package/dist/infrastructure/sii-http-session.js +20 -5
- package/dist/sii-error.d.ts +3 -3
- package/dist/sii-error.js +10 -4
- package/package.json +45 -45
- package/dist/domain/sii-error.d.ts +0 -27
- package/dist/domain/sii-error.js +0 -82
package/dist/domain/invoicing.js
CHANGED
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.hashContenido = exports.calcularTotalesFactura = exports.validarFactura = void 0;
|
|
3
|
+
exports.hashContenido = exports.calcularTotalesFactura = exports.validarFactura = exports.INVOICE_ADDITIONAL_TAX_RATES = void 0;
|
|
4
|
+
exports.invoiceBreakdown = invoiceBreakdown;
|
|
4
5
|
exports.validateInvoice = validateInvoice;
|
|
5
6
|
exports.calculateInvoiceTotals = calculateInvoiceTotals;
|
|
6
7
|
exports.hashContent = hashContent;
|
|
7
8
|
const node_crypto_1 = require("node:crypto");
|
|
8
9
|
const rut_1 = require("./rut");
|
|
10
|
+
exports.INVOICE_ADDITIONAL_TAX_RATES = Object.freeze({ 23: '15', 44: '15', 24: '31.5', 25: '20.5', 26: '20.5', 27: '10', 271: '18' });
|
|
9
11
|
const controls = /[\u0000-\u001f\u007f-\u009f]/u;
|
|
10
12
|
function invalid(field) { throw new TypeError(`Factura inválida: ${field}`); }
|
|
11
13
|
function isRecord(value) {
|
|
@@ -30,17 +32,36 @@ function text(value, limit, field, optional = false) {
|
|
|
30
32
|
function requiredText(value, limit, field) {
|
|
31
33
|
return text(value, limit, field) ?? invalid(field);
|
|
32
34
|
}
|
|
33
|
-
function decimal(value, field) {
|
|
35
|
+
function decimal(value, field, allowZero = false) {
|
|
34
36
|
const result = requiredText(value, 12, field);
|
|
35
37
|
const match = /^(\d{1,10})(?:\.(\d{1,2}))?$/.exec(result);
|
|
36
38
|
if (!match)
|
|
37
39
|
invalid(field);
|
|
38
40
|
const integer = match[1].replace(/^0+(?=\d)/u, '');
|
|
39
41
|
const fraction = (match[2] ?? '').replace(/0+$/u, '');
|
|
40
|
-
if (integer === '0' && !fraction)
|
|
42
|
+
if (!allowZero && integer === '0' && !fraction)
|
|
41
43
|
invalid(field);
|
|
42
44
|
return fraction ? `${integer}.${fraction}` : integer;
|
|
43
45
|
}
|
|
46
|
+
function percentage(value, field, allowZero = false) {
|
|
47
|
+
const result = decimal(value, field, allowZero);
|
|
48
|
+
return hundredths(result) <= 10000n ? result : invalid(field);
|
|
49
|
+
}
|
|
50
|
+
function amount(value, field, allowZero = false) {
|
|
51
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < (allowZero ? 0 : 1) || value > 9999999999)
|
|
52
|
+
invalid(field);
|
|
53
|
+
return value;
|
|
54
|
+
}
|
|
55
|
+
function globalDiscount(value) {
|
|
56
|
+
if (value === undefined)
|
|
57
|
+
return undefined;
|
|
58
|
+
const source = record(value, ['percent', 'amountClp'], 'globalDiscount');
|
|
59
|
+
if (Object.keys(source).length !== 1)
|
|
60
|
+
invalid('globalDiscount');
|
|
61
|
+
return Object.freeze(source.percent !== undefined
|
|
62
|
+
? { percent: percentage(source.percent, 'globalDiscount.percent', true) }
|
|
63
|
+
: { amountClp: amount(source.amountClp, 'globalDiscount.amountClp', true) });
|
|
64
|
+
}
|
|
44
65
|
function hundredths(value) {
|
|
45
66
|
const [integer, fraction = ''] = value.split('.');
|
|
46
67
|
return BigInt(integer) * 100n + BigInt(fraction.padEnd(2, '0'));
|
|
@@ -49,65 +70,155 @@ function items(value) {
|
|
|
49
70
|
if (!Array.isArray(value) || !value.length || value.length > 10)
|
|
50
71
|
invalid('items');
|
|
51
72
|
return Array.from(value, entry => {
|
|
52
|
-
const source = record(entry, ['name', 'description', 'quantity', 'unitNetPriceClp', 'unit'], 'items');
|
|
73
|
+
const source = record(entry, ['name', 'description', 'quantity', 'unitNetPriceClp', 'unit', 'productCode', 'additionalTaxCode', 'discountPercent'], 'items');
|
|
53
74
|
const description = text(source.description, 999, 'description', true);
|
|
54
75
|
const unit = text(source.unit, 4, 'unit', true);
|
|
76
|
+
const code = source.productCode === undefined ? undefined : record(source.productCode, ['type', 'value'], 'productCode');
|
|
77
|
+
const additionalTaxCode = source.additionalTaxCode;
|
|
78
|
+
if (additionalTaxCode !== undefined && (typeof additionalTaxCode !== 'number' || !Object.hasOwn(exports.INVOICE_ADDITIONAL_TAX_RATES, additionalTaxCode)))
|
|
79
|
+
invalid('additionalTaxCode');
|
|
55
80
|
return Object.freeze({
|
|
56
81
|
name: requiredText(source.name, 25, 'name'),
|
|
57
82
|
...(description === undefined ? {} : { description }),
|
|
58
83
|
quantity: decimal(source.quantity, 'quantity'),
|
|
59
84
|
unitNetPriceClp: decimal(source.unitNetPriceClp, 'unitNetPriceClp'),
|
|
60
85
|
...(unit === undefined ? {} : { unit }),
|
|
86
|
+
...(code === undefined ? {} : { productCode: Object.freeze({ type: requiredText(code.type, 10, 'productCode.type'), value: requiredText(code.value, 15, 'productCode.value') }) }),
|
|
87
|
+
...(additionalTaxCode === undefined ? {} : { additionalTaxCode: additionalTaxCode }),
|
|
88
|
+
...(source.discountPercent === undefined ? {} : { discountPercent: percentage(source.discountPercent, 'discountPercent') }),
|
|
61
89
|
});
|
|
62
90
|
});
|
|
63
91
|
}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
92
|
+
const round = (numerator, denominator) => (numerator + denominator / 2n) / denominator;
|
|
93
|
+
const fromHundredths = (value) => `${value / 100n}.${String(value % 100n).padStart(2, '0')}`.replace(/\.?0+$/, '');
|
|
94
|
+
/** Shared exact arithmetic for the portal and the unsigned/signed XML guard. */
|
|
95
|
+
function invoiceBreakdown(lines, discount) {
|
|
96
|
+
const lineAmounts = lines.map(line => {
|
|
97
|
+
const product = hundredths(line.quantity) * hundredths(line.unitNetPriceClp);
|
|
98
|
+
const pct = hundredths(line.discountPercent ?? '0');
|
|
99
|
+
const result = round(product * (10000n - pct), 100000000n);
|
|
100
|
+
if (result < 1n && pct !== 10000n || result > 9999999999n)
|
|
68
101
|
invalid('lineAmount');
|
|
69
|
-
|
|
70
|
-
|
|
102
|
+
if (line.additionalTaxCode !== undefined && pct > 0n && (pct === 10000n || hundredths(line.unitNetPriceClp) * pct < 1000000n))
|
|
103
|
+
invalid('discountPercent.additionalTax');
|
|
104
|
+
return { amount: Number(result), discountAmount: Number(round(product * pct, 100000000n)) };
|
|
105
|
+
});
|
|
106
|
+
const subtotal = lineAmounts.reduce((sum, line) => sum + BigInt(line.amount), 0n);
|
|
107
|
+
if (subtotal > 9999999999n)
|
|
108
|
+
invalid('subtotal');
|
|
109
|
+
const discountAmount = discount?.amountClp !== undefined ? BigInt(discount.amountClp) : round(subtotal * hundredths(discount?.percent ?? '0'), 10000n);
|
|
110
|
+
if (discountAmount > subtotal)
|
|
111
|
+
invalid('globalDiscount');
|
|
112
|
+
const discountPercent = discount?.percent !== undefined ? hundredths(discount.percent) : subtotal ? round(discountAmount * 10000n, subtotal) : 0n;
|
|
113
|
+
const net = subtotal - discountAmount;
|
|
71
114
|
const vat = (net * 19n + 50n) / 100n;
|
|
72
|
-
const
|
|
73
|
-
|
|
115
|
+
const taxBases = new Map();
|
|
116
|
+
lines.forEach((line, index) => { if (line.additionalTaxCode !== undefined)
|
|
117
|
+
taxBases.set(line.additionalTaxCode, (taxBases.get(line.additionalTaxCode) ?? 0n) + BigInt(lineAmounts[index].amount)); });
|
|
118
|
+
let taxNumerator = 0n;
|
|
119
|
+
const taxes = [...taxBases].map(([type, base]) => {
|
|
120
|
+
const rate = exports.INVOICE_ADDITIONAL_TAX_RATES[type];
|
|
121
|
+
const numerator = base * hundredths(rate) * (10000n - discountPercent);
|
|
122
|
+
taxNumerator += numerator;
|
|
123
|
+
return { type, rate, amount: Number(round(numerator, 100000000n)) };
|
|
124
|
+
});
|
|
125
|
+
const additionalTaxAmount = round(taxNumerator, 100000000n);
|
|
126
|
+
if (taxes.length && additionalTaxAmount < 1n)
|
|
127
|
+
invalid('additionalTaxAmount');
|
|
128
|
+
const total = net + vat + additionalTaxAmount;
|
|
129
|
+
if ((!subtotal && !lines.every(line => line.discountPercent === '100')) || total > 9999999999n)
|
|
74
130
|
invalid('totalAmount');
|
|
75
|
-
return
|
|
131
|
+
return {
|
|
132
|
+
totals: Object.freeze({ netAmount: Number(net), vatAmount: Number(vat), totalAmount: Number(total) }),
|
|
133
|
+
subtotal: Number(subtotal), discountAmount: Number(discountAmount), discountPercent: fromHundredths(discountPercent), discountAmountFromPercent: Number(round(subtotal * discountPercent, 10000n)),
|
|
134
|
+
additionalTaxAmount: Number(additionalTaxAmount), lineAmounts, taxes,
|
|
135
|
+
};
|
|
76
136
|
}
|
|
77
|
-
function
|
|
137
|
+
function civilDate(value, field, minimum, maximum = '9999-12-31') {
|
|
78
138
|
if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/u.test(value))
|
|
79
|
-
invalid(
|
|
139
|
+
invalid(field);
|
|
80
140
|
const year = Number(value.slice(0, 4)), month = Number(value.slice(5, 7)), day = Number(value.slice(8, 10));
|
|
81
141
|
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
82
142
|
const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
83
|
-
if (
|
|
84
|
-
invalid(
|
|
143
|
+
if (value < minimum || value > maximum || month < 1 || month > 12 || day < 1 || day > days[month - 1])
|
|
144
|
+
invalid(field);
|
|
85
145
|
return value;
|
|
86
146
|
}
|
|
87
|
-
|
|
147
|
+
function smallArray(value, field) {
|
|
148
|
+
if (!Array.isArray(value) || !value.length || value.length > 3)
|
|
149
|
+
invalid(field);
|
|
150
|
+
return Array.from(value);
|
|
151
|
+
}
|
|
152
|
+
const referenceTypes = ['30', '32', '33', '34', '35', '38', '39', '40', '41', '43', '45', '46', '48', '50', '52', '55', '56', '60', '61', '103', '801', '802', '803', '804', '805', '806', '813', '820', '821', '822', '823', 'HES'];
|
|
153
|
+
function references(value) {
|
|
154
|
+
return Object.freeze(smallArray(value, 'references').map(entry => {
|
|
155
|
+
const source = record(entry, ['documentType', 'folio', 'date', 'reason', 'global'], 'reference');
|
|
156
|
+
if (typeof source.documentType !== 'string' || !referenceTypes.includes(source.documentType))
|
|
157
|
+
invalid('reference.documentType');
|
|
158
|
+
if (source.global !== undefined && typeof source.global !== 'boolean')
|
|
159
|
+
invalid('reference.global');
|
|
160
|
+
const folio = requiredText(source.folio, 18, 'reference.folio');
|
|
161
|
+
if (source.global ? folio !== '0' : ['30', '32', '38', '40', '45', '50', '55', '60', '33', '34', '39', '46', '56', '61', '52', '103'].includes(source.documentType) && !/^[1-9]\d*$/.test(folio))
|
|
162
|
+
invalid('reference.folio');
|
|
163
|
+
const reason = text(source.reason, 90, 'reference.reason', true);
|
|
164
|
+
return Object.freeze({ documentType: source.documentType, folio, date: civilDate(source.date, 'reference.date', '2002-08-01', '2050-12-31'), ...(reason === undefined ? {} : { reason }), ...(source.global ? { global: true } : {}) });
|
|
165
|
+
}));
|
|
166
|
+
}
|
|
167
|
+
function payments(value, issued, total) {
|
|
168
|
+
let previous = issued, sum = 0;
|
|
169
|
+
const result = smallArray(value, 'payments').map((entry, index) => {
|
|
170
|
+
const source = record(entry, ['date', 'amountClp', 'description'], 'payment');
|
|
171
|
+
const date = civilDate(source.date, 'payment.date', issued);
|
|
172
|
+
if (index && date <= previous)
|
|
173
|
+
invalid('payment.date');
|
|
174
|
+
previous = date;
|
|
175
|
+
const amountClp = amount(source.amountClp, 'payment.amountClp');
|
|
176
|
+
sum += amountClp;
|
|
177
|
+
const description = text(source.description, 40, 'payment.description', true);
|
|
178
|
+
return Object.freeze({ date, amountClp, ...(description === undefined ? {} : { description }) });
|
|
179
|
+
});
|
|
180
|
+
if (sum !== total)
|
|
181
|
+
invalid('payments.total');
|
|
182
|
+
return Object.freeze(result);
|
|
183
|
+
}
|
|
184
|
+
function transport(value) {
|
|
185
|
+
const source = record(value, ['carrierRut', 'licensePlate', 'driverRut', 'driverName'], 'transport');
|
|
186
|
+
return Object.freeze({ carrierRut: (0, rut_1.parseRut)(requiredText(source.carrierRut, 15, 'transport.carrierRut')).formatted, licensePlate: requiredText(source.licensePlate, 8, 'transport.licensePlate'), driverRut: (0, rut_1.parseRut)(requiredText(source.driverRut, 15, 'transport.driverRut')).formatted, driverName: requiredText(source.driverName, 30, 'transport.driverName') });
|
|
187
|
+
}
|
|
188
|
+
/** Tipo 33, IVA 19%, con opcionales explícitos del facturador gratuito. */
|
|
88
189
|
function validateInvoice(input) {
|
|
89
|
-
const source = record(input, ['issuedDate', 'issuer', 'receiver', 'paymentForm', 'saleType', 'purchaseType', 'items'], 'input');
|
|
90
|
-
const issuer = record(source.issuer, ['address', 'commune', 'city', 'activityCode'], 'issuer');
|
|
190
|
+
const source = record(input, ['issuedDate', 'issuer', 'receiver', 'paymentForm', 'saleType', 'purchaseType', 'items', 'globalDiscount', 'references', 'payments', 'requesterRut', 'transport', 'smallBusiness'], 'input');
|
|
191
|
+
const issuer = record(source.issuer, ['address', 'commune', 'city', 'activityCode', 'email', 'phone'], 'issuer');
|
|
91
192
|
const receiver = record(source.receiver, ['rut', 'legalName', 'address', 'commune', 'city', 'businessActivity', 'contact'], 'receiver');
|
|
92
193
|
const activityCode = requiredText(issuer.activityCode, 6, 'activityCode');
|
|
93
194
|
if (!/^\d{6}$/u.test(activityCode))
|
|
94
195
|
invalid('activityCode');
|
|
95
196
|
const paymentForm = source.paymentForm, saleType = source.saleType, purchaseType = source.purchaseType;
|
|
96
|
-
if (paymentForm !== 1 && paymentForm !== 2)
|
|
197
|
+
if (paymentForm !== 1 && paymentForm !== 2 && paymentForm !== 3)
|
|
97
198
|
invalid('paymentForm');
|
|
98
|
-
if (saleType !== 1 && saleType !== 2)
|
|
199
|
+
if (saleType !== 1 && saleType !== 2 && saleType !== 3)
|
|
99
200
|
invalid('saleType');
|
|
100
201
|
if (purchaseType !== 1 && purchaseType !== 2 && purchaseType !== 3 && purchaseType !== 4 && purchaseType !== 5 && purchaseType !== 6 && purchaseType !== 7)
|
|
101
202
|
invalid('purchaseType');
|
|
102
203
|
const lines = items(source.items);
|
|
103
|
-
|
|
204
|
+
const discount = globalDiscount(source.globalDiscount);
|
|
205
|
+
const totals = invoiceBreakdown(lines, discount).totals;
|
|
206
|
+
const issued = civilDate(source.issuedDate, 'issuedDate', '2017-01-01');
|
|
207
|
+
const email = text(issuer.email, 30, 'issuer.email', true), phone = text(issuer.phone, 14, 'issuer.phone', true);
|
|
208
|
+
if (email !== undefined && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(email))
|
|
209
|
+
invalid('issuer.email');
|
|
210
|
+
if (phone !== undefined && !/^\d[\d ]*$/u.test(phone))
|
|
211
|
+
invalid('issuer.phone');
|
|
212
|
+
if (source.smallBusiness !== undefined && typeof source.smallBusiness !== 'boolean')
|
|
213
|
+
invalid('smallBusiness');
|
|
104
214
|
const contact = text(receiver.contact, 80, 'contact', true);
|
|
105
215
|
const result = {
|
|
106
|
-
issuedDate:
|
|
216
|
+
issuedDate: issued,
|
|
107
217
|
issuer: Object.freeze({
|
|
108
218
|
address: requiredText(issuer.address, 70, 'issuer.address'),
|
|
109
219
|
commune: requiredText(issuer.commune, 20, 'issuer.commune'),
|
|
110
220
|
city: requiredText(issuer.city, 15, 'issuer.city'), activityCode,
|
|
221
|
+
...(email === undefined ? {} : { email }), ...(phone === undefined ? {} : { phone }),
|
|
111
222
|
}),
|
|
112
223
|
receiver: Object.freeze({
|
|
113
224
|
rut: (0, rut_1.parseRut)(requiredText(receiver.rut, 15, 'receiver.rut')).formatted,
|
|
@@ -119,12 +230,18 @@ function validateInvoice(input) {
|
|
|
119
230
|
...(contact === undefined ? {} : { contact }),
|
|
120
231
|
}),
|
|
121
232
|
paymentForm, saleType, purchaseType, items: lines,
|
|
233
|
+
...(discount === undefined ? {} : { globalDiscount: discount }),
|
|
234
|
+
...(source.references === undefined ? {} : { references: references(source.references) }),
|
|
235
|
+
...(source.payments === undefined ? {} : { payments: payments(source.payments, issued, totals.totalAmount) }),
|
|
236
|
+
...(source.transport === undefined ? {} : { transport: transport(source.transport) }),
|
|
237
|
+
...(source.requesterRut === undefined ? {} : { requesterRut: (0, rut_1.parseRut)(requiredText(source.requesterRut, 15, 'requesterRut')).formatted }),
|
|
238
|
+
...(source.smallBusiness === undefined ? {} : { smallBusiness: source.smallBusiness }),
|
|
122
239
|
};
|
|
123
240
|
Object.freeze(result.items);
|
|
124
241
|
return Object.freeze(result);
|
|
125
242
|
}
|
|
126
|
-
/** Redondea
|
|
127
|
-
function calculateInvoiceTotals(input) { return
|
|
243
|
+
/** Redondea líneas, descuento global, IVA e impuestos adicionales sin decimales binarios. */
|
|
244
|
+
function calculateInvoiceTotals(input, discount) { return invoiceBreakdown(items(input), globalDiscount(discount)).totals; }
|
|
128
245
|
/** Huella determinista del contenido fiscal; el llamador excluye claves y tokens. */
|
|
129
246
|
function hashContent(value) {
|
|
130
247
|
const ancestors = new Set();
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { IssuedInvoice } from './issued-invoice';
|
|
2
|
+
export type RcvDocumentType = 33 | 34 | 61;
|
|
3
|
+
export interface RcvDocumentsQuery {
|
|
4
|
+
periodo: string;
|
|
5
|
+
tokenRecaptcha?: string;
|
|
6
|
+
}
|
|
7
|
+
export interface RcvDocument extends Omit<IssuedInvoice, 'documentType'> {
|
|
8
|
+
documentType: RcvDocumentType;
|
|
9
|
+
issuerName?: string | null;
|
|
10
|
+
}
|
|
11
|
+
export interface RcvDocumentsResult {
|
|
12
|
+
data: RcvDocument[];
|
|
13
|
+
complete: boolean;
|
|
14
|
+
expectedCount: number;
|
|
15
|
+
observedAt: string;
|
|
16
|
+
incompleteDocumentTypes: RcvDocumentType[];
|
|
17
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,19 +1,22 @@
|
|
|
1
1
|
export { SiiClient, SiiError } from './infrastructure/sii-client';
|
|
2
2
|
export { sanitizeSiiDiagnostics } from './sii-error';
|
|
3
3
|
export type { SiiDiagnostics } from './sii-error';
|
|
4
|
+
export type { CompanyInfo } from './domain/company-info';
|
|
5
|
+
export type { RcvDocumentType, RcvDocument, RcvDocumentsQuery, RcvDocumentsResult } from './domain/rcv-document';
|
|
6
|
+
export type { DocumentQueryOptions, DocumentDirection, DocumentIdentity, DocumentStatusQuery, DocumentVerification, DocumentStatusResult, RecipientEventsQuery, RecipientEvent, RecipientEventsResult, } from './domain/document-status';
|
|
4
7
|
export type { IssuedInvoicePdfQuery, ReceivedInvoicePdfQuery, PdfDownloadOptions, InvoicePdfResult } from './contracts';
|
|
5
8
|
export { parseRut } from './domain/rut';
|
|
6
|
-
export { validateInvoice, calculateInvoiceTotals, hashContent, validarFactura, calcularTotalesFactura, hashContenido } from './domain/invoicing';
|
|
7
|
-
export type { InvoiceInput, InvoiceLineInput, InvoiceTotals, EntradaFactura, LineaFactura, TotalesFactura } from './domain/invoicing';
|
|
9
|
+
export { validateInvoice, calculateInvoiceTotals, hashContent, INVOICE_ADDITIONAL_TAX_RATES, validarFactura, calcularTotalesFactura, hashContenido } from './domain/invoicing';
|
|
10
|
+
export type { InvoiceInput, InvoiceLineInput, InvoiceTotals, InvoiceAdditionalTaxCode, InvoiceGlobalDiscount, InvoiceReferenceDocumentType, InvoiceReferenceInput, InvoicePaymentInput, InvoiceTransportInput, EntradaFactura, LineaFactura, TotalesFactura } from './domain/invoicing';
|
|
8
11
|
export type { DocumentoPreparado, DocumentoFirmado, DocumentoEnviado, FirmaDocumento } from './infrastructure/sii-client';
|
|
9
12
|
export { parseDteXml, parseDteDocumentXml } from './infrastructure/dte-xml';
|
|
10
13
|
export { DteXmlError, MAX_DTE_XML_BYTES } from './domain/invoice-xml';
|
|
11
14
|
export type { ConsultaXmlFacturaEmitida, ConsultaXmlFacturaRecibida, DteInvoiceLine, DteInvoiceDetail, ResultadoXmlFacturaEmitida } from './domain/invoice-xml';
|
|
12
|
-
export type { TipoDocumentoEmitido, ConsultaXmlDocumentoEmitido, DteDocumentDetail, ResultadoXmlDocumentoEmitido } from './domain/invoice-xml';
|
|
15
|
+
export type { TipoDocumentoEmitido, ConsultaXmlDocumentoEmitido, DteDocumentDetail, DteIssuanceOptions, ResultadoXmlDocumentoEmitido } from './domain/invoice-xml';
|
|
13
16
|
export type { ConsultaFacturasEmitidas, FacturaEmitida, ResultadoFacturasEmitidas, TipoFacturaEmitida } from './domain/issued-invoice';
|
|
14
17
|
export type { ConsultaFacturasRecibidas, FacturaRecibida, ResultadoFacturasRecibidas } from './domain/received-invoice';
|
|
15
18
|
export type { ConsultaResumen, CredencialesSii, EmpresaAutorizada, EstadoCompra, Operacion, RegistroSii, RespuestaSii, SesionSii, SiiClientOptions, } from './infrastructure/sii-client';
|
|
16
19
|
export type { SummaryQuery, SiiCredentials, SiiSession, Operation, PurchaseStatus, SiiRecord, SiiResponse, AuthorizedCompany, PreparedDocument, SignedDocument, SentDocument, SignDocumentInput, } from './infrastructure/sii-client';
|
|
17
20
|
export type { IssuedInvoicesQuery, IssuedInvoice, IssuedInvoicesResult, InvoiceDocumentType, } from './domain/issued-invoice';
|
|
18
21
|
export type { ReceivedInvoicesQuery, ReceivedInvoice, ReceivedInvoicesResult, } from './domain/received-invoice';
|
|
19
|
-
export type { IssuedInvoiceXmlQuery, ReceivedInvoiceXmlQuery, InvoiceXmlResult, IssuedDocumentType, IssuedDocumentXmlQuery, IssuedDocumentXmlResult, } from './domain/invoice-xml';
|
|
22
|
+
export type { IssuedInvoiceXmlQuery, ReceivedInvoiceXmlQuery, InvoiceXmlResult, IssuedDocumentType, IssuedDocumentXmlQuery, ReceivedDocumentXmlQuery, IssuedDocumentXmlResult, } from './domain/invoice-xml';
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.MAX_DTE_XML_BYTES = exports.DteXmlError = exports.parseDteDocumentXml = exports.parseDteXml = exports.hashContenido = exports.calcularTotalesFactura = exports.validarFactura = exports.hashContent = exports.calculateInvoiceTotals = exports.validateInvoice = exports.parseRut = exports.sanitizeSiiDiagnostics = exports.SiiError = exports.SiiClient = void 0;
|
|
3
|
+
exports.MAX_DTE_XML_BYTES = exports.DteXmlError = exports.parseDteDocumentXml = exports.parseDteXml = exports.hashContenido = exports.calcularTotalesFactura = exports.validarFactura = exports.INVOICE_ADDITIONAL_TAX_RATES = exports.hashContent = exports.calculateInvoiceTotals = exports.validateInvoice = exports.parseRut = exports.sanitizeSiiDiagnostics = exports.SiiError = exports.SiiClient = void 0;
|
|
4
4
|
var sii_client_1 = require("./infrastructure/sii-client");
|
|
5
5
|
Object.defineProperty(exports, "SiiClient", { enumerable: true, get: function () { return sii_client_1.SiiClient; } });
|
|
6
6
|
Object.defineProperty(exports, "SiiError", { enumerable: true, get: function () { return sii_client_1.SiiError; } });
|
|
@@ -12,6 +12,7 @@ var invoicing_1 = require("./domain/invoicing");
|
|
|
12
12
|
Object.defineProperty(exports, "validateInvoice", { enumerable: true, get: function () { return invoicing_1.validateInvoice; } });
|
|
13
13
|
Object.defineProperty(exports, "calculateInvoiceTotals", { enumerable: true, get: function () { return invoicing_1.calculateInvoiceTotals; } });
|
|
14
14
|
Object.defineProperty(exports, "hashContent", { enumerable: true, get: function () { return invoicing_1.hashContent; } });
|
|
15
|
+
Object.defineProperty(exports, "INVOICE_ADDITIONAL_TAX_RATES", { enumerable: true, get: function () { return invoicing_1.INVOICE_ADDITIONAL_TAX_RATES; } });
|
|
15
16
|
Object.defineProperty(exports, "validarFactura", { enumerable: true, get: function () { return invoicing_1.validarFactura; } });
|
|
16
17
|
Object.defineProperty(exports, "calcularTotalesFactura", { enumerable: true, get: function () { return invoicing_1.calcularTotalesFactura; } });
|
|
17
18
|
Object.defineProperty(exports, "hashContenido", { enumerable: true, get: function () { return invoicing_1.hashContenido; } });
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { DocumentReadPort } from '../application/document-status';
|
|
2
|
+
import type { BoundDocumentStatusQuery, BoundRecipientEventsQuery, DocumentQueryOptions } from '../domain/document-status';
|
|
3
|
+
import { SiiHttpSession } from './sii-http-session';
|
|
4
|
+
/** Read-only personal queries; authentication and company authorization belong to the session. */
|
|
5
|
+
export declare class DocumentStatusGateway implements DocumentReadPort {
|
|
6
|
+
#private;
|
|
7
|
+
private readonly session;
|
|
8
|
+
constructor(session: SiiHttpSession);
|
|
9
|
+
get companyRut(): string;
|
|
10
|
+
assertReady(): void;
|
|
11
|
+
status(query: BoundDocumentStatusQuery, options?: DocumentQueryOptions): Promise<import("../domain/document-status").DocumentVerification>;
|
|
12
|
+
recipientEvents(query: BoundRecipientEventsQuery, options?: DocumentQueryOptions): Promise<import("../domain/document-status").RecipientEventsObservation>;
|
|
13
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DocumentStatusGateway = void 0;
|
|
4
|
+
const node_crypto_1 = require("node:crypto");
|
|
5
|
+
const rut_1 = require("../domain/rut");
|
|
6
|
+
const facturador_1 = require("./facturador");
|
|
7
|
+
const document_status_parser_1 = require("./document-status-parser");
|
|
8
|
+
const sii_http_session_1 = require("./sii-http-session");
|
|
9
|
+
/** Read-only personal queries; authentication and company authorization belong to the session. */
|
|
10
|
+
class DocumentStatusGateway {
|
|
11
|
+
session;
|
|
12
|
+
constructor(session) {
|
|
13
|
+
this.session = session;
|
|
14
|
+
}
|
|
15
|
+
get companyRut() { return this.session.company.formatted; }
|
|
16
|
+
assertReady() { this.session.assertReady(); }
|
|
17
|
+
status(query, options) {
|
|
18
|
+
return this.#read('QEstadoDTE', options?.signal, async (signal) => {
|
|
19
|
+
const actor = this.session.assertReady();
|
|
20
|
+
const fields = await this.session.request(sii_http_session_1.DOCUMENT_STATUS_FORM, async (response) => {
|
|
21
|
+
const html = await this.#html(response, 'DTEauth', signal);
|
|
22
|
+
return this.#parse('DTEauth', response, () => (0, document_status_parser_1.parseContentQueryForm)(html, actor.formatted));
|
|
23
|
+
}, { signal }, true);
|
|
24
|
+
const issuer = (0, rut_1.parseRut)(query.issuerRut), receiver = (0, rut_1.parseRut)(query.receiverRut);
|
|
25
|
+
const [year, month, day] = query.issuedDate.split('-');
|
|
26
|
+
for (const [key, value] of Object.entries({
|
|
27
|
+
rutQuery: actor.rut, dvQuery: actor.dv, rutCompany: issuer.rut, dvCompany: issuer.dv,
|
|
28
|
+
rutReceiver: receiver.rut, dvReceiver: receiver.dv, tipoDTE: String(query.documentType),
|
|
29
|
+
folioDTE: query.folio, fechaDTE: `${day}${month}${year}`, montoDTE: String(query.totalAmount),
|
|
30
|
+
}))
|
|
31
|
+
fields.set(key, value);
|
|
32
|
+
return this.session.request(sii_http_session_1.DOCUMENT_STATUS_URL, async (response) => {
|
|
33
|
+
const html = await this.#html(response, 'QEstadoDTE', signal);
|
|
34
|
+
return this.#parse('QEstadoDTE', response, () => (0, document_status_parser_1.parseDocumentVerification)(html));
|
|
35
|
+
}, { method: 'POST', signal, headers: {
|
|
36
|
+
'Content-Type': 'application/x-www-form-urlencoded', Accept: 'text/html',
|
|
37
|
+
Origin: 'https://palena.sii.cl', Referer: sii_http_session_1.DOCUMENT_STATUS_FORM,
|
|
38
|
+
}, body: fields.toString() }, true);
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
recipientEvents(query, options) {
|
|
42
|
+
return this.#read('validarAccesoReceptor', options?.signal, async (signal) => {
|
|
43
|
+
const actor = this.session.assertReady(), issuer = (0, rut_1.parseRut)(query.issuerRut);
|
|
44
|
+
await this.session.request(sii_http_session_1.RECIPIENT_EVENTS_PORTAL, async (response) => {
|
|
45
|
+
const html = await this.#html(response, 'registrorechazodtej6ui', signal);
|
|
46
|
+
this.#parse('registrorechazodtej6ui', response, () => (0, document_status_parser_1.assertDocumentQueryPage)(html));
|
|
47
|
+
}, { signal }, true);
|
|
48
|
+
const token = (await this.session.cookies(sii_http_session_1.RECIPIENT_EVENTS_URL)).find(cookie => cookie.key === 'TOKEN')?.value;
|
|
49
|
+
if (!token)
|
|
50
|
+
throw this.session.failure('SESSION_OR_INTERACTIVE_AUTH_REQUIRED', 'validarAccesoReceptor', 'SESSION_REQUIRED');
|
|
51
|
+
const body = JSON.stringify({
|
|
52
|
+
metaData: {
|
|
53
|
+
namespace: 'cl.sii.sdi.lob.diii.registrorechazodtej6.data.api.interfaces.FacadeService/validarAccesoReceptor',
|
|
54
|
+
conversationId: token, transactionId: (0, node_crypto_1.randomUUID)(), page: null,
|
|
55
|
+
},
|
|
56
|
+
data: { rutEmisor: issuer.rut, dvEmisor: issuer.dv, tipoDoc: query.documentType, folio: query.folio, rutToken: actor.rut, dvToken: actor.dv },
|
|
57
|
+
});
|
|
58
|
+
return this.session.request(sii_http_session_1.RECIPIENT_EVENTS_URL, async (response) => {
|
|
59
|
+
const mime = response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase();
|
|
60
|
+
if (mime === 'text/html') {
|
|
61
|
+
const html = await this.#html(response, 'validarAccesoReceptor', signal);
|
|
62
|
+
this.#parse('validarAccesoReceptor', response, () => (0, document_status_parser_1.assertDocumentQueryPage)(html));
|
|
63
|
+
}
|
|
64
|
+
const charset = /\bcharset\s*=\s*["']?([^;\s"']+)/i.exec(response.headers.get('content-type') ?? '')?.[1]?.toLowerCase();
|
|
65
|
+
if (mime !== 'application/json' || charset && !['utf-8', 'utf8'].includes(charset)) {
|
|
66
|
+
throw this.session.failure('SII_PROTOCOL_CHANGED', 'validarAccesoReceptor', 'INVALID_RESPONSE', response);
|
|
67
|
+
}
|
|
68
|
+
const value = await this.session.json(response, 'validarAccesoReceptor', signal);
|
|
69
|
+
return this.#parse('validarAccesoReceptor', response, () => (0, document_status_parser_1.parseRecipientEvents)(value));
|
|
70
|
+
}, { method: 'POST', signal, headers: {
|
|
71
|
+
'Content-Type': 'application/json', Accept: 'application/json, text/plain, */*',
|
|
72
|
+
Origin: 'https://www4.sii.cl', Referer: sii_http_session_1.RECIPIENT_EVENTS_PORTAL,
|
|
73
|
+
}, body }, true);
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
async #html(response, endpoint, signal) {
|
|
77
|
+
if (response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase() !== 'text/html' || !response.body) {
|
|
78
|
+
throw this.session.failure('SII_PROTOCOL_CHANGED', endpoint, 'INVALID_RESPONSE', response);
|
|
79
|
+
}
|
|
80
|
+
const bytes = await this.session.readBounded(response, endpoint, 1024 * 1024, 'SII_PROTOCOL_CHANGED', signal);
|
|
81
|
+
if (!bytes.length)
|
|
82
|
+
throw this.session.failure('SII_PROTOCOL_CHANGED', endpoint, 'EMPTY_RESPONSE', response, { responseType: 'EMPTY' });
|
|
83
|
+
const charset = (/\bcharset\s*=\s*["']?([^;\s"']+)/i.exec(response.headers.get('content-type') ?? '')?.[1]
|
|
84
|
+
?? /\bcharset\s*=\s*["']?([^;\s"'/>]+)/i.exec(Buffer.from(bytes.subarray(0, 4096)).toString('latin1'))?.[1]
|
|
85
|
+
?? 'windows-1252').toLowerCase();
|
|
86
|
+
try {
|
|
87
|
+
if (['windows-1252', 'iso-8859-1'].includes(charset))
|
|
88
|
+
return (0, facturador_1.readPortalHtml)(bytes);
|
|
89
|
+
if (['utf-8', 'utf8'].includes(charset))
|
|
90
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
91
|
+
}
|
|
92
|
+
catch { /* Reject bytes outside the declared encoding. */ }
|
|
93
|
+
throw this.session.failure('SII_PROTOCOL_CHANGED', endpoint, 'INVALID_RESPONSE', response, (0, sii_http_session_1.responseFormat)(response, bytes));
|
|
94
|
+
}
|
|
95
|
+
#parse(endpoint, response, parse) {
|
|
96
|
+
try {
|
|
97
|
+
return parse();
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
if (error instanceof document_status_parser_1.DocumentStatusProtocolError) {
|
|
101
|
+
const reason = error.code === 'CAPTCHA_INTERACTION_REQUIRED' ? 'CAPTCHA_REQUIRED'
|
|
102
|
+
: error.code === 'SESSION_OR_INTERACTIVE_AUTH_REQUIRED' ? 'SESSION_REQUIRED'
|
|
103
|
+
: error.code === 'SESSION_IDENTITY_MISMATCH' ? 'SESSION_IDENTITY_MISMATCH'
|
|
104
|
+
: error.code === 'SII_SERVICE_ERROR' ? 'PROVIDER_REJECTED' : 'INVALID_RESPONSE';
|
|
105
|
+
throw this.session.failure(error.code, endpoint, reason, response, { siiResponseCode: error.siiResponseCode });
|
|
106
|
+
}
|
|
107
|
+
throw this.session.failure('SII_PROTOCOL_CHANGED', endpoint, 'INVALID_RESPONSE', response);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
async #read(endpoint, signal, operation) {
|
|
111
|
+
if (!signal)
|
|
112
|
+
return operation();
|
|
113
|
+
// Caller-supplied abort reasons may contain secrets; only SDK diagnostics cross the boundary.
|
|
114
|
+
const controller = new AbortController();
|
|
115
|
+
const abort = () => controller.abort(this.session.failure('SII_OPERATION_ABORTED', endpoint, 'OPERATION_ABORTED'));
|
|
116
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
117
|
+
if (signal.aborted)
|
|
118
|
+
abort();
|
|
119
|
+
try {
|
|
120
|
+
return await operation(controller.signal);
|
|
121
|
+
}
|
|
122
|
+
finally {
|
|
123
|
+
signal.removeEventListener('abort', abort);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
exports.DocumentStatusGateway = DocumentStatusGateway;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { DocumentVerification, RecipientEventsObservation } from '../domain/document-status';
|
|
2
|
+
type ProtocolCode = 'SII_PROTOCOL_CHANGED' | 'SII_SERVICE_ERROR' | 'CAPTCHA_INTERACTION_REQUIRED' | 'SESSION_OR_INTERACTIVE_AUTH_REQUIRED' | 'SESSION_IDENTITY_MISMATCH';
|
|
3
|
+
export declare class DocumentStatusProtocolError extends Error {
|
|
4
|
+
readonly code: ProtocolCode;
|
|
5
|
+
readonly siiResponseCode?: number;
|
|
6
|
+
constructor(code?: ProtocolCode, siiResponseCode?: number);
|
|
7
|
+
}
|
|
8
|
+
export declare function assertDocumentQueryPage(html: string): void;
|
|
9
|
+
export declare function parseContentQueryForm(html: string, actorRut: string): URLSearchParams;
|
|
10
|
+
export declare function parseDocumentVerification(html: string): DocumentVerification;
|
|
11
|
+
export declare function parseRecipientEvents(value: unknown): RecipientEventsObservation;
|
|
12
|
+
export {};
|