@devly-cl/sii-client 0.7.1 → 0.7.9
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 +18 -1
- package/dist/domain/document.js +2 -0
- package/dist/domain/dte-reconciliation.d.ts +5 -0
- package/dist/domain/dte-reconciliation.js +351 -0
- package/dist/domain/invoice-xml.d.ts +99 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +4 -1
- package/dist/infrastructure/dte-xml.js +71 -28
- package/dist/infrastructure/facturador.d.ts +1 -1
- package/dist/infrastructure/facturador.js +4 -3
- package/dist/infrastructure/sii-http-session.js +55 -22
- package/dist/sii-error.d.ts +1 -0
- package/dist/sii-error.js +1 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -57,11 +57,26 @@ async function getInvoices(
|
|
|
57
57
|
|
|
58
58
|
Las consultas RCV reciben `{ periodo, tokenRecaptcha? }` y devuelven `{ data, complete, expectedCount, observedAt, incompleteDocumentTypes }`. El XML recibido requiere `{ issuerRut, documentType, folio }`; conserva las referencias del documento.
|
|
59
59
|
|
|
60
|
+
El detalle XML conserva, cuando existen, `nonBillableAmount` (`MontoNF`), `periodAmount` (`MontoPeriodo`), `previousBalance` (`SaldoAnterior`) y `payableAmount` (`VlrPagar`). Son totalizadores originales: no modifican `totalAmount`, no implican redondeo en efectivo y no autorizan emitir cargos adicionales. `nonBillableAmount` y `previousBalance` admiten signo; los consumidores deben conciliar las líneas y separar saldos de períodos anteriores.
|
|
61
|
+
|
|
62
|
+
Los parsers entregan además `detail.reconciliation`. `declared` conserva los totalizadores recibidos; `derived` contiene cantidades/precios decimales como strings, importes de línea conciliados, conversión bruto/neto, descuentos, impuestos adicionales o anticipados y montos no facturables. Los campos originales de `detail` y los bytes de `xml` no se reemplazan por cálculos. `normalizeDteFolio` normaliza identidades numéricas sin pasar por `Number`; `declaredFolio` conserva ceros iniciales cuando se normalizan el folio o sus referencias fiscales. Las referencias informativas de una NC se distinguen de sus referencias fiscales y los códigos de producto opcionales vacíos no eliminan el documento.
|
|
63
|
+
|
|
64
|
+
`reconcileDteDetail(detail)` permite conciliar también detalle declarado almacenado previamente. Su resultado es `RECONCILED` o `REVIEW_REQUIRED`; en revisión, `derived` es `null` y los diagnósticos explican el bloqueo. Reconoce métodos verificables de redondeo de descuentos/IVA, distribuye el neto declarado en líneas brutas y distingue redondeo por línea de redondeo del subtotal exacto. No aplica una tolerancia monetaria general, no inventa una línea para cerrar diferencias ni modifica IVA, impuestos o total declarado. Los códigos de impuesto desconocidos, alcances no soportados e inconsistencias sin explicación requieren revisión. Esta conciliación de lectura no certifica aceptación fiscal ni relaja las comprobaciones del contenido aprobado para emisión.
|
|
65
|
+
|
|
66
|
+
El diagnóstico `VAT_PRECISE_PRODUCTS` explica el IVA calculado sobre productos netos exactos antes de redondear la base. Requiere tasa, cantidades y precios originales, ausencia de ajustes globales efectivos, y que la base exacta redondeada coincida con el neto declarado. Excluye líneas no facturables y conserva todos los importes y bytes originales; una diferencia de un peso sin ese cálculo sigue requiriendo revisión.
|
|
67
|
+
|
|
68
|
+
La normalización de lectura puede entregar **observaciones no bloqueantes** en `derived.observations` (código, mensaje e importes declarado/calculado). `RECONCILED` indica que el modelo es representable y puede incluir esas observaciones; no acredita aceptación fiscal. Los valores del XML y sus diagnósticos se conservan, sin líneas artificiales ni cambios de IVA, impuestos o total.
|
|
69
|
+
|
|
70
|
+
Una diferencia de encabezado de **un peso por documento** conserva el total original con observación, siempre que líneas, subtotal, tasas y datos originales sean verificables y representables. Diferencias mayores y otros errores bloqueantes siguen en revisión. Sólo se añade `derived.totalRounding` cuando un cálculo exacto soportado reproduce ese total: conserva delta, método, base (`DECLARED_LINE_AMOUNTS` o `EXACT_PRODUCTS`) y suma de totalizadores. Requiere tasa de IVA declarada para líneas afectas y cantidades/precios originales para productos exactos; no utiliza conversiones brutas ni reparto supuesto de ajustes globales. La diferencia observada sin ese cálculo no se etiqueta como redondeo demostrado. Esta política de lectura no representa una tolerancia general del SII ni redondeo de pagos en efectivo.
|
|
71
|
+
|
|
72
|
+
Un ajuste global fijo con distintos códigos de impuesto genera la observación `GLOBAL_ADJUSTMENT_REQUIRES_PERCENT`, según la sección D del [formato DTE del SII](https://www.sii.cl/factura_electronica/factura_mercado/formato_dte_202602.pdf#page=44). Se conservan los impuestos originales sin inferir el reparto del ajuste entre sus bases. Las glosas comerciales no se transforman en descuentos estructurados. Tipos desconocidos, tasas/bases ausentes y defectos no representables siguen siendo bloqueantes.
|
|
73
|
+
|
|
60
74
|
Los nombres anteriores en español siguen disponibles como aliases de compatibilidad. La tabla describe este repositorio; las nuevas consultas de documentos RCV, XML recibido 33/34/61, estado y eventos no están incluidas en npm `0.6.0`.
|
|
61
75
|
|
|
62
76
|
## Integración
|
|
63
77
|
|
|
64
78
|
- Crear una instancia por empresa, identidad y operación. Usar acceso personal y esperar `dispose()` en `finally`; no compartir clientes autenticados entre tenants.
|
|
79
|
+
- `dispose()` confirma el logout remoto o rechaza con `SII_LOGOUT_FAILED`; libera cookies y recursos también si falla. Reintenta el cierre idempotente ante transporte o HTTP 429/502/503/504 hasta `retries + 1` veces, conservando las cookies durante esos intentos. Respeta `Retry-After` de hasta cinco segundos; esperas mayores quedan en `diagnostics.retryAfterMs` para que el consumidor programe una nueva lectura con otra instancia y sesión verificada. Un fallo de cierre detiene la operación actual. Si la operación ya falló, conservar ese error y registrar por separado el fallo de cierre. Un 302 de login sólo se acepta con destino HTTPS del SII, TOKEN y verificación posterior de identidad personal y empresa; no se sigue la redirección ni se reintenta el login.
|
|
65
80
|
- Pasar credenciales sólo por parámetros y mantenerlas en memoria. No persistir secretos ni registrar cuerpos HTTP.
|
|
66
81
|
- El backend gestiona RBAC, permisos por recurso/sucursal, auditoría, notificaciones e idempotencia. RCV contiene datos de toda la empresa: un permiso de sucursal no autoriza automáticamente su consulta completa.
|
|
67
82
|
- `complete`, `expectedCount` e `incompleteDocumentTypes` sólo cubren los tipos consultados: 33/34 en facturas, 33/34/61 en documentos. Comparar con `getSummary` para detectar otros tipos pendientes; no acreditan cobertura fiscal total. La identidad es `issuerRut + documentType + folio`.
|
|
@@ -73,11 +88,13 @@ Preparar → revisar y aprobar `contentHash` → firmar y enviar. `beforeSend` e
|
|
|
73
88
|
|
|
74
89
|
Ante `SII_ISSUANCE_OUTCOME_UNKNOWN`, bloquear una nueva emisión y reconciliar con el documento respaldado. `ENVIADO` confirma el envío observado; no acredita aceptación fiscal. Las consultas de estado mantienen `fiscalVerdict: 'NOT_OBSERVED'`.
|
|
75
90
|
|
|
91
|
+
`getCompanyInfo` conserva los domicilios y giros disponibles, también en empresas con muchas sucursales. Las tablas del portal admiten hasta 1000 domicilios y 100 giros, con un máximo de 256 KiB por tabla. Se mantienen los controles de identidad, estructura, tamaño de respuesta y rechazo de scripts ejecutables.
|
|
92
|
+
|
|
76
93
|
## Errores
|
|
77
94
|
|
|
78
95
|
Entradas inválidas generan `TypeError`. Fallos de sesión, proveedor o protocolo generan `SiiError` con `code`, `description` y `diagnostics` opcionales saneados.
|
|
79
96
|
|
|
80
|
-
Sólo lecturas conocidas admiten reintentos automáticos. Login, selección de empresa, preparación, firma y envío no se reintentan. CAPTCHA requiere intervención del consumidor.
|
|
97
|
+
Sólo lecturas conocidas y el cierre idempotente admiten reintentos automáticos. Login, selección de empresa, preparación, firma y envío no se reintentan. CAPTCHA requiere intervención del consumidor.
|
|
81
98
|
|
|
82
99
|
## Referencias
|
|
83
100
|
|
package/dist/domain/document.js
CHANGED
|
@@ -9,6 +9,8 @@ class DocumentContentMismatchError extends Error {
|
|
|
9
9
|
exports.DocumentContentMismatchError = DocumentContentMismatchError;
|
|
10
10
|
function assertApprovedDocument(document, approved) {
|
|
11
11
|
const d = document.detail;
|
|
12
|
+
if (d.nonBillableAmount || d.previousBalance || (d.periodAmount != null && d.periodAmount !== 0 && d.periodAmount !== d.totalAmount) || (d.payableAmount != null && d.payableAmount !== 0 && d.payableAmount !== d.totalAmount))
|
|
13
|
+
throw new DocumentContentMismatchError();
|
|
12
14
|
const decimal = (value) => value == null ? null : value.replace(/^0+(?=\d)/, '').replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '');
|
|
13
15
|
if (d.issuerRut !== approved.issuerRut || d.receiverRut !== approved.receiverRut || d.documentType !== approved.documentType || d.issuedDate !== approved.issuedDate || d.netAmount !== approved.netAmount || d.vatAmount !== approved.vatAmount || d.totalAmount !== approved.totalAmount || Number(d.vatRate) !== 19 || d.exemptAmount || d.fiscalHeader?.noDebitReduction != null || d.fiscalHeader?.unapprovedFiscalFields.length || d.issuanceOptions?.unapprovedFields.length)
|
|
14
16
|
throw new DocumentContentMismatchError();
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { DteFiscalDetail, DteReconciliation } from './invoice-xml';
|
|
2
|
+
/** Positive numeric identity, independent of presentation and JavaScript integer precision. */
|
|
3
|
+
export declare function normalizeDteFolio(value: string): string;
|
|
4
|
+
/** Pure read normalization. Inconsistencies produce diagnostics, never amended declared totals. */
|
|
5
|
+
export declare function reconcileDteDetail(detail: DteFiscalDetail): DteReconciliation;
|
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.normalizeDteFolio = normalizeDteFolio;
|
|
4
|
+
exports.reconcileDteDetail = reconcileDteDetail;
|
|
5
|
+
class Review extends Error {
|
|
6
|
+
code;
|
|
7
|
+
amounts;
|
|
8
|
+
constructor(code, message, amounts) {
|
|
9
|
+
super(message);
|
|
10
|
+
this.code = code;
|
|
11
|
+
this.amounts = amounts;
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
function fail(code, message, amounts) { throw new Review(code, message, amounts); }
|
|
15
|
+
const gcd = (a, b) => { while (b)
|
|
16
|
+
[a, b] = [b, a % b]; return a < 0n ? -a : a; };
|
|
17
|
+
const fraction = (n, d = 1n) => { const divisor = gcd(n, d); return { n: n / divisor, d: d / divisor }; };
|
|
18
|
+
const add = (a, b) => fraction(a.n * b.d + b.n * a.d, a.d * b.d);
|
|
19
|
+
const multiply = (a, b) => fraction(a.n * b.n, a.d * b.d);
|
|
20
|
+
const round = (v) => v.n < 0n ? -round({ n: -v.n, d: v.d }) : (v.n * 2n + v.d) / (v.d * 2n);
|
|
21
|
+
function decimal(value) {
|
|
22
|
+
if (typeof value !== 'string' || value.length > 40 || !/^\d+(?:\.\d+)?$/.test(value))
|
|
23
|
+
fail('INVALID_DECIMAL', 'Valor decimal XML inválido o fuera de precisión.');
|
|
24
|
+
const [whole, part = ''] = value.split('.');
|
|
25
|
+
return fraction(BigInt(whole + part), 10n ** BigInt(part.length));
|
|
26
|
+
}
|
|
27
|
+
function money(value, signed = false) {
|
|
28
|
+
if (!Number.isSafeInteger(value) || (!signed && value < 0))
|
|
29
|
+
fail('INVALID_AMOUNT', 'Importe XML fuera del rango entero seguro.');
|
|
30
|
+
return value;
|
|
31
|
+
}
|
|
32
|
+
function moneySum(values, signed = false) {
|
|
33
|
+
return money(Number(values.reduce((sum, value) => sum + BigInt(money(value, true)), 0n)), signed);
|
|
34
|
+
}
|
|
35
|
+
function decimalText(value, places = 6) {
|
|
36
|
+
const scale = 10n ** BigInt(places), scaled = round(multiply(value, fraction(scale)));
|
|
37
|
+
return `${scaled / scale}.${String(scaled % scale).padStart(places, '0')}`.replace(/\.?0+$/, '');
|
|
38
|
+
}
|
|
39
|
+
/** Positive numeric identity, independent of presentation and JavaScript integer precision. */
|
|
40
|
+
function normalizeDteFolio(value) {
|
|
41
|
+
if (typeof value !== 'string' || !/^\d{1,20}$/.test(value) || BigInt(value) === 0n)
|
|
42
|
+
throw new Error('SII_FOLIO_INVALID');
|
|
43
|
+
return BigInt(value).toString();
|
|
44
|
+
}
|
|
45
|
+
function lineAdjustment(gross, price, quantity, percent, declared, kind, info) {
|
|
46
|
+
const amount = money(declared ?? 0), pct = decimal(percent ?? '0');
|
|
47
|
+
if (pct.n > pct.d * 100n)
|
|
48
|
+
fail('INVALID_PERCENT', 'Porcentaje de ajuste de línea fuera de rango.');
|
|
49
|
+
if (!pct.n)
|
|
50
|
+
return amount;
|
|
51
|
+
if (declared === null)
|
|
52
|
+
fail('MISSING_ADJUSTMENT_AMOUNT', 'El porcentaje de línea requiere su monto declarado.');
|
|
53
|
+
const rate = fraction(pct.n, pct.d * 100n), unit = multiply(price, rate);
|
|
54
|
+
const candidates = [
|
|
55
|
+
['PERCENT_OF_PRODUCT', round(multiply(gross, rate))],
|
|
56
|
+
['PERCENT_OF_ROUNDED_PRODUCT', round(multiply(fraction(round(gross)), rate))],
|
|
57
|
+
['PER_UNIT_ROUNDING', round(multiply(quantity, fraction(round(multiply(unit, fraction(100n))), 100n)))],
|
|
58
|
+
['PER_UNIT_TRUNCATION', round(multiply(quantity, fraction(unit.n * 100n / unit.d, 100n)))],
|
|
59
|
+
['NET_FIRST_ROUNDING', kind === 'DISCOUNT' ? round(gross) - round(multiply(gross, fraction(rate.d - rate.n, rate.d))) : round(multiply(gross, fraction(rate.d + rate.n, rate.d))) - round(gross)],
|
|
60
|
+
];
|
|
61
|
+
const matched = candidates.find(([, value]) => value === BigInt(amount));
|
|
62
|
+
if (!matched)
|
|
63
|
+
fail('LINE_ADJUSTMENT_MISMATCH', 'El monto del descuento o recargo de línea no coincide con el porcentaje informado.');
|
|
64
|
+
if (matched[0] !== 'PERCENT_OF_PRODUCT')
|
|
65
|
+
info(`${kind}_${matched[0]}`, 'El ajuste declarado concilia con un método de redondeo distinto al porcentaje del producto exacto.');
|
|
66
|
+
return amount;
|
|
67
|
+
}
|
|
68
|
+
/** Largest remainder allocation, with stable original order as the tie breaker. */
|
|
69
|
+
function allocate(weights, target) {
|
|
70
|
+
const total = weights.reduce((s, w) => s + BigInt(w), 0n);
|
|
71
|
+
if (!total) {
|
|
72
|
+
if (target)
|
|
73
|
+
fail('GROSS_ALLOCATION_MISMATCH', 'No hay base para distribuir el neto fiscal.');
|
|
74
|
+
return weights.map(() => 0);
|
|
75
|
+
}
|
|
76
|
+
const parts = weights.map((w, index) => { const product = BigInt(w) * BigInt(target); return { index, amount: Number(product / total), remainder: product % total }; });
|
|
77
|
+
const remaining = target - parts.reduce((s, p) => s + p.amount, 0);
|
|
78
|
+
const ranked = [...parts].sort((a, b) => a.remainder === b.remainder ? a.index - b.index : a.remainder > b.remainder ? -1 : 1);
|
|
79
|
+
for (let i = 0; i < remaining; i++)
|
|
80
|
+
ranked[i].amount++;
|
|
81
|
+
return parts.map(p => p.amount);
|
|
82
|
+
}
|
|
83
|
+
/** Pure read normalization. Inconsistencies produce diagnostics, never amended declared totals. */
|
|
84
|
+
function reconcileDteDetail(detail) {
|
|
85
|
+
const diagnostics = [];
|
|
86
|
+
const declared = {
|
|
87
|
+
netAmount: detail.netAmount, exemptAmount: detail.exemptAmount, vatAmount: detail.vatAmount, totalAmount: detail.totalAmount,
|
|
88
|
+
nonBillableAmount: detail.nonBillableAmount ?? null, periodAmount: detail.periodAmount ?? null, previousBalance: detail.previousBalance ?? null, payableAmount: detail.payableAmount ?? null,
|
|
89
|
+
grossAmounts: detail.grossAmounts ?? null,
|
|
90
|
+
};
|
|
91
|
+
try {
|
|
92
|
+
return { version: 1, status: 'RECONCILED', declared, derived: reconcile(detail, diagnostics), diagnostics };
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
if (!(error instanceof Review))
|
|
96
|
+
throw error;
|
|
97
|
+
if (!diagnostics.some(d => d.severity === 'ERROR' && d.code === error.code))
|
|
98
|
+
diagnostics.push({ code: error.code, severity: 'ERROR', message: error.message, ...error.amounts });
|
|
99
|
+
return { version: 1, status: 'REVIEW_REQUIRED', declared, derived: null, diagnostics };
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
function reconcile(detail, diagnostics) {
|
|
103
|
+
const info = (code, message, lineNumber, amounts) => diagnostics.push({ code, severity: 'INFO', message, ...(lineNumber !== undefined ? { lineNumber } : {}), ...amounts });
|
|
104
|
+
if (![33, 34, 61].includes(detail.documentType))
|
|
105
|
+
fail('UNSUPPORTED_DOCUMENT', 'Tipo de documento fuera del alcance de conciliación.');
|
|
106
|
+
if (!detail.lines.length || detail.lines.length > 1000)
|
|
107
|
+
fail('INVALID_LINES', 'Documento sin líneas o con demasiadas líneas.');
|
|
108
|
+
if (detail.documentType === 61 && !detail.references.some(r => /^\d{1,3}$/.test(r.documentType) && Number(r.documentType) < 200 && Number(r.documentType) > 0 && /^[1-9]\d{0,19}$/.test(r.folio) && [1, 2, 3].includes(r.code ?? 0) && r.date <= detail.issuedDate))
|
|
109
|
+
fail('INVALID_FISCAL_REFERENCE', 'La nota de crédito requiere una referencia fiscal original válida.');
|
|
110
|
+
const netAmount = money(detail.netAmount ?? 0), exemptAmount = money(detail.exemptAmount ?? 0), vatAmount = money(detail.vatAmount ?? 0), totalAmount = money(detail.totalAmount);
|
|
111
|
+
if ((detail.documentType === 34 && (netAmount || vatAmount)) || (netAmount && exemptAmount))
|
|
112
|
+
fail('UNSUPPORTED_TAX_SPLIT', 'La combinación de importes afectos y exentos requiere revisión.');
|
|
113
|
+
const exempt = detail.documentType === 34 || (!netAmount && exemptAmount > 0);
|
|
114
|
+
const taxes = detail.taxes.map(tax => {
|
|
115
|
+
if (![18, 23, 24, 25, 26, 27, 271].includes(tax.type))
|
|
116
|
+
fail('UNSUPPORTED_TAX', 'Código de impuesto o retención fuera del alcance de conciliación.');
|
|
117
|
+
money(tax.amount);
|
|
118
|
+
if (tax.rate !== null)
|
|
119
|
+
decimal(tax.rate);
|
|
120
|
+
return { ...tax, kind: tax.type === 18 ? 'ANTICIPATED' : 'ADDITIONAL' };
|
|
121
|
+
});
|
|
122
|
+
if (new Set(taxes.map(t => t.type)).size !== taxes.length)
|
|
123
|
+
fail('DUPLICATE_TAX_TYPE', 'Un mismo impuesto de encabezado aparece más de una vez; requiere revisión de su base.');
|
|
124
|
+
const headerTotal = moneySum([netAmount, exemptAmount, vatAmount, ...taxes.map(t => t.amount)]);
|
|
125
|
+
if (headerTotal !== totalAmount)
|
|
126
|
+
diagnostics.push({ code: 'HEADER_TOTAL_MISMATCH', severity: 'ERROR', message: 'Subtotal, IVA e impuestos adicionales XML no cuadran con el total fiscal.', declaredAmount: totalAmount, derivedAmount: headerTotal });
|
|
127
|
+
const rate = decimal(detail.vatRate ?? (vatAmount ? '19' : '0'));
|
|
128
|
+
const expectedVat = round(multiply(fraction(BigInt(netAmount)), fraction(rate.n, rate.d * 100n)));
|
|
129
|
+
const precise = [];
|
|
130
|
+
let lines = detail.lines.map((source, index) => {
|
|
131
|
+
const lineNumber = source.lineNumber ?? index + 1, quantityText = source.quantity ?? '1', quantity = decimal(quantityText);
|
|
132
|
+
if (!quantity.n)
|
|
133
|
+
fail('INVALID_QUANTITY', 'La cantidad XML debe ser mayor a cero.');
|
|
134
|
+
const amount = money(source.amount), indicator = source.exemptIndicator ?? 0;
|
|
135
|
+
if (![0, 1, 2, 6].includes(indicator))
|
|
136
|
+
fail('UNSUPPORTED_EXEMPT_INDICATOR', 'Indicador de exención o no facturable fuera del alcance de conciliación.');
|
|
137
|
+
if (!exempt && indicator === 1)
|
|
138
|
+
fail('UNSUPPORTED_TAX_SPLIT', 'Las líneas exentas y afectas requieren conciliación separada.');
|
|
139
|
+
let priceText = source.unitPrice;
|
|
140
|
+
if (priceText === null) {
|
|
141
|
+
if (source.discountAmount || source.discountPercent && decimal(source.discountPercent).n || source.surchargeAmount || source.surchargePercent && decimal(source.surchargePercent).n)
|
|
142
|
+
fail('MISSING_UNIT_PRICE', 'Línea sin precio unitario verificable.');
|
|
143
|
+
priceText = decimalText(fraction(BigInt(amount) * quantity.d, quantity.n));
|
|
144
|
+
info('DERIVED_UNIT_PRICE', 'Precio unitario derivado del importe declarado y la cantidad.', lineNumber);
|
|
145
|
+
}
|
|
146
|
+
const price = decimal(priceText), gross = multiply(quantity, price);
|
|
147
|
+
const lineInfo = (code, message) => info(code, message, lineNumber);
|
|
148
|
+
const discount = lineAdjustment(gross, price, quantity, source.discountPercent, source.discountAmount, 'DISCOUNT', lineInfo);
|
|
149
|
+
const surcharge = lineAdjustment(gross, price, quantity, source.surchargePercent, source.surchargeAmount, 'SURCHARGE', lineInfo);
|
|
150
|
+
if (BigInt(discount) > round(gross))
|
|
151
|
+
fail('LINE_DISCOUNT_EXCEEDS_GROSS', 'El descuento supera el importe de la línea.');
|
|
152
|
+
if (round(gross) - BigInt(discount) + BigInt(surcharge) !== BigInt(amount))
|
|
153
|
+
fail('LINE_AMOUNT_MISMATCH', 'Cantidad, precio, descuento y recargo no cuadran con MontoItem.');
|
|
154
|
+
precise.push(add(gross, fraction(BigInt(surcharge - discount))));
|
|
155
|
+
return { lineNumber, quantity: quantityText, unitPrice: priceText, discountPercent: source.discountPercent ?? '0', discountAmount: discount, surchargeAmount: surcharge, netAmount: amount, declaredAmount: amount, category: indicator === 2 ? 'NON_BILLABLE' : indicator === 6 ? 'NON_BILLABLE_DEDUCTION' : exempt || indicator === 1 ? 'EXEMPT' : 'TAXABLE' };
|
|
156
|
+
});
|
|
157
|
+
const nonBillableLines = lines.filter(l => l.category === 'NON_BILLABLE' || l.category === 'NON_BILLABLE_DEDUCTION').map(l => ({ lineNumber: l.lineNumber, amount: l.netAmount, indicator: l.category === 'NON_BILLABLE' ? 2 : 6 }));
|
|
158
|
+
const nonBillableAmount = moneySum(nonBillableLines.map(l => l.amount * (l.indicator === 6 ? -1 : 1)), true);
|
|
159
|
+
if (nonBillableAmount !== money(detail.nonBillableAmount ?? 0, true) || (detail.nonBillableAmount && !nonBillableLines.length))
|
|
160
|
+
fail('NON_BILLABLE_MISMATCH', 'El monto no facturable no cuadra con las líneas XML.');
|
|
161
|
+
const periodAmount = moneySum([totalAmount, nonBillableAmount]);
|
|
162
|
+
const payableAmount = moneySum([periodAmount, detail.previousBalance ?? 0]);
|
|
163
|
+
if (detail.periodAmount && detail.periodAmount !== periodAmount || detail.payableAmount && detail.payableAmount !== payableAmount)
|
|
164
|
+
fail('PAYABLE_TOTAL_MISMATCH', 'El valor a pagar no cuadra con los totalizadores XML.');
|
|
165
|
+
for (const [field, expected] of [['periodAmount', periodAmount], ['payableAmount', payableAmount]]) {
|
|
166
|
+
if (detail[field] === 0 && expected !== 0)
|
|
167
|
+
info('ZERO_OPTIONAL_PAYMENT_TOTAL', `Totalizador opcional ${field} en cero conservado como declarado; el valor derivado no acredita pagos.`, undefined, { declaredAmount: 0, derivedAmount: expected });
|
|
168
|
+
}
|
|
169
|
+
const fiscalLines = lines.filter(l => l.category !== 'NON_BILLABLE' && l.category !== 'NON_BILLABLE_DEDUCTION');
|
|
170
|
+
const lineTotal = money(fiscalLines.reduce((s, l) => s + l.netAmount, 0));
|
|
171
|
+
let discount = 0, globalSurcharge = 0;
|
|
172
|
+
for (const adjustment of detail.adjustments) {
|
|
173
|
+
if (!['D', 'R'].includes(adjustment.movement) || adjustment.exemptIndicator != null && !(exempt && adjustment.exemptIndicator === 1) || !['$', '%'].includes(adjustment.valueType))
|
|
174
|
+
fail('UNSUPPORTED_GLOBAL_ADJUSTMENT', 'El ajuste global requiere conciliación de su alcance y tipo.');
|
|
175
|
+
const value = decimal(adjustment.value);
|
|
176
|
+
if (adjustment.valueType === '$' && value.n % value.d || adjustment.valueType === '%' && value.n > value.d * 100n)
|
|
177
|
+
fail('INVALID_GLOBAL_DISCOUNT', 'El ajuste global requiere un importe entero CLP o un porcentaje entre cero y cien.');
|
|
178
|
+
const amount = adjustment.valueType === '$' ? Number(value.n / value.d) : Number(round(multiply(fraction(BigInt(lineTotal - discount + globalSurcharge)), fraction(value.n, value.d * 100n))));
|
|
179
|
+
if (adjustment.movement === 'D')
|
|
180
|
+
discount = money(discount + amount);
|
|
181
|
+
else
|
|
182
|
+
globalSurcharge = money(globalSurcharge + amount);
|
|
183
|
+
money(lineTotal - discount + globalSurcharge);
|
|
184
|
+
}
|
|
185
|
+
if (discount && globalSurcharge)
|
|
186
|
+
fail('MIXED_GLOBAL_ADJUSTMENTS', 'La combinación de descuentos y recargos globales requiere revisión de su distribución.');
|
|
187
|
+
const subtotal = netAmount + exemptAmount;
|
|
188
|
+
const inferred = detail.grossAmounts === undefined && !exempt && !taxes.length && !nonBillableLines.length && netAmount > 0 && vatAmount > 0 && rate.n === 19n * rate.d && lineTotal - discount + globalSurcharge === totalAmount;
|
|
189
|
+
if (BigInt(vatAmount) !== expectedVat) {
|
|
190
|
+
// Gross historic documents may total independently rounded VAT per line.
|
|
191
|
+
const truncatedVat = BigInt(vatAmount) === BigInt(netAmount) * rate.n / (rate.d * 100n);
|
|
192
|
+
const preciseNet = precise.reduce((sum, value, index) => lines[index].category === 'TAXABLE' ? add(sum, value) : sum, fraction(0n));
|
|
193
|
+
const preciseVat = !truncatedVat && !discount && !globalSurcharge && !exempt && !detail.grossAmounts && !inferred && detail.vatRate != null
|
|
194
|
+
&& detail.lines.every((source, index) => lines[index].category !== 'TAXABLE' || source.quantity != null && source.unitPrice != null)
|
|
195
|
+
&& round(preciseNet) === BigInt(netAmount) && round(multiply(preciseNet, fraction(rate.n, rate.d * 100n))) === BigInt(vatAmount);
|
|
196
|
+
const perLineVat = !truncatedVat && !discount && !globalSurcharge && (detail.grossAmounts || inferred) && !taxes.length
|
|
197
|
+
? ['NEAREST', 'CEILING', 'FLOOR', 'PER_UNIT_NEAREST'].find(method => fiscalLines.reduce((sum, line) => {
|
|
198
|
+
const value = fraction(BigInt(line.declaredAmount) * rate.n, rate.d * 100n + rate.n);
|
|
199
|
+
if (method === 'PER_UNIT_NEAREST') {
|
|
200
|
+
if (line.discountAmount || line.surchargeAmount)
|
|
201
|
+
return -1n;
|
|
202
|
+
const unitTax = round(multiply(decimal(line.unitPrice), fraction(rate.n, rate.d * 100n + rate.n)));
|
|
203
|
+
return sum + round(multiply(fraction(unitTax), decimal(line.quantity)));
|
|
204
|
+
}
|
|
205
|
+
return sum + (method === 'NEAREST' ? round(value) : method === 'CEILING' ? (value.n + value.d - 1n) / value.d : value.n / value.d);
|
|
206
|
+
}, 0n) === BigInt(vatAmount)) : undefined;
|
|
207
|
+
if (!truncatedVat && !perLineVat && !preciseVat)
|
|
208
|
+
fail('VAT_MISMATCH', 'El IVA del XML no cuadra con el neto fiscal y la tasa declarada.');
|
|
209
|
+
if (preciseVat)
|
|
210
|
+
info('VAT_PRECISE_PRODUCTS', 'El IVA declarado concilia al aplicar la tasa a la suma exacta de cantidad por precio y ajustes de línea, antes de redondear el neto.');
|
|
211
|
+
else
|
|
212
|
+
info(truncatedVat ? 'VAT_TRUNCATED' : `VAT_PER_GROSS_LINE_${perLineVat}`, truncatedVat ? 'El IVA declarado concilia con truncamiento del impuesto sobre el neto fiscal.' : 'El IVA declarado concilia al totalizar el impuesto por cada línea bruta.');
|
|
213
|
+
}
|
|
214
|
+
let globalDiscount;
|
|
215
|
+
let surcharge;
|
|
216
|
+
let lineRounding;
|
|
217
|
+
if (detail.grossAmounts || inferred) {
|
|
218
|
+
if (taxes.length || exempt || lineTotal - discount + globalSurcharge !== totalAmount)
|
|
219
|
+
fail('GROSS_TOTAL_MISMATCH', 'Las líneas y ajustes globales no cuadran con el total bruto del XML.');
|
|
220
|
+
const netBeforeDiscount = discount || globalSurcharge ? Number(round(fraction(BigInt(lineTotal) * rate.d * 100n, rate.d * 100n + rate.n))) : subtotal;
|
|
221
|
+
if (discount && netBeforeDiscount < subtotal || globalSurcharge && netBeforeDiscount > subtotal)
|
|
222
|
+
fail('GROSS_DISCOUNT_MISMATCH', 'El ajuste global bruto no conserva el neto fiscal.');
|
|
223
|
+
const allocated = allocate(fiscalLines.map(l => l.netAmount), netBeforeDiscount);
|
|
224
|
+
let fiscalIndex = 0;
|
|
225
|
+
lines = lines.map(l => {
|
|
226
|
+
if (l.category === 'NON_BILLABLE' || l.category === 'NON_BILLABLE_DEDUCTION')
|
|
227
|
+
return l;
|
|
228
|
+
const net = allocated[fiscalIndex++], quantity = decimal(l.quantity);
|
|
229
|
+
const lineDiscount = Number(round(fraction(BigInt(l.discountAmount) * rate.d * 100n, rate.d * 100n + rate.n)));
|
|
230
|
+
const surcharge = Number(round(fraction(BigInt(l.surchargeAmount) * rate.d * 100n, rate.d * 100n + rate.n)));
|
|
231
|
+
const price = decimalText(fraction(BigInt(net + lineDiscount - surcharge) * quantity.d, quantity.n));
|
|
232
|
+
if (round(multiply(quantity, decimal(price))) - BigInt(lineDiscount) + BigInt(surcharge) !== BigInt(net))
|
|
233
|
+
fail('GROSS_PRICE_PRECISION', 'La conversión de precio bruto no conserva el importe neto de línea.');
|
|
234
|
+
return { ...l, unitPrice: price, discountAmount: lineDiscount, surchargeAmount: surcharge, netAmount: net };
|
|
235
|
+
});
|
|
236
|
+
if (discount)
|
|
237
|
+
globalDiscount = { netAmount: netBeforeDiscount - subtotal, grossAmount: discount };
|
|
238
|
+
if (globalSurcharge)
|
|
239
|
+
surcharge = { netAmount: subtotal - netBeforeDiscount, grossAmount: globalSurcharge };
|
|
240
|
+
info(inferred ? 'GROSS_AMOUNTS_INFERRED' : 'GROSS_AMOUNTS_CONVERTED', 'Líneas brutas convertidas contra los totales fiscales declarados, conservando cantidades y XML.');
|
|
241
|
+
}
|
|
242
|
+
else {
|
|
243
|
+
if (discount)
|
|
244
|
+
globalDiscount = { netAmount: discount };
|
|
245
|
+
if (globalSurcharge)
|
|
246
|
+
surcharge = { netAmount: globalSurcharge };
|
|
247
|
+
if (lineTotal - discount + globalSurcharge !== subtotal) {
|
|
248
|
+
const preciseTotal = precise.reduce((s, v, index) => lines[index].category.startsWith('NON_BILLABLE') ? s : add(s, v), fraction(0n));
|
|
249
|
+
if (Number(round(preciseTotal)) - discount + globalSurcharge !== subtotal)
|
|
250
|
+
fail('LINE_SUBTOTAL_MISMATCH', 'Las líneas y ajustes XML no cuadran con el subtotal fiscal.');
|
|
251
|
+
lineRounding = subtotal - (lineTotal - discount + globalSurcharge);
|
|
252
|
+
info('PRECISE_SUBTOTAL_ROUNDING', 'El subtotal concilia al sumar los productos exactos antes de redondear, en lugar de sumar MontoItem redondeados.', undefined, { declaredAmount: subtotal, derivedAmount: lineTotal - discount + globalSurcharge });
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
for (const source of detail.lines) {
|
|
256
|
+
const codes = source.additionalTaxCodes ?? [];
|
|
257
|
+
if (codes.length > 2 || new Set(codes).size !== codes.length)
|
|
258
|
+
fail('INVALID_LINE_TAX_CODES', 'Códigos de impuesto de línea duplicados o fuera de alcance.');
|
|
259
|
+
for (const code of codes) {
|
|
260
|
+
if (![18, 23, 24, 25, 26, 27, 271].includes(code))
|
|
261
|
+
fail('UNSUPPORTED_LINE_TAX', 'Código de impuesto de línea fuera del alcance de conciliación.');
|
|
262
|
+
if (!taxes.some(t => t.type === code))
|
|
263
|
+
fail('MISSING_HEADER_TAX', 'Un impuesto de línea no tiene su monto declarado en el encabezado.');
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
const distinctCodes = new Set(detail.lines.flatMap(source => source.additionalTaxCodes ?? []));
|
|
267
|
+
const fixedMixedAdjustment = distinctCodes.size > 1 && detail.adjustments.some(adjustment => adjustment.valueType === '$' && decimal(adjustment.value).n !== 0n);
|
|
268
|
+
if (fixedMixedAdjustment) {
|
|
269
|
+
const code = 'GLOBAL_ADJUSTMENT_REQUIRES_PERCENT';
|
|
270
|
+
const message = 'El descuento o recargo global está expresado en un monto fijo para ítems con distintos impuestos. Se conservan los impuestos declarados; su reparto por línea no es verificable.';
|
|
271
|
+
diagnostics.unshift({ code, severity: 'INFO', message });
|
|
272
|
+
}
|
|
273
|
+
for (const tax of taxes) {
|
|
274
|
+
const scope = detail.lines.flatMap((source, index) => source.additionalTaxCodes?.includes(tax.type) ? [index] : []);
|
|
275
|
+
if (!scope.length || scope.some(i => lines[i].category !== 'TAXABLE'))
|
|
276
|
+
fail('MISSING_TAX_BASE', 'La base del impuesto adicional no puede identificarse en las líneas fiscales.');
|
|
277
|
+
if (tax.rate === null) {
|
|
278
|
+
if (tax.amount)
|
|
279
|
+
fail('MISSING_TAX_RATE', 'El impuesto adicional requiere su tasa declarada para conciliar la base.');
|
|
280
|
+
info('ZERO_TAX_WITHOUT_RATE', 'Impuesto declarado en cero sin tasa; no se deriva una tasa del documento.');
|
|
281
|
+
continue;
|
|
282
|
+
}
|
|
283
|
+
const percentage = decimal(tax.rate);
|
|
284
|
+
if (percentage.n > percentage.d * 100n)
|
|
285
|
+
fail('INVALID_TAX_RATE', 'Tasa de impuesto adicional fuera de alcance.');
|
|
286
|
+
if (!percentage.n && tax.amount)
|
|
287
|
+
fail('TAX_AMOUNT_MISMATCH', 'Un impuesto con tasa cero no puede tener un monto positivo.', { declaredAmount: tax.amount, derivedAmount: 0 });
|
|
288
|
+
if (!lineTotal && (discount || globalSurcharge))
|
|
289
|
+
fail('MISSING_TAX_BASE', 'No hay base de líneas para distribuir el ajuste global del impuesto.');
|
|
290
|
+
if (fixedMixedAdjustment)
|
|
291
|
+
continue;
|
|
292
|
+
const taxRate = fraction(percentage.n, percentage.d * 100n);
|
|
293
|
+
const prorate = (amount) => discount || globalSurcharge ? multiply(amount, fraction(BigInt(subtotal), BigInt(lineTotal))) : amount;
|
|
294
|
+
const base = prorate(fraction(scope.reduce((s, i) => s + BigInt(lines[i].netAmount), 0n)));
|
|
295
|
+
const computed = multiply(base, taxRate);
|
|
296
|
+
const exactBase = !detail.grossAmounts && !inferred ? prorate(scope.reduce((s, i) => add(s, precise[i]), fraction(0n))) : base;
|
|
297
|
+
const candidates = [
|
|
298
|
+
['GROUP_NEAREST', round(computed)],
|
|
299
|
+
['GROUP_TRUNCATED', computed.n / computed.d],
|
|
300
|
+
['GROUP_CEILING', (computed.n + computed.d - 1n) / computed.d],
|
|
301
|
+
['PRECISE_PRODUCTS', round(multiply(exactBase, taxRate))],
|
|
302
|
+
['PER_LINE_NEAREST', scope.reduce((s, i) => s + round(multiply(prorate(fraction(BigInt(lines[i].netAmount))), taxRate)), 0n)],
|
|
303
|
+
];
|
|
304
|
+
const method = candidates.find(([, value]) => value === BigInt(tax.amount));
|
|
305
|
+
if (!method)
|
|
306
|
+
fail(discount || globalSurcharge ? 'TAX_BASE_REVIEW_REQUIRED' : 'TAX_AMOUNT_MISMATCH', discount || globalSurcharge ? 'La distribución proporcional del ajuste global no explica el impuesto declarado; requiere verificar el alcance del ajuste sobre su base.' : 'El impuesto adicional no concilia con sus líneas y tasa declaradas.', { declaredAmount: tax.amount, derivedAmount: Number(round(computed)) });
|
|
307
|
+
if (method[0] !== 'GROUP_NEAREST')
|
|
308
|
+
info(`TAX_${method[0]}`, 'El impuesto adicional concilia con un método de redondeo distinto al del grupo de líneas.', undefined, { declaredAmount: tax.amount, derivedAmount: Number(round(computed)) });
|
|
309
|
+
}
|
|
310
|
+
let totalRounding;
|
|
311
|
+
if (headerTotal !== totalAmount) {
|
|
312
|
+
const difference = totalAmount - headerTotal;
|
|
313
|
+
// Global adjustments lack structured per-line allocation; never guess their scope to explain a total.
|
|
314
|
+
if ((difference === -1 || difference === 1) && !detail.adjustments.length && !detail.grossAmounts && !inferred && lineRounding === undefined && (!fiscalLines.some(line => line.category === 'TAXABLE') || detail.vatRate != null) && taxes.every(t => t.rate !== null)) {
|
|
315
|
+
const taxRates = new Map(taxes.map(t => { const percentage = decimal(t.rate); return [t.type, fraction(percentage.n, percentage.d * 100n)]; }));
|
|
316
|
+
const vatFactor = fraction(rate.d * 100n + rate.n, rate.d * 100n);
|
|
317
|
+
for (const basis of ['DECLARED_LINE_AMOUNTS', 'EXACT_PRODUCTS']) {
|
|
318
|
+
if (basis === 'EXACT_PRODUCTS' && detail.lines.some((source, i) => !lines[i].category.startsWith('NON_BILLABLE') && (source.unitPrice == null || source.quantity == null)))
|
|
319
|
+
continue;
|
|
320
|
+
let candidate = 0n;
|
|
321
|
+
for (let i = 0; i < lines.length; i++) {
|
|
322
|
+
const line = lines[i];
|
|
323
|
+
if (line.category.startsWith('NON_BILLABLE'))
|
|
324
|
+
continue;
|
|
325
|
+
const base = basis === 'DECLARED_LINE_AMOUNTS' ? fraction(BigInt(line.netAmount)) : precise[i];
|
|
326
|
+
candidate += round(line.category === 'EXEMPT' ? base : multiply(base, vatFactor));
|
|
327
|
+
for (const code of detail.lines[i].additionalTaxCodes ?? [])
|
|
328
|
+
candidate += round(multiply(base, taxRates.get(code)));
|
|
329
|
+
}
|
|
330
|
+
if (candidate === BigInt(totalAmount)) {
|
|
331
|
+
totalRounding = { difference, method: 'PER_LINE_VAT_AND_TAX', basis, componentTotal: headerTotal };
|
|
332
|
+
const diagnostic = diagnostics.find(d => d.code === 'HEADER_TOTAL_MISMATCH');
|
|
333
|
+
diagnostic.code = 'TOTAL_ROUNDING_EXPLAINED';
|
|
334
|
+
diagnostic.severity = 'INFO';
|
|
335
|
+
diagnostic.message = 'El total declarado concilia al sumar por línea el importe con IVA y sus impuestos adicionales redondeados. Se conservan todos los valores originales y la diferencia frente a sumar los totalizadores.';
|
|
336
|
+
break;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
if (!totalRounding) {
|
|
341
|
+
const originalLineValues = detail.lines.every((source, i) => lines[i].category.startsWith('NON_BILLABLE') || source.quantity != null && source.unitPrice != null);
|
|
342
|
+
if ((difference !== -1 && difference !== 1) || detail.grossAmounts || inferred || !originalLineValues || fiscalLines.some(line => line.category === 'TAXABLE') && detail.vatRate == null || taxes.some(t => t.rate === null))
|
|
343
|
+
fail('HEADER_TOTAL_MISMATCH', 'Subtotal, IVA e impuestos adicionales XML no cuadran con el total fiscal.', { declaredAmount: totalAmount, derivedAmount: headerTotal });
|
|
344
|
+
const diagnostic = diagnostics.find(d => d.code === 'HEADER_TOTAL_MISMATCH');
|
|
345
|
+
diagnostic.severity = 'INFO';
|
|
346
|
+
diagnostic.message = 'El total informado difiere en un peso de la suma del neto, exento, IVA e impuestos. Se conserva el total original del documento.';
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
const observations = diagnostics.filter(d => d.code === 'GLOBAL_ADJUSTMENT_REQUIRES_PERCENT' || d.code === 'HEADER_TOTAL_MISMATCH').map(({ code, message, declaredAmount, derivedAmount }) => ({ code, message, ...(declaredAmount !== undefined ? { declaredAmount } : {}), ...(derivedAmount !== undefined ? { derivedAmount } : {}) }));
|
|
350
|
+
return { netAmount, exemptAmount, vatAmount, totalAmount, payableAmount, lines, taxes, ...(globalDiscount ? { globalDiscount } : {}), ...(surcharge ? { globalSurcharge: surcharge } : {}), ...(nonBillableLines.length ? { nonBillable: { amount: nonBillableAmount, lines: nonBillableLines } } : {}), ...(inferred ? { grossAmountsInferred: true } : {}), ...(lineRounding !== undefined ? { lineRounding } : {}), ...(totalRounding ? { totalRounding } : {}), ...(observations.length ? { observations } : {}) };
|
|
351
|
+
}
|
|
@@ -32,6 +32,8 @@ export interface DteInvoiceLine {
|
|
|
32
32
|
surchargeAmount: number | null;
|
|
33
33
|
exemptIndicator: number | null;
|
|
34
34
|
amount: number;
|
|
35
|
+
/** Original per-line tax codes, when present. They do not replace the declared header taxes. */
|
|
36
|
+
additionalTaxCodes?: number[];
|
|
35
37
|
}
|
|
36
38
|
export interface DteInvoiceDetail {
|
|
37
39
|
/** Present only for MntBruto=1: line amounts/prices include VAT. Original fiscal totals are unchanged. */
|
|
@@ -39,6 +41,8 @@ export interface DteInvoiceDetail {
|
|
|
39
41
|
issuerRut: string;
|
|
40
42
|
documentType: InvoiceDocumentType;
|
|
41
43
|
folio: string;
|
|
44
|
+
/** Original spelling when numeric normalization removes leading zeroes. XML bytes are unchanged. */
|
|
45
|
+
declaredFolio?: string;
|
|
42
46
|
issuedDate: string;
|
|
43
47
|
receiverRut: string;
|
|
44
48
|
netAmount: number | null;
|
|
@@ -46,6 +50,11 @@ export interface DteInvoiceDetail {
|
|
|
46
50
|
vatRate: string | null;
|
|
47
51
|
vatAmount: number | null;
|
|
48
52
|
totalAmount: number;
|
|
53
|
+
/** Optional original totalizers; do not change the fiscal total or infer cash rounding. */
|
|
54
|
+
nonBillableAmount?: number;
|
|
55
|
+
periodAmount?: number;
|
|
56
|
+
previousBalance?: number;
|
|
57
|
+
payableAmount?: number;
|
|
49
58
|
lines: DteInvoiceLine[];
|
|
50
59
|
taxes: {
|
|
51
60
|
type: number;
|
|
@@ -64,11 +73,101 @@ export interface DteInvoiceDetail {
|
|
|
64
73
|
lineNumber: number;
|
|
65
74
|
documentType: string;
|
|
66
75
|
folio: string;
|
|
76
|
+
declaredFolio?: string;
|
|
67
77
|
date: string;
|
|
68
78
|
code: number | null;
|
|
69
79
|
reason: string | null;
|
|
70
80
|
}[];
|
|
81
|
+
/** Read reconciliation only. Never authorizes issuing or modifying a fiscal document. */
|
|
82
|
+
reconciliation?: DteReconciliation;
|
|
71
83
|
}
|
|
84
|
+
export interface DteReconciliationDiagnostic {
|
|
85
|
+
code: string;
|
|
86
|
+
severity: 'INFO' | 'ERROR';
|
|
87
|
+
message: string;
|
|
88
|
+
lineNumber?: number;
|
|
89
|
+
declaredAmount?: number;
|
|
90
|
+
derivedAmount?: number;
|
|
91
|
+
}
|
|
92
|
+
/** Non-blocking documentary observations; declared fiscal amounts remain authoritative. */
|
|
93
|
+
export type DteFiscalObservation = Pick<DteReconciliationDiagnostic, 'code' | 'message' | 'declaredAmount' | 'derivedAmount'>;
|
|
94
|
+
export interface DteReconciledLine {
|
|
95
|
+
lineNumber: number;
|
|
96
|
+
quantity: string;
|
|
97
|
+
unitPrice: string;
|
|
98
|
+
discountPercent: string;
|
|
99
|
+
discountAmount: number;
|
|
100
|
+
surchargeAmount: number;
|
|
101
|
+
netAmount: number;
|
|
102
|
+
/** MontoItem exactly as declared, even when the derived line is converted from gross to net. */
|
|
103
|
+
declaredAmount: number;
|
|
104
|
+
category: 'TAXABLE' | 'EXEMPT' | 'NON_BILLABLE' | 'NON_BILLABLE_DEDUCTION';
|
|
105
|
+
}
|
|
106
|
+
/** Derived explanation only; the original header and line amounts are never changed. */
|
|
107
|
+
export interface DteTotalRounding {
|
|
108
|
+
difference: -1 | 1;
|
|
109
|
+
method: 'PER_LINE_VAT_AND_TAX';
|
|
110
|
+
basis: 'DECLARED_LINE_AMOUNTS' | 'EXACT_PRODUCTS';
|
|
111
|
+
componentTotal: number;
|
|
112
|
+
}
|
|
113
|
+
export interface DteReconciledAmounts {
|
|
114
|
+
netAmount: number;
|
|
115
|
+
exemptAmount: number;
|
|
116
|
+
vatAmount: number;
|
|
117
|
+
totalAmount: number;
|
|
118
|
+
payableAmount: number;
|
|
119
|
+
lines: DteReconciledLine[];
|
|
120
|
+
taxes: {
|
|
121
|
+
type: number;
|
|
122
|
+
rate: string | null;
|
|
123
|
+
amount: number;
|
|
124
|
+
kind: 'ADDITIONAL' | 'ANTICIPATED';
|
|
125
|
+
}[];
|
|
126
|
+
globalDiscount?: {
|
|
127
|
+
netAmount: number;
|
|
128
|
+
grossAmount?: number;
|
|
129
|
+
};
|
|
130
|
+
globalSurcharge?: {
|
|
131
|
+
netAmount: number;
|
|
132
|
+
grossAmount?: number;
|
|
133
|
+
};
|
|
134
|
+
nonBillable?: {
|
|
135
|
+
amount: number;
|
|
136
|
+
lines: {
|
|
137
|
+
lineNumber: number;
|
|
138
|
+
amount: number;
|
|
139
|
+
indicator: 2 | 6;
|
|
140
|
+
}[];
|
|
141
|
+
};
|
|
142
|
+
grossAmountsInferred?: true;
|
|
143
|
+
/** Difference explained by summing exact source products before rounding the subtotal. */
|
|
144
|
+
lineRounding?: number;
|
|
145
|
+
/** At most one peso per document, explained by an exact supported line calculation. */
|
|
146
|
+
totalRounding?: DteTotalRounding;
|
|
147
|
+
observations?: DteFiscalObservation[];
|
|
148
|
+
}
|
|
149
|
+
export interface DteReconciliation {
|
|
150
|
+
version: 1;
|
|
151
|
+
status: 'RECONCILED' | 'REVIEW_REQUIRED';
|
|
152
|
+
/** Header values are never overwritten by calculations. Null means absent in the XML. */
|
|
153
|
+
declared: {
|
|
154
|
+
netAmount: number | null;
|
|
155
|
+
exemptAmount: number | null;
|
|
156
|
+
vatAmount: number | null;
|
|
157
|
+
totalAmount: number;
|
|
158
|
+
nonBillableAmount: number | null;
|
|
159
|
+
periodAmount: number | null;
|
|
160
|
+
previousBalance: number | null;
|
|
161
|
+
payableAmount: number | null;
|
|
162
|
+
grossAmounts: boolean | null;
|
|
163
|
+
};
|
|
164
|
+
derived: DteReconciledAmounts | null;
|
|
165
|
+
diagnostics: DteReconciliationDiagnostic[];
|
|
166
|
+
}
|
|
167
|
+
/** Fiscal parser model, also usable for reconciling previously stored declared detail. */
|
|
168
|
+
export type DteFiscalDetail = Omit<DteInvoiceDetail, 'documentType'> & {
|
|
169
|
+
documentType: number;
|
|
170
|
+
};
|
|
72
171
|
export interface InvoiceXmlResult {
|
|
73
172
|
/** Original bytes, including the original encoding and signatures. */
|
|
74
173
|
xml: Uint8Array;
|
package/dist/index.d.ts
CHANGED
|
@@ -10,6 +10,8 @@ export { validateInvoice, calculateInvoiceTotals, hashContent, INVOICE_ADDITIONA
|
|
|
10
10
|
export type { InvoiceInput, InvoiceLineInput, InvoiceTotals, InvoiceAdditionalTaxCode, InvoiceGlobalDiscount, InvoiceReferenceDocumentType, InvoiceReferenceInput, InvoicePaymentInput, InvoiceTransportInput, EntradaFactura, LineaFactura, TotalesFactura } from './domain/invoicing';
|
|
11
11
|
export type { DocumentoPreparado, DocumentoFirmado, DocumentoEnviado, FirmaDocumento } from './infrastructure/sii-client';
|
|
12
12
|
export { parseDteXml, parseDteDocumentXml } from './infrastructure/dte-xml';
|
|
13
|
+
export { normalizeDteFolio, reconcileDteDetail } from './domain/dte-reconciliation';
|
|
14
|
+
export type { DteFiscalDetail, DteReconciliation, DteReconciliationDiagnostic, DteReconciledAmounts, DteReconciledLine, DteTotalRounding, DteFiscalObservation } from './domain/invoice-xml';
|
|
13
15
|
export { DteXmlError, MAX_DTE_XML_BYTES } from './domain/invoice-xml';
|
|
14
16
|
export type { ConsultaXmlFacturaEmitida, ConsultaXmlFacturaRecibida, DteInvoiceLine, DteInvoiceDetail, ResultadoXmlFacturaEmitida } from './domain/invoice-xml';
|
|
15
17
|
export type { TipoDocumentoEmitido, ConsultaXmlDocumentoEmitido, DteDocumentDetail, DteIssuanceOptions, ResultadoXmlDocumentoEmitido } 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.INVOICE_ADDITIONAL_TAX_RATES = 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.reconcileDteDetail = exports.normalizeDteFolio = 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; } });
|
|
@@ -19,6 +19,9 @@ Object.defineProperty(exports, "hashContenido", { enumerable: true, get: functio
|
|
|
19
19
|
var dte_xml_1 = require("./infrastructure/dte-xml");
|
|
20
20
|
Object.defineProperty(exports, "parseDteXml", { enumerable: true, get: function () { return dte_xml_1.parseDteXml; } });
|
|
21
21
|
Object.defineProperty(exports, "parseDteDocumentXml", { enumerable: true, get: function () { return dte_xml_1.parseDteDocumentXml; } });
|
|
22
|
+
var dte_reconciliation_1 = require("./domain/dte-reconciliation");
|
|
23
|
+
Object.defineProperty(exports, "normalizeDteFolio", { enumerable: true, get: function () { return dte_reconciliation_1.normalizeDteFolio; } });
|
|
24
|
+
Object.defineProperty(exports, "reconcileDteDetail", { enumerable: true, get: function () { return dte_reconciliation_1.reconcileDteDetail; } });
|
|
22
25
|
var invoice_xml_1 = require("./domain/invoice-xml");
|
|
23
26
|
Object.defineProperty(exports, "DteXmlError", { enumerable: true, get: function () { return invoice_xml_1.DteXmlError; } });
|
|
24
27
|
Object.defineProperty(exports, "MAX_DTE_XML_BYTES", { enumerable: true, get: function () { return invoice_xml_1.MAX_DTE_XML_BYTES; } });
|
|
@@ -5,6 +5,7 @@ exports.parseDteDocumentXml = parseDteDocumentXml;
|
|
|
5
5
|
const saxes_1 = require("saxes");
|
|
6
6
|
const rut_1 = require("../domain/rut");
|
|
7
7
|
const invoice_xml_1 = require("../domain/invoice-xml");
|
|
8
|
+
const dte_reconciliation_1 = require("../domain/dte-reconciliation");
|
|
8
9
|
function invalid() { throw new invoice_xml_1.DteXmlError('SII_XML_INVALID'); }
|
|
9
10
|
const children = (node, name) => node.children.filter(n => n.name === name && n.uri === node.uri);
|
|
10
11
|
function one(node, name) {
|
|
@@ -24,12 +25,12 @@ function nodeText(node, required = false, limit = 1000) {
|
|
|
24
25
|
invalid();
|
|
25
26
|
return node.text.trim() || null;
|
|
26
27
|
}
|
|
27
|
-
function integer(node, name, required = false) {
|
|
28
|
+
function integer(node, name, required = false, signed = false) {
|
|
28
29
|
const value = text(node, name, required, 20);
|
|
29
30
|
if (value === null)
|
|
30
31
|
return null;
|
|
31
32
|
const number = Number(value);
|
|
32
|
-
if (
|
|
33
|
+
if (!(signed ? /^-?\d+$/ : /^\d+$/).test(value) || !Number.isSafeInteger(number))
|
|
33
34
|
invalid();
|
|
34
35
|
return number;
|
|
35
36
|
}
|
|
@@ -54,6 +55,14 @@ function uniqueLines(items) {
|
|
|
54
55
|
if (new Set(items.map(item => item.lineNumber)).size !== items.length)
|
|
55
56
|
invalid();
|
|
56
57
|
}
|
|
58
|
+
function fiscalFolio(value) {
|
|
59
|
+
try {
|
|
60
|
+
return (0, dte_reconciliation_1.normalizeDteFolio)(value);
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return invalid();
|
|
64
|
+
}
|
|
65
|
+
}
|
|
57
66
|
/** Bounded, namespace-aware parsing; no DTD, external entities or network I/O. */
|
|
58
67
|
function parseDteXml(xml, expected) {
|
|
59
68
|
const parsed = parseDocumentXml(xml, expected, false);
|
|
@@ -120,7 +129,11 @@ function parseDocumentXml(xml, expected, allowCreditNotes) {
|
|
|
120
129
|
const grossAmounts = integer(identity, 'MntBruto');
|
|
121
130
|
if (grossAmounts !== null && grossAmounts !== 1)
|
|
122
131
|
invalid();
|
|
123
|
-
const
|
|
132
|
+
const declaredFolio = text(identity, 'Folio', true, 20);
|
|
133
|
+
const folio = fiscalFolio(declaredFolio);
|
|
134
|
+
const normalization = [];
|
|
135
|
+
if (folio !== declaredFolio)
|
|
136
|
+
normalization.push({ code: 'FOLIO_NORMALIZED', severity: 'INFO', message: 'Folio numérico normalizado sin modificar su forma declarada ni los bytes XML.' });
|
|
124
137
|
let issuerRut, receiverRut;
|
|
125
138
|
try {
|
|
126
139
|
issuerRut = (0, rut_1.parseRut)(text(issuer, 'RUTEmisor', true, 12)).formatted;
|
|
@@ -129,13 +142,26 @@ function parseDocumentXml(xml, expected, allowCreditNotes) {
|
|
|
129
142
|
catch {
|
|
130
143
|
return invalid();
|
|
131
144
|
}
|
|
132
|
-
if (
|
|
145
|
+
if (documentType !== 33 && documentType !== 34 && (!allowCreditNotes || documentType !== 61))
|
|
133
146
|
invalid();
|
|
134
|
-
if (issuerRut !== (0, rut_1.parseRut)(expected.issuerRut).formatted || documentType !== expected.documentType || folio !== expected.folio || (expected.receiverRut !== undefined && receiverRut !== (0, rut_1.parseRut)(expected.receiverRut).formatted))
|
|
147
|
+
if (issuerRut !== (0, rut_1.parseRut)(expected.issuerRut).formatted || documentType !== expected.documentType || folio !== fiscalFolio(expected.folio) || (expected.receiverRut !== undefined && receiverRut !== (0, rut_1.parseRut)(expected.receiverRut).formatted))
|
|
135
148
|
throw new invoice_xml_1.DteXmlError('SII_XML_IDENTITY_MISMATCH');
|
|
136
149
|
const lines = children(document, 'Detalle').map(line => ({
|
|
137
150
|
lineNumber: lineNumber(line, 'NroLinDet'), name: text(line, 'NmbItem', true, 80), description: text(line, 'DscItem'),
|
|
138
|
-
codes: children(line, 'CdgItem').
|
|
151
|
+
codes: children(line, 'CdgItem').flatMap(code => {
|
|
152
|
+
const type = text(code, 'TpoCodigo', false, 10), value = text(code, 'VlrCodigo', false, 35);
|
|
153
|
+
if (value && !type)
|
|
154
|
+
invalid();
|
|
155
|
+
if (!value)
|
|
156
|
+
normalization.push({ code: 'EMPTY_OPTIONAL_PRODUCT_CODE', severity: 'INFO', message: 'Código de producto opcional vacío tratado como ausente.', lineNumber: lineNumber(line, 'NroLinDet') });
|
|
157
|
+
return type && value ? [{ type, value }] : [];
|
|
158
|
+
}),
|
|
159
|
+
...(children(line, 'CodImpAdic').length ? { additionalTaxCodes: children(line, 'CodImpAdic').map(node => {
|
|
160
|
+
const value = nodeText(node, true, 6);
|
|
161
|
+
if (!/^\d{1,6}$/.test(value))
|
|
162
|
+
invalid();
|
|
163
|
+
return Number(value);
|
|
164
|
+
}) } : {}),
|
|
139
165
|
quantity: decimal(line, 'QtyItem'), unit: text(line, 'UnmdItem', false, 4), unitPrice: decimal(line, 'PrcItem'),
|
|
140
166
|
discountPercent: decimal(line, 'DescuentoPct'), discountAmount: integer(line, 'DescuentoMonto'),
|
|
141
167
|
surchargePercent: decimal(line, 'RecargoPct'), surchargeAmount: integer(line, 'RecargoMonto'), exemptIndicator: integer(line, 'IndExe'), amount: integer(line, 'MontoItem', true),
|
|
@@ -148,37 +174,54 @@ function parseDocumentXml(xml, expected, allowCreditNotes) {
|
|
|
148
174
|
invalid();
|
|
149
175
|
return { lineNumber: lineNumber(node, 'NroLinDR'), movement: movement, description: text(node, 'GlosaDR'), valueType: valueType, value: decimal(node, 'ValorDR', true), exemptIndicator: integer(node, 'IndExeDR') };
|
|
150
176
|
});
|
|
151
|
-
const references = children(document, 'Referencia').map(node =>
|
|
152
|
-
|
|
153
|
-
|
|
177
|
+
const references = children(document, 'Referencia').map(node => {
|
|
178
|
+
const documentType = text(node, 'TpoDocRef', true, 3), declared = text(node, 'FolioRef', true, 18);
|
|
179
|
+
const folio = /^\d{1,3}$/.test(documentType) && Number(documentType) > 0 && Number(documentType) < 200 && /^\d+$/.test(declared)
|
|
180
|
+
? BigInt(declared) === 0n ? '0' : fiscalFolio(declared) : declared;
|
|
181
|
+
if (folio !== declared)
|
|
182
|
+
normalization.push({ code: 'REFERENCE_FOLIO_NORMALIZED', severity: 'INFO', message: 'Folio de referencia fiscal normalizado; se conserva su forma declarada.' });
|
|
183
|
+
return { lineNumber: lineNumber(node, 'NroLinRef'), documentType, folio, ...(folio !== declared ? { declaredFolio: declared } : {}), date: date(node, 'FchRef'), code: integer(node, 'CodRef'), reason: text(node, 'RazonRef', false, 90) };
|
|
184
|
+
});
|
|
154
185
|
uniqueLines(lines);
|
|
155
186
|
uniqueLines(adjustments);
|
|
156
187
|
uniqueLines(references);
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
||
|
|
188
|
+
const fiscalReferences = references.filter(reference => /^\d{1,3}$/.test(reference.documentType) && Number(reference.documentType) > 0 && Number(reference.documentType) < 200);
|
|
189
|
+
if (documentType === 61 && (!fiscalReferences.length
|
|
190
|
+
|| fiscalReferences.some(reference => reference.code === null || ![1, 2, 3].includes(reference.code) || !/^[1-9]\d{0,19}$/.test(reference.folio))
|
|
191
|
+
|| (fiscalReferences.some(reference => reference.code === 1 || reference.code === 2) && fiscalReferences.length !== 1)))
|
|
160
192
|
invalid();
|
|
161
193
|
const signatures = dtes[0].children.filter(node => node.name === 'Signature' && node.uri === 'http://www.w3.org/2000/09/xmldsig#');
|
|
162
194
|
if (allowCreditNotes && signatures.length > 1)
|
|
163
195
|
invalid();
|
|
164
196
|
const options = allowCreditNotes ? issuanceOptions(headerNode, identity, issuer, document) : undefined;
|
|
165
197
|
const issuerActivities = allowCreditNotes ? children(issuer, 'Acteco').map(node => nodeText(node)) : [];
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
198
|
+
const paymentTotals = Object.fromEntries([
|
|
199
|
+
['MontoNF', 'nonBillableAmount', true], ['MontoPeriodo', 'periodAmount', false],
|
|
200
|
+
['SaldoAnterior', 'previousBalance', true], ['VlrPagar', 'payableAmount', false],
|
|
201
|
+
].flatMap(([tag, field, signed]) => {
|
|
202
|
+
const value = integer(totals, tag, false, signed);
|
|
203
|
+
return value === null ? [] : [[field, value]];
|
|
204
|
+
}));
|
|
205
|
+
const detail = {
|
|
206
|
+
...(grossAmounts === 1 ? { grossAmounts: true } : {}),
|
|
207
|
+
...paymentTotals,
|
|
208
|
+
issuerRut, documentType: expected.documentType, folio, ...(folio !== declaredFolio ? { declaredFolio } : {}), issuedDate: date(identity, 'FchEmis'), receiverRut,
|
|
209
|
+
hasSignature: signatures.length === 1,
|
|
210
|
+
hasTransport: children(headerNode, 'Transporte').some(node => node.children.length > 0 || node.text.trim().length > 0 || node.attributeCount > 0),
|
|
211
|
+
...(options ? { issuanceOptions: options } : {}),
|
|
212
|
+
...(allowCreditNotes ? { fiscalHeader: {
|
|
213
|
+
issuer: { legalName: text(issuer, 'RznSoc'), businessActivity: text(issuer, 'GiroEmis'), activityCode: issuerActivities.length === 1 ? issuerActivities[0] : null, branchCode: text(issuer, 'CdgSIISucur', false, 9), address: text(issuer, 'DirOrigen'), commune: text(issuer, 'CmnaOrigen'), city: text(issuer, 'CiudadOrigen') },
|
|
214
|
+
receiver: { legalName: text(receiver, 'RznSocRecep'), address: text(receiver, 'DirRecep'), commune: text(receiver, 'CmnaRecep'), city: text(receiver, 'CiudadRecep'), businessActivity: text(receiver, 'GiroRecep'), contact: text(receiver, 'Contacto') },
|
|
215
|
+
paymentForm: integer(identity, 'FmaPago'), saleType: integer(identity, 'TpoTranVenta'), purchaseType: integer(identity, 'TpoTranCompra'),
|
|
216
|
+
noDebitReduction: integer(identity, 'IndNoRebaja', children(identity, 'IndNoRebaja').length > 0),
|
|
217
|
+
unapprovedFiscalFields: [...identity.children.filter(node => node.uri === identity.uri && !['TipoDTE', 'Folio', 'FchEmis', 'FmaPago', 'TpoTranVenta', 'TpoTranCompra', 'IndNoRebaja', 'MntPagos'].includes(node.name)).map(node => node.name), ...(issuerActivities.length > 1 ? ['Acteco'] : [])],
|
|
218
|
+
} } : {}),
|
|
219
|
+
netAmount: integer(totals, 'MntNeto'), exemptAmount: integer(totals, 'MntExe'), vatRate: decimal(totals, 'TasaIVA'), vatAmount: integer(totals, 'IVA'), totalAmount: integer(totals, 'MntTotal', true), lines,
|
|
220
|
+
taxes: children(totals, 'ImptoReten').map(node => ({ type: integer(node, 'TipoImp', true), rate: decimal(node, 'TasaImp'), amount: integer(node, 'MontoImp', true) })), adjustments, references,
|
|
221
|
+
};
|
|
222
|
+
detail.reconciliation = (0, dte_reconciliation_1.reconcileDteDetail)(detail);
|
|
223
|
+
detail.reconciliation.diagnostics.unshift(...normalization);
|
|
224
|
+
return { xml: new Uint8Array(xml), encoding, detail };
|
|
182
225
|
}
|
|
183
226
|
function issuanceOptions(header, identity, issuer, document) {
|
|
184
227
|
const unsupported = [];
|
|
@@ -6,7 +6,7 @@ export declare function element(node: Html.Node): node is Html.Element;
|
|
|
6
6
|
export declare function parsePortalPage(html: string): Html.Document;
|
|
7
7
|
/** Serialize only inert successful controls; provider scripts are never executed. */
|
|
8
8
|
export declare function readForm(html: string | Html.Document, name: string, endpoint: string): URLSearchParams;
|
|
9
|
-
/** Decode
|
|
9
|
+
/** Decode bounded JSON option tables, never JavaScript expressions. */
|
|
10
10
|
export declare function readLiteralRows(html: string | Html.Document, variable: string): string[][];
|
|
11
11
|
/** The final all-zero row is a portal placeholder, never a company address or giro. */
|
|
12
12
|
export declare function readCompanyOptions(html: string | Html.Document): Pick<CompanyInfo, 'addresses' | 'businessActivities'>;
|
|
@@ -127,7 +127,7 @@ function readForm(html, name, endpoint) {
|
|
|
127
127
|
}
|
|
128
128
|
return fields;
|
|
129
129
|
}
|
|
130
|
-
/** Decode
|
|
130
|
+
/** Decode bounded JSON option tables, never JavaScript expressions. */
|
|
131
131
|
function readLiteralRows(html, variable) {
|
|
132
132
|
if (!ROW_VARIABLES.has(variable))
|
|
133
133
|
invalid();
|
|
@@ -140,7 +140,7 @@ function readLiteralRows(html, variable) {
|
|
|
140
140
|
declarations.push(match[1]);
|
|
141
141
|
}
|
|
142
142
|
const literal = declarations[0];
|
|
143
|
-
if (declarations.length !== 1 || !literal || Buffer.byteLength(literal) >
|
|
143
|
+
if (declarations.length !== 1 || !literal || Buffer.byteLength(literal) > 256 * 1024)
|
|
144
144
|
invalid();
|
|
145
145
|
let rows;
|
|
146
146
|
try {
|
|
@@ -149,7 +149,8 @@ function readLiteralRows(html, variable) {
|
|
|
149
149
|
catch {
|
|
150
150
|
invalid();
|
|
151
151
|
}
|
|
152
|
-
|
|
152
|
+
const maxRows = variable.endsWith('Dir') ? 1000 : 100;
|
|
153
|
+
if (!Array.isArray(rows) || rows.length > maxRows || !rows.every((row) => Array.isArray(row) && row.length > 0 && row.length <= 5 && row.every(value => typeof value === 'string' && value.length <= 200)))
|
|
153
154
|
invalid();
|
|
154
155
|
return rows;
|
|
155
156
|
}
|
|
@@ -63,10 +63,22 @@ class SiiHttpSession {
|
|
|
63
63
|
const body = new URLSearchParams({ rut: identity.rut, dv: identity.dv, referencia: exports.RCV, '411': '', rutcntr: identity.formatted, clave });
|
|
64
64
|
await this.request(AUTH, async (response) => {
|
|
65
65
|
await response.body?.cancel();
|
|
66
|
+
const redirected = response.status >= 300 && response.status < 400;
|
|
67
|
+
if (redirected) {
|
|
68
|
+
try {
|
|
69
|
+
const location = response.headers.get('location');
|
|
70
|
+
const target = new URL(location ?? '', AUTH);
|
|
71
|
+
if (!location || target.protocol !== 'https:' || !(target.hostname === 'sii.cl' || target.hostname.endsWith('.sii.cl')) || target.username || target.password || target.port)
|
|
72
|
+
throw new Error();
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
throw this.failure('SESSION_OR_INTERACTIVE_AUTH_REQUIRED', 'CAutInicio.cgi', 'SESSION_REQUIRED', response);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
66
78
|
const cookies = await this.cookies(exports.RCV);
|
|
67
79
|
if (!cookies.some(c => c.key === 'TOKEN' && c.value))
|
|
68
|
-
throw this.failure('LOGIN_NOT_CONFIRMED', 'CAutInicio.cgi', 'LOGIN_NOT_CONFIRMED', response);
|
|
69
|
-
}, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', Origin: 'https://zeusr.sii.cl', Referer: `https://zeusr.sii.cl/AUT2000/InicioAutenticacion/IngresoRutClave.html?${exports.RCV}` }, body: body.toString() });
|
|
80
|
+
throw this.failure(redirected ? 'SESSION_OR_INTERACTIVE_AUTH_REQUIRED' : 'LOGIN_NOT_CONFIRMED', 'CAutInicio.cgi', redirected ? 'SESSION_REQUIRED' : 'LOGIN_NOT_CONFIRMED', response);
|
|
81
|
+
}, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', Origin: 'https://zeusr.sii.cl', Referer: `https://zeusr.sii.cl/AUT2000/InicioAutenticacion/IngresoRutClave.html?${exports.RCV}` }, body: body.toString() }, false, true);
|
|
70
82
|
await this.request(SESSION, async (response) => {
|
|
71
83
|
const sessionEnvelope = await this.json(response, 'aaSessionService/load');
|
|
72
84
|
const session = isRecord(sessionEnvelope) && isRecord(sessionEnvelope.data) ? sessionEnvelope.data : undefined;
|
|
@@ -84,7 +96,8 @@ class SiiHttpSession {
|
|
|
84
96
|
return { usuarioRut: identity.formatted, empresaRut: this.company.formatted, representacion: false };
|
|
85
97
|
}
|
|
86
98
|
catch (error) {
|
|
87
|
-
|
|
99
|
+
// Preserve authentication failure; callers still observe cleanup failure through dispose().
|
|
100
|
+
await this.dispose().catch(() => { });
|
|
88
101
|
throw error;
|
|
89
102
|
}
|
|
90
103
|
}
|
|
@@ -96,7 +109,7 @@ class SiiHttpSession {
|
|
|
96
109
|
cookies(url) { return this.#jar.getCookies(url); }
|
|
97
110
|
failure(code, endpoint, reason, response, extra = {}) {
|
|
98
111
|
return new sii_error_1.SiiError(code, response?.status, { traceId: this.#traceId, stage: ENDPOINT_STAGES[endpoint], endpoint, reason,
|
|
99
|
-
...(response ? { httpStatus: response.status, ...responseFormat(response) } : {}), ...extra });
|
|
112
|
+
...(response ? { httpStatus: response.status, ...responseFormat(response), retryAfterMs: retryAfterMs(response) } : {}), ...extra });
|
|
100
113
|
}
|
|
101
114
|
abortFailure(signal, endpoint) {
|
|
102
115
|
return signal.reason instanceof sii_error_1.SiiError ? signal.reason : this.failure('SII_OPERATION_ABORTED', endpoint, 'OPERATION_ABORTED');
|
|
@@ -240,21 +253,36 @@ class SiiHttpSession {
|
|
|
240
253
|
if (!cookies.some(c => c.value && ['TOKEN', 'NETSCAPE_LIVEWIRE.mac'].includes(c.key)))
|
|
241
254
|
return;
|
|
242
255
|
const headers = new Headers({ Referer: exports.RCV, Cookie: cookies.map(c => c.cookieString()).join('; ') });
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
256
|
+
for (let attempt = 1;; attempt++) {
|
|
257
|
+
try {
|
|
258
|
+
const response = await this.#fetch(LOGOUT, { method: 'GET', headers, redirect: 'manual', signal: AbortSignal.timeout(this.#timeoutMs) });
|
|
259
|
+
if (!response.ok) {
|
|
260
|
+
await response.body?.cancel();
|
|
261
|
+
if (!(response.status >= 300 && response.status < 400 && response.headers.get('location') === 'https://homer.sii.cl/'))
|
|
262
|
+
throw this.failure('SII_LOGOUT_FAILED', 'autTermino.cgi', 'HTTP_ERROR', response, { attempts: attempt });
|
|
263
|
+
}
|
|
264
|
+
else {
|
|
265
|
+
const page = Buffer.from(await this.readBounded(response, 'autTermino.cgi')).toString('latin1');
|
|
266
|
+
const codes = page.match(/\b\d{2}\.\d{2}\.\d{3}\.\d{3}\.\d{3}\.\d{2}\b/g);
|
|
267
|
+
if (codes?.some(code => code !== '01.01.205.529.269.28'))
|
|
268
|
+
throw this.failure('SII_LOGOUT_FAILED', 'autTermino.cgi', 'INVALID_RESPONSE', response, { attempts: attempt });
|
|
269
|
+
}
|
|
270
|
+
break;
|
|
271
|
+
}
|
|
272
|
+
catch (error) {
|
|
273
|
+
const failure = error instanceof sii_error_1.SiiError ? error : this.failure('SII_LOGOUT_FAILED', 'autTermino.cgi', 'TRANSPORT_ERROR', undefined, { attempts: attempt });
|
|
274
|
+
const waitMs = failure.diagnostics?.retryAfterMs ?? 500 * attempt;
|
|
275
|
+
const transient = failure.diagnostics?.reason === 'TRANSPORT_ERROR' || failure.diagnostics?.reason === 'TIMEOUT' || RETRYABLE.has(failure.httpStatus ?? 0);
|
|
276
|
+
if (!transient || attempt > this.#retries || waitMs > 5000)
|
|
277
|
+
throw failure;
|
|
278
|
+
await (0, promises_1.setTimeout)(waitMs);
|
|
279
|
+
}
|
|
254
280
|
}
|
|
255
281
|
}
|
|
256
|
-
catch {
|
|
257
|
-
|
|
282
|
+
catch (error) {
|
|
283
|
+
if (error instanceof sii_error_1.SiiError)
|
|
284
|
+
throw new sii_error_1.SiiError('SII_LOGOUT_FAILED', error.httpStatus, error.diagnostics);
|
|
285
|
+
throw this.failure('SII_LOGOUT_FAILED', 'autTermino.cgi', 'TRANSPORT_ERROR');
|
|
258
286
|
}
|
|
259
287
|
finally {
|
|
260
288
|
await this.#jar.removeAllCookies();
|
|
@@ -299,13 +327,11 @@ class SiiHttpSession {
|
|
|
299
327
|
throw this.abortFailure(options.signal, endpoint);
|
|
300
328
|
}
|
|
301
329
|
if (canRetry && RETRYABLE.has(response.status) && attempt < this.#retries) {
|
|
302
|
-
const
|
|
303
|
-
const seconds = retryAfter === null ? NaN : Number(retryAfter);
|
|
304
|
-
const waitMs = Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : Date.parse(retryAfter ?? '') - Date.now();
|
|
330
|
+
const waitMs = retryAfterMs(response);
|
|
305
331
|
await response.body?.cancel();
|
|
306
|
-
if (
|
|
332
|
+
if (waitMs !== undefined && waitMs > 5000)
|
|
307
333
|
throw this.failure('SII_RETRY_LATER', endpoint, 'RETRY_LATER', response, { attempts: attempt + 1 });
|
|
308
|
-
await (0, promises_1.setTimeout)(
|
|
334
|
+
await (0, promises_1.setTimeout)(waitMs ?? 250 * (attempt + 1), undefined, { signal: options.signal ?? undefined });
|
|
309
335
|
continue;
|
|
310
336
|
}
|
|
311
337
|
if (!response.ok && !(allowRedirect && response.status >= 300 && response.status < 400)) {
|
|
@@ -318,6 +344,13 @@ class SiiHttpSession {
|
|
|
318
344
|
}
|
|
319
345
|
}
|
|
320
346
|
exports.SiiHttpSession = SiiHttpSession;
|
|
347
|
+
function retryAfterMs(response) {
|
|
348
|
+
const raw = response.headers.get('retry-after');
|
|
349
|
+
if (!raw?.trim())
|
|
350
|
+
return undefined;
|
|
351
|
+
const value = /^\d+(?:\.\d+)?$/.test(raw.trim()) ? Number(raw) * 1000 : Date.parse(raw) - Date.now();
|
|
352
|
+
return Number.isFinite(value) && value >= 0 ? Math.min(2_592_000_000, Math.ceil(value)) : undefined;
|
|
353
|
+
}
|
|
321
354
|
const ENDPOINT_STAGES = {
|
|
322
355
|
'CAutInicio.cgi': 'AUTHENTICATION', 'aaSessionService/load': 'SESSION_CHECK', getDcvEmpresasAutorizadas: 'COMPANY_AUTHORIZATION',
|
|
323
356
|
getDatosInicio: 'RCV_INITIALIZATION', getResumen: 'RCV_SUMMARY', getDetalleCompra: 'RCV_DETAIL', getDetalleVenta: 'RCV_DETAIL',
|
package/dist/sii-error.d.ts
CHANGED
|
@@ -14,6 +14,7 @@ export interface SiiDiagnostics {
|
|
|
14
14
|
readonly siiMessageCode?: string;
|
|
15
15
|
readonly siiResponseCode?: number;
|
|
16
16
|
readonly attempts?: number;
|
|
17
|
+
readonly retryAfterMs?: number;
|
|
17
18
|
}
|
|
18
19
|
/** Only bounded, known protocol values cross this boundary. Never provider text or URLs. */
|
|
19
20
|
export declare function sanitizeSiiDiagnostics(value: unknown): SiiDiagnostics | undefined;
|
package/dist/sii-error.js
CHANGED
|
@@ -26,6 +26,7 @@ function sanitizeSiiDiagnostics(value) {
|
|
|
26
26
|
...(typeof raw.siiMessageCode === 'string' && /^\d{2}\.\d{2}\.\d{3}\.\d{3}\.\d{3}\.\d{2}$/.test(raw.siiMessageCode) ? { siiMessageCode: raw.siiMessageCode } : {}),
|
|
27
27
|
...(typeof raw.siiResponseCode === 'number' && Number.isInteger(raw.siiResponseCode) && Math.abs(raw.siiResponseCode) <= 999999 ? { siiResponseCode: raw.siiResponseCode } : {}),
|
|
28
28
|
...(typeof raw.attempts === 'number' && Number.isInteger(raw.attempts) && raw.attempts >= 1 && raw.attempts <= 3 ? { attempts: raw.attempts } : {}),
|
|
29
|
+
...(typeof raw.retryAfterMs === 'number' && Number.isSafeInteger(raw.retryAfterMs) && raw.retryAfterMs >= 0 && raw.retryAfterMs <= 2_592_000_000 ? { retryAfterMs: raw.retryAfterMs } : {}),
|
|
29
30
|
});
|
|
30
31
|
}
|
|
31
32
|
const STAGE_LABELS = {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@devly-cl/sii-client",
|
|
3
|
-
"version": "0.7.
|
|
3
|
+
"version": "0.7.9",
|
|
4
4
|
"description": "Cliente HTTP del SII para acceso personal, RCV, XML, PDF por streaming y emisión de facturas y notas de crédito, independiente de framework.",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"type": "commonjs",
|
|
@@ -27,7 +27,7 @@
|
|
|
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/rcv-documents.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/invoice-optionals.mjs && node test/invoice-optionals-http.mjs && node test/issuance.mjs && node test/issuance-edges.mjs && node test/api-naming.mjs && node test/company-selection.mjs && node test/company-info.mjs && node test/transport-lifecycle.mjs && node test/application.mjs && node test/architecture.mjs && node test/pdf.mjs && node test/pdf-http.mjs && node test/document-status.mjs",
|
|
30
|
+
"test": "npm run build && node test/check.mjs && node test/invoices.mjs && node test/rcv-documents.mjs && node test/xml.mjs && node test/reconciliation.mjs && node --test test/rounding.mjs && node test/logout.mjs && node --test test/session-lifecycle.mjs && node test/credit-note-xml.mjs && node test/facturador.mjs && node test/invoicing.mjs && node test/invoice-optionals.mjs && node test/invoice-optionals-http.mjs && node test/issuance.mjs && node test/issuance-edges.mjs && node test/api-naming.mjs && node test/company-selection.mjs && node test/company-info.mjs && node test/transport-lifecycle.mjs && node test/application.mjs && node test/architecture.mjs && node test/pdf.mjs && node test/pdf-http.mjs && node test/document-status.mjs",
|
|
31
31
|
"check:example": "tsc --strict --noEmit --target ES2022 --module Node16 --moduleResolution Node16 --types node examples/consulta-rcv.ts examples/facturacion.ts examples/factura-opcionales.ts examples/consulta-pdf.ts examples/consulta-estado-documento.ts examples/consulta-empresa.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",
|