-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-dtes.js
More file actions
362 lines (324 loc) · 13.3 KB
/
generate-dtes.js
File metadata and controls
362 lines (324 loc) · 13.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
'use strict';
const fs = require('fs-extra');
const path = require('path');
const { create } = require('xmlbuilder2');
const {
getExpiryDteFormattedDate,
getIssueDteFormattedDate,
getHastaDteFormattedDate,
getDesdeDteFormattedDate,
getTedFormattedTimeStamp,
} = require('./util-date.js');
const { getSheetData, cN } = require('./database.js');
const { generateCer } = require('./extract-keys.js');
const paths = require('./paths.js');
const primerFolioDisponiblePath = paths.getPrimerFolioDisponiblePath();
const cafPath = paths.getCaf39Path();
const cafPrivateKeyPath = paths.getCaf39PrivateKeyPath();
const templatePath = paths.getTemplate39Path();
const cantidadFoliosEmitidosPath = paths.getCantidadFoliosEmitidosPath();
const montoNetoBoletasPath = paths.getMontoNetoBoletasPath();
const montoIvaBoletasPath = paths.getMontoIvaBoletasPath();
const montoExentoBoletasPath = paths.getMontoExentoBoletasPath();
const montoTotalBoletasPath = paths.getMontoTotalBoletasPath();
let dteClientData;
function addDetalle(detalleObjectArray, nroLinDet, qtyItem, unmdItem) {
if (qtyItem) {
detalleObjectArray.forEach(detalle => {
dteClientData.Detalle.push({
NroLinDet: nroLinDet++,
NmbItem: detalle.nmbItem,
DscItem: detalle.dscItem,
QtyItem: qtyItem,
UnmdItem: unmdItem,
PrcItem: detalle.prcItem,
MontoItem: detalle.montoItem,
});
});
}
return nroLinDet;
}
function addDscRcg(dscRcgObject, nroLinDR) {
dscRcgObject.forEach(dscRcg => {
if (dscRcg.valorDR) {
dteClientData.DscRcgGlobal.push({
NroLinDR: nroLinDR++,
TpoMov: dscRcg.tpoMov,
GlosaDR: dscRcg.glosaDR,
TpoValor: dscRcg.tpoValor,
ValorDR: dscRcg.valorDR,
IndExeDR: dscRcg.indExeDR,
});
}
});
}
async function buildClientDte() {
try {
const logOutput = [];
const excelDataObject = await getSheetData(0); // 0 = main excel, 1 = test excel
// Read the CAF.xml file as utf8
const cafFileContents = await fs.readFile(cafPath, 'utf8');
// Parse CafFileContents to Object
const cafFileObject = create(cafFileContents).end({ format: 'object' });
// Create cafObject from the CAF section
const cafObject = { CAF: cafFileObject.AUTORIZACION.CAF };
// Extract Private Key from CAF.xml
let cafPrivateKey = cafFileObject.AUTORIZACION.RSASK;
await fs.writeFile(cafPrivateKeyPath, cafPrivateKey);
let nroTotalBoletas = 0;
for (const [_, number] of excelDataObject.entries()) {
if (!number[cN().number]) break;
nroTotalBoletas++;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////FIXED DATA//////////////////////////////////////////////////////
let montoTotalBoletas = 0;
let montoNetoBoletas = 0;
let montoIvaBoletas = 0;
let montoExentoBoletas = 0;
const rutEmisor = String(excelDataObject[0][cN().rutEmisor]).toUpperCase().trim();
const rznSocEmisor = String(excelDataObject[0][cN().rznSocEmisor]).split(/\s+/).join(' ').trim().slice(0, 100);
const giroEmisor = String(excelDataObject[0][cN().giroEmisor]).split(/\s+/).join(' ').trim().slice(0, 80);
const tipoDte = 39;
const indServicio = excelDataObject[0][cN().indServicio];
const rutProvSw = rutEmisor;
const rutEnvia = String(excelDataObject[0][cN().rutEnvia]).toUpperCase().trim();
const rutReceptor = String(excelDataObject[0][cN().rutReceptor]).toUpperCase().trim();
const fchResol = String(excelDataObject[0][cN().fchResol]).toUpperCase().trim();
const nroResol = excelDataObject[0][cN().nroResol];
const periodoDesde = getDesdeDteFormattedDate();
const periodoHasta = getHastaDteFormattedDate();
const fchEmis = getIssueDteFormattedDate();
const fchVenc = getExpiryDteFormattedDate();
const timeStamp = getTedFormattedTimeStamp();
const firmaSig = '@!FRMT-SIG!@';
const signature = '@!SIGNATURE!@';
const nroDte = '@!NUM-DTE!@';
const dteSet = '@!SET-OF-DTE!@';
let folio = Number(await fs.readFile(primerFolioDisponiblePath, 'binary'));
let dtePath;
let currentBoleta = 1;
const logNroTotalBoletas = `Processing ${nroTotalBoletas} boletas...`;
console.log(logNroTotalBoletas);
const nroBoletas = nroTotalBoletas; // REMOVE
for (let i = 0; i < nroBoletas; i++) {
if (excelDataObject[i][cN().isFactura]) continue;
dtePath = path.join(__dirname, 'public', 'output', 'boletas', 'dtes', 'unsigned', `dte${currentBoleta}.xml`);
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////DATA//////////////////////////////////////////////////////
let nroLinDR = 1;
let nroLinDet = 1;
let nroLinRef = 1;
const rutRecep = String(excelDataObject[i][cN().rutRecep]).toUpperCase().trim();
const cdgIntRecep = String(excelDataObject[i][cN().cdgIntRecep]).trim();
const rznSocRecep = String(excelDataObject[i][cN().rznSocRecep]).split(/\s+/).join(' ').trim();
const correo = excelDataObject[i][cN().correo] ? String(excelDataObject[i][cN().correo]).trim() : null;
const dirRecep = String(excelDataObject[i][cN().dirRecep]).split(/\s+/).join(' ').trim();
const ciudadRecep = String(excelDataObject[i][cN().ciudadRecep]).split(/\s+/).join(' ').trim();
const cmnaRecep = String(excelDataObject[i][cN().cmnaRecep]).toUpperCase().trim();
const mntNeto = Number(excelDataObject[i][cN().mntNeto]);
const iva = Number(excelDataObject[i][cN().iva]);
const mntTotal = Number(excelDataObject[i][cN().mntTotal]);
const mntExe = excelDataObject[i][cN().mntExe] ? Number(excelDataObject[i][cN().mntExe]) : null;
const saldoAnterior = Number(excelDataObject[i][cN().saldoAnterior]);
const vlrPagar = Number(excelDataObject[i][cN().vlrPagar]);
const descuento = Number(excelDataObject[i][cN().descuento]);
const subsidio = Math.abs(Number(excelDataObject[i][cN().subsidio]));
const repactacion = Number(excelDataObject[i][cN().repactacion]);
const reposicion = Number(excelDataObject[i][cN().reposicion]);
const multa = Number(excelDataObject[i][cN().multa]);
const qtyItem = Number(excelDataObject[i][cN().consumoM3]);
const unmdItem = 'M3';
const detalleObjectArray = [
{
nmbItem: cN().detalleNmbAgua,
dscItem: cN().detalleDscAgua,
prcItem: Number(excelDataObject[i][cN().costoM3Agua]),
montoItem: Number(excelDataObject[i][cN().costoTotalAgua]),
},
{
nmbItem: cN().detalleNmbAlcantarillado,
dscItem: cN().detalleDscAlcantarillado,
prcItem: Number(excelDataObject[i][cN().costoM3Alcantarillado]),
montoItem: Number(excelDataObject[i][cN().costoTotalAlcantarillado]),
},
{
nmbItem: cN().detalleNmbTratamiento,
dscItem: cN().detalleDscTratamiento,
prcItem: Number(excelDataObject[i][cN().costoM3Tratamiento]),
montoItem: Number(excelDataObject[i][cN().costoTotalTratamiento]),
},
];
const cargoFijoObjectArray = [
{
nmbItem: cN().detalleNmbCargoFijo,
dscItem: cN().detalleDscCargoFijo,
qtyItem: 1,
prcItem: Number(excelDataObject[i][cN().cargoFijo]),
montoItem: Number(excelDataObject[i][cN().cargoFijo]),
},
];
const dscRcgObject = [
{ tpoMov: 'D', glosaDR: cN().descuento, tpoValor: '$', valorDR: descuento },
{ tpoMov: 'R', glosaDR: cN().reposicion, tpoValor: '$', valorDR: reposicion },
{ tpoMov: 'R', glosaDR: cN().multa, tpoValor: '$', valorDR: multa },
{ tpoMov: 'D', glosaDR: cN().subsidio, tpoValor: '$', valorDR: subsidio, indExeDR: 1 },
{ tpoMov: 'R', glosaDR: cN().repactacion, tpoValor: '$', valorDR: repactacion, indExeDR: 1 },
];
montoNetoBoletas += mntNeto;
montoIvaBoletas += iva;
montoExentoBoletas += mntExe;
montoTotalBoletas += mntTotal;
// //////////////////////////////////////////////////////////////////////////////////
// /////////////////////////////////CLIENT DTE JSON//////////////////////////////////
dteClientData = {
Encabezado: {
IdDoc: {
TipoDTE: tipoDte,
Folio: folio,
FchEmis: fchEmis,
IndServicio: indServicio,
PeriodoDesde: periodoDesde,
PeriodoHasta: periodoHasta,
FchVenc: fchVenc,
},
Emisor: {
RUTEmisor: rutEmisor,
RznSocEmisor: rznSocEmisor,
GiroEmisor: giroEmisor,
},
Receptor: {
RUTRecep: rutRecep,
CdgIntRecep: cdgIntRecep,
RznSocRecep: rznSocRecep,
Contacto: correo,
DirRecep: dirRecep,
CmnaRecep: cmnaRecep,
CiudadRecep: ciudadRecep,
},
Totales: {
MntNeto: mntNeto,
MntExe: mntExe,
IVA: iva,
MntTotal: mntTotal,
SaldoAnterior: saldoAnterior,
VlrPagar: vlrPagar,
},
},
Detalle: [],
DscRcgGlobal: [],
// Referencia: {
// NroLinRef: nroLinRef,
// CodRef: codRef,
// RazonRef: razonRef,
// },
};
nroLinDet = addDetalle(detalleObjectArray, nroLinDet, qtyItem, unmdItem);
addDetalle(cargoFijoObjectArray, nroLinDet, 1);
addDscRcg(dscRcgObject, nroLinDR);
//////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////CLIENT TED JSON//////////////////////////////////
const ted = {
DD: {
RE: rutEmisor,
TD: tipoDte,
F: folio,
FE: fchEmis,
RR: rutRecep,
RSR: rznSocRecep,
MNT: mntTotal,
IT1: cN().detalleDscAgua,
CAF: cafObject.CAF,
TSTED: timeStamp,
},
FRMT: { '@algoritmo': 'SHA1withRSA', '#': firmaSig },
};
// Create a Document out of the signedTedString and parse to Object
const tedObject = create().ele('TED', { version: '1.0' }).ele(ted).end({ format: 'object' });
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Combine DTE Client Object with TED Object and add a Timestamp to the end
const dteObject = { ...dteClientData, ...tedObject };
// Create a DTE Document from the combined data
const dteDoc = create()
// Add the root element 'DTE' with its version attribute
.ele('DTE', { version: '1.0' })
// Add the 'Documento' element including RUTEmisor, TipoDTE and Folio
.ele('Documento', { ID: `F${folio}_T${tipoDte}` })
// Add the dteObject data
.ele(dteObject)
.up()
.ele('TmstFirma')
.txt(timeStamp)
.up()
.up()
.ele('Signature')
.txt(signature);
// Convert the built document structure into a formatted XML string.
const dteXml = dteDoc.end({ prettyPrint: true }).replace('<?xml version="1.0"?>\n', '');
await fs.writeFile(dtePath, dteXml);
folio++;
nroLinRef++;
currentBoleta++;
}
// Create Document from the DteSobreObject, addding required attributes
const dteSobreDoc = create({ version: '1.0', encoding: 'ISO-8859-1' })
.ele('EnvioBOLETA', {
'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
'xsi:schemaLocation': 'http://www.sii.cl/SiiDte EnvioBOLETA_v11.xsd',
xmlns: 'http://www.sii.cl/SiiDte',
version: '1.0',
})
.ele('SetDTE', { ID: 'SetDoc' })
.ele('Caratula', { version: '1.0' })
.ele('RutEmisor')
.txt(rutEmisor)
.up()
.ele('RutEnvia')
.txt(rutEnvia)
.up()
.ele('RutReceptor')
.txt(rutReceptor)
.up()
.ele('FchResol')
.txt(fchResol)
.up()
.ele('NroResol')
.txt(nroResol)
.up()
.ele('TmstFirmaEnv')
.txt(timeStamp)
.up()
.ele('SubTotDTE')
.ele('TpoDTE')
.txt(tipoDte)
.up()
.ele('NroDTE')
.txt(nroDte)
.up()
.up()
.up()
.ele('DTE')
.txt(dteSet)
.up()
.up()
.ele('Signature')
.txt(signature);
// Parse the Sobre Doc to prettyPrinted XML format
const dteSobreXml = dteSobreDoc.end({ prettyPrint: true });
const logSobre = `Unsigned DTE's created successfully...`;
console.log(logSobre);
await fs.writeFile(templatePath, dteSobreXml);
await fs.writeFile(cantidadFoliosEmitidosPath, String(nroBoletas));
await fs.writeFile(montoNetoBoletasPath, String(montoNetoBoletas));
await fs.writeFile(montoIvaBoletasPath, String(montoIvaBoletas));
await fs.writeFile(montoExentoBoletasPath, String(montoExentoBoletas));
await fs.writeFile(montoTotalBoletasPath, String(montoTotalBoletas));
await generateCer();
logOutput.push(logNroTotalBoletas, logSobre);
return logOutput;
} catch (error) {
console.log(`XML build has failed: ${error}`);
}
}
module.exports = { buildClientDte };