@devly-cl/sii-client 0.7.1 → 0.7.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +84 -1
- package/dist/application/document-status.d.ts +5 -5
- package/dist/application/document-status.js +14 -9
- package/dist/application/dte-import-mapper.d.ts +8 -0
- package/dist/application/dte-import-mapper.js +25 -0
- package/dist/application/dte-import-model.d.ts +28 -0
- package/dist/application/dte-import-model.js +2 -0
- package/dist/application/dte-import.d.ts +37 -0
- package/dist/application/dte-import.js +352 -0
- package/dist/application/invoice-queries.d.ts +12 -6
- package/dist/application/invoice-queries.js +9 -5
- package/dist/application/issuance.d.ts +2 -2
- package/dist/application/issuance.js +26 -10
- package/dist/contracts.d.ts +32 -0
- package/dist/contracts.js +17 -0
- package/dist/domain/civil-date.d.ts +2 -0
- package/dist/domain/civil-date.js +10 -0
- package/dist/domain/document-status.d.ts +0 -4
- package/dist/domain/document-status.js +18 -11
- package/dist/domain/document.js +49 -9
- package/dist/domain/dte-arithmetic.d.ts +35 -0
- package/dist/domain/dte-arithmetic.js +78 -0
- package/dist/domain/dte-components.d.ts +9 -0
- package/dist/domain/dte-components.js +37 -0
- package/dist/domain/dte-detail.d.ts +111 -0
- package/dist/domain/dte-detail.js +2 -0
- package/dist/domain/dte-identity.d.ts +19 -0
- package/dist/domain/dte-identity.js +52 -0
- package/dist/domain/dte-money.d.ts +41 -0
- package/dist/domain/dte-money.js +81 -0
- package/dist/domain/dte-reconciliation-model.d.ts +87 -0
- package/dist/domain/dte-reconciliation-model.js +2 -0
- package/dist/domain/dte-reconciliation.d.ts +15 -0
- package/dist/domain/dte-reconciliation.js +390 -0
- package/dist/domain/dte-validation.d.ts +7 -0
- package/dist/domain/dte-validation.js +84 -0
- package/dist/domain/invoice-xml.d.ts +17 -57
- package/dist/domain/invoice-xml.js +0 -10
- package/dist/domain/invoicing.d.ts +30 -4
- package/dist/domain/invoicing.js +75 -21
- package/dist/domain/issued-invoice.d.ts +0 -6
- package/dist/domain/rcv-document.d.ts +0 -4
- package/dist/domain/received-invoice.d.ts +1 -4
- package/dist/index.d.ts +19 -9
- package/dist/index.js +20 -4
- package/dist/infrastructure/document-status-gateway.d.ts +6 -4
- package/dist/infrastructure/document-status-gateway.js +34 -13
- package/dist/infrastructure/document-status-parser.js +38 -12
- package/dist/infrastructure/dte-xml-mapper.d.ts +16 -0
- package/dist/infrastructure/dte-xml-mapper.js +381 -0
- package/dist/infrastructure/dte-xml.d.ts +40 -4
- package/dist/infrastructure/dte-xml.js +117 -196
- package/dist/infrastructure/facturador-gateway.d.ts +10 -7
- package/dist/infrastructure/facturador-gateway.js +256 -56
- package/dist/infrastructure/facturador.d.ts +1 -1
- package/dist/infrastructure/facturador.js +18 -10
- package/dist/infrastructure/invoice-pdf.js +10 -3
- package/dist/infrastructure/rcv-gateway.d.ts +7 -4
- package/dist/infrastructure/rcv-gateway.js +53 -12
- package/dist/infrastructure/rcv-normalization.d.ts +8 -1
- package/dist/infrastructure/rcv-normalization.js +54 -12
- package/dist/infrastructure/read-options.d.ts +3 -0
- package/dist/infrastructure/read-options.js +25 -0
- package/dist/infrastructure/sii-client.d.ts +98 -13
- package/dist/infrastructure/sii-client.js +182 -31
- package/dist/infrastructure/sii-http-session.d.ts +2 -2
- package/dist/infrastructure/sii-http-session.js +134 -37
- package/dist/sii-error.d.ts +5 -0
- package/dist/sii-error.js +39 -13
- package/package.json +2 -2
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/** Derived explanations of declared amounts; never fiscal approval or import authorization. */
|
|
2
|
+
export interface DteProjectedTax {
|
|
3
|
+
type: number;
|
|
4
|
+
rate: string | null;
|
|
5
|
+
amount: number;
|
|
6
|
+
kind: 'ADDITIONAL' | 'ANTICIPATED' | 'SPECIFIC' | 'RETENTION' | 'MARGIN' | 'UNCLASSIFIED';
|
|
7
|
+
effect: 'ADD' | 'SUBTRACT' | 'UNKNOWN';
|
|
8
|
+
contribution: number | null;
|
|
9
|
+
}
|
|
10
|
+
export interface DteReconciliationDiagnostic {
|
|
11
|
+
code: string;
|
|
12
|
+
severity: 'INFO' | 'ERROR';
|
|
13
|
+
message: string;
|
|
14
|
+
lineNumber?: number;
|
|
15
|
+
declaredAmount?: number;
|
|
16
|
+
derivedAmount?: number;
|
|
17
|
+
}
|
|
18
|
+
/** Non-blocking documentary observations; declared fiscal amounts remain authoritative. */
|
|
19
|
+
export type DteFiscalObservation = Pick<DteReconciliationDiagnostic, 'code' | 'message' | 'declaredAmount' | 'derivedAmount'>;
|
|
20
|
+
export interface DteReconciledLine {
|
|
21
|
+
lineNumber: number;
|
|
22
|
+
quantity: string;
|
|
23
|
+
unitPrice: string;
|
|
24
|
+
discountPercent: string;
|
|
25
|
+
discountAmount: number;
|
|
26
|
+
surchargeAmount: number;
|
|
27
|
+
netAmount: number;
|
|
28
|
+
/** MontoItem exactly as declared, even when the derived line is converted from gross to net. */
|
|
29
|
+
declaredAmount: number;
|
|
30
|
+
category: 'TAXABLE' | 'EXEMPT' | 'DEPOSIT' | 'NON_BILLABLE' | 'NON_BILLABLE_DEDUCTION';
|
|
31
|
+
}
|
|
32
|
+
/** Derived explanation only; the original header and line amounts are never changed. */
|
|
33
|
+
export interface DteTotalRounding {
|
|
34
|
+
difference: -1 | 1;
|
|
35
|
+
method: 'PER_LINE_VAT_AND_TAX';
|
|
36
|
+
basis: 'DECLARED_LINE_AMOUNTS' | 'EXACT_PRODUCTS';
|
|
37
|
+
componentTotal: number;
|
|
38
|
+
}
|
|
39
|
+
export interface DteReconciledAmounts {
|
|
40
|
+
netAmount: number;
|
|
41
|
+
exemptAmount: number;
|
|
42
|
+
vatAmount: number;
|
|
43
|
+
totalAmount: number;
|
|
44
|
+
payableAmount: number;
|
|
45
|
+
lines: DteReconciledLine[];
|
|
46
|
+
taxes: DteProjectedTax[];
|
|
47
|
+
globalDiscount?: {
|
|
48
|
+
netAmount: number;
|
|
49
|
+
grossAmount?: number;
|
|
50
|
+
};
|
|
51
|
+
globalSurcharge?: {
|
|
52
|
+
netAmount: number;
|
|
53
|
+
grossAmount?: number;
|
|
54
|
+
};
|
|
55
|
+
nonBillable?: {
|
|
56
|
+
amount: number;
|
|
57
|
+
lines: {
|
|
58
|
+
lineNumber: number;
|
|
59
|
+
amount: number;
|
|
60
|
+
indicator: 2 | 6;
|
|
61
|
+
}[];
|
|
62
|
+
};
|
|
63
|
+
grossAmountsInferred?: true;
|
|
64
|
+
/** Difference explained by summing exact source products before rounding the subtotal. */
|
|
65
|
+
lineRounding?: number;
|
|
66
|
+
/** At most one peso per document, explained by an exact supported line calculation. */
|
|
67
|
+
totalRounding?: DteTotalRounding;
|
|
68
|
+
observations?: DteFiscalObservation[];
|
|
69
|
+
}
|
|
70
|
+
export interface DteReconciliation {
|
|
71
|
+
version: 1;
|
|
72
|
+
status: 'RECONCILED' | 'REVIEW_REQUIRED';
|
|
73
|
+
/** Header values are never overwritten by calculations. Null means absent in the XML. */
|
|
74
|
+
declared: {
|
|
75
|
+
netAmount: number | null;
|
|
76
|
+
exemptAmount: number | null;
|
|
77
|
+
vatAmount: number | null;
|
|
78
|
+
totalAmount: number;
|
|
79
|
+
nonBillableAmount: number | null;
|
|
80
|
+
periodAmount: number | null;
|
|
81
|
+
previousBalance: number | null;
|
|
82
|
+
payableAmount: number | null;
|
|
83
|
+
grossAmounts: boolean | null;
|
|
84
|
+
};
|
|
85
|
+
derived: DteReconciledAmounts | null;
|
|
86
|
+
diagnostics: DteReconciliationDiagnostic[];
|
|
87
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { DteFiscalDetail } from './invoice-xml';
|
|
2
|
+
import type { DteReconciliation } from './dte-reconciliation-model';
|
|
3
|
+
/**
|
|
4
|
+
* Explica los importes declarados mediante las reglas aritméticas soportadas para DTE 33, 34 y 61.
|
|
5
|
+
* No modifica el detalle, sus líneas ni los totales fiscales originales.
|
|
6
|
+
*
|
|
7
|
+
* @param detail Detalle declarado con importes enteros seguros; las cantidades y precios son strings decimales.
|
|
8
|
+
* @returns RECONCILED con importes derivados, o REVIEW_REQUIRED con derived=null y diagnósticos.
|
|
9
|
+
* Ambos estados describen la capacidad de interpretación del SDK, no la validez fiscal del documento.
|
|
10
|
+
* @remarks No consulta el SII, no verifica autorización y no decide la persistencia en un consumidor.
|
|
11
|
+
* @example
|
|
12
|
+
* const analysis = reconcileDteDetail(detail);
|
|
13
|
+
* if (analysis.status === 'REVIEW_REQUIRED') console.log(analysis.diagnostics);
|
|
14
|
+
*/
|
|
15
|
+
export declare function reconcileDteDetail(detail: DteFiscalDetail): DteReconciliation;
|
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.reconcileDteDetail = reconcileDteDetail;
|
|
4
|
+
const dte_components_1 = require("./dte-components");
|
|
5
|
+
const dte_arithmetic_1 = require("./dte-arithmetic");
|
|
6
|
+
const dte_validation_1 = require("./dte-validation");
|
|
7
|
+
function lineAdjustment(gross, price, quantity, percent, declared, kind, info) {
|
|
8
|
+
const amount = (0, dte_arithmetic_1.money)(declared ?? 0), pct = (0, dte_arithmetic_1.decimal)(percent ?? '0');
|
|
9
|
+
if (pct.n > pct.d * 100n)
|
|
10
|
+
(0, dte_arithmetic_1.fail)('INVALID_PERCENT', 'Porcentaje de ajuste de línea fuera de rango.');
|
|
11
|
+
if (!pct.n)
|
|
12
|
+
return amount;
|
|
13
|
+
if (declared === null)
|
|
14
|
+
(0, dte_arithmetic_1.fail)('MISSING_ADJUSTMENT_AMOUNT', 'El porcentaje de línea requiere su monto declarado.');
|
|
15
|
+
const rate = (0, dte_arithmetic_1.fraction)(pct.n, pct.d * 100n), unit = (0, dte_arithmetic_1.multiply)(price, rate);
|
|
16
|
+
const candidates = [
|
|
17
|
+
['PERCENT_OF_PRODUCT', (0, dte_arithmetic_1.round)((0, dte_arithmetic_1.multiply)(gross, rate))],
|
|
18
|
+
['PERCENT_OF_ROUNDED_PRODUCT', (0, dte_arithmetic_1.round)((0, dte_arithmetic_1.multiply)((0, dte_arithmetic_1.fraction)((0, dte_arithmetic_1.round)(gross)), rate))],
|
|
19
|
+
['PER_UNIT_ROUNDING', (0, dte_arithmetic_1.round)((0, dte_arithmetic_1.multiply)(quantity, (0, dte_arithmetic_1.fraction)((0, dte_arithmetic_1.round)((0, dte_arithmetic_1.multiply)(unit, (0, dte_arithmetic_1.fraction)(100n))), 100n)))],
|
|
20
|
+
['PER_UNIT_TRUNCATION', (0, dte_arithmetic_1.round)((0, dte_arithmetic_1.multiply)(quantity, (0, dte_arithmetic_1.fraction)(unit.n * 100n / unit.d, 100n)))],
|
|
21
|
+
['NET_FIRST_ROUNDING', kind === 'DISCOUNT' ? (0, dte_arithmetic_1.round)(gross) - (0, dte_arithmetic_1.round)((0, dte_arithmetic_1.multiply)(gross, (0, dte_arithmetic_1.fraction)(rate.d - rate.n, rate.d))) : (0, dte_arithmetic_1.round)((0, dte_arithmetic_1.multiply)(gross, (0, dte_arithmetic_1.fraction)(rate.d + rate.n, rate.d))) - (0, dte_arithmetic_1.round)(gross)],
|
|
22
|
+
];
|
|
23
|
+
const matched = candidates.find(([, value]) => value === BigInt(amount));
|
|
24
|
+
if (!matched)
|
|
25
|
+
(0, dte_arithmetic_1.fail)('LINE_ADJUSTMENT_MISMATCH', 'El monto del descuento o recargo de línea no coincide con el porcentaje informado.');
|
|
26
|
+
if (matched[0] !== 'PERCENT_OF_PRODUCT')
|
|
27
|
+
info(`${kind}_${matched[0]}`, 'El ajuste declarado concilia con un método de redondeo distinto al porcentaje del producto exacto.');
|
|
28
|
+
return amount;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Explica los importes declarados mediante las reglas aritméticas soportadas para DTE 33, 34 y 61.
|
|
32
|
+
* No modifica el detalle, sus líneas ni los totales fiscales originales.
|
|
33
|
+
*
|
|
34
|
+
* @param detail Detalle declarado con importes enteros seguros; las cantidades y precios son strings decimales.
|
|
35
|
+
* @returns RECONCILED con importes derivados, o REVIEW_REQUIRED con derived=null y diagnósticos.
|
|
36
|
+
* Ambos estados describen la capacidad de interpretación del SDK, no la validez fiscal del documento.
|
|
37
|
+
* @remarks No consulta el SII, no verifica autorización y no decide la persistencia en un consumidor.
|
|
38
|
+
* @example
|
|
39
|
+
* const analysis = reconcileDteDetail(detail);
|
|
40
|
+
* if (analysis.status === 'REVIEW_REQUIRED') console.log(analysis.diagnostics);
|
|
41
|
+
*/
|
|
42
|
+
function reconcileDteDetail(detail) {
|
|
43
|
+
const diagnostics = [];
|
|
44
|
+
const declared = {
|
|
45
|
+
netAmount: detail.netAmount,
|
|
46
|
+
exemptAmount: detail.exemptAmount,
|
|
47
|
+
vatAmount: detail.vatAmount,
|
|
48
|
+
totalAmount: detail.totalAmount,
|
|
49
|
+
nonBillableAmount: detail.nonBillableAmount ?? null,
|
|
50
|
+
periodAmount: detail.periodAmount ?? null,
|
|
51
|
+
previousBalance: detail.previousBalance ?? null,
|
|
52
|
+
payableAmount: detail.payableAmount ?? null,
|
|
53
|
+
grossAmounts: detail.grossAmounts ?? null,
|
|
54
|
+
};
|
|
55
|
+
try {
|
|
56
|
+
return { version: 1, status: 'RECONCILED', declared, derived: reconcile(detail, diagnostics), diagnostics };
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
if (!(error instanceof dte_arithmetic_1.DteInterpretationError))
|
|
60
|
+
throw error;
|
|
61
|
+
if (!diagnostics.some(d => d.severity === 'ERROR' && d.code === error.code))
|
|
62
|
+
diagnostics.push({
|
|
63
|
+
code: error.code,
|
|
64
|
+
severity: 'ERROR',
|
|
65
|
+
message: error.message, ...error.amounts
|
|
66
|
+
});
|
|
67
|
+
return { version: 1, status: 'REVIEW_REQUIRED', declared, derived: null, diagnostics };
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
function reconcile(detail, diagnostics) {
|
|
71
|
+
const info = (code, message, lineNumber, amounts) => diagnostics.push({
|
|
72
|
+
code,
|
|
73
|
+
severity: 'INFO',
|
|
74
|
+
message, ...(lineNumber !== undefined ? { lineNumber } : {}), ...amounts
|
|
75
|
+
});
|
|
76
|
+
if (![33, 34, 61].includes(detail.documentType))
|
|
77
|
+
(0, dte_arithmetic_1.fail)('UNSUPPORTED_DOCUMENT', 'Tipo de documento fuera del alcance de conciliación.');
|
|
78
|
+
if (!detail.lines.length || detail.lines.length > 1000)
|
|
79
|
+
(0, dte_arithmetic_1.fail)('INVALID_LINES', 'Documento sin líneas o con demasiadas líneas.');
|
|
80
|
+
(0, dte_validation_1.validateFiscalReference)(detail);
|
|
81
|
+
(0, dte_validation_1.validateComponentAmounts)(detail);
|
|
82
|
+
const netAmount = (0, dte_arithmetic_1.money)(detail.netAmount ?? 0), exemptAmount = (0, dte_arithmetic_1.money)(detail.exemptAmount ?? 0), vatAmount = (0, dte_arithmetic_1.money)(detail.vatAmount ?? 0), totalAmount = (0, dte_arithmetic_1.money)(detail.totalAmount);
|
|
83
|
+
if ((detail.documentType === 34 && (netAmount || vatAmount)) || (netAmount && exemptAmount))
|
|
84
|
+
(0, dte_arithmetic_1.fail)('UNSUPPORTED_TAX_SPLIT', 'La combinación de importes afectos y exentos requiere revisión.');
|
|
85
|
+
const exempt = detail.documentType === 34 || (!netAmount && exemptAmount > 0);
|
|
86
|
+
const taxes = detail.taxes.map(tax => {
|
|
87
|
+
(0, dte_arithmetic_1.money)(tax.amount);
|
|
88
|
+
if (tax.rate !== null)
|
|
89
|
+
(0, dte_arithmetic_1.decimal)(tax.rate);
|
|
90
|
+
return (0, dte_components_1.projectDteTax)(detail, tax);
|
|
91
|
+
});
|
|
92
|
+
if (new Set(taxes.map(t => t.type)).size !== taxes.length)
|
|
93
|
+
(0, dte_arithmetic_1.fail)('DUPLICATE_TAX_TYPE', 'Un mismo impuesto de encabezado aparece más de una vez; requiere revisión de su base.');
|
|
94
|
+
const exactHeaderTotal = (0, dte_components_1.dteHeaderTotal)(detail, taxes);
|
|
95
|
+
if (exactHeaderTotal === null)
|
|
96
|
+
(0, dte_arithmetic_1.fail)('UNRESOLVED_TAX_EFFECT', 'El efecto de un impuesto o comisión no puede determinarse para el tipo y referencias originales; no se supone aditivo.');
|
|
97
|
+
const headerTotal = (0, dte_arithmetic_1.money)(Number(exactHeaderTotal), true);
|
|
98
|
+
if (headerTotal !== totalAmount)
|
|
99
|
+
diagnostics.push({
|
|
100
|
+
code: 'HEADER_TOTAL_MISMATCH',
|
|
101
|
+
severity: 'ERROR',
|
|
102
|
+
message: 'Subtotal, IVA e impuestos adicionales XML no cuadran con el total fiscal.',
|
|
103
|
+
declaredAmount: totalAmount,
|
|
104
|
+
derivedAmount: headerTotal
|
|
105
|
+
});
|
|
106
|
+
const rate = (0, dte_arithmetic_1.decimal)(detail.vatRate ?? (vatAmount ? '19' : '0'));
|
|
107
|
+
const expectedVat = (0, dte_arithmetic_1.round)((0, dte_arithmetic_1.multiply)((0, dte_arithmetic_1.fraction)(BigInt(netAmount)), (0, dte_arithmetic_1.fraction)(rate.n, rate.d * 100n)));
|
|
108
|
+
const precise = [];
|
|
109
|
+
let lines = detail.lines.map((source, index) => {
|
|
110
|
+
const lineNumber = source.lineNumber ?? index + 1, quantityText = source.quantity ?? '1', quantity = (0, dte_arithmetic_1.decimal)(quantityText);
|
|
111
|
+
if (!quantity.n)
|
|
112
|
+
(0, dte_arithmetic_1.fail)('INVALID_QUANTITY', 'La cantidad XML debe ser mayor a cero.');
|
|
113
|
+
const amount = (0, dte_arithmetic_1.money)(source.amount), indicator = source.exemptIndicator ?? 0;
|
|
114
|
+
if (![0, 1, 2, 3, 6].includes(indicator))
|
|
115
|
+
(0, dte_arithmetic_1.fail)('UNSUPPORTED_EXEMPT_INDICATOR', 'Indicador de exención o no facturable fuera del alcance de conciliación.');
|
|
116
|
+
if (!exempt && indicator === 1)
|
|
117
|
+
(0, dte_arithmetic_1.fail)('UNSUPPORTED_TAX_SPLIT', 'Las líneas exentas y afectas requieren conciliación separada.');
|
|
118
|
+
let priceText = source.unitPrice;
|
|
119
|
+
if (priceText === null) {
|
|
120
|
+
if (source.discountAmount || source.discountPercent && (0, dte_arithmetic_1.decimal)(source.discountPercent).n || source.surchargeAmount || source.surchargePercent && (0, dte_arithmetic_1.decimal)(source.surchargePercent).n)
|
|
121
|
+
(0, dte_arithmetic_1.fail)('MISSING_UNIT_PRICE', 'Línea sin precio unitario verificable.');
|
|
122
|
+
priceText = (0, dte_arithmetic_1.decimalText)((0, dte_arithmetic_1.fraction)(BigInt(amount) * quantity.d, quantity.n));
|
|
123
|
+
info('DERIVED_UNIT_PRICE', 'Precio unitario derivado del importe declarado y la cantidad.', lineNumber);
|
|
124
|
+
}
|
|
125
|
+
const price = (0, dte_arithmetic_1.decimal)(priceText), gross = (0, dte_arithmetic_1.multiply)(quantity, price);
|
|
126
|
+
const lineInfo = (code, message) => info(code, message, lineNumber);
|
|
127
|
+
const discount = lineAdjustment(gross, price, quantity, source.discountPercent, source.discountAmount, 'DISCOUNT', lineInfo);
|
|
128
|
+
const surcharge = lineAdjustment(gross, price, quantity, source.surchargePercent, source.surchargeAmount, 'SURCHARGE', lineInfo);
|
|
129
|
+
if (BigInt(discount) > (0, dte_arithmetic_1.round)(gross))
|
|
130
|
+
(0, dte_arithmetic_1.fail)('LINE_DISCOUNT_EXCEEDS_GROSS', 'El descuento supera el importe de la línea.');
|
|
131
|
+
if ((0, dte_arithmetic_1.round)(gross) - BigInt(discount) + BigInt(surcharge) !== BigInt(amount))
|
|
132
|
+
(0, dte_arithmetic_1.fail)('LINE_AMOUNT_MISMATCH', 'Cantidad, precio, descuento y recargo no cuadran con MontoItem.', {
|
|
133
|
+
declaredAmount: amount,
|
|
134
|
+
derivedAmount: Number((0, dte_arithmetic_1.round)(gross)) - discount + surcharge
|
|
135
|
+
});
|
|
136
|
+
precise.push((0, dte_arithmetic_1.add)(gross, (0, dte_arithmetic_1.fraction)(BigInt(surcharge - discount))));
|
|
137
|
+
return {
|
|
138
|
+
lineNumber,
|
|
139
|
+
quantity: quantityText,
|
|
140
|
+
unitPrice: priceText,
|
|
141
|
+
discountPercent: source.discountPercent ?? '0',
|
|
142
|
+
discountAmount: discount,
|
|
143
|
+
surchargeAmount: surcharge,
|
|
144
|
+
netAmount: amount,
|
|
145
|
+
declaredAmount: amount,
|
|
146
|
+
category: indicator === 2 ? 'NON_BILLABLE' : indicator === 6 ? 'NON_BILLABLE_DEDUCTION' : indicator === 3 ? 'DEPOSIT' : exempt || indicator === 1 ? 'EXEMPT' : 'TAXABLE'
|
|
147
|
+
};
|
|
148
|
+
});
|
|
149
|
+
const nonBillableLines = lines.filter(l => l.category === 'NON_BILLABLE' || l.category === 'NON_BILLABLE_DEDUCTION').map(l => ({
|
|
150
|
+
lineNumber: l.lineNumber,
|
|
151
|
+
amount: l.netAmount,
|
|
152
|
+
indicator: l.category === 'NON_BILLABLE' ? 2 : 6
|
|
153
|
+
}));
|
|
154
|
+
const nonBillableAmount = (0, dte_arithmetic_1.moneySum)(nonBillableLines.map(l => l.amount * (l.indicator === 6 ? -1 : 1)), true);
|
|
155
|
+
if (nonBillableAmount !== (0, dte_arithmetic_1.money)(detail.nonBillableAmount ?? 0, true) || (detail.nonBillableAmount && !nonBillableLines.length))
|
|
156
|
+
(0, dte_arithmetic_1.fail)('NON_BILLABLE_MISMATCH', 'El monto no facturable no cuadra con las líneas XML.');
|
|
157
|
+
const periodAmount = (0, dte_arithmetic_1.moneySum)([totalAmount, nonBillableAmount], true);
|
|
158
|
+
const payableAmount = (0, dte_arithmetic_1.moneySum)([periodAmount, detail.previousBalance ?? 0], true);
|
|
159
|
+
if (detail.periodAmount && detail.periodAmount !== periodAmount || detail.payableAmount && detail.payableAmount !== payableAmount)
|
|
160
|
+
(0, dte_arithmetic_1.fail)('PAYABLE_TOTAL_MISMATCH', 'El valor a pagar no cuadra con los totalizadores XML.');
|
|
161
|
+
for (const [field, expected] of [['periodAmount', periodAmount], ['payableAmount', payableAmount]]) {
|
|
162
|
+
if (detail[field] === 0 && expected !== 0)
|
|
163
|
+
info('ZERO_OPTIONAL_PAYMENT_TOTAL', `Totalizador opcional ${field} en cero conservado como declarado; el valor derivado no acredita pagos.`, undefined, {
|
|
164
|
+
declaredAmount: 0,
|
|
165
|
+
derivedAmount: expected
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
const deposits = lines.filter(l => l.category === 'DEPOSIT');
|
|
169
|
+
if ((0, dte_arithmetic_1.moneySum)(deposits.map(l => l.netAmount)) !== (detail.fiscalComponents?.containerDeposit ?? 0))
|
|
170
|
+
(0, dte_arithmetic_1.fail)('DEPOSIT_TOTAL_MISMATCH', 'La garantía declarada por envases no coincide con las líneas de depósito.');
|
|
171
|
+
const fiscalLines = lines.filter(l => l.category === 'TAXABLE' || l.category === 'EXEMPT');
|
|
172
|
+
const lineTotal = (0, dte_arithmetic_1.money)(fiscalLines.reduce((s, l) => s + l.netAmount, 0));
|
|
173
|
+
let discount = 0, globalSurcharge = 0;
|
|
174
|
+
for (const adjustment of detail.adjustments) {
|
|
175
|
+
if (!['D', 'R'].includes(adjustment.movement) || adjustment.exemptIndicator != null && !(exempt && adjustment.exemptIndicator === 1) || !['$', '%'].includes(adjustment.valueType))
|
|
176
|
+
(0, dte_arithmetic_1.fail)('UNSUPPORTED_GLOBAL_ADJUSTMENT', 'El ajuste global requiere conciliación de su alcance y tipo.');
|
|
177
|
+
const value = (0, dte_arithmetic_1.decimal)(adjustment.value);
|
|
178
|
+
if (adjustment.valueType === '$' && value.n % value.d || adjustment.valueType === '%' && value.n > value.d * 100n)
|
|
179
|
+
(0, dte_arithmetic_1.fail)('INVALID_GLOBAL_DISCOUNT', 'El ajuste global requiere un importe entero CLP o un porcentaje entre cero y cien.');
|
|
180
|
+
const amount = adjustment.valueType === '$' ? Number(value.n / value.d) : Number((0, dte_arithmetic_1.round)((0, dte_arithmetic_1.multiply)((0, dte_arithmetic_1.fraction)(BigInt(lineTotal - discount + globalSurcharge)), (0, dte_arithmetic_1.fraction)(value.n, value.d * 100n))));
|
|
181
|
+
if (adjustment.movement === 'D')
|
|
182
|
+
discount = (0, dte_arithmetic_1.money)(discount + amount);
|
|
183
|
+
else
|
|
184
|
+
globalSurcharge = (0, dte_arithmetic_1.money)(globalSurcharge + amount);
|
|
185
|
+
(0, dte_arithmetic_1.money)(lineTotal - discount + globalSurcharge);
|
|
186
|
+
}
|
|
187
|
+
if (discount && globalSurcharge)
|
|
188
|
+
(0, dte_arithmetic_1.fail)('MIXED_GLOBAL_ADJUSTMENTS', 'La combinación de descuentos y recargos globales requiere revisión de su distribución.');
|
|
189
|
+
const subtotal = netAmount + exemptAmount;
|
|
190
|
+
const inferred = detail.grossAmounts === undefined && !exempt && !taxes.length && !nonBillableLines.length && netAmount > 0 && vatAmount > 0 && rate.n === 19n * rate.d && lineTotal - discount + globalSurcharge === totalAmount;
|
|
191
|
+
if (BigInt(vatAmount) !== expectedVat) {
|
|
192
|
+
// Gross historic documents may total independently rounded VAT per line.
|
|
193
|
+
const truncatedVat = BigInt(vatAmount) === BigInt(netAmount) * rate.n / (rate.d * 100n);
|
|
194
|
+
const preciseNet = precise.reduce((sum, value, index) => lines[index].category === 'TAXABLE' ? (0, dte_arithmetic_1.add)(sum, value) : sum, (0, dte_arithmetic_1.fraction)(0n));
|
|
195
|
+
const preciseVat = !truncatedVat && !discount && !globalSurcharge && !exempt && !detail.grossAmounts && !inferred && detail.vatRate != null
|
|
196
|
+
&& detail.lines.every((source, index) => lines[index].category !== 'TAXABLE' || source.quantity != null && source.unitPrice != null)
|
|
197
|
+
&& (0, dte_arithmetic_1.round)(preciseNet) === BigInt(netAmount) && (0, dte_arithmetic_1.round)((0, dte_arithmetic_1.multiply)(preciseNet, (0, dte_arithmetic_1.fraction)(rate.n, rate.d * 100n))) === BigInt(vatAmount);
|
|
198
|
+
const perLineVat = !truncatedVat && !discount && !globalSurcharge && (detail.grossAmounts || inferred) && !taxes.length
|
|
199
|
+
? ['NEAREST', 'CEILING', 'FLOOR', 'PER_UNIT_NEAREST'].find(method => fiscalLines.reduce((sum, line) => {
|
|
200
|
+
const value = (0, dte_arithmetic_1.fraction)(BigInt(line.declaredAmount) * rate.n, rate.d * 100n + rate.n);
|
|
201
|
+
if (method === 'PER_UNIT_NEAREST') {
|
|
202
|
+
if (line.discountAmount || line.surchargeAmount)
|
|
203
|
+
return -1n;
|
|
204
|
+
const unitTax = (0, dte_arithmetic_1.round)((0, dte_arithmetic_1.multiply)((0, dte_arithmetic_1.decimal)(line.unitPrice), (0, dte_arithmetic_1.fraction)(rate.n, rate.d * 100n + rate.n)));
|
|
205
|
+
return sum + (0, dte_arithmetic_1.round)((0, dte_arithmetic_1.multiply)((0, dte_arithmetic_1.fraction)(unitTax), (0, dte_arithmetic_1.decimal)(line.quantity)));
|
|
206
|
+
}
|
|
207
|
+
return sum + (method === 'NEAREST' ? (0, dte_arithmetic_1.round)(value) : method === 'CEILING' ? (value.n + value.d - 1n) / value.d : value.n / value.d);
|
|
208
|
+
}, 0n) === BigInt(vatAmount)) : undefined;
|
|
209
|
+
if (!truncatedVat && !perLineVat && !preciseVat)
|
|
210
|
+
(0, dte_arithmetic_1.fail)('VAT_MISMATCH', 'El IVA del XML no cuadra con el neto fiscal y la tasa declarada.', {
|
|
211
|
+
declaredAmount: vatAmount,
|
|
212
|
+
derivedAmount: Number(expectedVat)
|
|
213
|
+
});
|
|
214
|
+
if (preciseVat)
|
|
215
|
+
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.');
|
|
216
|
+
else
|
|
217
|
+
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.');
|
|
218
|
+
}
|
|
219
|
+
let globalDiscount;
|
|
220
|
+
let surcharge;
|
|
221
|
+
let lineRounding;
|
|
222
|
+
if (detail.grossAmounts || inferred) {
|
|
223
|
+
if (taxes.length || exempt || lineTotal - discount + globalSurcharge !== totalAmount)
|
|
224
|
+
(0, dte_arithmetic_1.fail)('GROSS_TOTAL_MISMATCH', 'Las líneas y ajustes globales no cuadran con el total bruto del XML.');
|
|
225
|
+
const netBeforeDiscount = discount || globalSurcharge ? Number((0, dte_arithmetic_1.round)((0, dte_arithmetic_1.fraction)(BigInt(lineTotal) * rate.d * 100n, rate.d * 100n + rate.n))) : subtotal;
|
|
226
|
+
if (discount && netBeforeDiscount < subtotal || globalSurcharge && netBeforeDiscount > subtotal)
|
|
227
|
+
(0, dte_arithmetic_1.fail)('GROSS_DISCOUNT_MISMATCH', 'El ajuste global bruto no conserva el neto fiscal.');
|
|
228
|
+
const allocated = (0, dte_arithmetic_1.allocate)(fiscalLines.map(l => l.netAmount), netBeforeDiscount);
|
|
229
|
+
let fiscalIndex = 0;
|
|
230
|
+
lines = lines.map(l => {
|
|
231
|
+
if (l.category !== 'TAXABLE' && l.category !== 'EXEMPT')
|
|
232
|
+
return l;
|
|
233
|
+
const net = allocated[fiscalIndex++], quantity = (0, dte_arithmetic_1.decimal)(l.quantity);
|
|
234
|
+
const lineDiscount = Number((0, dte_arithmetic_1.round)((0, dte_arithmetic_1.fraction)(BigInt(l.discountAmount) * rate.d * 100n, rate.d * 100n + rate.n)));
|
|
235
|
+
const surcharge = Number((0, dte_arithmetic_1.round)((0, dte_arithmetic_1.fraction)(BigInt(l.surchargeAmount) * rate.d * 100n, rate.d * 100n + rate.n)));
|
|
236
|
+
const price = (0, dte_arithmetic_1.decimalText)((0, dte_arithmetic_1.fraction)(BigInt(net + lineDiscount - surcharge) * quantity.d, quantity.n));
|
|
237
|
+
if ((0, dte_arithmetic_1.round)((0, dte_arithmetic_1.multiply)(quantity, (0, dte_arithmetic_1.decimal)(price))) - BigInt(lineDiscount) + BigInt(surcharge) !== BigInt(net))
|
|
238
|
+
(0, dte_arithmetic_1.fail)('GROSS_PRICE_PRECISION', 'La conversión de precio bruto no conserva el importe neto de línea.');
|
|
239
|
+
return { ...l, unitPrice: price, discountAmount: lineDiscount, surchargeAmount: surcharge, netAmount: net };
|
|
240
|
+
});
|
|
241
|
+
if (discount)
|
|
242
|
+
globalDiscount = { netAmount: netBeforeDiscount - subtotal, grossAmount: discount };
|
|
243
|
+
if (globalSurcharge)
|
|
244
|
+
surcharge = { netAmount: subtotal - netBeforeDiscount, grossAmount: globalSurcharge };
|
|
245
|
+
info(inferred ? 'GROSS_AMOUNTS_INFERRED' : 'GROSS_AMOUNTS_CONVERTED', 'Líneas brutas convertidas contra los totales fiscales declarados, conservando cantidades y XML.');
|
|
246
|
+
}
|
|
247
|
+
else {
|
|
248
|
+
if (discount)
|
|
249
|
+
globalDiscount = { netAmount: discount };
|
|
250
|
+
if (globalSurcharge)
|
|
251
|
+
surcharge = { netAmount: globalSurcharge };
|
|
252
|
+
if (lineTotal - discount + globalSurcharge !== subtotal) {
|
|
253
|
+
const preciseTotal = precise.reduce((s, v, index) => lines[index].category === 'TAXABLE' || lines[index].category === 'EXEMPT' ? (0, dte_arithmetic_1.add)(s, v) : s, (0, dte_arithmetic_1.fraction)(0n));
|
|
254
|
+
if (Number((0, dte_arithmetic_1.round)(preciseTotal)) - discount + globalSurcharge !== subtotal)
|
|
255
|
+
(0, dte_arithmetic_1.fail)('LINE_SUBTOTAL_MISMATCH', 'Las líneas y ajustes XML no cuadran con el subtotal fiscal.');
|
|
256
|
+
lineRounding = subtotal - (lineTotal - discount + globalSurcharge);
|
|
257
|
+
info('PRECISE_SUBTOTAL_ROUNDING', 'El subtotal concilia al sumar los productos exactos antes de redondear, en lugar de sumar MontoItem redondeados.', undefined, {
|
|
258
|
+
declaredAmount: subtotal,
|
|
259
|
+
derivedAmount: lineTotal - discount + globalSurcharge
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
for (const source of detail.lines) {
|
|
264
|
+
const codes = source.additionalTaxCodes ?? [];
|
|
265
|
+
if (codes.length > 2 || new Set(codes).size !== codes.length)
|
|
266
|
+
(0, dte_arithmetic_1.fail)('INVALID_LINE_TAX_CODES', 'Códigos de impuesto de línea duplicados o fuera de alcance.');
|
|
267
|
+
for (const code of codes) {
|
|
268
|
+
if (![18, 23, 24, 25, 26, 27, 271].includes(code))
|
|
269
|
+
(0, dte_arithmetic_1.fail)('UNSUPPORTED_LINE_TAX', 'Código de impuesto de línea fuera del alcance de conciliación.');
|
|
270
|
+
if (!taxes.some(t => t.type === code))
|
|
271
|
+
(0, dte_arithmetic_1.fail)('MISSING_HEADER_TAX', 'Un impuesto de línea no tiene su monto declarado en el encabezado.');
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
const distinctCodes = new Set(detail.lines.flatMap(source => source.additionalTaxCodes ?? []));
|
|
275
|
+
const fixedMixedAdjustment = distinctCodes.size > 1 && detail.adjustments.some(adjustment => adjustment.valueType === '$' && (0, dte_arithmetic_1.decimal)(adjustment.value).n !== 0n);
|
|
276
|
+
if (fixedMixedAdjustment) {
|
|
277
|
+
const code = 'GLOBAL_ADJUSTMENT_REQUIRES_PERCENT';
|
|
278
|
+
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.';
|
|
279
|
+
diagnostics.unshift({ code, severity: 'INFO', message });
|
|
280
|
+
}
|
|
281
|
+
for (const tax of taxes) {
|
|
282
|
+
const scope = detail.lines.flatMap((source, index) => source.additionalTaxCodes?.includes(tax.type) ? [index] : []);
|
|
283
|
+
if (!scope.length || scope.some(i => lines[i].category !== 'TAXABLE'))
|
|
284
|
+
(0, dte_arithmetic_1.fail)('MISSING_TAX_BASE', 'La base del impuesto adicional no puede identificarse en las líneas fiscales.');
|
|
285
|
+
if (tax.rate === null) {
|
|
286
|
+
if (tax.amount)
|
|
287
|
+
(0, dte_arithmetic_1.fail)('MISSING_TAX_RATE', 'El impuesto adicional requiere su tasa declarada para conciliar la base.');
|
|
288
|
+
info('ZERO_TAX_WITHOUT_RATE', 'Impuesto declarado en cero sin tasa; no se deriva una tasa del documento.');
|
|
289
|
+
continue;
|
|
290
|
+
}
|
|
291
|
+
const percentage = (0, dte_arithmetic_1.decimal)(tax.rate);
|
|
292
|
+
if (percentage.n > percentage.d * 100n)
|
|
293
|
+
(0, dte_arithmetic_1.fail)('INVALID_TAX_RATE', 'Tasa de impuesto adicional fuera de alcance.');
|
|
294
|
+
if (!percentage.n && tax.amount)
|
|
295
|
+
(0, dte_arithmetic_1.fail)('TAX_AMOUNT_MISMATCH', 'Un impuesto con tasa cero no puede tener un monto positivo.', {
|
|
296
|
+
declaredAmount: tax.amount,
|
|
297
|
+
derivedAmount: 0
|
|
298
|
+
});
|
|
299
|
+
if (!lineTotal && (discount || globalSurcharge))
|
|
300
|
+
(0, dte_arithmetic_1.fail)('MISSING_TAX_BASE', 'No hay base de líneas para distribuir el ajuste global del impuesto.');
|
|
301
|
+
if (fixedMixedAdjustment)
|
|
302
|
+
continue;
|
|
303
|
+
const taxRate = (0, dte_arithmetic_1.fraction)(percentage.n, percentage.d * 100n);
|
|
304
|
+
const prorate = (amount) => discount || globalSurcharge ? (0, dte_arithmetic_1.multiply)(amount, (0, dte_arithmetic_1.fraction)(BigInt(subtotal), BigInt(lineTotal))) : amount;
|
|
305
|
+
const base = prorate((0, dte_arithmetic_1.fraction)(scope.reduce((s, i) => s + BigInt(lines[i].netAmount), 0n)));
|
|
306
|
+
const computed = (0, dte_arithmetic_1.multiply)(base, taxRate);
|
|
307
|
+
const exactBase = !detail.grossAmounts && !inferred ? prorate(scope.reduce((s, i) => (0, dte_arithmetic_1.add)(s, precise[i]), (0, dte_arithmetic_1.fraction)(0n))) : base;
|
|
308
|
+
const candidates = [
|
|
309
|
+
['GROUP_NEAREST', (0, dte_arithmetic_1.round)(computed)],
|
|
310
|
+
['GROUP_TRUNCATED', computed.n / computed.d],
|
|
311
|
+
['GROUP_CEILING', (computed.n + computed.d - 1n) / computed.d],
|
|
312
|
+
['PRECISE_PRODUCTS', (0, dte_arithmetic_1.round)((0, dte_arithmetic_1.multiply)(exactBase, taxRate))],
|
|
313
|
+
['PER_LINE_NEAREST', scope.reduce((s, i) => s + (0, dte_arithmetic_1.round)((0, dte_arithmetic_1.multiply)(prorate((0, dte_arithmetic_1.fraction)(BigInt(lines[i].netAmount))), taxRate)), 0n)],
|
|
314
|
+
];
|
|
315
|
+
const method = candidates.find(([, value]) => value === BigInt(tax.amount));
|
|
316
|
+
if (!method)
|
|
317
|
+
(0, dte_arithmetic_1.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.', {
|
|
318
|
+
declaredAmount: tax.amount,
|
|
319
|
+
derivedAmount: Number((0, dte_arithmetic_1.round)(computed))
|
|
320
|
+
});
|
|
321
|
+
if (method[0] !== 'GROUP_NEAREST')
|
|
322
|
+
info(`TAX_${method[0]}`, 'El impuesto adicional concilia con un método de redondeo distinto al del grupo de líneas.', undefined, {
|
|
323
|
+
declaredAmount: tax.amount,
|
|
324
|
+
derivedAmount: Number((0, dte_arithmetic_1.round)(computed))
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
let totalRounding;
|
|
328
|
+
if (headerTotal !== totalAmount) {
|
|
329
|
+
const difference = totalAmount - headerTotal;
|
|
330
|
+
// Global adjustments lack structured per-line allocation; never guess their scope to explain a total.
|
|
331
|
+
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)) {
|
|
332
|
+
const taxRates = new Map(taxes.map(t => {
|
|
333
|
+
const percentage = (0, dte_arithmetic_1.decimal)(t.rate);
|
|
334
|
+
return [t.type, (0, dte_arithmetic_1.fraction)(percentage.n, percentage.d * 100n)];
|
|
335
|
+
}));
|
|
336
|
+
const vatFactor = (0, dte_arithmetic_1.fraction)(rate.d * 100n + rate.n, rate.d * 100n);
|
|
337
|
+
for (const basis of ['DECLARED_LINE_AMOUNTS', 'EXACT_PRODUCTS']) {
|
|
338
|
+
if (basis === 'EXACT_PRODUCTS' && detail.lines.some((source, i) => !lines[i].category.startsWith('NON_BILLABLE') && (source.unitPrice == null || source.quantity == null)))
|
|
339
|
+
continue;
|
|
340
|
+
let candidate = 0n;
|
|
341
|
+
for (let i = 0; i < lines.length; i++) {
|
|
342
|
+
const line = lines[i];
|
|
343
|
+
if (line.category.startsWith('NON_BILLABLE'))
|
|
344
|
+
continue;
|
|
345
|
+
const base = basis === 'DECLARED_LINE_AMOUNTS' ? (0, dte_arithmetic_1.fraction)(BigInt(line.netAmount)) : precise[i];
|
|
346
|
+
candidate += (0, dte_arithmetic_1.round)(line.category === 'EXEMPT' ? base : (0, dte_arithmetic_1.multiply)(base, vatFactor));
|
|
347
|
+
for (const code of detail.lines[i].additionalTaxCodes ?? [])
|
|
348
|
+
candidate += (0, dte_arithmetic_1.round)((0, dte_arithmetic_1.multiply)(base, taxRates.get(code)));
|
|
349
|
+
}
|
|
350
|
+
if (candidate === BigInt(totalAmount)) {
|
|
351
|
+
totalRounding = { difference, method: 'PER_LINE_VAT_AND_TAX', basis, componentTotal: headerTotal };
|
|
352
|
+
const diagnostic = diagnostics.find(d => d.code === 'HEADER_TOTAL_MISMATCH');
|
|
353
|
+
diagnostic.code = 'TOTAL_ROUNDING_EXPLAINED';
|
|
354
|
+
diagnostic.severity = 'INFO';
|
|
355
|
+
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.';
|
|
356
|
+
break;
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
if (!totalRounding) {
|
|
361
|
+
const originalLineValues = detail.lines.every((source, i) => lines[i].category.startsWith('NON_BILLABLE') || source.quantity != null && source.unitPrice != null);
|
|
362
|
+
if ((difference !== -1 && difference !== 1) || detail.grossAmounts || inferred || !originalLineValues || fiscalLines.some(line => line.category === 'TAXABLE') && detail.vatRate == null || taxes.some(t => t.rate === null))
|
|
363
|
+
(0, dte_arithmetic_1.fail)('HEADER_TOTAL_MISMATCH', 'Subtotal, IVA e impuestos adicionales XML no cuadran con el total fiscal.', {
|
|
364
|
+
declaredAmount: totalAmount,
|
|
365
|
+
derivedAmount: headerTotal
|
|
366
|
+
});
|
|
367
|
+
const diagnostic = diagnostics.find(d => d.code === 'HEADER_TOTAL_MISMATCH');
|
|
368
|
+
diagnostic.severity = 'INFO';
|
|
369
|
+
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.';
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
const observations = diagnostics.filter(d => d.code === 'GLOBAL_ADJUSTMENT_REQUIRES_PERCENT' || d.code === 'HEADER_TOTAL_MISMATCH').map(({ code, message, declaredAmount, derivedAmount }) => ({
|
|
373
|
+
code,
|
|
374
|
+
message, ...(declaredAmount !== undefined ? { declaredAmount } : {}), ...(derivedAmount !== undefined ? { derivedAmount } : {})
|
|
375
|
+
}));
|
|
376
|
+
return {
|
|
377
|
+
netAmount,
|
|
378
|
+
exemptAmount,
|
|
379
|
+
vatAmount,
|
|
380
|
+
totalAmount,
|
|
381
|
+
payableAmount,
|
|
382
|
+
lines,
|
|
383
|
+
taxes, ...(globalDiscount ? { globalDiscount } : {}), ...(surcharge ? { globalSurcharge: surcharge } : {}), ...(nonBillableLines.length ? {
|
|
384
|
+
nonBillable: {
|
|
385
|
+
amount: nonBillableAmount,
|
|
386
|
+
lines: nonBillableLines
|
|
387
|
+
}
|
|
388
|
+
} : {}), ...(inferred ? { grossAmountsInferred: true } : {}), ...(lineRounding !== undefined ? { lineRounding } : {}), ...(totalRounding ? { totalRounding } : {}), ...(observations.length ? { observations } : {})
|
|
389
|
+
};
|
|
390
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { DteFiscalDetail, ExactDteFiscalDetail } from './invoice-xml';
|
|
2
|
+
export declare function validateComponentAmounts(detail: DteFiscalDetail | ExactDteFiscalDetail): void;
|
|
3
|
+
/** Decimal syntax is independent of the chosen monetary representation. */
|
|
4
|
+
export declare function validateDteSourceDecimals(detail: DteFiscalDetail | ExactDteFiscalDetail): void;
|
|
5
|
+
/** Shared source invariants; arithmetic feasibility is evaluated separately by reconciliation. */
|
|
6
|
+
export declare function validateDteImportSource(detail: DteFiscalDetail | ExactDteFiscalDetail): void;
|
|
7
|
+
export declare function validateFiscalReference(detail: Pick<DteFiscalDetail, 'documentType' | 'references' | 'issuedDate'>): void;
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.validateComponentAmounts = validateComponentAmounts;
|
|
4
|
+
exports.validateDteSourceDecimals = validateDteSourceDecimals;
|
|
5
|
+
exports.validateDteImportSource = validateDteImportSource;
|
|
6
|
+
exports.validateFiscalReference = validateFiscalReference;
|
|
7
|
+
const dte_money_1 = require("./dte-money");
|
|
8
|
+
const dte_arithmetic_1 = require("./dte-arithmetic");
|
|
9
|
+
const dte_identity_1 = require("./dte-identity");
|
|
10
|
+
function validateComponentAmounts(detail) {
|
|
11
|
+
try {
|
|
12
|
+
for (const value of Object.values(detail.fiscalConditions ?? {}))
|
|
13
|
+
if (!Number.isSafeInteger(value) || value < 0)
|
|
14
|
+
(0, dte_arithmetic_1.fail)('INVALID_FISCAL_CONDITION', 'Condición fiscal XML inválida.');
|
|
15
|
+
for (const value of Object.values(detail.fiscalComponents ?? {}))
|
|
16
|
+
(0, dte_money_1.exactDteMoney)(value);
|
|
17
|
+
for (const line of detail.lines)
|
|
18
|
+
if (line.retention) {
|
|
19
|
+
for (const value of [line.retention.meatProcessingBase, line.retention.marginBase])
|
|
20
|
+
if (value !== null)
|
|
21
|
+
(0, dte_money_1.exactDteMoney)(value);
|
|
22
|
+
if (line.retention.consumerUnitPrice !== null)
|
|
23
|
+
(0, dte_arithmetic_1.decimal)(line.retention.consumerUnitPrice);
|
|
24
|
+
}
|
|
25
|
+
for (const commission of detail.commissions ?? []) {
|
|
26
|
+
(0, dte_money_1.exactDteMoney)(commission.netAmount);
|
|
27
|
+
(0, dte_money_1.exactDteMoney)(commission.exemptAmount);
|
|
28
|
+
if (commission.vatAmount !== null)
|
|
29
|
+
(0, dte_money_1.exactDteMoney)(commission.vatAmount);
|
|
30
|
+
if (commission.rate !== null)
|
|
31
|
+
(0, dte_arithmetic_1.decimal)(commission.rate);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
if (error instanceof dte_arithmetic_1.DteInterpretationError)
|
|
36
|
+
throw error;
|
|
37
|
+
(0, dte_arithmetic_1.fail)('INVALID_AMOUNT', 'Los componentes fiscales contienen importes fuera de su representación exacta.');
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** Decimal syntax is independent of the chosen monetary representation. */
|
|
41
|
+
function validateDteSourceDecimals(detail) {
|
|
42
|
+
if (detail.vatRate != null)
|
|
43
|
+
(0, dte_arithmetic_1.decimal)(detail.vatRate);
|
|
44
|
+
for (const adjustment of detail.adjustments)
|
|
45
|
+
(0, dte_arithmetic_1.decimal)(adjustment.value);
|
|
46
|
+
for (const line of detail.lines) {
|
|
47
|
+
for (const value of [line.quantity, line.unitPrice, line.discountPercent, line.surchargePercent]) {
|
|
48
|
+
if (value != null)
|
|
49
|
+
(0, dte_arithmetic_1.decimal)(value);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
for (const tax of detail.taxes)
|
|
53
|
+
if (tax.rate != null)
|
|
54
|
+
(0, dte_arithmetic_1.decimal)(tax.rate);
|
|
55
|
+
}
|
|
56
|
+
/** Shared source invariants; arithmetic feasibility is evaluated separately by reconciliation. */
|
|
57
|
+
function validateDteImportSource(detail) {
|
|
58
|
+
if (!detail || ![33, 34, 61].includes(detail.documentType))
|
|
59
|
+
(0, dte_arithmetic_1.fail)('UNSUPPORTED_DOCUMENT', 'Tipo de documento fuera del alcance de importación.');
|
|
60
|
+
if (!Array.isArray(detail.lines) || !detail.lines.length || detail.lines.length > 1000 || !Array.isArray(detail.taxes) || !Array.isArray(detail.adjustments) || !Array.isArray(detail.references)) {
|
|
61
|
+
(0, dte_arithmetic_1.fail)('INVALID_LINES', 'Detalle XML incompleto o fuera de límites.');
|
|
62
|
+
}
|
|
63
|
+
validateFiscalReference(detail);
|
|
64
|
+
validateComponentAmounts(detail);
|
|
65
|
+
validateDteSourceDecimals(detail);
|
|
66
|
+
const numbers = new Set();
|
|
67
|
+
for (const line of detail.lines) {
|
|
68
|
+
if (!Number.isSafeInteger(line.lineNumber) || line.lineNumber < 1 || numbers.has(line.lineNumber)) {
|
|
69
|
+
(0, dte_arithmetic_1.fail)('INVALID_LINE_IDENTITY', 'La identidad de las líneas XML es inválida o está repetida.');
|
|
70
|
+
}
|
|
71
|
+
numbers.add(line.lineNumber);
|
|
72
|
+
}
|
|
73
|
+
for (const tax of detail.taxes) {
|
|
74
|
+
if (!Number.isSafeInteger(tax.type) || tax.type < 1 || tax.type > 999)
|
|
75
|
+
(0, dte_arithmetic_1.fail)('INVALID_TAX_CODE', 'Código XML de impuesto inválido.');
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
function validateFiscalReference(detail) {
|
|
79
|
+
if (detail.documentType !== 61)
|
|
80
|
+
return;
|
|
81
|
+
const references = detail.references.filter(r => r && /^\d{1,3}$/.test(r.documentType) && Number(r.documentType) < 200 && Number(r.documentType) > 0);
|
|
82
|
+
if (!references.length || references.some(r => !(0, dte_identity_1.validDteCreditReference)(r) || r.date > detail.issuedDate) || references.some(r => r.code === 1 || r.code === 2) && references.length !== 1)
|
|
83
|
+
(0, dte_arithmetic_1.fail)('INVALID_FISCAL_REFERENCE', 'La nota de crédito requiere referencias fiscales originales válidas.');
|
|
84
|
+
}
|