@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,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;
@@ -4,11 +4,17 @@ exports.DocumentContentMismatchError = void 0;
4
4
  exports.assertApprovedDocument = assertApprovedDocument;
5
5
  const invoicing_1 = require("./invoicing");
6
6
  class DocumentContentMismatchError extends Error {
7
- constructor() { super('SII_DOCUMENT_CONTENT_MISMATCH'); }
7
+ constructor() {
8
+ super('SII_DOCUMENT_CONTENT_MISMATCH');
9
+ }
8
10
  }
9
11
  exports.DocumentContentMismatchError = DocumentContentMismatchError;
10
12
  function assertApprovedDocument(document, approved) {
11
13
  const d = document.detail;
14
+ if (d.references.some(reference => Object.hasOwn(reference, 'issuerRut')))
15
+ throw new DocumentContentMismatchError();
16
+ if (d.fiscalComponents || d.commissions?.length || d.lines.some(line => line.retention) || d.fiscalConditions?.noDebitReduction != null)
17
+ throw new DocumentContentMismatchError();
12
18
  if (d.nonBillableAmount || d.previousBalance || (d.periodAmount != null && d.periodAmount !== 0 && d.periodAmount !== d.totalAmount) || (d.payableAmount != null && d.payableAmount !== 0 && d.payableAmount !== d.totalAmount))
13
19
  throw new DocumentContentMismatchError();
14
20
  const decimal = (value) => value == null ? null : value.replace(/^0+(?=\d)/, '').replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '');
@@ -29,7 +35,10 @@ function assertApprovedDocument(document, approved) {
29
35
  return line.lineNumber !== index + 1 || (0, invoicing_1.hashContent)(line.codes) !== (0, invoicing_1.hashContent)(item.productCode ? [item.productCode] : []) || line.name !== item.name || (line.description ?? '') !== (item.description ?? '') || decimal(line.quantity) !== decimal(item.quantity) || decimal(line.unitPrice) !== decimal(item.unitNetPriceClp) || (line.unit ?? '') !== (item.unit ?? '') || line.amount !== expected.amount || decimal(line.discountPercent ?? '0') !== decimal(item.discountPercent ?? '0') || (line.discountAmount ?? 0) !== expected.discountAmount || line.surchargeAmount || line.surchargePercent && Number(line.surchargePercent) || line.exemptIndicator;
30
36
  }))
31
37
  throw new DocumentContentMismatchError();
32
- const taxOrder = (taxes) => taxes.map(tax => ({ ...tax, rate: decimal(tax.rate) })).sort((a, b) => a.type - b.type);
38
+ const taxOrder = (taxes) => taxes.map(tax => ({
39
+ ...tax,
40
+ rate: decimal(tax.rate)
41
+ })).sort((a, b) => a.type - b.type);
33
42
  if ((0, invoicing_1.hashContent)(taxOrder(d.taxes)) !== (0, invoicing_1.hashContent)(taxOrder(breakdown.taxes)))
34
43
  throw new DocumentContentMismatchError();
35
44
  const adjustment = d.adjustments[0];
@@ -44,12 +53,25 @@ function assertApprovedDocument(document, approved) {
44
53
  else if (d.adjustments.length)
45
54
  throw new DocumentContentMismatchError();
46
55
  const references = i.references ?? [];
47
- if (d.references.length !== references.length || d.references.some((ref, index) => { const expected = references[index]; return ref.lineNumber !== index + 1 || ref.documentType !== expected.documentType || ref.folio !== expected.folio || ref.date !== expected.date || (ref.reason ?? '') !== (expected.reason ?? '') || ref.code !== null; }))
56
+ if (d.references.length !== references.length || d.references.some((ref, index) => {
57
+ const expected = references[index];
58
+ return ref.lineNumber !== index + 1 || ref.documentType !== expected.documentType || ref.folio !== expected.folio || ref.date !== expected.date || (ref.reason ?? '') !== (expected.reason ?? '') || ref.code !== null;
59
+ }))
48
60
  throw new DocumentContentMismatchError();
49
61
  const options = d.issuanceOptions;
50
- const expectedPayments = (i.payments ?? []).map(payment => ({ date: payment.date, amount: payment.amountClp, description: payment.description ?? null }));
51
- const expectedTaxCodes = items.flatMap((item, index) => item.additionalTaxCode === undefined ? [] : [{ lineNumber: index + 1, codes: [item.additionalTaxCode] }]);
52
- const expectedGlobal = references.flatMap((ref, index) => ref.global ? [{ lineNumber: index + 1, indicator: 1 }] : []);
62
+ const expectedPayments = (i.payments ?? []).map(payment => ({
63
+ date: payment.date,
64
+ amount: payment.amountClp,
65
+ description: payment.description ?? null
66
+ }));
67
+ const expectedTaxCodes = items.flatMap((item, index) => item.additionalTaxCode === undefined ? [] : [{
68
+ lineNumber: index + 1,
69
+ codes: [item.additionalTaxCode]
70
+ }]);
71
+ const expectedGlobal = references.flatMap((ref, index) => ref.global ? [{
72
+ lineNumber: index + 1,
73
+ indicator: 1
74
+ }] : []);
53
75
  if (d.hasTransport !== !!i.transport || (0, invoicing_1.hashContent)(options?.transport ?? null) !== (0, invoicing_1.hashContent)(i.transport ?? null) || (options?.requesterRut ?? '') !== (i.requesterRut ?? '') || (0, invoicing_1.hashContent)(options?.payments ?? []) !== (0, invoicing_1.hashContent)(expectedPayments) || (0, invoicing_1.hashContent)(options?.lineTaxCodes ?? []) !== (0, invoicing_1.hashContent)(expectedTaxCodes) || (0, invoicing_1.hashContent)(options?.referenceGlobalIndicators ?? []) !== (0, invoicing_1.hashContent)(expectedGlobal))
54
76
  throw new DocumentContentMismatchError();
55
77
  const email = approved.issuerContact?.email ?? i.issuer.email ?? '', phone = approved.issuerContact?.phone ?? i.issuer.phone ?? '';
@@ -63,10 +85,26 @@ function assertApprovedDocument(document, approved) {
63
85
  const original = approved.originalInvoice;
64
86
  const header = d.fiscalHeader;
65
87
  const originalHeader = original?.fiscalHeader;
66
- const lines = (values) => values.map(line => ({ ...line, quantity: decimal(line.quantity), unitPrice: decimal(line.unitPrice), discountPercent: decimal(line.discountPercent), surchargePercent: decimal(line.surchargePercent) }));
67
- const fiscalOptions = (detail) => ({ issuerEmail: detail.issuanceOptions?.issuerEmail ?? null, issuerPhones: detail.issuanceOptions?.issuerPhones ?? [], requesterRut: detail.issuanceOptions?.requesterRut ?? null, transport: detail.issuanceOptions?.transport ?? null, payments: detail.issuanceOptions?.payments ?? [], lineTaxCodes: detail.issuanceOptions?.lineTaxCodes ?? [] });
88
+ const lines = (values) => values.map(line => ({
89
+ ...line,
90
+ quantity: decimal(line.quantity),
91
+ unitPrice: decimal(line.unitPrice),
92
+ discountPercent: decimal(line.discountPercent),
93
+ surchargePercent: decimal(line.surchargePercent)
94
+ }));
95
+ const fiscalOptions = (detail) => ({
96
+ issuerEmail: detail.issuanceOptions?.issuerEmail ?? null,
97
+ issuerPhones: detail.issuanceOptions?.issuerPhones ?? [],
98
+ requesterRut: detail.issuanceOptions?.requesterRut ?? null,
99
+ transport: detail.issuanceOptions?.transport ?? null,
100
+ payments: detail.issuanceOptions?.payments ?? [],
101
+ lineTaxCodes: detail.issuanceOptions?.lineTaxCodes ?? []
102
+ });
68
103
  const taxes = (detail) => detail.taxes.map(tax => ({ ...tax, rate: decimal(tax.rate) }));
69
- const adjustments = (detail) => detail.adjustments.map(adjustment => ({ ...adjustment, value: decimal(adjustment.value) }));
104
+ const adjustments = (detail) => detail.adjustments.map(adjustment => ({
105
+ ...adjustment,
106
+ value: decimal(adjustment.value)
107
+ }));
70
108
  if (!original || !header || !originalHeader || original.issuanceOptions?.unapprovedFields.length || (0, invoicing_1.hashContent)(lines(d.lines)) !== (0, invoicing_1.hashContent)(lines(original.lines)) || (0, invoicing_1.hashContent)(taxes(d)) !== (0, invoicing_1.hashContent)(taxes(original)) || (0, invoicing_1.hashContent)(adjustments(d)) !== (0, invoicing_1.hashContent)(adjustments(original)) || d.hasTransport !== original.hasTransport || (0, invoicing_1.hashContent)(fiscalOptions(d)) !== (0, invoicing_1.hashContent)(fiscalOptions(original)) || d.issuanceOptions?.referenceGlobalIndicators.length || (0, invoicing_1.hashContent)(header.issuer) !== (0, invoicing_1.hashContent)(originalHeader.issuer) || (0, invoicing_1.hashContent)(header.receiver) !== (0, invoicing_1.hashContent)(originalHeader.receiver) || ['paymentForm', 'saleType', 'purchaseType'].some(field => header[field] !== null && header[field] !== originalHeader[field]))
71
109
  throw new DocumentContentMismatchError();
72
110
  }
@@ -0,0 +1,35 @@
1
+ /** Exact rational arithmetic and safe CLP amounts shared by read interpretation and import preparation. */
2
+ /** n is the numerator; d is the positive denominator. Both remain exact BigInts. */
3
+ export interface Rational {
4
+ readonly n: bigint;
5
+ readonly d: bigint;
6
+ }
7
+ /** A supported interpretation could not explain the source; callers turn this into a diagnostic. */
8
+ export declare class DteInterpretationError extends Error {
9
+ readonly code: string;
10
+ readonly amounts?: {
11
+ declaredAmount: number;
12
+ derivedAmount: number;
13
+ } | undefined;
14
+ constructor(code: string, message: string, amounts?: {
15
+ declaredAmount: number;
16
+ derivedAmount: number;
17
+ } | undefined);
18
+ }
19
+ export declare function fail(code: string, message: string, amounts?: {
20
+ declaredAmount: number;
21
+ derivedAmount: number;
22
+ }): never;
23
+ export declare function fraction(n: bigint, d?: bigint): Rational;
24
+ export declare const add: (a: Rational, b: Rational) => Rational;
25
+ export declare const multiply: (a: Rational, b: Rational) => Rational;
26
+ /** Nearest integer; ties go away from zero. Never applies a monetary tolerance. */
27
+ export declare const round: (v: Rational) => bigint;
28
+ /** Parses a nonnegative XML decimal without binary floating-point conversion. */
29
+ export declare function decimal(value: string): Rational;
30
+ /** Requires an integer CLP amount that Number can represent exactly; no coercion or rounding. */
31
+ export declare function money(value: number, signed?: boolean): number;
32
+ export declare function moneySum(values: readonly number[], signed?: boolean): number;
33
+ export declare function decimalText(value: Rational, places?: number): string;
34
+ /** Largest remainder allocation, with stable original order as the tie breaker. */
35
+ export declare function allocate(weights: readonly number[], target: number): number[];
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.round = exports.multiply = exports.add = exports.DteInterpretationError = void 0;
4
+ exports.fail = fail;
5
+ exports.fraction = fraction;
6
+ exports.decimal = decimal;
7
+ exports.money = money;
8
+ exports.moneySum = moneySum;
9
+ exports.decimalText = decimalText;
10
+ exports.allocate = allocate;
11
+ /** A supported interpretation could not explain the source; callers turn this into a diagnostic. */
12
+ class DteInterpretationError extends Error {
13
+ code;
14
+ amounts;
15
+ constructor(code, message, amounts) {
16
+ super(message);
17
+ this.code = code;
18
+ this.amounts = amounts;
19
+ }
20
+ }
21
+ exports.DteInterpretationError = DteInterpretationError;
22
+ function fail(code, message, amounts) {
23
+ throw new DteInterpretationError(code, message, amounts);
24
+ }
25
+ function gcd(a, b) {
26
+ while (b)
27
+ [a, b] = [b, a % b];
28
+ return a < 0n ? -a : a;
29
+ }
30
+ function fraction(n, d = 1n) {
31
+ const divisor = gcd(n, d);
32
+ return { n: n / divisor, d: d / divisor };
33
+ }
34
+ const add = (a, b) => fraction(a.n * b.d + b.n * a.d, a.d * b.d);
35
+ exports.add = add;
36
+ const multiply = (a, b) => fraction(a.n * b.n, a.d * b.d);
37
+ exports.multiply = multiply;
38
+ /** Nearest integer; ties go away from zero. Never applies a monetary tolerance. */
39
+ const round = (v) => v.n < 0n ? -(0, exports.round)({ n: -v.n, d: v.d }) : (v.n * 2n + v.d) / (v.d * 2n);
40
+ exports.round = round;
41
+ /** Parses a nonnegative XML decimal without binary floating-point conversion. */
42
+ function decimal(value) {
43
+ if (typeof value !== 'string' || value.length > 40 || !/^\d+(?:\.\d+)?$/.test(value))
44
+ fail('INVALID_DECIMAL', 'Valor decimal XML inválido o fuera de precisión.');
45
+ const [whole, part = ''] = value.split('.');
46
+ return fraction(BigInt(whole + part), 10n ** BigInt(part.length));
47
+ }
48
+ /** Requires an integer CLP amount that Number can represent exactly; no coercion or rounding. */
49
+ function money(value, signed = false) {
50
+ if (!Number.isSafeInteger(value) || (!signed && value < 0))
51
+ fail('INVALID_AMOUNT', 'Importe XML fuera del rango entero seguro.');
52
+ return value;
53
+ }
54
+ function moneySum(values, signed = false) {
55
+ return money(Number(values.reduce((sum, value) => sum + BigInt(money(value, true)), 0n)), signed);
56
+ }
57
+ function decimalText(value, places = 6) {
58
+ const scale = 10n ** BigInt(places), scaled = (0, exports.round)((0, exports.multiply)(value, fraction(scale)));
59
+ return `${scaled / scale}.${String(scaled % scale).padStart(places, '0')}`.replace(/\.?0+$/, '');
60
+ }
61
+ /** Largest remainder allocation, with stable original order as the tie breaker. */
62
+ function allocate(weights, target) {
63
+ const total = weights.reduce((s, w) => s + BigInt(w), 0n);
64
+ if (!total) {
65
+ if (target)
66
+ fail('GROSS_ALLOCATION_MISMATCH', 'No hay base para distribuir el neto fiscal.');
67
+ return weights.map(() => 0);
68
+ }
69
+ const parts = weights.map((w, index) => {
70
+ const product = BigInt(w) * BigInt(target);
71
+ return { index, amount: Number(product / total), remainder: product % total };
72
+ });
73
+ const remaining = target - parts.reduce((s, p) => s + p.amount, 0);
74
+ const ranked = [...parts].sort((a, b) => a.remainder === b.remainder ? a.index - b.index : a.remainder > b.remainder ? -1 : 1);
75
+ for (let i = 0; i < remaining; i++)
76
+ ranked[i].amount++;
77
+ return parts.map(p => p.amount);
78
+ }
@@ -0,0 +1,9 @@
1
+ import type { DteFiscalDetail, DteProjectedTax, ExactDteFiscalDetail } from './invoice-xml';
2
+ import type { ExactDte } from './dte-money';
3
+ type TaxContext = Pick<DteFiscalDetail, 'documentType' | 'references'>;
4
+ /** DTE 2.5 catalog, February 2026. Purchase-invoice retentions require their fiscal reference context. */
5
+ export declare function projectDteTax(detail: TaxContext, tax: DteFiscalDetail['taxes'][number]): DteProjectedTax;
6
+ export declare function projectDteTax(detail: TaxContext, tax: ExactDteFiscalDetail['taxes'][number]): ExactDte<DteProjectedTax>;
7
+ /** Informational bases and IVA breakdowns are not added again to the fiscal total. */
8
+ export declare function dteHeaderTotal(detail: DteFiscalDetail | ExactDteFiscalDetail, taxes: readonly (DteProjectedTax | ExactDte<DteProjectedTax>)[]): bigint | null;
9
+ export {};
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.projectDteTax = projectDteTax;
4
+ exports.dteHeaderTotal = dteHeaderTotal;
5
+ function purchaseReference(detail) {
6
+ const references = detail.references.filter(r => /^\d+$/.test(r.documentType) && Number(r.documentType) > 0 && Number(r.documentType) < 200);
7
+ return detail.documentType === 61 && references.length > 0 && references.every(r => ['45', '46'].includes(r.documentType));
8
+ }
9
+ function projectDteTax(detail, tax) {
10
+ const retention = [15, 30, 301, 31, 32, 321, 33, 331, 34, 341, 36, 361, 37, 371, 38, 39, 41, 47, 48, 481, 49].includes(tax.type);
11
+ const kind = retention || tax.type === 46 ? 'RETENTION' : [14, 50].includes(tax.type) ? 'MARGIN' : [17, 18, 19].includes(tax.type) ? 'ANTICIPATED' : [28, 35, 51, 52].includes(tax.type) ? 'SPECIFIC' : [23, 24, 25, 26, 27, 271, 44, 45].includes(tax.type) ? 'ADDITIONAL' : 'UNCLASSIFIED';
12
+ const zeroRetentionConflict = tax.type === 49 && (BigInt(tax.amount) !== 0n || tax.rate != null && Number(tax.rate) !== 0);
13
+ const known = !zeroRetentionConflict && detail.documentType !== 34 && kind !== 'UNCLASSIFIED' && (!retention || purchaseReference(detail));
14
+ const effect = !known ? 'UNKNOWN' : kind === 'RETENTION' ? 'SUBTRACT' : 'ADD';
15
+ const contribution = effect === 'UNKNOWN' ? null : BigInt(tax.amount) * (effect === 'SUBTRACT' ? -1n : 1n);
16
+ return {
17
+ ...tax,
18
+ kind,
19
+ effect,
20
+ contribution: contribution === null ? null : typeof tax.amount === 'string' ? String(contribution) : Number(contribution)
21
+ };
22
+ }
23
+ /** Informational bases and IVA breakdowns are not added again to the fiscal total. */
24
+ function dteHeaderTotal(detail, taxes) {
25
+ if (taxes.some(tax => tax.contribution === null))
26
+ return null;
27
+ const c = detail.fiscalComponents;
28
+ if (BigInt(c?.constructionCredit ?? 0) !== 0n && detail.documentType === 34)
29
+ return null;
30
+ const commissions = [c?.commissionNet, c?.commissionExempt, c?.commissionVat].some(value => BigInt(value ?? 0) !== 0n);
31
+ if (commissions && !purchaseReference(detail))
32
+ return null;
33
+ return BigInt(detail.netAmount ?? 0) + BigInt(detail.exemptAmount ?? 0) + BigInt(detail.vatAmount ?? 0)
34
+ + taxes.reduce((sum, tax) => sum + BigInt(tax.contribution), 0n)
35
+ + BigInt(c?.containerDeposit ?? 0) - BigInt(c?.constructionCredit ?? 0)
36
+ - BigInt(c?.commissionNet ?? 0) - BigInt(c?.commissionExempt ?? 0) - BigInt(c?.commissionVat ?? 0);
37
+ }