@devly-cl/sii-client 0.7.9 → 0.7.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +68 -2
  2. package/dist/application/document-status.d.ts +5 -5
  3. package/dist/application/document-status.js +14 -9
  4. package/dist/application/dte-import-mapper.d.ts +8 -0
  5. package/dist/application/dte-import-mapper.js +25 -0
  6. package/dist/application/dte-import-model.d.ts +28 -0
  7. package/dist/application/dte-import-model.js +2 -0
  8. package/dist/application/dte-import.d.ts +37 -0
  9. package/dist/application/dte-import.js +352 -0
  10. package/dist/application/invoice-queries.d.ts +12 -6
  11. package/dist/application/invoice-queries.js +9 -5
  12. package/dist/application/issuance.d.ts +2 -2
  13. package/dist/application/issuance.js +26 -10
  14. package/dist/contracts.d.ts +32 -0
  15. package/dist/contracts.js +17 -0
  16. package/dist/domain/civil-date.d.ts +2 -0
  17. package/dist/domain/civil-date.js +10 -0
  18. package/dist/domain/document-status.d.ts +0 -4
  19. package/dist/domain/document-status.js +18 -11
  20. package/dist/domain/document.js +47 -9
  21. package/dist/domain/dte-arithmetic.d.ts +35 -0
  22. package/dist/domain/dte-arithmetic.js +78 -0
  23. package/dist/domain/dte-components.d.ts +9 -0
  24. package/dist/domain/dte-components.js +37 -0
  25. package/dist/domain/dte-detail.d.ts +111 -0
  26. package/dist/domain/dte-detail.js +2 -0
  27. package/dist/domain/dte-identity.d.ts +19 -0
  28. package/dist/domain/dte-identity.js +52 -0
  29. package/dist/domain/dte-money.d.ts +41 -0
  30. package/dist/domain/dte-money.js +81 -0
  31. package/dist/domain/dte-reconciliation-model.d.ts +87 -0
  32. package/dist/domain/dte-reconciliation-model.js +2 -0
  33. package/dist/domain/dte-reconciliation.d.ts +14 -4
  34. package/dist/domain/dte-reconciliation.js +211 -172
  35. package/dist/domain/dte-validation.d.ts +7 -0
  36. package/dist/domain/dte-validation.js +84 -0
  37. package/dist/domain/invoice-xml.d.ts +12 -151
  38. package/dist/domain/invoice-xml.js +0 -10
  39. package/dist/domain/invoicing.d.ts +30 -4
  40. package/dist/domain/invoicing.js +75 -21
  41. package/dist/domain/issued-invoice.d.ts +0 -6
  42. package/dist/domain/rcv-document.d.ts +0 -4
  43. package/dist/domain/received-invoice.d.ts +1 -4
  44. package/dist/index.d.ts +18 -10
  45. package/dist/index.js +18 -5
  46. package/dist/infrastructure/document-status-gateway.d.ts +6 -4
  47. package/dist/infrastructure/document-status-gateway.js +34 -13
  48. package/dist/infrastructure/document-status-parser.js +38 -12
  49. package/dist/infrastructure/dte-xml-mapper.d.ts +16 -0
  50. package/dist/infrastructure/dte-xml-mapper.js +381 -0
  51. package/dist/infrastructure/dte-xml.d.ts +40 -4
  52. package/dist/infrastructure/dte-xml.js +116 -238
  53. package/dist/infrastructure/facturador-gateway.d.ts +10 -7
  54. package/dist/infrastructure/facturador-gateway.js +256 -56
  55. package/dist/infrastructure/facturador.js +14 -7
  56. package/dist/infrastructure/invoice-pdf.js +10 -3
  57. package/dist/infrastructure/rcv-gateway.d.ts +7 -4
  58. package/dist/infrastructure/rcv-gateway.js +53 -12
  59. package/dist/infrastructure/rcv-normalization.d.ts +8 -1
  60. package/dist/infrastructure/rcv-normalization.js +54 -12
  61. package/dist/infrastructure/read-options.d.ts +3 -0
  62. package/dist/infrastructure/read-options.js +25 -0
  63. package/dist/infrastructure/sii-client.d.ts +98 -13
  64. package/dist/infrastructure/sii-client.js +182 -31
  65. package/dist/infrastructure/sii-http-session.d.ts +2 -2
  66. package/dist/infrastructure/sii-http-session.js +83 -19
  67. package/dist/sii-error.d.ts +4 -0
  68. package/dist/sii-error.js +38 -13
  69. package/package.json +2 -2
@@ -1,211 +1,216 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.normalizeDteFolio = normalizeDteFolio;
4
3
  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
- }
4
+ const dte_components_1 = require("./dte-components");
5
+ const dte_arithmetic_1 = require("./dte-arithmetic");
6
+ const dte_validation_1 = require("./dte-validation");
45
7
  function lineAdjustment(gross, price, quantity, percent, declared, kind, info) {
46
- const amount = money(declared ?? 0), pct = decimal(percent ?? '0');
8
+ const amount = (0, dte_arithmetic_1.money)(declared ?? 0), pct = (0, dte_arithmetic_1.decimal)(percent ?? '0');
47
9
  if (pct.n > pct.d * 100n)
48
- fail('INVALID_PERCENT', 'Porcentaje de ajuste de línea fuera de rango.');
10
+ (0, dte_arithmetic_1.fail)('INVALID_PERCENT', 'Porcentaje de ajuste de línea fuera de rango.');
49
11
  if (!pct.n)
50
12
  return amount;
51
13
  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);
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);
54
16
  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)],
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)],
60
22
  ];
61
23
  const matched = candidates.find(([, value]) => value === BigInt(amount));
62
24
  if (!matched)
63
- fail('LINE_ADJUSTMENT_MISMATCH', 'El monto del descuento o recargo de línea no coincide con el porcentaje informado.');
25
+ (0, dte_arithmetic_1.fail)('LINE_ADJUSTMENT_MISMATCH', 'El monto del descuento o recargo de línea no coincide con el porcentaje informado.');
64
26
  if (matched[0] !== 'PERCENT_OF_PRODUCT')
65
27
  info(`${kind}_${matched[0]}`, 'El ajuste declarado concilia con un método de redondeo distinto al porcentaje del producto exacto.');
66
28
  return amount;
67
29
  }
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. */
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
+ */
84
42
  function reconcileDteDetail(detail) {
85
43
  const diagnostics = [];
86
44
  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,
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,
89
53
  grossAmounts: detail.grossAmounts ?? null,
90
54
  };
91
55
  try {
92
56
  return { version: 1, status: 'RECONCILED', declared, derived: reconcile(detail, diagnostics), diagnostics };
93
57
  }
94
58
  catch (error) {
95
- if (!(error instanceof Review))
59
+ if (!(error instanceof dte_arithmetic_1.DteInterpretationError))
96
60
  throw error;
97
61
  if (!diagnostics.some(d => d.severity === 'ERROR' && d.code === error.code))
98
- diagnostics.push({ code: error.code, severity: 'ERROR', message: error.message, ...error.amounts });
62
+ diagnostics.push({
63
+ code: error.code,
64
+ severity: 'ERROR',
65
+ message: error.message, ...error.amounts
66
+ });
99
67
  return { version: 1, status: 'REVIEW_REQUIRED', declared, derived: null, diagnostics };
100
68
  }
101
69
  }
102
70
  function reconcile(detail, diagnostics) {
103
- const info = (code, message, lineNumber, amounts) => diagnostics.push({ code, severity: 'INFO', message, ...(lineNumber !== undefined ? { lineNumber } : {}), ...amounts });
71
+ const info = (code, message, lineNumber, amounts) => diagnostics.push({
72
+ code,
73
+ severity: 'INFO',
74
+ message, ...(lineNumber !== undefined ? { lineNumber } : {}), ...amounts
75
+ });
104
76
  if (![33, 34, 61].includes(detail.documentType))
105
- fail('UNSUPPORTED_DOCUMENT', 'Tipo de documento fuera del alcance de conciliación.');
77
+ (0, dte_arithmetic_1.fail)('UNSUPPORTED_DOCUMENT', 'Tipo de documento fuera del alcance de conciliación.');
106
78
  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);
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);
111
83
  if ((detail.documentType === 34 && (netAmount || vatAmount)) || (netAmount && exemptAmount))
112
- fail('UNSUPPORTED_TAX_SPLIT', 'La combinación de importes afectos y exentos requiere revisión.');
84
+ (0, dte_arithmetic_1.fail)('UNSUPPORTED_TAX_SPLIT', 'La combinación de importes afectos y exentos requiere revisión.');
113
85
  const exempt = detail.documentType === 34 || (!netAmount && exemptAmount > 0);
114
86
  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);
87
+ (0, dte_arithmetic_1.money)(tax.amount);
118
88
  if (tax.rate !== null)
119
- decimal(tax.rate);
120
- return { ...tax, kind: tax.type === 18 ? 'ANTICIPATED' : 'ADDITIONAL' };
89
+ (0, dte_arithmetic_1.decimal)(tax.rate);
90
+ return (0, dte_components_1.projectDteTax)(detail, tax);
121
91
  });
122
92
  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)]);
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);
125
98
  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)));
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)));
129
108
  const precise = [];
130
109
  let lines = detail.lines.map((source, index) => {
131
- const lineNumber = source.lineNumber ?? index + 1, quantityText = source.quantity ?? '1', quantity = decimal(quantityText);
110
+ const lineNumber = source.lineNumber ?? index + 1, quantityText = source.quantity ?? '1', quantity = (0, dte_arithmetic_1.decimal)(quantityText);
132
111
  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.');
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.');
137
116
  if (!exempt && indicator === 1)
138
- fail('UNSUPPORTED_TAX_SPLIT', 'Las líneas exentas y afectas requieren conciliación separada.');
117
+ (0, dte_arithmetic_1.fail)('UNSUPPORTED_TAX_SPLIT', 'Las líneas exentas y afectas requieren conciliación separada.');
139
118
  let priceText = source.unitPrice;
140
119
  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));
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));
144
123
  info('DERIVED_UNIT_PRICE', 'Precio unitario derivado del importe declarado y la cantidad.', lineNumber);
145
124
  }
146
- const price = decimal(priceText), gross = multiply(quantity, price);
125
+ const price = (0, dte_arithmetic_1.decimal)(priceText), gross = (0, dte_arithmetic_1.multiply)(quantity, price);
147
126
  const lineInfo = (code, message) => info(code, message, lineNumber);
148
127
  const discount = lineAdjustment(gross, price, quantity, source.discountPercent, source.discountAmount, 'DISCOUNT', lineInfo);
149
128
  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' };
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
+ };
156
148
  });
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]);
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);
163
159
  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.');
160
+ (0, dte_arithmetic_1.fail)('PAYABLE_TOTAL_MISMATCH', 'El valor a pagar no cuadra con los totalizadores XML.');
165
161
  for (const [field, expected] of [['periodAmount', periodAmount], ['payableAmount', payableAmount]]) {
166
162
  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 });
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
+ });
168
167
  }
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));
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));
171
173
  let discount = 0, globalSurcharge = 0;
172
174
  for (const adjustment of detail.adjustments) {
173
175
  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
+ (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);
176
178
  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
+ (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))));
179
181
  if (adjustment.movement === 'D')
180
- discount = money(discount + amount);
182
+ discount = (0, dte_arithmetic_1.money)(discount + amount);
181
183
  else
182
- globalSurcharge = money(globalSurcharge + amount);
183
- money(lineTotal - discount + globalSurcharge);
184
+ globalSurcharge = (0, dte_arithmetic_1.money)(globalSurcharge + amount);
185
+ (0, dte_arithmetic_1.money)(lineTotal - discount + globalSurcharge);
184
186
  }
185
187
  if (discount && globalSurcharge)
186
- fail('MIXED_GLOBAL_ADJUSTMENTS', 'La combinación de descuentos y recargos globales requiere revisión de su distribución.');
188
+ (0, dte_arithmetic_1.fail)('MIXED_GLOBAL_ADJUSTMENTS', 'La combinación de descuentos y recargos globales requiere revisión de su distribución.');
187
189
  const subtotal = netAmount + exemptAmount;
188
190
  const inferred = detail.grossAmounts === undefined && !exempt && !taxes.length && !nonBillableLines.length && netAmount > 0 && vatAmount > 0 && rate.n === 19n * rate.d && lineTotal - discount + globalSurcharge === totalAmount;
189
191
  if (BigInt(vatAmount) !== expectedVat) {
190
192
  // Gross historic documents may total independently rounded VAT per line.
191
193
  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));
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));
193
195
  const preciseVat = !truncatedVat && !discount && !globalSurcharge && !exempt && !detail.grossAmounts && !inferred && detail.vatRate != null
194
196
  && 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);
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);
196
198
  const perLineVat = !truncatedVat && !discount && !globalSurcharge && (detail.grossAmounts || inferred) && !taxes.length
197
199
  ? ['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);
200
+ const value = (0, dte_arithmetic_1.fraction)(BigInt(line.declaredAmount) * rate.n, rate.d * 100n + rate.n);
199
201
  if (method === 'PER_UNIT_NEAREST') {
200
202
  if (line.discountAmount || line.surchargeAmount)
201
203
  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
+ 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)));
204
206
  }
205
- return sum + (method === 'NEAREST' ? round(value) : method === 'CEILING' ? (value.n + value.d - 1n) / value.d : value.n / value.d);
207
+ return sum + (method === 'NEAREST' ? (0, dte_arithmetic_1.round)(value) : method === 'CEILING' ? (value.n + value.d - 1n) / value.d : value.n / value.d);
206
208
  }, 0n) === BigInt(vatAmount)) : undefined;
207
209
  if (!truncatedVat && !perLineVat && !preciseVat)
208
- fail('VAT_MISMATCH', 'El IVA del XML no cuadra con el neto fiscal y la tasa declarada.');
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
+ });
209
214
  if (preciseVat)
210
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.');
211
216
  else
@@ -216,21 +221,21 @@ function reconcile(detail, diagnostics) {
216
221
  let lineRounding;
217
222
  if (detail.grossAmounts || inferred) {
218
223
  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;
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;
221
226
  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);
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);
224
229
  let fiscalIndex = 0;
225
230
  lines = lines.map(l => {
226
- if (l.category === 'NON_BILLABLE' || l.category === 'NON_BILLABLE_DEDUCTION')
231
+ if (l.category !== 'TAXABLE' && l.category !== 'EXEMPT')
227
232
  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.');
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.');
234
239
  return { ...l, unitPrice: price, discountAmount: lineDiscount, surchargeAmount: surcharge, netAmount: net };
235
240
  });
236
241
  if (discount)
@@ -245,26 +250,29 @@ function reconcile(detail, diagnostics) {
245
250
  if (globalSurcharge)
246
251
  surcharge = { netAmount: globalSurcharge };
247
252
  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.');
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.');
251
256
  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 });
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
+ });
253
261
  }
254
262
  }
255
263
  for (const source of detail.lines) {
256
264
  const codes = source.additionalTaxCodes ?? [];
257
265
  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.');
266
+ (0, dte_arithmetic_1.fail)('INVALID_LINE_TAX_CODES', 'Códigos de impuesto de línea duplicados o fuera de alcance.');
259
267
  for (const code of codes) {
260
268
  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.');
269
+ (0, dte_arithmetic_1.fail)('UNSUPPORTED_LINE_TAX', 'Código de impuesto de línea fuera del alcance de conciliación.');
262
270
  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.');
271
+ (0, dte_arithmetic_1.fail)('MISSING_HEADER_TAX', 'Un impuesto de línea no tiene su monto declarado en el encabezado.');
264
272
  }
265
273
  }
266
274
  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);
275
+ const fixedMixedAdjustment = distinctCodes.size > 1 && detail.adjustments.some(adjustment => adjustment.valueType === '$' && (0, dte_arithmetic_1.decimal)(adjustment.value).n !== 0n);
268
276
  if (fixedMixedAdjustment) {
269
277
  const code = 'GLOBAL_ADJUSTMENT_REQUIRES_PERCENT';
270
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.';
@@ -273,47 +281,59 @@ function reconcile(detail, diagnostics) {
273
281
  for (const tax of taxes) {
274
282
  const scope = detail.lines.flatMap((source, index) => source.additionalTaxCodes?.includes(tax.type) ? [index] : []);
275
283
  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.');
284
+ (0, dte_arithmetic_1.fail)('MISSING_TAX_BASE', 'La base del impuesto adicional no puede identificarse en las líneas fiscales.');
277
285
  if (tax.rate === null) {
278
286
  if (tax.amount)
279
- fail('MISSING_TAX_RATE', 'El impuesto adicional requiere su tasa declarada para conciliar la base.');
287
+ (0, dte_arithmetic_1.fail)('MISSING_TAX_RATE', 'El impuesto adicional requiere su tasa declarada para conciliar la base.');
280
288
  info('ZERO_TAX_WITHOUT_RATE', 'Impuesto declarado en cero sin tasa; no se deriva una tasa del documento.');
281
289
  continue;
282
290
  }
283
- const percentage = decimal(tax.rate);
291
+ const percentage = (0, dte_arithmetic_1.decimal)(tax.rate);
284
292
  if (percentage.n > percentage.d * 100n)
285
- fail('INVALID_TAX_RATE', 'Tasa de impuesto adicional fuera de alcance.');
293
+ (0, dte_arithmetic_1.fail)('INVALID_TAX_RATE', 'Tasa de impuesto adicional fuera de alcance.');
286
294
  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 });
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
+ });
288
299
  if (!lineTotal && (discount || globalSurcharge))
289
- fail('MISSING_TAX_BASE', 'No hay base de líneas para distribuir el ajuste global del impuesto.');
300
+ (0, dte_arithmetic_1.fail)('MISSING_TAX_BASE', 'No hay base de líneas para distribuir el ajuste global del impuesto.');
290
301
  if (fixedMixedAdjustment)
291
302
  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;
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;
297
308
  const candidates = [
298
- ['GROUP_NEAREST', round(computed)],
309
+ ['GROUP_NEAREST', (0, dte_arithmetic_1.round)(computed)],
299
310
  ['GROUP_TRUNCATED', computed.n / computed.d],
300
311
  ['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)],
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)],
303
314
  ];
304
315
  const method = candidates.find(([, value]) => value === BigInt(tax.amount));
305
316
  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)) });
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
+ });
307
321
  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)) });
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
+ });
309
326
  }
310
327
  let totalRounding;
311
328
  if (headerTotal !== totalAmount) {
312
329
  const difference = totalAmount - headerTotal;
313
330
  // Global adjustments lack structured per-line allocation; never guess their scope to explain a total.
314
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)) {
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);
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);
317
337
  for (const basis of ['DECLARED_LINE_AMOUNTS', 'EXACT_PRODUCTS']) {
318
338
  if (basis === 'EXACT_PRODUCTS' && detail.lines.some((source, i) => !lines[i].category.startsWith('NON_BILLABLE') && (source.unitPrice == null || source.quantity == null)))
319
339
  continue;
@@ -322,10 +342,10 @@ function reconcile(detail, diagnostics) {
322
342
  const line = lines[i];
323
343
  if (line.category.startsWith('NON_BILLABLE'))
324
344
  continue;
325
- const base = basis === 'DECLARED_LINE_AMOUNTS' ? fraction(BigInt(line.netAmount)) : precise[i];
326
- candidate += round(line.category === 'EXEMPT' ? base : multiply(base, vatFactor));
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));
327
347
  for (const code of detail.lines[i].additionalTaxCodes ?? [])
328
- candidate += round(multiply(base, taxRates.get(code)));
348
+ candidate += (0, dte_arithmetic_1.round)((0, dte_arithmetic_1.multiply)(base, taxRates.get(code)));
329
349
  }
330
350
  if (candidate === BigInt(totalAmount)) {
331
351
  totalRounding = { difference, method: 'PER_LINE_VAT_AND_TAX', basis, componentTotal: headerTotal };
@@ -340,12 +360,31 @@ function reconcile(detail, diagnostics) {
340
360
  if (!totalRounding) {
341
361
  const originalLineValues = detail.lines.every((source, i) => lines[i].category.startsWith('NON_BILLABLE') || source.quantity != null && source.unitPrice != null);
342
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))
343
- fail('HEADER_TOTAL_MISMATCH', 'Subtotal, IVA e impuestos adicionales XML no cuadran con el total fiscal.', { declaredAmount: totalAmount, derivedAmount: headerTotal });
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
+ });
344
367
  const diagnostic = diagnostics.find(d => d.code === 'HEADER_TOTAL_MISMATCH');
345
368
  diagnostic.severity = 'INFO';
346
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.';
347
370
  }
348
371
  }
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 } : {}) };
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
+ };
351
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;