@devly-cl/sii-client 0.7.1 → 0.7.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +84 -1
  2. package/dist/application/document-status.d.ts +5 -5
  3. package/dist/application/document-status.js +14 -9
  4. package/dist/application/dte-import-mapper.d.ts +8 -0
  5. package/dist/application/dte-import-mapper.js +25 -0
  6. package/dist/application/dte-import-model.d.ts +28 -0
  7. package/dist/application/dte-import-model.js +2 -0
  8. package/dist/application/dte-import.d.ts +37 -0
  9. package/dist/application/dte-import.js +352 -0
  10. package/dist/application/invoice-queries.d.ts +12 -6
  11. package/dist/application/invoice-queries.js +9 -5
  12. package/dist/application/issuance.d.ts +2 -2
  13. package/dist/application/issuance.js +26 -10
  14. package/dist/contracts.d.ts +32 -0
  15. package/dist/contracts.js +17 -0
  16. package/dist/domain/civil-date.d.ts +2 -0
  17. package/dist/domain/civil-date.js +10 -0
  18. package/dist/domain/document-status.d.ts +0 -4
  19. package/dist/domain/document-status.js +18 -11
  20. package/dist/domain/document.js +49 -9
  21. package/dist/domain/dte-arithmetic.d.ts +35 -0
  22. package/dist/domain/dte-arithmetic.js +78 -0
  23. package/dist/domain/dte-components.d.ts +9 -0
  24. package/dist/domain/dte-components.js +37 -0
  25. package/dist/domain/dte-detail.d.ts +111 -0
  26. package/dist/domain/dte-detail.js +2 -0
  27. package/dist/domain/dte-identity.d.ts +19 -0
  28. package/dist/domain/dte-identity.js +52 -0
  29. package/dist/domain/dte-money.d.ts +41 -0
  30. package/dist/domain/dte-money.js +81 -0
  31. package/dist/domain/dte-reconciliation-model.d.ts +87 -0
  32. package/dist/domain/dte-reconciliation-model.js +2 -0
  33. package/dist/domain/dte-reconciliation.d.ts +15 -0
  34. package/dist/domain/dte-reconciliation.js +390 -0
  35. package/dist/domain/dte-validation.d.ts +7 -0
  36. package/dist/domain/dte-validation.js +84 -0
  37. package/dist/domain/invoice-xml.d.ts +17 -57
  38. package/dist/domain/invoice-xml.js +0 -10
  39. package/dist/domain/invoicing.d.ts +30 -4
  40. package/dist/domain/invoicing.js +75 -21
  41. package/dist/domain/issued-invoice.d.ts +0 -6
  42. package/dist/domain/rcv-document.d.ts +0 -4
  43. package/dist/domain/received-invoice.d.ts +1 -4
  44. package/dist/index.d.ts +19 -9
  45. package/dist/index.js +20 -4
  46. package/dist/infrastructure/document-status-gateway.d.ts +6 -4
  47. package/dist/infrastructure/document-status-gateway.js +34 -13
  48. package/dist/infrastructure/document-status-parser.js +38 -12
  49. package/dist/infrastructure/dte-xml-mapper.d.ts +16 -0
  50. package/dist/infrastructure/dte-xml-mapper.js +381 -0
  51. package/dist/infrastructure/dte-xml.d.ts +40 -4
  52. package/dist/infrastructure/dte-xml.js +117 -196
  53. package/dist/infrastructure/facturador-gateway.d.ts +10 -7
  54. package/dist/infrastructure/facturador-gateway.js +256 -56
  55. package/dist/infrastructure/facturador.d.ts +1 -1
  56. package/dist/infrastructure/facturador.js +18 -10
  57. package/dist/infrastructure/invoice-pdf.js +10 -3
  58. package/dist/infrastructure/rcv-gateway.d.ts +7 -4
  59. package/dist/infrastructure/rcv-gateway.js +53 -12
  60. package/dist/infrastructure/rcv-normalization.d.ts +8 -1
  61. package/dist/infrastructure/rcv-normalization.js +54 -12
  62. package/dist/infrastructure/read-options.d.ts +3 -0
  63. package/dist/infrastructure/read-options.js +25 -0
  64. package/dist/infrastructure/sii-client.d.ts +98 -13
  65. package/dist/infrastructure/sii-client.js +182 -31
  66. package/dist/infrastructure/sii-http-session.d.ts +2 -2
  67. package/dist/infrastructure/sii-http-session.js +134 -37
  68. package/dist/sii-error.d.ts +5 -0
  69. package/dist/sii-error.js +39 -13
  70. package/package.json +2 -2
@@ -2,84 +2,101 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.parseDteXml = parseDteXml;
4
4
  exports.parseDteDocumentXml = parseDteDocumentXml;
5
+ exports.parseDteDocumentXmlExact = parseDteDocumentXmlExact;
6
+ exports.parseDteDocumentXmlForIssuance = parseDteDocumentXmlForIssuance;
7
+ const contracts_1 = require("../contracts");
8
+ const dte_xml_mapper_1 = require("./dte-xml-mapper");
5
9
  const saxes_1 = require("saxes");
6
- const rut_1 = require("../domain/rut");
7
- const invoice_xml_1 = require("../domain/invoice-xml");
8
- function invalid() { throw new invoice_xml_1.DteXmlError('SII_XML_INVALID'); }
9
- const children = (node, name) => node.children.filter(n => n.name === name && n.uri === node.uri);
10
- function one(node, name) {
11
- const values = children(node, name);
12
- return values.length === 1 ? values[0] : invalid();
10
+ const dte_reconciliation_1 = require("../domain/dte-reconciliation");
11
+ const dte_identity_1 = require("../domain/dte-identity");
12
+ const dte_money_1 = require("../domain/dte-money");
13
+ const read_options_1 = require("./read-options");
14
+ function invalid() {
15
+ throw new contracts_1.DteXmlError('SII_XML_INVALID');
13
16
  }
14
- function text(node, name, required = false, limit = 1000) {
15
- const values = children(node, name);
16
- if (values.length > 1 || (required && values.length !== 1))
17
- invalid();
18
- if (!values.length)
19
- return null;
20
- return nodeText(values[0], required, limit);
21
- }
22
- function nodeText(node, required = false, limit = 1000) {
23
- if (node.children.length || node.text.length > limit || (required && !node.text.trim()))
24
- invalid();
25
- return node.text.trim() || null;
26
- }
27
- function integer(node, name, required = false) {
28
- const value = text(node, name, required, 20);
29
- if (value === null)
30
- return null;
31
- const number = Number(value);
32
- if (!/^\d+$/.test(value) || !Number.isSafeInteger(number))
33
- invalid();
34
- return number;
35
- }
36
- function decimal(node, name, required = false) {
37
- const value = text(node, name, required, 40);
38
- if (value !== null && !/^\d+(?:\.\d+)?$/.test(value))
39
- invalid();
40
- return value;
41
- }
42
- function date(node, name) {
43
- const value = text(node, name, true, 10);
44
- const parsed = new Date(`${value}T00:00:00Z`);
45
- if (!/^\d{4}-\d{2}-\d{2}$/.test(value) || !Number.isFinite(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== value)
46
- invalid();
47
- return value;
48
- }
49
- function lineNumber(node, name) {
50
- const value = integer(node, name, true);
51
- return value > 0 ? value : invalid();
52
- }
53
- function uniqueLines(items) {
54
- if (new Set(items.map(item => item.lineNumber)).size !== items.length)
55
- invalid();
56
- }
57
- /** Bounded, namespace-aware parsing; no DTD, external entities or network I/O. */
58
- function parseDteXml(xml, expected) {
59
- const parsed = parseDocumentXml(xml, expected, false);
17
+ /**
18
+ * Lee un XML de factura 33/34 y conserva el contrato histórico de detalle numérico.
19
+ * El parser es acotado, reconoce namespaces y rechaza DTD y entidades externas, sin I/O de red.
20
+ * @param xml Bytes originales UTF-8 o ISO-8859-1; máximo MAX_DTE_XML_BYTES.
21
+ * @param expected Identidad esperada; siempre comprueba emisor, tipo, folio y receptor cuando se indica.
22
+ * @param options Por defecto incluye conciliación. reconcile=false devuelve sólo los hechos declarados.
23
+ * @returns Bytes originales, codificación y detalle; no modifica los importes de fuente.
24
+ * @throws DteXmlError por XML no representable o identidad distinta; TypeError por opciones inválidas.
25
+ * @remarks No valida criptográficamente firmas ni autoriza acceso al documento.
26
+ */
27
+ function parseDteXml(xml, expected, options) {
28
+ const parsed = parseDocumentXml(xml, expected, false, false, options);
60
29
  const documentType = parsed.detail.documentType;
61
30
  if (documentType !== 33 && documentType !== 34)
62
31
  invalid();
63
32
  const { fiscalHeader: _header, hasSignature: _signature, hasTransport: _transport, issuanceOptions: _options, ...detail } = parsed.detail;
64
33
  return { ...parsed, detail: { ...detail, documentType } };
65
34
  }
66
- /** Issued invoices and credit notes; preserves original bytes and validates fiscal references. */
67
- function parseDteDocumentXml(xml, expected) {
35
+ /**
36
+ * Lee facturas 33/34 y notas de crédito 61, emitidas o recibidas, con importes numéricos seguros.
37
+ * Incluye encabezado fiscal y presencia de firma/transporte; los bytes y valores declarados se conservan.
38
+ * @param expected Identidad esperada; incluya receiverRut para comprobar también el receptor.
39
+ * @param options reconcile=false omite conciliación y requisitos de interpretación de referencias fiscales.
40
+ * Los controles de identidad, estructura, precisión y límites siempre se ejecutan.
41
+ * @throws DteXmlError por XML/identidad inválidos; TypeError por opciones inválidas.
42
+ * @see parseDteXml
43
+ */
44
+ function parseDteDocumentXml(xml, expected, options) {
45
+ if (!expected || ![33, 34, 61].includes(expected.documentType))
46
+ invalid();
47
+ return parseDocumentXml(xml, expected, true, false, options);
48
+ }
49
+ /**
50
+ * Lee DTE 33/34/61 con importes monetarios enteros como strings, hasta 18 dígitos de fuente.
51
+ * Precios, cantidades y porcentajes conservan su representación decimal original.
52
+ * @param options Por defecto intenta conciliar si los importes caben en Number; reconcile=false omite ese paso.
53
+ * @returns XML original y detalle exacto. La ausencia de reconciliation no acredita validez fiscal.
54
+ * @throws DteXmlError por XML/identidad inválidos; TypeError por opciones inválidas.
55
+ * @see parseDteDocumentXml
56
+ */
57
+ function parseDteDocumentXmlExact(xml, expected, options) {
68
58
  if (!expected || ![33, 34, 61].includes(expected.documentType))
69
59
  invalid();
70
- return parseDocumentXml(xml, expected, true);
60
+ return parseDocumentXml(xml, expected, true, true, options);
71
61
  }
72
- function parseDocumentXml(xml, expected, allowCreditNotes) {
73
- if (!(xml instanceof Uint8Array) || !xml.byteLength || xml.byteLength > invoice_xml_1.MAX_DTE_XML_BYTES)
62
+ /** Issuance accepts one physical DTE, even when additional copies are identical. */
63
+ function parseDteDocumentXmlForIssuance(xml, expected) {
64
+ return parseDocumentXml(xml, expected, true, false, undefined, false);
65
+ }
66
+ function uniqueDteRoot(root, spans, source) {
67
+ const sets = root.name === 'SetDTE' ? [root] : root.name === 'EnvioDTE' ? root.children.filter(node => node.name === 'SetDTE' && node.uri === root.uri) : [];
68
+ if (sets.length !== 1)
69
+ return root;
70
+ const set = sets[0];
71
+ const documents = set.children.filter(node => node.name === 'DTE');
72
+ if (documents.length < 2)
73
+ return root;
74
+ if (!['', 'http://www.sii.cl/SiiDte'].includes(root.uri) || documents.length !== spans.size || documents.some(node => !['', 'http://www.sii.cl/SiiDte'].includes(node.uri)))
75
+ invalid();
76
+ const first = documents[0], firstSpan = spans.get(first);
77
+ const original = source.slice(firstSpan.start, firstSpan.end);
78
+ for (const document of documents.slice(1)) {
79
+ const span = spans.get(document);
80
+ if (source.slice(span.start, span.end) !== original)
81
+ invalid();
82
+ }
83
+ return first;
84
+ }
85
+ function parseDocumentXml(xml, expected, allowCreditNotes, exact = false, options, allowIdenticalDuplicates = true) {
86
+ (0, read_options_1.assertDteXmlReadOptions)(options);
87
+ const reconcile = options?.reconcile !== false;
88
+ if (!(xml instanceof Uint8Array) || !xml.byteLength || xml.byteLength > contracts_1.MAX_DTE_XML_BYTES)
74
89
  invalid();
75
90
  let root;
91
+ let source = '';
92
+ const spans = new Map();
76
93
  const stack = [];
77
94
  let nodes = 0;
78
95
  const header = Buffer.from(xml.subarray(0, 200)).toString('latin1');
79
96
  const declared = /<\?xml\b[^?]*\bencoding\s*=\s*['"]([^'"]+)['"]/i.exec(header)?.[1]?.toUpperCase() ?? 'UTF-8';
80
97
  const encoding = declared === 'UTF-8' || declared === 'UTF8' ? 'UTF-8' : declared === 'ISO-8859-1' ? 'ISO-8859-1' : invalid();
81
98
  try {
82
- const source = encoding === 'ISO-8859-1' ? Buffer.from(xml).toString('latin1') : new TextDecoder('utf-8', { fatal: true }).decode(xml);
99
+ source = encoding === 'ISO-8859-1' ? Buffer.from(xml).toString('latin1') : new TextDecoder('utf-8', { fatal: true }).decode(xml);
83
100
  const parser = new saxes_1.SaxesParser({ xmlns: true });
84
101
  parser.on('error', invalid);
85
102
  parser.on('doctype', invalid);
@@ -87,7 +104,15 @@ function parseDocumentXml(xml, expected, allowCreditNotes) {
87
104
  parser.on('opentag', tag => {
88
105
  if (++nodes > 10000 || stack.length >= 32)
89
106
  invalid();
90
- const node = { name: tag.local, uri: tag.uri, text: '', attributeCount: Object.values(tag.attributes).filter(attribute => attribute.uri !== 'http://www.w3.org/2000/xmlns/').length, children: [] };
107
+ const node = {
108
+ name: tag.local,
109
+ uri: tag.uri,
110
+ text: '',
111
+ attributeCount: Object.values(tag.attributes).filter(attribute => attribute.uri !== 'http://www.w3.org/2000/xmlns/').length,
112
+ children: []
113
+ };
114
+ if (node.name === 'DTE')
115
+ spans.set(node, { start: source.lastIndexOf('<', parser.position - 1), end: 0 });
91
116
  if (stack.length)
92
117
  stack[stack.length - 1].children.push(node);
93
118
  else if (root)
@@ -96,153 +121,49 @@ function parseDocumentXml(xml, expected, allowCreditNotes) {
96
121
  root = node;
97
122
  stack.push(node);
98
123
  });
99
- const append = (value) => { if (stack.length)
100
- stack[stack.length - 1].text += value; };
124
+ const append = (value) => {
125
+ if (stack.length)
126
+ stack[stack.length - 1].text += value;
127
+ };
101
128
  parser.on('text', append);
102
129
  parser.on('cdata', append);
103
- parser.on('closetag', () => { stack.pop(); });
130
+ parser.on('closetag', () => {
131
+ const node = stack.pop();
132
+ const span = node && spans.get(node);
133
+ if (span)
134
+ span.end = parser.position;
135
+ });
104
136
  parser.write(source).close();
105
137
  }
106
138
  catch {
107
139
  invalid();
108
140
  }
109
- if (!root || !['', 'http://www.sii.cl/SiiDte'].includes(root.uri))
110
- invalid();
111
- const dtes = root.name === 'DTE' ? [root] : root.name === 'SetDTE' ? children(root, 'DTE') : root.name === 'EnvioDTE' ? children(one(root, 'SetDTE'), 'DTE') : [];
112
- if (dtes.length !== 1)
141
+ if (!root)
113
142
  invalid();
114
- const document = one(dtes[0], 'Documento');
115
- const headerNode = one(document, 'Encabezado');
116
- const identity = one(headerNode, 'IdDoc');
117
- const totals = one(headerNode, 'Totales');
118
- const issuer = one(headerNode, 'Emisor'), receiver = one(headerNode, 'Receptor');
119
- const documentType = integer(identity, 'TipoDTE', true);
120
- const grossAmounts = integer(identity, 'MntBruto');
121
- if (grossAmounts !== null && grossAmounts !== 1)
143
+ if (!allowIdenticalDuplicates && spans.size !== 1)
122
144
  invalid();
123
- const folio = text(identity, 'Folio', true, 20);
124
- let issuerRut, receiverRut;
125
- try {
126
- issuerRut = (0, rut_1.parseRut)(text(issuer, 'RUTEmisor', true, 12)).formatted;
127
- receiverRut = (0, rut_1.parseRut)(text(receiver, 'RUTRecep', true, 12)).formatted;
128
- }
129
- catch {
130
- return invalid();
131
- }
132
- if ((documentType !== 33 && documentType !== 34 && (!allowCreditNotes || documentType !== 61)) || !/^[1-9]\d{0,19}$/.test(folio))
133
- invalid();
134
- 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))
135
- throw new invoice_xml_1.DteXmlError('SII_XML_IDENTITY_MISMATCH');
136
- const lines = children(document, 'Detalle').map(line => ({
137
- lineNumber: lineNumber(line, 'NroLinDet'), name: text(line, 'NmbItem', true, 80), description: text(line, 'DscItem'),
138
- codes: children(line, 'CdgItem').map(code => ({ type: text(code, 'TpoCodigo', true, 10), value: text(code, 'VlrCodigo', true, 35) })),
139
- quantity: decimal(line, 'QtyItem'), unit: text(line, 'UnmdItem', false, 4), unitPrice: decimal(line, 'PrcItem'),
140
- discountPercent: decimal(line, 'DescuentoPct'), discountAmount: integer(line, 'DescuentoMonto'),
141
- surchargePercent: decimal(line, 'RecargoPct'), surchargeAmount: integer(line, 'RecargoMonto'), exemptIndicator: integer(line, 'IndExe'), amount: integer(line, 'MontoItem', true),
142
- }));
143
- if (!lines.length || lines.length > 1000)
144
- invalid();
145
- const adjustments = children(document, 'DscRcgGlobal').map(node => {
146
- const movement = text(node, 'TpoMov', true), valueType = text(node, 'TpoValor', true);
147
- if ((movement !== 'D' && movement !== 'R') || (valueType !== '%' && valueType !== '$'))
145
+ const { detail, normalization } = (0, dte_xml_mapper_1.mapDteXmlDetail)(allowIdenticalDuplicates ? uniqueDteRoot(root, spans, source) : root, expected, allowCreditNotes);
146
+ if (reconcile && detail.documentType === 61) {
147
+ const references = detail.references.filter(reference => /^\d{1,3}$/.test(reference.documentType) && Number(reference.documentType) > 0 && Number(reference.documentType) < 200);
148
+ if (!references.length || references.some(reference => !(0, dte_identity_1.validDteCreditReference)(reference))
149
+ || references.some(reference => reference.code === 1 || reference.code === 2) && references.length !== 1)
148
150
  invalid();
149
- return { lineNumber: lineNumber(node, 'NroLinDR'), movement: movement, description: text(node, 'GlosaDR'), valueType: valueType, value: decimal(node, 'ValorDR', true), exemptIndicator: integer(node, 'IndExeDR') };
150
- });
151
- const references = children(document, 'Referencia').map(node => ({
152
- 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),
153
- }));
154
- uniqueLines(lines);
155
- uniqueLines(adjustments);
156
- uniqueLines(references);
157
- if (documentType === 61 && (!references.length
158
- || references.some(reference => reference.code === null || ![1, 2, 3].includes(reference.code))
159
- || (references.some(reference => reference.code === 1 || reference.code === 2) && references.length !== 1)))
160
- invalid();
161
- const signatures = dtes[0].children.filter(node => node.name === 'Signature' && node.uri === 'http://www.w3.org/2000/09/xmldsig#');
162
- if (allowCreditNotes && signatures.length > 1)
163
- invalid();
164
- const options = allowCreditNotes ? issuanceOptions(headerNode, identity, issuer, document) : undefined;
165
- const issuerActivities = allowCreditNotes ? children(issuer, 'Acteco').map(node => nodeText(node)) : [];
166
- return { xml: new Uint8Array(xml), encoding, detail: {
167
- ...(grossAmounts === 1 ? { grossAmounts: true } : {}),
168
- issuerRut, documentType: expected.documentType, folio, issuedDate: date(identity, 'FchEmis'), receiverRut,
169
- hasSignature: signatures.length === 1,
170
- hasTransport: children(headerNode, 'Transporte').some(node => node.children.length > 0 || node.text.trim().length > 0 || node.attributeCount > 0),
171
- ...(options ? { issuanceOptions: options } : {}),
172
- ...(allowCreditNotes ? { fiscalHeader: {
173
- 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') },
174
- 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') },
175
- paymentForm: integer(identity, 'FmaPago'), saleType: integer(identity, 'TpoTranVenta'), purchaseType: integer(identity, 'TpoTranCompra'),
176
- noDebitReduction: integer(identity, 'IndNoRebaja', children(identity, 'IndNoRebaja').length > 0),
177
- 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'] : [])],
178
- } } : {}),
179
- netAmount: integer(totals, 'MntNeto'), exemptAmount: integer(totals, 'MntExe'), vatRate: decimal(totals, 'TasaIVA'), vatAmount: integer(totals, 'IVA'), totalAmount: integer(totals, 'MntTotal', true), lines,
180
- taxes: children(totals, 'ImptoReten').map(node => ({ type: integer(node, 'TipoImp', true), rate: decimal(node, 'TasaImp'), amount: integer(node, 'MontoImp', true) })), adjustments, references,
181
- } };
182
- }
183
- function issuanceOptions(header, identity, issuer, document) {
184
- const unsupported = [];
185
- const inspect = (node, allowed, path) => {
186
- if (node.attributeCount || node.text.trim())
187
- unsupported.push(path);
188
- for (const child of node.children) {
189
- if (child.uri !== node.uri || !allowed.includes(child.name) || child.attributeCount)
190
- unsupported.push(`${path}/${child.name}`);
191
- }
192
- };
193
- const optionalRut = (node, name) => {
194
- const value = text(node, name, false, 15);
195
- if (value === null)
196
- return null;
197
- try {
198
- return (0, rut_1.parseRut)(value).formatted;
151
+ }
152
+ if (exact && !reconcile)
153
+ return { xml: new Uint8Array(xml), encoding, detail };
154
+ try {
155
+ const numeric = (0, dte_money_1.withNumberDteAmounts)(detail);
156
+ if (reconcile) {
157
+ numeric.reconciliation = (0, dte_reconciliation_1.reconcileDteDetail)(numeric);
158
+ numeric.reconciliation.diagnostics.unshift(...normalization);
159
+ detail.reconciliation = (0, dte_money_1.withExactDteAmounts)(numeric.reconciliation);
199
160
  }
200
- catch {
161
+ if (!exact)
162
+ return { xml: new Uint8Array(xml), encoding, detail: numeric };
163
+ }
164
+ catch (error) {
165
+ if (!exact || !(error instanceof dte_money_1.DteMoneyRangeError))
201
166
  return invalid();
202
- }
203
- };
204
- const transports = children(header, 'Transporte');
205
- if (transports.length > 1)
206
- invalid();
207
- const transportNode = transports[0];
208
- let transport = null;
209
- if (transportNode) {
210
- inspect(transportNode, ['Patente', 'RUTTrans', 'Chofer'], 'Transporte');
211
- const drivers = children(transportNode, 'Chofer');
212
- if (drivers.length > 1)
213
- invalid();
214
- const driver = drivers[0];
215
- if (driver)
216
- inspect(driver, ['RUTChofer', 'NombreChofer'], 'Transporte/Chofer');
217
- 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 };
218
- if (Object.values(value).some(part => part !== null))
219
- transport = value;
220
167
  }
221
- const payments = children(identity, 'MntPagos').map(node => {
222
- inspect(node, ['FchPago', 'MntPago', 'GlosaPagos'], 'IdDoc/MntPagos');
223
- return { date: date(node, 'FchPago'), amount: integer(node, 'MntPago', true), description: text(node, 'GlosaPagos', false, 40) };
224
- });
225
- const lineTaxCodes = children(document, 'Detalle').flatMap(line => {
226
- const codes = children(line, 'CodImpAdic').map(node => {
227
- if (node.children.length || node.attributeCount)
228
- unsupported.push('Detalle/CodImpAdic');
229
- const value = node.text.trim();
230
- if (!/^\d{1,6}$/.test(value))
231
- invalid();
232
- return Number(value);
233
- });
234
- return codes.length ? [{ lineNumber: lineNumber(line, 'NroLinDet'), codes }] : [];
235
- });
236
- const referenceGlobalIndicators = children(document, 'Referencia').flatMap(ref => {
237
- const indicator = integer(ref, 'IndGlobal');
238
- return indicator === null ? [] : [{ lineNumber: lineNumber(ref, 'NroLinRef'), indicator }];
239
- });
240
- const issuerPhones = children(issuer, 'Telefono').map(node => {
241
- if (node.children.length || node.text.length > 20 || !node.text.trim())
242
- invalid();
243
- return node.text.trim();
244
- });
245
- const issuerEmail = text(issuer, 'CorreoEmisor', false, 80), requesterRut = optionalRut(header, 'RUTSolicita');
246
- const result = { issuerEmail, issuerPhones, requesterRut, transport, payments, lineTaxCodes, referenceGlobalIndicators, unapprovedFields: unsupported };
247
- return issuerEmail !== null || issuerPhones.length || requesterRut !== null || transport !== null || payments.length || lineTaxCodes.length || referenceGlobalIndicators.length || unsupported.length ? result : undefined;
168
+ return { xml: new Uint8Array(xml), encoding, detail };
248
169
  }
@@ -1,9 +1,10 @@
1
+ import type { DteXmlReadOptions, InvoicePdfResult, IssuedInvoicePdfQuery, PdfDownloadOptions, ReceivedInvoicePdfQuery } from '../contracts';
1
2
  import type { CompanyInfo } from '../domain/company-info';
2
3
  import { type InvoiceInput } from '../domain/invoicing';
3
- import { type PreparedDocument, type DocumentContent, type SignedDocument } from '../domain/document';
4
- import { type IssuedInvoiceXmlQuery, type ReceivedInvoiceXmlQuery, type InvoiceXmlResult, type IssuedDocumentXmlQuery, type ReceivedDocumentXmlQuery, type IssuedDocumentXmlResult } from '../domain/invoice-xml';
4
+ import { type DocumentContent, type PreparedDocument, type SignedDocument } from '../domain/document';
5
+ import type { ExactDteDocumentXmlResult } from '../domain/invoice-xml';
6
+ import { type InvoiceXmlResult, type IssuedDocumentXmlQuery, type IssuedDocumentXmlResult, type IssuedInvoiceXmlQuery, type ReceivedDocumentXmlQuery, type ReceivedInvoiceXmlQuery } from '../domain/invoice-xml';
5
7
  import type { InvoicingPort } from '../application/issuance';
6
- import type { IssuedInvoicePdfQuery, ReceivedInvoicePdfQuery, PdfDownloadOptions, InvoicePdfResult } from '../contracts';
7
8
  import { SiiHttpSession } from './sii-http-session';
8
9
  export declare class FacturadorGateway implements InvoicingPort {
9
10
  #private;
@@ -22,10 +23,12 @@ export declare class FacturadorGateway implements InvoicingPort {
22
23
  unsignedDocument(approved: PreparedDocument): Promise<IssuedDocumentXmlResult>;
23
24
  signDocument(approved: PreparedDocument, password: string): Promise<SignedDocument>;
24
25
  sendDocument(document: SignedDocument, password: string): Promise<void>;
25
- issuedInvoiceXml(input: IssuedInvoiceXmlQuery): Promise<InvoiceXmlResult>;
26
- receivedInvoiceXml(input: ReceivedInvoiceXmlQuery): Promise<InvoiceXmlResult>;
27
- issuedDocumentXml(input: IssuedDocumentXmlQuery): Promise<IssuedDocumentXmlResult>;
28
- receivedDocumentXml(input: ReceivedDocumentXmlQuery): Promise<IssuedDocumentXmlResult>;
26
+ issuedInvoiceXml(input: IssuedInvoiceXmlQuery, options?: DteXmlReadOptions): Promise<InvoiceXmlResult>;
27
+ receivedInvoiceXml(input: ReceivedInvoiceXmlQuery, options?: DteXmlReadOptions): Promise<InvoiceXmlResult>;
28
+ issuedDocumentXml(input: IssuedDocumentXmlQuery, options?: DteXmlReadOptions): Promise<IssuedDocumentXmlResult>;
29
+ receivedDocumentXml(input: ReceivedDocumentXmlQuery, options?: DteXmlReadOptions): Promise<IssuedDocumentXmlResult>;
30
+ issuedDocumentXmlExact(input: IssuedDocumentXmlQuery, options?: DteXmlReadOptions): Promise<ExactDteDocumentXmlResult>;
31
+ receivedDocumentXmlExact(input: ReceivedDocumentXmlQuery, options?: DteXmlReadOptions): Promise<ExactDteDocumentXmlResult>;
29
32
  issuedInvoicePdf(input: IssuedInvoicePdfQuery, options?: PdfDownloadOptions): Promise<InvoicePdfResult>;
30
33
  receivedInvoicePdf(input: ReceivedInvoicePdfQuery, options?: PdfDownloadOptions): Promise<InvoicePdfResult>;
31
34
  }