bonsaif 1.10.3

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/lib/utl.js ADDED
@@ -0,0 +1,1422 @@
1
+ /**
2
+ * ::: B[]NSAIF() ::: => 2022
3
+ */
4
+
5
+ 'use strict';
6
+ /**
7
+ * console.log con estilo de color
8
+ * @param {string} msg mensaje de log
9
+ * @param {<obj>} obj Objeto o string
10
+ */
11
+
12
+ const log=(msg, c, o)=>{
13
+ let color ='';
14
+ const color_white = "\x1b[37m", color_yellow = "\x1b[33m";
15
+ switch (c){
16
+ case 'black': color = "\x1b[30m"; break;
17
+ case 'green': color = "\x1b[32m"; break;
18
+ case 'red': color = "\x1b[31m"; break;
19
+ case 'green': color = "\x1b[32m"; break;
20
+ case 'yellow': color = "\x1b[33m"; break;
21
+ case 'blue': color = "\x1b[34m"; break;
22
+ case 'purple':
23
+ case 'magenta': color = "\x1b[35m"; break;
24
+ case 'cyan': color = "\x1b[36m"; break;
25
+ case 'white': color = "\x1b[37m"; break;
26
+ case 'gray': color = "\x1b[38m"; break;
27
+
28
+ default:
29
+ if (c){
30
+ o = c;
31
+ }
32
+ color = "\x1b[32m";
33
+ }
34
+ if (!o){
35
+ console.log(color,'['+dateHour()+']',color_white , msg);
36
+ }else{
37
+ console.log(color,'['+dateHour()+']',color_yellow, msg, color_white, o);
38
+ }
39
+ }
40
+
41
+ const addZero=(i)=> {
42
+ if (i < 10) { i = "0" + i; }
43
+ return i;
44
+ }
45
+
46
+ const getIp=(req)=>{
47
+ let ip ='';
48
+ try{
49
+ ip =
50
+ (req.headers['x-forwarded-for'] || '').split(',').pop() ||
51
+ req.socket.remoteAddress ||
52
+ req.connection.socket.remoteAddress ||
53
+ req.connection.remoteAddress ;
54
+ //2019/07/04 VRSZ Validacion de IPV6
55
+ ip = ip.replace('::ffff:', '');
56
+
57
+ }catch(e){
58
+ }
59
+ if (!ip){
60
+ ip = '127.0.0.1'
61
+ }
62
+ return ip;
63
+ }
64
+
65
+ const milisegundosASegundos=(milisegundos)=>(milisegundos / 1000);
66
+
67
+ const miliseconds_to_seconds=(milisegundos)=>(milisegundos / 1000);
68
+
69
+ const dateFormat=(format, date)=>{
70
+ const dayjs = require('dayjs');
71
+ let today = date ? dayjs(date) : dayjs();
72
+ return today.format(format);
73
+ }
74
+
75
+ const date_format=(format, date)=>{
76
+ const dayjs = require('dayjs');
77
+ let today = date ? dayjs(date) : dayjs();
78
+ return today.format(format);
79
+ }
80
+
81
+ const dateHour=()=>date()+' '+hour();
82
+
83
+ const date_hour=()=>date()+' '+hour();
84
+
85
+ const date=(format)=>{
86
+ let date='';
87
+ try{
88
+ let d = new Date();
89
+ if (format==null){
90
+ date = d.getFullYear()+'-'+addZero(d.getMonth()+1)+'-'+addZero(d.getDate());
91
+ }else{
92
+ const dayjs = require('dayjs');
93
+ let today = dayjs();
94
+ date = today.format(format);
95
+ }
96
+ }catch(e){
97
+ log('err.date:'+e);
98
+ }
99
+ return date;
100
+ }
101
+
102
+ const hour=()=>{
103
+ let hour='';
104
+ try{
105
+ let d = new Date();
106
+ hour = addZero(d.getHours())+':'+addZero(d.getMinutes())+":"+addZero(d.getSeconds());
107
+ }catch(e){
108
+ log('err.hour:'+e);
109
+ }
110
+ return hour;
111
+ }
112
+
113
+ const dateHourFull=()=>date()+' '+hourFull();
114
+
115
+ const date_hour_full=()=>date()+' '+hourFull();
116
+
117
+ const hourFull=()=>{
118
+ let hour='';
119
+ try{
120
+ let d = new Date();
121
+ hour = addZero(d.getHours())+':'+addZero(d.getMinutes())+":"+addZero(d.getSeconds())+":"+d.getMilliseconds();
122
+ }catch(e){
123
+ log('err.hour:'+e);
124
+ }
125
+ return hour;
126
+ }
127
+
128
+ //2019/08/25 VRSZ Ordenar json
129
+ const sort=(data, key, orden)=> {
130
+ orden = orden==null?'asc':orden!=''?orden:'asc';
131
+ if (orden!=''){
132
+ orden = orden.toLowerCase() ;
133
+ }
134
+
135
+ try{
136
+ return data.sort(function (a, b) {
137
+ let x = a[key], y = b[key];
138
+ x = Number.isInteger(x*1) ? x*1: x;
139
+ y = Number.isInteger(y*1) ? y*1: y;
140
+
141
+ if (orden === 'asc') {
142
+ return ((x < y) ? -1 : ((x > y) ? 1 : 0));
143
+ }
144
+
145
+ if (orden === 'desc') {
146
+ return ((x > y) ? -1 : ((x < y) ? 1 : 0));
147
+ }
148
+ });
149
+ }catch(e){
150
+ log('e.sort:'+e);
151
+ return data;
152
+ }
153
+ }
154
+
155
+ //2022/04/27 VRSZ Convertir ArrayString a ArrayJson
156
+ const ArraytoJson=(ArrayString)=>{
157
+ let ArrayJson = new Array();
158
+ try{
159
+ for (let x of ArrayString){
160
+ const xjson = JSON.parse(x);
161
+ ArrayJson.push(xjson);
162
+ }
163
+ return ArrayJson;
164
+ }catch(e){
165
+ log('err.ArraytoJson '+e);
166
+ return ArrayString;
167
+ }
168
+ }
169
+
170
+ const array_to_json=(ArrayString)=>{
171
+ let ArrayJson = new Array();
172
+ try{
173
+ for (let x of ArrayString){
174
+ const xjson = JSON.parse(x);
175
+ ArrayJson.push(xjson);
176
+ }
177
+ return ArrayJson;
178
+ }catch(e){
179
+ log('err.ArraytoJson '+e);
180
+ return ArrayString;
181
+ }
182
+ }
183
+
184
+ const isObjectEmpty=(obj)=> Object.keys(obj).length === 0;
185
+
186
+ const is_object_empty=(obj)=> Object.keys(obj).length === 0;
187
+
188
+ //2022/04/28 Ejecuta multiples funciones de abajo hacia arriba
189
+ const compose = (...fns) => x=> fns.reduceRight((x, f) => f(y), x);
190
+
191
+ //2022/04/28 Ejecuta multiples funciones de arriba hacia abajo
192
+ const pipe = (...fns) => x=> fns.reduce((x, f) => f(y), x);
193
+
194
+ //2022/04/28 realizar traza con la funcion de compose y pipe
195
+ const trace = x => y => console.log(x,y);
196
+
197
+ const find = f => xs => xs.find(f);
198
+
199
+ const filter = f => xs => xs.filter(f);
200
+
201
+ const hex_to_ascii=(str1)=>{
202
+ let hex = str1.toString();
203
+ let str = '';
204
+ for (let n = 0; n < hex.length; n += 2) {
205
+ str += String.fromCharCode(parseInt(hex.substr(n, 2), 16));
206
+ }
207
+ return str;
208
+ }
209
+
210
+ const traceId=(tag)=>{
211
+ tag = tag!=null?tag+':':'';
212
+ return tag +dateHour()+':'+random({length:4});
213
+ }
214
+
215
+ const trace_id=(tag)=>{
216
+ tag = tag!=null?tag+':':'';
217
+ return tag +dateHour()+':'+random({length:4});
218
+ }
219
+
220
+ const random=(o)=>{
221
+ o = o ? o : {};
222
+ const {min=0, max=0, length =0, string=false, special_characters=''}=o;
223
+ let opt = 0;
224
+ let hexDigits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
225
+ let numero = "0123456789";
226
+ let especial = special_characters ? special_characters : hexDigits;
227
+ let randString = "";
228
+
229
+ if (min>0 && max >0){
230
+ opt = 1;
231
+ }
232
+ if (length>0){
233
+ opt = 2;
234
+ }
235
+ if (string){
236
+ opt = 3;
237
+ for (let i = 0; i < length-2; i++){
238
+ randString += hexDigits.charAt(Math.floor(Math.random() * hexDigits.length));
239
+ }
240
+ randString += numero.charAt(Math.floor(Math.random() * numero.length));
241
+ randString += especial.charAt(Math.floor(Math.random() * especial.length));
242
+ }
243
+ switch (opt){
244
+ case 1: return Math.floor(Math.random() * (max - min)) + min;
245
+ case 2: return (Math.pow(10,length).toString().slice(length-1) + Math.floor((Math.random()*Math.pow(10,length))+1).toString()).slice(-length);
246
+ case 3: return randString;
247
+ default: return Math.random();
248
+ }
249
+ };
250
+
251
+ const valueIn=(o)=>{
252
+ let vin = o.in != null ? o.in.split(',') : '';
253
+ let v = o.value != null ? o.value.split(',') : '';
254
+
255
+ for (let xv of v){
256
+ for (let xvin of vin ){
257
+ if (xv == xvin){
258
+ return true; break;
259
+ }
260
+ }
261
+ }
262
+
263
+ return false;
264
+ }
265
+
266
+ const value_in=(o)=>{
267
+ let vin = o.in != null ? o.in.split(',') : '';
268
+ let v = o.value != null ? o.value.split(',') : '';
269
+
270
+ for (let xv of v){
271
+ for (let xvin of vin ){
272
+ if (xv == xvin){
273
+ return true; break;
274
+ }
275
+ }
276
+ }
277
+
278
+ return false;
279
+ }
280
+
281
+ //2022/04/08 VRSZ Ajuste para obtener solo los campos principales
282
+ const ObjectEmpty = (obj, target) =>{
283
+ try{
284
+ for (let key in obj){
285
+ if (obj.hasOwnProperty(key)) {
286
+ if (key.toLowerCase()==target.toLowerCase()){
287
+ return true;
288
+ }
289
+ }
290
+ }
291
+ }catch(e){
292
+ log('err.ObjectEmpty:'+e);
293
+ }
294
+ return false;
295
+ }
296
+
297
+ const object_empty = (obj, target) =>{
298
+ try{
299
+ for (let key in obj){
300
+ if (obj.hasOwnProperty(key)) {
301
+ if (key.toLowerCase()==target.toLowerCase()){
302
+ return true;
303
+ }
304
+ }
305
+ }
306
+ }catch(e){
307
+ log('err.ObjectEmpty:'+e);
308
+ }
309
+ return false;
310
+ }
311
+
312
+ const ObjectId = (m = Math, d = Date, h = 16, s = s => m.floor(s).toString(h)) =>
313
+ s(d.now() / 1000) + ' '.repeat(h).replace(/./g, () => s(m.random() * h))
314
+
315
+ const object_id = (m = Math, d = Date, h = 16, s = s => m.floor(s).toString(h)) =>
316
+ s(d.now() / 1000) + ' '.repeat(h).replace(/./g, () => s(m.random() * h))
317
+
318
+ /* uuid({mask:'xxxx_xxxx'})*/
319
+ const uuid=(o)=>{
320
+ o = o !=null ? o : {};
321
+ let {mask='xxxxxxxx-xxxx-xxxx-yxxx-xxxxxxxxxxxx'} = o;
322
+ let dt = new Date().getTime();
323
+ let uuid = '';
324
+ uuid = mask.replace(/[xy]/g, function(c) {
325
+ let r = (dt + Math.random()*16)%16 | 0;
326
+ dt = Math.floor(dt/16);
327
+ return (c=='x' ? r :(r&0x3|0x8)).toString(16);
328
+ });
329
+ return uuid;
330
+ }
331
+
332
+ class Timer{
333
+ constructor(o){
334
+ const {inputs=[], time=0, countdown=false, debug=false, callback, hearbeat={} }=o ? o : {};
335
+ this.blnTimer = false;
336
+ this.timeIni = 0;
337
+ this.timerId = 0;
338
+ this.time = time;
339
+ this.inputs = inputs;
340
+ this.timeDefault = time;
341
+ this.debug =debug;
342
+ this.countdown = countdown;
343
+ this.callback = callback;
344
+ this.hearbeat = hearbeat;
345
+ }
346
+ start(){
347
+ if (!this.blnTimer){
348
+ this.timeIni = new Date();
349
+ this.timerId =setInterval(() => {this.chrono();}, 1000);
350
+ this.blnTimer = true;
351
+ }
352
+ }
353
+ stop(){
354
+ if (this.blnTimer){
355
+ clearTimeout(this.timerId);
356
+ this.timeIni = 0;
357
+ this.timerId =0;
358
+ this.blnTimer = false;
359
+ }
360
+ }
361
+ reset(time){
362
+ this.stop();
363
+ this.time = time?time:0;
364
+ this.timeDefault = time?time:0;
365
+ this.start();
366
+ }
367
+ chrono(){
368
+ let timeActual = new Date();
369
+ let diff = Math.round(timeActual.getTime() / 1000) - Math.round(this.timeIni.getTime() / 1000);
370
+ this.time = this.countdown ? (this.timeDefault) - (diff*1) : (diff*1)+this.timeDefault ;
371
+ this.show();
372
+ if (this.countdown && this.time=='0'){
373
+ this.stop();
374
+ this.callback ? this.callback() : '';
375
+ }
376
+ try{ // 2022/11/06 Heartbeat
377
+ let {pulse=0, timeIni=0, startEvent = false} = this.hearbeat ? this.hearbeat: {};
378
+ if (pulse>0){
379
+ if (startEvent){
380
+ this.hearbeat.startEvent = false;
381
+ this.hearbeat.event ? this.hearbeat.event(0) : '';
382
+ }
383
+ timeIni == 0 ? this.hearbeat.timeIni = timeActual : '';
384
+ let diffpulse = Math.round(timeActual.getTime() / 1000) - Math.round(this.hearbeat.timeIni.getTime() / 1000);
385
+ if ( diffpulse >= pulse ){
386
+ this.hearbeat.timeIni = 0;
387
+ this.hearbeat.event ? this.hearbeat.event(diffpulse) : '';
388
+ }
389
+ }
390
+ }catch(e){
391
+ console.log('heartbeat.err',e);
392
+ }
393
+ this.debug ? console.log(' date => countdown['+this.countdown+'] '+this.timeIni+' Time ==>'+this.time+' display =>' +this.display(this.time)) : '';
394
+ }
395
+ getTime(){
396
+ return this.time;
397
+ }
398
+ display(time){
399
+ let hours = Math.floor(time / 3600);
400
+ let minutes = Math.floor((time - (hours * 3600)) / 60);
401
+ let seconds = time - (hours * 3600) - (minutes * 60);
402
+ if (hours < 10) {hours = "0"+hours;}
403
+ if (minutes < 10) {minutes = "0"+minutes;}
404
+ if (seconds < 10) {seconds = "0"+seconds;}
405
+ return hours+':'+minutes+':'+seconds;
406
+ }
407
+ show(){
408
+ this.inputs.forEach(x=>{const {id='', property='innerHTML', display=false} = x; OB_(id) ? eval (`OB_('${id}').${property}='${display? this.display(this.time) :this.time}';`) : '';});
409
+ }
410
+ }
411
+
412
+ class Sauron {
413
+ constructor(o) {
414
+ Object.assign(this, o);
415
+ this.observers = [];
416
+ }
417
+ notify(topic, data){
418
+ //console.log(`notify "${topic}"`, this.observers);
419
+ if(this.observers[topic]){
420
+ this.observers[topic].forEach(observer => observer.fn(data));
421
+ }else{
422
+ console.log(`No existe topico: ${topic}`);
423
+ }
424
+ }
425
+ subscribe(topic, observer){
426
+ if(!this.observers[topic]){
427
+ this.observers[topic] = new Array();
428
+ }
429
+ //console.log(`suscribiendo a "${topic}"`, this.observers[topic]);
430
+ this.observers[topic].push(observer);
431
+ }
432
+ unsubscribeTopic(topic, id) {
433
+ //console.log(`unsuscribe :${id}`);
434
+ this.observers[topic] = this.observers[topic].filter(subscriber => subscriber.id !== id);
435
+ }
436
+ }
437
+
438
+ Date.prototype.getWeekNumber = function () {
439
+ let d = new Date(+this); //Creamos un nuevo Date con la fecha de "this".
440
+ d.setHours(0, 0, 0, 0); //Nos aseguramos de limpiar la hora.
441
+ d.setDate(d.getDate() + 4 - (d.getDay() || 7)); // Recorremos los días para asegurarnos de estar "dentro de la semana"
442
+ //Finalmente, calculamos redondeando y ajustando por la naturaleza de los números en JS:
443
+ return Math.ceil((((d - new Date(d.getFullYear(), 0, 1)) / 8.64e7) + 1) / 7);
444
+ };
445
+
446
+ const getId_key=(o)=>{ // Genera Identificador Unico Ultimo Digito del Anio+dia de la semana 2 digitos + hora 2 digitos + min 2 digitos + random 4 digitos
447
+ let ID = '';
448
+ const {mask='',length=6, token = ''}=o?o:{};
449
+ let extra = random({length});
450
+
451
+ if (mask!=''){
452
+ extra = uuid({mask});
453
+ }
454
+
455
+ try{
456
+ let dt = new Date();
457
+ let YY = dt.getFullYear().toString().substr(-2);
458
+ let SW = addZero(dt.getWeekNumber());
459
+ let Hora = addZero(dt.getHours())+''+addZero(dt.getMinutes())+''+addZero(dt.getSeconds())+token+extra;
460
+ ID = YY+''+SW+'-'+Hora;
461
+ ID = ID.toUpperCase();
462
+ }catch(e){
463
+ console.log(e);
464
+ }
465
+ return ID;
466
+ }
467
+
468
+ const get_id_key=(o)=>{ // Genera Identificador Unico Ultimo Digito del Anio+dia de la semana 2 digitos + hora 2 digitos + min 2 digitos + random 4 digitos
469
+ let ID = '';
470
+ const {mask='',length=6, token = ''}=o?o:{};
471
+ let extra = random({length});
472
+
473
+ if (mask!=''){
474
+ extra = uuid({mask});
475
+ }
476
+
477
+ try{
478
+ let dt = new Date();
479
+ let YY = dt.getFullYear().toString().substr(-2);
480
+ let SW = addZero(dt.getWeekNumber());
481
+ let Hora = addZero(dt.getHours())+''+addZero(dt.getMinutes())+''+addZero(dt.getSeconds())+token+extra;
482
+ ID = YY+''+SW+'-'+Hora;
483
+ ID = ID.toUpperCase();
484
+ }catch(e){
485
+ console.log(e);
486
+ }
487
+ return ID;
488
+ }
489
+
490
+ const health_check=(o)=>{
491
+ try{
492
+ const {uri='', pulse=0, user='', pass='' } = o;
493
+ if (uri==''){
494
+ log('healthCheck.notUri:', o);
495
+ return;
496
+ }
497
+ const timerHelth= new Timer({
498
+ hearbeat:{pulse, startEvent:true,
499
+ event:function(pulseEvent){
500
+ const request = require('request');
501
+ let auth = "Basic " + Buffer.from(user + ":" + pass).toString("base64");
502
+ o.pulseEvent = pulseEvent;
503
+ o.date = dateHour();
504
+ const options = {
505
+ url:uri,
506
+ headers:{
507
+ 'Content-Type': 'application/json',
508
+ 'authorization': auth
509
+ },
510
+ body: JSON.stringify(o)
511
+ }
512
+ request.post(options, function(err, resp, body) {
513
+ if (err) {
514
+ log('healthCheck.err', err);
515
+ }else{
516
+ log('healthCheck.hearbeat', resp.statusCode);
517
+ }
518
+ })
519
+ }
520
+ }
521
+ });
522
+ timerHelth.start();
523
+ }catch(e){
524
+ log('healthCheck.err',e);
525
+ }
526
+ }
527
+
528
+ const endpointAuth=(json)=>{
529
+ let obj;
530
+ try{
531
+ let {o = {}, req = {}} = json ? json : {};
532
+ let {authorization}=req.headers ? req.headers : {};
533
+ obj = {...o};
534
+ if (authorization) {
535
+ let auth = new Buffer.from(authorization.split(' ')[1],'base64').toString().split(':');
536
+ obj.user = auth[0]
537
+ obj.password = auth[1];
538
+ }
539
+ }catch(e){
540
+ log('endpointAuth.err:',e)
541
+ }
542
+ return obj;
543
+ }
544
+
545
+ const endpoint_auth=(json)=>{
546
+ let obj;
547
+ try{
548
+ let {o = {}, req = {}} = json ? json : {};
549
+ let {authorization}=req.headers ? req.headers : {};
550
+ obj = {...o};
551
+ if (authorization) {
552
+ let auth = new Buffer.from(authorization.split(' ')[1],'base64').toString().split(':');
553
+ obj.user = auth[0]
554
+ obj.password = auth[1];
555
+ }
556
+ }catch(e){
557
+ log('endpointAuth.err:',e)
558
+ }
559
+ return obj;
560
+ }
561
+
562
+ const execute_command = async (o)=> {
563
+ const {command} = o;
564
+ return new Promise(function (resolve, reject) {
565
+ if (command==''){
566
+ resolve({code:400, ds_code:'no se informo comando'});
567
+ }
568
+ let exec = require('child_process').exec;
569
+ exec(command, (err, stdout, stderr) => {
570
+ if (err){
571
+ resolve({code:400, err, stderr });
572
+ }
573
+ stdout= stdout.trim();
574
+ resolve({code:200, stdout, command });
575
+ });
576
+ }
577
+ );
578
+ }
579
+
580
+ const parse_url = (url)=> {
581
+ let result=[];
582
+ try{
583
+ const re = /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
584
+ result = re .exec(url);
585
+ }catch(e){
586
+ log('parse_url.err',e);
587
+ }
588
+ return result;
589
+ }
590
+
591
+ const join = async(conjuntosUno, prefijo1, llave1, conjuntosDos, prefijo2, llave2, tipoJoin, salida=[]) => {
592
+ let res =[];
593
+ let separador = '_';
594
+ try{
595
+ if(ObjectEmpty(conjuntosUno[0],llave1) && ObjectEmpty(conjuntosDos[0],llave2) ){
596
+ let propertiesA = Object.getOwnPropertyNames(conjuntosUno[0]);
597
+ let propertiesB = Object.getOwnPropertyNames(conjuntosDos[0]);
598
+ switch(tipoJoin){
599
+ case 'right':
600
+ res = conjuntosDos.map(function(conjuntoDos) {
601
+ let obj = {};
602
+ let conjuntoC = conjuntosUno.filter(function(p) {
603
+ return p[llave1] === conjuntoDos[llave2];
604
+ })[0];
605
+ propertiesA.forEach((property) => {
606
+ try{
607
+ let descriptor = conjuntoC ? Object.getOwnPropertyDescriptor(conjuntoC, property) : Object.getOwnPropertyDescriptor({ property1: '' }, 'property1');
608
+ if (salida.length>0){
609
+ for (let e of salida){
610
+ if (property==e.property && prefijo1==e.prefijo){
611
+ Object.defineProperty(obj, e.alias, descriptor); break;
612
+ }
613
+ }
614
+ }else{
615
+ Object.defineProperty(obj, prefijo1+separador+property, descriptor);
616
+ }
617
+ }catch(e){
618
+ }
619
+ });
620
+ propertiesB.forEach((property) => {
621
+ try{
622
+ let descriptor = Object.getOwnPropertyDescriptor(conjuntoDos, property);
623
+ if (salida.length>0){
624
+ for (let e of salida){
625
+ if (property==e.property && prefijo2==e.prefijo){
626
+ Object.defineProperty(obj, e.alias, descriptor); break;
627
+ }
628
+ }
629
+ }else{
630
+ Object.defineProperty(obj, prefijo2+separador+property, descriptor);
631
+ }
632
+ }catch(e){
633
+ }
634
+ });
635
+ if (Object.keys(obj).length!==0){
636
+ return obj;
637
+ }
638
+ });
639
+ break;
640
+ case 'left':
641
+ res = conjuntosUno.map(function(conjuntoUno) {
642
+ let obj = {}
643
+ let conjuntoC = conjuntosDos.filter(function(p) {
644
+ return p[llave2] === conjuntoUno[llave1];
645
+ })[0];
646
+ propertiesA.forEach((property) => {
647
+ try {
648
+ let descriptor = Object.getOwnPropertyDescriptor(conjuntoUno, property);
649
+ if (salida.length>0){
650
+ for (let e of salida){
651
+ if (property==e.property && prefijo1==e.prefijo){
652
+ Object.defineProperty(obj, e.alias, descriptor); break;
653
+ }
654
+ }
655
+ }else{
656
+ Object.defineProperty(obj, prefijo1+separador+property, descriptor);
657
+ }
658
+ }catch(e){
659
+ }
660
+ });
661
+ propertiesB.forEach((property) => {
662
+ try{
663
+ let descriptor = conjuntoC ? Object.getOwnPropertyDescriptor(conjuntoC, property) : Object.getOwnPropertyDescriptor({ property1:''}, 'property1');
664
+ if (salida.length>0){
665
+ for (let e of salida){
666
+ if (property==e.property && prefijo2==e.prefijo){
667
+ Object.defineProperty(obj, e.alias, descriptor); break;
668
+ }
669
+ }
670
+ }else{
671
+ Object.defineProperty(obj, prefijo2+separador+property, descriptor);
672
+ }
673
+ }catch(e){
674
+ }
675
+ });
676
+ if (Object.keys(obj).length!==0){
677
+ return obj;
678
+ }
679
+ });
680
+ break;
681
+ case 'inner':
682
+ res = conjuntosUno.map(function(conjuntoUno) {
683
+ let obj = {}
684
+ let conjuntoC = conjuntosDos.filter(function(p) {
685
+ return p[llave2] === conjuntoUno[llave1];
686
+ })[0];
687
+ if (conjuntoC){
688
+ propertiesA.forEach((property) => {
689
+ try{
690
+ let descriptor = Object.getOwnPropertyDescriptor(conjuntoUno, property);
691
+ if (salida.length>0){
692
+ for (let e of salida){
693
+ if (property==e.property && prefijo1==e.prefijo){
694
+ Object.defineProperty(obj, e.alias, descriptor); break;
695
+ }
696
+ }
697
+ }else{
698
+ Object.defineProperty(obj, prefijo1+separador+property, descriptor);
699
+ }
700
+ }catch(e){
701
+ }
702
+ });
703
+ propertiesB.forEach((property) => {
704
+ try{
705
+ let descriptor = conjuntoC ? Object.getOwnPropertyDescriptor(conjuntoC, property) : Object.getOwnPropertyDescriptor({ property1: '' }, 'property1');
706
+ // Valor del campo log('descriptor', descriptor);
707
+ if (salida.length>0){
708
+ for (let e of salida){
709
+ if (property==e.property && prefijo2==e.prefijo){
710
+ Object.defineProperty(obj, e.alias, descriptor); break;
711
+ }
712
+ }
713
+ }else{
714
+ Object.defineProperty(obj, prefijo2+separador+property, descriptor);
715
+ }
716
+ }catch(e){
717
+ }
718
+ });
719
+ if (Object.keys(obj).length!==0){
720
+ return obj;
721
+ }
722
+ }
723
+ });
724
+ break;
725
+ }
726
+ }else{
727
+ console.log("joins.err Ambas o alguna llave no existe, verificar argumento de la función");
728
+ }
729
+ res = res.filter(function(array) {
730
+ return array != undefined;
731
+ });
732
+ }catch(e){
733
+ console.log('joins.err', e);
734
+ }
735
+ return res;
736
+ }
737
+
738
+ const tag=(path='', split='/', ext=false)=>{
739
+ let result = '';
740
+ try{
741
+ path = path.replace(/\\/g,"/");
742
+ path = path.split(split);
743
+ if (path.length>0){
744
+ result = path[path.length-1];
745
+ if (!ext){
746
+ let result_ext=result.split('.');
747
+ try{result=result.replace('.'+result_ext[result_ext.length-1],'')}catch(e){}
748
+ }
749
+ }
750
+ }catch(e){
751
+ console.log('tag.err', e);
752
+ }
753
+ return result;
754
+ }
755
+
756
+ /**
757
+ * Convierte un json array a un json de tipo resultSet
758
+ * @param {array<String>} json example: [{id:1, ds:'|'}, {id:2, ds:'2'}]
759
+ * @param {json<string>} {} example: {dml='', time=0, results='', code=200, error=0, msg='', extra=''}
760
+ * @returns {json<string>}
761
+ */
762
+ const jsonToResultSet=async(json, {dml='', time=0, results='', code=200, error=0, msg='', extra='' }={} )=>{
763
+ let headers = "", ltheaders=[];
764
+ let columns = 0;
765
+ const rows = json;
766
+ const irows = rows.length?rows.length:0;
767
+ try{ ltheaders = Object.keys(json[0]); }catch(e){}
768
+ try{ headers = Object.keys(json[0]); headers = headers.join("|"); }catch(e){}
769
+ columns = ltheaders.length;
770
+ return {
771
+ dml,
772
+ time,
773
+ headers,
774
+ ltheaders,
775
+ columns,
776
+ rows,
777
+ irows,
778
+ nextIndex : 0,
779
+ row:{},
780
+ next:function(){
781
+ if (this.nextIndex < this.rows.length){
782
+ this.row = this.rows[this.nextIndex++];
783
+ return true;
784
+ }else{
785
+ return false;
786
+ }
787
+ },
788
+ get:function(x){
789
+ if (!isNaN(x)){
790
+ x = this.ltheaders[x];
791
+ }
792
+ return this.row[x]!=null?this.row[x]:'';
793
+ },
794
+ reset:function(){
795
+ this.nextIndex = 0;
796
+ },
797
+ results,
798
+ code,
799
+ error,
800
+ msg,
801
+ extra
802
+ }
803
+ }
804
+
805
+ const json_to_result=async(json, {dml='', time=0, results='', code=200, error=0, msg='', extra='' }={} )=>{
806
+ let headers = "", ltheaders=[];
807
+ let columns = 0;
808
+ const rows = json;
809
+ const irows = rows.length?rows.length:0;
810
+ try{ ltheaders = Object.keys(json[0]); }catch(e){}
811
+ try{ headers = Object.keys(json[0]); headers = headers.join("|"); }catch(e){}
812
+ columns = ltheaders.length;
813
+ return {
814
+ dml,
815
+ time,
816
+ headers,
817
+ ltheaders,
818
+ columns,
819
+ rows,
820
+ irows,
821
+ nextIndex : 0,
822
+ row:{},
823
+ next:function(){
824
+ if (this.nextIndex < this.rows.length){
825
+ this.row = this.rows[this.nextIndex++];
826
+ return true;
827
+ }else{
828
+ return false;
829
+ }
830
+ },
831
+ get:function(x){
832
+ if (!isNaN(x)){
833
+ x = this.ltheaders[x];
834
+ }
835
+ return this.row[x]!=null?this.row[x]:'';
836
+ },
837
+ reset:function(){
838
+ this.nextIndex = 0;
839
+ },
840
+ results,
841
+ code,
842
+ error,
843
+ msg,
844
+ extra
845
+ }
846
+ }
847
+
848
+ const differenceInDays=(day1, day2)=>{
849
+ let days = 0;
850
+ try{
851
+ let date1 = new Date(day1);
852
+ let date2 = new Date(day2);
853
+ let Difference_In_Time = date2.getTime() - date1.getTime();
854
+ days = Difference_In_Time / (1000 * 3600 * 24);
855
+ }catch(e){
856
+ console.log('differenceInDays.err',e);
857
+ }
858
+ return days;
859
+ }
860
+
861
+ const difference_day=(day1, day2)=>{
862
+ let days = 0;
863
+ try{
864
+ let date1 = new Date(day1);
865
+ let date2 = new Date(day2);
866
+ let Difference_In_Time = date2.getTime() - date1.getTime();
867
+ days = Difference_In_Time / (1000 * 3600 * 24);
868
+ }catch(e){
869
+ console.log('differenceInDays.err',e);
870
+ }
871
+ return days;
872
+ }
873
+
874
+ const datePart=(date='1990-01-01 00:00:00')=>{
875
+ let d = new Date(date);
876
+ return {
877
+ date: d,
878
+ year: d.getFullYear(),
879
+ month: addZero(d.getMonth()+1),
880
+ day: addZero(d.getDate()),
881
+ hours: addZero(d.getHours()),
882
+ minutes: addZero(d.getMinutes()),
883
+ seconds: addZero(d.getSeconds())
884
+ }
885
+ }
886
+
887
+ const date_part=(date='1990-01-01 00:00:00')=>{
888
+ let d = new Date(date);
889
+ return {
890
+ date: d,
891
+ year: d.getFullYear(),
892
+ month: addZero(d.getMonth()+1),
893
+ day: addZero(d.getDate()),
894
+ hours: addZero(d.getHours()),
895
+ minutes: addZero(d.getMinutes()),
896
+ seconds: addZero(d.getSeconds())
897
+ }
898
+ }
899
+
900
+ const ascii_to_hexa=(str)=>{
901
+ let arr1 = [];
902
+ for (let n = 0, l = str.length; n < l; n++) {
903
+ let hex = Number(str.charCodeAt(n)).toString(16);
904
+ arr1.push(hex);
905
+ }
906
+ return arr1.join('');
907
+ }
908
+
909
+ const get_user_agent=(user_agent)=>{
910
+ let ua = {};
911
+ try{
912
+ let parser = require('ua-parser-js');
913
+ ua = parser(user_agent);
914
+ }catch(e){
915
+ }
916
+ return ua;
917
+ }
918
+
919
+
920
+ const get_formatted_date=(date, prefomattedDate = false, hideYear = false)=>{
921
+ const MONTH_NAMES = [
922
+ 'Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun','Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'
923
+ ];
924
+ const day = date.getDate();
925
+ const month = MONTH_NAMES[date.getMonth()];
926
+ const year = date.getFullYear();
927
+ const hours = date.getHours();
928
+ let minutes = date.getMinutes();
929
+
930
+ if (minutes < 10) {
931
+ // Adding leading zero to minutes
932
+ minutes = `0${ minutes }`;
933
+ }
934
+
935
+ if (prefomattedDate) {// Today at 10:20 // Yesterday at 10:20
936
+ return `${ prefomattedDate } ${ hours }:${ minutes }`;
937
+ }
938
+
939
+ if (hideYear) {// 10. January at 10:20
940
+ return `${ day }. ${ month } ${ hours }:${ minutes }`;
941
+ }
942
+
943
+ // 10. January 2017. at 10:20
944
+ return `${ day }. ${ month } ${ year }. ${ hours }:${ minutes }`;
945
+ }
946
+
947
+ /**
948
+ * devuelve formato de fecha
949
+ * https://muffinman.io/blog/javascript-time-ago-function/
950
+ * @param {date} dateParam
951
+ * @param {string} language
952
+ * @returns
953
+ */
954
+ const time_ago=(dateParam, language='spanish') =>{
955
+ if (!dateParam) {
956
+ return null;
957
+ }
958
+
959
+ const date = typeof dateParam === 'object' ? dateParam : new Date(dateParam);
960
+ const DAY_IN_MS = 86400000; // 24 * 60 * 60 * 1000
961
+ const today = new Date();
962
+ const yesterday = new Date(today - DAY_IN_MS);
963
+ const seconds = Math.round((today - date) / 1000);
964
+ const minutes = Math.round(seconds / 60);
965
+ const isToday = today.toDateString() === date.toDateString();
966
+ const isYesterday = yesterday.toDateString() === date.toDateString();
967
+ const isThisYear = today.getFullYear() === date.getFullYear();
968
+
969
+ if (seconds < 5) {
970
+ return 'ahora';//'now';
971
+ } else if (seconds < 60) {
972
+ return `hace ${ seconds } sec`;
973
+ } else if (seconds < 90) {
974
+ return 'hace 1 minuto';//'about a minute ago';
975
+ } else if (minutes < 60) {
976
+ return `hace ${ minutes } min`;
977
+ } else if (isToday) {
978
+ return get_formatted_date(date, 'Hoy'); // Today at 10:20
979
+ } else if (isYesterday) {
980
+ return get_formatted_date(date, 'Ayer'); // Yesterday at 10:20
981
+ } else if (isThisYear) {
982
+ return get_formatted_date(date, false, true); // 10. January at 10:20
983
+ }
984
+ return get_formatted_date(date); // 10. January 2017. at 10:20
985
+ }
986
+ /**
987
+ * Convierte segundos a formato time
988
+ * @param {int} seconds example 10
989
+ * @returns formato time 00:00:00
990
+ */
991
+ const seconds_to_time=(seconds)=>{
992
+ let hour = Math.floor(seconds / 3600);
993
+ hour = (hour < 10)? '0' + hour : hour;
994
+ let minute = Math.floor((seconds / 60) % 60);
995
+ minute = (minute < 10)? '0' + minute : minute;
996
+ let second = seconds % 60;
997
+ second = (second < 10)? '0' + second : second;
998
+ return hour + ':' + minute + ':' + second;
999
+ }
1000
+
1001
+ /**
1002
+ * Detiene flujo por x tiempo
1003
+ * @param {*} ms milisegundos
1004
+ * @returns
1005
+ */
1006
+ const sleep =(ms, debug=false)=> {
1007
+ debug ? log(':::::::::::::::> sleep ',ms) : '';
1008
+ return new Promise(resolve => setTimeout(resolve, ms));
1009
+ }
1010
+
1011
+ /**
1012
+ * Get name page web
1013
+ * @param {*} path
1014
+ * @param {*} split
1015
+ * @returns
1016
+ */
1017
+ const get_name_pw=(path)=>{
1018
+ let result = '';
1019
+ try{
1020
+ path = tag(path);
1021
+ path = path.replace("pw_","");
1022
+ path = path.replace(".js","");
1023
+ try{ if (!isNaN(path)) {path = path*1;} }catch(e){}
1024
+ result = path;
1025
+ }catch(e){
1026
+ console.log('tag.err', e);
1027
+ }
1028
+ return result;
1029
+ }
1030
+
1031
+
1032
+ /**
1033
+ * Metodo que realiza intentos sincronos o asincronos en cualquir tipo de peticion utiliza la librerio de request
1034
+ * @param {json<string>} {} example: apix({options:{url:'[url]'}, retries=3, time:30, async:false, callback:function(){}}); default: retries=3, time=60, status_ok=[200]
1035
+ * @returns {err, statusCode, res, body, retry, Object_id}
1036
+ */
1037
+ const apix=async(o)=>{
1038
+ let result;
1039
+ try{
1040
+ let { retry=1, retries=3, time=60, async=false, status_ok=[200], callback} = o ? o:{};
1041
+ let status = status_ok.toString();
1042
+ if (async){ // Metodo asincrono
1043
+ o.retries = 1; // Incializar reintentos para no realizar un cliclo sin fin
1044
+ try{delete o.callback }catch(e){} // Se elimina callback en async: true ya que se ejecutara cuando terminen los intentos
1045
+ do {
1046
+ result = await apix_backend(o);
1047
+ if ( valueIn({ value:''+result.statusCode, in:status }) ){
1048
+ break;
1049
+ }
1050
+ retry++;
1051
+ o.retry = retry;
1052
+ await sleep(time*1000);
1053
+ } while (retry <= retries);
1054
+ callback ? callback({...result}) : '';
1055
+ }else{
1056
+ result = await apix_backend(o);
1057
+ }
1058
+ }catch(e){
1059
+ log('apix.err', e);
1060
+ }
1061
+ return result;
1062
+ }
1063
+
1064
+ /**
1065
+ * Metodo que realiza cualquier tipo de peticion utiliza la librerio de request
1066
+ * @param {json<string>} {} example: apix_backend({options:{url:'[url]'}, retries=3, time:30, async:false, callback:function(o){}}); default: retries=3, time=60, status_ok=[200]
1067
+ * @returns {err, statusCode, res, body, retry, Object_id}
1068
+ */
1069
+ const apix_backend=async(o)=>{
1070
+ let result;
1071
+ try{
1072
+ let {method='get', options='', retry=1, retries=3, time=60, status_ok=[200], Object_id, callback} = o ? o:{};
1073
+ const request = require('request');
1074
+ const tag='apix';
1075
+ let status = status_ok.toString();
1076
+
1077
+ if (!Object_id){
1078
+ o.Object_id = ObjectId()+`_${retry}_${retries}_${time}`; // id_intento_intentos_time
1079
+ }else{
1080
+ let Object_id_new = Object_id.split('_');
1081
+ Object_id_new[1]=retry;
1082
+ o.Object_id=Object_id_new.toString().replace(/,/gi,'_');
1083
+ }
1084
+ let {url=''} = options ? options : {};
1085
+ eval(`result = new Promise((resolve, reject) => {
1086
+ try{
1087
+ request.${method}( options, (err, res, body) => {
1088
+ const {statusCode=404} = res ? res : {};
1089
+ if ( !valueIn({ value:''+statusCode, in:'${status}' }) ){
1090
+ log(tag+' ${o.Object_id} '+statusCode,\`apix({method:"${method}", options, time:${time}, url:"${url}"});\`);
1091
+ if (retry<retries){ // Solo permite el numero de intentos
1092
+ o.retry = retry+1;
1093
+ const timer = new Timer({time:${time}, countdown: true,
1094
+ callback:async function(){
1095
+ apix_backend(o);
1096
+ }
1097
+ });
1098
+ timer.start();
1099
+ }else{
1100
+ callback ? callback({err, statusCode, res, body, retry, Object_id:'${o.Object_id}' }) : '';
1101
+ }
1102
+ }else{
1103
+ callback ? callback({err, statusCode, res, body, retry, Object_id:'${o.Object_id}' }) : '';
1104
+ if (retry>1){
1105
+ log(tag+' ${o.Object_id} '+statusCode, \`apix({method:"${method}", options, time:${time}, url:"${url}"});\`);
1106
+ }
1107
+ }
1108
+ resolve ({err, statusCode, res, body, retry, Object_id:'${o.Object_id}'});
1109
+ });
1110
+ }catch(e){
1111
+ log('apix_backend request err', e);
1112
+ }
1113
+ });
1114
+ `);
1115
+ }catch(e){
1116
+ log('apix_backend.err', e);
1117
+ result = 'err:'+e;
1118
+ }
1119
+ return result;
1120
+ }
1121
+
1122
+ /**
1123
+ * Metodo que agrega o quita un intervalo (day,hour,minute,second) a una fecha
1124
+ * @param {json} {} example: date_add({date:new Date(), interval:-10, unit:'day'}); default:format='YYYY-MM-DD HH:mm:ss'
1125
+ * @returns date
1126
+ */
1127
+ const date_add=(o)=>{
1128
+ let {date, interval, unit, format='YYYY-MM-DD HH:mm:ss'} = o ? o : {};
1129
+ let newDate;
1130
+ try{
1131
+ unit = unit.toLowerCase();
1132
+ switch(unit){
1133
+ case 'day' : newDate = new Date(date.getTime() + interval*24*60*60*1000); break;
1134
+ case 'hour': newDate = new Date(date.getTime() + interval*60*60*1000); break;
1135
+ case 'minute': newDate = new Date(date.getTime() + interval*60*1000); break;
1136
+ case 'second': newDate = new Date(date.getTime() + interval*1000); break;
1137
+ default: newDate = new Date(date.getTime());
1138
+ }
1139
+ newDate = dateFormat(format,newDate);
1140
+ }catch(e){
1141
+ log('date_add.err', e);
1142
+ }
1143
+ return newDate;
1144
+ }
1145
+
1146
+ const remove_accents=(text)=>{
1147
+ return text.normalize('NFD').replace(/[\u0300-\u036f]/g,"");
1148
+ }
1149
+
1150
+ /**
1151
+ * Metodo que agrega todos los campos de un json a otro ya creado
1152
+ * @param {json_main, json} {} example: add_json(json_main, json);
1153
+ * @returns {}
1154
+ */
1155
+ const add_json=(json_main, json)=>{
1156
+ try{
1157
+ for (let key in json){
1158
+ json_main[key] = json[key];
1159
+ }
1160
+ }catch(e){
1161
+ log('add_json.err', e);
1162
+ }
1163
+ return json_main;
1164
+ }
1165
+
1166
+ /**
1167
+ * Method that returns the operating system
1168
+ * @param path __dirname
1169
+ * @param folder folder substring
1170
+ * @returns {}
1171
+ */
1172
+ const info_path=(path, folder='')=>{
1173
+ let result = {so:'linux'}; // default linux
1174
+ try{
1175
+ path = path.replace(/\\/g,"/");
1176
+ result.array_path = path.split('/');
1177
+ if (path.length>0){
1178
+ result.last_path= result.array_path[result.array_path.length-1];
1179
+ result.subpath = path.replace(result.last_path,'');
1180
+ }
1181
+ result.path = path;
1182
+ if (path.includes("C:")){ // windows
1183
+ result.so = 'windows';
1184
+ }
1185
+ try{
1186
+ let main_path = path.substring(0,path.indexOf(folder));
1187
+ result.main_path = main_path;
1188
+ result.submain_path = path.replace(main_path,'');
1189
+ }catch(e){
1190
+
1191
+ }
1192
+ }catch(e){
1193
+ result.err = e;
1194
+ }
1195
+ return result;
1196
+ }
1197
+
1198
+ const json_to_csv=(obj={}, token=',')=>{
1199
+ let linea = "";
1200
+ for (const key in obj) {
1201
+ try{
1202
+ let value = ""+obj[key]; // Convert text
1203
+ value = value.replace(/\"/gm, '\"\"'); // Escape double quote
1204
+ value = value.replace(null, ''); // replace nulls with whitespace
1205
+ value = value.replace(/[\t|\r|\n|\t\n\r|\r\n]/gm, ''); //Remove tabs, carriage returns and enters
1206
+ if (linea.length>0){
1207
+ linea = linea + `${token}`;
1208
+ }
1209
+ linea = linea + `"`+value+`"`;
1210
+ }catch(e){
1211
+ log('json_to_csv.err key['+key+'] value['+value+']',e)
1212
+ }
1213
+ }
1214
+ return linea+"\n";
1215
+ }
1216
+
1217
+ /**
1218
+ * Create csv file by default the file is saved in ascii
1219
+ * @param {<string>} path example: /var/test.csv
1220
+ * @param {<string>} data example: "test1","test2"
1221
+ * @param {<string>} charset example: utf8, ascii default: ascii
1222
+ */
1223
+ const create_file_csv=async(path, data, charset='ascii')=>{
1224
+ const fs = require('fs');
1225
+ return new Promise ((resolve, reject)=>{
1226
+ try{
1227
+ if (path){
1228
+ fs.writeFile(path, data, charset, function(err) {
1229
+ if (err) {
1230
+ return resolve ({ error:1, err });
1231
+ } else {
1232
+ return resolve ({ error:0, path });
1233
+ }
1234
+ });
1235
+ }
1236
+ }catch(e){
1237
+ return resolve({ error:0, err:e });
1238
+ }
1239
+ });
1240
+ }
1241
+
1242
+ const is_valid_email = (email) => {
1243
+ const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
1244
+ return regex.test(email);
1245
+ };
1246
+
1247
+ /**
1248
+ * Segment array of json objects
1249
+ * @param {[]} rows : Array
1250
+ * @param {int} elements_number: number of elements to be separated
1251
+ * @param {String} key_id: Not required; key of a field inside the json to get the ids
1252
+ * @returns
1253
+ */
1254
+ const parts_array=async(array=[], elements_number=1, key_id)=>{
1255
+ let ir = 0;
1256
+ let batch_array = [], batch_total = [];
1257
+ let row_part =[];
1258
+ let batch_ids = [], ids_part=[];
1259
+ try{
1260
+ for (let row of array){
1261
+ ir++;
1262
+ row_part.push(row);
1263
+ try{ key_id ? ids_part.push(row[key_id]) : ''; }catch(e){ }
1264
+ if (ir == elements_number){
1265
+ batch_total.push(ir);
1266
+ batch_array.push(row_part);
1267
+ try{ key_id ? batch_ids.push(ids_part) : ''; ids_part=[] }catch(e){ }
1268
+ row_part=[];
1269
+ ir = 0;
1270
+ }
1271
+ }
1272
+ if (ir>0 && ir<elements_number){
1273
+ batch_total.push(ir);
1274
+ batch_array.push(row_part);
1275
+ try{ key_id ? batch_ids.push(ids_part) : ''; ids_part=[] }catch(e){ }
1276
+ row_part=[];
1277
+ ir = 0;
1278
+ }
1279
+ }catch(e){
1280
+ log(tag+' parts_array.err', e);
1281
+ }
1282
+ return {batch_array, batch_total, parts: batch_array.length, total:array.length, batch_ids };
1283
+ }
1284
+
1285
+ const hour_to_seconds=(hour='00:00')=>{
1286
+ let current_seconds = 0;
1287
+ try{
1288
+ let current_time = hour.split(":");
1289
+ current_seconds = (parseInt(current_time[0], 10) * 60 * 60) + (parseInt(current_time[1], 10) * 60);
1290
+ }catch(e){
1291
+
1292
+ }
1293
+ return current_seconds;
1294
+ }
1295
+
1296
+ /**
1297
+ * Group on array json
1298
+ * @param {string} key : Name of the field to group by
1299
+ * @param {array} array : Array
1300
+ * @param {string} field_id : Not required; adds only the object field default: adds the entire object
1301
+ * @returns
1302
+ */
1303
+ const group_by_array=async (array, key, field_id='')=>{
1304
+ let group = {};
1305
+ try{
1306
+ for (let x of array){
1307
+ let value_key = x[key] ? x[key] : '';
1308
+ let value_field_id = x[field_id] ? x[field_id] : '';
1309
+ value_key = ''+value_key;
1310
+ if (value_key){
1311
+ let object_key = group[value_key] ? group[value_key] : [];
1312
+ if (field_id){
1313
+ object_key.push(value_field_id);
1314
+ }else{
1315
+ object_key.push(x);
1316
+ }
1317
+ group[value_key] = object_key;
1318
+ }
1319
+ }
1320
+ }catch(e){
1321
+ log(tag+' group_by_array.err', e);
1322
+ }
1323
+ return group;
1324
+ }
1325
+
1326
+ /**
1327
+ * Returns comma-separated values ​​from an array
1328
+ * @param {array} array
1329
+ * @param {string} keys_id example: id,ds keys separated by commas
1330
+ * @returns {json}
1331
+ */
1332
+ const keys_array_ids=async(array=[], keys='')=>{
1333
+ let ids = {};
1334
+ keys = keys.split(',');
1335
+ try{
1336
+ for (let x of array){
1337
+ for (let key of keys){
1338
+ let value_key = x[key] ? x[key] : '';
1339
+ let object_key = ids[key] ? ids[key] : [];
1340
+ object_key.push(value_key);
1341
+ ids[key] = object_key;
1342
+ }
1343
+ }
1344
+ }catch(e){
1345
+ log(tag+' keys_array_ids.err', e);
1346
+ }
1347
+ return ids;
1348
+
1349
+ }
1350
+
1351
+ module.exports={
1352
+ log,
1353
+ addZero,
1354
+ getIp,
1355
+ milisegundosASegundos,
1356
+ date,
1357
+ hour,
1358
+ dateHour,
1359
+ sort,
1360
+ ArraytoJson,
1361
+ find,
1362
+ filter,
1363
+ isObjectEmpty,
1364
+ compose,
1365
+ pipe,
1366
+ trace,
1367
+ traceId,
1368
+ random,
1369
+ valueIn,
1370
+ hex_to_ascii,
1371
+ ObjectEmpty,
1372
+ ObjectId,
1373
+ uuid,
1374
+ dateFormat,
1375
+ dateHourFull,
1376
+ getId_key,
1377
+ Timer,
1378
+ Sauron,
1379
+ health_check,
1380
+ endpointAuth,
1381
+ endpoint_auth,
1382
+ execute_command,
1383
+ parse_url,
1384
+ join,
1385
+ tag,
1386
+ jsonToResultSet,
1387
+ differenceInDays,
1388
+ datePart,
1389
+ ascii_to_hexa,
1390
+ get_user_agent,
1391
+ get_formatted_date,
1392
+ time_ago,
1393
+ seconds_to_time,
1394
+ sleep,
1395
+ get_name_pw,
1396
+ apix,
1397
+ date_add,
1398
+ remove_accents,
1399
+ add_json,
1400
+ info_path,
1401
+ json_to_csv,
1402
+ create_file_csv,
1403
+ is_valid_email,
1404
+ miliseconds_to_seconds,
1405
+ parts_array,
1406
+ hour_to_seconds,
1407
+ group_by_array,
1408
+ keys_array_ids,
1409
+ date_format,
1410
+ date_hour,
1411
+ date_hour_full,
1412
+ array_to_json,
1413
+ is_object_empty,
1414
+ trace_id,
1415
+ value_in,
1416
+ object_empty,
1417
+ object_id,
1418
+ get_id_key,
1419
+ json_to_result,
1420
+ difference_day,
1421
+ date_part
1422
+ }