@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
package/README.md CHANGED
@@ -45,8 +45,10 @@ async function getInvoices(
45
45
  | `getSummary` | Resumen RCV por período, operación y estado. |
46
46
  | `getIssuedInvoices` / `getReceivedInvoices` | Facturas 33/34 normalizadas, con cobertura del período. |
47
47
  | `getIssuedDocuments` / `getReceivedDocuments` | Documentos RCV 33/34/61 normalizados, con cobertura por tipo. |
48
+ | `getIssuedDocumentsExact` / `getReceivedDocumentsExact` | La misma lectura RCV con importes enteros exactos como cadenas. |
48
49
  | `getIssuedInvoiceXml` / `getReceivedInvoiceXml` | XML original y detalle de facturas 33/34. |
49
50
  | `getIssuedDocumentXml` / `getReceivedDocumentXml` | XML original y detalle de documentos emitidos/recibidos 33/34/61. |
51
+ | `getIssuedDocumentXmlExact` / `getReceivedDocumentXmlExact` | XML original y detalle 33/34/61 con importes de hasta 18 dígitos sin pérdida de precisión. |
50
52
  | `getIssuedInvoicePdf` / `getReceivedInvoicePdf` | PDF original 33/34 como stream `Readable` de Node.js. |
51
53
  | `getDocumentStatus` | Recepción, coincidencia de contenido y anulación reportada. |
52
54
  | `getDocumentRecipientEvents` | Eventos de facturas 33/34 como emisor o receptor. |
@@ -57,9 +59,11 @@ async function getInvoices(
57
59
 
58
60
  Las consultas RCV reciben `{ periodo, tokenRecaptcha? }` y devuelven `{ data, complete, expectedCount, observedAt, incompleteDocumentTypes }`. El XML recibido requiere `{ issuerRut, documentType, folio }`; conserva las referencias del documento.
59
61
 
60
- El detalle XML conserva, cuando existen, `nonBillableAmount` (`MontoNF`), `periodAmount` (`MontoPeriodo`), `previousBalance` (`SaldoAnterior`) y `payableAmount` (`VlrPagar`). Son totalizadores originales: no modifican `totalAmount`, no implican redondeo en efectivo y no autorizan emitir cargos adicionales. `nonBillableAmount` y `previousBalance` admiten signo; los consumidores deben conciliar las líneas y separar saldos de períodos anteriores.
62
+ Si SII repite un DTE dentro de `SetDTE` o `EnvioDTE`, la lectura utiliza la primera ocurrencia sólo cuando todas las copias son idénticas en su XML completo, incluida la firma. No basta que coincidan folio y total. Se valida la identidad esperada y se conservan íntegros los bytes y la codificación de la respuesta original. Cualquier diferencia mantiene el rechazo por ambigüedad. La preparación, firma y envío siguen exigiendo un solo DTE físico.
61
63
 
62
- Los parsers entregan además `detail.reconciliation`. `declared` conserva los totalizadores recibidos; `derived` contiene cantidades/precios decimales como strings, importes de línea conciliados, conversión bruto/neto, descuentos, impuestos adicionales o anticipados y montos no facturables. Los campos originales de `detail` y los bytes de `xml` no se reemplazan por cálculos. `normalizeDteFolio` normaliza identidades numéricas sin pasar por `Number`; `declaredFolio` conserva ceros iniciales cuando se normalizan el folio o sus referencias fiscales. Las referencias informativas de una NC se distinguen de sus referencias fiscales y los códigos de producto opcionales vacíos no eliminan el documento.
64
+ El detalle XML conserva, cuando existen, `nonBillableAmount` (`MontoNF`), `periodAmount` (`MontoPeriodo`), `previousBalance` (`SaldoAnterior`) y `payableAmount` (`VlrPagar`). Los cuatro admiten signo. Son totalizadores originales: no modifican `totalAmount`, no implican redondeo en efectivo y no autorizan emitir cargos adicionales. La proyección separa el cobro nuevo del período del saldo anterior y no acredita pagos.
65
+
66
+ Por defecto, los parsers entregan además `detail.reconciliation`. `declared` conserva los totalizadores recibidos; `derived` contiene cantidades/precios decimales como strings, importes de línea conciliados, conversión bruto/neto, descuentos, impuestos adicionales o anticipados y montos no facturables. Los campos originales de `detail` y los bytes de `xml` no se reemplazan por cálculos. `normalizeDteFolio` normaliza identidades numéricas sin pasar por `Number`; `declaredFolio` conserva ceros iniciales cuando se normalizan el folio o sus referencias fiscales. Las referencias informativas de una NC se distinguen de sus referencias fiscales y los códigos de producto opcionales vacíos no eliminan el documento.
63
67
 
64
68
  `reconcileDteDetail(detail)` permite conciliar también detalle declarado almacenado previamente. Su resultado es `RECONCILED` o `REVIEW_REQUIRED`; en revisión, `derived` es `null` y los diagnósticos explican el bloqueo. Reconoce métodos verificables de redondeo de descuentos/IVA, distribuye el neto declarado en líneas brutas y distingue redondeo por línea de redondeo del subtotal exacto. No aplica una tolerancia monetaria general, no inventa una línea para cerrar diferencias ni modifica IVA, impuestos o total declarado. Los códigos de impuesto desconocidos, alcances no soportados e inconsistencias sin explicación requieren revisión. Esta conciliación de lectura no certifica aceptación fiscal ni relaja las comprobaciones del contenido aprobado para emisión.
65
69
 
@@ -111,3 +115,65 @@ npm pack
111
115
  ```
112
116
 
113
117
  `check` valida tipos, build, integración HTTP simulada, autorización y ejemplos. Licencia: `UNLICENSED`.
118
+
119
+ ## Leer detalle sin conciliación
120
+
121
+ Los métodos XML y los tres parsers aceptan `{ reconcile: false }`. El valor predeterminado es `true`,
122
+ por lo que las llamadas existentes mantienen sus resultados y validaciones.
123
+
124
+ ```ts
125
+ import { buildDteImportProjection, reconcileDteDetail } from '@devly-cl/sii-client';
126
+
127
+ // client ya autenticado y consulta autorizada por actor, tenant, empresa, recurso y sucursal.
128
+ const result = await client.getReceivedDocumentXml(
129
+ { issuerRut: '33333333-3', documentType: 33, folio: '101' },
130
+ { reconcile: false },
131
+ );
132
+
133
+ const declared = result.detail; // Sin propiedad reconciliation; no se recalculan los importes.
134
+ const analysis = reconcileDteDetail(declared); // Opcional: explicar cálculos sobre el detalle numérico.
135
+ const projection = buildDteImportProjection(declared); // Opcional: preparar datos comerciales.
136
+ ```
137
+
138
+ Esta opción omite la conciliación y los requisitos para interpretar referencias fiscales de una NC.
139
+ Conserva RUT, emisor/receptor esperados, tipo, folio, estructura, límites de tamaño/profundidad y precisión.
140
+ No acepta DTD ni entidades externas, no omite autorización y no modifica los controles de emisión.
141
+ Las opciones inválidas se rechazan antes de iniciar nuevas solicitudes HTTP.
142
+
143
+ `getIssuedDocumentXmlExact` y `getReceivedDocumentXmlExact` aceptan la misma opción y conservan importes
144
+ monetarios como strings. Para preparar sus datos se usa `buildDteImportProjectionExact`; el conciliador
145
+ numérico no debe recibir strings monetarios sin una conversión segura explícita.
146
+
147
+ ## Responsabilidades y modelos
148
+
149
+ | Capacidad | Modelo | Responsable |
150
+ |---|---|---|
151
+ | Leer hechos declarados | `DteDeclaredDetail`, enriquecido por los DTOs XML compatibles | Parser y mapper de infraestructura |
152
+ | Explicar importes | `DteReconciliation` | Reglas puras de dominio |
153
+ | Preparar importación | `DteImportProjection` | Política de aplicación y mapper hacia datos comerciales |
154
+ | Aprobar y emitir | `InvoiceInput`, `PreparedDocument` | Caso de uso de emisión y política de contenido aprobado |
155
+
156
+ `domain/dte-detail.ts` describe hechos; `domain/dte-identity.ts`, identidad; `domain/dte-arithmetic.ts`,
157
+ aritmética exacta; y `domain/dte-reconciliation.ts`, su interpretación. `application/dte-import.ts`
158
+ decide cómo preparar una importación. Los formatos XML/RCV, CAPTCHA y cancelación se resuelven en
159
+ infraestructura. El consumidor decide la persistencia, revisión humana, RBAC, auditoría e idempotencia.
160
+
161
+ # Importación documental
162
+
163
+ `buildDteImportProjection(detail, { referenceTotalAmount })` prepara un XML cuya identidad ya fue verificada para registrarlo en un sistema consumidor. A diferencia de `reconcileDteDetail`, una discrepancia aritmética o un impuesto todavía no conciliable genera observaciones y conserva los importes declarados; no impide por sí sola el registro. El resultado distingue `RECONCILED` de `OBSERVED` y nunca autoriza emisión ni acredita pagos o crédito fiscal.
164
+
165
+ Los ítems informativos no se convierten en líneas cobrables. Impuestos específicos y códigos no clasificados conservan código, tasa e importe originales. El saldo anterior y el valor del estado de cuenta quedan separados del importe nuevo del período. Cuando no existe una conversión verificable del bruto al neto por línea, `lineBasis: 'SUMMARY'` entrega un resumen del subtotal declarado: el consumidor debe conservar y mostrar también el detalle XML original, sin inventar precios netos.
166
+
167
+ La proyección no modifica su entrada ni los bytes devueltos por los parsers. Identidad incorrecta, XML ilegible, cantidades/valores fuera de representación segura y conflictos de persistencia siguen sujetos a sus controles. Las APIs de aprobación y emisión conservan sus validaciones estrictas.
168
+
169
+ ## Lecturas exactas y componentes DTE 2.5
170
+
171
+ `getIssuedDocumentsExact`, `getReceivedDocumentsExact`, `getIssuedDocumentXmlExact` y `getReceivedDocumentXmlExact` son extensiones de lectura. Entregan importes monetarios enteros como cadenas canónicas, hasta los 18 dígitos del formato SII. Los números JSON se leen desde su texto original, antes de cualquier conversión que pierda precisión. Las llamadas existentes conservan sus contratos numéricos y rechazan importes fuera de su rango seguro.
172
+
173
+ `parseDteDocumentXmlExact(xml, identidad)` usa el mismo parser de XML; `buildDteImportProjectionExact(detail)` comparte las reglas fiscales de la proyección numérica. Para importes que superan la representación numérica, entrega un resumen documental exacto con observación, sin atribuir una conciliación por línea. `withNumberDteAmounts` es una frontera explícita para consumidores numéricos: lanza `DteMoneyRangeError` si algún importe perdería precisión. `withExactDteAmounts` convierte modelos numéricos seguros al contrato exacto. Los precios, cantidades y porcentajes decimales y los bytes/codificación del XML original se conservan.
174
+
175
+ Las referencias conservan `RUTOtr` como `issuerRut` e `IndGlobal` como `globalIndicator`. `resolveDteReferenceIdentity` devuelve la identidad concreta o `null` para una referencia global o no resoluble: un emisor explícito inválido nunca se sustituye por el emisor actual. Una NC de corrección global admite `IndGlobal=1`, `FolioRef=0`, `CodRef=3`; el folio del propio documento sigue siendo positivo.
176
+
177
+ `fiscalComponents` conserva garantías por envases, crédito de constructoras, IVA no retenido, bases especiales, IVA propio/de terceros y totalizadores de comisiones. `commissions` conserva su detalle y las líneas mantienen sus indicadores y datos de `Retenedor`. Los impuestos proyectados distinguen código/importe original de `effect` y `contribution`: las retenciones sólo se restan en su contexto fiscal conocido y un código o contexto desconocido conserva efecto `UNKNOWN`. Las bases y el IVA informativo no se suman otra vez al total. `fiscalConditions` propaga `IndNoRebaja`, forma de pago y tipos de compra/venta incluso con conciliación completa. Nada de esto determina aceptación fiscal ni derecho a crédito.
178
+
179
+ `projectDteForImport` y `projectDteForImportExact` conservan exactamente las mismas funciones como aliases de compatibilidad.
@@ -1,13 +1,13 @@
1
- import { type BoundDocumentStatusQuery, type BoundRecipientEventsQuery, type DocumentQueryOptions, type DocumentStatusQuery, type DocumentStatusResult, type DocumentVerification, type RecipientEventsQuery, type RecipientEventsResult, type RecipientEventsObservation } from '../domain/document-status';
1
+ import { type BoundDocumentStatusQuery, type BoundRecipientEventsQuery, type DocumentStatusQuery, type DocumentStatusResult, type DocumentVerification, type RecipientEventsObservation, type RecipientEventsQuery, type RecipientEventsResult } from '../domain/document-status';
2
2
  export interface DocumentReadPort {
3
3
  readonly companyRut: string;
4
4
  assertReady(): void;
5
- status(query: BoundDocumentStatusQuery, options?: DocumentQueryOptions): Promise<DocumentVerification>;
6
- recipientEvents(query: BoundRecipientEventsQuery, options?: DocumentQueryOptions): Promise<RecipientEventsObservation>;
5
+ status(query: BoundDocumentStatusQuery): Promise<DocumentVerification>;
6
+ recipientEvents(query: BoundRecipientEventsQuery): Promise<RecipientEventsObservation>;
7
7
  }
8
8
  export declare class DocumentQueries {
9
9
  private readonly port;
10
10
  constructor(port: DocumentReadPort);
11
- getDocumentStatus(query: DocumentStatusQuery, options?: DocumentQueryOptions): Promise<DocumentStatusResult>;
12
- getDocumentRecipientEvents(query: RecipientEventsQuery, options?: DocumentQueryOptions): Promise<RecipientEventsResult>;
11
+ getDocumentStatus(query: DocumentStatusQuery): Promise<DocumentStatusResult>;
12
+ getDocumentRecipientEvents(query: RecipientEventsQuery): Promise<RecipientEventsResult>;
13
13
  }
@@ -8,30 +8,35 @@ class DocumentQueries {
8
8
  constructor(port) {
9
9
  this.port = port;
10
10
  }
11
- async getDocumentStatus(query, options) {
11
+ async getDocumentStatus(query) {
12
12
  this.port.assertReady();
13
13
  const bound = (0, document_status_1.bindDocumentStatusQuery)(this.port.companyRut, query);
14
- (0, document_status_1.assertDocumentQueryOptions)(options);
15
- const result = await this.port.status(bound, options);
14
+ const result = await this.port.status(bound);
16
15
  const verification = result.verification === 'RECEIVED_MATCH'
17
16
  ? { verification: result.verification, cancellation: result.cancellation }
18
17
  : { verification: result.verification, cancellation: 'UNCONFIRMED' };
19
18
  return {
20
19
  ...verification,
21
- document: { issuerRut: bound.issuerRut, receiverRut: bound.receiverRut, documentType: bound.documentType, folio: bound.folio },
20
+ document: {
21
+ issuerRut: bound.issuerRut,
22
+ receiverRut: bound.receiverRut,
23
+ documentType: bound.documentType,
24
+ folio: bound.folio
25
+ },
22
26
  fiscalVerdict: 'NOT_OBSERVED', source: 'SII_CONTENT_QUERY', observedAt: new Date().toISOString(),
23
27
  };
24
28
  }
25
- async getDocumentRecipientEvents(query, options) {
29
+ async getDocumentRecipientEvents(query) {
26
30
  this.port.assertReady();
27
31
  const bound = (0, document_status_1.bindRecipientEventsQuery)(this.port.companyRut, query);
28
- (0, document_status_1.assertDocumentQueryOptions)(options);
29
- const result = await this.port.recipientEvents(bound, options);
32
+ const result = await this.port.recipientEvents(bound);
30
33
  (0, document_status_1.assertRecipientEventsAccess)(bound, result);
31
34
  return {
32
35
  document: {
33
- issuerRut: bound.issuerRut, receiverRut: bound.direction === 'RECEIVED' ? bound.companyRut : (0, rut_1.parseRut)(result.document.receiverRut).formatted,
34
- documentType: bound.documentType, folio: bound.folio,
36
+ issuerRut: bound.issuerRut,
37
+ receiverRut: bound.direction === 'RECEIVED' ? bound.companyRut : (0, rut_1.parseRut)(result.document.receiverRut).formatted,
38
+ documentType: bound.documentType,
39
+ folio: bound.folio,
35
40
  },
36
41
  siiReceivedAtLocal: result.siiReceivedAtLocal, timeZone: null,
37
42
  indicators: {
@@ -0,0 +1,8 @@
1
+ import type { DteFiscalDetail, ExactDteFiscalDetail } from '../domain/invoice-xml';
2
+ import type { ExactDte } from '../domain/dte-money';
3
+ import type { DteImportAmounts } from './dte-import-model';
4
+ type ImportFacts = Pick<DteImportAmounts, 'periodAmount' | 'previousBalance' | 'statementPayableAmount' | 'fiscalComponents' | 'fiscalConditions' | 'commissions'>;
5
+ /** Copies declared fiscal facts into the import DTO; no calculation, allocation or source mutation. */
6
+ export declare function mapDteImportFacts(detail: DteFiscalDetail): ImportFacts;
7
+ export declare function mapDteImportFacts(detail: ExactDteFiscalDetail): ExactDte<ImportFacts>;
8
+ export {};
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.mapDteImportFacts = mapDteImportFacts;
4
+ /** Older stored document DTOs expose these facts only in fiscalHeader. */
5
+ function fiscalConditions(detail) {
6
+ if (detail.fiscalConditions)
7
+ return { ...detail.fiscalConditions };
8
+ const header = detail.fiscalHeader;
9
+ if (!header)
10
+ return undefined;
11
+ const facts = Object.fromEntries(['noDebitReduction', 'paymentForm', 'saleType', 'purchaseType']
12
+ .flatMap(key => header[key] == null ? [] : [[key, header[key]]]));
13
+ return Object.keys(facts).length ? facts : undefined;
14
+ }
15
+ function mapDteImportFacts(detail) {
16
+ const conditions = fiscalConditions(detail);
17
+ return {
18
+ ...(detail.periodAmount !== undefined ? { periodAmount: detail.periodAmount } : {}),
19
+ ...(detail.previousBalance !== undefined ? { previousBalance: detail.previousBalance } : {}),
20
+ ...(detail.payableAmount !== undefined ? { statementPayableAmount: detail.payableAmount } : {}),
21
+ ...(detail.fiscalComponents ? { fiscalComponents: { ...detail.fiscalComponents } } : {}),
22
+ ...(conditions ? { fiscalConditions: conditions } : {}),
23
+ ...(detail.commissions ? { commissions: detail.commissions.map(item => ({ ...item })) } : {}),
24
+ };
25
+ }
@@ -0,0 +1,28 @@
1
+ import type { DteCommission, DteFiscalComponents, DteFiscalConditions } from '../domain/dte-detail';
2
+ import type { DteProjectedTax, DteReconciledAmounts, DteReconciledLine, DteReconciliationDiagnostic } from '../domain/dte-reconciliation-model';
3
+ import type { ExactDte } from '../domain/dte-money';
4
+ /** Documentary import is separate from strict arithmetic reconciliation and never authorizes issuance. */
5
+ export interface DteImportAmounts extends Omit<DteReconciledAmounts, 'taxes' | 'lines'> {
6
+ subtotalAmount: number;
7
+ /** A summary has lineNumber=0 and no declared MontoItem; original source lines remain untouched. */
8
+ lines: (Omit<DteReconciledLine, 'declaredAmount'> & {
9
+ declaredAmount: number | null;
10
+ })[];
11
+ taxes: DteProjectedTax[];
12
+ fiscalComponents?: DteFiscalComponents;
13
+ fiscalConditions?: DteFiscalConditions;
14
+ commissions?: DteCommission[];
15
+ reconciliationStatus: 'RECONCILED' | 'OBSERVED';
16
+ lineBasis: 'RECONCILED' | 'DECLARED' | 'SUMMARY';
17
+ /** Original optional collection totalizers; payableAmount covers only the new period. */
18
+ periodAmount?: number;
19
+ previousBalance?: number;
20
+ statementPayableAmount?: number;
21
+ }
22
+ export interface DteImportProjection {
23
+ version: 1;
24
+ status: 'IMPORTABLE' | 'REVIEW_REQUIRED';
25
+ amounts: DteImportAmounts | null;
26
+ diagnostics: DteReconciliationDiagnostic[];
27
+ }
28
+ export type ExactDteImportProjection = ExactDte<DteImportProjection>;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,37 @@
1
+ import type { DteFiscalDetail, ExactDteFiscalDetail } from '../domain/invoice-xml';
2
+ import type { DteImportProjection, ExactDteImportProjection } from './dte-import-model';
3
+ /**
4
+ * Construye los importes comerciales de un DTE 33, 34 o 61 cuya identidad ya fue verificada.
5
+ * Conserva los totales declarados; puede derivar precios netos, excluir ítems informativos o entregar
6
+ * un resumen con lineBasis='SUMMARY' y lineNumber=0. El detalle original no se modifica.
7
+ *
8
+ * @param detail Hechos declarados, obtenidos del parser o de una fuente previamente verificada.
9
+ * @param options referenceTotalAmount es el total RCV opcional; una diferencia genera una observación.
10
+ * @returns IMPORTABLE con importes y observaciones, o REVIEW_REQUIRED con amounts=null por datos no representables.
11
+ * Un ERROR de conciliación puede coexistir con IMPORTABLE: la política conserva los valores del XML.
12
+ * @throws Los errores inesperados no se ocultan. Los montos numéricos deben ser enteros seguros.
13
+ * @example
14
+ * const result = buildDteImportProjection(parsed.detail);
15
+ * if (result.status === 'IMPORTABLE') console.log(result.amounts.lineBasis);
16
+ * @remarks No persiste, no autoriza acceso, no certifica aceptación fiscal ni habilita emisión.
17
+ */
18
+ export declare function buildDteImportProjection(detail: DteFiscalDetail, options?: {
19
+ referenceTotalAmount?: number;
20
+ }): DteImportProjection;
21
+ /**
22
+ * Construye la misma proyección documental con importes monetarios enteros como strings.
23
+ * Comparte validaciones de fuente con la representación numérica. Por encima del rango seguro de Number,
24
+ * entrega un resumen exacto con lineBasis='SUMMARY', sin atribuir una conciliación por línea.
25
+ *
26
+ * @param detail Detalle exacto con identidad previamente verificada; precios y cantidades siguen siendo strings decimales.
27
+ * @param options referenceTotalAmount es un entero exacto opcional para observar diferencias con RCV.
28
+ * @returns IMPORTABLE o REVIEW_REQUIRED; los importes originales y la entrada se conservan.
29
+ * @see buildDteImportProjection
30
+ */
31
+ export declare function buildDteImportProjectionExact(detail: ExactDteFiscalDetail, options?: {
32
+ referenceTotalAmount?: string;
33
+ }): ExactDteImportProjection;
34
+ /** @deprecated Use buildDteImportProjection. Identical documentary import policy. */
35
+ export declare const projectDteForImport: typeof buildDteImportProjection;
36
+ /** @deprecated Use buildDteImportProjectionExact. Identical exact documentary import policy. */
37
+ export declare const projectDteForImportExact: typeof buildDteImportProjectionExact;
@@ -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;