@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,7 @@ exports.parseDteDocumentXml = parseDteDocumentXml;
5
5
  const saxes_1 = require("saxes");
6
6
  const rut_1 = require("../domain/rut");
7
7
  const invoice_xml_1 = require("../domain/invoice-xml");
8
+ const dte_reconciliation_1 = require("../domain/dte-reconciliation");
8
9
  function invalid() { throw new invoice_xml_1.DteXmlError('SII_XML_INVALID'); }
9
10
  const children = (node, name) => node.children.filter(n => n.name === name && n.uri === node.uri);
10
11
  function one(node, name) {
@@ -17,17 +18,19 @@ function text(node, name, required = false, limit = 1000) {
17
18
  invalid();
18
19
  if (!values.length)
19
20
  return null;
20
- const value = values[0];
21
- if (value.children.length || value.text.length > limit || (required && !value.text.trim()))
21
+ return nodeText(values[0], required, limit);
22
+ }
23
+ function nodeText(node, required = false, limit = 1000) {
24
+ if (node.children.length || node.text.length > limit || (required && !node.text.trim()))
22
25
  invalid();
23
- return value.text.trim() || null;
26
+ return node.text.trim() || null;
24
27
  }
25
- function integer(node, name, required = false) {
28
+ function integer(node, name, required = false, signed = false) {
26
29
  const value = text(node, name, required, 20);
27
30
  if (value === null)
28
31
  return null;
29
32
  const number = Number(value);
30
- if (!/^\d+$/.test(value) || !Number.isSafeInteger(number))
33
+ if (!(signed ? /^-?\d+$/ : /^\d+$/).test(value) || !Number.isSafeInteger(number))
31
34
  invalid();
32
35
  return number;
33
36
  }
@@ -52,13 +55,21 @@ function uniqueLines(items) {
52
55
  if (new Set(items.map(item => item.lineNumber)).size !== items.length)
53
56
  invalid();
54
57
  }
58
+ function fiscalFolio(value) {
59
+ try {
60
+ return (0, dte_reconciliation_1.normalizeDteFolio)(value);
61
+ }
62
+ catch {
63
+ return invalid();
64
+ }
65
+ }
55
66
  /** Bounded, namespace-aware parsing; no DTD, external entities or network I/O. */
56
67
  function parseDteXml(xml, expected) {
57
68
  const parsed = parseDocumentXml(xml, expected, false);
58
69
  const documentType = parsed.detail.documentType;
59
70
  if (documentType !== 33 && documentType !== 34)
60
71
  invalid();
61
- const { fiscalHeader: _header, hasSignature: _signature, hasTransport: _transport, ...detail } = parsed.detail;
72
+ const { fiscalHeader: _header, hasSignature: _signature, hasTransport: _transport, issuanceOptions: _options, ...detail } = parsed.detail;
62
73
  return { ...parsed, detail: { ...detail, documentType } };
63
74
  }
64
75
  /** Issued invoices and credit notes; preserves original bytes and validates fiscal references. */
@@ -115,7 +126,14 @@ function parseDocumentXml(xml, expected, allowCreditNotes) {
115
126
  const totals = one(headerNode, 'Totales');
116
127
  const issuer = one(headerNode, 'Emisor'), receiver = one(headerNode, 'Receptor');
117
128
  const documentType = integer(identity, 'TipoDTE', true);
118
- const folio = text(identity, 'Folio', true, 20);
129
+ const grossAmounts = integer(identity, 'MntBruto');
130
+ if (grossAmounts !== null && grossAmounts !== 1)
131
+ invalid();
132
+ const declaredFolio = text(identity, 'Folio', true, 20);
133
+ const folio = fiscalFolio(declaredFolio);
134
+ const normalization = [];
135
+ if (folio !== declaredFolio)
136
+ normalization.push({ code: 'FOLIO_NORMALIZED', severity: 'INFO', message: 'Folio numérico normalizado sin modificar su forma declarada ni los bytes XML.' });
119
137
  let issuerRut, receiverRut;
120
138
  try {
121
139
  issuerRut = (0, rut_1.parseRut)(text(issuer, 'RUTEmisor', true, 12)).formatted;
@@ -124,13 +142,26 @@ function parseDocumentXml(xml, expected, allowCreditNotes) {
124
142
  catch {
125
143
  return invalid();
126
144
  }
127
- if ((documentType !== 33 && documentType !== 34 && (!allowCreditNotes || documentType !== 61)) || !/^[1-9]\d{0,19}$/.test(folio))
145
+ if (documentType !== 33 && documentType !== 34 && (!allowCreditNotes || documentType !== 61))
128
146
  invalid();
129
- if (issuerRut !== (0, rut_1.parseRut)(expected.issuerRut).formatted || documentType !== expected.documentType || folio !== expected.folio || (expected.receiverRut !== undefined && receiverRut !== (0, rut_1.parseRut)(expected.receiverRut).formatted))
147
+ if (issuerRut !== (0, rut_1.parseRut)(expected.issuerRut).formatted || documentType !== expected.documentType || folio !== fiscalFolio(expected.folio) || (expected.receiverRut !== undefined && receiverRut !== (0, rut_1.parseRut)(expected.receiverRut).formatted))
130
148
  throw new invoice_xml_1.DteXmlError('SII_XML_IDENTITY_MISMATCH');
131
149
  const lines = children(document, 'Detalle').map(line => ({
132
150
  lineNumber: lineNumber(line, 'NroLinDet'), name: text(line, 'NmbItem', true, 80), description: text(line, 'DscItem'),
133
- codes: children(line, 'CdgItem').map(code => ({ type: text(code, 'TpoCodigo', true, 10), value: text(code, 'VlrCodigo', true, 35) })),
151
+ codes: children(line, 'CdgItem').flatMap(code => {
152
+ const type = text(code, 'TpoCodigo', false, 10), value = text(code, 'VlrCodigo', false, 35);
153
+ if (value && !type)
154
+ invalid();
155
+ if (!value)
156
+ normalization.push({ code: 'EMPTY_OPTIONAL_PRODUCT_CODE', severity: 'INFO', message: 'Código de producto opcional vacío tratado como ausente.', lineNumber: lineNumber(line, 'NroLinDet') });
157
+ return type && value ? [{ type, value }] : [];
158
+ }),
159
+ ...(children(line, 'CodImpAdic').length ? { additionalTaxCodes: children(line, 'CodImpAdic').map(node => {
160
+ const value = nodeText(node, true, 6);
161
+ if (!/^\d{1,6}$/.test(value))
162
+ invalid();
163
+ return Number(value);
164
+ }) } : {}),
134
165
  quantity: decimal(line, 'QtyItem'), unit: text(line, 'UnmdItem', false, 4), unitPrice: decimal(line, 'PrcItem'),
135
166
  discountPercent: decimal(line, 'DescuentoPct'), discountAmount: integer(line, 'DescuentoMonto'),
136
167
  surchargePercent: decimal(line, 'RecargoPct'), surchargeAmount: integer(line, 'RecargoMonto'), exemptIndicator: integer(line, 'IndExe'), amount: integer(line, 'MontoItem', true),
@@ -143,31 +174,118 @@ function parseDocumentXml(xml, expected, allowCreditNotes) {
143
174
  invalid();
144
175
  return { lineNumber: lineNumber(node, 'NroLinDR'), movement: movement, description: text(node, 'GlosaDR'), valueType: valueType, value: decimal(node, 'ValorDR', true), exemptIndicator: integer(node, 'IndExeDR') };
145
176
  });
146
- const references = children(document, 'Referencia').map(node => ({
147
- lineNumber: lineNumber(node, 'NroLinRef'), documentType: text(node, 'TpoDocRef', true, 3), folio: text(node, 'FolioRef', true, 18), date: date(node, 'FchRef'), code: integer(node, 'CodRef'), reason: text(node, 'RazonRef', false, 90),
148
- }));
177
+ const references = children(document, 'Referencia').map(node => {
178
+ const documentType = text(node, 'TpoDocRef', true, 3), declared = text(node, 'FolioRef', true, 18);
179
+ const folio = /^\d{1,3}$/.test(documentType) && Number(documentType) > 0 && Number(documentType) < 200 && /^\d+$/.test(declared)
180
+ ? BigInt(declared) === 0n ? '0' : fiscalFolio(declared) : declared;
181
+ if (folio !== declared)
182
+ normalization.push({ code: 'REFERENCE_FOLIO_NORMALIZED', severity: 'INFO', message: 'Folio de referencia fiscal normalizado; se conserva su forma declarada.' });
183
+ return { lineNumber: lineNumber(node, 'NroLinRef'), documentType, folio, ...(folio !== declared ? { declaredFolio: declared } : {}), date: date(node, 'FchRef'), code: integer(node, 'CodRef'), reason: text(node, 'RazonRef', false, 90) };
184
+ });
149
185
  uniqueLines(lines);
150
186
  uniqueLines(adjustments);
151
187
  uniqueLines(references);
152
- if (documentType === 61 && (!references.length
153
- || references.some(reference => reference.code === null || ![1, 2, 3].includes(reference.code))
154
- || (references.some(reference => reference.code === 1 || reference.code === 2) && references.length !== 1)))
188
+ const fiscalReferences = references.filter(reference => /^\d{1,3}$/.test(reference.documentType) && Number(reference.documentType) > 0 && Number(reference.documentType) < 200);
189
+ if (documentType === 61 && (!fiscalReferences.length
190
+ || fiscalReferences.some(reference => reference.code === null || ![1, 2, 3].includes(reference.code) || !/^[1-9]\d{0,19}$/.test(reference.folio))
191
+ || (fiscalReferences.some(reference => reference.code === 1 || reference.code === 2) && fiscalReferences.length !== 1)))
155
192
  invalid();
156
193
  const signatures = dtes[0].children.filter(node => node.name === 'Signature' && node.uri === 'http://www.w3.org/2000/09/xmldsig#');
157
194
  if (allowCreditNotes && signatures.length > 1)
158
195
  invalid();
159
- return { xml: new Uint8Array(xml), encoding, detail: {
160
- issuerRut, documentType: expected.documentType, folio, issuedDate: date(identity, 'FchEmis'), receiverRut,
161
- hasSignature: signatures.length === 1,
162
- hasTransport: children(headerNode, 'Transporte').some(node => node.children.length > 0 || node.text.trim().length > 0 || node.attributeCount > 0),
163
- ...(allowCreditNotes ? { fiscalHeader: {
164
- issuer: { legalName: text(issuer, 'RznSoc'), businessActivity: text(issuer, 'GiroEmis'), activityCode: text(issuer, 'Acteco'), branchCode: text(issuer, 'CdgSIISucur', false, 9), address: text(issuer, 'DirOrigen'), commune: text(issuer, 'CmnaOrigen'), city: text(issuer, 'CiudadOrigen') },
165
- receiver: { legalName: text(receiver, 'RznSocRecep'), address: text(receiver, 'DirRecep'), commune: text(receiver, 'CmnaRecep'), city: text(receiver, 'CiudadRecep'), businessActivity: text(receiver, 'GiroRecep'), contact: text(receiver, 'Contacto') },
166
- paymentForm: integer(identity, 'FmaPago'), saleType: integer(identity, 'TpoTranVenta'), purchaseType: integer(identity, 'TpoTranCompra'),
167
- noDebitReduction: integer(identity, 'IndNoRebaja', children(identity, 'IndNoRebaja').length > 0),
168
- unapprovedFiscalFields: identity.children.filter(node => node.uri === identity.uri && !['TipoDTE', 'Folio', 'FchEmis', 'FmaPago', 'TpoTranVenta', 'TpoTranCompra', 'IndNoRebaja'].includes(node.name)).map(node => node.name),
169
- } } : {}),
170
- netAmount: integer(totals, 'MntNeto'), exemptAmount: integer(totals, 'MntExe'), vatRate: decimal(totals, 'TasaIVA'), vatAmount: integer(totals, 'IVA'), totalAmount: integer(totals, 'MntTotal', true), lines,
171
- taxes: children(totals, 'ImptoReten').map(node => ({ type: integer(node, 'TipoImp', true), rate: decimal(node, 'TasaImp'), amount: integer(node, 'MontoImp', true) })), adjustments, references,
172
- } };
196
+ const options = allowCreditNotes ? issuanceOptions(headerNode, identity, issuer, document) : undefined;
197
+ const issuerActivities = allowCreditNotes ? children(issuer, 'Acteco').map(node => nodeText(node)) : [];
198
+ const paymentTotals = Object.fromEntries([
199
+ ['MontoNF', 'nonBillableAmount', true], ['MontoPeriodo', 'periodAmount', false],
200
+ ['SaldoAnterior', 'previousBalance', true], ['VlrPagar', 'payableAmount', false],
201
+ ].flatMap(([tag, field, signed]) => {
202
+ const value = integer(totals, tag, false, signed);
203
+ return value === null ? [] : [[field, value]];
204
+ }));
205
+ const detail = {
206
+ ...(grossAmounts === 1 ? { grossAmounts: true } : {}),
207
+ ...paymentTotals,
208
+ issuerRut, documentType: expected.documentType, folio, ...(folio !== declaredFolio ? { declaredFolio } : {}), issuedDate: date(identity, 'FchEmis'), receiverRut,
209
+ hasSignature: signatures.length === 1,
210
+ hasTransport: children(headerNode, 'Transporte').some(node => node.children.length > 0 || node.text.trim().length > 0 || node.attributeCount > 0),
211
+ ...(options ? { issuanceOptions: options } : {}),
212
+ ...(allowCreditNotes ? { fiscalHeader: {
213
+ issuer: { legalName: text(issuer, 'RznSoc'), businessActivity: text(issuer, 'GiroEmis'), activityCode: issuerActivities.length === 1 ? issuerActivities[0] : null, branchCode: text(issuer, 'CdgSIISucur', false, 9), address: text(issuer, 'DirOrigen'), commune: text(issuer, 'CmnaOrigen'), city: text(issuer, 'CiudadOrigen') },
214
+ receiver: { legalName: text(receiver, 'RznSocRecep'), address: text(receiver, 'DirRecep'), commune: text(receiver, 'CmnaRecep'), city: text(receiver, 'CiudadRecep'), businessActivity: text(receiver, 'GiroRecep'), contact: text(receiver, 'Contacto') },
215
+ paymentForm: integer(identity, 'FmaPago'), saleType: integer(identity, 'TpoTranVenta'), purchaseType: integer(identity, 'TpoTranCompra'),
216
+ noDebitReduction: integer(identity, 'IndNoRebaja', children(identity, 'IndNoRebaja').length > 0),
217
+ unapprovedFiscalFields: [...identity.children.filter(node => node.uri === identity.uri && !['TipoDTE', 'Folio', 'FchEmis', 'FmaPago', 'TpoTranVenta', 'TpoTranCompra', 'IndNoRebaja', 'MntPagos'].includes(node.name)).map(node => node.name), ...(issuerActivities.length > 1 ? ['Acteco'] : [])],
218
+ } } : {}),
219
+ netAmount: integer(totals, 'MntNeto'), exemptAmount: integer(totals, 'MntExe'), vatRate: decimal(totals, 'TasaIVA'), vatAmount: integer(totals, 'IVA'), totalAmount: integer(totals, 'MntTotal', true), lines,
220
+ taxes: children(totals, 'ImptoReten').map(node => ({ type: integer(node, 'TipoImp', true), rate: decimal(node, 'TasaImp'), amount: integer(node, 'MontoImp', true) })), adjustments, references,
221
+ };
222
+ detail.reconciliation = (0, dte_reconciliation_1.reconcileDteDetail)(detail);
223
+ detail.reconciliation.diagnostics.unshift(...normalization);
224
+ return { xml: new Uint8Array(xml), encoding, detail };
225
+ }
226
+ function issuanceOptions(header, identity, issuer, document) {
227
+ const unsupported = [];
228
+ const inspect = (node, allowed, path) => {
229
+ if (node.attributeCount || node.text.trim())
230
+ unsupported.push(path);
231
+ for (const child of node.children) {
232
+ if (child.uri !== node.uri || !allowed.includes(child.name) || child.attributeCount)
233
+ unsupported.push(`${path}/${child.name}`);
234
+ }
235
+ };
236
+ const optionalRut = (node, name) => {
237
+ const value = text(node, name, false, 15);
238
+ if (value === null)
239
+ return null;
240
+ try {
241
+ return (0, rut_1.parseRut)(value).formatted;
242
+ }
243
+ catch {
244
+ return invalid();
245
+ }
246
+ };
247
+ const transports = children(header, 'Transporte');
248
+ if (transports.length > 1)
249
+ invalid();
250
+ const transportNode = transports[0];
251
+ let transport = null;
252
+ if (transportNode) {
253
+ inspect(transportNode, ['Patente', 'RUTTrans', 'Chofer'], 'Transporte');
254
+ const drivers = children(transportNode, 'Chofer');
255
+ if (drivers.length > 1)
256
+ invalid();
257
+ const driver = drivers[0];
258
+ if (driver)
259
+ inspect(driver, ['RUTChofer', 'NombreChofer'], 'Transporte/Chofer');
260
+ const value = { carrierRut: optionalRut(transportNode, 'RUTTrans'), licensePlate: text(transportNode, 'Patente', false, 8), driverRut: driver ? optionalRut(driver, 'RUTChofer') : null, driverName: driver ? text(driver, 'NombreChofer', false, 30) : null };
261
+ if (Object.values(value).some(part => part !== null))
262
+ transport = value;
263
+ }
264
+ const payments = children(identity, 'MntPagos').map(node => {
265
+ inspect(node, ['FchPago', 'MntPago', 'GlosaPagos'], 'IdDoc/MntPagos');
266
+ return { date: date(node, 'FchPago'), amount: integer(node, 'MntPago', true), description: text(node, 'GlosaPagos', false, 40) };
267
+ });
268
+ const lineTaxCodes = children(document, 'Detalle').flatMap(line => {
269
+ const codes = children(line, 'CodImpAdic').map(node => {
270
+ if (node.children.length || node.attributeCount)
271
+ unsupported.push('Detalle/CodImpAdic');
272
+ const value = node.text.trim();
273
+ if (!/^\d{1,6}$/.test(value))
274
+ invalid();
275
+ return Number(value);
276
+ });
277
+ return codes.length ? [{ lineNumber: lineNumber(line, 'NroLinDet'), codes }] : [];
278
+ });
279
+ const referenceGlobalIndicators = children(document, 'Referencia').flatMap(ref => {
280
+ const indicator = integer(ref, 'IndGlobal');
281
+ return indicator === null ? [] : [{ lineNumber: lineNumber(ref, 'NroLinRef'), indicator }];
282
+ });
283
+ const issuerPhones = children(issuer, 'Telefono').map(node => {
284
+ if (node.children.length || node.text.length > 20 || !node.text.trim())
285
+ invalid();
286
+ return node.text.trim();
287
+ });
288
+ const issuerEmail = text(issuer, 'CorreoEmisor', false, 80), requesterRut = optionalRut(header, 'RUTSolicita');
289
+ const result = { issuerEmail, issuerPhones, requesterRut, transport, payments, lineTaxCodes, referenceGlobalIndicators, unapprovedFields: unsupported };
290
+ return issuerEmail !== null || issuerPhones.length || requesterRut !== null || transport !== null || payments.length || lineTaxCodes.length || referenceGlobalIndicators.length || unsupported.length ? result : undefined;
173
291
  }
@@ -1,6 +1,7 @@
1
+ import type { CompanyInfo } from '../domain/company-info';
1
2
  import { type InvoiceInput } from '../domain/invoicing';
2
3
  import { type PreparedDocument, type DocumentContent, type SignedDocument } from '../domain/document';
3
- import { type IssuedInvoiceXmlQuery, type ReceivedInvoiceXmlQuery, type InvoiceXmlResult, type IssuedDocumentXmlQuery, type IssuedDocumentXmlResult } from '../domain/invoice-xml';
4
+ import { type IssuedInvoiceXmlQuery, type ReceivedInvoiceXmlQuery, type InvoiceXmlResult, type IssuedDocumentXmlQuery, type ReceivedDocumentXmlQuery, type IssuedDocumentXmlResult } from '../domain/invoice-xml';
4
5
  import type { InvoicingPort } from '../application/issuance';
5
6
  import type { IssuedInvoicePdfQuery, ReceivedInvoicePdfQuery, PdfDownloadOptions, InvoicePdfResult } from '../contracts';
6
7
  import { SiiHttpSession } from './sii-http-session';
@@ -12,6 +13,7 @@ export declare class FacturadorGateway implements InvoicingPort {
12
13
  assertReady(): void;
13
14
  close(): Promise<void>;
14
15
  clearPreparation(): void;
16
+ companyInfo(rut: string): Promise<CompanyInfo>;
15
17
  prepareInvoice(input: InvoiceInput): Promise<DocumentContent>;
16
18
  prepareCancellationCreditNote({ factura, issuedDate }: {
17
19
  factura: IssuedInvoiceXmlQuery;
@@ -23,6 +25,7 @@ export declare class FacturadorGateway implements InvoicingPort {
23
25
  issuedInvoiceXml(input: IssuedInvoiceXmlQuery): Promise<InvoiceXmlResult>;
24
26
  receivedInvoiceXml(input: ReceivedInvoiceXmlQuery): Promise<InvoiceXmlResult>;
25
27
  issuedDocumentXml(input: IssuedDocumentXmlQuery): Promise<IssuedDocumentXmlResult>;
28
+ receivedDocumentXml(input: ReceivedDocumentXmlQuery): Promise<IssuedDocumentXmlResult>;
26
29
  issuedInvoicePdf(input: IssuedInvoicePdfQuery, options?: PdfDownloadOptions): Promise<InvoicePdfResult>;
27
30
  receivedInvoicePdf(input: ReceivedInvoicePdfQuery, options?: PdfDownloadOptions): Promise<InvoicePdfResult>;
28
31
  }
@@ -25,6 +25,38 @@ class FacturadorGateway {
25
25
  assertReady() { this.session.assertReady(); }
26
26
  close() { return this.closeSession(); }
27
27
  clearPreparation() { this.#ready = false; this.#preparation = undefined; this.#signing = undefined; }
28
+ async companyInfo(rut) {
29
+ this.session.assertReady();
30
+ const receiver = (0, rut_1.parseRut)(rut);
31
+ if (this.#preparation || this.#signing)
32
+ throw new sii_error_1.SiiError('SII_OPERATION_IN_PROGRESS');
33
+ await this.#ensurePortal(DESTINATION, undefined, true);
34
+ const fields = new URLSearchParams({ PTDC_CODIGO: '33', EHDR_CODIGO: '', EFXP_FOLIO: '', ES_BORR: 'FALSE', esCRED_EC: 'FALSE', esFACT_TUR: 'FALSE' });
35
+ const lookup = await this.#lookupReceiver(fields, receiver);
36
+ let returnedRut;
37
+ try {
38
+ returnedRut = (0, rut_1.parseRut)(`${lookup.fields.get('EFXP_RUT_RECEP')?.trim()}-${lookup.fields.get('EFXP_DV_RECEP')?.trim()}`).formatted;
39
+ }
40
+ catch {
41
+ throw this.session.failure('SII_PROTOCOL_CHANGED', 'mipeGenFacEx.cgi', 'INVALID_RESPONSE', undefined, { stage: 'COMPANY_LOOKUP' });
42
+ }
43
+ if (returnedRut !== receiver.formatted)
44
+ throw this.session.failure('SII_COMPANY_IDENTITY_MISMATCH', 'mipeGenFacEx.cgi', 'COMPANY_IDENTITY_MISMATCH', undefined, { stage: 'COMPANY_LOOKUP' });
45
+ const legalName = lookup.fields.get('EFXP_RZN_SOC_RECEP')?.trim();
46
+ if (legalName === undefined || legalName.length > 100 || /[\u0000-\u001f\u007f]/u.test(legalName))
47
+ throw this.session.failure('SII_PROTOCOL_CHANGED', 'mipeGenFacEx.cgi', 'INVALID_RESPONSE', undefined, { stage: 'COMPANY_LOOKUP' });
48
+ if (!legalName)
49
+ throw this.session.failure('SII_COMPANY_INFO_UNAVAILABLE', 'mipeGenFacEx.cgi', 'COMPANY_INFO_UNAVAILABLE', undefined, { stage: 'COMPANY_LOOKUP' });
50
+ let options;
51
+ try {
52
+ options = (0, facturador_1.readCompanyOptions)(lookup.page.document);
53
+ }
54
+ catch {
55
+ throw this.session.failure('SII_PROTOCOL_CHANGED', 'mipeGenFacEx.cgi', 'INVALID_RESPONSE', undefined, { stage: 'COMPANY_LOOKUP' });
56
+ }
57
+ this.session.assertReady();
58
+ return { rut: returnedRut, legalName, ...options, source: 'SII_FACTURADOR', observedAt: new Date().toISOString() };
59
+ }
28
60
  async prepareInvoice(input) {
29
61
  this.session.assertReady();
30
62
  const invoice = input;
@@ -35,45 +67,99 @@ class FacturadorGateway {
35
67
  const issuerAddress = this.#assertOption(page, 'emisorDir', invoice.issuer.address, invoice.issuer.commune);
36
68
  this.#assertOption(page, 'emisorActEco', invoice.issuer.activityCode);
37
69
  const receiver = (0, rut_1.parseRut)(invoice.receiver.rut);
38
- fields.set('EFXP_RUT_RECEP', receiver.rut);
39
- fields.set('EFXP_DV_RECEP', receiver.dv);
40
- page = await this.#portal('mipeGenFacEx.cgi', fields);
41
- fields = this.#form(page, 'VIEW_EFXP', 'mipeDisplayPreView.cgi');
42
- this.#assertNewInvoice(fields);
70
+ ({ page, fields } = await this.#lookupReceiver(fields, receiver));
43
71
  this.#assertOption(page, 'recptorDir', invoice.receiver.address, invoice.receiver.commune);
44
72
  this.#assertOption(page, 'recptoActEco', invoice.receiver.businessActivity, undefined, 1);
45
73
  if (fields.get('EFXP_RZN_SOC_RECEP')?.trim() && fields.get('EFXP_RZN_SOC_RECEP')?.trim() !== invoice.receiver.legalName)
46
74
  throw this.session.failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeGenFacEx.cgi', 'DOCUMENT_CONTENT_MISMATCH');
47
- const totals = (0, invoicing_1.calculateInvoiceTotals)(invoice.items);
75
+ const breakdown = (0, invoicing_1.invoiceBreakdown)(invoice.items, invoice.globalDiscount), totals = breakdown.totals;
76
+ for (const key of [...fields.keys()])
77
+ if (/^(?:EFXP_(?:TPO_COD|COD|NMB|QTY|UNMD|PRC|OTRO_IMP|PCTD|SUBT|DSC_ITEM)_\d{2}|DESCRIP_\d{2}|.*_SI_NO|EMP_MENOR_TAMANO|EFXP_(?:TPO_DOC_REF|IND_GLOBAL|FOLIO_REF|FCH_REF|CODIGO_REF|RAZON_REF|FCH_PAGO|MNT_PAGO|GLOSA_PAGOS)_\d{3}|cbo_(?:dia|mes|anio)_boleta_(?:ref|pago)_\d{2}|EFXP_(?:FCH_VENC|COMUNA_ROL_ORIGEN|MAN_ROL_ORIGEN|PRED_ROL_ORIGEN|SIST_REF_GEO|LAT_ORIG_MADERA|LONG_ORIG_MADERA|COD_PLAN_CONAF))$/.test(key))
78
+ fields.delete(key);
79
+ const requester = invoice.requesterRut ? (0, rut_1.parseRut)(invoice.requesterRut) : undefined;
80
+ const carrier = invoice.transport ? (0, rut_1.parseRut)(invoice.transport.carrierRut) : undefined, driver = invoice.transport ? (0, rut_1.parseRut)(invoice.transport.driverRut) : undefined;
48
81
  const values = {
49
82
  PTDC_CODIGO: '33', EFXP_FCH_EMIS: invoice.issuedDate, CANT_DET: String(invoice.items.length), ES_BORR: 'FALSE',
50
83
  EFXP_DIR_ORIGEN: invoice.issuer.address, EFXP_CMNA_ORIGEN: invoice.issuer.commune, EFXP_CIUDAD_ORIGEN: invoice.issuer.city,
51
- EFXP_CDG_SII_SUCUR: issuerAddress[3]?.trim() === '0' ? '' : issuerAddress[3]?.trim() ?? '', EFXP_FONO_EMISOR: issuerAddress[4]?.trim() ?? '',
84
+ EFXP_CDG_SII_SUCUR: issuerAddress[3]?.trim() === '0' ? '' : issuerAddress[3]?.trim() ?? '', EFXP_FONO_EMISOR: invoice.issuer.phone ?? issuerAddress[4]?.trim() ?? '',
85
+ EFXP_EMAIL_EMISOR: invoice.issuer.email ?? fields.get('EFXP_EMAIL_EMISOR')?.trim() ?? '',
52
86
  EFXP_ACTECO: invoice.issuer.activityCode, EFXP_ACTECO_SELECT: invoice.issuer.activityCode, EFXP_TIPOVENTA_SELECT: String(invoice.saleType),
53
87
  EFXP_RUT_RECEP: receiver.rut, EFXP_DV_RECEP: receiver.dv, EFXP_RZN_SOC_RECEP: invoice.receiver.legalName,
54
88
  EFXP_DIR_RECEP: invoice.receiver.address, EFXP_CMNA_RECEP: invoice.receiver.commune, EFXP_CIUDAD_RECEP: invoice.receiver.city,
55
89
  EFXP_GIRO_RECEP: invoice.receiver.businessActivity, EFXP_CONTACTO: invoice.receiver.contact ?? '', EFXP_TIPOCOMPRA_SELECT: String(invoice.purchaseType),
56
- EFXP_RUT_SOLICITA: '', EFXP_DV_SOLICITA: '', EFXP_FMA_PAGO: String(invoice.paymentForm),
57
- EFXP_SUBTOTAL: String(totals.netAmount), EFXP_PCT_DESC: '0', EFXP_MNT_DESC: '0', MNT_NETO_TEMP: String(totals.netAmount), IVA_TEMP: String(totals.vatAmount),
58
- EFXP_MNT_NETO: String(totals.netAmount), EFXP_TASA_IVA: '19', EFXP_IVA: String(totals.vatAmount), EFXP_MNT_TOTAL: String(totals.totalAmount), EFXP_OTRO_IMP_TOTAL: '0',
90
+ EFXP_RUT_SOLICITA: requester?.rut ?? '', EFXP_DV_SOLICITA: requester?.dv ?? '', EFXP_FMA_PAGO: String(invoice.paymentForm),
91
+ EFXP_RUT_TRANSPORTE: carrier?.rut ?? '', EFXP_DV_TRANSPORTE: carrier?.dv ?? '', EFXP_PATENTE: invoice.transport?.licensePlate ?? '',
92
+ EFXP_RUT_CHOFER: driver?.rut ?? '', EFXP_DV_CHOFER: driver?.dv ?? '', EFXP_NOMBRE_CHOFER: invoice.transport?.driverName ?? '',
93
+ EFXP_SUBTOTAL: String(breakdown.subtotal), EFXP_PCT_DESC: breakdown.discountPercent, EFXP_MNT_DESC: String(breakdown.discountAmount), MNT_NETO_TEMP: String(totals.netAmount), IVA_TEMP: String(totals.vatAmount),
94
+ EFXP_MNT_NETO: String(totals.netAmount), EFXP_TASA_IVA: '19', EFXP_IVA: String(totals.vatAmount), EFXP_MNT_TOTAL: String(totals.totalAmount), EFXP_OTRO_IMP_TOTAL: String(breakdown.additionalTaxAmount),
59
95
  };
60
96
  for (const [key, value] of Object.entries(values))
61
97
  fields.set(key, value);
62
- for (const key of [...fields.keys()])
63
- if (/^(?:EFXP_(?:TPO_COD|COD|NMB|QTY|UNMD|PRC|OTRO_IMP|PCTD|SUBT|DSC_ITEM)_\d{2}|DESCRIP_\d{2}|.*_SI_NO)$/.test(key))
64
- fields.delete(key);
98
+ const optionalPreview = {};
99
+ const optionalField = (key, value) => { fields.set(key, value); if (value)
100
+ optionalPreview[key] = value; };
101
+ if (invoice.items.some(item => item.productCode))
102
+ fields.set('COD_SI_NO', 'SiChecked');
103
+ if (invoice.items.some(item => item.additionalTaxCode !== undefined))
104
+ fields.set('OTRO_IMP_SI_NO', 'SiChecked');
105
+ if (invoice.smallBusiness)
106
+ optionalField('EMP_MENOR_TAMANO', 'SiChecked');
107
+ if (invoice.globalDiscount)
108
+ for (const key of ['EFXP_SUBTOTAL', 'EFXP_PCT_DESC', 'EFXP_MNT_DESC'])
109
+ optionalPreview[key] = values[key];
110
+ for (const key of ['EFXP_RUT_SOLICITA', 'EFXP_DV_SOLICITA', 'EFXP_RUT_TRANSPORTE', 'EFXP_DV_TRANSPORTE', 'EFXP_PATENTE', 'EFXP_RUT_CHOFER', 'EFXP_DV_CHOFER', 'EFXP_NOMBRE_CHOFER'])
111
+ if (values[key])
112
+ optionalPreview[key] = values[key];
113
+ if (invoice.issuer.email)
114
+ optionalPreview.EFXP_EMAIL_EMISOR = invoice.issuer.email;
115
+ if (invoice.issuer.phone)
116
+ optionalPreview.EFXP_FONO_EMISOR = invoice.issuer.phone;
65
117
  for (const [index, item] of invoice.items.entries()) {
66
118
  const suffix = String(index + 1).padStart(2, '0');
67
- for (const [field, value] of Object.entries({ NMB: item.name, QTY: item.quantity, PRC: item.unitNetPriceClp, UNMD: item.unit ?? '', DSC_ITEM: item.description ?? '', PCTD: '', SUBT: String((0, invoicing_1.calculateInvoiceTotals)([item]).netAmount) }))
119
+ for (const [field, value] of Object.entries({ NMB: item.name, QTY: item.quantity, PRC: item.unitNetPriceClp, UNMD: item.unit ?? '', DSC_ITEM: item.description ?? '', PCTD: item.discountPercent ?? '', SUBT: String(breakdown.lineAmounts[index].amount) }))
68
120
  fields.set(`EFXP_${field}_${suffix}`, value);
121
+ if (item.productCode) {
122
+ optionalField(`EFXP_TPO_COD_${suffix}`, item.productCode.type);
123
+ optionalField(`EFXP_COD_${suffix}`, item.productCode.value);
124
+ }
125
+ if (fields.has('OTRO_IMP_SI_NO'))
126
+ optionalField(`EFXP_OTRO_IMP_${suffix}`, item.additionalTaxCode === undefined ? '' : String(item.additionalTaxCode));
127
+ if (item.discountPercent)
128
+ optionalPreview[`EFXP_PCTD_${suffix}`] = item.discountPercent;
69
129
  if (item.description)
70
130
  fields.set(`DESCRIP_${suffix}`, 'SiChecked');
71
131
  }
132
+ const scheduleDate = (kind, index, date) => {
133
+ const suffix = String(index + 1).padStart(2, '0');
134
+ for (const [part, value] of [['anio', date.slice(0, 4)], ['mes', date.slice(5, 7)], ['dia', date.slice(8, 10)]])
135
+ fields.set(`cbo_${part}_boleta_${kind}_${suffix}`, value);
136
+ };
137
+ if (invoice.references) {
138
+ fields.set('REF_SI_NO', 'SiChecked');
139
+ invoice.references.forEach((ref, index) => {
140
+ const suffix = String(index + 1).padStart(3, '0');
141
+ for (const [key, value] of Object.entries({ TPO_DOC_REF: ref.documentType, IND_GLOBAL: ref.global ? '1' : '', FOLIO_REF: ref.folio, FCH_REF: ref.date, CODIGO_REF: '', RAZON_REF: ref.reason ?? '' }))
142
+ optionalField(`EFXP_${key}_${suffix}`, value);
143
+ scheduleDate('ref', index, ref.date);
144
+ });
145
+ }
146
+ if (invoice.payments) {
147
+ fields.set('PAGO_SI_NO', 'SiChecked');
148
+ invoice.payments.forEach((payment, index) => {
149
+ const suffix = String(index + 1).padStart(3, '0');
150
+ for (const [key, value] of Object.entries({ FCH_PAGO: payment.date, MNT_PAGO: String(payment.amountClp), GLOSA_PAGOS: payment.description ?? '' }))
151
+ optionalField(`EFXP_${key}_${suffix}`, value);
152
+ scheduleDate('pago', index, payment.date);
153
+ });
154
+ }
72
155
  page = await this.#portal('mipeDisplayPreView.cgi', fields);
73
156
  const preview = this.#form(page, 'PreViewDTE', 'mipeGenXMLFirma.cgi', 'mipeGenFacEx.cgi');
74
157
  this.#assertFields(preview, { PTDC_CODIGO: '33', EFXP_FCH_EMIS: invoice.issuedDate, EFXP_RUT_RECEP: receiver.rut, EFXP_DV_RECEP: receiver.dv, EFXP_MNT_NETO: String(totals.netAmount), EFXP_IVA: String(totals.vatAmount), EFXP_MNT_TOTAL: String(totals.totalAmount) });
158
+ this.#assertFields(preview, optionalPreview);
159
+ if (!invoice.smallBusiness && preview.get('EMP_MENOR_TAMANO') === 'SiChecked')
160
+ throw this.session.failure('SII_DOCUMENT_CONTENT_MISMATCH', 'mipeDisplayPreView.cgi', 'DOCUMENT_CONTENT_MISMATCH');
75
161
  this.#preparation = preview;
76
- return { issuerRut: this.session.company.formatted, receiverRut: receiver.formatted, documentType: 33, issuedDate: invoice.issuedDate, ...totals, invoice, issuerLegalName: fields.get('EFXP_RZN_SOC')?.trim() ?? '', issuerBusinessActivity: fields.get('EFXP_GIRO_EMIS')?.trim() ?? '', issuerBranchCode: fields.get('EFXP_CDG_SII_SUCUR') ?? '' };
162
+ return { issuerRut: this.session.company.formatted, receiverRut: receiver.formatted, documentType: 33, issuedDate: invoice.issuedDate, ...totals, invoice, issuerLegalName: fields.get('EFXP_RZN_SOC')?.trim() ?? '', issuerBusinessActivity: fields.get('EFXP_GIRO_EMIS')?.trim() ?? '', issuerBranchCode: fields.get('EFXP_CDG_SII_SUCUR') ?? '', issuerContact: { email: values.EFXP_EMAIL_EMISOR, phone: values.EFXP_FONO_EMISOR } };
77
163
  }
78
164
  async prepareCancellationCreditNote({ factura, issuedDate }) {
79
165
  this.session.assertReady();
@@ -194,6 +280,7 @@ class FacturadorGateway {
194
280
  return this.#documentXml(input, (0, rut_1.parseRut)(input.issuerRut), true);
195
281
  }
196
282
  issuedDocumentXml(input) { return this.#documentXml(input); }
283
+ async receivedDocumentXml(input) { return this.#documentXml(input, (0, rut_1.parseRut)(input.issuerRut)); }
197
284
  issuedInvoicePdf(input, options) { return this.#documentPdf(input, undefined, options); }
198
285
  async receivedInvoicePdf(input, options) { return this.#documentPdf(input, (0, rut_1.parseRut)(input.issuerRut), options); }
199
286
  async #documentPdf({ documentType, folio }, supplier, options = {}) {
@@ -356,6 +443,17 @@ class FacturadorGateway {
356
443
  throw this.session.failure('SII_PROTOCOL_CHANGED', source, 'INVALID_RESPONSE');
357
444
  }
358
445
  }
446
+ async #lookupReceiver(fields, receiver) {
447
+ fields.set('EFXP_RUT_RECEP', receiver.rut);
448
+ fields.set('EFXP_DV_RECEP', receiver.dv);
449
+ const page = await this.#portal('mipeGenFacEx.cgi', fields);
450
+ await this.#assertCompany('mipeGenFacEx.cgi');
451
+ if ((0, facturador_1.hasInteractiveCaptcha)(page.document))
452
+ throw this.session.failure('CAPTCHA_INTERACTION_REQUIRED', 'mipeGenFacEx.cgi', 'CAPTCHA_REQUIRED');
453
+ const result = this.#form(page, 'VIEW_EFXP', 'mipeDisplayPreView.cgi');
454
+ this.#assertNewInvoice(result);
455
+ return { page, fields: result };
456
+ }
359
457
  #assertOption(page, variable, value, commune, column = 0) {
360
458
  try {
361
459
  const rows = (0, facturador_1.readLiteralRows)(page.document, variable).filter(row => row[column]?.trim() === value && (commune === undefined || row[1]?.trim() === commune));
@@ -1,12 +1,15 @@
1
1
  import { type DefaultTreeAdapterTypes as Html } from 'parse5';
2
+ import type { CompanyInfo } from '../domain/company-info';
2
3
  export declare function attr(element: Html.Element, name: string): string | undefined;
3
4
  export declare function nodes(root: Html.Node): Generator<Html.Node>;
4
5
  export declare function element(node: Html.Node): node is Html.Element;
5
6
  export declare function parsePortalPage(html: string): Html.Document;
6
7
  /** Serialize only inert successful controls; provider scripts are never executed. */
7
8
  export declare function readForm(html: string | Html.Document, name: string, endpoint: string): URLSearchParams;
8
- /** Decode only the observed small JSON array declarations, never JavaScript expressions. */
9
+ /** Decode bounded JSON option tables, never JavaScript expressions. */
9
10
  export declare function readLiteralRows(html: string | Html.Document, variable: string): string[][];
11
+ /** The final all-zero row is a portal placeholder, never a company address or giro. */
12
+ export declare function readCompanyOptions(html: string | Html.Document): Pick<CompanyInfo, 'addresses' | 'businessActivities'>;
10
13
  /** Browser legacy form encoding differs from UTF-8 URLSearchParams for accents and € . */
11
14
  export declare function encodePortalForm(fields: URLSearchParams): string;
12
15
  export declare function readPortalHtml(bytes: Uint8Array): string;
@@ -6,6 +6,7 @@ exports.element = element;
6
6
  exports.parsePortalPage = parsePortalPage;
7
7
  exports.readForm = readForm;
8
8
  exports.readLiteralRows = readLiteralRows;
9
+ exports.readCompanyOptions = readCompanyOptions;
9
10
  exports.encodePortalForm = encodePortalForm;
10
11
  exports.readPortalHtml = readPortalHtml;
11
12
  exports.encodeUnsignedDteXml = encodeUnsignedDteXml;
@@ -126,7 +127,7 @@ function readForm(html, name, endpoint) {
126
127
  }
127
128
  return fields;
128
129
  }
129
- /** Decode only the observed small JSON array declarations, never JavaScript expressions. */
130
+ /** Decode bounded JSON option tables, never JavaScript expressions. */
130
131
  function readLiteralRows(html, variable) {
131
132
  if (!ROW_VARIABLES.has(variable))
132
133
  invalid();
@@ -139,7 +140,7 @@ function readLiteralRows(html, variable) {
139
140
  declarations.push(match[1]);
140
141
  }
141
142
  const literal = declarations[0];
142
- if (declarations.length !== 1 || !literal || Buffer.byteLength(literal) > 16 * 1024)
143
+ if (declarations.length !== 1 || !literal || Buffer.byteLength(literal) > 256 * 1024)
143
144
  invalid();
144
145
  let rows;
145
146
  try {
@@ -148,10 +149,27 @@ function readLiteralRows(html, variable) {
148
149
  catch {
149
150
  invalid();
150
151
  }
151
- if (!Array.isArray(rows) || rows.length > 20 || !rows.every((row) => Array.isArray(row) && row.length > 0 && row.length <= 5 && row.every(value => typeof value === 'string' && value.length <= 200)))
152
+ const maxRows = variable.endsWith('Dir') ? 1000 : 100;
153
+ if (!Array.isArray(rows) || rows.length > maxRows || !rows.every((row) => Array.isArray(row) && row.length > 0 && row.length <= 5 && row.every(value => typeof value === 'string' && value.length <= 200)))
152
154
  invalid();
153
155
  return rows;
154
156
  }
157
+ /** The final all-zero row is a portal placeholder, never a company address or giro. */
158
+ function readCompanyOptions(html) {
159
+ const rows = (variable, widths) => readLiteralRows(html, variable)
160
+ .map(row => row.map(value => value.trim()))
161
+ .filter(row => { if (!widths.includes(row.length))
162
+ invalid(); return !row.every(value => value === '0'); })
163
+ .map(row => {
164
+ if (!row[0] || !row[1] || row.some(value => /[\u0000-\u001f\u007f]/u.test(value)))
165
+ invalid();
166
+ return row;
167
+ });
168
+ return {
169
+ addresses: rows('recptorDir', [3, 5]).map(row => ({ address: row[0], commune: row[1] })),
170
+ businessActivities: rows('recptoActEco', [2]).map(row => row[1]),
171
+ };
172
+ }
155
173
  /** Browser legacy form encoding differs from UTF-8 URLSearchParams for accents and € . */
156
174
  function encodePortalForm(fields) {
157
175
  const encode = (value) => {
@@ -204,7 +222,7 @@ function readVisiblePortalText(html) {
204
222
  continue;
205
223
  }
206
224
  if (element(node)) {
207
- if (hiddenTags.has(node.tagName) || attr(node, 'hidden') !== undefined || attr(node, 'aria-hidden')?.toLowerCase() === 'true'
225
+ if (hiddenTags.has(node.tagName) || attr(node, 'hidden') !== undefined || attr(node, 'aria-hidden')?.trim().toLowerCase() === 'true'
208
226
  || /(?:^|;)\s*(?:display\s*:\s*none|(?:content-)?visibility\s*:\s*hidden)\s*(?:!important\s*)?(?:;|$)/i.test(attr(node, 'style') ?? ''))
209
227
  continue;
210
228
  if (blockTags.has(node.tagName)) {
@@ -1,5 +1,6 @@
1
1
  import { type IssuedInvoicesQuery, type IssuedInvoicesResult } from '../domain/issued-invoice';
2
2
  import type { ReceivedInvoicesQuery, ReceivedInvoicesResult } from '../domain/received-invoice';
3
+ import type { RcvDocumentsQuery, RcvDocumentsResult } from '../domain/rcv-document';
3
4
  import type { AuthorizedCompany, SummaryQuery, SiiResponse } from '../contracts';
4
5
  import { SiiHttpSession } from './sii-http-session';
5
6
  export declare class RcvGateway {
@@ -14,4 +15,6 @@ export declare class RcvGateway {
14
15
  summary({ periodo, operacion, estado }: SummaryQuery): Promise<SiiResponse>;
15
16
  issuedInvoices(input: IssuedInvoicesQuery): Promise<IssuedInvoicesResult>;
16
17
  receivedInvoices(input: ReceivedInvoicesQuery): Promise<ReceivedInvoicesResult>;
18
+ issuedDocuments(input: RcvDocumentsQuery): Promise<RcvDocumentsResult>;
19
+ receivedDocuments(input: RcvDocumentsQuery): Promise<RcvDocumentsResult>;
17
20
  }
@@ -8,6 +8,8 @@ const rcv_normalization_1 = require("./rcv-normalization");
8
8
  const sii_http_session_1 = require("./sii-http-session");
9
9
  const NAMESPACE = 'cl.sii.sdi.lob.diii.consdcv.data.api.interfaces.FacadeService/';
10
10
  const STATES = new Set(['REGISTRO', 'PENDIENTE', 'NO_INCLUIR', 'RECLAMADO']);
11
+ const isInvoiceType = (type) => type === 33 || type === 34;
12
+ const isDocumentType = (type) => isInvoiceType(type) || type === 61;
11
13
  class RcvGateway {
12
14
  session;
13
15
  constructor(session) {
@@ -26,13 +28,15 @@ class RcvGateway {
26
28
  const company = this.session.company;
27
29
  return this.#call('getResumen', { rutEmisor: company.rut, dvEmisor: company.dv, ptributario: periodo, estadoContab: estado, operacion });
28
30
  }
29
- issuedInvoices(input) { return this.#invoices('VENTA', input, rcv_normalization_1.normalizeIssuedInvoice); }
30
- receivedInvoices(input) { return this.#invoices('COMPRA', input, rcv_normalization_1.normalizeReceivedInvoice); }
31
- async #invoices(operation, input, normalize) {
31
+ issuedInvoices(input) { return this.#documents('VENTA', input, isInvoiceType, rcv_normalization_1.normalizeIssuedInvoice); }
32
+ receivedInvoices(input) { return this.#documents('COMPRA', input, isInvoiceType, rcv_normalization_1.normalizeReceivedInvoice); }
33
+ issuedDocuments(input) { return this.#documents('VENTA', input, isDocumentType, rcv_normalization_1.normalizeIssuedDocument); }
34
+ receivedDocuments(input) { return this.#documents('COMPRA', input, isDocumentType, rcv_normalization_1.normalizeReceivedDocument); }
35
+ async #documents(operation, input, supported, normalize) {
32
36
  this.session.assertReady();
33
37
  const detailMethod = operation === 'COMPRA' ? 'getDetalleCompra' : 'getDetalleVenta';
34
38
  try {
35
- return await (0, invoice_queries_1.readInvoices)({
39
+ return await (0, invoice_queries_1.readDocuments)({
36
40
  initialLimit: async () => {
37
41
  const initial = await this.#call('getDatosInicio', {});
38
42
  if (typeof initial.limiteDtes !== 'number' || !Number.isSafeInteger(initial.limiteDtes) || initial.limiteDtes < 1)
@@ -45,7 +49,7 @@ class RcvGateway {
45
49
  const type = row.rsmnTipoDocInteger;
46
50
  if (typeof type !== 'number' || !Number.isSafeInteger(type) || type < 1)
47
51
  throw this.session.failure('SII_INVALID_RESPONSE', 'getResumen', 'INVALID_RESPONSE');
48
- if (type !== 33 && type !== 34)
52
+ if (!supported(type))
49
53
  return [];
50
54
  const count = row.rsmnTotDoc;
51
55
  if (typeof count !== 'number' || !Number.isSafeInteger(count) || count < 0)
@@ -1,6 +1,13 @@
1
1
  import type { IssuedInvoice, InvoiceDocumentType } from '../domain/issued-invoice';
2
2
  import type { ReceivedInvoice } from '../domain/received-invoice';
3
+ import type { RcvDocumentType } from '../domain/rcv-document';
3
4
  /** Campos del proveedor validados; emisor y periodo vienen de la consulta autorizada. */
4
5
  export declare function normalizeIssuedInvoice(row: Record<string, unknown>, issuerRut: string, period: string, type: InvoiceDocumentType): IssuedInvoice;
6
+ export declare function normalizeIssuedDocument<D extends RcvDocumentType>(row: Record<string, unknown>, issuerRut: string, period: string, type: D): Omit<IssuedInvoice, 'documentType'> & {
7
+ documentType: D;
8
+ };
5
9
  /** In purchases detRutDoc identifies the supplier; the authorized company is the receiver. */
6
10
  export declare function normalizeReceivedInvoice(row: Record<string, unknown>, receiverRut: string, period: string, type: InvoiceDocumentType): ReceivedInvoice;
11
+ export declare function normalizeReceivedDocument<D extends RcvDocumentType>(row: Record<string, unknown>, receiverRut: string, period: string, type: D): Omit<ReceivedInvoice, 'documentType'> & {
12
+ documentType: D;
13
+ };