@devly-cl/sii-client 0.6.0 → 0.7.1

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 (40) hide show
  1. package/README.md +96 -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 +36 -3
  12. package/dist/domain/invoice-xml.d.ts +34 -1
  13. package/dist/domain/invoicing.d.ts +78 -5
  14. package/dist/domain/invoicing.js +143 -26
  15. package/dist/domain/rcv-document.d.ts +17 -0
  16. package/dist/domain/rcv-document.js +2 -0
  17. package/dist/index.d.ts +7 -4
  18. package/dist/index.js +2 -1
  19. package/dist/infrastructure/document-status-gateway.d.ts +13 -0
  20. package/dist/infrastructure/document-status-gateway.js +127 -0
  21. package/dist/infrastructure/document-status-parser.d.ts +12 -0
  22. package/dist/infrastructure/document-status-parser.js +258 -0
  23. package/dist/infrastructure/dte-xml.js +81 -6
  24. package/dist/infrastructure/facturador-gateway.d.ts +4 -1
  25. package/dist/infrastructure/facturador-gateway.js +113 -15
  26. package/dist/infrastructure/facturador.d.ts +3 -0
  27. package/dist/infrastructure/facturador.js +18 -1
  28. package/dist/infrastructure/rcv-gateway.d.ts +3 -0
  29. package/dist/infrastructure/rcv-gateway.js +9 -5
  30. package/dist/infrastructure/rcv-normalization.d.ts +7 -0
  31. package/dist/infrastructure/rcv-normalization.js +9 -1
  32. package/dist/infrastructure/sii-client.d.ts +10 -1
  33. package/dist/infrastructure/sii-client.js +29 -3
  34. package/dist/infrastructure/sii-http-session.d.ts +5 -1
  35. package/dist/infrastructure/sii-http-session.js +20 -5
  36. package/dist/sii-error.d.ts +3 -3
  37. package/dist/sii-error.js +10 -4
  38. package/package.json +45 -45
  39. package/dist/domain/sii-error.d.ts +0 -27
  40. package/dist/domain/sii-error.js +0 -82
@@ -0,0 +1,258 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DocumentStatusProtocolError = void 0;
4
+ exports.assertDocumentQueryPage = assertDocumentQueryPage;
5
+ exports.parseContentQueryForm = parseContentQueryForm;
6
+ exports.parseDocumentVerification = parseDocumentVerification;
7
+ exports.parseRecipientEvents = parseRecipientEvents;
8
+ const parse5_1 = require("parse5");
9
+ const rut_1 = require("../domain/rut");
10
+ const facturador_1 = require("./facturador");
11
+ const ERROR_CODES = new Set(['SII_PROTOCOL_CHANGED', 'SII_SERVICE_ERROR', 'CAPTCHA_INTERACTION_REQUIRED', 'SESSION_OR_INTERACTIVE_AUTH_REQUIRED', 'SESSION_IDENTITY_MISMATCH']);
12
+ const QUERY_PAGE = 'https://palena.sii.cl/cgi_dte/UPL/DTEauth?6';
13
+ const QUERY_ACTION = 'https://palena.sii.cl/cgi_dte/UPL/QEstadoDTE';
14
+ const QUERY_FIELDS = ['rutQuery', 'dvQuery', 'rutCompany', 'dvCompany', 'rutReceiver', 'dvReceiver', 'tipoDTE', 'folioDTE', 'fechaDTE', 'montoDTE'];
15
+ const EVENT_KINDS = new Map([
16
+ ['ACD', 'CONTENT_ACCEPTANCE'], ['ERM', 'GOODS_RECEIPT'], ['RCD', 'CONTENT_CLAIM'],
17
+ ['RFP', 'PARTIAL_DELIVERY_CLAIM'], ['RFT', 'TOTAL_DELIVERY_CLAIM'], ['PAG', 'CASH_PAYMENT'], ['NCA', 'CREDIT_NOTE_CANCELLATION'],
18
+ ]);
19
+ class DocumentStatusProtocolError extends Error {
20
+ code;
21
+ siiResponseCode;
22
+ constructor(code = 'SII_PROTOCOL_CHANGED', siiResponseCode) {
23
+ const safeCode = ERROR_CODES.has(code) ? code : 'SII_PROTOCOL_CHANGED';
24
+ super(safeCode);
25
+ this.code = safeCode;
26
+ if (Number.isSafeInteger(siiResponseCode))
27
+ this.siiResponseCode = siiResponseCode;
28
+ }
29
+ }
30
+ exports.DocumentStatusProtocolError = DocumentStatusProtocolError;
31
+ function invalid() { throw new DocumentStatusProtocolError(); }
32
+ function inside(node, ancestor) {
33
+ for (let current = node; current; current = 'parentNode' in current ? current.parentNode : null) {
34
+ if (current === ancestor)
35
+ return true;
36
+ }
37
+ return false;
38
+ }
39
+ function visible(node) {
40
+ for (let current = node; current; current = 'parentNode' in current ? current.parentNode : null) {
41
+ if (!(0, facturador_1.element)(current))
42
+ continue;
43
+ if (['head', 'script', 'style', 'template', 'noscript'].includes(current.tagName) || (0, facturador_1.attr)(current, 'hidden') !== undefined
44
+ || (0, facturador_1.attr)(current, 'aria-hidden')?.trim().toLowerCase() === 'true'
45
+ || /(?:^|;)\s*(?:display\s*:\s*none|(?:content-)?visibility\s*:\s*hidden)\s*(?:!important\s*)?(?:;|$)/i.test((0, facturador_1.attr)(current, 'style') ?? ''))
46
+ return false;
47
+ }
48
+ return true;
49
+ }
50
+ function disabled(control) {
51
+ if ((0, facturador_1.attr)(control, 'disabled') !== undefined)
52
+ return true;
53
+ for (let parent = control.parentNode; parent; parent = 'parentNode' in parent ? parent.parentNode : null) {
54
+ if (!(0, facturador_1.element)(parent) || (0, facturador_1.attr)(parent, 'disabled') === undefined)
55
+ continue;
56
+ if (parent.tagName === 'optgroup')
57
+ return true;
58
+ if (parent.tagName === 'fieldset') {
59
+ const legend = parent.childNodes.find(child => (0, facturador_1.element)(child) && child.tagName === 'legend');
60
+ if (!legend || !inside(control, legend))
61
+ return true;
62
+ }
63
+ }
64
+ return false;
65
+ }
66
+ function queryPage(html) {
67
+ if (typeof html !== 'string' || !/^\s*(?:<!--[\s\S]*?-->\s*)*(?:<!doctype\s+html\b[^>]*>\s*)?<[a-z][a-z\d-]*(?:\s|>)/i.test(html) || html.includes('\0'))
68
+ invalid();
69
+ let document;
70
+ try {
71
+ document = (0, facturador_1.parsePortalPage)(html);
72
+ // Observed legacy syntax and late head metadata do not waive field ownership, visibility or attribute checks.
73
+ (0, parse5_1.parse)(html, { onParseError: error => {
74
+ if (!['missing-doctype', 'non-conforming-doctype', 'missing-semicolon-after-character-reference', 'abandoned-head-element-child'].includes(error.code))
75
+ invalid();
76
+ } });
77
+ }
78
+ catch {
79
+ invalid();
80
+ }
81
+ const elements = [...(0, facturador_1.nodes)(document)].filter(facturador_1.element);
82
+ if ((0, facturador_1.hasInteractiveCaptcha)(document) && (/captcha/i.test((0, facturador_1.readVisiblePortalText)(document)) || elements.some(node => visible(node) && ((0, facturador_1.attr)(node, 'class')?.split(/\s+/).includes('g-recaptcha')
83
+ || node.tagName === 'input' && (0, facturador_1.attr)(node, 'type')?.toLowerCase() !== 'hidden' && /captcha/i.test((0, facturador_1.attr)(node, 'name') ?? '')
84
+ || node.tagName === 'iframe' && /\/recaptcha\/(?:api2|enterprise)\/(?:anchor|bframe)(?:[?#/]|$)/i.test((0, facturador_1.attr)(node, 'src') ?? '')))))
85
+ throw new DocumentStatusProtocolError('CAPTCHA_INTERACTION_REQUIRED');
86
+ if (elements.some(node => visible(node) && (node.tagName === 'input' && (0, facturador_1.attr)(node, 'type')?.toLowerCase() === 'password' && !disabled(node)
87
+ || node.tagName === 'form' && (/(?:^|\/)(?:CAutInicio\.cgi|login|signin|auth|autenticacion)(?:[/?#]|$)/i.test((0, facturador_1.attr)(node, 'action') ?? '')
88
+ || ['name', 'id'].some(attribute => /^(?:login|signin|auth|authentication|autenticacion)$/i.test((0, facturador_1.attr)(node, attribute) ?? ''))))))
89
+ throw new DocumentStatusProtocolError('SESSION_OR_INTERACTIVE_AUTH_REQUIRED');
90
+ return document;
91
+ }
92
+ function assertDocumentQueryPage(html) { queryPage(html); }
93
+ function parseContentQueryForm(html, actorRut) {
94
+ const document = queryPage(html);
95
+ const elements = [...(0, facturador_1.nodes)(document)].filter(facturador_1.element);
96
+ const forms = elements.filter(node => {
97
+ if (node.tagName !== 'form')
98
+ return false;
99
+ try {
100
+ return new URL((0, facturador_1.attr)(node, 'action') ?? '', QUERY_PAGE).href === QUERY_ACTION;
101
+ }
102
+ catch {
103
+ return false;
104
+ }
105
+ });
106
+ const form = forms[0];
107
+ if (forms.length !== 1 || !form || (0, facturador_1.attr)(form, 'method')?.toLowerCase() !== 'post')
108
+ invalid();
109
+ const controls = elements.filter(node => QUERY_FIELDS.includes((0, facturador_1.attr)(node, 'name') ?? ''));
110
+ const fields = new URLSearchParams();
111
+ for (const name of QUERY_FIELDS) {
112
+ const matching = controls.filter(control => (0, facturador_1.attr)(control, 'name') === name);
113
+ const control = matching[0];
114
+ if (matching.length !== 1 || !control || !inside(control, form) || disabled(control)
115
+ || (0, facturador_1.attr)(control, 'form') !== undefined && ((0, facturador_1.attr)(control, 'form') !== (0, facturador_1.attr)(form, 'id')
116
+ || elements.filter(node => (0, facturador_1.attr)(node, 'id') === (0, facturador_1.attr)(control, 'form')).length !== 1))
117
+ invalid();
118
+ let value;
119
+ if (name === 'tipoDTE') {
120
+ if (control.tagName !== 'select' || (0, facturador_1.attr)(control, 'multiple') !== undefined)
121
+ invalid();
122
+ const options = [...(0, facturador_1.nodes)(control)].filter(facturador_1.element).filter(node => node.tagName === 'option');
123
+ const selected = options.filter(option => (0, facturador_1.attr)(option, 'selected') !== undefined);
124
+ const available = options.filter(option => !disabled(option));
125
+ const optionValue = (option) => (0, facturador_1.attr)(option, 'value') ?? (0, facturador_1.readVisiblePortalText)(option);
126
+ if (selected.length > 1 || !['33', '34', '61'].every(type => available.some(option => optionValue(option) === type)))
127
+ invalid();
128
+ const option = selected[0] ?? available[0];
129
+ if (!option || disabled(option))
130
+ invalid();
131
+ value = optionValue(option);
132
+ }
133
+ else {
134
+ const type = (0, facturador_1.attr)(control, 'type')?.toLowerCase() ?? 'text';
135
+ if (control.tagName !== 'input' || ['button', 'submit', 'image', 'reset', 'file', 'checkbox', 'radio'].includes(type)
136
+ || ['rutQuery', 'dvQuery'].includes(name) && type !== 'hidden')
137
+ invalid();
138
+ value = (0, facturador_1.attr)(control, 'value') ?? '';
139
+ }
140
+ fields.set(name, value);
141
+ }
142
+ try {
143
+ const actor = (0, rut_1.parseRut)(actorRut);
144
+ const sourceActor = (0, rut_1.parseRut)(`${fields.get('rutQuery')}-${fields.get('dvQuery')}`);
145
+ if (actor.formatted !== sourceActor.formatted)
146
+ throw new DocumentStatusProtocolError('SESSION_IDENTITY_MISMATCH');
147
+ fields.set('rutQuery', actor.rut);
148
+ fields.set('dvQuery', actor.dv);
149
+ }
150
+ catch {
151
+ throw new DocumentStatusProtocolError('SESSION_IDENTITY_MISMATCH');
152
+ }
153
+ return fields;
154
+ }
155
+ function parseDocumentVerification(html) {
156
+ const document = queryPage(html);
157
+ const labelText = 'Resultado de la Consulta:';
158
+ const elements = [...(0, facturador_1.nodes)(document)].filter(facturador_1.element), footers = elements.filter(node => node.tagName === 'footer');
159
+ const labels = elements.filter(node => ['td', 'th'].includes(node.tagName) && visible(node) && !footers.some(footer => inside(node, footer) || inside(footer, node))
160
+ && (0, facturador_1.readVisiblePortalText)(node).startsWith(labelText));
161
+ const label = labels[0], row = label?.parentNode;
162
+ if (labels.length !== 1 || !label || !row || !(0, facturador_1.element)(row) || row.tagName !== 'tr')
163
+ invalid();
164
+ const cells = row.childNodes.filter(facturador_1.element).filter(node => ['td', 'th'].includes(node.tagName));
165
+ const inlineText = (0, facturador_1.readVisiblePortalText)(label).slice(labelText.length).trim();
166
+ if (cells.length !== (inlineText ? 1 : 2))
167
+ invalid();
168
+ const result = inlineText ? label : cells[cells.indexOf(label) + 1];
169
+ if (!result || !visible(result) || footers.some(footer => inside(result, footer) || inside(footer, result)))
170
+ invalid();
171
+ switch (inlineText || (0, facturador_1.readVisiblePortalText)(result)) {
172
+ case 'Documento recibido por el SII. Datos coinciden con los registrados': return { verification: 'RECEIVED_MATCH', cancellation: 'NOT_REPORTED' };
173
+ case 'Documento recibido por el SII. Datos coinciden con los registrados. Existe Nota de Crédito que anula documento': return { verification: 'RECEIVED_MATCH', cancellation: 'REPORTED' };
174
+ case 'Documento recibido por el SII pero datos NO coinciden con los registrados': return { verification: 'RECEIVED_MISMATCH', cancellation: 'UNCONFIRMED' };
175
+ case 'Documento no autorizado': return { verification: 'DOCUMENT_NOT_AUTHORIZED', cancellation: 'UNCONFIRMED' };
176
+ default: return invalid();
177
+ }
178
+ }
179
+ function record(value) {
180
+ if (!value || typeof value !== 'object' || Array.isArray(value))
181
+ invalid();
182
+ const prototype = Object.getPrototypeOf(value);
183
+ if (prototype !== Object.prototype && prototype !== null)
184
+ invalid();
185
+ return value;
186
+ }
187
+ function readRut(rut, dv) {
188
+ if (!(typeof rut === 'string' && /^\d{1,8}$/.test(rut) || typeof rut === 'number' && Number.isSafeInteger(rut) && rut > 0 && rut <= 99999999)
189
+ || !(typeof dv === 'string' && /^[\dkK]$/.test(dv) || typeof dv === 'number' && Number.isInteger(dv) && dv >= 0 && dv <= 9))
190
+ invalid();
191
+ try {
192
+ return (0, rut_1.parseRut)(`${rut}-${dv}`).formatted;
193
+ }
194
+ catch {
195
+ return invalid();
196
+ }
197
+ }
198
+ function localTime(value) {
199
+ if (value == null)
200
+ return null;
201
+ if (typeof value !== 'string')
202
+ invalid();
203
+ const parts = /^(\d{2})-(\d{2})-(\d{4}) (\d{2}):(\d{2}):(\d{2})$/.exec(value);
204
+ if (!parts)
205
+ invalid();
206
+ const [, dayText, monthText, yearText, hourText, minuteText, secondText] = parts;
207
+ const day = Number(dayText), month = Number(monthText), year = Number(yearText);
208
+ const days = [31, year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
209
+ if (year < 1 || month < 1 || month > 12 || day < 1 || day > (days[month - 1] ?? 0)
210
+ || Number(hourText) > 23 || Number(minuteText) > 59 || Number(secondText) > 59)
211
+ invalid();
212
+ return `${yearText}-${monthText}-${dayText}T${hourText}:${minuteText}:${secondText}`;
213
+ }
214
+ function indicator(value) {
215
+ if (value == null)
216
+ return null;
217
+ if (typeof value !== 'boolean')
218
+ invalid();
219
+ return value;
220
+ }
221
+ function recipientEvent(value) {
222
+ const event = record(value);
223
+ const code = event.codEvento, description = event.descEvento;
224
+ if (typeof code !== 'string' || !/^[A-Za-z0-9_]{1,32}$/.test(code) || typeof description !== 'string'
225
+ || description.length > 512 || /[\u0000-\u001f\u007f-\u009f]/u.test(description))
226
+ invalid();
227
+ const responsibleRut = event.rutResponsable == null && event.dvResponsable == null ? null : readRut(event.rutResponsable, event.dvResponsable);
228
+ return { code, kind: EVENT_KINDS.get(code) ?? 'UNKNOWN', description, occurredAtLocal: localTime(event.fechaEvento), responsibleRut };
229
+ }
230
+ function parseRecipientEvents(value) {
231
+ const envelope = record(value), status = record(envelope.respEstado);
232
+ const metadata = envelope.metaData == null ? {} : record(envelope.metaData);
233
+ const code = status.codRespuesta;
234
+ if (typeof code !== 'number' || !Number.isSafeInteger(code))
235
+ invalid();
236
+ const errors = [envelope.errors, status.errors, metadata.errors];
237
+ if (errors.some(error => error != null && !Array.isArray(error)))
238
+ invalid();
239
+ if (code === 98)
240
+ throw new DocumentStatusProtocolError('CAPTCHA_INTERACTION_REQUIRED', code);
241
+ if (code !== 0 || status.codError != null || errors.some(error => Array.isArray(error) && error.length > 0))
242
+ throw new DocumentStatusProtocolError('SII_SERVICE_ERROR', code);
243
+ const source = record(envelope.data);
244
+ const documentType = source.dtdcCodigo, rawFolio = source.dhdrFolio;
245
+ if (documentType !== 33 && documentType !== 34 || typeof source.tieneAccesoEmisor !== 'boolean' || typeof source.tieneAccesoReceptor !== 'boolean')
246
+ invalid();
247
+ if (!(typeof rawFolio === 'string' || typeof rawFolio === 'number' && Number.isSafeInteger(rawFolio)) || !/^[1-9]\d{0,9}$/.test(String(rawFolio)))
248
+ invalid();
249
+ if (!Object.hasOwn(source, 'listEvenHistDoc') || source.listEvenHistDoc !== null && !Array.isArray(source.listEvenHistDoc))
250
+ invalid();
251
+ return {
252
+ document: { issuerRut: readRut(source.dhdrRutEmisor, source.dhdrDvEmisor), receiverRut: readRut(source.dhdrRutRecep, source.dhdrDvRecep), documentType, folio: String(rawFolio) },
253
+ siiReceivedAtLocal: localTime(source.dtecTmstRecep), timeZone: null,
254
+ indicators: { paidInCashReported: indicator(source.pagadoAlContado), claimsReported: indicator(source.tieneReclamos), acknowledgementsReported: indicator(source.tieneAcuses) },
255
+ events: source.listEvenHistDoc === null ? [] : Array.from(source.listEvenHistDoc, recipientEvent),
256
+ accessAsIssuer: source.tieneAccesoEmisor, accessAsReceiver: source.tieneAccesoReceptor,
257
+ };
258
+ }
@@ -17,10 +17,12 @@ function text(node, name, required = false, limit = 1000) {
17
17
  invalid();
18
18
  if (!values.length)
19
19
  return null;
20
- const value = values[0];
21
- if (value.children.length || value.text.length > limit || (required && !value.text.trim()))
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()))
22
24
  invalid();
23
- return value.text.trim() || null;
25
+ return node.text.trim() || null;
24
26
  }
25
27
  function integer(node, name, required = false) {
26
28
  const value = text(node, name, required, 20);
@@ -58,7 +60,7 @@ function parseDteXml(xml, expected) {
58
60
  const documentType = parsed.detail.documentType;
59
61
  if (documentType !== 33 && documentType !== 34)
60
62
  invalid();
61
- const { fiscalHeader: _header, hasSignature: _signature, hasTransport: _transport, ...detail } = parsed.detail;
63
+ const { fiscalHeader: _header, hasSignature: _signature, hasTransport: _transport, issuanceOptions: _options, ...detail } = parsed.detail;
62
64
  return { ...parsed, detail: { ...detail, documentType } };
63
65
  }
64
66
  /** Issued invoices and credit notes; preserves original bytes and validates fiscal references. */
@@ -115,6 +117,9 @@ function parseDocumentXml(xml, expected, allowCreditNotes) {
115
117
  const totals = one(headerNode, 'Totales');
116
118
  const issuer = one(headerNode, 'Emisor'), receiver = one(headerNode, 'Receptor');
117
119
  const documentType = integer(identity, 'TipoDTE', true);
120
+ const grossAmounts = integer(identity, 'MntBruto');
121
+ if (grossAmounts !== null && grossAmounts !== 1)
122
+ invalid();
118
123
  const folio = text(identity, 'Folio', true, 20);
119
124
  let issuerRut, receiverRut;
120
125
  try {
@@ -156,18 +161,88 @@ function parseDocumentXml(xml, expected, allowCreditNotes) {
156
161
  const signatures = dtes[0].children.filter(node => node.name === 'Signature' && node.uri === 'http://www.w3.org/2000/09/xmldsig#');
157
162
  if (allowCreditNotes && signatures.length > 1)
158
163
  invalid();
164
+ const options = allowCreditNotes ? issuanceOptions(headerNode, identity, issuer, document) : undefined;
165
+ const issuerActivities = allowCreditNotes ? children(issuer, 'Acteco').map(node => nodeText(node)) : [];
159
166
  return { xml: new Uint8Array(xml), encoding, detail: {
167
+ ...(grossAmounts === 1 ? { grossAmounts: true } : {}),
160
168
  issuerRut, documentType: expected.documentType, folio, issuedDate: date(identity, 'FchEmis'), receiverRut,
161
169
  hasSignature: signatures.length === 1,
162
170
  hasTransport: children(headerNode, 'Transporte').some(node => node.children.length > 0 || node.text.trim().length > 0 || node.attributeCount > 0),
171
+ ...(options ? { issuanceOptions: options } : {}),
163
172
  ...(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') },
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') },
165
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') },
166
175
  paymentForm: integer(identity, 'FmaPago'), saleType: integer(identity, 'TpoTranVenta'), purchaseType: integer(identity, 'TpoTranCompra'),
167
176
  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),
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'] : [])],
169
178
  } } : {}),
170
179
  netAmount: integer(totals, 'MntNeto'), exemptAmount: integer(totals, 'MntExe'), vatRate: decimal(totals, 'TasaIVA'), vatAmount: integer(totals, 'IVA'), totalAmount: integer(totals, 'MntTotal', true), lines,
171
180
  taxes: children(totals, 'ImptoReten').map(node => ({ type: integer(node, 'TipoImp', true), rate: decimal(node, 'TasaImp'), amount: integer(node, 'MontoImp', true) })), adjustments, references,
172
181
  } };
173
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;
199
+ }
200
+ catch {
201
+ 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
+ }
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;
248
+ }
@@ -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,4 +1,5 @@
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;
@@ -7,6 +8,8 @@ export declare function parsePortalPage(html: string): Html.Document;
7
8
  export declare function readForm(html: string | Html.Document, name: string, endpoint: string): URLSearchParams;
8
9
  /** Decode only the observed small JSON array declarations, 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;