@devly-cl/sii-client 0.6.0 → 0.7.9

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 (42) hide show
  1. package/README.md +113 -251
  2. package/dist/application/document-status.d.ts +13 -0
  3. package/dist/application/document-status.js +50 -0
  4. package/dist/application/invoice-queries.d.ts +11 -5
  5. package/dist/application/invoice-queries.js +13 -9
  6. package/dist/domain/company-info.d.ts +13 -0
  7. package/dist/domain/company-info.js +2 -0
  8. package/dist/domain/document-status.d.ts +93 -0
  9. package/dist/domain/document-status.js +69 -0
  10. package/dist/domain/document.d.ts +4 -0
  11. package/dist/domain/document.js +38 -3
  12. package/dist/domain/dte-reconciliation.d.ts +5 -0
  13. package/dist/domain/dte-reconciliation.js +351 -0
  14. package/dist/domain/invoice-xml.d.ts +133 -1
  15. package/dist/domain/invoicing.d.ts +78 -5
  16. package/dist/domain/invoicing.js +143 -26
  17. package/dist/domain/rcv-document.d.ts +17 -0
  18. package/dist/domain/rcv-document.js +2 -0
  19. package/dist/index.d.ts +9 -4
  20. package/dist/index.js +5 -1
  21. package/dist/infrastructure/document-status-gateway.d.ts +13 -0
  22. package/dist/infrastructure/document-status-gateway.js +127 -0
  23. package/dist/infrastructure/document-status-parser.d.ts +12 -0
  24. package/dist/infrastructure/document-status-parser.js +258 -0
  25. package/dist/infrastructure/dte-xml.js +148 -30
  26. package/dist/infrastructure/facturador-gateway.d.ts +4 -1
  27. package/dist/infrastructure/facturador-gateway.js +113 -15
  28. package/dist/infrastructure/facturador.d.ts +4 -1
  29. package/dist/infrastructure/facturador.js +22 -4
  30. package/dist/infrastructure/rcv-gateway.d.ts +3 -0
  31. package/dist/infrastructure/rcv-gateway.js +9 -5
  32. package/dist/infrastructure/rcv-normalization.d.ts +7 -0
  33. package/dist/infrastructure/rcv-normalization.js +9 -1
  34. package/dist/infrastructure/sii-client.d.ts +10 -1
  35. package/dist/infrastructure/sii-client.js +29 -3
  36. package/dist/infrastructure/sii-http-session.d.ts +5 -1
  37. package/dist/infrastructure/sii-http-session.js +75 -27
  38. package/dist/sii-error.d.ts +4 -3
  39. package/dist/sii-error.js +11 -4
  40. package/package.json +45 -45
  41. package/dist/domain/sii-error.d.ts +0 -27
  42. package/dist/domain/sii-error.js +0 -82
@@ -5,6 +5,9 @@ export interface IssuedDocumentXmlQuery {
5
5
  documentType: IssuedDocumentType;
6
6
  folio: string;
7
7
  }
8
+ export interface ReceivedDocumentXmlQuery extends IssuedDocumentXmlQuery {
9
+ issuerRut: string;
10
+ }
8
11
  export interface IssuedInvoiceXmlQuery {
9
12
  documentType: InvoiceDocumentType;
10
13
  folio: string;
@@ -29,11 +32,17 @@ export interface DteInvoiceLine {
29
32
  surchargeAmount: number | null;
30
33
  exemptIndicator: number | null;
31
34
  amount: number;
35
+ /** Original per-line tax codes, when present. They do not replace the declared header taxes. */
36
+ additionalTaxCodes?: number[];
32
37
  }
33
38
  export interface DteInvoiceDetail {
39
+ /** Present only for MntBruto=1: line amounts/prices include VAT. Original fiscal totals are unchanged. */
40
+ grossAmounts?: boolean;
34
41
  issuerRut: string;
35
42
  documentType: InvoiceDocumentType;
36
43
  folio: string;
44
+ /** Original spelling when numeric normalization removes leading zeroes. XML bytes are unchanged. */
45
+ declaredFolio?: string;
37
46
  issuedDate: string;
38
47
  receiverRut: string;
39
48
  netAmount: number | null;
@@ -41,6 +50,11 @@ export interface DteInvoiceDetail {
41
50
  vatRate: string | null;
42
51
  vatAmount: number | null;
43
52
  totalAmount: number;
53
+ /** Optional original totalizers; do not change the fiscal total or infer cash rounding. */
54
+ nonBillableAmount?: number;
55
+ periodAmount?: number;
56
+ previousBalance?: number;
57
+ payableAmount?: number;
44
58
  lines: DteInvoiceLine[];
45
59
  taxes: {
46
60
  type: number;
@@ -59,11 +73,101 @@ export interface DteInvoiceDetail {
59
73
  lineNumber: number;
60
74
  documentType: string;
61
75
  folio: string;
76
+ declaredFolio?: string;
62
77
  date: string;
63
78
  code: number | null;
64
79
  reason: string | null;
65
80
  }[];
81
+ /** Read reconciliation only. Never authorizes issuing or modifying a fiscal document. */
82
+ reconciliation?: DteReconciliation;
83
+ }
84
+ export interface DteReconciliationDiagnostic {
85
+ code: string;
86
+ severity: 'INFO' | 'ERROR';
87
+ message: string;
88
+ lineNumber?: number;
89
+ declaredAmount?: number;
90
+ derivedAmount?: number;
91
+ }
92
+ /** Non-blocking documentary observations; declared fiscal amounts remain authoritative. */
93
+ export type DteFiscalObservation = Pick<DteReconciliationDiagnostic, 'code' | 'message' | 'declaredAmount' | 'derivedAmount'>;
94
+ export interface DteReconciledLine {
95
+ lineNumber: number;
96
+ quantity: string;
97
+ unitPrice: string;
98
+ discountPercent: string;
99
+ discountAmount: number;
100
+ surchargeAmount: number;
101
+ netAmount: number;
102
+ /** MontoItem exactly as declared, even when the derived line is converted from gross to net. */
103
+ declaredAmount: number;
104
+ category: 'TAXABLE' | 'EXEMPT' | 'NON_BILLABLE' | 'NON_BILLABLE_DEDUCTION';
105
+ }
106
+ /** Derived explanation only; the original header and line amounts are never changed. */
107
+ export interface DteTotalRounding {
108
+ difference: -1 | 1;
109
+ method: 'PER_LINE_VAT_AND_TAX';
110
+ basis: 'DECLARED_LINE_AMOUNTS' | 'EXACT_PRODUCTS';
111
+ componentTotal: number;
112
+ }
113
+ export interface DteReconciledAmounts {
114
+ netAmount: number;
115
+ exemptAmount: number;
116
+ vatAmount: number;
117
+ totalAmount: number;
118
+ payableAmount: number;
119
+ lines: DteReconciledLine[];
120
+ taxes: {
121
+ type: number;
122
+ rate: string | null;
123
+ amount: number;
124
+ kind: 'ADDITIONAL' | 'ANTICIPATED';
125
+ }[];
126
+ globalDiscount?: {
127
+ netAmount: number;
128
+ grossAmount?: number;
129
+ };
130
+ globalSurcharge?: {
131
+ netAmount: number;
132
+ grossAmount?: number;
133
+ };
134
+ nonBillable?: {
135
+ amount: number;
136
+ lines: {
137
+ lineNumber: number;
138
+ amount: number;
139
+ indicator: 2 | 6;
140
+ }[];
141
+ };
142
+ grossAmountsInferred?: true;
143
+ /** Difference explained by summing exact source products before rounding the subtotal. */
144
+ lineRounding?: number;
145
+ /** At most one peso per document, explained by an exact supported line calculation. */
146
+ totalRounding?: DteTotalRounding;
147
+ observations?: DteFiscalObservation[];
66
148
  }
149
+ export interface DteReconciliation {
150
+ version: 1;
151
+ status: 'RECONCILED' | 'REVIEW_REQUIRED';
152
+ /** Header values are never overwritten by calculations. Null means absent in the XML. */
153
+ declared: {
154
+ netAmount: number | null;
155
+ exemptAmount: number | null;
156
+ vatAmount: number | null;
157
+ totalAmount: number;
158
+ nonBillableAmount: number | null;
159
+ periodAmount: number | null;
160
+ previousBalance: number | null;
161
+ payableAmount: number | null;
162
+ grossAmounts: boolean | null;
163
+ };
164
+ derived: DteReconciledAmounts | null;
165
+ diagnostics: DteReconciliationDiagnostic[];
166
+ }
167
+ /** Fiscal parser model, also usable for reconciling previously stored declared detail. */
168
+ export type DteFiscalDetail = Omit<DteInvoiceDetail, 'documentType'> & {
169
+ documentType: number;
170
+ };
67
171
  export interface InvoiceXmlResult {
68
172
  /** Original bytes, including the original encoding and signatures. */
69
173
  xml: Uint8Array;
@@ -76,6 +180,8 @@ export interface DteDocumentDetail extends Omit<DteInvoiceDetail, 'documentType'
76
180
  hasSignature: boolean;
77
181
  /** Transport data is present; an observed empty Transporte container does not count. */
78
182
  hasTransport: boolean;
183
+ /** Present only when optional issuance data exists. Legacy parseDteXml keeps its shape. */
184
+ issuanceOptions?: DteIssuanceOptions;
79
185
  fiscalHeader?: {
80
186
  issuer: {
81
187
  legalName: string | null;
@@ -98,10 +204,36 @@ export interface DteDocumentDetail extends Omit<DteInvoiceDetail, 'documentType'
98
204
  saleType: number | null;
99
205
  purchaseType: number | null;
100
206
  noDebitReduction: number | null;
101
- /** IdDoc fields outside the supported invoice/annulment issuance command. Reads preserve them. */
207
+ /** Fiscal fields outside the supported invoice/annulment issuance command. Reads preserve them. */
102
208
  unapprovedFiscalFields: string[];
103
209
  };
104
210
  }
211
+ export interface DteIssuanceOptions {
212
+ issuerEmail: string | null;
213
+ issuerPhones: string[];
214
+ requesterRut: string | null;
215
+ transport: {
216
+ carrierRut: string | null;
217
+ licensePlate: string | null;
218
+ driverRut: string | null;
219
+ driverName: string | null;
220
+ } | null;
221
+ payments: {
222
+ date: string;
223
+ amount: number;
224
+ description: string | null;
225
+ }[];
226
+ lineTaxCodes: {
227
+ lineNumber: number;
228
+ codes: number[];
229
+ }[];
230
+ referenceGlobalIndicators: {
231
+ lineNumber: number;
232
+ indicator: number;
233
+ }[];
234
+ /** Optional structures outside the supported form are readable but cannot be issued. */
235
+ unapprovedFields: string[];
236
+ }
105
237
  export interface IssuedDocumentXmlResult extends Omit<InvoiceXmlResult, 'detail'> {
106
238
  detail: DteDocumentDetail;
107
239
  }
@@ -4,6 +4,48 @@ export interface InvoiceLineInput {
4
4
  quantity: string;
5
5
  unitNetPriceClp: string;
6
6
  unit?: string;
7
+ productCode?: {
8
+ type: string;
9
+ value: string;
10
+ };
11
+ additionalTaxCode?: InvoiceAdditionalTaxCode;
12
+ discountPercent?: string;
13
+ }
14
+ export type InvoiceAdditionalTaxCode = 23 | 44 | 24 | 25 | 26 | 27 | 271;
15
+ export declare const INVOICE_ADDITIONAL_TAX_RATES: Readonly<{
16
+ 23: "15";
17
+ 44: "15";
18
+ 24: "31.5";
19
+ 25: "20.5";
20
+ 26: "20.5";
21
+ 27: "10";
22
+ 271: "18";
23
+ }>;
24
+ export type InvoiceGlobalDiscount = {
25
+ percent: string;
26
+ amountClp?: never;
27
+ } | {
28
+ amountClp: number;
29
+ percent?: never;
30
+ };
31
+ export type InvoiceReferenceDocumentType = '30' | '32' | '33' | '34' | '35' | '38' | '39' | '40' | '41' | '43' | '45' | '46' | '48' | '50' | '52' | '55' | '56' | '60' | '61' | '103' | '801' | '802' | '803' | '804' | '805' | '806' | '813' | '820' | '821' | '822' | '823' | 'HES';
32
+ export interface InvoiceReferenceInput {
33
+ documentType: InvoiceReferenceDocumentType;
34
+ folio: string;
35
+ date: string;
36
+ reason?: string;
37
+ global?: boolean;
38
+ }
39
+ export interface InvoicePaymentInput {
40
+ date: string;
41
+ amountClp: number;
42
+ description?: string;
43
+ }
44
+ export interface InvoiceTransportInput {
45
+ carrierRut: string;
46
+ licensePlate: string;
47
+ driverRut: string;
48
+ driverName: string;
7
49
  }
8
50
  export interface InvoiceInput {
9
51
  issuedDate: string;
@@ -12,6 +54,8 @@ export interface InvoiceInput {
12
54
  commune: string;
13
55
  city: string;
14
56
  activityCode: string;
57
+ email?: string;
58
+ phone?: string;
15
59
  };
16
60
  receiver: {
17
61
  rut: string;
@@ -22,10 +66,17 @@ export interface InvoiceInput {
22
66
  businessActivity: string;
23
67
  contact?: string;
24
68
  };
25
- paymentForm: 1 | 2;
26
- saleType: 1 | 2;
69
+ paymentForm: 1 | 2 | 3;
70
+ saleType: 1 | 2 | 3;
27
71
  purchaseType: 1 | 2 | 3 | 4 | 5 | 6 | 7;
28
72
  items: InvoiceLineInput[];
73
+ globalDiscount?: InvoiceGlobalDiscount;
74
+ references?: InvoiceReferenceInput[];
75
+ payments?: InvoicePaymentInput[];
76
+ requesterRut?: string;
77
+ transport?: InvoiceTransportInput;
78
+ /** Presentation flag in the SII form; not a tax calculation or an XML identifier. */
79
+ smallBusiness?: boolean;
29
80
  }
30
81
  export interface InvoiceTotals {
31
82
  netAmount: number;
@@ -38,10 +89,32 @@ export type LineaFactura = InvoiceLineInput;
38
89
  export type EntradaFactura = InvoiceInput;
39
90
  /** @deprecated Use InvoiceTotals. */
40
91
  export type TotalesFactura = InvoiceTotals;
41
- /** Tipo 33, IVA 19%, sin descuentos ni opciones fiscales implícitas. */
92
+ /** Shared exact arithmetic for the portal and the unsigned/signed XML guard. */
93
+ export declare function invoiceBreakdown(lines: readonly InvoiceLineInput[], discount?: InvoiceGlobalDiscount): {
94
+ totals: Readonly<{
95
+ netAmount: number;
96
+ vatAmount: number;
97
+ totalAmount: number;
98
+ }>;
99
+ subtotal: number;
100
+ discountAmount: number;
101
+ discountPercent: string;
102
+ discountAmountFromPercent: number;
103
+ additionalTaxAmount: number;
104
+ lineAmounts: {
105
+ amount: number;
106
+ discountAmount: number;
107
+ }[];
108
+ taxes: {
109
+ type: InvoiceAdditionalTaxCode;
110
+ rate: "15" | "31.5" | "20.5" | "10" | "18";
111
+ amount: number;
112
+ }[];
113
+ };
114
+ /** Tipo 33, IVA 19%, con opcionales explícitos del facturador gratuito. */
42
115
  export declare function validateInvoice(input: unknown): InvoiceInput;
43
- /** Redondea cada línea a CLP y después el IVA; sin aritmética decimal binaria. */
44
- export declare function calculateInvoiceTotals(input: unknown): InvoiceTotals;
116
+ /** Redondea líneas, descuento global, IVA e impuestos adicionales sin decimales binarios. */
117
+ export declare function calculateInvoiceTotals(input: unknown, discount?: InvoiceGlobalDiscount): InvoiceTotals;
45
118
  /** Huella determinista del contenido fiscal; el llamador excluye claves y tokens. */
46
119
  export declare function hashContent(value: unknown): string;
47
120
  /** @deprecated Use validateInvoice. */
@@ -1,11 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.hashContenido = exports.calcularTotalesFactura = exports.validarFactura = void 0;
3
+ exports.hashContenido = exports.calcularTotalesFactura = exports.validarFactura = exports.INVOICE_ADDITIONAL_TAX_RATES = void 0;
4
+ exports.invoiceBreakdown = invoiceBreakdown;
4
5
  exports.validateInvoice = validateInvoice;
5
6
  exports.calculateInvoiceTotals = calculateInvoiceTotals;
6
7
  exports.hashContent = hashContent;
7
8
  const node_crypto_1 = require("node:crypto");
8
9
  const rut_1 = require("./rut");
10
+ exports.INVOICE_ADDITIONAL_TAX_RATES = Object.freeze({ 23: '15', 44: '15', 24: '31.5', 25: '20.5', 26: '20.5', 27: '10', 271: '18' });
9
11
  const controls = /[\u0000-\u001f\u007f-\u009f]/u;
10
12
  function invalid(field) { throw new TypeError(`Factura inválida: ${field}`); }
11
13
  function isRecord(value) {
@@ -30,17 +32,36 @@ function text(value, limit, field, optional = false) {
30
32
  function requiredText(value, limit, field) {
31
33
  return text(value, limit, field) ?? invalid(field);
32
34
  }
33
- function decimal(value, field) {
35
+ function decimal(value, field, allowZero = false) {
34
36
  const result = requiredText(value, 12, field);
35
37
  const match = /^(\d{1,10})(?:\.(\d{1,2}))?$/.exec(result);
36
38
  if (!match)
37
39
  invalid(field);
38
40
  const integer = match[1].replace(/^0+(?=\d)/u, '');
39
41
  const fraction = (match[2] ?? '').replace(/0+$/u, '');
40
- if (integer === '0' && !fraction)
42
+ if (!allowZero && integer === '0' && !fraction)
41
43
  invalid(field);
42
44
  return fraction ? `${integer}.${fraction}` : integer;
43
45
  }
46
+ function percentage(value, field, allowZero = false) {
47
+ const result = decimal(value, field, allowZero);
48
+ return hundredths(result) <= 10000n ? result : invalid(field);
49
+ }
50
+ function amount(value, field, allowZero = false) {
51
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < (allowZero ? 0 : 1) || value > 9999999999)
52
+ invalid(field);
53
+ return value;
54
+ }
55
+ function globalDiscount(value) {
56
+ if (value === undefined)
57
+ return undefined;
58
+ const source = record(value, ['percent', 'amountClp'], 'globalDiscount');
59
+ if (Object.keys(source).length !== 1)
60
+ invalid('globalDiscount');
61
+ return Object.freeze(source.percent !== undefined
62
+ ? { percent: percentage(source.percent, 'globalDiscount.percent', true) }
63
+ : { amountClp: amount(source.amountClp, 'globalDiscount.amountClp', true) });
64
+ }
44
65
  function hundredths(value) {
45
66
  const [integer, fraction = ''] = value.split('.');
46
67
  return BigInt(integer) * 100n + BigInt(fraction.padEnd(2, '0'));
@@ -49,65 +70,155 @@ function items(value) {
49
70
  if (!Array.isArray(value) || !value.length || value.length > 10)
50
71
  invalid('items');
51
72
  return Array.from(value, entry => {
52
- const source = record(entry, ['name', 'description', 'quantity', 'unitNetPriceClp', 'unit'], 'items');
73
+ const source = record(entry, ['name', 'description', 'quantity', 'unitNetPriceClp', 'unit', 'productCode', 'additionalTaxCode', 'discountPercent'], 'items');
53
74
  const description = text(source.description, 999, 'description', true);
54
75
  const unit = text(source.unit, 4, 'unit', true);
76
+ const code = source.productCode === undefined ? undefined : record(source.productCode, ['type', 'value'], 'productCode');
77
+ const additionalTaxCode = source.additionalTaxCode;
78
+ if (additionalTaxCode !== undefined && (typeof additionalTaxCode !== 'number' || !Object.hasOwn(exports.INVOICE_ADDITIONAL_TAX_RATES, additionalTaxCode)))
79
+ invalid('additionalTaxCode');
55
80
  return Object.freeze({
56
81
  name: requiredText(source.name, 25, 'name'),
57
82
  ...(description === undefined ? {} : { description }),
58
83
  quantity: decimal(source.quantity, 'quantity'),
59
84
  unitNetPriceClp: decimal(source.unitNetPriceClp, 'unitNetPriceClp'),
60
85
  ...(unit === undefined ? {} : { unit }),
86
+ ...(code === undefined ? {} : { productCode: Object.freeze({ type: requiredText(code.type, 10, 'productCode.type'), value: requiredText(code.value, 15, 'productCode.value') }) }),
87
+ ...(additionalTaxCode === undefined ? {} : { additionalTaxCode: additionalTaxCode }),
88
+ ...(source.discountPercent === undefined ? {} : { discountPercent: percentage(source.discountPercent, 'discountPercent') }),
61
89
  });
62
90
  });
63
91
  }
64
- function totals(lines) {
65
- const net = lines.reduce((sum, line) => {
66
- const amount = (hundredths(line.quantity) * hundredths(line.unitNetPriceClp) + 5000n) / 10000n;
67
- if (amount < 1n)
92
+ const round = (numerator, denominator) => (numerator + denominator / 2n) / denominator;
93
+ const fromHundredths = (value) => `${value / 100n}.${String(value % 100n).padStart(2, '0')}`.replace(/\.?0+$/, '');
94
+ /** Shared exact arithmetic for the portal and the unsigned/signed XML guard. */
95
+ function invoiceBreakdown(lines, discount) {
96
+ const lineAmounts = lines.map(line => {
97
+ const product = hundredths(line.quantity) * hundredths(line.unitNetPriceClp);
98
+ const pct = hundredths(line.discountPercent ?? '0');
99
+ const result = round(product * (10000n - pct), 100000000n);
100
+ if (result < 1n && pct !== 10000n || result > 9999999999n)
68
101
  invalid('lineAmount');
69
- return sum + amount;
70
- }, 0n);
102
+ if (line.additionalTaxCode !== undefined && pct > 0n && (pct === 10000n || hundredths(line.unitNetPriceClp) * pct < 1000000n))
103
+ invalid('discountPercent.additionalTax');
104
+ return { amount: Number(result), discountAmount: Number(round(product * pct, 100000000n)) };
105
+ });
106
+ const subtotal = lineAmounts.reduce((sum, line) => sum + BigInt(line.amount), 0n);
107
+ if (subtotal > 9999999999n)
108
+ invalid('subtotal');
109
+ const discountAmount = discount?.amountClp !== undefined ? BigInt(discount.amountClp) : round(subtotal * hundredths(discount?.percent ?? '0'), 10000n);
110
+ if (discountAmount > subtotal)
111
+ invalid('globalDiscount');
112
+ const discountPercent = discount?.percent !== undefined ? hundredths(discount.percent) : subtotal ? round(discountAmount * 10000n, subtotal) : 0n;
113
+ const net = subtotal - discountAmount;
71
114
  const vat = (net * 19n + 50n) / 100n;
72
- const total = net + vat;
73
- if (net < 1n || total > 9999999999n)
115
+ const taxBases = new Map();
116
+ lines.forEach((line, index) => { if (line.additionalTaxCode !== undefined)
117
+ taxBases.set(line.additionalTaxCode, (taxBases.get(line.additionalTaxCode) ?? 0n) + BigInt(lineAmounts[index].amount)); });
118
+ let taxNumerator = 0n;
119
+ const taxes = [...taxBases].map(([type, base]) => {
120
+ const rate = exports.INVOICE_ADDITIONAL_TAX_RATES[type];
121
+ const numerator = base * hundredths(rate) * (10000n - discountPercent);
122
+ taxNumerator += numerator;
123
+ return { type, rate, amount: Number(round(numerator, 100000000n)) };
124
+ });
125
+ const additionalTaxAmount = round(taxNumerator, 100000000n);
126
+ if (taxes.length && additionalTaxAmount < 1n)
127
+ invalid('additionalTaxAmount');
128
+ const total = net + vat + additionalTaxAmount;
129
+ if ((!subtotal && !lines.every(line => line.discountPercent === '100')) || total > 9999999999n)
74
130
  invalid('totalAmount');
75
- return Object.freeze({ netAmount: Number(net), vatAmount: Number(vat), totalAmount: Number(total) });
131
+ return {
132
+ totals: Object.freeze({ netAmount: Number(net), vatAmount: Number(vat), totalAmount: Number(total) }),
133
+ subtotal: Number(subtotal), discountAmount: Number(discountAmount), discountPercent: fromHundredths(discountPercent), discountAmountFromPercent: Number(round(subtotal * discountPercent, 10000n)),
134
+ additionalTaxAmount: Number(additionalTaxAmount), lineAmounts, taxes,
135
+ };
76
136
  }
77
- function issuedDate(value) {
137
+ function civilDate(value, field, minimum, maximum = '9999-12-31') {
78
138
  if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/u.test(value))
79
- invalid('issuedDate');
139
+ invalid(field);
80
140
  const year = Number(value.slice(0, 4)), month = Number(value.slice(5, 7)), day = Number(value.slice(8, 10));
81
141
  const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
82
142
  const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
83
- if (year < 2017 || month < 1 || month > 12 || day < 1 || day > days[month - 1])
84
- invalid('issuedDate');
143
+ if (value < minimum || value > maximum || month < 1 || month > 12 || day < 1 || day > days[month - 1])
144
+ invalid(field);
85
145
  return value;
86
146
  }
87
- /** Tipo 33, IVA 19%, sin descuentos ni opciones fiscales implícitas. */
147
+ function smallArray(value, field) {
148
+ if (!Array.isArray(value) || !value.length || value.length > 3)
149
+ invalid(field);
150
+ return Array.from(value);
151
+ }
152
+ const referenceTypes = ['30', '32', '33', '34', '35', '38', '39', '40', '41', '43', '45', '46', '48', '50', '52', '55', '56', '60', '61', '103', '801', '802', '803', '804', '805', '806', '813', '820', '821', '822', '823', 'HES'];
153
+ function references(value) {
154
+ return Object.freeze(smallArray(value, 'references').map(entry => {
155
+ const source = record(entry, ['documentType', 'folio', 'date', 'reason', 'global'], 'reference');
156
+ if (typeof source.documentType !== 'string' || !referenceTypes.includes(source.documentType))
157
+ invalid('reference.documentType');
158
+ if (source.global !== undefined && typeof source.global !== 'boolean')
159
+ invalid('reference.global');
160
+ const folio = requiredText(source.folio, 18, 'reference.folio');
161
+ if (source.global ? folio !== '0' : ['30', '32', '38', '40', '45', '50', '55', '60', '33', '34', '39', '46', '56', '61', '52', '103'].includes(source.documentType) && !/^[1-9]\d*$/.test(folio))
162
+ invalid('reference.folio');
163
+ const reason = text(source.reason, 90, 'reference.reason', true);
164
+ return Object.freeze({ documentType: source.documentType, folio, date: civilDate(source.date, 'reference.date', '2002-08-01', '2050-12-31'), ...(reason === undefined ? {} : { reason }), ...(source.global ? { global: true } : {}) });
165
+ }));
166
+ }
167
+ function payments(value, issued, total) {
168
+ let previous = issued, sum = 0;
169
+ const result = smallArray(value, 'payments').map((entry, index) => {
170
+ const source = record(entry, ['date', 'amountClp', 'description'], 'payment');
171
+ const date = civilDate(source.date, 'payment.date', issued);
172
+ if (index && date <= previous)
173
+ invalid('payment.date');
174
+ previous = date;
175
+ const amountClp = amount(source.amountClp, 'payment.amountClp');
176
+ sum += amountClp;
177
+ const description = text(source.description, 40, 'payment.description', true);
178
+ return Object.freeze({ date, amountClp, ...(description === undefined ? {} : { description }) });
179
+ });
180
+ if (sum !== total)
181
+ invalid('payments.total');
182
+ return Object.freeze(result);
183
+ }
184
+ function transport(value) {
185
+ const source = record(value, ['carrierRut', 'licensePlate', 'driverRut', 'driverName'], 'transport');
186
+ return Object.freeze({ carrierRut: (0, rut_1.parseRut)(requiredText(source.carrierRut, 15, 'transport.carrierRut')).formatted, licensePlate: requiredText(source.licensePlate, 8, 'transport.licensePlate'), driverRut: (0, rut_1.parseRut)(requiredText(source.driverRut, 15, 'transport.driverRut')).formatted, driverName: requiredText(source.driverName, 30, 'transport.driverName') });
187
+ }
188
+ /** Tipo 33, IVA 19%, con opcionales explícitos del facturador gratuito. */
88
189
  function validateInvoice(input) {
89
- const source = record(input, ['issuedDate', 'issuer', 'receiver', 'paymentForm', 'saleType', 'purchaseType', 'items'], 'input');
90
- const issuer = record(source.issuer, ['address', 'commune', 'city', 'activityCode'], 'issuer');
190
+ const source = record(input, ['issuedDate', 'issuer', 'receiver', 'paymentForm', 'saleType', 'purchaseType', 'items', 'globalDiscount', 'references', 'payments', 'requesterRut', 'transport', 'smallBusiness'], 'input');
191
+ const issuer = record(source.issuer, ['address', 'commune', 'city', 'activityCode', 'email', 'phone'], 'issuer');
91
192
  const receiver = record(source.receiver, ['rut', 'legalName', 'address', 'commune', 'city', 'businessActivity', 'contact'], 'receiver');
92
193
  const activityCode = requiredText(issuer.activityCode, 6, 'activityCode');
93
194
  if (!/^\d{6}$/u.test(activityCode))
94
195
  invalid('activityCode');
95
196
  const paymentForm = source.paymentForm, saleType = source.saleType, purchaseType = source.purchaseType;
96
- if (paymentForm !== 1 && paymentForm !== 2)
197
+ if (paymentForm !== 1 && paymentForm !== 2 && paymentForm !== 3)
97
198
  invalid('paymentForm');
98
- if (saleType !== 1 && saleType !== 2)
199
+ if (saleType !== 1 && saleType !== 2 && saleType !== 3)
99
200
  invalid('saleType');
100
201
  if (purchaseType !== 1 && purchaseType !== 2 && purchaseType !== 3 && purchaseType !== 4 && purchaseType !== 5 && purchaseType !== 6 && purchaseType !== 7)
101
202
  invalid('purchaseType');
102
203
  const lines = items(source.items);
103
- totals(lines);
204
+ const discount = globalDiscount(source.globalDiscount);
205
+ const totals = invoiceBreakdown(lines, discount).totals;
206
+ const issued = civilDate(source.issuedDate, 'issuedDate', '2017-01-01');
207
+ const email = text(issuer.email, 30, 'issuer.email', true), phone = text(issuer.phone, 14, 'issuer.phone', true);
208
+ if (email !== undefined && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(email))
209
+ invalid('issuer.email');
210
+ if (phone !== undefined && !/^\d[\d ]*$/u.test(phone))
211
+ invalid('issuer.phone');
212
+ if (source.smallBusiness !== undefined && typeof source.smallBusiness !== 'boolean')
213
+ invalid('smallBusiness');
104
214
  const contact = text(receiver.contact, 80, 'contact', true);
105
215
  const result = {
106
- issuedDate: issuedDate(source.issuedDate),
216
+ issuedDate: issued,
107
217
  issuer: Object.freeze({
108
218
  address: requiredText(issuer.address, 70, 'issuer.address'),
109
219
  commune: requiredText(issuer.commune, 20, 'issuer.commune'),
110
220
  city: requiredText(issuer.city, 15, 'issuer.city'), activityCode,
221
+ ...(email === undefined ? {} : { email }), ...(phone === undefined ? {} : { phone }),
111
222
  }),
112
223
  receiver: Object.freeze({
113
224
  rut: (0, rut_1.parseRut)(requiredText(receiver.rut, 15, 'receiver.rut')).formatted,
@@ -119,12 +230,18 @@ function validateInvoice(input) {
119
230
  ...(contact === undefined ? {} : { contact }),
120
231
  }),
121
232
  paymentForm, saleType, purchaseType, items: lines,
233
+ ...(discount === undefined ? {} : { globalDiscount: discount }),
234
+ ...(source.references === undefined ? {} : { references: references(source.references) }),
235
+ ...(source.payments === undefined ? {} : { payments: payments(source.payments, issued, totals.totalAmount) }),
236
+ ...(source.transport === undefined ? {} : { transport: transport(source.transport) }),
237
+ ...(source.requesterRut === undefined ? {} : { requesterRut: (0, rut_1.parseRut)(requiredText(source.requesterRut, 15, 'requesterRut')).formatted }),
238
+ ...(source.smallBusiness === undefined ? {} : { smallBusiness: source.smallBusiness }),
122
239
  };
123
240
  Object.freeze(result.items);
124
241
  return Object.freeze(result);
125
242
  }
126
- /** Redondea cada línea a CLP y después el IVA; sin aritmética decimal binaria. */
127
- function calculateInvoiceTotals(input) { return totals(items(input)); }
243
+ /** Redondea líneas, descuento global, IVA e impuestos adicionales sin decimales binarios. */
244
+ function calculateInvoiceTotals(input, discount) { return invoiceBreakdown(items(input), globalDiscount(discount)).totals; }
128
245
  /** Huella determinista del contenido fiscal; el llamador excluye claves y tokens. */
129
246
  function hashContent(value) {
130
247
  const ancestors = new Set();
@@ -0,0 +1,17 @@
1
+ import type { IssuedInvoice } from './issued-invoice';
2
+ export type RcvDocumentType = 33 | 34 | 61;
3
+ export interface RcvDocumentsQuery {
4
+ periodo: string;
5
+ tokenRecaptcha?: string;
6
+ }
7
+ export interface RcvDocument extends Omit<IssuedInvoice, 'documentType'> {
8
+ documentType: RcvDocumentType;
9
+ issuerName?: string | null;
10
+ }
11
+ export interface RcvDocumentsResult {
12
+ data: RcvDocument[];
13
+ complete: boolean;
14
+ expectedCount: number;
15
+ observedAt: string;
16
+ incompleteDocumentTypes: RcvDocumentType[];
17
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/dist/index.d.ts CHANGED
@@ -1,19 +1,24 @@
1
1
  export { SiiClient, SiiError } from './infrastructure/sii-client';
2
2
  export { sanitizeSiiDiagnostics } from './sii-error';
3
3
  export type { SiiDiagnostics } from './sii-error';
4
+ export type { CompanyInfo } from './domain/company-info';
5
+ export type { RcvDocumentType, RcvDocument, RcvDocumentsQuery, RcvDocumentsResult } from './domain/rcv-document';
6
+ export type { DocumentQueryOptions, DocumentDirection, DocumentIdentity, DocumentStatusQuery, DocumentVerification, DocumentStatusResult, RecipientEventsQuery, RecipientEvent, RecipientEventsResult, } from './domain/document-status';
4
7
  export type { IssuedInvoicePdfQuery, ReceivedInvoicePdfQuery, PdfDownloadOptions, InvoicePdfResult } from './contracts';
5
8
  export { parseRut } from './domain/rut';
6
- export { validateInvoice, calculateInvoiceTotals, hashContent, validarFactura, calcularTotalesFactura, hashContenido } from './domain/invoicing';
7
- export type { InvoiceInput, InvoiceLineInput, InvoiceTotals, EntradaFactura, LineaFactura, TotalesFactura } from './domain/invoicing';
9
+ export { validateInvoice, calculateInvoiceTotals, hashContent, INVOICE_ADDITIONAL_TAX_RATES, validarFactura, calcularTotalesFactura, hashContenido } from './domain/invoicing';
10
+ export type { InvoiceInput, InvoiceLineInput, InvoiceTotals, InvoiceAdditionalTaxCode, InvoiceGlobalDiscount, InvoiceReferenceDocumentType, InvoiceReferenceInput, InvoicePaymentInput, InvoiceTransportInput, EntradaFactura, LineaFactura, TotalesFactura } from './domain/invoicing';
8
11
  export type { DocumentoPreparado, DocumentoFirmado, DocumentoEnviado, FirmaDocumento } from './infrastructure/sii-client';
9
12
  export { parseDteXml, parseDteDocumentXml } from './infrastructure/dte-xml';
13
+ export { normalizeDteFolio, reconcileDteDetail } from './domain/dte-reconciliation';
14
+ export type { DteFiscalDetail, DteReconciliation, DteReconciliationDiagnostic, DteReconciledAmounts, DteReconciledLine, DteTotalRounding, DteFiscalObservation } from './domain/invoice-xml';
10
15
  export { DteXmlError, MAX_DTE_XML_BYTES } from './domain/invoice-xml';
11
16
  export type { ConsultaXmlFacturaEmitida, ConsultaXmlFacturaRecibida, DteInvoiceLine, DteInvoiceDetail, ResultadoXmlFacturaEmitida } from './domain/invoice-xml';
12
- export type { TipoDocumentoEmitido, ConsultaXmlDocumentoEmitido, DteDocumentDetail, ResultadoXmlDocumentoEmitido } from './domain/invoice-xml';
17
+ export type { TipoDocumentoEmitido, ConsultaXmlDocumentoEmitido, DteDocumentDetail, DteIssuanceOptions, ResultadoXmlDocumentoEmitido } from './domain/invoice-xml';
13
18
  export type { ConsultaFacturasEmitidas, FacturaEmitida, ResultadoFacturasEmitidas, TipoFacturaEmitida } from './domain/issued-invoice';
14
19
  export type { ConsultaFacturasRecibidas, FacturaRecibida, ResultadoFacturasRecibidas } from './domain/received-invoice';
15
20
  export type { ConsultaResumen, CredencialesSii, EmpresaAutorizada, EstadoCompra, Operacion, RegistroSii, RespuestaSii, SesionSii, SiiClientOptions, } from './infrastructure/sii-client';
16
21
  export type { SummaryQuery, SiiCredentials, SiiSession, Operation, PurchaseStatus, SiiRecord, SiiResponse, AuthorizedCompany, PreparedDocument, SignedDocument, SentDocument, SignDocumentInput, } from './infrastructure/sii-client';
17
22
  export type { IssuedInvoicesQuery, IssuedInvoice, IssuedInvoicesResult, InvoiceDocumentType, } from './domain/issued-invoice';
18
23
  export type { ReceivedInvoicesQuery, ReceivedInvoice, ReceivedInvoicesResult, } from './domain/received-invoice';
19
- export type { IssuedInvoiceXmlQuery, ReceivedInvoiceXmlQuery, InvoiceXmlResult, IssuedDocumentType, IssuedDocumentXmlQuery, IssuedDocumentXmlResult, } from './domain/invoice-xml';
24
+ export type { IssuedInvoiceXmlQuery, ReceivedInvoiceXmlQuery, InvoiceXmlResult, IssuedDocumentType, IssuedDocumentXmlQuery, ReceivedDocumentXmlQuery, IssuedDocumentXmlResult, } from './domain/invoice-xml';
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MAX_DTE_XML_BYTES = exports.DteXmlError = exports.parseDteDocumentXml = exports.parseDteXml = exports.hashContenido = exports.calcularTotalesFactura = exports.validarFactura = exports.hashContent = exports.calculateInvoiceTotals = exports.validateInvoice = exports.parseRut = exports.sanitizeSiiDiagnostics = exports.SiiError = exports.SiiClient = void 0;
3
+ exports.MAX_DTE_XML_BYTES = exports.DteXmlError = exports.reconcileDteDetail = exports.normalizeDteFolio = exports.parseDteDocumentXml = exports.parseDteXml = exports.hashContenido = exports.calcularTotalesFactura = exports.validarFactura = exports.INVOICE_ADDITIONAL_TAX_RATES = exports.hashContent = exports.calculateInvoiceTotals = exports.validateInvoice = exports.parseRut = exports.sanitizeSiiDiagnostics = exports.SiiError = exports.SiiClient = void 0;
4
4
  var sii_client_1 = require("./infrastructure/sii-client");
5
5
  Object.defineProperty(exports, "SiiClient", { enumerable: true, get: function () { return sii_client_1.SiiClient; } });
6
6
  Object.defineProperty(exports, "SiiError", { enumerable: true, get: function () { return sii_client_1.SiiError; } });
@@ -12,12 +12,16 @@ var invoicing_1 = require("./domain/invoicing");
12
12
  Object.defineProperty(exports, "validateInvoice", { enumerable: true, get: function () { return invoicing_1.validateInvoice; } });
13
13
  Object.defineProperty(exports, "calculateInvoiceTotals", { enumerable: true, get: function () { return invoicing_1.calculateInvoiceTotals; } });
14
14
  Object.defineProperty(exports, "hashContent", { enumerable: true, get: function () { return invoicing_1.hashContent; } });
15
+ Object.defineProperty(exports, "INVOICE_ADDITIONAL_TAX_RATES", { enumerable: true, get: function () { return invoicing_1.INVOICE_ADDITIONAL_TAX_RATES; } });
15
16
  Object.defineProperty(exports, "validarFactura", { enumerable: true, get: function () { return invoicing_1.validarFactura; } });
16
17
  Object.defineProperty(exports, "calcularTotalesFactura", { enumerable: true, get: function () { return invoicing_1.calcularTotalesFactura; } });
17
18
  Object.defineProperty(exports, "hashContenido", { enumerable: true, get: function () { return invoicing_1.hashContenido; } });
18
19
  var dte_xml_1 = require("./infrastructure/dte-xml");
19
20
  Object.defineProperty(exports, "parseDteXml", { enumerable: true, get: function () { return dte_xml_1.parseDteXml; } });
20
21
  Object.defineProperty(exports, "parseDteDocumentXml", { enumerable: true, get: function () { return dte_xml_1.parseDteDocumentXml; } });
22
+ var dte_reconciliation_1 = require("./domain/dte-reconciliation");
23
+ Object.defineProperty(exports, "normalizeDteFolio", { enumerable: true, get: function () { return dte_reconciliation_1.normalizeDteFolio; } });
24
+ Object.defineProperty(exports, "reconcileDteDetail", { enumerable: true, get: function () { return dte_reconciliation_1.reconcileDteDetail; } });
21
25
  var invoice_xml_1 = require("./domain/invoice-xml");
22
26
  Object.defineProperty(exports, "DteXmlError", { enumerable: true, get: function () { return invoice_xml_1.DteXmlError; } });
23
27
  Object.defineProperty(exports, "MAX_DTE_XML_BYTES", { enumerable: true, get: function () { return invoice_xml_1.MAX_DTE_XML_BYTES; } });
@@ -0,0 +1,13 @@
1
+ import type { DocumentReadPort } from '../application/document-status';
2
+ import type { BoundDocumentStatusQuery, BoundRecipientEventsQuery, DocumentQueryOptions } from '../domain/document-status';
3
+ import { SiiHttpSession } from './sii-http-session';
4
+ /** Read-only personal queries; authentication and company authorization belong to the session. */
5
+ export declare class DocumentStatusGateway implements DocumentReadPort {
6
+ #private;
7
+ private readonly session;
8
+ constructor(session: SiiHttpSession);
9
+ get companyRut(): string;
10
+ assertReady(): void;
11
+ status(query: BoundDocumentStatusQuery, options?: DocumentQueryOptions): Promise<import("../domain/document-status").DocumentVerification>;
12
+ recipientEvents(query: BoundRecipientEventsQuery, options?: DocumentQueryOptions): Promise<import("../domain/document-status").RecipientEventsObservation>;
13
+ }