@jvsoft/utils 0.0.1

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.
@@ -0,0 +1,1701 @@
1
+ import { Validators, FormGroup, FormControl, FormArray } from '@angular/forms';
2
+ import { untilDestroyed } from '@ngneat/until-destroy';
3
+ import { startWith, debounceTime, tap, isObservable, switchMap, of, finalize } from 'rxjs';
4
+ import { map } from 'rxjs/operators';
5
+ import { Buffer } from 'buffer';
6
+ import CryptoJS from 'crypto-js';
7
+ import { formatDate, formatNumber } from '@angular/common';
8
+ import { ReactiveFormConfig } from '@rxweb/reactive-form-validators';
9
+ import swal from 'sweetalert2';
10
+ import moment from 'moment';
11
+ import { jwtDecode } from 'jwt-decode';
12
+ import * as i0 from '@angular/core';
13
+ import { Pipe } from '@angular/core';
14
+ import * as i1 from '@angular/platform-browser';
15
+
16
+ function deepMerge(source, target) {
17
+ // Crea un clon profundo sin usar JSON.parse(JSON.stringify)
18
+ let cloneSource = deepClone(source);
19
+ if (typeof target !== 'object' || target === null) {
20
+ return target;
21
+ }
22
+ if (typeof cloneSource !== 'object' || cloneSource === null) {
23
+ cloneSource = Array.isArray(target) ? [] : {};
24
+ }
25
+ for (const key of Object.keys(target)) {
26
+ const targetValue = target[key];
27
+ const sourceValue = cloneSource[key];
28
+ if (typeof targetValue === 'object' && targetValue !== null && !Array.isArray(targetValue)) {
29
+ cloneSource[key] = deepMerge(sourceValue, targetValue);
30
+ }
31
+ else {
32
+ cloneSource[key] = targetValue;
33
+ }
34
+ }
35
+ return cloneSource; // Retorna el clon y no modifica el original
36
+ }
37
+ // Función de clonación profunda que maneja funciones, fechas y otros tipos especiales
38
+ function deepClone(obj) {
39
+ if (obj === null || typeof obj !== 'object') {
40
+ return obj; // Devuelve el valor si no es un objeto
41
+ }
42
+ // Manejar instancias de Date
43
+ if (obj instanceof Date) {
44
+ return new Date(obj.getTime());
45
+ }
46
+ // Manejar funciones devolviendo una copia directa
47
+ if (typeof obj === 'function') {
48
+ return obj.bind({}); // Devuelve una copia de la función enlazada a un contexto vacío
49
+ }
50
+ // Crear un nuevo objeto o array
51
+ const clonedObj = Array.isArray(obj) ? [] : {};
52
+ // Clonar recursivamente las propiedades del objeto
53
+ for (const key in obj) {
54
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
55
+ clonedObj[key] = deepClone(obj[key]);
56
+ }
57
+ }
58
+ return clonedObj;
59
+ }
60
+ /**
61
+ * Busca un elemento en un array o jerarquía de objetos según un campo y valor especificado.
62
+ *
63
+ * @returns El elemento encontrado o undefined si no existe.
64
+ */
65
+ function buscarPorCampo(datosFn) {
66
+ for (const item of datosFn.items) {
67
+ // Verifica si el campo coincide con el valor
68
+ if (item[datosFn.campo] === datosFn.valor) {
69
+ return item;
70
+ }
71
+ // Verifica si hay un campo hijo y si es un array
72
+ if (datosFn.campoHijo && item[datosFn.campoHijo] && Array.isArray(item[datosFn.campoHijo])) {
73
+ // Realiza la búsqueda recursiva en el campo hijo
74
+ const encontrado = buscarPorCampo({
75
+ items: item[datosFn.campoHijo], // Asegura el tipo correcto
76
+ campo: datosFn.campo,
77
+ valor: datosFn.valor,
78
+ campoHijo: datosFn.campoHijo,
79
+ });
80
+ // Si se encuentra el valor en el campo hijo, retorna el resultado
81
+ if (encontrado) {
82
+ return encontrado;
83
+ }
84
+ }
85
+ }
86
+ // Si no se encuentra nada, retorna undefined
87
+ return undefined;
88
+ }
89
+ function sumarPropiedades(item, campos) {
90
+ const datosSumar = campos.map(campo => (item[campo] * 1));
91
+ return datosSumar.reduce((a, b) => a + b, 0);
92
+ }
93
+ function esNumero(value) {
94
+ return !isNaN(Number(value));
95
+ }
96
+ function sumarObjetos(arrayObjetos, campos) {
97
+ return arrayObjetos.reduce((accumulator, item) => {
98
+ campos.forEach(campo => {
99
+ if (esNumero(item[campo])) {
100
+ accumulator[campo] = (accumulator[campo] ?? 0) + (item[campo] ?? 0);
101
+ }
102
+ });
103
+ return accumulator;
104
+ }, {});
105
+ }
106
+ function getUniqueValues(array) {
107
+ return array.filter((currentValue, index, arr) => (arr.indexOf(currentValue) === index));
108
+ }
109
+ function getUniqueValuesByProperty(objetos, campo) {
110
+ const objetosUnicos = {};
111
+ objetos.forEach(objeto => {
112
+ // Verificar si el objeto tiene el campo especificado
113
+ // @ts-ignore
114
+ if (objeto.hasOwnProperty(campo)) {
115
+ // @ts-ignore
116
+ const valorCampo = objeto[campo];
117
+ // Utilizar el valor del campo como clave en un objeto para asegurar que no haya duplicados
118
+ objetosUnicos[valorCampo] = objeto;
119
+ }
120
+ });
121
+ // Convertir el objeto de claves únicas de vuelta a una lista de objetos
122
+ return Object.values(objetosUnicos);
123
+ }
124
+ function ordenarArray(array, numeros = false, sentido = 'ASC') {
125
+ if (numeros) {
126
+ if (sentido != 'ASC') {
127
+ return array.sort((a, b) => b - a);
128
+ }
129
+ return array.sort((a, b) => a - b);
130
+ }
131
+ return array.sort((a, b) => (a > b) ? 1 : ((b > a) ? -1 : 0));
132
+ }
133
+ function ordenarPorPropiedad(objData, propiedad, /**@deprecated*/ numeros = false) {
134
+ return ordenarPorPropiedades(objData, { propiedades: [propiedad], direcciones: ['asc'] });
135
+ }
136
+ function ordenarPorPropiedades(arr, options) {
137
+ const { propiedades, direcciones = [] } = options;
138
+ const orden = direcciones.map(d => d === 'desc' ? -1 : 1);
139
+ return [...arr].sort((a, b) => {
140
+ return propiedades.reduce((acc, propiedad, index) => {
141
+ if (acc !== 0)
142
+ return acc; // Si ya hay diferencia, no seguir comparando
143
+ const aValue = a[propiedad];
144
+ const bValue = b[propiedad];
145
+ if (typeof aValue === 'string' && typeof bValue === 'string') {
146
+ return aValue.localeCompare(bValue) * orden[index]; // 🔹 Comparación alfabética
147
+ }
148
+ if (typeof aValue === 'number' && typeof bValue === 'number') {
149
+ return (aValue - bValue) * orden[index]; // 🔹 Comparación numérica
150
+ }
151
+ return 0; // En caso de valores no comparables
152
+ }, 0);
153
+ });
154
+ }
155
+
156
+ function mostrarValorEnBusqueda(campos, idxSel) {
157
+ const impDataMostrar = () => {
158
+ let vD;
159
+ if (campos.campoId == '*object*' || campos.campoId == '*objeto*') {
160
+ console.log(campos);
161
+ vD = campos.lista.find((x) => JSON.stringify(x).trim() == JSON.stringify(idxSel).trim());
162
+ console.log(vD);
163
+ }
164
+ else {
165
+ vD = campos.lista.find((x) => x[campos.campoId] == idxSel);
166
+ }
167
+ if (!vD && campos.opcExtra) {
168
+ console.log('eval ', campos.opcExtra);
169
+ if (campos.campoId == '*object*' || campos.campoId == '*objeto*') {
170
+ console.log(campos);
171
+ vD = campos.opcExtra.find((x) => JSON.stringify(x).trim() == JSON.stringify(idxSel).trim());
172
+ console.log(vD);
173
+ }
174
+ else {
175
+ vD = campos.opcExtra.find((x) => x[campos.campoId] == idxSel);
176
+ }
177
+ }
178
+ if (vD) {
179
+ let txtFinal = '';
180
+ if (Array.isArray(campos.campoValue)) {
181
+ campos.campoValue.forEach((vCampo, idx) => {
182
+ txtFinal += (vD[vCampo] ?? '');
183
+ if (idx < campos.campoValue.length - 1) {
184
+ txtFinal += ' - ';
185
+ }
186
+ });
187
+ }
188
+ else {
189
+ txtFinal = vD[campos.campoValue] ?? '';
190
+ }
191
+ return txtFinal.trim();
192
+ }
193
+ else {
194
+ console.log('ASSSSS ----- SSSS ');
195
+ }
196
+ return '';
197
+ };
198
+ if (esNumero(idxSel)) {
199
+ if (idxSel > 0 && campos.lista?.length > 0) {
200
+ return impDataMostrar();
201
+ }
202
+ else if (idxSel && typeof idxSel == 'object') {
203
+ return impDataMostrar();
204
+ }
205
+ }
206
+ else {
207
+ if (campos.lista?.length > 0) {
208
+ return impDataMostrar();
209
+ }
210
+ }
211
+ return '';
212
+ }
213
+ function changeSelectData(objThis, dataFiltro) {
214
+ objThis['filtrados'][dataFiltro.variableResultado] = dataFiltro.formControl.valueChanges.pipe(untilDestroyed(objThis)).pipe(startWith(''), map(value => {
215
+ const varN = dataFiltro.data;
216
+ if (varN) {
217
+ if (value) {
218
+ return varN.map(x => x).filter(dat => {
219
+ if (Array.isArray(dataFiltro.campoBuscar)) {
220
+ let encontrado = false;
221
+ for (const vCampo of dataFiltro.campoBuscar) {
222
+ // console.log(vCampo, value, dat[vCampo]);
223
+ if (isNaN(Number(value))) {
224
+ // NO ES NUMERO
225
+ if (value && dat[vCampo] && dat[vCampo].toLowerCase().includes(value?.toString().toLowerCase())) {
226
+ encontrado = true;
227
+ break;
228
+ }
229
+ }
230
+ else {
231
+ if (value && dat[vCampo] && dat[vCampo].toString().includes(value?.toString())) {
232
+ encontrado = true;
233
+ break;
234
+ }
235
+ }
236
+ }
237
+ return encontrado;
238
+ }
239
+ else {
240
+ if (isNaN(Number(value))) {
241
+ return dat[dataFiltro.campoBuscar].toLowerCase().includes(value?.toString().toLowerCase());
242
+ }
243
+ else {
244
+ return dat[dataFiltro.campoBuscar].toString().includes(value?.toString());
245
+ }
246
+ }
247
+ });
248
+ }
249
+ return varN;
250
+ }
251
+ return false;
252
+ }));
253
+ }
254
+ function changeSelect(control, formControl, tipo, campoBuscar, campoFiltro = null) {
255
+ // console.log(formControl);
256
+ // const formGroup = formControl.parent.controls;
257
+ // console.warn( Object.keys(formGroup).find(name => formControl === formGroup[name]) || null );
258
+ if (!campoFiltro) {
259
+ campoFiltro = tipo;
260
+ }
261
+ control['filtrados'][campoFiltro ?? '__'] = formControl.valueChanges.pipe(untilDestroyed(control)).pipe(startWith(''), map(value => {
262
+ // console.warn(value);
263
+ const partes = tipo.split('.');
264
+ let varN;
265
+ if (control['dataServidor']) {
266
+ varN = (partes.length > 1) ? control['dataServidor'][partes[0]][partes[1]] : control['dataServidor'][tipo];
267
+ }
268
+ else if (control['dataServidorSuscripcion']) {
269
+ varN = control['dataServidorSuscripcion'][tipo].getValue();
270
+ }
271
+ if (varN) {
272
+ if (value) {
273
+ return varN.map((x) => x).filter((dat) => {
274
+ if (Array.isArray(campoBuscar)) {
275
+ let encontrado = false;
276
+ for (const vCampo of campoBuscar) {
277
+ // console.log(vCampo, value, dat[vCampo]);
278
+ if (isNaN(Number(value))) {
279
+ // NO ES NUMERO
280
+ if (value && dat[vCampo] && dat[vCampo].toLowerCase().includes(value?.toString().toLowerCase())) {
281
+ encontrado = true;
282
+ break;
283
+ }
284
+ }
285
+ else {
286
+ if (value && dat[vCampo] && dat[vCampo].toString().includes(value?.toString())) {
287
+ encontrado = true;
288
+ break;
289
+ }
290
+ }
291
+ }
292
+ return encontrado;
293
+ }
294
+ else {
295
+ if (isNaN(Number(value))) {
296
+ return dat[campoBuscar].toLowerCase().includes(value?.toString().toLowerCase());
297
+ }
298
+ else {
299
+ return dat[campoBuscar].toString().includes(value?.toString());
300
+ }
301
+ }
302
+ });
303
+ }
304
+ return varN;
305
+ }
306
+ return false;
307
+ }));
308
+ }
309
+ function changeSelectDataApi(objThis, dataFiltro) {
310
+ if (!dataFiltro.variableResultado) {
311
+ dataFiltro.variableResultado = dataFiltro.tipoReq;
312
+ }
313
+ const idFiltrado = dataFiltro.variableResultado;
314
+ dataFiltro.formControl.valueChanges.pipe(debounceTime(500), tap(() => {
315
+ objThis.filtrados[dataFiltro.variableResultado + 'tmp'] = isObservable(objThis.filtrados[idFiltrado]) ? [] : objThis.filtrados[idFiltrado] || [];
316
+ if (objThis.filtrados[idFiltrado] !== objThis.filtrados[idFiltrado + 'tmp']) {
317
+ objThis.filtrados[idFiltrado] = [];
318
+ }
319
+ objThis.isLoading = true;
320
+ }), switchMap(value => {
321
+ if (dataFiltro.campoId) {
322
+ const busquedaActual2 = objThis.filtrados[idFiltrado + 'tmp'].findIndex((item) => item[dataFiltro.campoId ?? '--'] === value);
323
+ if (busquedaActual2 >= 0) {
324
+ return of({ [dataFiltro.tipoReq]: objThis.filtrados[idFiltrado + 'tmp'] });
325
+ }
326
+ }
327
+ return !value || value.length < (dataFiltro.minLength ?? 3) ? [] : (dataFiltro.queryService.getDataMethod('GET', dataFiltro.tipoReq, {
328
+ ...(dataFiltro.dataExtra ?? {}),
329
+ ...(dataFiltro.dataExtraVariable ? Object.fromEntries(dataFiltro.dataExtraVariable.map((objData) => [objData.campo, objData.ctrlValue.value])) : {}),
330
+ txtBuscar: value,
331
+ }, dataFiltro.anonimo).pipe(finalize(() => objThis.isLoading = false)));
332
+ })).subscribe((data) => {
333
+ objThis.filtrados[idFiltrado] = data[dataFiltro.tipoReq] ?? [];
334
+ });
335
+ }
336
+ function changeSelectApi(control, queryService, formControl, tipo, dataExtra = {}, dataExtraVariable = null, minLength = 1, anonimo = false) {
337
+ formControl.valueChanges.pipe(debounceTime(500), tap((value) => {
338
+ control['filtrados'][tipo + 'tmp'] = isObservable(control['filtrados'][tipo]) ? [] : control['filtrados'][tipo];
339
+ if (control['filtrados'][tipo] != control['filtrados'][tipo + 'tmp']) {
340
+ control['filtrados'][tipo] = [];
341
+ }
342
+ control['isLoading'] = true;
343
+ }), switchMap(value => {
344
+ const formGroup = formControl.parent?.controls;
345
+ const nombreControl = Object.keys(formGroup).find(name => formControl === formGroup[name]) || null;
346
+ if (nombreControl && control['filtrados'][tipo + 'tmp'] && control['filtrados'][tipo + 'tmp'].length > 0) {
347
+ const busquedaActual = control['filtrados'][tipo + 'tmp'].findIndex((item) => item[nombreControl] == value);
348
+ if (busquedaActual >= 0) {
349
+ const vRet = {};
350
+ vRet[tipo] = control['filtrados'][tipo + 'tmp'];
351
+ control['isLoading'] = false;
352
+ return of(vRet);
353
+ }
354
+ }
355
+ if (!value || value.length < minLength) {
356
+ return [];
357
+ }
358
+ const dataExtraVariableData = {};
359
+ if (dataExtraVariable) {
360
+ // @ts-ignore
361
+ for (const objData of dataExtraVariable) {
362
+ dataExtraVariableData[objData.campo] = objData.ctrlValue.value;
363
+ }
364
+ }
365
+ return queryService.getDataMethod('GET', tipo, { ...dataExtra, ...dataExtraVariableData, ...{ txtBuscar: value } }, anonimo).pipe(finalize(() => {
366
+ control['isLoading'] = false;
367
+ }));
368
+ })).subscribe((data) => {
369
+ if (data[tipo] == undefined) {
370
+ control['filtrados'][tipo] = [];
371
+ }
372
+ else {
373
+ control['filtrados'][tipo] = data[tipo];
374
+ }
375
+ });
376
+ }
377
+
378
+ function b64Encode(val) {
379
+ return Buffer.from(val, 'binary').toString('base64');
380
+ }
381
+ function b64Decode(val) {
382
+ return Buffer.from(val, 'base64').toString('binary');
383
+ }
384
+
385
+ function getBrowserName() {
386
+ const agent = window.navigator.userAgent.toLowerCase();
387
+ switch (true) {
388
+ case agent.indexOf('edge') > -1:
389
+ return 'edge';
390
+ case agent.indexOf('opr') > -1 && !!window.opr:
391
+ return 'opera';
392
+ case agent.indexOf('chrome') > -1 && !!window.chrome:
393
+ return 'chrome';
394
+ case agent.indexOf('trident') > -1:
395
+ return 'ie';
396
+ case agent.indexOf('firefox') > -1:
397
+ return 'firefox';
398
+ case agent.indexOf('safari') > -1:
399
+ return 'safari';
400
+ default:
401
+ return 'other';
402
+ }
403
+ }
404
+
405
+ // import * as CryptoJS from 'crypto-js';
406
+ // var CryptoJS = require("crypto-js");
407
+ // Clave secreta (debe ser de 16, 24 o 32 caracteres)
408
+ const secretKey = CryptoJS.enc.Utf8.parse('JVSoftSecret@20615178350');
409
+ const iv = CryptoJS.enc.Utf8.parse('AnSalHuaJVSoft07'); // Debe ser de 16 bytes
410
+ // Función para encriptar texto
411
+ function encriptar(text) {
412
+ const encrypted = CryptoJS.AES.encrypt(text, secretKey, {
413
+ iv: iv,
414
+ mode: CryptoJS.mode.CBC,
415
+ padding: CryptoJS.pad.Pkcs7,
416
+ });
417
+ return encrypted.toString(); // Texto cifrado en Base64
418
+ }
419
+ // Función para desencriptar texto
420
+ function desencriptar(ciphertext) {
421
+ const decrypted = CryptoJS.AES.decrypt(ciphertext, secretKey, {
422
+ iv: iv,
423
+ mode: CryptoJS.mode.CBC,
424
+ padding: CryptoJS.pad.Pkcs7,
425
+ });
426
+ return decrypted.toString(CryptoJS.enc.Utf8);
427
+ }
428
+
429
+ function formatearFechaFormato(val, format = 'dd/MM/yyyy') {
430
+ return val ? formatDate(val, format, 'es-PE') : '';
431
+ }
432
+ function formatearFecha(val, hora = '00:00:00') {
433
+ if (val) {
434
+ if (val.length <= 10) {
435
+ val = val + ' ' + hora;
436
+ }
437
+ return new Date(val);
438
+ }
439
+ return val;
440
+ }
441
+ function formatearFechaCadena(fecha) {
442
+ const year = parseInt(fecha.substring(0, 4), 10);
443
+ const month = parseInt(fecha.substring(4, 6), 10) - 1;
444
+ const day = parseInt(fecha.substring(6, 8), 10);
445
+ return new Date(year, month, day);
446
+ }
447
+
448
+ const mimeTypes = {
449
+ // Imágenes
450
+ 'jpg': 'image/jpeg',
451
+ 'jpeg': 'image/jpeg',
452
+ 'png': 'image/png',
453
+ 'gif': 'image/gif',
454
+ 'webp': 'image/webp',
455
+ 'svg': 'image/svg+xml',
456
+ 'ico': 'image/x-icon',
457
+ 'bmp': 'image/bmp',
458
+ // Documentos
459
+ 'pdf': 'application/pdf',
460
+ 'doc': 'application/msword',
461
+ 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
462
+ 'xls': 'application/vnd.ms-excel',
463
+ 'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
464
+ 'ppt': 'application/vnd.ms-powerpoint',
465
+ 'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
466
+ 'txt': 'text/plain',
467
+ 'csv': 'text/csv',
468
+ 'json': 'application/json',
469
+ 'xml': 'application/xml',
470
+ 'html': 'text/html',
471
+ // Audio
472
+ 'mp3': 'audio/mpeg',
473
+ 'wav': 'audio/wav',
474
+ 'ogg': 'audio/ogg',
475
+ 'm4a': 'audio/mp4',
476
+ // Video
477
+ 'mp4': 'video/mp4',
478
+ 'avi': 'video/x-msvideo',
479
+ 'mov': 'video/quicktime',
480
+ 'wmv': 'video/x-ms-wmv',
481
+ 'flv': 'video/x-flv',
482
+ 'webm': 'video/webm',
483
+ 'mkv': 'video/x-matroska',
484
+ // Archivos comprimidos
485
+ 'zip': 'application/zip',
486
+ 'rar': 'application/vnd.rar',
487
+ '7z': 'application/x-7z-compressed',
488
+ 'tar': 'application/x-tar',
489
+ 'gz': 'application/gzip',
490
+ 'bz2': 'application/x-bzip2',
491
+ // Otros formatos
492
+ 'js': 'application/javascript',
493
+ 'css': 'text/css',
494
+ 'ts': 'application/typescript',
495
+ 'md': 'text/markdown',
496
+ 'exe': 'application/octet-stream',
497
+ 'eot': 'application/vnd.ms-fontobject',
498
+ 'woff': 'font/woff',
499
+ 'woff2': 'font/woff2',
500
+ 'ttf': 'font/ttf',
501
+ 'otf': 'font/otf',
502
+ };
503
+ function obtenerMimeType(nombreArchivo) {
504
+ const extension = nombreArchivo.split('.').pop()?.toLowerCase();
505
+ return extension ? mimeTypes[extension] || 'application/octet-stream' : null;
506
+ }
507
+ function sanitizarNombreArchivo(nombre, reemplazo = '_') {
508
+ // 1. Quitar caracteres no válidos para nombres de archivo
509
+ const nombreSanitizado = nombre.replace(/[\/\\:*?"<>|]/g, reemplazo);
510
+ // 2. Reemplazar espacios múltiples o al inicio/final
511
+ const nombreLimpio = nombreSanitizado.trim().replace(/\s+/g, reemplazo);
512
+ // 3. Asegurar longitud máxima (opcional, aquí 255 caracteres)
513
+ return nombreLimpio.substring(0, 255);
514
+ }
515
+
516
+ function establecerQuitarRequired(formulario, establecer = [], quitar = [], camposDisabled = []) {
517
+ establecer.forEach((control) => {
518
+ if (!formulario.get(control)?.hasValidator(Validators.required)) {
519
+ formulario.get(control)?.addValidators([Validators.required]);
520
+ formulario.get(control)?.enable();
521
+ formulario.get(control)?.updateValueAndValidity();
522
+ }
523
+ });
524
+ const deshabilitar = (strControl) => {
525
+ if (camposDisabled == 'todos') {
526
+ formulario.get(strControl)?.disable();
527
+ console.log(strControl);
528
+ }
529
+ else {
530
+ if (camposDisabled.includes(strControl)) {
531
+ formulario.get(strControl)?.disable();
532
+ }
533
+ }
534
+ };
535
+ quitar.forEach(control => {
536
+ if (formulario.get(control)?.hasValidator(Validators.required)) {
537
+ formulario.get(control)?.removeValidators([Validators.required]);
538
+ formulario.get(control)?.updateValueAndValidity();
539
+ }
540
+ deshabilitar(control);
541
+ });
542
+ }
543
+ function getFormValidationErrors(form) {
544
+ const result = [];
545
+ Object.keys(form.controls).forEach(key => {
546
+ const formProperty = form.get(key);
547
+ if (formProperty instanceof FormGroup) {
548
+ result.push(...getFormValidationErrors(formProperty));
549
+ }
550
+ const controlErrors = formProperty?.errors;
551
+ if (controlErrors) {
552
+ Object.keys(controlErrors).forEach(keyError => {
553
+ result.push({
554
+ control: key,
555
+ error: keyError,
556
+ value: controlErrors[keyError]
557
+ });
558
+ });
559
+ }
560
+ });
561
+ return result;
562
+ }
563
+ function mensajesErrorFormControl(control) {
564
+ if (!control || !control.errors || !control.touched)
565
+ return '';
566
+ ReactiveFormConfig.set({
567
+ // RxwebValidators
568
+ validationMessage: {
569
+ required: 'Es requerido',
570
+ numeric: 'Debe ser numérico valido',
571
+ // minLength: 'minimum length is {{1}}',
572
+ // maxLength: 'allowed max length is {{1}}',
573
+ },
574
+ });
575
+ const errorMessages = {
576
+ required: 'Es requerido',
577
+ numeric: 'Debe ser numérico válido',
578
+ min: `Valor mínimo permitido: ${control.errors['min']?.min}`,
579
+ minValue: 'Debe ser positivo',
580
+ minlength: `Mínimo ${control.errors['minlength']?.requiredLength} caracteres.`,
581
+ maxlength: `Caracteres ${control.errors['maxlength']?.actualLength}/${control.errors['maxlength']?.requiredLength}`,
582
+ email: 'No se cumple con el formato de Correo Electrónico',
583
+ isNumeric: 'Debe seleccionar una opción',
584
+ hasNumber: 'Se requiere al menos un número',
585
+ hasCapitalCase: 'Se requiere al menos una mayúscula',
586
+ hasSmallCase: 'Se requiere al menos una minúscula',
587
+ hasSpecialCharacters: 'Se requiere al menos un carácter especial',
588
+ NoPassswordMatch: 'La contraseña no coincide',
589
+ itemSelected: 'Debe seleccionar una opción de la lista',
590
+ inputMask: 'El formato ingresado no es válido',
591
+ };
592
+ // Devuelve el primer mensaje de error encontrado
593
+ for (const errorKey of Object.keys(control.errors)) {
594
+ if (errorMessages[errorKey]) {
595
+ return errorMessages[errorKey];
596
+ }
597
+ }
598
+ // Si el error tiene un mensaje personalizado, usarlo
599
+ return control.errors[Object.keys(control.errors)[0]]?.message || '';
600
+ }
601
+ function toFormData(formValue) {
602
+ const formData = new FormData();
603
+ Object.keys(formValue).forEach((key) => {
604
+ const value = formValue[key];
605
+ if (value === null || value === undefined) {
606
+ return; // Ignorar valores nulos o indefinidos
607
+ }
608
+ if (Array.isArray(value)) {
609
+ value.forEach((item, index) => {
610
+ if (typeof item === 'object' && item !== null) {
611
+ if ('file' in item) {
612
+ formData.append(`${key}[${index}]`, item.file);
613
+ }
614
+ else {
615
+ formData.append(`${key}[${index}]`, JSON.stringify(item));
616
+ }
617
+ }
618
+ else {
619
+ formData.append(`${key}[${index}]`, item.toString());
620
+ }
621
+ });
622
+ }
623
+ else if (typeof value === 'object') {
624
+ // Si es un objeto (pero no un array), convertirlo a JSON
625
+ formData.append(key, JSON.stringify(value));
626
+ }
627
+ else {
628
+ // Para valores primitivos (string, number, boolean)
629
+ formData.append(key, value.toString());
630
+ }
631
+ });
632
+ return formData;
633
+ }
634
+ function markAsTouchedWithoutEmitEvent(control) {
635
+ if (control instanceof FormControl) {
636
+ control.markAsTouched({ onlySelf: true });
637
+ control.updateValueAndValidity({ emitEvent: false });
638
+ }
639
+ else if (control instanceof FormGroup || control instanceof FormArray) {
640
+ Object.values(control.controls).forEach(childControl => {
641
+ markAsTouchedWithoutEmitEvent(childControl);
642
+ });
643
+ control.updateValueAndValidity({ emitEvent: false });
644
+ }
645
+ }
646
+
647
+ function mensajeAlerta(tipo, titulo, mensaje, opciones) {
648
+ opciones = {
649
+ ...{
650
+ heightAuto: false,
651
+ title: titulo,
652
+ html: mensaje,
653
+ icon: tipo,
654
+ confirmButtonText: 'Aceptar',
655
+ // customClass: {
656
+ // confirmButton: 'btn btn-lg btn-outline-success mx-2',
657
+ // cancelButton: 'btn btn-lg btn-outline-dark mx-2'
658
+ // },
659
+ // buttonsStyling: false
660
+ },
661
+ ...opciones
662
+ };
663
+ return swal.fire(opciones);
664
+ }
665
+ function mensajeTimer(tipo, titulo, mensaje, milisegundos = 3000, showLoading = true, opciones) {
666
+ let timerInterval;
667
+ opciones = {
668
+ ...{
669
+ heightAuto: false,
670
+ title: titulo,
671
+ html: mensaje + '<br> Se cerrará en <strong> X </strong> segundos.',
672
+ icon: tipo,
673
+ timer: milisegundos,
674
+ showCancelButton: false,
675
+ showConfirmButton: false,
676
+ willOpen: () => {
677
+ if (showLoading) {
678
+ swal.showLoading();
679
+ }
680
+ timerInterval = setInterval(() => {
681
+ const impr = Math.ceil(((swal.getTimerLeft() ?? 1) / 1000));
682
+ if (swal.getHtmlContainer()) {
683
+ // @ts-ignore
684
+ swal.getHtmlContainer().querySelector('strong').textContent = String(impr);
685
+ }
686
+ }, 100);
687
+ },
688
+ willClose: () => {
689
+ clearInterval(timerInterval);
690
+ }
691
+ },
692
+ ...opciones
693
+ };
694
+ return swal.fire(opciones);
695
+ }
696
+ // @ts-ignore
697
+ function mensajeConfirmacion(tipo, titulo, mensaje, opciones) {
698
+ opciones = {
699
+ ...{
700
+ heightAuto: false,
701
+ title: titulo,
702
+ html: mensaje,
703
+ icon: tipo,
704
+ showCancelButton: true,
705
+ // confirmButtonColor: '#3f51b5',
706
+ // cancelButtonColor: '#ffffff',
707
+ confirmButtonText: 'Confirmar',
708
+ cancelButtonText: 'Cancelar',
709
+ reverseButtons: true,
710
+ // customClass: {
711
+ // confirmButton: 'btn btn-lg btn-outline-success mx-2',
712
+ // cancelButton: 'btn btn-lg btn-outline-dark mx-2'
713
+ // },
714
+ // buttonsStyling: false
715
+ },
716
+ ...opciones
717
+ };
718
+ return swal.fire(opciones);
719
+ }
720
+ function mensajeToast(tipo, titulo, mensaje, opciones) {
721
+ opciones = {
722
+ ...{
723
+ heightAuto: false,
724
+ title: titulo,
725
+ html: mensaje,
726
+ icon: tipo,
727
+ confirmButtonText: 'Aceptar',
728
+ toast: true,
729
+ position: 'top-end',
730
+ showConfirmButton: false,
731
+ timer: 3000,
732
+ timerProgressBar: true,
733
+ },
734
+ ...opciones
735
+ };
736
+ return swal.fire(opciones);
737
+ }
738
+
739
+ function mensajesDeError(error, toast = false) {
740
+ let msg;
741
+ if (error.error && error.error instanceof ArrayBuffer) {
742
+ const msgArrayBuffer = (arrayBuffer) => {
743
+ try {
744
+ const mensajeError = JSON.parse(new TextDecoder("utf-8").decode(arrayBuffer));
745
+ return mensajeError.message || 'Error desconocido';
746
+ }
747
+ catch (parseError) {
748
+ console.error('Error al analizar la respuesta JSON:', parseError);
749
+ return 'Error al analizar la respuesta JSON';
750
+ }
751
+ };
752
+ msg = msgArrayBuffer(error.error);
753
+ }
754
+ else {
755
+ switch (error.status) {
756
+ case 0:
757
+ // msg = error.message;
758
+ msg = 'El servidor no responde, verifica tu conexion a la red';
759
+ console.log(error);
760
+ break;
761
+ case 401:
762
+ if (error.error && typeof error.error == 'object') {
763
+ if (error.error.message) {
764
+ msg = error.error.message;
765
+ }
766
+ else if (error.error.error) {
767
+ msg = error.error.error;
768
+ }
769
+ else {
770
+ msg = JSON.stringify(error.error);
771
+ console.log(error);
772
+ }
773
+ }
774
+ else if (error.error && typeof error.error == 'string') {
775
+ msg = error.error;
776
+ }
777
+ else {
778
+ msg = 'Acceso no autorizado';
779
+ console.log(error);
780
+ }
781
+ break;
782
+ case 422:
783
+ let strEr = '';
784
+ console.log(typeof error.error.errors);
785
+ console.log(error.error.errors);
786
+ if (error.error.errors) {
787
+ Object.keys(error.error.errors).forEach(o => {
788
+ strEr += '<li>' + error.error.errors[o][0] + '</li>';
789
+ });
790
+ msg = (error.error.message ?? '') + '<ul>' + strEr + '</ul>';
791
+ }
792
+ else if (error.error.error) {
793
+ msg = error.error.msg;
794
+ }
795
+ break;
796
+ case 429:
797
+ case 400:
798
+ case 500:
799
+ case 503:
800
+ msg = error.error.message;
801
+ break;
802
+ case 504:
803
+ msg = 'No se puede conectar al servidor. Comprueba tu conexion a la red - ' + error.statusText;
804
+ break;
805
+ default:
806
+ msg = 'Error de Sistema';
807
+ console.log(error);
808
+ break;
809
+ }
810
+ }
811
+ if (!msg) {
812
+ msg = error.statusText ?? 'Error inesperado o datos inexistentes.';
813
+ }
814
+ let tituloFinal = 'Error!';
815
+ let mensajeFinal;
816
+ if (msg.includes('Hmac::doVerify')) {
817
+ console.log(error, msg);
818
+ return;
819
+ }
820
+ else if (msg == 'Server Error') {
821
+ console.log(error, msg);
822
+ return;
823
+ }
824
+ else if (msg.includes('[IMSSP]')) {
825
+ mensajeFinal = 'Error en consulta de registros.';
826
+ }
827
+ else if (msg.includes('Tiempo de espera de la')) {
828
+ mensajeFinal = 'Hubo un error en la solicitud de datos, por favor actualice (SHIFT + F5)';
829
+ }
830
+ else {
831
+ mensajeFinal = msg;
832
+ }
833
+ if (toast) {
834
+ mensajeToast('error', tituloFinal, mensajeFinal);
835
+ }
836
+ else {
837
+ mensajeAlerta('error', tituloFinal, mensajeFinal);
838
+ }
839
+ throw new Error(mensajeFinal);
840
+ }
841
+
842
+ let dataSessionStorageKey = {
843
+ tokenStringKey: 'JVSoftTkn',
844
+ changePasswordKey: 'chPwd',
845
+ logoUrl: 'logo_url',
846
+ logoLogin: 'login-logo',
847
+ backgroundLogin: 'login-background',
848
+ favicon: 'favicon',
849
+ darkMode: 'darkMode',
850
+ serverTimestamp: 'srvtmstp',
851
+ apiDataKey: 'reqDt',
852
+ };
853
+ let localStorageKeys = dataSessionStorageKey;
854
+ function inicializarVariablesSessionStorage(datSesion) {
855
+ dataSessionStorageKey = datSesion;
856
+ }
857
+ function setJwtTokenData(data) {
858
+ localStorage.setItem(dataSessionStorageKey.tokenStringKey, data);
859
+ }
860
+ function jwtTokenData(key = dataSessionStorageKey.tokenStringKey) {
861
+ const tokenObj = localStorage.getItem(key);
862
+ try {
863
+ return JSON.parse(tokenObj);
864
+ }
865
+ catch (error) {
866
+ return null;
867
+ }
868
+ }
869
+ function jwtToken(key = dataSessionStorageKey.tokenStringKey) {
870
+ const varJwtTokenData = jwtTokenData(key);
871
+ if (varJwtTokenData) {
872
+ return varJwtTokenData.access_token;
873
+ }
874
+ return '';
875
+ }
876
+ function jwtTokenExpiracion(key = dataSessionStorageKey.tokenStringKey) {
877
+ const jwtStr = jwtToken(key);
878
+ if (!jwtStr)
879
+ return null;
880
+ try {
881
+ const decodedToken = jwtDecode(jwtStr);
882
+ return decodedToken.exp ? decodedToken.exp * 1000 : null; // Convertir a milisegundos
883
+ }
884
+ catch (e) {
885
+ return null;
886
+ }
887
+ }
888
+ function jwtTokenExpiracionFaltante() {
889
+ return Math.abs(moment().diff(jwtTokenExpiracion(), 'seconds'));
890
+ }
891
+ function setCambiarPwd(accion = true) {
892
+ localStorage.setItem(dataSessionStorageKey.changePasswordKey, (accion ? 1 : 0).toString());
893
+ }
894
+ function getCambiarPwd() {
895
+ const frmCambioPwd = localStorage.getItem(dataSessionStorageKey.changePasswordKey);
896
+ if (!frmCambioPwd) {
897
+ return null;
898
+ }
899
+ return frmCambioPwd == '1';
900
+ }
901
+ function delLocalStorage(keyElim = [
902
+ dataSessionStorageKey.tokenStringKey,
903
+ dataSessionStorageKey.changePasswordKey,
904
+ dataSessionStorageKey.apiDataKey,
905
+ ]) {
906
+ keyElim.forEach(key => {
907
+ localStorage.removeItem(key);
908
+ });
909
+ }
910
+ function getLocalStorage(key) {
911
+ return localStorage.getItem(key);
912
+ }
913
+ function setLocalStorage(key, value = '') {
914
+ localStorage.setItem(key, value.toString());
915
+ }
916
+
917
+ function finalizarGuardadoMantenimiento(objThis, dataGuardado, nombreColeccion, campoId, dialogRef = null) {
918
+ if (dataGuardado && dataGuardado['data']) {
919
+ if (dialogRef) {
920
+ dialogRef.close();
921
+ }
922
+ const partesNombreColeccion = nombreColeccion.split('.');
923
+ const objSeleccionado = objThis['seleccionados'][partesNombreColeccion[partesNombreColeccion.length - 1]];
924
+ const dataServidor = objThis['dataServidor'];
925
+ const [parte1, parte2] = partesNombreColeccion;
926
+ /*if (!objSeleccionado || objSeleccionado[campoId] != dataGuardado['data'][campoId]) {
927
+ return fnCargarLista();
928
+ }*/
929
+ if (dataGuardado['data'][campoId]) {
930
+ let coleccion;
931
+ if (partesNombreColeccion.length == 1 && dataServidor?.[parte1]) {
932
+ coleccion = objThis['dataServidor'][parte1];
933
+ }
934
+ else if (dataServidor?.[parte1]?.[parte2]) {
935
+ coleccion = objThis['dataServidor'][parte1][parte2];
936
+ }
937
+ if (coleccion == null) {
938
+ coleccion = [];
939
+ if (objThis['dataServidorSuscripcion'] && objThis['dataServidorSuscripcion'][nombreColeccion] && objThis['dataServidorSuscripcion'][nombreColeccion].getValue()) {
940
+ coleccion = objThis['dataServidorSuscripcion'][nombreColeccion].getValue();
941
+ }
942
+ }
943
+ const dEnviar = {};
944
+ // dEnviar[campoId] = objSeleccionado[campoId];
945
+ dEnviar[campoId] = dataGuardado['data'][campoId];
946
+ // return of('MAsssL');
947
+ return objThis.queryService.getDataMethod('GET', nombreColeccion, dEnviar).toPromise().then((daIndiv) => {
948
+ if (dataGuardado['data'][campoId]) {
949
+ const idxDataActual = coleccion.findIndex((item) => item[campoId] == dataGuardado['data'][campoId]);
950
+ if (idxDataActual >= 0) {
951
+ coleccion[idxDataActual] = {
952
+ ...coleccion[idxDataActual],
953
+ ...daIndiv[nombreColeccion][0]
954
+ };
955
+ objThis['seleccionados'][partesNombreColeccion[partesNombreColeccion.length - 1]] = coleccion[idxDataActual];
956
+ }
957
+ else {
958
+ coleccion.unshift(daIndiv[nombreColeccion][0]);
959
+ objThis['seleccionados'][partesNombreColeccion[partesNombreColeccion.length - 1]] = coleccion[0];
960
+ }
961
+ }
962
+ /*
963
+ else if (objSeleccionado && objSeleccionado[campoId] == dataGuardado['data'][campoId]) {
964
+ const idxDataActual = coleccion.findIndex(item => item[campoId] == objSeleccionado[campoId]);
965
+ if (idxDataActual >= 0) {
966
+ coleccion[idxDataActual] = {
967
+ ...objSeleccionado,
968
+ ...daIndiv[nombreColeccion][0]
969
+ };
970
+ objThis['seleccionados'][partesNombreColeccion[partesNombreColeccion.length - 1]] = coleccion[idxDataActual];
971
+ }
972
+ }
973
+ else {
974
+ if (coleccion == null) {
975
+ coleccion = [];
976
+ }
977
+ coleccion.unshift(daIndiv[nombreColeccion][0]);
978
+ objThis['seleccionados'][partesNombreColeccion[partesNombreColeccion.length - 1]] = coleccion[0];
979
+ }
980
+ */
981
+ return coleccion;
982
+ });
983
+ }
984
+ else if (dataGuardado['data']['iResult']) {
985
+ objThis['seleccionados'][partesNombreColeccion[partesNombreColeccion.length - 1]] = null;
986
+ let lstNuevo;
987
+ if (partesNombreColeccion.length == 1 && dataServidor?.[parte1]) {
988
+ lstNuevo = objThis['dataServidor'][parte1] = objThis['dataServidor'][parte1].filter((item) => item[campoId] != objSeleccionado[campoId]);
989
+ }
990
+ else {
991
+ if (objSeleccionado) {
992
+ if (dataServidor?.[parte1]?.[parte2]) {
993
+ lstNuevo = objThis['dataServidor'][parte1][parte2] = objThis['dataServidor'][parte1][parte2].filter((item) => item[campoId] != objSeleccionado[campoId]);
994
+ }
995
+ else if (objThis['dataServidorSuscripcion'] && objThis['dataServidorSuscripcion'][nombreColeccion] && objThis['dataServidorSuscripcion'][nombreColeccion].getValue()) {
996
+ const dValor = objThis['dataServidorSuscripcion'][nombreColeccion].getValue();
997
+ lstNuevo = dValor.filter((item) => item[campoId] != objSeleccionado[campoId]);
998
+ objThis['dataServidorSuscripcion'][nombreColeccion].next(lstNuevo);
999
+ }
1000
+ }
1001
+ }
1002
+ return new Promise((resolve, reject) => {
1003
+ resolve(lstNuevo);
1004
+ });
1005
+ }
1006
+ }
1007
+ else if (!dataGuardado) {
1008
+ return new Promise((resolve, reject) => {
1009
+ reject('no existen datos de retorno');
1010
+ });
1011
+ }
1012
+ return new Promise((resolve, reject) => {
1013
+ resolve('');
1014
+ });
1015
+ }
1016
+
1017
+ function objectPropertiesToType(formFields) {
1018
+ Object.keys(formFields).filter(control => !!formFields[control]).forEach(control => {
1019
+ if (/^dt[a-zA-Z]+/.test(control)) {
1020
+ formFields[control] = formatDate(formFields[control], 'yyyy-MM-dd HH:mm', 'es-PE');
1021
+ }
1022
+ else if (control.startsWith('d')) {
1023
+ formFields[control] = formatearFecha(formFields[control]);
1024
+ }
1025
+ else if (control.startsWith('n')) {
1026
+ formFields[control] = Number(formFields[control]);
1027
+ }
1028
+ });
1029
+ return formFields;
1030
+ }
1031
+
1032
+ function generateRandomString(length) {
1033
+ let result = '';
1034
+ const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
1035
+ const charactersLength = characters.length;
1036
+ for (let i = 0; i < length; i++) {
1037
+ result += characters.charAt(Math.floor(Math.random() * charactersLength));
1038
+ }
1039
+ return result;
1040
+ }
1041
+
1042
+ // @ts-ignore
1043
+ function tipoValorFuncion(datoParam, ...param) {
1044
+ if (typeof datoParam === 'function') {
1045
+ return datoParam(...param);
1046
+ }
1047
+ return datoParam;
1048
+ }
1049
+
1050
+ function imprimirCelda(data, tipo = null, opcAdicionales = {}) {
1051
+ let texto = data;
1052
+ // if (typeof data)
1053
+ switch (tipo) {
1054
+ case 'money':
1055
+ case 'number':
1056
+ case 'integer':
1057
+ let formatoNumero = (tipo == 'money' ? '1.2-2' : (tipo == 'number' ? '1.0-2' : '1.0-0'));
1058
+ texto = data * 1;
1059
+ if (opcAdicionales?.format) {
1060
+ formatoNumero = opcAdicionales.format;
1061
+ }
1062
+ texto = formatNumber(texto, 'es-PE', formatoNumero);
1063
+ break;
1064
+ case 'date':
1065
+ case 'datetime':
1066
+ case 'time':
1067
+ let formatoFecha = (tipo == 'date' ? 'dd/MM/yyyy' : (tipo == 'time' ? 'HH:mm:ss' : 'dd/MM/yyyy HH:mm'));
1068
+ if (!opcAdicionales?.alignment) {
1069
+ opcAdicionales.alignment = 'center';
1070
+ }
1071
+ if (opcAdicionales?.format) {
1072
+ formatoFecha = opcAdicionales.format;
1073
+ }
1074
+ texto = texto ? formatDate(data, formatoFecha, 'es-PE') : null;
1075
+ break;
1076
+ default:
1077
+ break;
1078
+ }
1079
+ opcAdicionales['text'] = texto ?? ' ';
1080
+ return opcAdicionales;
1081
+ }
1082
+ function generarDesdeMantenimiento(tabla) {
1083
+ const celdasHeaderDetalle = [];
1084
+ const tHead = [];
1085
+ const titUsar = columnasValidas(tabla.titulos);
1086
+ const camposTotales = titUsar.filter(titulo => titulo.reporte && titulo.reporte.totalizar).map(titulo => titulo.property);
1087
+ const sumaObj = sumarObjetos(tabla.contenido, camposTotales);
1088
+ if (tabla.numeracion) {
1089
+ tHead.push(imprimirCelda('Nº', null, { style: 'thSmall', ...tabla.opcionesPdfmake?.titulo }));
1090
+ }
1091
+ titUsar.forEach(dT => {
1092
+ if (tabla.titulosMayusculas) {
1093
+ dT.label = dT.label.toUpperCase();
1094
+ }
1095
+ const opcionesPdfMakeTitulo = {
1096
+ ...tabla.opcionesPdfmake?.titulo,
1097
+ ...dT.reporte?.opcionesPdfmake?.titulo
1098
+ };
1099
+ tHead.push(imprimirCelda(dT.label.replace('<br>', ' '), null, { style: 'thSmall', ...opcionesPdfMakeTitulo }));
1100
+ });
1101
+ if (!tabla.sinTitulos) {
1102
+ if (tabla.prependTitle) {
1103
+ tabla.prependTitle.forEach((filaAdic) => {
1104
+ celdasHeaderDetalle.push(filaAdic);
1105
+ });
1106
+ // celdasHeaderDetalle.concat(tabla.prependTitle);
1107
+ }
1108
+ celdasHeaderDetalle.push(tHead);
1109
+ if (tabla.appendTitle) {
1110
+ tabla.appendTitle.forEach((filaAdic) => {
1111
+ celdasHeaderDetalle.push(filaAdic);
1112
+ });
1113
+ // celdasHeaderDetalle.concat(tabla.appendTitle);
1114
+ }
1115
+ }
1116
+ let celdasBodyDetalle = [];
1117
+ tabla.contenido.forEach((dataProd, idxProd) => {
1118
+ const tBody = [];
1119
+ if (tabla.numeracion) {
1120
+ tBody.push(imprimirCelda(idxProd + 1, 'number', {
1121
+ style: tabla.resaltarNumeracion == false ? 'tdSmall' : 'thSmall',
1122
+ alignment: 'center',
1123
+ rowSpan: tabla.detalle?.length > 0 ? 2 : 1,
1124
+ ...tabla.opcionesPdfmake?.cuerpo
1125
+ }));
1126
+ }
1127
+ titUsar.forEach(dT => {
1128
+ let add;
1129
+ if (dT.transformarDirecto) {
1130
+ add = dT.transformarDirecto(dataProd);
1131
+ }
1132
+ else {
1133
+ let txtImprimir = dataProd[dT.property];
1134
+ if (dT.transformar)
1135
+ txtImprimir = dT.transformar(dataProd);
1136
+ const opcionesPdfMakeCuerpo = {
1137
+ ...{
1138
+ format: dT.format,
1139
+ },
1140
+ ...tabla.opcionesPdfmake?.cuerpo,
1141
+ ...dT.reporte?.opcionesPdfmake?.cuerpo,
1142
+ };
1143
+ switch (dT.type) {
1144
+ case 'date':
1145
+ add = imprimirCelda(txtImprimir, 'date', {
1146
+ style: 'tdSmall',
1147
+ ...opcionesPdfMakeCuerpo
1148
+ });
1149
+ break;
1150
+ case 'number':
1151
+ add = imprimirCelda(txtImprimir, 'number', {
1152
+ style: 'tdSmall',
1153
+ ...opcionesPdfMakeCuerpo
1154
+ });
1155
+ break;
1156
+ case 'money':
1157
+ add = imprimirCelda(txtImprimir, 'money', {
1158
+ style: 'tdSmall',
1159
+ alignment: 'right',
1160
+ ...opcionesPdfMakeCuerpo
1161
+ });
1162
+ break;
1163
+ default:
1164
+ add = imprimirCelda(txtImprimir, null, { style: 'tdSmall', ...opcionesPdfMakeCuerpo });
1165
+ }
1166
+ if (dT.cssClasses) {
1167
+ dT.cssClasses.forEach((clase) => {
1168
+ // @ts-ignore
1169
+ add = { ...add, alignment: clase.replace('text-', '') };
1170
+ });
1171
+ }
1172
+ }
1173
+ tBody.push(add);
1174
+ });
1175
+ celdasBodyDetalle.push(tBody);
1176
+ if (tabla.detalle?.length > 0) {
1177
+ const tBody2 = [];
1178
+ const lineasBody2 = [];
1179
+ if (tabla.numeracion)
1180
+ tBody2.push({});
1181
+ titUsar.forEach(dT => tBody2.push({ text: dT.property }));
1182
+ tabla.detalle.forEach((campoDet) => {
1183
+ if (campoDet.label)
1184
+ lineasBody2.push(JSON.parse(JSON.stringify(campoDet.label)));
1185
+ if (dataProd[campoDet.campo]) {
1186
+ lineasBody2.push(generarDesdeMantenimiento({
1187
+ ...campoDet, contenido: dataProd[campoDet.campo]
1188
+ }));
1189
+ }
1190
+ });
1191
+ tBody2[tabla.numeracion ? 1 : 0] = {
1192
+ colSpan: titUsar.length,
1193
+ style: 'tdSmall',
1194
+ stack: lineasBody2,
1195
+ };
1196
+ celdasBodyDetalle.push(tBody2);
1197
+ }
1198
+ });
1199
+ const filaTotales = [];
1200
+ if (tabla.numeracion) {
1201
+ filaTotales.push(imprimirCelda('', null, { border: [false, false, false, false] }));
1202
+ }
1203
+ titUsar.forEach(titulo => {
1204
+ if (titulo.reporte && titulo.reporte.totalizar) {
1205
+ camposTotales.push(titulo.property);
1206
+ let txtImprimirTotal = sumaObj[titulo.property] ?? 0;
1207
+ if (titulo.reporte?.opcionesPdfmake?.total) {
1208
+ txtImprimirTotal = tipoValorFuncion(titulo.reporte?.opcionesPdfmake?.total, titulo);
1209
+ console.warn(txtImprimirTotal);
1210
+ }
1211
+ else if (typeof titulo.reporte.totalizar === 'object') {
1212
+ if (typeof titulo.reporte.totalizar.transformar === 'function') {
1213
+ txtImprimirTotal = titulo.reporte.totalizar.transformar(titulo);
1214
+ }
1215
+ else if (titulo.reporte.totalizar?.campoTotal) {
1216
+ txtImprimirTotal = tabla.contenido[0] ? tabla.contenido[0][titulo.reporte.totalizar?.campoTotal] : '';
1217
+ }
1218
+ // txtImprimirTotal = titulo.reporte.transformar(titulo)
1219
+ }
1220
+ // @ts-ignore
1221
+ const tipoCol = titulo.type;
1222
+ filaTotales.push(imprimirCelda(txtImprimirTotal, tipoCol, {
1223
+ bold: true, style: 'thSmall', alignment: 'right',
1224
+ }));
1225
+ }
1226
+ else {
1227
+ filaTotales.push(imprimirCelda('', null, { border: [false, false, false, false] }));
1228
+ }
1229
+ });
1230
+ if (camposTotales && camposTotales.length > 0) {
1231
+ celdasBodyDetalle = celdasBodyDetalle.concat([filaTotales]);
1232
+ }
1233
+ let filaTabla = celdasHeaderDetalle.concat(celdasBodyDetalle);
1234
+ const tablaHeaderPedido = {
1235
+ margin: tabla.margin ?? [0, 5, 0, 10],
1236
+ table: {
1237
+ dontBreakRows: true,
1238
+ headerRows: tabla.filasTitulos ?? 1,
1239
+ widths: anchoCols(celdasBodyDetalle.length > 0 ? celdasBodyDetalle : celdasHeaderDetalle, tabla.idxResto ?? [], tabla.idxAnchoValor ?? []),
1240
+ body: filaTabla,
1241
+ },
1242
+ layout: tabla.sinBordes ? 'noBorders' : tabla.customLayout ?? undefined
1243
+ };
1244
+ if (tabla.separado) {
1245
+ return {
1246
+ titulos: celdasHeaderDetalle,
1247
+ cuerpo: celdasBodyDetalle,
1248
+ completo: tablaHeaderPedido,
1249
+ };
1250
+ }
1251
+ // console.log(JSON.stringify(tablaHeaderPedido))
1252
+ return tablaHeaderPedido;
1253
+ }
1254
+ function anchoCols(dataCant, idxResto = [], idxAnchoValor = []) {
1255
+ const retorno = [];
1256
+ if (Array.isArray(dataCant)) {
1257
+ if (dataCant.length === 0)
1258
+ return [];
1259
+ dataCant[0].forEach((_, idx) => {
1260
+ retorno.push(Array.isArray(idxResto) && idxResto.includes(idx) ? '*' : 'auto');
1261
+ });
1262
+ }
1263
+ else {
1264
+ for (let idx = 0; idx < dataCant; idx++) {
1265
+ if (Array.isArray(idxResto)) {
1266
+ retorno.push(idxResto.includes(idx) ? '*' : 'auto');
1267
+ }
1268
+ else {
1269
+ retorno.push('*');
1270
+ }
1271
+ }
1272
+ }
1273
+ idxAnchoValor.forEach(({ idx, valor }) => {
1274
+ if (idx == 'todos') {
1275
+ retorno.fill(valor);
1276
+ }
1277
+ else {
1278
+ retorno[idx] = valor;
1279
+ }
1280
+ });
1281
+ return retorno;
1282
+ }
1283
+ /**
1284
+ * Funciones PRIVADAS
1285
+ */
1286
+ function verificarColumnaTablaMantenimiento(titulo) {
1287
+ return titulo.visible !== false && !titulo.ocultarReporte && (!titulo.reporte || !titulo.reporte.ocultar);
1288
+ }
1289
+ function columnasValidas(titulos) {
1290
+ // Filtrar títulos visibles y válidos para el reporte
1291
+ return titulos.map(titulo => ({
1292
+ ...titulo,
1293
+ visible: titulo.visible ?? true, // Asignar `true` si `visible` es `undefined`
1294
+ })).filter(titulo => {
1295
+ return (titulo.visible &&
1296
+ !titulo.ocultarReporte &&
1297
+ (!titulo.reporte || !titulo.reporte.ocultar));
1298
+ });
1299
+ }
1300
+
1301
+ var formatearPdfmake = /*#__PURE__*/Object.freeze({
1302
+ __proto__: null,
1303
+ anchoCols: anchoCols,
1304
+ generarDesdeMantenimiento: generarDesdeMantenimiento,
1305
+ imprimirCelda: imprimirCelda
1306
+ });
1307
+
1308
+ class DataModel {
1309
+ modelosChk = {}; // Usar any para valores dinámicos
1310
+ checkbox;
1311
+ constructor() {
1312
+ this.checkbox = new ForCheckboxModel(this);
1313
+ }
1314
+ generarId(row, campoValor, separador = '') {
1315
+ if (typeof campoValor == 'string') {
1316
+ campoValor = [campoValor];
1317
+ }
1318
+ return campoValor.map(data => row[data]).join(separador);
1319
+ }
1320
+ // Agrega controles al objeto modelosChk
1321
+ agregarControles(lista, idLista, limpiar = true, campoValor = null, campoValorSeparador = '') {
1322
+ if (limpiar) {
1323
+ this.modelosChk = {};
1324
+ }
1325
+ const asignarValor = (dat, idLista, campoValor, key) => {
1326
+ if (!key) {
1327
+ key = dat[idLista] + (campoValor.includes('.') ? '' : `.${campoValor}`);
1328
+ }
1329
+ const mat = campoValor.match(/^([in])[A-Z][a-zA-Z]+/);
1330
+ if (mat) {
1331
+ this.modelosChk[key] = dat[campoValor] * 1;
1332
+ }
1333
+ else {
1334
+ this.modelosChk[key] = dat[campoValor];
1335
+ }
1336
+ };
1337
+ lista.forEach(dat => {
1338
+ if (campoValor === null) {
1339
+ // Caso 1: Sin campoValor, se asigna false
1340
+ this.modelosChk[dat[idLista]] = false;
1341
+ }
1342
+ else if (typeof campoValor === 'string') {
1343
+ // Caso 2: campoValor es un string
1344
+ asignarValor(dat, idLista, campoValor, dat[idLista]);
1345
+ }
1346
+ else if (campoValorSeparador) {
1347
+ const idStr = this.generarId(dat, campoValor, campoValorSeparador);
1348
+ // Caso 2: campoValor es un string
1349
+ asignarValor(dat, idLista, '.', idStr);
1350
+ }
1351
+ else {
1352
+ // Caso 3: campoValor es un array de strings
1353
+ campoValor.forEach(data => asignarValor(dat, idLista, data));
1354
+ }
1355
+ });
1356
+ }
1357
+ // Establece el estado de un índice
1358
+ setState(idx, state) {
1359
+ this.modelosChk[idx] = state;
1360
+ }
1361
+ // Obtiene el estado de un índice
1362
+ getState(idx) {
1363
+ return this.modelosChk[idx];
1364
+ }
1365
+ getDataMultiple(idx) {
1366
+ const camposMod = Object.keys(this.modelosChk).filter(key => key.split('.')[0] == idx);
1367
+ const vRet = {};
1368
+ camposMod.forEach(key => {
1369
+ vRet[key.split('.')[1]] = this.modelosChk[key];
1370
+ });
1371
+ return vRet;
1372
+ }
1373
+ // Genera una lista basada en el estado de los índices
1374
+ generarLista(tipoRetorno = null, esCampoNumerico = false) {
1375
+ const strLista = [];
1376
+ const objLista = {};
1377
+ Object.keys(this.modelosChk).forEach(key => {
1378
+ if ((esCampoNumerico && esNumero(this.modelosChk[key])) ||
1379
+ (this.modelosChk[key])) {
1380
+ strLista.push(key);
1381
+ objLista[key] = this.modelosChk[key];
1382
+ }
1383
+ });
1384
+ if (tipoRetorno === 'array') {
1385
+ return strLista;
1386
+ }
1387
+ if (tipoRetorno === 'object') {
1388
+ return objLista;
1389
+ }
1390
+ return strLista.join(',');
1391
+ }
1392
+ generarFormGroupFromModelosChk(tipo) {
1393
+ const formGroupObj = {};
1394
+ let validadores = [];
1395
+ if (tipo == 'number') {
1396
+ validadores = [
1397
+ Validators.required,
1398
+ Validators.min(1)
1399
+ ];
1400
+ }
1401
+ Object.keys(this.modelosChk).forEach(key => {
1402
+ formGroupObj[key] = new FormControl(this.modelosChk[key], validadores);
1403
+ });
1404
+ return new FormGroup(formGroupObj);
1405
+ // return this.formBuilder.group(formGroupObj);
1406
+ }
1407
+ }
1408
+ class ForCheckboxModel {
1409
+ modeloCheck;
1410
+ constructor(modeloCheck) {
1411
+ this.modeloCheck = modeloCheck;
1412
+ }
1413
+ get cantidadActivos() {
1414
+ return Object.values(this.modeloCheck.modelosChk).filter(Boolean).length;
1415
+ }
1416
+ get existenActivados() {
1417
+ return this.cantidadActivos > 0;
1418
+ }
1419
+ get todosActivos() {
1420
+ const total = Object.keys(this.modeloCheck.modelosChk).length;
1421
+ const activos = this.cantidadActivos;
1422
+ return activos > 0 && total === activos;
1423
+ }
1424
+ get algunosActivos() {
1425
+ const total = Object.keys(this.modeloCheck.modelosChk).length;
1426
+ const activos = this.cantidadActivos;
1427
+ return activos > 0 && total !== activos;
1428
+ }
1429
+ establecerTodos(activo) {
1430
+ Object.keys(this.modeloCheck.modelosChk).forEach(idx => this.modeloCheck.modelosChk[idx] = activo);
1431
+ }
1432
+ }
1433
+
1434
+ class DataEnListaPipe {
1435
+ transform(coleccion, idBuscar, dato) {
1436
+ if (coleccion) {
1437
+ if (Array.isArray(idBuscar)) {
1438
+ return coleccion.find(item => {
1439
+ const arrCoincide = [];
1440
+ idBuscar.forEach((campo, idx) => {
1441
+ // @ts-ignore
1442
+ arrCoincide.push((item[campo] == dato[idx]));
1443
+ });
1444
+ return arrCoincide.every(e => e === true);
1445
+ });
1446
+ }
1447
+ // @ts-ignore
1448
+ return coleccion.find(item => item[idBuscar] == dato);
1449
+ }
1450
+ return null;
1451
+ }
1452
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.7", ngImport: i0, type: DataEnListaPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe });
1453
+ static ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "19.1.7", ngImport: i0, type: DataEnListaPipe, isStandalone: true, name: "dataEnLista" });
1454
+ }
1455
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.7", ngImport: i0, type: DataEnListaPipe, decorators: [{
1456
+ type: Pipe,
1457
+ args: [{
1458
+ name: 'dataEnLista',
1459
+ }]
1460
+ }] });
1461
+ function dataEnLista(coleccion, idBuscar, dato) {
1462
+ return new DataEnListaPipe().transform(coleccion, idBuscar, dato);
1463
+ }
1464
+
1465
+ class DateDiffStringPipe {
1466
+ transform(startingDate, endingDate) {
1467
+ let startDate = new Date(startingDate);
1468
+ // user not pass endingDate then set current date as end date.
1469
+ if (!endingDate) {
1470
+ endingDate = new Date();
1471
+ }
1472
+ let endDate = new Date(endingDate);
1473
+ // chack start date and end date and base on condication alter date.
1474
+ if (startDate > endDate) {
1475
+ const swap = startDate;
1476
+ startDate = endDate;
1477
+ endDate = swap;
1478
+ }
1479
+ const disgregado = this.separarMilisegundos(endDate.getTime() - startDate.getTime());
1480
+ // console.log(disgregado);
1481
+ const formatearATexto = (arrayToFill, campo, texto, textoPlural = 's') => {
1482
+ if (campo > 0) {
1483
+ arrayToFill.push(campo + ' ' + texto + (campo > 1 ? textoPlural : ''));
1484
+ }
1485
+ return arrayToFill;
1486
+ };
1487
+ let arrDFinal = [];
1488
+ arrDFinal = formatearATexto(arrDFinal, disgregado.years, 'año');
1489
+ arrDFinal = formatearATexto(arrDFinal, disgregado.months, 'mes', 'es');
1490
+ arrDFinal = formatearATexto(arrDFinal, disgregado.weeks, 'semana');
1491
+ arrDFinal = formatearATexto(arrDFinal, disgregado.days, 'día');
1492
+ arrDFinal = formatearATexto(arrDFinal, disgregado.hours, 'hora');
1493
+ arrDFinal = formatearATexto(arrDFinal, disgregado.minutes, 'minuto');
1494
+ arrDFinal = formatearATexto(arrDFinal, disgregado.seconds, 'segundo');
1495
+ if (arrDFinal.length > 3) {
1496
+ arrDFinal.splice(3);
1497
+ arrDFinal.splice(-1, 0, 'y');
1498
+ }
1499
+ else {
1500
+ if (arrDFinal.length > 1) {
1501
+ arrDFinal.splice(-1, 0, 'y');
1502
+ }
1503
+ }
1504
+ return arrDFinal.join(' ');
1505
+ }
1506
+ separarMilisegundos(milisegundos) {
1507
+ const todoEnSegundos = milisegundos / 1000;
1508
+ let secsUsed = 0;
1509
+ const years = Math.floor(todoEnSegundos / 31536000);
1510
+ if (years > 0) {
1511
+ secsUsed += (years * 31536000);
1512
+ }
1513
+ const months = Math.floor((todoEnSegundos - secsUsed) / 2628288);
1514
+ if (months > 0) {
1515
+ secsUsed += (months * 2628288);
1516
+ }
1517
+ const weeks = Math.floor((todoEnSegundos - secsUsed) / 604800);
1518
+ if (weeks > 0) {
1519
+ secsUsed += (weeks * 604800);
1520
+ }
1521
+ const days = Math.floor((todoEnSegundos - secsUsed) / 86400);
1522
+ if (days > 0) {
1523
+ secsUsed += (days * 86400);
1524
+ }
1525
+ const hours = Math.floor((todoEnSegundos - secsUsed) / 3600);
1526
+ if (hours > 0) {
1527
+ secsUsed += (hours * 3600);
1528
+ }
1529
+ const minutes = Math.floor((todoEnSegundos - secsUsed) / 60);
1530
+ if (minutes > 0) {
1531
+ secsUsed += (minutes * 60);
1532
+ }
1533
+ const seconds = Math.round(todoEnSegundos - secsUsed);
1534
+ return {
1535
+ years,
1536
+ months,
1537
+ weeks,
1538
+ days,
1539
+ hours,
1540
+ minutes,
1541
+ seconds,
1542
+ };
1543
+ }
1544
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.7", ngImport: i0, type: DateDiffStringPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe });
1545
+ static ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "19.1.7", ngImport: i0, type: DateDiffStringPipe, isStandalone: true, name: "dateDiffString" });
1546
+ }
1547
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.7", ngImport: i0, type: DateDiffStringPipe, decorators: [{
1548
+ type: Pipe,
1549
+ args: [{
1550
+ name: 'dateDiffString',
1551
+ pure: true
1552
+ }]
1553
+ }] });
1554
+ function dateDiffString(startingDate, endingDate) {
1555
+ return new DateDiffStringPipe().transform(startingDate, endingDate);
1556
+ }
1557
+
1558
+ class FiltroPipe {
1559
+ transform(items, opcionesBusqueda) {
1560
+ if (!items || !Array.isArray(items))
1561
+ return [];
1562
+ if (!opcionesBusqueda.texto || opcionesBusqueda.texto.length < (opcionesBusqueda.longitudMinima ?? 1))
1563
+ return items;
1564
+ const normalize = (() => {
1565
+ const from = 'ÃÀÁÄÂÈÉËÊÌÍÏÎÒÓÖÔÙÚÜÛãàáäâèéëêìíïîòóöôùúüûÑñÇç';
1566
+ const to = 'AAAAAEEEEIIIIOOOOUUUUaaaaaeeeeiiiioooouuuunncc';
1567
+ const mapping = {};
1568
+ for (let i = 0; i < from.length; i++) {
1569
+ mapping[from[i]] = to[i];
1570
+ }
1571
+ return (str) => {
1572
+ return str.split('').map(c => mapping[c] || c).join('');
1573
+ };
1574
+ })();
1575
+ const textoNormalizado = normalize(opcionesBusqueda.texto.toLowerCase());
1576
+ return items.filter(item => {
1577
+ // 🔹 Manejo de `mostrarObligado`
1578
+ if (opcionesBusqueda.mostrarObligado) {
1579
+ const { campo, items: obligados } = opcionesBusqueda.mostrarObligado;
1580
+ if (obligados.includes(item[campo]))
1581
+ return true;
1582
+ }
1583
+ // 🔹 Manejo de `campo`
1584
+ if (opcionesBusqueda.campo) {
1585
+ if (Array.isArray(opcionesBusqueda.campo)) {
1586
+ return opcionesBusqueda.campo.some(campo => {
1587
+ const valor = item[campo];
1588
+ return valor ? normalize(valor.toLowerCase()).includes(textoNormalizado) : false;
1589
+ });
1590
+ }
1591
+ else {
1592
+ const valor = item[opcionesBusqueda.campo];
1593
+ return valor ? normalize(valor.toLowerCase()).includes(textoNormalizado) : false;
1594
+ }
1595
+ }
1596
+ return false;
1597
+ });
1598
+ }
1599
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.7", ngImport: i0, type: FiltroPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe });
1600
+ static ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "19.1.7", ngImport: i0, type: FiltroPipe, isStandalone: true, name: "filtro" });
1601
+ }
1602
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.7", ngImport: i0, type: FiltroPipe, decorators: [{
1603
+ type: Pipe,
1604
+ args: [{
1605
+ name: 'filtro'
1606
+ }]
1607
+ }] });
1608
+
1609
+ class FormControlIsRequiredPipe {
1610
+ transform(formControl, ...args) {
1611
+ if (!formControl) {
1612
+ return false;
1613
+ }
1614
+ return formControl.hasValidator(Validators.required);
1615
+ }
1616
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.7", ngImport: i0, type: FormControlIsRequiredPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe });
1617
+ static ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "19.1.7", ngImport: i0, type: FormControlIsRequiredPipe, isStandalone: true, name: "formControlIsRequired" });
1618
+ }
1619
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.7", ngImport: i0, type: FormControlIsRequiredPipe, decorators: [{
1620
+ type: Pipe,
1621
+ args: [{
1622
+ name: 'formControlIsRequired'
1623
+ }]
1624
+ }] });
1625
+ function formControlIsRequired(formControl) {
1626
+ return new FormControlIsRequiredPipe().transform(formControl);
1627
+ }
1628
+
1629
+ class JsonParsePipe {
1630
+ transform(value, ...args) {
1631
+ if (!value) {
1632
+ return [];
1633
+ }
1634
+ try {
1635
+ return JSON.parse(value);
1636
+ }
1637
+ catch (e) {
1638
+ console.warn('La cadena "' + value + '" no es JSON');
1639
+ return [];
1640
+ }
1641
+ }
1642
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.7", ngImport: i0, type: JsonParsePipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe });
1643
+ static ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "19.1.7", ngImport: i0, type: JsonParsePipe, isStandalone: true, name: "jsonParse" });
1644
+ }
1645
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.7", ngImport: i0, type: JsonParsePipe, decorators: [{
1646
+ type: Pipe,
1647
+ args: [{
1648
+ name: 'jsonParse'
1649
+ }]
1650
+ }] });
1651
+
1652
+ class NoSanitizePipe {
1653
+ domSanitizer;
1654
+ constructor(domSanitizer) {
1655
+ this.domSanitizer = domSanitizer;
1656
+ }
1657
+ transform(html) {
1658
+ return this.domSanitizer.bypassSecurityTrustHtml(html);
1659
+ }
1660
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.7", ngImport: i0, type: NoSanitizePipe, deps: [{ token: i1.DomSanitizer }], target: i0.ɵɵFactoryTarget.Pipe });
1661
+ static ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "19.1.7", ngImport: i0, type: NoSanitizePipe, isStandalone: true, name: "noSanitize" });
1662
+ }
1663
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.7", ngImport: i0, type: NoSanitizePipe, decorators: [{
1664
+ type: Pipe,
1665
+ args: [{ name: 'noSanitize' }]
1666
+ }], ctorParameters: () => [{ type: i1.DomSanitizer }] });
1667
+
1668
+ class ZeroFillPipe {
1669
+ transform(value, digitos, ...args) {
1670
+ let s = value + '';
1671
+ while (s.length < digitos) {
1672
+ s = '0' + s;
1673
+ }
1674
+ return s;
1675
+ }
1676
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.1.7", ngImport: i0, type: ZeroFillPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe });
1677
+ static ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "19.1.7", ngImport: i0, type: ZeroFillPipe, isStandalone: true, name: "zeroFill" });
1678
+ }
1679
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.1.7", ngImport: i0, type: ZeroFillPipe, decorators: [{
1680
+ type: Pipe,
1681
+ args: [{
1682
+ name: 'zeroFill',
1683
+ }]
1684
+ }] });
1685
+ function zeroFill(value, digitos, ...args) {
1686
+ return new ZeroFillPipe().transform(value, digitos, args);
1687
+ }
1688
+
1689
+ /*
1690
+ * Public API Surface of utils
1691
+ */
1692
+ // export * from './functions/common.function';
1693
+ // export * from './lib/utils.component';
1694
+ // export * from './lib/utils.service';
1695
+
1696
+ /**
1697
+ * Generated bundle index. Do not edit.
1698
+ */
1699
+
1700
+ export { DataEnListaPipe, DataModel, DateDiffStringPipe, FiltroPipe, FormControlIsRequiredPipe, JsonParsePipe, NoSanitizePipe, formatearPdfmake as PdfMake, ZeroFillPipe, b64Decode, b64Encode, buscarPorCampo, changeSelect, changeSelectApi, changeSelectData, changeSelectDataApi, dataEnLista, dateDiffString, deepClone, deepMerge, delLocalStorage, desencriptar, encriptar, esNumero, establecerQuitarRequired, finalizarGuardadoMantenimiento, formControlIsRequired, formatearFecha, formatearFechaCadena, formatearFechaFormato, generateRandomString, getBrowserName, getCambiarPwd, getFormValidationErrors, getLocalStorage, getUniqueValues, getUniqueValuesByProperty, inicializarVariablesSessionStorage, jwtToken, jwtTokenData, jwtTokenExpiracion, jwtTokenExpiracionFaltante, localStorageKeys, markAsTouchedWithoutEmitEvent, mensajeAlerta, mensajeConfirmacion, mensajeTimer, mensajeToast, mensajesDeError, mensajesErrorFormControl, mostrarValorEnBusqueda, objectPropertiesToType, obtenerMimeType, ordenarArray, ordenarPorPropiedad, ordenarPorPropiedades, sanitizarNombreArchivo, setCambiarPwd, setJwtTokenData, setLocalStorage, sumarObjetos, sumarPropiedades, tipoValorFuncion, toFormData, zeroFill };
1701
+ //# sourceMappingURL=jvsoft-utils.mjs.map