@devlas/dte-sii 2.5.0
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/BoletaService.js +109 -0
- package/CAF.js +173 -0
- package/CafSolicitor.js +380 -0
- package/Certificado.js +123 -0
- package/ConsumoFolio.js +376 -0
- package/DTE.js +399 -0
- package/EnviadorSII.js +1304 -0
- package/Envio.js +196 -0
- package/FolioRegistry.js +553 -0
- package/FolioService.js +703 -0
- package/LICENSE +27 -0
- package/LibroBase.js +134 -0
- package/LibroCompraVenta.js +205 -0
- package/LibroGuia.js +225 -0
- package/README.md +239 -0
- package/Signer.js +94 -0
- package/SiiCertificacion.js +1189 -0
- package/SiiPortalAuth.js +460 -0
- package/SiiSession.js +499 -0
- package/cert/BoletaCert.js +731 -0
- package/cert/CertFolioHelper.js +185 -0
- package/cert/CertRunner.js +2658 -0
- package/cert/ConfigLoader.js +133 -0
- package/cert/IntercambioCert.js +429 -0
- package/cert/LibroCompras.js +359 -0
- package/cert/LibroGuias.js +171 -0
- package/cert/LibroVentas.js +153 -0
- package/cert/MuestrasImpresas.js +676 -0
- package/cert/SetBase.js +321 -0
- package/cert/SetBasico.js +413 -0
- package/cert/SetCompra.js +472 -0
- package/cert/SetExenta.js +490 -0
- package/cert/SetGuia.js +283 -0
- package/cert/SetParser.js +1184 -0
- package/cert/SetsProvider.js +499 -0
- package/cert/Simulacion.js +521 -0
- package/cert/comunaOficina.js +460 -0
- package/cert/index.js +124 -0
- package/cert/types.js +330 -0
- package/dte-sii.d.ts +458 -0
- package/index.js +428 -0
- package/package.json +48 -0
- package/utils/c14n.js +275 -0
- package/utils/calculo.js +396 -0
- package/utils/config.js +276 -0
- package/utils/constants.js +302 -0
- package/utils/emisor.js +174 -0
- package/utils/endpoints.js +225 -0
- package/utils/error.js +235 -0
- package/utils/index.js +339 -0
- package/utils/logger.js +239 -0
- package/utils/pfx.js +203 -0
- package/utils/receptor.js +218 -0
- package/utils/referencia.js +169 -0
- package/utils/resolucion.js +119 -0
- package/utils/rut.js +169 -0
- package/utils/sanitize.js +124 -0
- package/utils/tokenCache.js +214 -0
- package/utils/xml.js +358 -0
- package/utils.js +4 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Devlas SpA — https://devlas.cl
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
Esta librería implementa el protocolo XML del Servicio de Impuestos Internos (SII)
|
|
26
|
+
de Chile tal como está documentado públicamente por el propio SII.
|
|
27
|
+
Inspirada conceptualmente en LibreDTE de SASCO SpA (https://libredte.cl).
|
package/LibroBase.js
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// Copyright (c) 2026 Devlas SpA — https://devlas.cl
|
|
2
|
+
// Licencia MIT. Ver archivo LICENSE para mas detalles.
|
|
3
|
+
/**
|
|
4
|
+
* LibroBase.js
|
|
5
|
+
*
|
|
6
|
+
* Clase base para libros electrónicos (LibroCompraVenta, LibroGuia).
|
|
7
|
+
* Contiene lógica común de C14N, firma digital y serialización XML.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const crypto = require('crypto');
|
|
11
|
+
const { DOMParser } = require('@xmldom/xmldom');
|
|
12
|
+
const { serializeElement, escapeText, escapeAttr } = require('./utils/c14n');
|
|
13
|
+
|
|
14
|
+
class LibroBase {
|
|
15
|
+
constructor(certificado) {
|
|
16
|
+
this.certificado = certificado;
|
|
17
|
+
this.caratula = null;
|
|
18
|
+
this.resumen = [];
|
|
19
|
+
this.detalle = [];
|
|
20
|
+
this.xml = null;
|
|
21
|
+
this.id = null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
setResumen(resumen) {
|
|
25
|
+
this.resumen = Array.isArray(resumen) ? resumen : [];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
setDetalle(detalle) {
|
|
29
|
+
this.detalle = Array.isArray(detalle) ? detalle : [];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Firma el XML del libro.
|
|
34
|
+
* Método genérico que puede ser usado por subclases.
|
|
35
|
+
*
|
|
36
|
+
* @param {string} xml - XML sin firmar
|
|
37
|
+
* @param {string} envioTagName - Nombre del tag de envío (ej: 'EnvioLibro')
|
|
38
|
+
* @param {string} rootTagName - Nombre del tag raíz (ej: 'LibroCompraVenta', 'LibroGuia')
|
|
39
|
+
* @returns {string} - XML firmado
|
|
40
|
+
*/
|
|
41
|
+
firmar(xml, envioTagName = 'EnvioLibro', rootTagName = null) {
|
|
42
|
+
const parser = new DOMParser();
|
|
43
|
+
const doc = parser.parseFromString(xml, 'text/xml');
|
|
44
|
+
const envioLibro = doc.getElementsByTagName(envioTagName)[0];
|
|
45
|
+
|
|
46
|
+
// Detectar rootTagName si no se proporciona
|
|
47
|
+
const detectedRootTagName = rootTagName || doc.documentElement.tagName;
|
|
48
|
+
const root = doc.getElementsByTagName(detectedRootTagName)[0];
|
|
49
|
+
const nsDefault = root.getAttribute('xmlns') || 'http://www.sii.cl/SiiDte';
|
|
50
|
+
|
|
51
|
+
const c14nEnvio = this._c14nEnvioLibro(envioLibro, nsDefault, envioTagName);
|
|
52
|
+
const digest = crypto.createHash('sha1').update(c14nEnvio).digest('base64');
|
|
53
|
+
|
|
54
|
+
const signedInfoParaFirmar = `<SignedInfo xmlns="http://www.w3.org/2000/09/xmldsig#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"></CanonicalizationMethod><SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"></SignatureMethod><Reference URI="#${this.id}"><Transforms><Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"></Transform></Transforms><DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"></DigestMethod><DigestValue>${digest}</DigestValue></Reference></SignedInfo>`;
|
|
55
|
+
|
|
56
|
+
const sign = crypto.createSign('RSA-SHA1');
|
|
57
|
+
sign.update(signedInfoParaFirmar);
|
|
58
|
+
const signatureValue = sign.sign(this.certificado.getPrivateKeyPem(), 'base64');
|
|
59
|
+
const formattedSignatureValue = signatureValue.match(/.{1,76}/g).join('\n');
|
|
60
|
+
|
|
61
|
+
const certBase64 = this.certificado.getCertificatePem()
|
|
62
|
+
.replace('-----BEGIN CERTIFICATE-----', '')
|
|
63
|
+
.replace('-----END CERTIFICATE-----', '')
|
|
64
|
+
.replace(/\s/g, '');
|
|
65
|
+
const modulus = this.certificado.getModulus();
|
|
66
|
+
const exponent = this.certificado.getExponent();
|
|
67
|
+
|
|
68
|
+
const signedInfoParaGuardar = `<SignedInfo xmlns="http://www.w3.org/2000/09/xmldsig#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/><SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/><Reference URI="#${this.id}"><Transforms><Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/></Transforms><DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/><DigestValue>${digest}</DigestValue></Reference></SignedInfo>`;
|
|
69
|
+
|
|
70
|
+
const signatureXml = `<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">${signedInfoParaGuardar}<SignatureValue>\n${formattedSignatureValue}</SignatureValue><KeyInfo><KeyValue><RSAKeyValue><Modulus>${modulus}</Modulus><Exponent>${exponent}</Exponent></RSAKeyValue></KeyValue><X509Data><X509Certificate>${certBase64}</X509Certificate></X509Data></KeyInfo></Signature>`;
|
|
71
|
+
|
|
72
|
+
// Insertar firma antes del cierre del root tag
|
|
73
|
+
const closeTag = `</${envioTagName}></${detectedRootTagName}>`;
|
|
74
|
+
const closeTagWithSignature = `</${envioTagName}>${signatureXml}</${detectedRootTagName}>`;
|
|
75
|
+
|
|
76
|
+
// Manejar variaciones de formato (con/sin espacios)
|
|
77
|
+
return xml
|
|
78
|
+
.replace(new RegExp(`</${envioTagName}>\\s*</${detectedRootTagName}>`), closeTagWithSignature);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Canonicaliza un elemento de envío de libro - Usa utils/c14n.js
|
|
83
|
+
*/
|
|
84
|
+
_c14nEnvioLibro(elemento, nsDefault, tagName = 'EnvioLibro') {
|
|
85
|
+
const id = elemento.getAttribute('ID');
|
|
86
|
+
let c14n = `<${tagName}`;
|
|
87
|
+
c14n += ` xmlns="${nsDefault}"`;
|
|
88
|
+
c14n += ` xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"`;
|
|
89
|
+
c14n += ` ID="${id}">`;
|
|
90
|
+
|
|
91
|
+
for (let i = 0; i < elemento.childNodes.length; i++) {
|
|
92
|
+
const child = elemento.childNodes[i];
|
|
93
|
+
if (child.nodeType === 1) {
|
|
94
|
+
c14n += serializeElement(child, { omitRootNs: true });
|
|
95
|
+
} else if (child.nodeType === 3) {
|
|
96
|
+
c14n += escapeText(child.nodeValue);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
c14n += `</${tagName}>`;
|
|
101
|
+
return c14n;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
getXML() {
|
|
105
|
+
return this.xml;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Escapa texto XML (método de conveniencia para subclases)
|
|
110
|
+
* Usa la función centralizada de utils/c14n.js
|
|
111
|
+
*/
|
|
112
|
+
_escapeXmlText(text) {
|
|
113
|
+
return escapeText(text);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Escapa atributos XML (método de conveniencia para subclases)
|
|
118
|
+
* Usa la función centralizada de utils/c14n.js
|
|
119
|
+
*/
|
|
120
|
+
_escapeXmlAttr(text) {
|
|
121
|
+
return escapeAttr(text);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Obtener timestamp de firma en formato ISO
|
|
126
|
+
*/
|
|
127
|
+
_getTmstFirma() {
|
|
128
|
+
const now = new Date();
|
|
129
|
+
const pad = n => n.toString().padStart(2, '0');
|
|
130
|
+
return `${now.getFullYear()}-${pad(now.getMonth()+1)}-${pad(now.getDate())}T${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
module.exports = LibroBase;
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
// Copyright (c) 2026 Devlas SpA — https://devlas.cl
|
|
2
|
+
// Licencia MIT. Ver archivo LICENSE para mas detalles.
|
|
3
|
+
/**
|
|
4
|
+
* LibroCompraVenta.js
|
|
5
|
+
*
|
|
6
|
+
* Genera Libro de Compra/Venta electrónico para el SII.
|
|
7
|
+
*
|
|
8
|
+
* Hereda de LibroBase: C14N, firma digital y serialización XML.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const LibroBase = require('./LibroBase');
|
|
12
|
+
|
|
13
|
+
class LibroCompraVenta extends LibroBase {
|
|
14
|
+
constructor(certificado) {
|
|
15
|
+
super(certificado);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
setCaratula(caratula) {
|
|
19
|
+
this.caratula = { ...caratula };
|
|
20
|
+
this.id = this.caratula.ID || `LCV_${(caratula.RutEmisorLibro || '').replace('-', '')}_${Date.now()}`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
generar() {
|
|
24
|
+
if (!this.caratula) {
|
|
25
|
+
throw new Error('Debe establecer la carátula antes de generar');
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const caratulaXml = this._renderCaratula();
|
|
29
|
+
const resumenXml = this._renderResumen();
|
|
30
|
+
const detalleXml = this._renderDetalle();
|
|
31
|
+
const envioLibroId = this.id;
|
|
32
|
+
const tmstFirma = this._getTmstFirma();
|
|
33
|
+
|
|
34
|
+
const xmlSinFirma = `<?xml version="1.0" encoding="ISO-8859-1"?>\n` +
|
|
35
|
+
`<LibroCompraVenta xmlns="http://www.sii.cl/SiiDte" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sii.cl/SiiDte LibroCV_v10.xsd" version="1.0">` +
|
|
36
|
+
`<EnvioLibro ID="${envioLibroId}">${caratulaXml}${resumenXml}${detalleXml}<TmstFirma>${tmstFirma}</TmstFirma></EnvioLibro>` +
|
|
37
|
+
`</LibroCompraVenta>`;
|
|
38
|
+
|
|
39
|
+
const xmlConSaltos = xmlSinFirma.replace(/></g, '><').replace(/></g, '>\n<');
|
|
40
|
+
// Usar firmar() heredado de LibroBase
|
|
41
|
+
this.xml = this.firmar(xmlConSaltos, 'EnvioLibro', 'LibroCompraVenta');
|
|
42
|
+
return this.xml;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
_renderCaratula() {
|
|
46
|
+
const c = this.caratula || {};
|
|
47
|
+
let xml = '<Caratula>';
|
|
48
|
+
|
|
49
|
+
if (c.RutEmisorLibro) xml += `<RutEmisorLibro>${this._escapeXmlText(String(c.RutEmisorLibro))}</RutEmisorLibro>`;
|
|
50
|
+
if (c.RutEnvia) xml += `<RutEnvia>${this._escapeXmlText(String(c.RutEnvia))}</RutEnvia>`;
|
|
51
|
+
if (c.PeriodoTributario) xml += `<PeriodoTributario>${this._escapeXmlText(String(c.PeriodoTributario))}</PeriodoTributario>`;
|
|
52
|
+
if (c.FchResol) xml += `<FchResol>${this._escapeXmlText(String(c.FchResol))}</FchResol>`;
|
|
53
|
+
// NroResol SIEMPRE presente (aunque sea 0)
|
|
54
|
+
xml += `<NroResol>${this._escapeXmlText(String(c.NroResol !== undefined ? c.NroResol : '0'))}</NroResol>`;
|
|
55
|
+
if (c.TipoOperacion) xml += `<TipoOperacion>${this._escapeXmlText(String(c.TipoOperacion))}</TipoOperacion>`;
|
|
56
|
+
if (c.TipoLibro) xml += `<TipoLibro>${this._escapeXmlText(String(c.TipoLibro))}</TipoLibro>`;
|
|
57
|
+
if (c.TipoEnvio) xml += `<TipoEnvio>${this._escapeXmlText(String(c.TipoEnvio))}</TipoEnvio>`;
|
|
58
|
+
if (c.FolioNotificacion) xml += `<FolioNotificacion>${this._escapeXmlText(String(c.FolioNotificacion))}</FolioNotificacion>`;
|
|
59
|
+
if (c.TmstFirmaEnv) xml += `<TmstFirmaEnv>${this._escapeXmlText(String(c.TmstFirmaEnv))}</TmstFirmaEnv>`;
|
|
60
|
+
|
|
61
|
+
xml += '</Caratula>';
|
|
62
|
+
return xml;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
_renderResumen() {
|
|
66
|
+
if (!this.resumen.length) return '';
|
|
67
|
+
|
|
68
|
+
const tipoEnvio = String(this.caratula?.TipoEnvio || '').toUpperCase();
|
|
69
|
+
const useSegmento = tipoEnvio && tipoEnvio !== 'TOTAL';
|
|
70
|
+
const resumenTag = useSegmento ? 'ResumenSegmento' : 'ResumenPeriodo';
|
|
71
|
+
const totalesTag = useSegmento ? 'TotalesSegmento' : 'TotalesPeriodo';
|
|
72
|
+
|
|
73
|
+
const order = [
|
|
74
|
+
'TpoDoc', 'TpoImp', 'TotDoc', 'TotAnulado', 'TotOpExe', 'TotMntExe',
|
|
75
|
+
'TotMntNeto', 'TotOpIVARec', 'TotMntIVA', 'TotOpActivoFijo',
|
|
76
|
+
'TotMntActivoFijo', 'TotMntIVAActivoFijo', 'TotIVANoRec',
|
|
77
|
+
'TotOpIVAUsoComun', 'TotIVAUsoComun', 'FctProp', 'TotCredIVAUsoComun',
|
|
78
|
+
'TotIVAFueraPlazo', 'TotIVAPropio', 'TotIVATerceros', 'TotLey18211',
|
|
79
|
+
'TotOtrosImp', 'TotImpSinCredito', 'TotOpIVARetTotal', 'TotIVARetTotal',
|
|
80
|
+
'TotOpIVARetParcial', 'TotIVARetParcial', 'TotCredEC', 'TotDepEnvase',
|
|
81
|
+
'TotLiquidaciones', 'TotMntTotal', 'TotOpIVANoRetenido', 'TotIVANoRetenido',
|
|
82
|
+
'TotMntNoFact', 'TotMntPeriodo', 'TotPsjNac', 'TotPsjInt', 'TotTabPuros',
|
|
83
|
+
'TotTabCigarrillos', 'TotTabElaborado', 'TotImpVehiculo',
|
|
84
|
+
];
|
|
85
|
+
|
|
86
|
+
let xml = `<${resumenTag}>`;
|
|
87
|
+
for (const r of this.resumen) {
|
|
88
|
+
const normalized = { ...r };
|
|
89
|
+
if (
|
|
90
|
+
normalized.TotMntExe === undefined &&
|
|
91
|
+
(normalized.TotMntNeto !== undefined ||
|
|
92
|
+
normalized.TotMntIVA !== undefined ||
|
|
93
|
+
normalized.TotMntTotal !== undefined)
|
|
94
|
+
) {
|
|
95
|
+
normalized.TotMntExe = 0;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
xml += `<${totalesTag}>`;
|
|
99
|
+
order.forEach((key) => {
|
|
100
|
+
const value = normalized[key];
|
|
101
|
+
if (value === undefined || value === null || value === '') return;
|
|
102
|
+
|
|
103
|
+
if (Array.isArray(value)) {
|
|
104
|
+
value.forEach((item) => {
|
|
105
|
+
if (item && typeof item === 'object') {
|
|
106
|
+
xml += `<${key}>`;
|
|
107
|
+
Object.keys(item).forEach((itemKey) => {
|
|
108
|
+
if (item[itemKey] !== undefined && item[itemKey] !== null && item[itemKey] !== '') {
|
|
109
|
+
xml += `<${itemKey}>${this._escapeXmlText(String(item[itemKey]))}</${itemKey}>`;
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
xml += `</${key}>`;
|
|
113
|
+
} else {
|
|
114
|
+
xml += `<${key}>${this._escapeXmlText(String(item))}</${key}>`;
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
} else if (value && typeof value === 'object') {
|
|
118
|
+
xml += `<${key}>`;
|
|
119
|
+
Object.keys(value).forEach((itemKey) => {
|
|
120
|
+
if (value[itemKey] !== undefined && value[itemKey] !== null && value[itemKey] !== '') {
|
|
121
|
+
xml += `<${itemKey}>${this._escapeXmlText(String(value[itemKey]))}</${itemKey}>`;
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
xml += `</${key}>`;
|
|
125
|
+
} else {
|
|
126
|
+
xml += `<${key}>${this._escapeXmlText(String(value))}</${key}>`;
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
xml += `</${totalesTag}>`;
|
|
130
|
+
}
|
|
131
|
+
xml += `</${resumenTag}>`;
|
|
132
|
+
return xml;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
_renderDetalle() {
|
|
136
|
+
if (!this.detalle.length) return '';
|
|
137
|
+
|
|
138
|
+
const order = [
|
|
139
|
+
'TpoDoc', 'Emisor', 'IndFactCompra', 'NroDoc', 'Anulado', 'Operacion',
|
|
140
|
+
'TpoImp', 'TasaImp', 'NumInt', 'IndServicio', 'IndSinCosto', 'FchDoc',
|
|
141
|
+
'CdgSIISucur', 'RUTDoc', 'RznSoc', 'Extranjero', 'TpoDocRef', 'FolioDocRef',
|
|
142
|
+
'MntExe', 'MntNeto', 'MntIVA', 'MntActivoFijo', 'MntIVAActivoFijo',
|
|
143
|
+
'IVANoRec', 'IVAUsoComun', 'IVAFueraPlazo', 'IVAPropio', 'IVATerceros',
|
|
144
|
+
'Ley18211', 'OtrosImp', 'MntSinCred', 'IVARetTotal', 'IVARetParcial',
|
|
145
|
+
'CredEC', 'DepEnvase', 'Liquidaciones', 'MntTotal', 'IVANoRetenido',
|
|
146
|
+
'MntNoFact', 'MntPeriodo', 'PsjNac', 'PsjInt', 'TabPuros', 'TabCigarrillos',
|
|
147
|
+
'TabElaborado', 'ImpVehiculo',
|
|
148
|
+
];
|
|
149
|
+
|
|
150
|
+
let xml = '';
|
|
151
|
+
for (const d of this.detalle) {
|
|
152
|
+
const normalized = { ...d };
|
|
153
|
+
|
|
154
|
+
// Calcular TasaImp si no existe
|
|
155
|
+
if (
|
|
156
|
+
(normalized.TasaImp === undefined || normalized.TasaImp === null || normalized.TasaImp === '') &&
|
|
157
|
+
normalized.MntNeto !== undefined &&
|
|
158
|
+
normalized.MntIVA !== undefined
|
|
159
|
+
) {
|
|
160
|
+
const neto = Number(normalized.MntNeto);
|
|
161
|
+
const iva = Number(normalized.MntIVA);
|
|
162
|
+
if (Number.isFinite(neto) && Number.isFinite(iva) && neto > 0 && iva > 0) {
|
|
163
|
+
const tasa = (iva / neto) * 100;
|
|
164
|
+
normalized.TasaImp = tasa.toFixed(2).replace(/\.00$/, '.0');
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
xml += '<Detalle>';
|
|
169
|
+
order.forEach((key) => {
|
|
170
|
+
const value = normalized[key];
|
|
171
|
+
if (value === undefined || value === null || value === '') return;
|
|
172
|
+
|
|
173
|
+
if (Array.isArray(value)) {
|
|
174
|
+
value.forEach((item) => {
|
|
175
|
+
if (item && typeof item === 'object') {
|
|
176
|
+
xml += `<${key}>`;
|
|
177
|
+
Object.keys(item).forEach((itemKey) => {
|
|
178
|
+
if (item[itemKey] !== undefined && item[itemKey] !== null && item[itemKey] !== '') {
|
|
179
|
+
xml += `<${itemKey}>${this._escapeXmlText(String(item[itemKey]))}</${itemKey}>`;
|
|
180
|
+
}
|
|
181
|
+
});
|
|
182
|
+
xml += `</${key}>`;
|
|
183
|
+
} else {
|
|
184
|
+
xml += `<${key}>${this._escapeXmlText(String(item))}</${key}>`;
|
|
185
|
+
}
|
|
186
|
+
});
|
|
187
|
+
} else if (value && typeof value === 'object') {
|
|
188
|
+
xml += `<${key}>`;
|
|
189
|
+
Object.keys(value).forEach((itemKey) => {
|
|
190
|
+
if (value[itemKey] !== undefined && value[itemKey] !== null && value[itemKey] !== '') {
|
|
191
|
+
xml += `<${itemKey}>${this._escapeXmlText(String(value[itemKey]))}</${itemKey}>`;
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
xml += `</${key}>`;
|
|
195
|
+
} else {
|
|
196
|
+
xml += `<${key}>${this._escapeXmlText(String(value))}</${key}>`;
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
xml += '</Detalle>';
|
|
200
|
+
}
|
|
201
|
+
return xml;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
module.exports = LibroCompraVenta;
|
package/LibroGuia.js
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
// Copyright (c) 2026 Devlas SpA — https://devlas.cl
|
|
2
|
+
// Licencia MIT. Ver archivo LICENSE para mas detalles.
|
|
3
|
+
/**
|
|
4
|
+
* LibroGuia.js
|
|
5
|
+
*
|
|
6
|
+
* Genera Libro de Guías de Despacho electrónico para el SII.
|
|
7
|
+
*
|
|
8
|
+
* Hereda de LibroBase: C14N, firma digital y serialización XML.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const LibroBase = require('./LibroBase');
|
|
12
|
+
|
|
13
|
+
class LibroGuia extends LibroBase {
|
|
14
|
+
constructor(certificado) {
|
|
15
|
+
super(certificado);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
setCaratula(caratula) {
|
|
19
|
+
this.caratula = {
|
|
20
|
+
RutEmisorLibro: null,
|
|
21
|
+
RutEnvia: this.certificado?.rut || null,
|
|
22
|
+
PeriodoTributario: null,
|
|
23
|
+
FchResol: null,
|
|
24
|
+
NroResol: 0,
|
|
25
|
+
TipoLibro: 'ESPECIAL',
|
|
26
|
+
TipoEnvio: 'TOTAL',
|
|
27
|
+
FolioNotificacion: null,
|
|
28
|
+
...caratula,
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
if (this.caratula.TipoEnvio === 'ESPECIAL') {
|
|
32
|
+
this.caratula.FolioNotificacion = null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
this.id = this.caratula.ID || `LIBRO_GUIA_${(this.caratula.RutEmisorLibro || '').replace('-', '')}_${String(this.caratula.PeriodoTributario || '').replace(/-/g, '')}_${Date.now()}`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
generar() {
|
|
39
|
+
if (!this.caratula) {
|
|
40
|
+
throw new Error('Debe establecer la carátula antes de generar');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const caratulaXml = this._renderCaratula();
|
|
44
|
+
const resumenXml = this._renderResumen();
|
|
45
|
+
const detalleXml = this._renderDetalle();
|
|
46
|
+
|
|
47
|
+
const schemaLoc = 'http://www.sii.cl/SiiDte LibroGuia_v10.xsd';
|
|
48
|
+
const tmstFirma = this._getTmstFirma();
|
|
49
|
+
|
|
50
|
+
const xmlSinFirma = `<?xml version="1.0" encoding="ISO-8859-1"?>\n` +
|
|
51
|
+
`<LibroGuia xmlns="http://www.sii.cl/SiiDte" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="${schemaLoc}" version="1.0">` +
|
|
52
|
+
`<EnvioLibro ID="${this.id}">${caratulaXml}${resumenXml}${detalleXml}<TmstFirma>${tmstFirma}</TmstFirma></EnvioLibro>` +
|
|
53
|
+
`</LibroGuia>`;
|
|
54
|
+
|
|
55
|
+
// Usar firmar() heredado de LibroBase
|
|
56
|
+
this.xml = this.firmar(xmlSinFirma, 'EnvioLibro', 'LibroGuia');
|
|
57
|
+
return this.xml;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
_renderCaratula(includeVersion = false) {
|
|
61
|
+
const c = this.caratula || {};
|
|
62
|
+
const fields = [
|
|
63
|
+
'RutEmisorLibro',
|
|
64
|
+
'RutEnvia',
|
|
65
|
+
'PeriodoTributario',
|
|
66
|
+
'FchResol',
|
|
67
|
+
'NroResol',
|
|
68
|
+
'TipoLibro',
|
|
69
|
+
'TipoEnvio',
|
|
70
|
+
'FolioNotificacion',
|
|
71
|
+
];
|
|
72
|
+
|
|
73
|
+
let xml = includeVersion ? '<Caratula version="1.0">' : '<Caratula>';
|
|
74
|
+
for (const f of fields) {
|
|
75
|
+
if (f === 'NroResol') {
|
|
76
|
+
xml += `<NroResol>${this._escapeXmlText(String(c.NroResol !== undefined ? c.NroResol : '0'))}</NroResol>`;
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
if (c[f] !== undefined && c[f] !== null && c[f] !== '') {
|
|
80
|
+
xml += `<${f}>${this._escapeXmlText(String(c[f]))}</${f}>`;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
xml += '</Caratula>';
|
|
84
|
+
return xml;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
_renderResumen() {
|
|
88
|
+
const resumen = this._buildResumenPeriodo();
|
|
89
|
+
if (!resumen) return '';
|
|
90
|
+
|
|
91
|
+
const order = [
|
|
92
|
+
'TotFolAnulado',
|
|
93
|
+
'TotGuiaAnulada',
|
|
94
|
+
'TotGuiaVenta',
|
|
95
|
+
'TotMntGuiaVta',
|
|
96
|
+
'TotTraslado',
|
|
97
|
+
];
|
|
98
|
+
|
|
99
|
+
let xml = '<ResumenPeriodo>';
|
|
100
|
+
order.forEach((key) => {
|
|
101
|
+
const value = resumen[key];
|
|
102
|
+
if (value === undefined || value === null || value === '' || value === false) return;
|
|
103
|
+
|
|
104
|
+
if (Array.isArray(value)) {
|
|
105
|
+
value.forEach((item) => {
|
|
106
|
+
if (item && typeof item === 'object') {
|
|
107
|
+
xml += `<${key}>`;
|
|
108
|
+
Object.keys(item).forEach((itemKey) => {
|
|
109
|
+
if (item[itemKey] !== undefined && item[itemKey] !== null && item[itemKey] !== '') {
|
|
110
|
+
xml += `<${itemKey}>${this._escapeXmlText(String(item[itemKey]))}</${itemKey}>`;
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
xml += `</${key}>`;
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
} else {
|
|
117
|
+
xml += `<${key}>${this._escapeXmlText(String(value))}</${key}>`;
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
xml += '</ResumenPeriodo>';
|
|
121
|
+
return xml;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
_renderDetalle() {
|
|
125
|
+
if (!this.detalle.length) return '';
|
|
126
|
+
|
|
127
|
+
const order = [
|
|
128
|
+
'Folio', 'Anulado', 'Operacion', 'TpoOper', 'FchDoc', 'RUTDoc',
|
|
129
|
+
'RznSoc', 'MntNeto', 'TasaImp', 'IVA', 'MntTotal', 'MntModificado',
|
|
130
|
+
'TpoDocRef', 'FolioDocRef', 'FchDocRef',
|
|
131
|
+
];
|
|
132
|
+
|
|
133
|
+
let xml = '';
|
|
134
|
+
for (const d of this.detalle) {
|
|
135
|
+
const normalized = {
|
|
136
|
+
Folio: null,
|
|
137
|
+
Anulado: null,
|
|
138
|
+
Operacion: null,
|
|
139
|
+
TpoOper: null,
|
|
140
|
+
FchDoc: null,
|
|
141
|
+
RUTDoc: null,
|
|
142
|
+
RznSoc: null,
|
|
143
|
+
MntNeto: null,
|
|
144
|
+
TasaImp: 0,
|
|
145
|
+
IVA: 0,
|
|
146
|
+
MntTotal: null,
|
|
147
|
+
MntModificado: null,
|
|
148
|
+
TpoDocRef: null,
|
|
149
|
+
FolioDocRef: null,
|
|
150
|
+
FchDocRef: null,
|
|
151
|
+
...d,
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
// Calcular IVA si no existe
|
|
155
|
+
if ((!normalized.IVA || Number(normalized.IVA) === 0) && normalized.TasaImp && normalized.MntNeto) {
|
|
156
|
+
const neto = Number(normalized.MntNeto);
|
|
157
|
+
const tasa = Number(normalized.TasaImp);
|
|
158
|
+
if (Number.isFinite(neto) && Number.isFinite(tasa)) {
|
|
159
|
+
normalized.IVA = Math.round(neto * (tasa / 100));
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// Calcular MntTotal si no existe
|
|
164
|
+
if (normalized.MntTotal === null || normalized.MntTotal === undefined || normalized.MntTotal === '') {
|
|
165
|
+
const neto = Number(normalized.MntNeto) || 0;
|
|
166
|
+
const iva = Number(normalized.IVA) || 0;
|
|
167
|
+
normalized.MntTotal = neto + iva;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
xml += '<Detalle>';
|
|
171
|
+
order.forEach((key) => {
|
|
172
|
+
const value = normalized[key];
|
|
173
|
+
if (value === undefined || value === null || value === '' || value === false) return;
|
|
174
|
+
xml += `<${key}>${this._escapeXmlText(String(value))}</${key}>`;
|
|
175
|
+
});
|
|
176
|
+
xml += '</Detalle>';
|
|
177
|
+
}
|
|
178
|
+
return xml;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
_buildResumenPeriodo() {
|
|
182
|
+
if (!this.detalle.length) return null;
|
|
183
|
+
|
|
184
|
+
const resumen = {
|
|
185
|
+
TotFolAnulado: false,
|
|
186
|
+
TotGuiaAnulada: false,
|
|
187
|
+
TotGuiaVenta: 0,
|
|
188
|
+
TotMntGuiaVta: 0,
|
|
189
|
+
TotTraslado: false,
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
for (const d of this.detalle) {
|
|
193
|
+
const anulado = Number(d.Anulado);
|
|
194
|
+
if (anulado === 1 || anulado === 2) {
|
|
195
|
+
if (anulado === 1) {
|
|
196
|
+
resumen.TotFolAnulado = (resumen.TotFolAnulado || 0) + 1;
|
|
197
|
+
} else {
|
|
198
|
+
resumen.TotGuiaAnulada = (resumen.TotGuiaAnulada || 0) + 1;
|
|
199
|
+
}
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const tpoOper = Number(d.TpoOper);
|
|
204
|
+
const mntTotal = Number(d.MntTotal || 0);
|
|
205
|
+
|
|
206
|
+
if (tpoOper === 1) {
|
|
207
|
+
resumen.TotGuiaVenta += 1;
|
|
208
|
+
resumen.TotMntGuiaVta += mntTotal;
|
|
209
|
+
} else if (!Number.isNaN(tpoOper)) {
|
|
210
|
+
if (!resumen.TotTraslado) resumen.TotTraslado = [];
|
|
211
|
+
let item = resumen.TotTraslado.find((t) => Number(t.TpoTraslado) === tpoOper);
|
|
212
|
+
if (!item) {
|
|
213
|
+
item = { TpoTraslado: tpoOper, CantGuia: 0, MntGuia: 0 };
|
|
214
|
+
resumen.TotTraslado.push(item);
|
|
215
|
+
}
|
|
216
|
+
item.CantGuia += 1;
|
|
217
|
+
item.MntGuia += mntTotal;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
return resumen;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
module.exports = LibroGuia;
|