@devly-cl/sii-client 0.7.9 → 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.
- package/README.md +68 -2
- package/dist/application/document-status.d.ts +5 -5
- package/dist/application/document-status.js +14 -9
- package/dist/application/dte-import-mapper.d.ts +8 -0
- package/dist/application/dte-import-mapper.js +25 -0
- package/dist/application/dte-import-model.d.ts +28 -0
- package/dist/application/dte-import-model.js +2 -0
- package/dist/application/dte-import.d.ts +37 -0
- package/dist/application/dte-import.js +352 -0
- package/dist/application/invoice-queries.d.ts +12 -6
- package/dist/application/invoice-queries.js +9 -5
- package/dist/application/issuance.d.ts +2 -2
- package/dist/application/issuance.js +26 -10
- package/dist/contracts.d.ts +32 -0
- package/dist/contracts.js +17 -0
- package/dist/domain/civil-date.d.ts +2 -0
- package/dist/domain/civil-date.js +10 -0
- package/dist/domain/document-status.d.ts +0 -4
- package/dist/domain/document-status.js +18 -11
- package/dist/domain/document.js +47 -9
- package/dist/domain/dte-arithmetic.d.ts +35 -0
- package/dist/domain/dte-arithmetic.js +78 -0
- package/dist/domain/dte-components.d.ts +9 -0
- package/dist/domain/dte-components.js +37 -0
- package/dist/domain/dte-detail.d.ts +111 -0
- package/dist/domain/dte-detail.js +2 -0
- package/dist/domain/dte-identity.d.ts +19 -0
- package/dist/domain/dte-identity.js +52 -0
- package/dist/domain/dte-money.d.ts +41 -0
- package/dist/domain/dte-money.js +81 -0
- package/dist/domain/dte-reconciliation-model.d.ts +87 -0
- package/dist/domain/dte-reconciliation-model.js +2 -0
- package/dist/domain/dte-reconciliation.d.ts +14 -4
- package/dist/domain/dte-reconciliation.js +211 -172
- package/dist/domain/dte-validation.d.ts +7 -0
- package/dist/domain/dte-validation.js +84 -0
- package/dist/domain/invoice-xml.d.ts +12 -151
- package/dist/domain/invoice-xml.js +0 -10
- package/dist/domain/invoicing.d.ts +30 -4
- package/dist/domain/invoicing.js +75 -21
- package/dist/domain/issued-invoice.d.ts +0 -6
- package/dist/domain/rcv-document.d.ts +0 -4
- package/dist/domain/received-invoice.d.ts +1 -4
- package/dist/index.d.ts +18 -10
- package/dist/index.js +18 -5
- package/dist/infrastructure/document-status-gateway.d.ts +6 -4
- package/dist/infrastructure/document-status-gateway.js +34 -13
- package/dist/infrastructure/document-status-parser.js +38 -12
- package/dist/infrastructure/dte-xml-mapper.d.ts +16 -0
- package/dist/infrastructure/dte-xml-mapper.js +381 -0
- package/dist/infrastructure/dte-xml.d.ts +40 -4
- package/dist/infrastructure/dte-xml.js +116 -238
- package/dist/infrastructure/facturador-gateway.d.ts +10 -7
- package/dist/infrastructure/facturador-gateway.js +256 -56
- package/dist/infrastructure/facturador.js +14 -7
- package/dist/infrastructure/invoice-pdf.js +10 -3
- package/dist/infrastructure/rcv-gateway.d.ts +7 -4
- package/dist/infrastructure/rcv-gateway.js +53 -12
- package/dist/infrastructure/rcv-normalization.d.ts +8 -1
- package/dist/infrastructure/rcv-normalization.js +54 -12
- package/dist/infrastructure/read-options.d.ts +3 -0
- package/dist/infrastructure/read-options.js +25 -0
- package/dist/infrastructure/sii-client.d.ts +98 -13
- package/dist/infrastructure/sii-client.js +182 -31
- package/dist/infrastructure/sii-http-session.d.ts +2 -2
- package/dist/infrastructure/sii-http-session.js +83 -19
- package/dist/sii-error.d.ts +4 -0
- package/dist/sii-error.js +38 -13
- package/package.json +2 -2
|
@@ -2,93 +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
10
|
const dte_reconciliation_1 = require("../domain/dte-reconciliation");
|
|
9
|
-
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
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');
|
|
14
16
|
}
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
}
|
|
28
|
-
function integer(node, name, required = false, signed = false) {
|
|
29
|
-
const value = text(node, name, required, 20);
|
|
30
|
-
if (value === null)
|
|
31
|
-
return null;
|
|
32
|
-
const number = Number(value);
|
|
33
|
-
if (!(signed ? /^-?\d+$/ : /^\d+$/).test(value) || !Number.isSafeInteger(number))
|
|
34
|
-
invalid();
|
|
35
|
-
return number;
|
|
36
|
-
}
|
|
37
|
-
function decimal(node, name, required = false) {
|
|
38
|
-
const value = text(node, name, required, 40);
|
|
39
|
-
if (value !== null && !/^\d+(?:\.\d+)?$/.test(value))
|
|
40
|
-
invalid();
|
|
41
|
-
return value;
|
|
42
|
-
}
|
|
43
|
-
function date(node, name) {
|
|
44
|
-
const value = text(node, name, true, 10);
|
|
45
|
-
const parsed = new Date(`${value}T00:00:00Z`);
|
|
46
|
-
if (!/^\d{4}-\d{2}-\d{2}$/.test(value) || !Number.isFinite(parsed.getTime()) || parsed.toISOString().slice(0, 10) !== value)
|
|
47
|
-
invalid();
|
|
48
|
-
return value;
|
|
49
|
-
}
|
|
50
|
-
function lineNumber(node, name) {
|
|
51
|
-
const value = integer(node, name, true);
|
|
52
|
-
return value > 0 ? value : invalid();
|
|
53
|
-
}
|
|
54
|
-
function uniqueLines(items) {
|
|
55
|
-
if (new Set(items.map(item => item.lineNumber)).size !== items.length)
|
|
56
|
-
invalid();
|
|
57
|
-
}
|
|
58
|
-
function fiscalFolio(value) {
|
|
59
|
-
try {
|
|
60
|
-
return (0, dte_reconciliation_1.normalizeDteFolio)(value);
|
|
61
|
-
}
|
|
62
|
-
catch {
|
|
63
|
-
return invalid();
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
/** Bounded, namespace-aware parsing; no DTD, external entities or network I/O. */
|
|
67
|
-
function parseDteXml(xml, expected) {
|
|
68
|
-
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);
|
|
69
29
|
const documentType = parsed.detail.documentType;
|
|
70
30
|
if (documentType !== 33 && documentType !== 34)
|
|
71
31
|
invalid();
|
|
72
32
|
const { fiscalHeader: _header, hasSignature: _signature, hasTransport: _transport, issuanceOptions: _options, ...detail } = parsed.detail;
|
|
73
33
|
return { ...parsed, detail: { ...detail, documentType } };
|
|
74
34
|
}
|
|
75
|
-
/**
|
|
76
|
-
|
|
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) {
|
|
77
58
|
if (!expected || ![33, 34, 61].includes(expected.documentType))
|
|
78
59
|
invalid();
|
|
79
|
-
return parseDocumentXml(xml, expected, true);
|
|
60
|
+
return parseDocumentXml(xml, expected, true, true, options);
|
|
61
|
+
}
|
|
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;
|
|
80
84
|
}
|
|
81
|
-
function parseDocumentXml(xml, expected, allowCreditNotes) {
|
|
82
|
-
|
|
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)
|
|
83
89
|
invalid();
|
|
84
90
|
let root;
|
|
91
|
+
let source = '';
|
|
92
|
+
const spans = new Map();
|
|
85
93
|
const stack = [];
|
|
86
94
|
let nodes = 0;
|
|
87
95
|
const header = Buffer.from(xml.subarray(0, 200)).toString('latin1');
|
|
88
96
|
const declared = /<\?xml\b[^?]*\bencoding\s*=\s*['"]([^'"]+)['"]/i.exec(header)?.[1]?.toUpperCase() ?? 'UTF-8';
|
|
89
97
|
const encoding = declared === 'UTF-8' || declared === 'UTF8' ? 'UTF-8' : declared === 'ISO-8859-1' ? 'ISO-8859-1' : invalid();
|
|
90
98
|
try {
|
|
91
|
-
|
|
99
|
+
source = encoding === 'ISO-8859-1' ? Buffer.from(xml).toString('latin1') : new TextDecoder('utf-8', { fatal: true }).decode(xml);
|
|
92
100
|
const parser = new saxes_1.SaxesParser({ xmlns: true });
|
|
93
101
|
parser.on('error', invalid);
|
|
94
102
|
parser.on('doctype', invalid);
|
|
@@ -96,7 +104,15 @@ function parseDocumentXml(xml, expected, allowCreditNotes) {
|
|
|
96
104
|
parser.on('opentag', tag => {
|
|
97
105
|
if (++nodes > 10000 || stack.length >= 32)
|
|
98
106
|
invalid();
|
|
99
|
-
const node = {
|
|
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 });
|
|
100
116
|
if (stack.length)
|
|
101
117
|
stack[stack.length - 1].children.push(node);
|
|
102
118
|
else if (root)
|
|
@@ -105,187 +121,49 @@ function parseDocumentXml(xml, expected, allowCreditNotes) {
|
|
|
105
121
|
root = node;
|
|
106
122
|
stack.push(node);
|
|
107
123
|
});
|
|
108
|
-
const append = (value) => {
|
|
109
|
-
stack
|
|
124
|
+
const append = (value) => {
|
|
125
|
+
if (stack.length)
|
|
126
|
+
stack[stack.length - 1].text += value;
|
|
127
|
+
};
|
|
110
128
|
parser.on('text', append);
|
|
111
129
|
parser.on('cdata', append);
|
|
112
|
-
parser.on('closetag', () => {
|
|
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
|
+
});
|
|
113
136
|
parser.write(source).close();
|
|
114
137
|
}
|
|
115
138
|
catch {
|
|
116
139
|
invalid();
|
|
117
140
|
}
|
|
118
|
-
if (!root
|
|
141
|
+
if (!root)
|
|
119
142
|
invalid();
|
|
120
|
-
|
|
121
|
-
if (dtes.length !== 1)
|
|
143
|
+
if (!allowIdenticalDuplicates && spans.size !== 1)
|
|
122
144
|
invalid();
|
|
123
|
-
const
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
const documentType = integer(identity, 'TipoDTE', true);
|
|
129
|
-
const grossAmounts = integer(identity, 'MntBruto');
|
|
130
|
-
if (grossAmounts !== null && grossAmounts !== 1)
|
|
131
|
-
invalid();
|
|
132
|
-
const declaredFolio = text(identity, 'Folio', true, 20);
|
|
133
|
-
const folio = fiscalFolio(declaredFolio);
|
|
134
|
-
const normalization = [];
|
|
135
|
-
if (folio !== declaredFolio)
|
|
136
|
-
normalization.push({ code: 'FOLIO_NORMALIZED', severity: 'INFO', message: 'Folio numérico normalizado sin modificar su forma declarada ni los bytes XML.' });
|
|
137
|
-
let issuerRut, receiverRut;
|
|
138
|
-
try {
|
|
139
|
-
issuerRut = (0, rut_1.parseRut)(text(issuer, 'RUTEmisor', true, 12)).formatted;
|
|
140
|
-
receiverRut = (0, rut_1.parseRut)(text(receiver, 'RUTRecep', true, 12)).formatted;
|
|
141
|
-
}
|
|
142
|
-
catch {
|
|
143
|
-
return invalid();
|
|
144
|
-
}
|
|
145
|
-
if (documentType !== 33 && documentType !== 34 && (!allowCreditNotes || documentType !== 61))
|
|
146
|
-
invalid();
|
|
147
|
-
if (issuerRut !== (0, rut_1.parseRut)(expected.issuerRut).formatted || documentType !== expected.documentType || folio !== fiscalFolio(expected.folio) || (expected.receiverRut !== undefined && receiverRut !== (0, rut_1.parseRut)(expected.receiverRut).formatted))
|
|
148
|
-
throw new invoice_xml_1.DteXmlError('SII_XML_IDENTITY_MISMATCH');
|
|
149
|
-
const lines = children(document, 'Detalle').map(line => ({
|
|
150
|
-
lineNumber: lineNumber(line, 'NroLinDet'), name: text(line, 'NmbItem', true, 80), description: text(line, 'DscItem'),
|
|
151
|
-
codes: children(line, 'CdgItem').flatMap(code => {
|
|
152
|
-
const type = text(code, 'TpoCodigo', false, 10), value = text(code, 'VlrCodigo', false, 35);
|
|
153
|
-
if (value && !type)
|
|
154
|
-
invalid();
|
|
155
|
-
if (!value)
|
|
156
|
-
normalization.push({ code: 'EMPTY_OPTIONAL_PRODUCT_CODE', severity: 'INFO', message: 'Código de producto opcional vacío tratado como ausente.', lineNumber: lineNumber(line, 'NroLinDet') });
|
|
157
|
-
return type && value ? [{ type, value }] : [];
|
|
158
|
-
}),
|
|
159
|
-
...(children(line, 'CodImpAdic').length ? { additionalTaxCodes: children(line, 'CodImpAdic').map(node => {
|
|
160
|
-
const value = nodeText(node, true, 6);
|
|
161
|
-
if (!/^\d{1,6}$/.test(value))
|
|
162
|
-
invalid();
|
|
163
|
-
return Number(value);
|
|
164
|
-
}) } : {}),
|
|
165
|
-
quantity: decimal(line, 'QtyItem'), unit: text(line, 'UnmdItem', false, 4), unitPrice: decimal(line, 'PrcItem'),
|
|
166
|
-
discountPercent: decimal(line, 'DescuentoPct'), discountAmount: integer(line, 'DescuentoMonto'),
|
|
167
|
-
surchargePercent: decimal(line, 'RecargoPct'), surchargeAmount: integer(line, 'RecargoMonto'), exemptIndicator: integer(line, 'IndExe'), amount: integer(line, 'MontoItem', true),
|
|
168
|
-
}));
|
|
169
|
-
if (!lines.length || lines.length > 1000)
|
|
170
|
-
invalid();
|
|
171
|
-
const adjustments = children(document, 'DscRcgGlobal').map(node => {
|
|
172
|
-
const movement = text(node, 'TpoMov', true), valueType = text(node, 'TpoValor', true);
|
|
173
|
-
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)
|
|
174
150
|
invalid();
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
const
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
});
|
|
185
|
-
uniqueLines(lines);
|
|
186
|
-
uniqueLines(adjustments);
|
|
187
|
-
uniqueLines(references);
|
|
188
|
-
const fiscalReferences = references.filter(reference => /^\d{1,3}$/.test(reference.documentType) && Number(reference.documentType) > 0 && Number(reference.documentType) < 200);
|
|
189
|
-
if (documentType === 61 && (!fiscalReferences.length
|
|
190
|
-
|| fiscalReferences.some(reference => reference.code === null || ![1, 2, 3].includes(reference.code) || !/^[1-9]\d{0,19}$/.test(reference.folio))
|
|
191
|
-
|| (fiscalReferences.some(reference => reference.code === 1 || reference.code === 2) && fiscalReferences.length !== 1)))
|
|
192
|
-
invalid();
|
|
193
|
-
const signatures = dtes[0].children.filter(node => node.name === 'Signature' && node.uri === 'http://www.w3.org/2000/09/xmldsig#');
|
|
194
|
-
if (allowCreditNotes && signatures.length > 1)
|
|
195
|
-
invalid();
|
|
196
|
-
const options = allowCreditNotes ? issuanceOptions(headerNode, identity, issuer, document) : undefined;
|
|
197
|
-
const issuerActivities = allowCreditNotes ? children(issuer, 'Acteco').map(node => nodeText(node)) : [];
|
|
198
|
-
const paymentTotals = Object.fromEntries([
|
|
199
|
-
['MontoNF', 'nonBillableAmount', true], ['MontoPeriodo', 'periodAmount', false],
|
|
200
|
-
['SaldoAnterior', 'previousBalance', true], ['VlrPagar', 'payableAmount', false],
|
|
201
|
-
].flatMap(([tag, field, signed]) => {
|
|
202
|
-
const value = integer(totals, tag, false, signed);
|
|
203
|
-
return value === null ? [] : [[field, value]];
|
|
204
|
-
}));
|
|
205
|
-
const detail = {
|
|
206
|
-
...(grossAmounts === 1 ? { grossAmounts: true } : {}),
|
|
207
|
-
...paymentTotals,
|
|
208
|
-
issuerRut, documentType: expected.documentType, folio, ...(folio !== declaredFolio ? { declaredFolio } : {}), issuedDate: date(identity, 'FchEmis'), receiverRut,
|
|
209
|
-
hasSignature: signatures.length === 1,
|
|
210
|
-
hasTransport: children(headerNode, 'Transporte').some(node => node.children.length > 0 || node.text.trim().length > 0 || node.attributeCount > 0),
|
|
211
|
-
...(options ? { issuanceOptions: options } : {}),
|
|
212
|
-
...(allowCreditNotes ? { fiscalHeader: {
|
|
213
|
-
issuer: { legalName: text(issuer, 'RznSoc'), businessActivity: text(issuer, 'GiroEmis'), activityCode: issuerActivities.length === 1 ? issuerActivities[0] : null, branchCode: text(issuer, 'CdgSIISucur', false, 9), address: text(issuer, 'DirOrigen'), commune: text(issuer, 'CmnaOrigen'), city: text(issuer, 'CiudadOrigen') },
|
|
214
|
-
receiver: { legalName: text(receiver, 'RznSocRecep'), address: text(receiver, 'DirRecep'), commune: text(receiver, 'CmnaRecep'), city: text(receiver, 'CiudadRecep'), businessActivity: text(receiver, 'GiroRecep'), contact: text(receiver, 'Contacto') },
|
|
215
|
-
paymentForm: integer(identity, 'FmaPago'), saleType: integer(identity, 'TpoTranVenta'), purchaseType: integer(identity, 'TpoTranCompra'),
|
|
216
|
-
noDebitReduction: integer(identity, 'IndNoRebaja', children(identity, 'IndNoRebaja').length > 0),
|
|
217
|
-
unapprovedFiscalFields: [...identity.children.filter(node => node.uri === identity.uri && !['TipoDTE', 'Folio', 'FchEmis', 'FmaPago', 'TpoTranVenta', 'TpoTranCompra', 'IndNoRebaja', 'MntPagos'].includes(node.name)).map(node => node.name), ...(issuerActivities.length > 1 ? ['Acteco'] : [])],
|
|
218
|
-
} } : {}),
|
|
219
|
-
netAmount: integer(totals, 'MntNeto'), exemptAmount: integer(totals, 'MntExe'), vatRate: decimal(totals, 'TasaIVA'), vatAmount: integer(totals, 'IVA'), totalAmount: integer(totals, 'MntTotal', true), lines,
|
|
220
|
-
taxes: children(totals, 'ImptoReten').map(node => ({ type: integer(node, 'TipoImp', true), rate: decimal(node, 'TasaImp'), amount: integer(node, 'MontoImp', true) })), adjustments, references,
|
|
221
|
-
};
|
|
222
|
-
detail.reconciliation = (0, dte_reconciliation_1.reconcileDteDetail)(detail);
|
|
223
|
-
detail.reconciliation.diagnostics.unshift(...normalization);
|
|
224
|
-
return { xml: new Uint8Array(xml), encoding, detail };
|
|
225
|
-
}
|
|
226
|
-
function issuanceOptions(header, identity, issuer, document) {
|
|
227
|
-
const unsupported = [];
|
|
228
|
-
const inspect = (node, allowed, path) => {
|
|
229
|
-
if (node.attributeCount || node.text.trim())
|
|
230
|
-
unsupported.push(path);
|
|
231
|
-
for (const child of node.children) {
|
|
232
|
-
if (child.uri !== node.uri || !allowed.includes(child.name) || child.attributeCount)
|
|
233
|
-
unsupported.push(`${path}/${child.name}`);
|
|
234
|
-
}
|
|
235
|
-
};
|
|
236
|
-
const optionalRut = (node, name) => {
|
|
237
|
-
const value = text(node, name, false, 15);
|
|
238
|
-
if (value === null)
|
|
239
|
-
return null;
|
|
240
|
-
try {
|
|
241
|
-
return (0, rut_1.parseRut)(value).formatted;
|
|
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);
|
|
242
160
|
}
|
|
243
|
-
|
|
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))
|
|
244
166
|
return invalid();
|
|
245
|
-
}
|
|
246
|
-
};
|
|
247
|
-
const transports = children(header, 'Transporte');
|
|
248
|
-
if (transports.length > 1)
|
|
249
|
-
invalid();
|
|
250
|
-
const transportNode = transports[0];
|
|
251
|
-
let transport = null;
|
|
252
|
-
if (transportNode) {
|
|
253
|
-
inspect(transportNode, ['Patente', 'RUTTrans', 'Chofer'], 'Transporte');
|
|
254
|
-
const drivers = children(transportNode, 'Chofer');
|
|
255
|
-
if (drivers.length > 1)
|
|
256
|
-
invalid();
|
|
257
|
-
const driver = drivers[0];
|
|
258
|
-
if (driver)
|
|
259
|
-
inspect(driver, ['RUTChofer', 'NombreChofer'], 'Transporte/Chofer');
|
|
260
|
-
const value = { carrierRut: optionalRut(transportNode, 'RUTTrans'), licensePlate: text(transportNode, 'Patente', false, 8), driverRut: driver ? optionalRut(driver, 'RUTChofer') : null, driverName: driver ? text(driver, 'NombreChofer', false, 30) : null };
|
|
261
|
-
if (Object.values(value).some(part => part !== null))
|
|
262
|
-
transport = value;
|
|
263
167
|
}
|
|
264
|
-
|
|
265
|
-
inspect(node, ['FchPago', 'MntPago', 'GlosaPagos'], 'IdDoc/MntPagos');
|
|
266
|
-
return { date: date(node, 'FchPago'), amount: integer(node, 'MntPago', true), description: text(node, 'GlosaPagos', false, 40) };
|
|
267
|
-
});
|
|
268
|
-
const lineTaxCodes = children(document, 'Detalle').flatMap(line => {
|
|
269
|
-
const codes = children(line, 'CodImpAdic').map(node => {
|
|
270
|
-
if (node.children.length || node.attributeCount)
|
|
271
|
-
unsupported.push('Detalle/CodImpAdic');
|
|
272
|
-
const value = node.text.trim();
|
|
273
|
-
if (!/^\d{1,6}$/.test(value))
|
|
274
|
-
invalid();
|
|
275
|
-
return Number(value);
|
|
276
|
-
});
|
|
277
|
-
return codes.length ? [{ lineNumber: lineNumber(line, 'NroLinDet'), codes }] : [];
|
|
278
|
-
});
|
|
279
|
-
const referenceGlobalIndicators = children(document, 'Referencia').flatMap(ref => {
|
|
280
|
-
const indicator = integer(ref, 'IndGlobal');
|
|
281
|
-
return indicator === null ? [] : [{ lineNumber: lineNumber(ref, 'NroLinRef'), indicator }];
|
|
282
|
-
});
|
|
283
|
-
const issuerPhones = children(issuer, 'Telefono').map(node => {
|
|
284
|
-
if (node.children.length || node.text.length > 20 || !node.text.trim())
|
|
285
|
-
invalid();
|
|
286
|
-
return node.text.trim();
|
|
287
|
-
});
|
|
288
|
-
const issuerEmail = text(issuer, 'CorreoEmisor', false, 80), requesterRut = optionalRut(header, 'RUTSolicita');
|
|
289
|
-
const result = { issuerEmail, issuerPhones, requesterRut, transport, payments, lineTaxCodes, referenceGlobalIndicators, unapprovedFields: unsupported };
|
|
290
|
-
return issuerEmail !== null || issuerPhones.length || requesterRut !== null || transport !== null || payments.length || lineTaxCodes.length || referenceGlobalIndicators.length || unsupported.length ? result : undefined;
|
|
168
|
+
return { xml: new Uint8Array(xml), encoding, detail };
|
|
291
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
|
|
4
|
-
import
|
|
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
|
}
|