@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.
- package/README.md +113 -251
- package/dist/application/document-status.d.ts +13 -0
- package/dist/application/document-status.js +50 -0
- package/dist/application/invoice-queries.d.ts +11 -5
- package/dist/application/invoice-queries.js +13 -9
- package/dist/domain/company-info.d.ts +13 -0
- package/dist/domain/company-info.js +2 -0
- package/dist/domain/document-status.d.ts +93 -0
- package/dist/domain/document-status.js +69 -0
- package/dist/domain/document.d.ts +4 -0
- package/dist/domain/document.js +38 -3
- package/dist/domain/dte-reconciliation.d.ts +5 -0
- package/dist/domain/dte-reconciliation.js +351 -0
- package/dist/domain/invoice-xml.d.ts +133 -1
- package/dist/domain/invoicing.d.ts +78 -5
- package/dist/domain/invoicing.js +143 -26
- package/dist/domain/rcv-document.d.ts +17 -0
- package/dist/domain/rcv-document.js +2 -0
- package/dist/index.d.ts +9 -4
- package/dist/index.js +5 -1
- package/dist/infrastructure/document-status-gateway.d.ts +13 -0
- package/dist/infrastructure/document-status-gateway.js +127 -0
- package/dist/infrastructure/document-status-parser.d.ts +12 -0
- package/dist/infrastructure/document-status-parser.js +258 -0
- package/dist/infrastructure/dte-xml.js +148 -30
- package/dist/infrastructure/facturador-gateway.d.ts +4 -1
- package/dist/infrastructure/facturador-gateway.js +113 -15
- package/dist/infrastructure/facturador.d.ts +4 -1
- package/dist/infrastructure/facturador.js +22 -4
- package/dist/infrastructure/rcv-gateway.d.ts +3 -0
- package/dist/infrastructure/rcv-gateway.js +9 -5
- package/dist/infrastructure/rcv-normalization.d.ts +7 -0
- package/dist/infrastructure/rcv-normalization.js +9 -1
- package/dist/infrastructure/sii-client.d.ts +10 -1
- package/dist/infrastructure/sii-client.js +29 -3
- package/dist/infrastructure/sii-http-session.d.ts +5 -1
- package/dist/infrastructure/sii-http-session.js +75 -27
- package/dist/sii-error.d.ts +4 -3
- package/dist/sii-error.js +11 -4
- package/package.json +45 -45
- package/dist/domain/sii-error.d.ts +0 -27
- package/dist/domain/sii-error.js +0 -82
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DocumentStatusGateway = void 0;
|
|
4
|
+
const node_crypto_1 = require("node:crypto");
|
|
5
|
+
const rut_1 = require("../domain/rut");
|
|
6
|
+
const facturador_1 = require("./facturador");
|
|
7
|
+
const document_status_parser_1 = require("./document-status-parser");
|
|
8
|
+
const sii_http_session_1 = require("./sii-http-session");
|
|
9
|
+
/** Read-only personal queries; authentication and company authorization belong to the session. */
|
|
10
|
+
class DocumentStatusGateway {
|
|
11
|
+
session;
|
|
12
|
+
constructor(session) {
|
|
13
|
+
this.session = session;
|
|
14
|
+
}
|
|
15
|
+
get companyRut() { return this.session.company.formatted; }
|
|
16
|
+
assertReady() { this.session.assertReady(); }
|
|
17
|
+
status(query, options) {
|
|
18
|
+
return this.#read('QEstadoDTE', options?.signal, async (signal) => {
|
|
19
|
+
const actor = this.session.assertReady();
|
|
20
|
+
const fields = await this.session.request(sii_http_session_1.DOCUMENT_STATUS_FORM, async (response) => {
|
|
21
|
+
const html = await this.#html(response, 'DTEauth', signal);
|
|
22
|
+
return this.#parse('DTEauth', response, () => (0, document_status_parser_1.parseContentQueryForm)(html, actor.formatted));
|
|
23
|
+
}, { signal }, true);
|
|
24
|
+
const issuer = (0, rut_1.parseRut)(query.issuerRut), receiver = (0, rut_1.parseRut)(query.receiverRut);
|
|
25
|
+
const [year, month, day] = query.issuedDate.split('-');
|
|
26
|
+
for (const [key, value] of Object.entries({
|
|
27
|
+
rutQuery: actor.rut, dvQuery: actor.dv, rutCompany: issuer.rut, dvCompany: issuer.dv,
|
|
28
|
+
rutReceiver: receiver.rut, dvReceiver: receiver.dv, tipoDTE: String(query.documentType),
|
|
29
|
+
folioDTE: query.folio, fechaDTE: `${day}${month}${year}`, montoDTE: String(query.totalAmount),
|
|
30
|
+
}))
|
|
31
|
+
fields.set(key, value);
|
|
32
|
+
return this.session.request(sii_http_session_1.DOCUMENT_STATUS_URL, async (response) => {
|
|
33
|
+
const html = await this.#html(response, 'QEstadoDTE', signal);
|
|
34
|
+
return this.#parse('QEstadoDTE', response, () => (0, document_status_parser_1.parseDocumentVerification)(html));
|
|
35
|
+
}, { method: 'POST', signal, headers: {
|
|
36
|
+
'Content-Type': 'application/x-www-form-urlencoded', Accept: 'text/html',
|
|
37
|
+
Origin: 'https://palena.sii.cl', Referer: sii_http_session_1.DOCUMENT_STATUS_FORM,
|
|
38
|
+
}, body: fields.toString() }, true);
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
recipientEvents(query, options) {
|
|
42
|
+
return this.#read('validarAccesoReceptor', options?.signal, async (signal) => {
|
|
43
|
+
const actor = this.session.assertReady(), issuer = (0, rut_1.parseRut)(query.issuerRut);
|
|
44
|
+
await this.session.request(sii_http_session_1.RECIPIENT_EVENTS_PORTAL, async (response) => {
|
|
45
|
+
const html = await this.#html(response, 'registrorechazodtej6ui', signal);
|
|
46
|
+
this.#parse('registrorechazodtej6ui', response, () => (0, document_status_parser_1.assertDocumentQueryPage)(html));
|
|
47
|
+
}, { signal }, true);
|
|
48
|
+
const token = (await this.session.cookies(sii_http_session_1.RECIPIENT_EVENTS_URL)).find(cookie => cookie.key === 'TOKEN')?.value;
|
|
49
|
+
if (!token)
|
|
50
|
+
throw this.session.failure('SESSION_OR_INTERACTIVE_AUTH_REQUIRED', 'validarAccesoReceptor', 'SESSION_REQUIRED');
|
|
51
|
+
const body = JSON.stringify({
|
|
52
|
+
metaData: {
|
|
53
|
+
namespace: 'cl.sii.sdi.lob.diii.registrorechazodtej6.data.api.interfaces.FacadeService/validarAccesoReceptor',
|
|
54
|
+
conversationId: token, transactionId: (0, node_crypto_1.randomUUID)(), page: null,
|
|
55
|
+
},
|
|
56
|
+
data: { rutEmisor: issuer.rut, dvEmisor: issuer.dv, tipoDoc: query.documentType, folio: query.folio, rutToken: actor.rut, dvToken: actor.dv },
|
|
57
|
+
});
|
|
58
|
+
return this.session.request(sii_http_session_1.RECIPIENT_EVENTS_URL, async (response) => {
|
|
59
|
+
const mime = response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase();
|
|
60
|
+
if (mime === 'text/html') {
|
|
61
|
+
const html = await this.#html(response, 'validarAccesoReceptor', signal);
|
|
62
|
+
this.#parse('validarAccesoReceptor', response, () => (0, document_status_parser_1.assertDocumentQueryPage)(html));
|
|
63
|
+
}
|
|
64
|
+
const charset = /\bcharset\s*=\s*["']?([^;\s"']+)/i.exec(response.headers.get('content-type') ?? '')?.[1]?.toLowerCase();
|
|
65
|
+
if (mime !== 'application/json' || charset && !['utf-8', 'utf8'].includes(charset)) {
|
|
66
|
+
throw this.session.failure('SII_PROTOCOL_CHANGED', 'validarAccesoReceptor', 'INVALID_RESPONSE', response);
|
|
67
|
+
}
|
|
68
|
+
const value = await this.session.json(response, 'validarAccesoReceptor', signal);
|
|
69
|
+
return this.#parse('validarAccesoReceptor', response, () => (0, document_status_parser_1.parseRecipientEvents)(value));
|
|
70
|
+
}, { method: 'POST', signal, headers: {
|
|
71
|
+
'Content-Type': 'application/json', Accept: 'application/json, text/plain, */*',
|
|
72
|
+
Origin: 'https://www4.sii.cl', Referer: sii_http_session_1.RECIPIENT_EVENTS_PORTAL,
|
|
73
|
+
}, body }, true);
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
async #html(response, endpoint, signal) {
|
|
77
|
+
if (response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase() !== 'text/html' || !response.body) {
|
|
78
|
+
throw this.session.failure('SII_PROTOCOL_CHANGED', endpoint, 'INVALID_RESPONSE', response);
|
|
79
|
+
}
|
|
80
|
+
const bytes = await this.session.readBounded(response, endpoint, 1024 * 1024, 'SII_PROTOCOL_CHANGED', signal);
|
|
81
|
+
if (!bytes.length)
|
|
82
|
+
throw this.session.failure('SII_PROTOCOL_CHANGED', endpoint, 'EMPTY_RESPONSE', response, { responseType: 'EMPTY' });
|
|
83
|
+
const charset = (/\bcharset\s*=\s*["']?([^;\s"']+)/i.exec(response.headers.get('content-type') ?? '')?.[1]
|
|
84
|
+
?? /\bcharset\s*=\s*["']?([^;\s"'/>]+)/i.exec(Buffer.from(bytes.subarray(0, 4096)).toString('latin1'))?.[1]
|
|
85
|
+
?? 'windows-1252').toLowerCase();
|
|
86
|
+
try {
|
|
87
|
+
if (['windows-1252', 'iso-8859-1'].includes(charset))
|
|
88
|
+
return (0, facturador_1.readPortalHtml)(bytes);
|
|
89
|
+
if (['utf-8', 'utf8'].includes(charset))
|
|
90
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
91
|
+
}
|
|
92
|
+
catch { /* Reject bytes outside the declared encoding. */ }
|
|
93
|
+
throw this.session.failure('SII_PROTOCOL_CHANGED', endpoint, 'INVALID_RESPONSE', response, (0, sii_http_session_1.responseFormat)(response, bytes));
|
|
94
|
+
}
|
|
95
|
+
#parse(endpoint, response, parse) {
|
|
96
|
+
try {
|
|
97
|
+
return parse();
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
if (error instanceof document_status_parser_1.DocumentStatusProtocolError) {
|
|
101
|
+
const reason = error.code === 'CAPTCHA_INTERACTION_REQUIRED' ? 'CAPTCHA_REQUIRED'
|
|
102
|
+
: error.code === 'SESSION_OR_INTERACTIVE_AUTH_REQUIRED' ? 'SESSION_REQUIRED'
|
|
103
|
+
: error.code === 'SESSION_IDENTITY_MISMATCH' ? 'SESSION_IDENTITY_MISMATCH'
|
|
104
|
+
: error.code === 'SII_SERVICE_ERROR' ? 'PROVIDER_REJECTED' : 'INVALID_RESPONSE';
|
|
105
|
+
throw this.session.failure(error.code, endpoint, reason, response, { siiResponseCode: error.siiResponseCode });
|
|
106
|
+
}
|
|
107
|
+
throw this.session.failure('SII_PROTOCOL_CHANGED', endpoint, 'INVALID_RESPONSE', response);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
async #read(endpoint, signal, operation) {
|
|
111
|
+
if (!signal)
|
|
112
|
+
return operation();
|
|
113
|
+
// Caller-supplied abort reasons may contain secrets; only SDK diagnostics cross the boundary.
|
|
114
|
+
const controller = new AbortController();
|
|
115
|
+
const abort = () => controller.abort(this.session.failure('SII_OPERATION_ABORTED', endpoint, 'OPERATION_ABORTED'));
|
|
116
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
117
|
+
if (signal.aborted)
|
|
118
|
+
abort();
|
|
119
|
+
try {
|
|
120
|
+
return await operation(controller.signal);
|
|
121
|
+
}
|
|
122
|
+
finally {
|
|
123
|
+
signal.removeEventListener('abort', abort);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
exports.DocumentStatusGateway = DocumentStatusGateway;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { DocumentVerification, RecipientEventsObservation } from '../domain/document-status';
|
|
2
|
+
type ProtocolCode = 'SII_PROTOCOL_CHANGED' | 'SII_SERVICE_ERROR' | 'CAPTCHA_INTERACTION_REQUIRED' | 'SESSION_OR_INTERACTIVE_AUTH_REQUIRED' | 'SESSION_IDENTITY_MISMATCH';
|
|
3
|
+
export declare class DocumentStatusProtocolError extends Error {
|
|
4
|
+
readonly code: ProtocolCode;
|
|
5
|
+
readonly siiResponseCode?: number;
|
|
6
|
+
constructor(code?: ProtocolCode, siiResponseCode?: number);
|
|
7
|
+
}
|
|
8
|
+
export declare function assertDocumentQueryPage(html: string): void;
|
|
9
|
+
export declare function parseContentQueryForm(html: string, actorRut: string): URLSearchParams;
|
|
10
|
+
export declare function parseDocumentVerification(html: string): DocumentVerification;
|
|
11
|
+
export declare function parseRecipientEvents(value: unknown): RecipientEventsObservation;
|
|
12
|
+
export {};
|
|
@@ -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
|
+
}
|