@devly-cl/sii-client 0.7.1 → 0.7.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +84 -1
- 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 +49 -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 +15 -0
- package/dist/domain/dte-reconciliation.js +390 -0
- package/dist/domain/dte-validation.d.ts +7 -0
- package/dist/domain/dte-validation.js +84 -0
- package/dist/domain/invoice-xml.d.ts +17 -57
- 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 +19 -9
- package/dist/index.js +20 -4
- 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 +117 -196
- package/dist/infrastructure/facturador-gateway.d.ts +10 -7
- package/dist/infrastructure/facturador-gateway.js +256 -56
- package/dist/infrastructure/facturador.d.ts +1 -1
- package/dist/infrastructure/facturador.js +18 -10
- 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 +134 -37
- package/dist/sii-error.d.ts +5 -0
- package/dist/sii-error.js +39 -13
- package/package.json +2 -2
|
@@ -28,7 +28,9 @@ class DocumentStatusProtocolError extends Error {
|
|
|
28
28
|
}
|
|
29
29
|
}
|
|
30
30
|
exports.DocumentStatusProtocolError = DocumentStatusProtocolError;
|
|
31
|
-
function invalid() {
|
|
31
|
+
function invalid() {
|
|
32
|
+
throw new DocumentStatusProtocolError();
|
|
33
|
+
}
|
|
32
34
|
function inside(node, ancestor) {
|
|
33
35
|
for (let current = node; current; current = 'parentNode' in current ? current.parentNode : null) {
|
|
34
36
|
if (current === ancestor)
|
|
@@ -70,10 +72,12 @@ function queryPage(html) {
|
|
|
70
72
|
try {
|
|
71
73
|
document = (0, facturador_1.parsePortalPage)(html);
|
|
72
74
|
// Observed legacy syntax and late head metadata do not waive field ownership, visibility or attribute checks.
|
|
73
|
-
(0, parse5_1.parse)(html, {
|
|
75
|
+
(0, parse5_1.parse)(html, {
|
|
76
|
+
onParseError: error => {
|
|
74
77
|
if (!['missing-doctype', 'non-conforming-doctype', 'missing-semicolon-after-character-reference', 'abandoned-head-element-child'].includes(error.code))
|
|
75
78
|
invalid();
|
|
76
|
-
}
|
|
79
|
+
}
|
|
80
|
+
});
|
|
77
81
|
}
|
|
78
82
|
catch {
|
|
79
83
|
invalid();
|
|
@@ -89,7 +93,9 @@ function queryPage(html) {
|
|
|
89
93
|
throw new DocumentStatusProtocolError('SESSION_OR_INTERACTIVE_AUTH_REQUIRED');
|
|
90
94
|
return document;
|
|
91
95
|
}
|
|
92
|
-
function assertDocumentQueryPage(html) {
|
|
96
|
+
function assertDocumentQueryPage(html) {
|
|
97
|
+
queryPage(html);
|
|
98
|
+
}
|
|
93
99
|
function parseContentQueryForm(html, actorRut) {
|
|
94
100
|
const document = queryPage(html);
|
|
95
101
|
const elements = [...(0, facturador_1.nodes)(document)].filter(facturador_1.element);
|
|
@@ -169,11 +175,16 @@ function parseDocumentVerification(html) {
|
|
|
169
175
|
if (!result || !visible(result) || footers.some(footer => inside(result, footer) || inside(footer, result)))
|
|
170
176
|
invalid();
|
|
171
177
|
switch (inlineText || (0, facturador_1.readVisiblePortalText)(result)) {
|
|
172
|
-
case 'Documento recibido por el SII. Datos coinciden con los registrados':
|
|
173
|
-
|
|
174
|
-
case 'Documento recibido por el SII
|
|
175
|
-
|
|
176
|
-
|
|
178
|
+
case 'Documento recibido por el SII. Datos coinciden con los registrados':
|
|
179
|
+
return { verification: 'RECEIVED_MATCH', cancellation: 'NOT_REPORTED' };
|
|
180
|
+
case 'Documento recibido por el SII. Datos coinciden con los registrados. Existe Nota de Crédito que anula documento':
|
|
181
|
+
return { verification: 'RECEIVED_MATCH', cancellation: 'REPORTED' };
|
|
182
|
+
case 'Documento recibido por el SII pero datos NO coinciden con los registrados':
|
|
183
|
+
return { verification: 'RECEIVED_MISMATCH', cancellation: 'UNCONFIRMED' };
|
|
184
|
+
case 'Documento no autorizado':
|
|
185
|
+
return { verification: 'DOCUMENT_NOT_AUTHORIZED', cancellation: 'UNCONFIRMED' };
|
|
186
|
+
default:
|
|
187
|
+
return invalid();
|
|
177
188
|
}
|
|
178
189
|
}
|
|
179
190
|
function record(value) {
|
|
@@ -225,7 +236,13 @@ function recipientEvent(value) {
|
|
|
225
236
|
|| description.length > 512 || /[\u0000-\u001f\u007f-\u009f]/u.test(description))
|
|
226
237
|
invalid();
|
|
227
238
|
const responsibleRut = event.rutResponsable == null && event.dvResponsable == null ? null : readRut(event.rutResponsable, event.dvResponsable);
|
|
228
|
-
return {
|
|
239
|
+
return {
|
|
240
|
+
code,
|
|
241
|
+
kind: EVENT_KINDS.get(code) ?? 'UNKNOWN',
|
|
242
|
+
description,
|
|
243
|
+
occurredAtLocal: localTime(event.fechaEvento),
|
|
244
|
+
responsibleRut
|
|
245
|
+
};
|
|
229
246
|
}
|
|
230
247
|
function parseRecipientEvents(value) {
|
|
231
248
|
const envelope = record(value), status = record(envelope.respEstado);
|
|
@@ -249,9 +266,18 @@ function parseRecipientEvents(value) {
|
|
|
249
266
|
if (!Object.hasOwn(source, 'listEvenHistDoc') || source.listEvenHistDoc !== null && !Array.isArray(source.listEvenHistDoc))
|
|
250
267
|
invalid();
|
|
251
268
|
return {
|
|
252
|
-
document: {
|
|
269
|
+
document: {
|
|
270
|
+
issuerRut: readRut(source.dhdrRutEmisor, source.dhdrDvEmisor),
|
|
271
|
+
receiverRut: readRut(source.dhdrRutRecep, source.dhdrDvRecep),
|
|
272
|
+
documentType,
|
|
273
|
+
folio: String(rawFolio)
|
|
274
|
+
},
|
|
253
275
|
siiReceivedAtLocal: localTime(source.dtecTmstRecep), timeZone: null,
|
|
254
|
-
indicators: {
|
|
276
|
+
indicators: {
|
|
277
|
+
paidInCashReported: indicator(source.pagadoAlContado),
|
|
278
|
+
claimsReported: indicator(source.tieneReclamos),
|
|
279
|
+
acknowledgementsReported: indicator(source.tieneAcuses)
|
|
280
|
+
},
|
|
255
281
|
events: source.listEvenHistDoc === null ? [] : Array.from(source.listEvenHistDoc, recipientEvent),
|
|
256
282
|
accessAsIssuer: source.tieneAccesoEmisor, accessAsReceiver: source.tieneAccesoReceptor,
|
|
257
283
|
};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type DteReconciliationDiagnostic, type ExactDteDocumentDetail, type IssuedDocumentXmlQuery } from '../domain/invoice-xml';
|
|
2
|
+
export interface XmlNode {
|
|
3
|
+
name: string;
|
|
4
|
+
uri: string;
|
|
5
|
+
text: string;
|
|
6
|
+
attributeCount: number;
|
|
7
|
+
children: XmlNode[];
|
|
8
|
+
}
|
|
9
|
+
/** Maps bounded XML nodes to identity-checked declared facts; arithmetic interpretation is a separate step. */
|
|
10
|
+
export declare function mapDteXmlDetail(root: XmlNode, expected: IssuedDocumentXmlQuery & {
|
|
11
|
+
issuerRut: string;
|
|
12
|
+
receiverRut?: string;
|
|
13
|
+
}, includeDocumentFields: boolean): {
|
|
14
|
+
detail: ExactDteDocumentDetail;
|
|
15
|
+
normalization: DteReconciliationDiagnostic[];
|
|
16
|
+
};
|
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.mapDteXmlDetail = mapDteXmlDetail;
|
|
4
|
+
const contracts_1 = require("../contracts");
|
|
5
|
+
const civil_date_1 = require("../domain/civil-date");
|
|
6
|
+
const rut_1 = require("../domain/rut");
|
|
7
|
+
const dte_identity_1 = require("../domain/dte-identity");
|
|
8
|
+
const dte_money_1 = require("../domain/dte-money");
|
|
9
|
+
function invalid() {
|
|
10
|
+
throw new contracts_1.DteXmlError('SII_XML_INVALID');
|
|
11
|
+
}
|
|
12
|
+
const children = (node, name) => node.children.filter(n => n.name === name && n.uri === node.uri);
|
|
13
|
+
function one(node, name) {
|
|
14
|
+
const values = children(node, name);
|
|
15
|
+
return values.length === 1 ? values[0] : invalid();
|
|
16
|
+
}
|
|
17
|
+
function text(node, name, required = false, limit = 1000) {
|
|
18
|
+
const values = children(node, name);
|
|
19
|
+
if (values.length > 1 || (required && values.length !== 1))
|
|
20
|
+
invalid();
|
|
21
|
+
if (!values.length)
|
|
22
|
+
return null;
|
|
23
|
+
return nodeText(values[0], required, limit);
|
|
24
|
+
}
|
|
25
|
+
function nodeText(node, required = false, limit = 1000) {
|
|
26
|
+
if (node.children.length || node.text.length > limit || (required && !node.text.trim()))
|
|
27
|
+
invalid();
|
|
28
|
+
return node.text.trim() || null;
|
|
29
|
+
}
|
|
30
|
+
function integer(node, name, required = false, signed = false) {
|
|
31
|
+
const value = text(node, name, required, 20);
|
|
32
|
+
if (value === null)
|
|
33
|
+
return null;
|
|
34
|
+
const number = Number(value);
|
|
35
|
+
if (!(signed ? /^-?\d+$/ : /^\d+$/).test(value) || !Number.isSafeInteger(number))
|
|
36
|
+
invalid();
|
|
37
|
+
return number;
|
|
38
|
+
}
|
|
39
|
+
function amount(node, name, required = false, signed = false) {
|
|
40
|
+
const value = text(node, name, required, 20);
|
|
41
|
+
if (value === null)
|
|
42
|
+
return null;
|
|
43
|
+
try {
|
|
44
|
+
return (0, dte_money_1.exactDteMoney)(value, signed);
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return invalid();
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
function decimal(node, name, required = false) {
|
|
51
|
+
const value = text(node, name, required, 40);
|
|
52
|
+
if (value !== null && !/^\d+(?:\.\d+)?$/.test(value))
|
|
53
|
+
invalid();
|
|
54
|
+
return value;
|
|
55
|
+
}
|
|
56
|
+
function date(node, name) {
|
|
57
|
+
const value = text(node, name, true, 10);
|
|
58
|
+
if (!(0, civil_date_1.isCivilDate)(value))
|
|
59
|
+
invalid();
|
|
60
|
+
return value;
|
|
61
|
+
}
|
|
62
|
+
function lineNumber(node, name) {
|
|
63
|
+
const value = integer(node, name, true);
|
|
64
|
+
return value > 0 ? value : invalid();
|
|
65
|
+
}
|
|
66
|
+
function uniqueLines(items) {
|
|
67
|
+
if (new Set(items.map(item => item.lineNumber)).size !== items.length)
|
|
68
|
+
invalid();
|
|
69
|
+
}
|
|
70
|
+
function fiscalFolio(value) {
|
|
71
|
+
try {
|
|
72
|
+
return (0, dte_identity_1.normalizeDteFolio)(value);
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
return invalid();
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
function issuanceOptions(header, identity, issuer, document) {
|
|
79
|
+
const unsupported = [];
|
|
80
|
+
const inspect = (node, allowed, path) => {
|
|
81
|
+
if (node.attributeCount || node.text.trim())
|
|
82
|
+
unsupported.push(path);
|
|
83
|
+
for (const child of node.children) {
|
|
84
|
+
if (child.uri !== node.uri || !allowed.includes(child.name) || child.attributeCount)
|
|
85
|
+
unsupported.push(`${path}/${child.name}`);
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
const optionalRut = (node, name) => {
|
|
89
|
+
const value = text(node, name, false, 15);
|
|
90
|
+
if (value === null)
|
|
91
|
+
return null;
|
|
92
|
+
try {
|
|
93
|
+
return (0, rut_1.parseRut)(value).formatted;
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return invalid();
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
const transports = children(header, 'Transporte');
|
|
100
|
+
if (transports.length > 1)
|
|
101
|
+
invalid();
|
|
102
|
+
const transportNode = transports[0];
|
|
103
|
+
let transport = null;
|
|
104
|
+
if (transportNode) {
|
|
105
|
+
inspect(transportNode, ['Patente', 'RUTTrans', 'Chofer'], 'Transporte');
|
|
106
|
+
const drivers = children(transportNode, 'Chofer');
|
|
107
|
+
if (drivers.length > 1)
|
|
108
|
+
invalid();
|
|
109
|
+
const driver = drivers[0];
|
|
110
|
+
if (driver)
|
|
111
|
+
inspect(driver, ['RUTChofer', 'NombreChofer'], 'Transporte/Chofer');
|
|
112
|
+
const value = {
|
|
113
|
+
carrierRut: optionalRut(transportNode, 'RUTTrans'),
|
|
114
|
+
licensePlate: text(transportNode, 'Patente', false, 8),
|
|
115
|
+
driverRut: driver ? optionalRut(driver, 'RUTChofer') : null,
|
|
116
|
+
driverName: driver ? text(driver, 'NombreChofer', false, 30) : null
|
|
117
|
+
};
|
|
118
|
+
if (Object.values(value).some(part => part !== null))
|
|
119
|
+
transport = value;
|
|
120
|
+
}
|
|
121
|
+
const payments = children(identity, 'MntPagos').map(node => {
|
|
122
|
+
inspect(node, ['FchPago', 'MntPago', 'GlosaPagos'], 'IdDoc/MntPagos');
|
|
123
|
+
return {
|
|
124
|
+
date: date(node, 'FchPago'),
|
|
125
|
+
amount: amount(node, 'MntPago', true),
|
|
126
|
+
description: text(node, 'GlosaPagos', false, 40)
|
|
127
|
+
};
|
|
128
|
+
});
|
|
129
|
+
const lineTaxCodes = children(document, 'Detalle').flatMap(line => {
|
|
130
|
+
const codes = children(line, 'CodImpAdic').map(node => {
|
|
131
|
+
if (node.children.length || node.attributeCount)
|
|
132
|
+
unsupported.push('Detalle/CodImpAdic');
|
|
133
|
+
const value = node.text.trim();
|
|
134
|
+
if (!/^\d{1,6}$/.test(value))
|
|
135
|
+
invalid();
|
|
136
|
+
return Number(value);
|
|
137
|
+
});
|
|
138
|
+
return codes.length ? [{ lineNumber: lineNumber(line, 'NroLinDet'), codes }] : [];
|
|
139
|
+
});
|
|
140
|
+
const referenceGlobalIndicators = children(document, 'Referencia').flatMap(ref => {
|
|
141
|
+
const indicator = integer(ref, 'IndGlobal');
|
|
142
|
+
return indicator === null ? [] : [{ lineNumber: lineNumber(ref, 'NroLinRef'), indicator }];
|
|
143
|
+
});
|
|
144
|
+
const issuerPhones = children(issuer, 'Telefono').map(node => {
|
|
145
|
+
if (node.children.length || node.text.length > 20 || !node.text.trim())
|
|
146
|
+
invalid();
|
|
147
|
+
return node.text.trim();
|
|
148
|
+
});
|
|
149
|
+
const issuerEmail = text(issuer, 'CorreoEmisor', false, 80), requesterRut = optionalRut(header, 'RUTSolicita');
|
|
150
|
+
const result = {
|
|
151
|
+
issuerEmail,
|
|
152
|
+
issuerPhones,
|
|
153
|
+
requesterRut,
|
|
154
|
+
transport,
|
|
155
|
+
payments,
|
|
156
|
+
lineTaxCodes,
|
|
157
|
+
referenceGlobalIndicators,
|
|
158
|
+
unapprovedFields: unsupported
|
|
159
|
+
};
|
|
160
|
+
return issuerEmail !== null || issuerPhones.length || requesterRut !== null || transport !== null || payments.length || lineTaxCodes.length || referenceGlobalIndicators.length || unsupported.length ? result : undefined;
|
|
161
|
+
}
|
|
162
|
+
/** Maps bounded XML nodes to identity-checked declared facts; arithmetic interpretation is a separate step. */
|
|
163
|
+
function mapDteXmlDetail(root, expected, includeDocumentFields) {
|
|
164
|
+
if (!root || !['', 'http://www.sii.cl/SiiDte'].includes(root.uri))
|
|
165
|
+
invalid();
|
|
166
|
+
const dtes = root.name === 'DTE' ? [root] : root.name === 'SetDTE' ? children(root, 'DTE') : root.name === 'EnvioDTE' ? children(one(root, 'SetDTE'), 'DTE') : [];
|
|
167
|
+
if (dtes.length !== 1)
|
|
168
|
+
invalid();
|
|
169
|
+
const document = one(dtes[0], 'Documento');
|
|
170
|
+
const headerNode = one(document, 'Encabezado');
|
|
171
|
+
const identity = one(headerNode, 'IdDoc');
|
|
172
|
+
const totals = one(headerNode, 'Totales');
|
|
173
|
+
const issuer = one(headerNode, 'Emisor'), receiver = one(headerNode, 'Receptor');
|
|
174
|
+
const documentType = integer(identity, 'TipoDTE', true);
|
|
175
|
+
const grossAmounts = integer(identity, 'MntBruto');
|
|
176
|
+
if (grossAmounts !== null && grossAmounts !== 1)
|
|
177
|
+
invalid();
|
|
178
|
+
const declaredFolio = text(identity, 'Folio', true, 20);
|
|
179
|
+
const folio = fiscalFolio(declaredFolio);
|
|
180
|
+
const normalization = [];
|
|
181
|
+
if (folio !== declaredFolio)
|
|
182
|
+
normalization.push({
|
|
183
|
+
code: 'FOLIO_NORMALIZED',
|
|
184
|
+
severity: 'INFO',
|
|
185
|
+
message: 'Folio numérico normalizado sin modificar su forma declarada ni los bytes XML.'
|
|
186
|
+
});
|
|
187
|
+
let issuerRut, receiverRut;
|
|
188
|
+
try {
|
|
189
|
+
issuerRut = (0, rut_1.parseRut)(text(issuer, 'RUTEmisor', true, 12)).formatted;
|
|
190
|
+
receiverRut = (0, rut_1.parseRut)(text(receiver, 'RUTRecep', true, 12)).formatted;
|
|
191
|
+
}
|
|
192
|
+
catch {
|
|
193
|
+
return invalid();
|
|
194
|
+
}
|
|
195
|
+
if (documentType !== 33 && documentType !== 34 && (!includeDocumentFields || documentType !== 61))
|
|
196
|
+
invalid();
|
|
197
|
+
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))
|
|
198
|
+
throw new contracts_1.DteXmlError('SII_XML_IDENTITY_MISMATCH');
|
|
199
|
+
const lines = children(document, 'Detalle').map(line => ({
|
|
200
|
+
lineNumber: lineNumber(line, 'NroLinDet'),
|
|
201
|
+
name: text(line, 'NmbItem', true, 80),
|
|
202
|
+
description: text(line, 'DscItem'),
|
|
203
|
+
codes: children(line, 'CdgItem').flatMap(code => {
|
|
204
|
+
const type = text(code, 'TpoCodigo', false, 10), value = text(code, 'VlrCodigo', false, 35);
|
|
205
|
+
if (value && !type)
|
|
206
|
+
invalid();
|
|
207
|
+
if (!value)
|
|
208
|
+
normalization.push({
|
|
209
|
+
code: 'EMPTY_OPTIONAL_PRODUCT_CODE',
|
|
210
|
+
severity: 'INFO',
|
|
211
|
+
message: 'Código de producto opcional vacío tratado como ausente.',
|
|
212
|
+
lineNumber: lineNumber(line, 'NroLinDet')
|
|
213
|
+
});
|
|
214
|
+
return type && value ? [{ type, value }] : [];
|
|
215
|
+
}),
|
|
216
|
+
...(children(line, 'CodImpAdic').length ? {
|
|
217
|
+
additionalTaxCodes: children(line, 'CodImpAdic').map(node => {
|
|
218
|
+
const value = nodeText(node, true, 6);
|
|
219
|
+
if (!/^\d{1,6}$/.test(value))
|
|
220
|
+
invalid();
|
|
221
|
+
return Number(value);
|
|
222
|
+
})
|
|
223
|
+
} : {}),
|
|
224
|
+
...(children(line, 'Retenedor').length ? {
|
|
225
|
+
retention: (() => {
|
|
226
|
+
const node = one(line, 'Retenedor');
|
|
227
|
+
return {
|
|
228
|
+
agentIndicator: text(node, 'IndAgente', false, 1),
|
|
229
|
+
meatProcessingBase: amount(node, 'MntBaseFaena'),
|
|
230
|
+
marginBase: amount(node, 'MntMargComer'),
|
|
231
|
+
consumerUnitPrice: decimal(node, 'PrcConsFinal')
|
|
232
|
+
};
|
|
233
|
+
})()
|
|
234
|
+
} : {}),
|
|
235
|
+
quantity: decimal(line, 'QtyItem'),
|
|
236
|
+
unit: text(line, 'UnmdItem', false, 4),
|
|
237
|
+
unitPrice: decimal(line, 'PrcItem'),
|
|
238
|
+
discountPercent: decimal(line, 'DescuentoPct'),
|
|
239
|
+
discountAmount: amount(line, 'DescuentoMonto'),
|
|
240
|
+
surchargePercent: decimal(line, 'RecargoPct'),
|
|
241
|
+
surchargeAmount: amount(line, 'RecargoMonto'),
|
|
242
|
+
exemptIndicator: integer(line, 'IndExe'),
|
|
243
|
+
amount: amount(line, 'MontoItem', true),
|
|
244
|
+
}));
|
|
245
|
+
if (!lines.length || lines.length > 1000)
|
|
246
|
+
invalid();
|
|
247
|
+
const adjustments = children(document, 'DscRcgGlobal').map(node => {
|
|
248
|
+
const movement = text(node, 'TpoMov', true), valueType = text(node, 'TpoValor', true);
|
|
249
|
+
if ((movement !== 'D' && movement !== 'R') || (valueType !== '%' && valueType !== '$'))
|
|
250
|
+
invalid();
|
|
251
|
+
return {
|
|
252
|
+
lineNumber: lineNumber(node, 'NroLinDR'),
|
|
253
|
+
movement: movement,
|
|
254
|
+
description: text(node, 'GlosaDR'),
|
|
255
|
+
valueType: valueType,
|
|
256
|
+
value: decimal(node, 'ValorDR', true),
|
|
257
|
+
exemptIndicator: integer(node, 'IndExeDR')
|
|
258
|
+
};
|
|
259
|
+
});
|
|
260
|
+
const references = children(document, 'Referencia').map(node => {
|
|
261
|
+
const documentType = text(node, 'TpoDocRef', true, 3), declared = text(node, 'FolioRef', true, 18);
|
|
262
|
+
const folio = /^\d{1,3}$/.test(documentType) && Number(documentType) > 0 && Number(documentType) < 200 && /^\d+$/.test(declared)
|
|
263
|
+
? BigInt(declared) === 0n ? '0' : fiscalFolio(declared) : declared;
|
|
264
|
+
if (folio !== declared)
|
|
265
|
+
normalization.push({
|
|
266
|
+
code: 'REFERENCE_FOLIO_NORMALIZED',
|
|
267
|
+
severity: 'INFO',
|
|
268
|
+
message: 'Folio de referencia fiscal normalizado; se conserva su forma declarada.'
|
|
269
|
+
});
|
|
270
|
+
const globalIndicator = integer(node, 'IndGlobal');
|
|
271
|
+
return {
|
|
272
|
+
lineNumber: lineNumber(node, 'NroLinRef'),
|
|
273
|
+
documentType,
|
|
274
|
+
folio, ...(folio !== declared ? { declaredFolio: declared } : {}),
|
|
275
|
+
date: date(node, 'FchRef'),
|
|
276
|
+
code: integer(node, 'CodRef'),
|
|
277
|
+
reason: text(node, 'RazonRef', false, 90), ...(children(node, 'RUTOtr').length ? { issuerRut: text(node, 'RUTOtr', false, 12) } : {}), ...(globalIndicator === null ? {} : { globalIndicator })
|
|
278
|
+
};
|
|
279
|
+
});
|
|
280
|
+
uniqueLines(lines);
|
|
281
|
+
uniqueLines(adjustments);
|
|
282
|
+
uniqueLines(references);
|
|
283
|
+
const signatures = dtes[0].children.filter(node => node.name === 'Signature' && node.uri === 'http://www.w3.org/2000/09/xmldsig#');
|
|
284
|
+
if (includeDocumentFields && signatures.length > 1)
|
|
285
|
+
invalid();
|
|
286
|
+
const issuance = includeDocumentFields ? issuanceOptions(headerNode, identity, issuer, document) : undefined;
|
|
287
|
+
const issuerActivities = includeDocumentFields ? children(issuer, 'Acteco').map(node => nodeText(node)) : [];
|
|
288
|
+
const paymentTotals = Object.fromEntries([
|
|
289
|
+
['MontoNF', 'nonBillableAmount', true], ['MontoPeriodo', 'periodAmount', true],
|
|
290
|
+
['SaldoAnterior', 'previousBalance', true], ['VlrPagar', 'payableAmount', true],
|
|
291
|
+
].flatMap(([tag, field, signed]) => {
|
|
292
|
+
const value = amount(totals, tag, false, signed);
|
|
293
|
+
return value === null ? [] : [[field, value]];
|
|
294
|
+
}));
|
|
295
|
+
const detail = {
|
|
296
|
+
...(() => {
|
|
297
|
+
const components = Object.fromEntries([
|
|
298
|
+
['GrntDep', 'containerDeposit'], ['CredEC', 'constructionCredit'], ['IVANoRet', 'unretainedVat'],
|
|
299
|
+
['MntBase', 'meatProcessingBase'], ['MntMargenCom', 'marginBase'], ['IVAProp', 'ownVat'], ['IVATerc', 'thirdPartyVat'],
|
|
300
|
+
['ValComNeto', 'commissionNet'], ['ValComExe', 'commissionExempt'], ['ValComIVA', 'commissionVat'],
|
|
301
|
+
].flatMap(([tag, field]) => {
|
|
302
|
+
const value = amount(totals, tag);
|
|
303
|
+
return value === null ? [] : [[field, value]];
|
|
304
|
+
}));
|
|
305
|
+
const conditions = Object.fromEntries([
|
|
306
|
+
['IndNoRebaja', 'noDebitReduction'], ['FmaPago', 'paymentForm'], ['TpoTranVenta', 'saleType'], ['TpoTranCompra', 'purchaseType'],
|
|
307
|
+
].flatMap(([tag, field]) => {
|
|
308
|
+
const value = integer(identity, tag);
|
|
309
|
+
return value === null ? [] : [[field, value]];
|
|
310
|
+
}));
|
|
311
|
+
const commissions = children(document, 'Comisiones').map(node => {
|
|
312
|
+
const movement = text(node, 'TipoMovim', true, 1);
|
|
313
|
+
if (movement !== 'C' && movement !== 'O')
|
|
314
|
+
invalid();
|
|
315
|
+
return {
|
|
316
|
+
lineNumber: lineNumber(node, 'NroLinCom'),
|
|
317
|
+
movement: movement,
|
|
318
|
+
description: text(node, 'Glosa', true, 60),
|
|
319
|
+
rate: decimal(node, 'TasaComision'),
|
|
320
|
+
netAmount: amount(node, 'ValComNeto', true),
|
|
321
|
+
exemptAmount: amount(node, 'ValComExe', true),
|
|
322
|
+
vatAmount: amount(node, 'ValComIVA')
|
|
323
|
+
};
|
|
324
|
+
});
|
|
325
|
+
if (commissions.length > 20)
|
|
326
|
+
invalid();
|
|
327
|
+
uniqueLines(commissions);
|
|
328
|
+
return { ...(Object.keys(components).length ? { fiscalComponents: components } : {}), ...(Object.keys(conditions).length ? { fiscalConditions: conditions } : {}), ...(commissions.length ? { commissions } : {}) };
|
|
329
|
+
})(),
|
|
330
|
+
...(grossAmounts === 1 ? { grossAmounts: true } : {}),
|
|
331
|
+
...paymentTotals,
|
|
332
|
+
issuerRut,
|
|
333
|
+
documentType: expected.documentType,
|
|
334
|
+
folio, ...(folio !== declaredFolio ? { declaredFolio } : {}),
|
|
335
|
+
issuedDate: date(identity, 'FchEmis'),
|
|
336
|
+
receiverRut,
|
|
337
|
+
hasSignature: signatures.length === 1,
|
|
338
|
+
hasTransport: children(headerNode, 'Transporte').some(node => node.children.length > 0 || node.text.trim().length > 0 || node.attributeCount > 0),
|
|
339
|
+
...(issuance ? { issuanceOptions: issuance } : {}),
|
|
340
|
+
...(includeDocumentFields ? {
|
|
341
|
+
fiscalHeader: {
|
|
342
|
+
issuer: {
|
|
343
|
+
legalName: text(issuer, 'RznSoc'),
|
|
344
|
+
businessActivity: text(issuer, 'GiroEmis'),
|
|
345
|
+
activityCode: issuerActivities.length === 1 ? issuerActivities[0] : null,
|
|
346
|
+
branchCode: text(issuer, 'CdgSIISucur', false, 9),
|
|
347
|
+
address: text(issuer, 'DirOrigen'),
|
|
348
|
+
commune: text(issuer, 'CmnaOrigen'),
|
|
349
|
+
city: text(issuer, 'CiudadOrigen')
|
|
350
|
+
},
|
|
351
|
+
receiver: {
|
|
352
|
+
legalName: text(receiver, 'RznSocRecep'),
|
|
353
|
+
address: text(receiver, 'DirRecep'),
|
|
354
|
+
commune: text(receiver, 'CmnaRecep'),
|
|
355
|
+
city: text(receiver, 'CiudadRecep'),
|
|
356
|
+
businessActivity: text(receiver, 'GiroRecep'),
|
|
357
|
+
contact: text(receiver, 'Contacto')
|
|
358
|
+
},
|
|
359
|
+
paymentForm: integer(identity, 'FmaPago'),
|
|
360
|
+
saleType: integer(identity, 'TpoTranVenta'),
|
|
361
|
+
purchaseType: integer(identity, 'TpoTranCompra'),
|
|
362
|
+
noDebitReduction: integer(identity, 'IndNoRebaja', children(identity, 'IndNoRebaja').length > 0),
|
|
363
|
+
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'] : [])],
|
|
364
|
+
}
|
|
365
|
+
} : {}),
|
|
366
|
+
netAmount: amount(totals, 'MntNeto'),
|
|
367
|
+
exemptAmount: amount(totals, 'MntExe'),
|
|
368
|
+
vatRate: decimal(totals, 'TasaIVA'),
|
|
369
|
+
vatAmount: amount(totals, 'IVA'),
|
|
370
|
+
totalAmount: amount(totals, 'MntTotal', true),
|
|
371
|
+
lines,
|
|
372
|
+
taxes: children(totals, 'ImptoReten').map(node => ({
|
|
373
|
+
type: integer(node, 'TipoImp', true),
|
|
374
|
+
rate: decimal(node, 'TasaImp'),
|
|
375
|
+
amount: amount(node, 'MontoImp', true)
|
|
376
|
+
})),
|
|
377
|
+
adjustments,
|
|
378
|
+
references,
|
|
379
|
+
};
|
|
380
|
+
return { detail, normalization };
|
|
381
|
+
}
|
|
@@ -1,11 +1,47 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
1
|
+
import type { DteXmlReadOptions } from '../contracts';
|
|
2
|
+
import type { ExactDteDocumentXmlResult } from '../domain/invoice-xml';
|
|
3
|
+
import { type InvoiceXmlResult, type IssuedDocumentXmlQuery, type IssuedDocumentXmlResult, type IssuedInvoiceXmlQuery } from '../domain/invoice-xml';
|
|
4
|
+
/**
|
|
5
|
+
* Lee un XML de factura 33/34 y conserva el contrato histórico de detalle numérico.
|
|
6
|
+
* El parser es acotado, reconoce namespaces y rechaza DTD y entidades externas, sin I/O de red.
|
|
7
|
+
* @param xml Bytes originales UTF-8 o ISO-8859-1; máximo MAX_DTE_XML_BYTES.
|
|
8
|
+
* @param expected Identidad esperada; siempre comprueba emisor, tipo, folio y receptor cuando se indica.
|
|
9
|
+
* @param options Por defecto incluye conciliación. reconcile=false devuelve sólo los hechos declarados.
|
|
10
|
+
* @returns Bytes originales, codificación y detalle; no modifica los importes de fuente.
|
|
11
|
+
* @throws DteXmlError por XML no representable o identidad distinta; TypeError por opciones inválidas.
|
|
12
|
+
* @remarks No valida criptográficamente firmas ni autoriza acceso al documento.
|
|
13
|
+
*/
|
|
3
14
|
export declare function parseDteXml(xml: Uint8Array, expected: IssuedInvoiceXmlQuery & {
|
|
4
15
|
issuerRut: string;
|
|
5
16
|
receiverRut?: string;
|
|
6
|
-
}): InvoiceXmlResult;
|
|
7
|
-
/**
|
|
17
|
+
}, options?: DteXmlReadOptions): InvoiceXmlResult;
|
|
18
|
+
/**
|
|
19
|
+
* Lee facturas 33/34 y notas de crédito 61, emitidas o recibidas, con importes numéricos seguros.
|
|
20
|
+
* Incluye encabezado fiscal y presencia de firma/transporte; los bytes y valores declarados se conservan.
|
|
21
|
+
* @param expected Identidad esperada; incluya receiverRut para comprobar también el receptor.
|
|
22
|
+
* @param options reconcile=false omite conciliación y requisitos de interpretación de referencias fiscales.
|
|
23
|
+
* Los controles de identidad, estructura, precisión y límites siempre se ejecutan.
|
|
24
|
+
* @throws DteXmlError por XML/identidad inválidos; TypeError por opciones inválidas.
|
|
25
|
+
* @see parseDteXml
|
|
26
|
+
*/
|
|
8
27
|
export declare function parseDteDocumentXml(xml: Uint8Array, expected: IssuedDocumentXmlQuery & {
|
|
9
28
|
issuerRut: string;
|
|
10
29
|
receiverRut?: string;
|
|
30
|
+
}, options?: DteXmlReadOptions): IssuedDocumentXmlResult;
|
|
31
|
+
/**
|
|
32
|
+
* Lee DTE 33/34/61 con importes monetarios enteros como strings, hasta 18 dígitos de fuente.
|
|
33
|
+
* Precios, cantidades y porcentajes conservan su representación decimal original.
|
|
34
|
+
* @param options Por defecto intenta conciliar si los importes caben en Number; reconcile=false omite ese paso.
|
|
35
|
+
* @returns XML original y detalle exacto. La ausencia de reconciliation no acredita validez fiscal.
|
|
36
|
+
* @throws DteXmlError por XML/identidad inválidos; TypeError por opciones inválidas.
|
|
37
|
+
* @see parseDteDocumentXml
|
|
38
|
+
*/
|
|
39
|
+
export declare function parseDteDocumentXmlExact(xml: Uint8Array, expected: IssuedDocumentXmlQuery & {
|
|
40
|
+
issuerRut: string;
|
|
41
|
+
receiverRut?: string;
|
|
42
|
+
}, options?: DteXmlReadOptions): ExactDteDocumentXmlResult;
|
|
43
|
+
/** Issuance accepts one physical DTE, even when additional copies are identical. */
|
|
44
|
+
export declare function parseDteDocumentXmlForIssuance(xml: Uint8Array, expected: IssuedDocumentXmlQuery & {
|
|
45
|
+
issuerRut: string;
|
|
46
|
+
receiverRut?: string;
|
|
11
47
|
}): IssuedDocumentXmlResult;
|