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