@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.
Files changed (70) hide show
  1. package/README.md +84 -1
  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 +49 -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 +15 -0
  34. package/dist/domain/dte-reconciliation.js +390 -0
  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 +17 -57
  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 +19 -9
  45. package/dist/index.js +20 -4
  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 +117 -196
  53. package/dist/infrastructure/facturador-gateway.d.ts +10 -7
  54. package/dist/infrastructure/facturador-gateway.js +256 -56
  55. package/dist/infrastructure/facturador.d.ts +1 -1
  56. package/dist/infrastructure/facturador.js +18 -10
  57. package/dist/infrastructure/invoice-pdf.js +10 -3
  58. package/dist/infrastructure/rcv-gateway.d.ts +7 -4
  59. package/dist/infrastructure/rcv-gateway.js +53 -12
  60. package/dist/infrastructure/rcv-normalization.d.ts +8 -1
  61. package/dist/infrastructure/rcv-normalization.js +54 -12
  62. package/dist/infrastructure/read-options.d.ts +3 -0
  63. package/dist/infrastructure/read-options.js +25 -0
  64. package/dist/infrastructure/sii-client.d.ts +98 -13
  65. package/dist/infrastructure/sii-client.js +182 -31
  66. package/dist/infrastructure/sii-http-session.d.ts +2 -2
  67. package/dist/infrastructure/sii-http-session.js +134 -37
  68. package/dist/sii-error.d.ts +5 -0
  69. package/dist/sii-error.js +39 -13
  70. package/package.json +2 -2
@@ -0,0 +1,352 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.projectDteForImportExact = exports.projectDteForImport = void 0;
4
+ exports.buildDteImportProjection = buildDteImportProjection;
5
+ exports.buildDteImportProjectionExact = buildDteImportProjectionExact;
6
+ const dte_components_1 = require("../domain/dte-components");
7
+ const dte_money_1 = require("../domain/dte-money");
8
+ const dte_reconciliation_1 = require("../domain/dte-reconciliation");
9
+ const dte_arithmetic_1 = require("../domain/dte-arithmetic");
10
+ const dte_validation_1 = require("../domain/dte-validation");
11
+ const dte_import_mapper_1 = require("./dte-import-mapper");
12
+ /**
13
+ * Construye los importes comerciales de un DTE 33, 34 o 61 cuya identidad ya fue verificada.
14
+ * Conserva los totales declarados; puede derivar precios netos, excluir ítems informativos o entregar
15
+ * un resumen con lineBasis='SUMMARY' y lineNumber=0. El detalle original no se modifica.
16
+ *
17
+ * @param detail Hechos declarados, obtenidos del parser o de una fuente previamente verificada.
18
+ * @param options referenceTotalAmount es el total RCV opcional; una diferencia genera una observación.
19
+ * @returns IMPORTABLE con importes y observaciones, o REVIEW_REQUIRED con amounts=null por datos no representables.
20
+ * Un ERROR de conciliación puede coexistir con IMPORTABLE: la política conserva los valores del XML.
21
+ * @throws Los errores inesperados no se ocultan. Los montos numéricos deben ser enteros seguros.
22
+ * @example
23
+ * const result = buildDteImportProjection(parsed.detail);
24
+ * if (result.status === 'IMPORTABLE') console.log(result.amounts.lineBasis);
25
+ * @remarks No persiste, no autoriza acceso, no certifica aceptación fiscal ni habilita emisión.
26
+ */
27
+ function buildDteImportProjection(detail, options = {}) {
28
+ const diagnostics = [];
29
+ try {
30
+ (0, dte_validation_1.validateDteImportSource)(detail);
31
+ for (const source of detail.lines) {
32
+ (0, dte_arithmetic_1.money)(source.amount);
33
+ for (const value of [source.discountAmount, source.surchargeAmount])
34
+ if (value != null)
35
+ (0, dte_arithmetic_1.money)(value);
36
+ }
37
+ 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);
38
+ for (const value of [detail.periodAmount, detail.previousBalance, detail.payableAmount, detail.nonBillableAmount])
39
+ if (value != null)
40
+ (0, dte_arithmetic_1.money)(value, true);
41
+ const taxes = detail.taxes.map(tax => {
42
+ (0, dte_arithmetic_1.money)(tax.amount);
43
+ return (0, dte_components_1.projectDteTax)(detail, tax);
44
+ });
45
+ // IndExe=4/5 is documentary information, never a billable line or a taxable base.
46
+ const sourceLines = detail.lines.filter(line => ![4, 5].includes(line.exemptIndicator ?? 0));
47
+ const fiscalDetail = {
48
+ ...detail,
49
+ lines: sourceLines, ...(detail.documentType === 34 ? { grossAmounts: undefined } : {})
50
+ };
51
+ const reconciliation = (0, dte_reconciliation_1.reconcileDteDetail)(fiscalDetail);
52
+ diagnostics.push(...reconciliation.diagnostics);
53
+ // Unsupported detail can fail early; independently observable header differences still matter.
54
+ if (!reconciliation.derived) {
55
+ const headerTotal = (0, dte_components_1.dteHeaderTotal)(detail, taxes);
56
+ if (headerTotal !== null && headerTotal !== BigInt(totalAmount) && headerTotal >= -BigInt(Number.MAX_SAFE_INTEGER) && headerTotal <= BigInt(Number.MAX_SAFE_INTEGER) && !diagnostics.some(d => d.code === 'HEADER_TOTAL_MISMATCH'))
57
+ diagnostics.push({
58
+ code: 'HEADER_TOTAL_MISMATCH',
59
+ severity: 'ERROR',
60
+ message: 'Los componentes declarados del encabezado difieren del total fiscal.',
61
+ declaredAmount: totalAmount,
62
+ derivedAmount: Number(headerTotal)
63
+ });
64
+ if (headerTotal === null && !diagnostics.some(d => d.code === 'UNRESOLVED_TAX_EFFECT'))
65
+ diagnostics.push({
66
+ code: 'UNRESOLVED_TAX_EFFECT',
67
+ severity: 'ERROR',
68
+ message: 'El efecto de un impuesto o comisión no puede determinarse para el tipo y referencias originales; no se supone aditivo.'
69
+ });
70
+ if (detail.vatRate != null && !diagnostics.some(d => d.code.startsWith('VAT_'))) {
71
+ const rate = (0, dte_arithmetic_1.decimal)(detail.vatRate), expected = (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)));
72
+ if (expected !== BigInt(vatAmount) && expected <= BigInt(Number.MAX_SAFE_INTEGER))
73
+ diagnostics.push({
74
+ code: 'VAT_MISMATCH',
75
+ severity: 'ERROR',
76
+ message: 'El IVA declarado difiere del cálculo sobre el neto de encabezado y la tasa original; la distribución del documento no pudo conciliarse.',
77
+ declaredAmount: vatAmount,
78
+ derivedAmount: Number(expected)
79
+ });
80
+ }
81
+ }
82
+ const observations = [...(reconciliation.derived?.observations ?? []).map(o => ({ ...o }))];
83
+ for (const diagnostic of diagnostics.filter(d => d.severity === 'ERROR')) {
84
+ if (observations.some(o => o.code === diagnostic.code))
85
+ continue;
86
+ observations.push({
87
+ code: diagnostic.code,
88
+ message: `${diagnostic.message} Se conservan los valores declarados del XML.`, ...(diagnostic.declaredAmount !== undefined ? { declaredAmount: diagnostic.declaredAmount } : {}), ...(diagnostic.derivedAmount !== undefined ? { derivedAmount: diagnostic.derivedAmount } : {})
89
+ });
90
+ }
91
+ const nonBillableLines = sourceLines.filter(line => [2, 6].includes(line.exemptIndicator ?? 0)).map(line => ({
92
+ lineNumber: line.lineNumber,
93
+ amount: line.amount,
94
+ indicator: line.exemptIndicator
95
+ }));
96
+ const nonBillableLineTotal = (0, dte_arithmetic_1.moneySum)(nonBillableLines.map(line => line.amount * (line.indicator === 6 ? -1 : 1)), true);
97
+ const nonBillableAmount = detail.nonBillableAmount ?? nonBillableLineTotal;
98
+ // A conflicting breakdown cannot be allocated to original rows; represent the declared header separately.
99
+ const importedNonBillableLines = nonBillableAmount === nonBillableLineTotal ? nonBillableLines : [{
100
+ lineNumber: 0,
101
+ amount: Math.abs(nonBillableAmount),
102
+ indicator: nonBillableAmount < 0 ? 6 : 2
103
+ }];
104
+ const periodPayable = (0, dte_arithmetic_1.moneySum)([totalAmount, nonBillableAmount], true);
105
+ let amounts;
106
+ if (reconciliation.derived) {
107
+ amounts = {
108
+ ...reconciliation.derived,
109
+ subtotalAmount: (0, dte_arithmetic_1.moneySum)([netAmount, exemptAmount]),
110
+ lines: reconciliation.derived.lines.map(line => ({ ...line })),
111
+ taxes,
112
+ payableAmount: periodPayable,
113
+ reconciliationStatus: 'RECONCILED',
114
+ lineBasis: 'RECONCILED'
115
+ };
116
+ }
117
+ else {
118
+ const fiscalLines = sourceLines.filter(line => ![2, 6].includes(line.exemptIndicator ?? 0));
119
+ const gross = vatAmount > 0 && (detail.grossAmounts === true || detail.grossAmounts === undefined && fiscalLines.reduce((sum, line) => sum + line.amount, 0) === totalAmount && totalAmount !== netAmount + exemptAmount);
120
+ const summary = gross || detail.adjustments.length > 0 || !fiscalLines.length || sourceLines.some(line => ![0, 1, 2, 6].includes(line.exemptIndicator ?? 0) || !(0, dte_arithmetic_1.decimal)(line.quantity ?? '1').n || (0, dte_arithmetic_1.decimal)(line.discountPercent ?? '0').n > (0, dte_arithmetic_1.decimal)(line.discountPercent ?? '0').d * 100n || line.unitPrice == null && Boolean(line.discountAmount || line.surchargeAmount || (0, dte_arithmetic_1.decimal)(line.discountPercent ?? '0').n || (0, dte_arithmetic_1.decimal)(line.surchargePercent ?? '0').n));
121
+ const lines = summary
122
+ ? [{
123
+ lineNumber: 0,
124
+ quantity: '1',
125
+ unitPrice: String((0, dte_arithmetic_1.moneySum)([netAmount, exemptAmount])),
126
+ discountPercent: '0',
127
+ discountAmount: 0,
128
+ surchargeAmount: 0,
129
+ netAmount: (0, dte_arithmetic_1.moneySum)([netAmount, exemptAmount]),
130
+ declaredAmount: null,
131
+ category: netAmount ? 'TAXABLE' : 'EXEMPT'
132
+ }]
133
+ : sourceLines.map(line => {
134
+ const quantity = (0, dte_arithmetic_1.decimal)(line.quantity ?? '1');
135
+ const unitPrice = line.unitPrice ?? (0, dte_arithmetic_1.decimalText)((0, dte_arithmetic_1.fraction)(BigInt(line.amount) * quantity.d, quantity.n));
136
+ return {
137
+ lineNumber: line.lineNumber,
138
+ quantity: line.quantity ?? '1',
139
+ unitPrice,
140
+ discountPercent: line.discountPercent ?? '0',
141
+ discountAmount: line.discountAmount ?? 0,
142
+ surchargeAmount: line.surchargeAmount ?? 0,
143
+ netAmount: line.amount,
144
+ declaredAmount: line.amount,
145
+ category: line.exemptIndicator === 2 ? 'NON_BILLABLE' : line.exemptIndicator === 6 ? 'NON_BILLABLE_DEDUCTION' : detail.documentType === 34 || line.exemptIndicator === 1 ? 'EXEMPT' : 'TAXABLE'
146
+ };
147
+ });
148
+ amounts = {
149
+ netAmount,
150
+ exemptAmount,
151
+ vatAmount,
152
+ totalAmount,
153
+ subtotalAmount: (0, dte_arithmetic_1.moneySum)([netAmount, exemptAmount]),
154
+ payableAmount: periodPayable,
155
+ lines,
156
+ taxes,
157
+ reconciliationStatus: 'OBSERVED',
158
+ lineBasis: summary ? 'SUMMARY' : 'DECLARED', ...(nonBillableLines.length || nonBillableAmount ? {
159
+ nonBillable: {
160
+ amount: nonBillableAmount,
161
+ lines: importedNonBillableLines
162
+ }
163
+ } : {})
164
+ };
165
+ if (summary)
166
+ observations.push({
167
+ code: 'DOCUMENTARY_SUMMARY',
168
+ message: 'El registro comercial conserva un resumen de los importes declarados. El detalle original permanece en el XML; no se inventa una distribución neta por línea.'
169
+ });
170
+ }
171
+ Object.assign(amounts, (0, dte_import_mapper_1.mapDteImportFacts)(detail));
172
+ if (detail.previousBalance)
173
+ observations.push({
174
+ code: 'PREVIOUS_BALANCE_EXCLUDED',
175
+ message: 'El saldo anterior se conserva como antecedente del cobro y no aumenta el importe nuevo del período.',
176
+ declaredAmount: detail.previousBalance,
177
+ derivedAmount: 0
178
+ });
179
+ if (options.referenceTotalAmount !== undefined && (0, dte_arithmetic_1.money)(options.referenceTotalAmount) !== totalAmount)
180
+ observations.push({
181
+ code: 'RCV_TOTAL_DIFFERENCE',
182
+ message: `El XML declara ${totalAmount} CLP y el RCV registra ${options.referenceTotalAmount} CLP. Se conservan ambas fuentes y el registro comercial usa el total original del XML.`,
183
+ declaredAmount: totalAmount
184
+ });
185
+ if (observations.length)
186
+ amounts.reconciliationStatus = 'OBSERVED';
187
+ const lineSurcharges = detail.lines.reduce((sum, line) => sum + BigInt(line.surchargeAmount ?? 0), 0n);
188
+ if (lineSurcharges)
189
+ observations.push({
190
+ code: 'LINE_SURCHARGE',
191
+ message: `El XML declara recargos de línea por ${lineSurcharges} CLP, conservados en los importes originales.`, ...(lineSurcharges <= BigInt(Number.MAX_SAFE_INTEGER) ? { declaredAmount: Number(lineSurcharges) } : {})
192
+ });
193
+ if (reconciliation.derived?.globalSurcharge)
194
+ observations.push({
195
+ code: 'GLOBAL_SURCHARGE',
196
+ message: `El subtotal incluye un recargo global neto de ${reconciliation.derived.globalSurcharge.netAmount} CLP, conciliado por el SDK desde los ajustes originales.`,
197
+ derivedAmount: reconciliation.derived.globalSurcharge.netAmount
198
+ });
199
+ if (observations.length)
200
+ amounts.observations = observations;
201
+ return { version: 1, status: 'IMPORTABLE', amounts, diagnostics };
202
+ }
203
+ catch (error) {
204
+ if (!(error instanceof dte_arithmetic_1.DteInterpretationError))
205
+ throw error;
206
+ diagnostics.push({ code: error.code, severity: 'ERROR', message: error.message, ...error.amounts });
207
+ return { version: 1, status: 'REVIEW_REQUIRED', amounts: null, diagnostics };
208
+ }
209
+ }
210
+ /**
211
+ * Construye la misma proyección documental con importes monetarios enteros como strings.
212
+ * Comparte validaciones de fuente con la representación numérica. Por encima del rango seguro de Number,
213
+ * entrega un resumen exacto con lineBasis='SUMMARY', sin atribuir una conciliación por línea.
214
+ *
215
+ * @param detail Detalle exacto con identidad previamente verificada; precios y cantidades siguen siendo strings decimales.
216
+ * @param options referenceTotalAmount es un entero exacto opcional para observar diferencias con RCV.
217
+ * @returns IMPORTABLE o REVIEW_REQUIRED; los importes originales y la entrada se conservan.
218
+ * @see buildDteImportProjection
219
+ */
220
+ function buildDteImportProjectionExact(detail, options = {}) {
221
+ try {
222
+ return (0, dte_money_1.withExactDteAmounts)(buildDteImportProjection((0, dte_money_1.withNumberDteAmounts)(detail), options.referenceTotalAmount === undefined ? {} : {
223
+ referenceTotalAmount: (0, dte_money_1.withNumberDteAmounts)({ totalAmount: options.referenceTotalAmount }).totalAmount
224
+ }));
225
+ }
226
+ catch (error) {
227
+ if (!(error instanceof dte_money_1.DteMoneyRangeError))
228
+ return {
229
+ version: 1,
230
+ status: 'REVIEW_REQUIRED',
231
+ amounts: null,
232
+ diagnostics: [{
233
+ code: 'INVALID_AMOUNT',
234
+ severity: 'ERROR',
235
+ message: 'El modelo fiscal exacto contiene importes inválidos.'
236
+ }]
237
+ };
238
+ }
239
+ try {
240
+ (0, dte_validation_1.validateDteImportSource)(detail);
241
+ for (const source of detail.lines) {
242
+ (0, dte_money_1.exactDteMoney)(source.amount);
243
+ for (const value of [source.discountAmount, source.surchargeAmount])
244
+ if (value != null)
245
+ (0, dte_money_1.exactDteMoney)(value);
246
+ }
247
+ const netAmount = (0, dte_money_1.exactDteMoney)(detail.netAmount ?? '0'), exemptAmount = (0, dte_money_1.exactDteMoney)(detail.exemptAmount ?? '0'), vatAmount = (0, dte_money_1.exactDteMoney)(detail.vatAmount ?? '0'), totalAmount = (0, dte_money_1.exactDteMoney)(detail.totalAmount);
248
+ for (const value of [detail.nonBillableAmount, detail.periodAmount, detail.previousBalance, detail.payableAmount])
249
+ if (value != null)
250
+ (0, dte_money_1.exactDteMoney)(value, true);
251
+ const taxes = detail.taxes.map(tax => {
252
+ (0, dte_money_1.exactDteMoney)(tax.amount);
253
+ return (0, dte_components_1.projectDteTax)(detail, tax);
254
+ });
255
+ const observations = [{
256
+ code: 'EXACT_MONETARY_SUMMARY',
257
+ message: 'Los importes se conservan como enteros exactos. El resumen no atribuye una conciliación por línea que el modelo numérico no puede representar.'
258
+ }];
259
+ const components = (0, dte_components_1.dteHeaderTotal)(detail, taxes);
260
+ if (components === null)
261
+ observations.push({
262
+ code: 'UNRESOLVED_TAX_EFFECT',
263
+ message: 'El efecto de un impuesto o comisión no puede determinarse en su contexto original; no se supone aditivo.'
264
+ });
265
+ else if (components !== BigInt(totalAmount))
266
+ observations.push({
267
+ code: 'HEADER_TOTAL_MISMATCH',
268
+ message: 'Los componentes declarados difieren del total fiscal. Se conservan los valores originales del XML.',
269
+ declaredAmount: totalAmount,
270
+ derivedAmount: String(components)
271
+ });
272
+ const nonBillableLines = detail.lines.filter(line => [2, 6].includes(line.exemptIndicator ?? 0)).map(line => ({
273
+ lineNumber: line.lineNumber,
274
+ amount: (0, dte_money_1.exactDteMoney)(line.amount),
275
+ indicator: line.exemptIndicator
276
+ }));
277
+ const lineTotal = nonBillableLines.reduce((sum, line) => sum + BigInt(line.amount) * (line.indicator === 6 ? -1n : 1n), 0n);
278
+ const nonBillableAmount = detail.nonBillableAmount === undefined ? lineTotal : BigInt(detail.nonBillableAmount);
279
+ const nonBillable = {
280
+ amount: String(nonBillableAmount),
281
+ lines: nonBillableAmount === lineTotal ? nonBillableLines : [{
282
+ lineNumber: 0,
283
+ amount: String(nonBillableAmount < 0n ? -nonBillableAmount : nonBillableAmount),
284
+ indicator: nonBillableAmount < 0n ? 6 : 2
285
+ }]
286
+ };
287
+ if (nonBillableAmount !== lineTotal)
288
+ observations.push({
289
+ code: 'NON_BILLABLE_MISMATCH',
290
+ message: 'El monto no facturable se conserva como resumen del encabezado; su desglose no coincide con las líneas originales.'
291
+ });
292
+ if (detail.previousBalance && BigInt(detail.previousBalance))
293
+ observations.push({
294
+ code: 'PREVIOUS_BALANCE_EXCLUDED',
295
+ message: 'El saldo anterior se conserva como antecedente del cobro y no aumenta el importe nuevo del período.',
296
+ declaredAmount: detail.previousBalance,
297
+ derivedAmount: '0'
298
+ });
299
+ if (options.referenceTotalAmount !== undefined && (0, dte_money_1.exactDteMoney)(options.referenceTotalAmount) !== totalAmount)
300
+ observations.push({
301
+ code: 'RCV_TOTAL_DIFFERENCE',
302
+ message: 'El RCV y el XML declaran importes distintos; se conservan ambas fuentes y el total original del XML.',
303
+ declaredAmount: totalAmount
304
+ });
305
+ const subtotalAmount = String(BigInt(netAmount) + BigInt(exemptAmount));
306
+ return {
307
+ version: 1, status: 'IMPORTABLE', diagnostics: [], amounts: {
308
+ netAmount,
309
+ exemptAmount,
310
+ vatAmount,
311
+ totalAmount,
312
+ subtotalAmount,
313
+ payableAmount: String(BigInt(totalAmount) + nonBillableAmount),
314
+ lines: [{
315
+ lineNumber: 0,
316
+ quantity: '1',
317
+ unitPrice: subtotalAmount,
318
+ discountPercent: '0',
319
+ discountAmount: '0',
320
+ surchargeAmount: '0',
321
+ netAmount: subtotalAmount,
322
+ declaredAmount: null,
323
+ category: BigInt(netAmount) ? 'TAXABLE' : 'EXEMPT'
324
+ }],
325
+ taxes,
326
+ reconciliationStatus: 'OBSERVED',
327
+ lineBasis: 'SUMMARY',
328
+ observations,
329
+ ...(nonBillable.lines.length || nonBillableAmount ? { nonBillable } : {}),
330
+ ...(0, dte_import_mapper_1.mapDteImportFacts)(detail),
331
+ }
332
+ };
333
+ }
334
+ catch (error) {
335
+ if (!(error instanceof dte_arithmetic_1.DteInterpretationError) && !(error instanceof TypeError) && !(error instanceof dte_money_1.DteMoneyRangeError))
336
+ throw error;
337
+ return {
338
+ version: 1,
339
+ status: 'REVIEW_REQUIRED',
340
+ amounts: null,
341
+ diagnostics: [{
342
+ code: error instanceof dte_arithmetic_1.DteInterpretationError ? error.code : 'INVALID_AMOUNT',
343
+ severity: 'ERROR',
344
+ message: error.message
345
+ }]
346
+ };
347
+ }
348
+ }
349
+ /** @deprecated Use buildDteImportProjection. Identical documentary import policy. */
350
+ exports.projectDteForImport = buildDteImportProjection;
351
+ /** @deprecated Use buildDteImportProjectionExact. Identical exact documentary import policy. */
352
+ exports.projectDteForImportExact = buildDteImportProjectionExact;
@@ -1,23 +1,29 @@
1
- import { type IssuedInvoice, type IssuedInvoicesQuery, type IssuedInvoicesResult, type InvoiceDocumentType } from '../domain/issued-invoice';
2
- import type { RcvDocument, RcvDocumentType, RcvDocumentsQuery, RcvDocumentsResult } from '../domain/rcv-document';
3
- export interface DocumentReadPort<D extends RcvDocumentType, T extends RcvDocument> {
1
+ import { type InvoiceDocumentType, type IssuedInvoice, type IssuedInvoicesResult } from '../domain/issued-invoice';
2
+ import type { RcvDocument, RcvDocumentsResult, RcvDocumentType } from '../domain/rcv-document';
3
+ /** Period-only application input; provider controls stay in the adapter. */
4
+ export interface RcvPeriodQuery {
5
+ periodo: string;
6
+ }
7
+ type RcvIdentity = Pick<RcvDocument, 'issuerRut' | 'documentType' | 'folio'>;
8
+ export interface DocumentReadPort<D extends RcvDocumentType, T extends RcvIdentity> {
4
9
  initialLimit(): Promise<number>;
5
10
  counts(): Promise<{
6
11
  documentType: D;
7
12
  count: number;
8
13
  }[]>;
9
- details(type: D, tokenRecaptcha: string): Promise<T[]>;
14
+ details(type: D): Promise<T[]>;
10
15
  }
11
16
  export type InvoiceReadPort<T extends IssuedInvoice> = DocumentReadPort<InvoiceDocumentType, T>;
12
17
  export declare class InvoiceQueryError extends Error {
13
18
  readonly section: 'SUMMARY' | 'DETAIL';
14
19
  constructor(section: 'SUMMARY' | 'DETAIL');
15
20
  }
16
- export declare function readInvoices<T extends IssuedInvoice>(port: InvoiceReadPort<T>, query: IssuedInvoicesQuery): Promise<Omit<IssuedInvoicesResult, 'data'> & {
21
+ export declare function readInvoices<T extends IssuedInvoice>(port: InvoiceReadPort<T>, query: RcvPeriodQuery): Promise<Omit<IssuedInvoicesResult, 'data'> & {
17
22
  data: T[];
18
23
  }>;
19
24
  /** Coverage and identity reconciliation operate on normalized documents, never provider rows. */
20
- export declare function readDocuments<D extends RcvDocumentType, T extends RcvDocument>(port: DocumentReadPort<D, T>, { periodo, tokenRecaptcha }: RcvDocumentsQuery): Promise<Omit<RcvDocumentsResult, 'data' | 'incompleteDocumentTypes'> & {
25
+ export declare function readDocuments<D extends RcvDocumentType, T extends RcvIdentity>(port: DocumentReadPort<D, T>, { periodo }: RcvPeriodQuery): Promise<Omit<RcvDocumentsResult, 'data' | 'incompleteDocumentTypes'> & {
21
26
  data: T[];
22
27
  incompleteDocumentTypes: D[];
23
28
  }>;
29
+ export {};
@@ -16,10 +16,8 @@ function readInvoices(port, query) {
16
16
  return readDocuments(port, query);
17
17
  }
18
18
  /** Coverage and identity reconciliation operate on normalized documents, never provider rows. */
19
- async function readDocuments(port, { periodo, tokenRecaptcha = 't-o-k-e-n-web' }) {
19
+ async function readDocuments(port, { periodo }) {
20
20
  (0, issued_invoice_1.assertPeriod)(periodo);
21
- if (typeof tokenRecaptcha !== 'string' || !tokenRecaptcha.trim())
22
- throw new TypeError('tokenRecaptcha inválido');
23
21
  const limit = await port.initialLimit();
24
22
  const expected = new Map();
25
23
  let expectedCount = 0;
@@ -38,7 +36,7 @@ async function readDocuments(port, { periodo, tokenRecaptcha = 't-o-k-e-n-web' }
38
36
  if (count === 0)
39
37
  continue;
40
38
  let uniqueCount = 0;
41
- for (const document of await port.details(type, tokenRecaptcha)) {
39
+ for (const document of await port.details(type)) {
42
40
  const key = `${document.issuerRut}:${document.documentType}:${document.folio}`;
43
41
  const previous = documents.get(key);
44
42
  if (previous && JSON.stringify(previous) !== JSON.stringify(document))
@@ -51,5 +49,11 @@ async function readDocuments(port, { periodo, tokenRecaptcha = 't-o-k-e-n-web' }
51
49
  if (count > limit || uniqueCount !== count)
52
50
  incompleteDocumentTypes.push(type);
53
51
  }
54
- return { data: [...documents.values()], complete: incompleteDocumentTypes.length === 0, expectedCount, observedAt: new Date().toISOString(), incompleteDocumentTypes };
52
+ return {
53
+ data: [...documents.values()],
54
+ complete: incompleteDocumentTypes.length === 0,
55
+ expectedCount,
56
+ observedAt: new Date().toISOString(),
57
+ incompleteDocumentTypes
58
+ };
55
59
  }
@@ -1,6 +1,6 @@
1
1
  import { type InvoiceInput } from '../domain/invoicing';
2
- import { type PreparedDocument, type DocumentContent, type SignedDocument, type SentDocument } from '../domain/document';
3
- import type { IssuedInvoiceXmlQuery, IssuedDocumentXmlResult } from '../domain/invoice-xml';
2
+ import { type DocumentContent, type PreparedDocument, type SentDocument, type SignedDocument } from '../domain/document';
3
+ import type { IssuedDocumentXmlResult, IssuedInvoiceXmlQuery } from '../domain/invoice-xml';
4
4
  export interface SignDocumentInput {
5
5
  preparacionId: string;
6
6
  approvedHash: string;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DocumentIssuance = exports.IssuanceError = void 0;
4
+ const civil_date_1 = require("../domain/civil-date");
4
5
  const node_crypto_1 = require("node:crypto");
5
6
  const invoicing_1 = require("../domain/invoicing");
6
7
  const document_1 = require("../domain/document");
@@ -20,8 +21,12 @@ class DocumentIssuance {
20
21
  constructor(port) {
21
22
  this.port = port;
22
23
  }
23
- get pendingWrite() { return this.#write; }
24
- clearPreparation() { this.#prepared = undefined; }
24
+ get pendingWrite() {
25
+ return this.#write;
26
+ }
27
+ clearPreparation() {
28
+ this.#prepared = undefined;
29
+ }
25
30
  async prepareInvoice(input) {
26
31
  this.port.assertReady();
27
32
  const invoice = (0, invoicing_1.validateInvoice)(input);
@@ -30,7 +35,7 @@ class DocumentIssuance {
30
35
  async prepareCancellationCreditNote(input) {
31
36
  this.port.assertReady();
32
37
  const { factura, issuedDate } = input;
33
- if (factura.documentType !== 33 || !/^[1-9]\d{0,19}$/.test(factura.folio) || !/^\d{4}-\d{2}-\d{2}$/.test(issuedDate) || new Date(`${issuedDate}T00:00:00Z`).toISOString().slice(0, 10) !== issuedDate)
38
+ if (factura.documentType !== 33 || !/^[1-9]\d{0,19}$/.test(factura.folio) || !(0, civil_date_1.isCivilDate)(issuedDate))
34
39
  throw new TypeError('Referencia o fecha de anulación inválida');
35
40
  return this.#writeOperation(async () => this.#keepPreparation(await this.port.prepareCancellationCreditNote(input)));
36
41
  }
@@ -61,16 +66,27 @@ class DocumentIssuance {
61
66
  return Promise.reject(new IssuanceError('SII_OPERATION_IN_PROGRESS'));
62
67
  const promise = action();
63
68
  this.#write = promise;
64
- void promise.then(() => { this.#write = undefined; }, () => { this.#write = undefined; });
69
+ void promise.then(() => {
70
+ this.#write = undefined;
71
+ }, () => {
72
+ this.#write = undefined;
73
+ });
65
74
  return promise;
66
75
  }
67
76
  #keepPreparation(content) {
68
- const result = Object.freeze({ ...content, preparacionId: (0, node_crypto_1.randomUUID)(), contentHash: (0, invoicing_1.hashContent)(content), expiresAt: new Date(Date.now() + 300_000).toISOString() });
69
- const freeze = (value) => { if (value && typeof value === 'object') {
70
- for (const child of Object.values(value))
71
- freeze(child);
72
- Object.freeze(value);
73
- } };
77
+ const result = Object.freeze({
78
+ ...content,
79
+ preparacionId: (0, node_crypto_1.randomUUID)(),
80
+ contentHash: (0, invoicing_1.hashContent)(content),
81
+ expiresAt: new Date(Date.now() + 300_000).toISOString()
82
+ });
83
+ const freeze = (value) => {
84
+ if (value && typeof value === 'object') {
85
+ for (const child of Object.values(value))
86
+ freeze(child);
87
+ Object.freeze(value);
88
+ }
89
+ };
74
90
  freeze(result);
75
91
  this.#prepared = result;
76
92
  return result;
@@ -5,6 +5,15 @@ export type ReceivedInvoicePdfQuery = ReceivedInvoiceXmlQuery;
5
5
  export interface PdfDownloadOptions {
6
6
  signal?: AbortSignal;
7
7
  }
8
+ /** Cancellation of a public document query; handled by the HTTP adapter. */
9
+ export interface DocumentQueryOptions {
10
+ signal?: AbortSignal;
11
+ }
12
+ /** Controls arithmetic interpretation of XML reads; identity, authorization and parser limits always apply. */
13
+ export interface DteXmlReadOptions {
14
+ /** Defaults to true. False omits reconciliation and fiscal-reference interpretation; declared facts remain available. */
15
+ reconcile?: boolean;
16
+ }
8
17
  export interface InvoicePdfResult {
9
18
  stream: Readable;
10
19
  contentType: 'application/pdf';
@@ -64,3 +73,26 @@ export type CredencialesSii = SiiCredentials;
64
73
  export type ConsultaResumen = SummaryQuery;
65
74
  /** @deprecated Use SiiSession. */
66
75
  export type SesionSii = SiiSession;
76
+ /** Public RCV input; CAPTCHA belongs to the SII adapter, not the coverage use case. */
77
+ export interface RcvDocumentsQuery {
78
+ periodo: string;
79
+ tokenRecaptcha?: string;
80
+ }
81
+ export type IssuedInvoicesQuery = RcvDocumentsQuery;
82
+ export type ReceivedInvoicesQuery = RcvDocumentsQuery;
83
+ /** @deprecated Use IssuedInvoicesQuery. */
84
+ export type ConsultaFacturasEmitidas = IssuedInvoicesQuery;
85
+ /** @deprecated Use ReceivedInvoicesQuery. */
86
+ export type ConsultaFacturasRecibidas = ReceivedInvoicesQuery;
87
+ /**
88
+ * Límite técnico de un XML individual: 1 MiB. Se aplica también sin conciliación.
89
+ */
90
+ export declare const MAX_DTE_XML_BYTES = 1048576;
91
+ /**
92
+ * Fallo del parser o de la identidad esperada; no representa un dictamen tributario.
93
+ * code distingue SII_XML_INVALID de SII_XML_IDENTITY_MISMATCH.
94
+ */
95
+ export declare class DteXmlError extends Error {
96
+ readonly code: 'SII_XML_INVALID' | 'SII_XML_IDENTITY_MISMATCH';
97
+ constructor(code: 'SII_XML_INVALID' | 'SII_XML_IDENTITY_MISMATCH');
98
+ }
package/dist/contracts.js CHANGED
@@ -1,2 +1,19 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DteXmlError = exports.MAX_DTE_XML_BYTES = void 0;
4
+ /**
5
+ * Límite técnico de un XML individual: 1 MiB. Se aplica también sin conciliación.
6
+ */
7
+ exports.MAX_DTE_XML_BYTES = 1_048_576;
8
+ /**
9
+ * Fallo del parser o de la identidad esperada; no representa un dictamen tributario.
10
+ * code distingue SII_XML_INVALID de SII_XML_IDENTITY_MISMATCH.
11
+ */
12
+ class DteXmlError extends Error {
13
+ code;
14
+ constructor(code) {
15
+ super(code);
16
+ this.code = code;
17
+ }
18
+ }
19
+ exports.DteXmlError = DteXmlError;
@@ -0,0 +1,2 @@
1
+ /** Checks an ISO civil date without coercing invalid days into the following month. */
2
+ export declare function isCivilDate(value: unknown): value is string;
@@ -0,0 +1,10 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isCivilDate = isCivilDate;
4
+ /** Checks an ISO civil date without coercing invalid days into the following month. */
5
+ function isCivilDate(value) {
6
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value))
7
+ return false;
8
+ const parsed = new Date(`${value}T00:00:00Z`);
9
+ return Number.isFinite(parsed.getTime()) && parsed.toISOString().slice(0, 10) === value;
10
+ }
@@ -1,6 +1,3 @@
1
- export interface DocumentQueryOptions {
2
- signal?: AbortSignal;
3
- }
4
1
  export type DocumentDirection = 'ISSUED' | 'RECEIVED';
5
2
  export interface DocumentIdentity {
6
3
  issuerRut: string;
@@ -89,5 +86,4 @@ export declare class DocumentQueryError extends Error {
89
86
  }
90
87
  export declare function bindDocumentStatusQuery(companyRut: string, query: DocumentStatusQuery): BoundDocumentStatusQuery;
91
88
  export declare function bindRecipientEventsQuery(companyRut: string, query: RecipientEventsQuery): BoundRecipientEventsQuery;
92
- export declare function assertDocumentQueryOptions(options?: DocumentQueryOptions): void;
93
89
  export declare function assertRecipientEventsAccess(query: BoundRecipientEventsQuery, observation: RecipientEventsObservation): void;
@@ -3,8 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.DocumentQueryError = void 0;
4
4
  exports.bindDocumentStatusQuery = bindDocumentStatusQuery;
5
5
  exports.bindRecipientEventsQuery = bindRecipientEventsQuery;
6
- exports.assertDocumentQueryOptions = assertDocumentQueryOptions;
7
6
  exports.assertRecipientEventsAccess = assertRecipientEventsAccess;
7
+ const civil_date_1 = require("./civil-date");
8
8
  const rut_1 = require("./rut");
9
9
  class DocumentQueryError extends Error {
10
10
  code;
@@ -33,24 +33,31 @@ function bindDocumentStatusQuery(companyRut, query) {
33
33
  const company = (0, rut_1.parseRut)(companyRut).formatted;
34
34
  const issuerRut = query.direction === 'ISSUED' ? company : (0, rut_1.parseRut)(query.issuerRut).formatted;
35
35
  const receiverRut = query.direction === 'RECEIVED' ? company : (0, rut_1.parseRut)(query.receiverRut).formatted;
36
- if (typeof query.issuedDate !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(query.issuedDate) || !Number.isFinite(Date.parse(`${query.issuedDate}T00:00:00Z`)) || new Date(`${query.issuedDate}T00:00:00Z`).toISOString().slice(0, 10) !== query.issuedDate)
36
+ if (!(0, civil_date_1.isCivilDate)(query.issuedDate))
37
37
  throw new TypeError('Fecha de emisión inválida: YYYY-MM-DD');
38
38
  if (!Number.isSafeInteger(query.totalAmount) || query.totalAmount < 0)
39
39
  throw new TypeError('Monto total inválido: entero CLP no negativo');
40
- return { direction: query.direction, issuerRut, receiverRut, documentType: query.documentType, folio: query.folio, issuedDate: query.issuedDate, totalAmount: query.totalAmount };
40
+ return {
41
+ direction: query.direction,
42
+ issuerRut,
43
+ receiverRut,
44
+ documentType: query.documentType,
45
+ folio: query.folio,
46
+ issuedDate: query.issuedDate,
47
+ totalAmount: query.totalAmount
48
+ };
41
49
  }
42
50
  function bindRecipientEventsQuery(companyRut, query) {
43
51
  assertFields(query, Object.getOwnPropertyDescriptor(query ?? {}, 'direction')?.value === 'RECEIVED' ? ['direction', 'documentType', 'folio', 'issuerRut'] : ['direction', 'documentType', 'folio'], 'Consulta de eventos del receptor inválida');
44
52
  assertIdentity(query.direction, query.documentType, query.folio, false);
45
53
  const company = (0, rut_1.parseRut)(companyRut).formatted;
46
- return { direction: query.direction, companyRut: company, issuerRut: query.direction === 'ISSUED' ? company : (0, rut_1.parseRut)(query.issuerRut).formatted, documentType: query.documentType, folio: query.folio };
47
- }
48
- function assertDocumentQueryOptions(options) {
49
- if (options === undefined)
50
- return;
51
- assertFields(options, ['signal'], 'Opciones de consulta documental inválidas');
52
- if (options.signal !== undefined && !(options.signal instanceof AbortSignal))
53
- throw new TypeError('Señal de consulta documental inválida');
54
+ return {
55
+ direction: query.direction,
56
+ companyRut: company,
57
+ issuerRut: query.direction === 'ISSUED' ? company : (0, rut_1.parseRut)(query.issuerRut).formatted,
58
+ documentType: query.documentType,
59
+ folio: query.folio
60
+ };
54
61
  }
55
62
  function assertRecipientEventsAccess(query, observation) {
56
63
  const document = observation?.document;