@jvsoft/utils 0.0.13-alpha.4 → 0.0.13-alpha.6

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 +1450 -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 +1867 -0
  9. package/fesm2022/jvsoft-utils.mjs.map +1 -0
  10. package/functions/base64.d.ts +26 -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 +51 -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 +147 -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 +28 -12
  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 +26 -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 +51 -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 +147 -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 -25
  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 -251
  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 -205
  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 -85
  94. package/src/functions/object-transformation.ts +0 -37
  95. package/src/functions/objects-arrays.ts +0 -321
  96. package/src/functions/public-api.ts +0 -19
  97. package/src/functions/string.ts +0 -68
  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 -18
  118. package/tsconfig.lib.prod.json +0 -11
  119. package/tsconfig.spec.json +0 -15
@@ -0,0 +1,1450 @@
1
+ import { untilDestroyed } from '@ngneat/until-destroy';
2
+ import { startWith, debounceTime, tap, isObservable, switchMap, of, finalize } from 'rxjs';
3
+ import { map } from 'rxjs/operators';
4
+ import { Buffer } from 'buffer';
5
+ import CryptoJS from 'crypto-js';
6
+ import { formatDate } from '@angular/common';
7
+ import { saveAs } from 'file-saver';
8
+ import { Validators, FormGroup, FormControl, FormArray } from '@angular/forms';
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
+
14
+ /**
15
+ * Realiza una fusión profunda entre dos objetos, sin modificar el original.
16
+ * Si el valor en target no es un objeto, lo reemplaza directamente.
17
+ *
18
+ * @param source - Objeto fuente que se clonará y fusionará.
19
+ * @param target - Objeto destino cuyos valores se fusionarán.
20
+ * @returns Un nuevo objeto con la fusión profunda.
21
+ */
22
+ function deepMerge(source, target) {
23
+ // Crea un clon profundo sin usar JSON.parse(JSON.stringify)
24
+ let cloneSource = deepClone(source);
25
+ if (typeof target !== 'object' || target === null) {
26
+ return target;
27
+ }
28
+ if (typeof cloneSource !== 'object' || cloneSource === null) {
29
+ cloneSource = Array.isArray(target) ? [] : {};
30
+ }
31
+ for (const key of Object.keys(target)) {
32
+ const targetValue = target[key];
33
+ const sourceValue = cloneSource[key];
34
+ if (typeof targetValue === 'object' && targetValue !== null && !Array.isArray(targetValue)) {
35
+ cloneSource[key] = deepMerge(sourceValue, targetValue);
36
+ }
37
+ else {
38
+ cloneSource[key] = targetValue;
39
+ }
40
+ }
41
+ return cloneSource; // Retorna el clon y no modifica el original
42
+ }
43
+ /**
44
+ * Realiza una clonación profunda de un objeto, manejando funciones, fechas y arrays.
45
+ *
46
+ * @param obj - Objeto a clonar.
47
+ * @returns Una copia profunda del objeto.
48
+ */
49
+ function deepClone(obj) {
50
+ if (obj === null || typeof obj !== 'object') {
51
+ return obj; // Devuelve el valor si no es un objeto
52
+ }
53
+ // Manejar instancias de Date
54
+ if (obj instanceof Date) {
55
+ return new Date(obj.getTime());
56
+ }
57
+ // Manejar funciones devolviendo una copia directa
58
+ if (typeof obj === 'function') {
59
+ return obj.bind({}); // Devuelve una copia de la función enlazada a un contexto vacío
60
+ }
61
+ // Crear un nuevo objeto o array
62
+ const clonedObj = Array.isArray(obj) ? [] : {};
63
+ // Clonar recursivamente las propiedades del objeto
64
+ for (const key in obj) {
65
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
66
+ clonedObj[key] = deepClone(obj[key]);
67
+ }
68
+ }
69
+ return clonedObj;
70
+ }
71
+ /**
72
+ * Busca un elemento en un array o jerarquía de objetos según un campo y valor especificado.
73
+ *
74
+ * @param datosFn - Objeto con los parámetros de búsqueda: items, campo, valor y opcionalmente campoHijo.
75
+ * @returns El elemento encontrado o undefined si no existe.
76
+ */
77
+ function buscarPorCampo(datosFn) {
78
+ for (const item of datosFn.items) {
79
+ // Verifica si el campo coincide con el valor
80
+ if (item[datosFn.campo] === datosFn.valor) {
81
+ return item;
82
+ }
83
+ // Verifica si hay un campo hijo y si es un array
84
+ if (datosFn.campoHijo && item[datosFn.campoHijo] && Array.isArray(item[datosFn.campoHijo])) {
85
+ // Realiza la búsqueda recursiva en el campo hijo
86
+ const encontrado = buscarPorCampo({
87
+ items: item[datosFn.campoHijo], // Asegura el tipo correcto
88
+ campo: datosFn.campo,
89
+ valor: datosFn.valor,
90
+ campoHijo: datosFn.campoHijo,
91
+ });
92
+ // Si se encuentra el valor en el campo hijo, retorna el resultado
93
+ if (encontrado) {
94
+ return encontrado;
95
+ }
96
+ }
97
+ }
98
+ // Si no se encuentra nada, retorna undefined
99
+ return undefined;
100
+ }
101
+ /**
102
+ * Suma los valores de las propiedades especificadas de un objeto.
103
+ *
104
+ * @param item - Objeto con las propiedades a sumar.
105
+ * @param campos - Array de nombres de las propiedades a sumar.
106
+ * @returns La suma de los valores de las propiedades.
107
+ */
108
+ function sumarPropiedades(item, campos) {
109
+ const datosSumar = campos.map(campo => (item[campo] * 1));
110
+ return datosSumar.reduce((a, b) => a + b, 0);
111
+ }
112
+ /**
113
+ * Verifica si el valor proporcionado es un número válido.
114
+ *
115
+ * @param value - Valor a verificar.
116
+ * @returns true si es un número, false en caso contrario.
117
+ */
118
+ function esNumero(value) {
119
+ return !isNaN(Number(value));
120
+ }
121
+ /**
122
+ * Suma los valores de las propiedades especificadas en un array de objetos.
123
+ *
124
+ * @param arrayObjetos - Array de objetos a procesar.
125
+ * @param campos - Array de nombres de las propiedades a sumar.
126
+ * @returns Objeto con la suma de cada propiedad.
127
+ */
128
+ function sumarObjetos(arrayObjetos, campos) {
129
+ return arrayObjetos.reduce((accumulator, item) => {
130
+ campos.forEach(campo => {
131
+ const valor = Number(item[campo]);
132
+ if (!isNaN(valor)) {
133
+ accumulator[campo] = (accumulator[campo] ?? 0) + valor;
134
+ }
135
+ });
136
+ return accumulator;
137
+ }, {});
138
+ }
139
+ /**
140
+ * Obtiene los valores únicos de un array.
141
+ *
142
+ * @param array - Array de valores.
143
+ * @returns Array con los valores únicos.
144
+ */
145
+ function getUniqueValues(array) {
146
+ return array.filter((currentValue, index, arr) => (arr.indexOf(currentValue) === index));
147
+ }
148
+ /**
149
+ * Obtiene los objetos únicos de un array según una propiedad específica.
150
+ *
151
+ * @param objetos - Array de objetos.
152
+ * @param campo - Nombre de la propiedad para determinar unicidad.
153
+ * @returns Array de objetos únicos por la propiedad.
154
+ */
155
+ function getUniqueValuesByProperty(objetos, campo) {
156
+ const objetosUnicos = {};
157
+ objetos.forEach(objeto => {
158
+ // Verificar si el objeto tiene el campo especificado
159
+ // @ts-ignore
160
+ if (objeto.hasOwnProperty(campo)) {
161
+ // @ts-ignore
162
+ const valorCampo = objeto[campo];
163
+ // Utilizar el valor del campo como clave en un objeto para asegurar que no haya duplicados
164
+ objetosUnicos[valorCampo] = objeto;
165
+ }
166
+ });
167
+ // Convertir el objeto de claves únicas de vuelta a una lista de objetos
168
+ return Object.values(objetosUnicos);
169
+ }
170
+ /**
171
+ * Ordena un array de valores numéricos o alfabéticos.
172
+ *
173
+ * @param array - Array a ordenar.
174
+ * @param numeros - Si es true, ordena como números.
175
+ * @param sentido - 'ASC' para ascendente, 'DESC' para descendente.
176
+ * @returns Array ordenado.
177
+ */
178
+ function ordenarArray(array, numeros = false, sentido = 'ASC') {
179
+ if (numeros) {
180
+ if (sentido != 'ASC') {
181
+ return array.sort((a, b) => b - a);
182
+ }
183
+ return array.sort((a, b) => a - b);
184
+ }
185
+ return array.sort((a, b) => (a > b) ? 1 : ((b > a) ? -1 : 0));
186
+ }
187
+ /**
188
+ * Ordena un array de objetos por una propiedad específica.
189
+ *
190
+ * @param objData - Array de objetos a ordenar.
191
+ * @param propiedad - Propiedad por la que se ordena.
192
+ * @param numeros - (Obsoleto) Si es true, ordena como números.
193
+ * @returns Array ordenado.
194
+ */
195
+ function ordenarPorPropiedad(objData, propiedad, /**@deprecated*/ numeros = false) {
196
+ return ordenarPorPropiedades(objData, { propiedades: [propiedad], direcciones: ['asc'] });
197
+ }
198
+ /**
199
+ * Ordena un array de objetos por varias propiedades y direcciones.
200
+ *
201
+ * @param arr - Array de objetos a ordenar.
202
+ * @param options - Opciones con propiedades y direcciones de orden.
203
+ * @returns Array ordenado.
204
+ */
205
+ function ordenarPorPropiedades(arr, options) {
206
+ const { propiedades, direcciones = [] } = options;
207
+ const orden = direcciones.map(d => d === 'desc' ? -1 : 1);
208
+ return [...arr].sort((a, b) => {
209
+ return propiedades.reduce((acc, propiedad, index) => {
210
+ if (acc !== 0)
211
+ return acc; // Si ya hay diferencia, no seguir comparando
212
+ const aValue = a[propiedad];
213
+ const bValue = b[propiedad];
214
+ if (typeof aValue === 'string' && typeof bValue === 'string') {
215
+ return aValue.localeCompare(bValue) * orden[index]; // 🔹 Comparación alfabética
216
+ }
217
+ if (typeof aValue === 'number' && typeof bValue === 'number') {
218
+ return (aValue - bValue) * orden[index]; // 🔹 Comparación numérica
219
+ }
220
+ return 0; // En caso de valores no comparables
221
+ }, 0);
222
+ });
223
+ }
224
+ /**
225
+ * Agrupa los elementos de un array según una clave o función de clave.
226
+ *
227
+ * @param array - Array de objetos a agrupar.
228
+ * @param key - Propiedad o función para agrupar.
229
+ * @returns Objeto con los grupos por clave.
230
+ */
231
+ function groupBy(array, key) {
232
+ const keyFn = key instanceof Function ? key : (obj) => obj[key];
233
+ return array.reduce((objectsByKeyValue, obj) => {
234
+ const value = keyFn(obj);
235
+ objectsByKeyValue[value] = (objectsByKeyValue[value] || []).concat(obj);
236
+ return objectsByKeyValue;
237
+ }, {});
238
+ }
239
+ /**
240
+ * Agrupa y anida los elementos de un array según una lista de propiedades.
241
+ *
242
+ * @param arr - Array de objetos a agrupar.
243
+ * @param properties - Propiedades para agrupar de forma anidada.
244
+ * @returns Objeto anidado por los grupos de propiedades.
245
+ */
246
+ function nestGroupsBy(arr, properties) {
247
+ const fnGroupBy = (conversions, property2) => {
248
+ return conversions.reduce((acc, obj) => {
249
+ const key = obj[property2];
250
+ if (!acc[key]) {
251
+ acc[key] = [];
252
+ }
253
+ acc[key].push(obj);
254
+ return acc;
255
+ }, {});
256
+ };
257
+ properties = Array.from(properties);
258
+ if (properties.length === 1) {
259
+ return fnGroupBy(arr, properties[0]);
260
+ }
261
+ const property = properties.shift();
262
+ const grouped = fnGroupBy(arr, property);
263
+ Object.keys(grouped).forEach(key => {
264
+ grouped[key] = nestGroupsBy(grouped[key], Array.from(properties));
265
+ });
266
+ return grouped;
267
+ }
268
+ /**
269
+ * Obtiene un valor de un objeto usando una ruta de propiedad anidada.
270
+ *
271
+ * @param obj - Objeto de entrada.
272
+ * @param path - Ruta en formato punto (ej: "cliente.orden").
273
+ * @returns El valor encontrado o undefined si no existe.
274
+ */
275
+ function getValueByPath(obj, path) {
276
+ return path.split('.').reduce((acc, key) => acc?.[key], obj);
277
+ }
278
+ /**
279
+ * Retorna el valor máximo del campo especificado (incluso anidado) en un arreglo de objetos.
280
+ *
281
+ * @param data - Lista de objetos a procesar.
282
+ * @param campo - Nombre del campo a evaluar, puede ser anidado (ej. "campo.orden").
283
+ * @param incrementar - Si es true, retorna el valor máximo + 1. Por defecto es true.
284
+ * @returns El valor máximo encontrado, posiblemente incrementado.
285
+ */
286
+ function obtenerUltimoOrden(data, campo, incrementar = true) {
287
+ const max = data.reduce((mayor, item) => {
288
+ const valor = Number(getValueByPath(item, campo)) || 0;
289
+ return valor > mayor ? valor : mayor;
290
+ }, 0);
291
+ return incrementar ? max + 1 : max;
292
+ }
293
+ /**
294
+ * Elimina una o varias columnas específicas (por índice) de una tabla representada como array de arrays.
295
+ *
296
+ * @param data - Array de filas (cada fila debe ser un array).
297
+ * @param columnIndex - Índice o lista de índices de las columnas a eliminar.
298
+ * @returns Nuevo array con las columnas eliminadas.
299
+ */
300
+ function eliminarColumnaPorIndex(data, columnIndex) {
301
+ if (!Array.isArray(data))
302
+ return [];
303
+ // Normalizar a array único y ordenado (descendente para evitar reindexación al splicing)
304
+ const indices = Array.isArray(columnIndex)
305
+ ? [...new Set(columnIndex)].filter((i) => (typeof i === 'number' && i >= 0)).sort((a, b) => b - a)
306
+ : [columnIndex];
307
+ return data.map((row) => {
308
+ if (!Array.isArray(row))
309
+ return row;
310
+ const newRow = [...row];
311
+ for (const index of indices) {
312
+ if (index >= 0 && index < newRow.length) {
313
+ newRow.splice(index, 1);
314
+ }
315
+ }
316
+ return newRow;
317
+ });
318
+ }
319
+ /**
320
+ * Elimina elementos duplicados de un array de objetos según claves específicas.
321
+ *
322
+ * @param array - Array de objetos.
323
+ * @param claves - Claves para determinar unicidad. Si no se especifica, compara todo el objeto.
324
+ * @returns Array sin duplicados.
325
+ */
326
+ function eliminarDuplicados(array, claves) {
327
+ const unicos = new Map();
328
+ for (const item of array) {
329
+ const claveUnica = claves && claves.length > 0
330
+ ? claves.map(k => item[k]).join('|')
331
+ : JSON.stringify(item);
332
+ if (!unicos.has(claveUnica)) {
333
+ unicos.set(claveUnica, item);
334
+ }
335
+ }
336
+ return Array.from(unicos.values());
337
+ }
338
+ /**
339
+ * Elimina elementos de un array origen que estén presentes en otro array, según claves específicas.
340
+ *
341
+ * @param origen - Array original.
342
+ * @param elementosAEliminar - Elementos a eliminar del array origen.
343
+ * @param claves - Claves para comparar los objetos. Si no se especifica, compara todo el objeto.
344
+ * @returns Array filtrado sin los elementos eliminados.
345
+ */
346
+ function eliminarElementos(origen, elementosAEliminar, claves) {
347
+ const clavesSet = new Set();
348
+ for (const item of elementosAEliminar) {
349
+ const key = claves && claves.length > 0
350
+ ? claves.map(k => item[k]).join('|')
351
+ : JSON.stringify(item);
352
+ clavesSet.add(key);
353
+ }
354
+ return origen.filter(item => {
355
+ const key = claves && claves.length > 0
356
+ ? claves.map(k => item[k]).join('|')
357
+ : JSON.stringify(item);
358
+ return !clavesSet.has(key);
359
+ });
360
+ }
361
+
362
+ /**
363
+ * Devuelve un valor de visualización para un elemento buscado.
364
+ * Compatible con listas simples, objetos y campos múltiples.
365
+ */
366
+ function mostrarValorEnBusqueda(campos, idxSel) {
367
+ const buscarEnLista = (lista) => {
368
+ if (!lista)
369
+ return null;
370
+ if (campos.campoId === '*object*' || campos.campoId === '*objeto*') {
371
+ return lista.find((x) => JSON.stringify(x).trim() === JSON.stringify(idxSel).trim());
372
+ }
373
+ return lista.find((x) => x[campos.campoId] === idxSel);
374
+ };
375
+ const impDataMostrar = () => {
376
+ let vD = buscarEnLista(campos.lista) || (campos.opcExtra && buscarEnLista(campos.opcExtra));
377
+ if (!vD)
378
+ return '';
379
+ if (Array.isArray(campos.campoValue)) {
380
+ return campos.campoValue.map((vCampo) => vD[vCampo] ?? '').join(' - ').trim();
381
+ }
382
+ return (vD[campos.campoValue] ?? '').trim();
383
+ };
384
+ if (esNumero(idxSel)) {
385
+ if ((idxSel > 0 && campos.lista?.length) || (idxSel && typeof idxSel === 'object')) {
386
+ return impDataMostrar();
387
+ }
388
+ }
389
+ else if (campos.lista?.length) {
390
+ return impDataMostrar();
391
+ }
392
+ return '';
393
+ }
394
+ /**
395
+ * Filtra datos locales de un array basado en un valor de búsqueda.
396
+ */
397
+ function filtrarDatosLocal(data, value, campoBuscar) {
398
+ if (!value)
399
+ return data;
400
+ const normalizar = (val) => val?.toString()?.toLowerCase() ?? '';
401
+ const esNum = !isNaN(Number(value));
402
+ return data.filter(item => {
403
+ const campos = Array.isArray(campoBuscar) ? campoBuscar : [campoBuscar];
404
+ return campos.some(campo => {
405
+ const campoVal = item[campo];
406
+ if (campoVal == null)
407
+ return false;
408
+ return esNum
409
+ ? campoVal.toString().includes(value.toString())
410
+ : normalizar(campoVal).includes(normalizar(value));
411
+ });
412
+ });
413
+ }
414
+ /**
415
+ * Vincula un FormControl a datos locales para autocompletado.
416
+ */
417
+ function changeSelectData(objThis, { formControl, data, campoBuscar, variableResultado }) {
418
+ objThis.filtrados[variableResultado] = formControl.valueChanges.pipe(untilDestroyed(objThis)).pipe(startWith(''), map(value => data ? filtrarDatosLocal(data, value, campoBuscar) : []));
419
+ }
420
+ /**
421
+ * Vincula un FormControl a datos locales obtenidos de dataServidor o dataServidorSuscripcion.
422
+ */
423
+ function changeSelect(control, formControl, tipo, campoBuscar, campoFiltro = null) {
424
+ const filtro = campoFiltro ?? tipo;
425
+ control.filtrados[filtro] = formControl.valueChanges.pipe(untilDestroyed(control)).pipe(startWith(''), map(value => {
426
+ const partes = tipo.split('.');
427
+ const varN = control.dataServidor?.[partes[0]]?.[partes[1]] ??
428
+ control.dataServidor?.[tipo] ??
429
+ control.dataServidorSuscripcion?.[tipo]?.getValue();
430
+ return varN ? filtrarDatosLocal(varN, value, campoBuscar) : [];
431
+ }));
432
+ }
433
+ /**
434
+ * Función genérica para vincular un FormControl con datos desde API o Promise.
435
+ * Preparada para migrar a signals en el futuro.
436
+ */
437
+ function changeSelectReformateado(config) {
438
+ const { objThis, tipoReq, formControl, queryService, campoId, minLength = 3, dataExtra = {}, dataExtraVariable = [], anonimo = false, variableResultado = tipoReq, } = config;
439
+ formControl.valueChanges.pipe(debounceTime(500), tap(() => {
440
+ objThis.filtrados[variableResultado + 'tmp'] = isObservable(objThis.filtrados[variableResultado])
441
+ ? []
442
+ : objThis.filtrados[variableResultado] || [];
443
+ if (objThis.filtrados[variableResultado] !== objThis.filtrados[variableResultado + 'tmp']) {
444
+ objThis.filtrados[variableResultado] = [];
445
+ }
446
+ objThis.isLoading = true;
447
+ }), switchMap(value => {
448
+ if (campoId) {
449
+ const existe = objThis.filtrados[variableResultado + 'tmp']
450
+ .findIndex((item) => item[campoId] === value);
451
+ if (existe >= 0) {
452
+ return of({ [tipoReq]: objThis.filtrados[variableResultado + 'tmp'] });
453
+ }
454
+ }
455
+ if (!value || value.length < minLength) {
456
+ objThis.isLoading = false;
457
+ return of({ [tipoReq]: [] });
458
+ }
459
+ const extraVars = Object.fromEntries(dataExtraVariable.map(v => [v.campo, v.ctrlValue.value]));
460
+ const query = queryService.getDataMethod('GET', tipoReq, { ...dataExtra, ...extraVars, txtBuscar: value }, anonimo);
461
+ if (esPromise(query)) {
462
+ return query.then((data) => ({ [tipoReq]: data[tipoReq] ?? [] }))
463
+ .finally(() => { objThis.isLoading = false; });
464
+ }
465
+ return query.pipe(finalize(() => { objThis.isLoading = false; }));
466
+ })).subscribe((data) => {
467
+ objThis.filtrados[variableResultado] = data[tipoReq] ?? [];
468
+ });
469
+ }
470
+ /**
471
+ * Alias para compatibilidad.
472
+ */
473
+ function changeSelectDataApi(objThis, dataFiltro) {
474
+ return changeSelectReformateado({
475
+ objThis,
476
+ tipoReq: dataFiltro.tipoReq,
477
+ formControl: dataFiltro.formControl,
478
+ queryService: dataFiltro.queryService,
479
+ campoId: dataFiltro.campoId,
480
+ minLength: dataFiltro.minLength,
481
+ dataExtra: dataFiltro.dataExtra,
482
+ dataExtraVariable: dataFiltro.dataExtraVariable,
483
+ anonimo: dataFiltro.anonimo,
484
+ variableResultado: dataFiltro.variableResultado,
485
+ });
486
+ }
487
+ /**
488
+ * Alias para compatibilidad.
489
+ */
490
+ function changeSelectApi(control, queryService, formControl, tipo, dataExtra = {}, dataExtraVariable = null, minLength = 1, anonimo = false) {
491
+ return changeSelectReformateado({
492
+ objThis: control,
493
+ tipoReq: tipo,
494
+ formControl,
495
+ queryService,
496
+ minLength,
497
+ dataExtra,
498
+ dataExtraVariable: dataExtraVariable ?? [],
499
+ anonimo,
500
+ });
501
+ }
502
+ /**
503
+ * Comprueba si un valor es una Promesa.
504
+ */
505
+ function esPromise(valor) {
506
+ return !!valor && typeof valor.then === 'function';
507
+ }
508
+
509
+ function seleccionarTextoInput(event) {
510
+ event.target.select();
511
+ }
512
+
513
+ function b64Encode(val) {
514
+ return Buffer.from(val, 'binary').toString('base64');
515
+ }
516
+ function b64Decode(val) {
517
+ return Buffer.from(val, 'base64').toString('binary');
518
+ }
519
+ /**
520
+ * Codificar string a Base64 (UTF-8 seguro)
521
+ */
522
+ function encodeBase64String(str) {
523
+ const encoder = new TextEncoder();
524
+ const bytes = encoder.encode(str);
525
+ let binary = '';
526
+ bytes.forEach(b => binary += String.fromCharCode(b));
527
+ return btoa(binary);
528
+ }
529
+ /**
530
+ * Decodificar Base64 a string (UTF-8 seguro)
531
+ */
532
+ function decodeBase64String(b64) {
533
+ const binary = atob(b64);
534
+ const bytes = new Uint8Array(binary.length);
535
+ for (let i = 0; i < binary.length; i++) {
536
+ bytes[i] = binary.charCodeAt(i);
537
+ }
538
+ const decoder = new TextDecoder();
539
+ return decoder.decode(bytes);
540
+ }
541
+ /**
542
+ * Codificar un objeto a base64 (UTF-8 seguro)
543
+ */
544
+ function encodeBase64Object(obj) {
545
+ return encodeBase64String(JSON.stringify(obj));
546
+ }
547
+ /**
548
+ * Decodificar un base64 y obtener el objeto original
549
+ */
550
+ function decodeBase64Object(b64) {
551
+ return JSON.parse(decodeBase64String(b64));
552
+ }
553
+ /**
554
+ * Codificar archivo a Base64 (retorna solo el contenido, sin "data:...")
555
+ */
556
+ function encodeBase64File(file) {
557
+ return new Promise((resolve, reject) => {
558
+ const reader = new FileReader();
559
+ reader.onload = () => {
560
+ const result = reader.result;
561
+ resolve(result.split(',')[1]); // quita el prefijo "data:...;base64,"
562
+ };
563
+ reader.onerror = reject;
564
+ reader.readAsDataURL(file);
565
+ });
566
+ }
567
+ /**
568
+ * Decodificar Base64 a Blob (para reconstruir archivos en Angular)
569
+ */
570
+ function decodeBase64ToBlob(b64, mimeType = 'application/octet-stream') {
571
+ const byteChars = atob(b64);
572
+ const byteNumbers = new Array(byteChars.length);
573
+ for (let i = 0; i < byteChars.length; i++) {
574
+ byteNumbers[i] = byteChars.charCodeAt(i);
575
+ }
576
+ return new Blob([new Uint8Array(byteNumbers)], { type: mimeType });
577
+ }
578
+
579
+ function getBrowserName() {
580
+ const agent = window.navigator.userAgent.toLowerCase();
581
+ switch (true) {
582
+ case agent.indexOf('edge') > -1:
583
+ return 'edge';
584
+ case agent.indexOf('opr') > -1 && !!window.opr:
585
+ return 'opera';
586
+ case agent.indexOf('chrome') > -1 && !!window.chrome:
587
+ return 'chrome';
588
+ case agent.indexOf('trident') > -1:
589
+ return 'ie';
590
+ case agent.indexOf('firefox') > -1:
591
+ return 'firefox';
592
+ case agent.indexOf('safari') > -1:
593
+ return 'safari';
594
+ default:
595
+ return 'other';
596
+ }
597
+ }
598
+
599
+ // import * as CryptoJS from 'crypto-js';
600
+ // var CryptoJS = require("crypto-js");
601
+ // Clave secreta (debe ser de 16, 24 o 32 caracteres)
602
+ const secretKey = CryptoJS.enc.Utf8.parse('JVSoftSecret@20615178350');
603
+ const iv = CryptoJS.enc.Utf8.parse('AnSalHuaJVSoft07'); // Debe ser de 16 bytes
604
+ // Función para encriptar texto
605
+ function encriptar(text) {
606
+ const encrypted = CryptoJS.AES.encrypt(text, secretKey, {
607
+ iv: iv,
608
+ mode: CryptoJS.mode.CBC,
609
+ padding: CryptoJS.pad.Pkcs7,
610
+ });
611
+ return encrypted.toString(); // Texto cifrado en Base64
612
+ }
613
+ // Función para desencriptar texto
614
+ function desencriptar(ciphertext) {
615
+ const decrypted = CryptoJS.AES.decrypt(ciphertext, secretKey, {
616
+ iv: iv,
617
+ mode: CryptoJS.mode.CBC,
618
+ padding: CryptoJS.pad.Pkcs7,
619
+ });
620
+ return decrypted.toString(CryptoJS.enc.Utf8);
621
+ }
622
+
623
+ function formatearFechaFormato(val, format = 'dd/MM/yyyy') {
624
+ return val ? formatDate(val, format, 'es-PE') : '';
625
+ }
626
+ function formatearFecha(val, hora = '00:00:00') {
627
+ if (val) {
628
+ if (val.length <= 10) {
629
+ val = val + ' ' + hora;
630
+ }
631
+ return new Date(val);
632
+ }
633
+ return val;
634
+ }
635
+ function formatearFechaCadena(fecha) {
636
+ const year = parseInt(fecha.substring(0, 4), 10);
637
+ const month = parseInt(fecha.substring(4, 6), 10) - 1;
638
+ const day = parseInt(fecha.substring(6, 8), 10);
639
+ return new Date(year, month, day);
640
+ }
641
+
642
+ function maskEmail(email) {
643
+ const [user, domain] = email.split("@");
644
+ if (user.length <= 2) {
645
+ return `${user[0]}***@${domain}`; // 🔹 Si el usuario es muy corto, no se oculta nada
646
+ }
647
+ if (user.length <= 4) {
648
+ return `${user[0]}***${user.slice(-1)}@${domain}`; // 🔹 Muestra 1 al inicio y 1 al final
649
+ }
650
+ return `${user.slice(0, 2)}***${user.slice(-2)}@${domain}`; // 🔹 Muestra 2 al inicio y 2 al final
651
+ }
652
+ function isEmail(email) {
653
+ return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
654
+ }
655
+
656
+ const mimeTypes = {
657
+ // Imágenes
658
+ 'jpg': 'image/jpeg',
659
+ 'jpeg': 'image/jpeg',
660
+ 'png': 'image/png',
661
+ 'gif': 'image/gif',
662
+ 'webp': 'image/webp',
663
+ 'svg': 'image/svg+xml',
664
+ 'ico': 'image/x-icon',
665
+ 'bmp': 'image/bmp',
666
+ // Documentos
667
+ 'pdf': 'application/pdf',
668
+ 'doc': 'application/msword',
669
+ 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
670
+ 'xls': 'application/vnd.ms-excel',
671
+ 'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
672
+ 'ppt': 'application/vnd.ms-powerpoint',
673
+ 'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
674
+ 'txt': 'text/plain',
675
+ 'csv': 'text/csv',
676
+ 'json': 'application/json',
677
+ 'xml': 'application/xml',
678
+ 'html': 'text/html',
679
+ // Audio
680
+ 'mp3': 'audio/mpeg',
681
+ 'wav': 'audio/wav',
682
+ 'ogg': 'audio/ogg',
683
+ 'm4a': 'audio/mp4',
684
+ // Video
685
+ 'mp4': 'video/mp4',
686
+ 'avi': 'video/x-msvideo',
687
+ 'mov': 'video/quicktime',
688
+ 'wmv': 'video/x-ms-wmv',
689
+ 'flv': 'video/x-flv',
690
+ 'webm': 'video/webm',
691
+ 'mkv': 'video/x-matroska',
692
+ // Archivos comprimidos
693
+ 'zip': 'application/zip',
694
+ 'rar': 'application/vnd.rar',
695
+ '7z': 'application/x-7z-compressed',
696
+ 'tar': 'application/x-tar',
697
+ 'gz': 'application/gzip',
698
+ 'bz2': 'application/x-bzip2',
699
+ // Otros formatos
700
+ 'js': 'application/javascript',
701
+ 'css': 'text/css',
702
+ 'ts': 'application/typescript',
703
+ 'md': 'text/markdown',
704
+ 'exe': 'application/octet-stream',
705
+ 'eot': 'application/vnd.ms-fontobject',
706
+ 'woff': 'font/woff',
707
+ 'woff2': 'font/woff2',
708
+ 'ttf': 'font/ttf',
709
+ 'otf': 'font/otf',
710
+ };
711
+ function obtenerMimeType(nombreArchivo) {
712
+ const extension = nombreArchivo.split('.').pop()?.toLowerCase();
713
+ return extension ? mimeTypes[extension] || 'application/octet-stream' : null;
714
+ }
715
+ function sanitizarNombreArchivo(nombre, reemplazo = '_') {
716
+ // 1. Quitar caracteres no válidos para nombres de archivo
717
+ const nombreSanitizado = nombre.replace(/[\/\\:*?"<>|]/g, reemplazo);
718
+ // 2. Reemplazar espacios múltiples o al inicio/final
719
+ const nombreLimpio = nombreSanitizado.trim().replace(/\s+/g, reemplazo);
720
+ // 3. Asegurar longitud máxima (opcional, aquí 255 caracteres)
721
+ return nombreLimpio.substring(0, 255);
722
+ }
723
+ function getDataArchivoFromPath(value, conTimeStamp = false) {
724
+ const partesPath = value.split('/');
725
+ const nombreCompleto = partesPath[partesPath.length - 1];
726
+ let timeStamp = 1;
727
+ let nombreSinTimeStamp = nombreCompleto;
728
+ const partesNombre = nombreCompleto.split('-');
729
+ if (partesNombre.length > 1) {
730
+ timeStamp = partesNombre[0] * 1;
731
+ partesNombre.shift();
732
+ nombreSinTimeStamp = partesNombre.join('-');
733
+ }
734
+ if (conTimeStamp) {
735
+ return {
736
+ nombre: nombreCompleto,
737
+ extension: nombreCompleto.split('.').pop(),
738
+ d: timeStamp,
739
+ fechaSubida: timeStamp ? new Date(timeStamp * 1000) : '',
740
+ };
741
+ }
742
+ return {
743
+ nombre: nombreSinTimeStamp,
744
+ extension: nombreSinTimeStamp.split('.').pop(),
745
+ d: timeStamp,
746
+ fechaSubida: timeStamp ? new Date(timeStamp * 1000) : '',
747
+ };
748
+ }
749
+ function convertirBytes(valor, unidadSalida = null, incluirUnidad = true) {
750
+ const unidades = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
751
+ const indiceEntrada = unidadSalida ? unidades.indexOf(unidadSalida) : 0;
752
+ if (indiceEntrada === -1) {
753
+ // Unidad de entrada no válida
754
+ return null;
755
+ }
756
+ let indiceActual = indiceEntrada;
757
+ let resultado = valor;
758
+ let cont = 0;
759
+ while (cont < 6 && (indiceActual < unidades.length - 1) && (resultado >= 1024)) {
760
+ resultado /= 1024;
761
+ indiceActual++;
762
+ }
763
+ if (incluirUnidad) {
764
+ return `${resultado.toFixed(2)} ${unidades[indiceActual]}`;
765
+ }
766
+ return resultado;
767
+ }
768
+ function downLoadFileStream(data, type, nombreArchivo) {
769
+ const blob = new Blob([data], { type });
770
+ saveAs(blob, nombreArchivo);
771
+ }
772
+
773
+ function establecerQuitarRequired(formulario, establecer = [], quitar = [], camposDisabled = []) {
774
+ establecer.forEach((control) => {
775
+ if (!formulario.get(control)?.hasValidator(Validators.required)) {
776
+ formulario.get(control)?.addValidators([Validators.required]);
777
+ formulario.get(control)?.enable();
778
+ formulario.get(control)?.updateValueAndValidity();
779
+ }
780
+ });
781
+ const deshabilitar = (strControl) => {
782
+ if (camposDisabled == 'todos') {
783
+ formulario.get(strControl)?.disable();
784
+ console.log(strControl);
785
+ }
786
+ else {
787
+ if (camposDisabled.includes(strControl)) {
788
+ formulario.get(strControl)?.disable();
789
+ }
790
+ }
791
+ };
792
+ quitar.forEach(control => {
793
+ if (formulario.get(control)?.hasValidator(Validators.required)) {
794
+ formulario.get(control)?.removeValidators([Validators.required]);
795
+ formulario.get(control)?.updateValueAndValidity();
796
+ }
797
+ deshabilitar(control);
798
+ });
799
+ }
800
+ function getFormValidationErrors(form) {
801
+ const result = [];
802
+ Object.keys(form.controls).forEach(key => {
803
+ const formProperty = form.get(key);
804
+ if (formProperty instanceof FormGroup) {
805
+ result.push(...getFormValidationErrors(formProperty));
806
+ }
807
+ const controlErrors = formProperty?.errors;
808
+ if (controlErrors) {
809
+ Object.keys(controlErrors).forEach(keyError => {
810
+ result.push({
811
+ control: key,
812
+ error: keyError,
813
+ value: controlErrors[keyError]
814
+ });
815
+ });
816
+ }
817
+ });
818
+ return result;
819
+ }
820
+ function mensajesErrorFormControl(control) {
821
+ if (!control || !control.errors || !control.touched)
822
+ return '';
823
+ ReactiveFormConfig.set({
824
+ // RxwebValidators
825
+ validationMessage: {
826
+ required: 'Es requerido',
827
+ numeric: 'Debe ser numérico valido',
828
+ // minLength: 'minimum length is {{1}}',
829
+ // maxLength: 'allowed max length is {{1}}',
830
+ },
831
+ });
832
+ const errorMessages = {
833
+ required: 'Es requerido',
834
+ numeric: 'Debe ser numérico válido',
835
+ min: `Valor mínimo permitido: ${control.errors['min']?.min}`,
836
+ minValue: 'Debe ser positivo',
837
+ minlength: `Mínimo ${control.errors['minlength']?.requiredLength} caracteres.`,
838
+ maxlength: `Caracteres ${control.errors['maxlength']?.actualLength}/${control.errors['maxlength']?.requiredLength}`,
839
+ email: 'No se cumple con el formato de Correo Electrónico',
840
+ isNumeric: 'Debe seleccionar una opción',
841
+ hasNumber: 'Se requiere al menos un número',
842
+ hasCapitalCase: 'Se requiere al menos una mayúscula',
843
+ hasSmallCase: 'Se requiere al menos una minúscula',
844
+ hasSpecialCharacters: 'Se requiere al menos un carácter especial',
845
+ NoPassswordMatch: 'La contraseña no coincide',
846
+ itemSelected: 'Debe seleccionar una opción de la lista',
847
+ inputMask: 'El formato ingresado no es válido',
848
+ };
849
+ // Devuelve el primer mensaje de error encontrado
850
+ for (const errorKey of Object.keys(control.errors)) {
851
+ if (errorMessages[errorKey]) {
852
+ return errorMessages[errorKey];
853
+ }
854
+ }
855
+ // Si el error tiene un mensaje personalizado, usarlo
856
+ return control.errors[Object.keys(control.errors)[0]]?.message || '';
857
+ }
858
+ function toFormData(formValue) {
859
+ const formData = new FormData();
860
+ Object.keys(formValue).forEach((key) => {
861
+ const value = formValue[key];
862
+ if (value === null || value === undefined) {
863
+ return; // Ignorar valores nulos o indefinidos
864
+ }
865
+ if (Array.isArray(value)) {
866
+ value.forEach((item, index) => {
867
+ if (typeof item === 'object' && item !== null) {
868
+ if ('file' in item) {
869
+ formData.append(`${key}[${index}]`, item.file);
870
+ }
871
+ else {
872
+ formData.append(`${key}[${index}]`, JSON.stringify(item));
873
+ }
874
+ }
875
+ else {
876
+ formData.append(`${key}[${index}]`, item.toString());
877
+ }
878
+ });
879
+ }
880
+ else if (typeof value === 'object') {
881
+ // Si es un objeto (pero no un array), convertirlo a JSON
882
+ formData.append(key, JSON.stringify(value));
883
+ }
884
+ else {
885
+ // Para valores primitivos (string, number, boolean)
886
+ formData.append(key, value.toString());
887
+ }
888
+ });
889
+ return formData;
890
+ }
891
+ function markAsTouchedWithoutEmitEvent(control) {
892
+ if (control instanceof FormControl) {
893
+ control.markAsTouched({ onlySelf: true });
894
+ control.updateValueAndValidity({ emitEvent: false });
895
+ }
896
+ else if (control instanceof FormGroup || control instanceof FormArray) {
897
+ Object.values(control.controls).forEach(childControl => {
898
+ markAsTouchedWithoutEmitEvent(childControl);
899
+ });
900
+ control.updateValueAndValidity({ emitEvent: false });
901
+ }
902
+ }
903
+ function setControlDesdeLista(config) {
904
+ const lista = config.lista$?.getValue() ?? [];
905
+ if (!lista.length)
906
+ return;
907
+ let seleccionado;
908
+ if (config.idProp && config.idValor !== undefined) {
909
+ seleccionado = lista.find((item) => item[config.idProp] === config.idValor);
910
+ }
911
+ else if (config.usarPrimeraOpcion) {
912
+ seleccionado = lista[0];
913
+ }
914
+ console.log(seleccionado);
915
+ if (!seleccionado)
916
+ return;
917
+ let valor;
918
+ if (config.selector) {
919
+ valor = config.selector(seleccionado);
920
+ }
921
+ else if (config.idProp) {
922
+ valor = seleccionado[config.idProp];
923
+ }
924
+ else {
925
+ valor = seleccionado;
926
+ }
927
+ if (config.formControl) {
928
+ config.formControl.setValue(valor);
929
+ }
930
+ else if (config.formGroup && config.controlName) {
931
+ const control = config.formGroup.get(config.controlName);
932
+ if (control instanceof FormControl) {
933
+ control.setValue(valor);
934
+ }
935
+ }
936
+ }
937
+ function transformarFechasPorNombreDeCampo(formValue) {
938
+ const retData = {};
939
+ Object.entries(formValue).forEach(([key, value]) => {
940
+ // ✅ No procesar Blob o File
941
+ if (value instanceof Blob || value instanceof File) {
942
+ retData[key] = value;
943
+ return;
944
+ }
945
+ if (value instanceof Date) {
946
+ if (/^d[A-Za-z]+/.test(key)) {
947
+ retData[key] = moment(value).format('YYYY-MM-DD');
948
+ }
949
+ else {
950
+ retData[key] = new Date(Date.UTC(value.getFullYear(), value.getMonth(), value.getDate(), value.getHours(), value.getMinutes(), value.getSeconds()));
951
+ }
952
+ }
953
+ else if (/^dt[A-Za-z]+/.test(key) && typeof value === 'string') {
954
+ if (/\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}\.\d{3}/.test(value)) {
955
+ retData[key] = new Date(value + 'Z');
956
+ }
957
+ 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)) {
958
+ retData[key] = new Date(value + ':00.000Z');
959
+ }
960
+ else {
961
+ console.warn('FECHA INVALIDA AL ENVIAR (FormInter):', key, value);
962
+ retData[key] = value;
963
+ }
964
+ }
965
+ else if (Array.isArray(value)) {
966
+ if (value.every(v => v instanceof File || v instanceof Blob)) {
967
+ retData[key] = value;
968
+ }
969
+ else {
970
+ retData[key] = value.map(item => typeof item === 'object' && item !== null
971
+ ? transformarFechasPorNombreDeCampo(item)
972
+ : item);
973
+ }
974
+ }
975
+ else if (typeof value === 'object' && value !== null) {
976
+ retData[key] = transformarFechasPorNombreDeCampo(value);
977
+ }
978
+ else {
979
+ retData[key] = value;
980
+ }
981
+ });
982
+ return retData;
983
+ }
984
+
985
+ function mensajeAlerta(tipo, titulo, mensaje, opciones) {
986
+ opciones = {
987
+ ...{
988
+ heightAuto: false,
989
+ title: titulo,
990
+ html: mensaje,
991
+ icon: tipo,
992
+ confirmButtonText: 'Aceptar',
993
+ // customClass: {
994
+ // confirmButton: 'btn btn-lg btn-outline-success mx-2',
995
+ // cancelButton: 'btn btn-lg btn-outline-dark mx-2'
996
+ // },
997
+ // buttonsStyling: false
998
+ },
999
+ ...opciones
1000
+ };
1001
+ return swal.fire(opciones);
1002
+ }
1003
+ function mensajeTimer(tipo, titulo, mensaje, milisegundos = 3000, showLoading = true, opciones) {
1004
+ let timerInterval;
1005
+ opciones = {
1006
+ ...{
1007
+ heightAuto: false,
1008
+ title: titulo,
1009
+ html: mensaje + '<br> Se cerrará en <strong> X </strong> segundos.',
1010
+ icon: tipo,
1011
+ timer: milisegundos,
1012
+ showCancelButton: false,
1013
+ showConfirmButton: false,
1014
+ willOpen: () => {
1015
+ if (showLoading) {
1016
+ swal.showLoading();
1017
+ }
1018
+ timerInterval = setInterval(() => {
1019
+ const impr = Math.ceil(((swal.getTimerLeft() ?? 1) / 1000));
1020
+ if (swal.getHtmlContainer()) {
1021
+ // @ts-ignore
1022
+ swal.getHtmlContainer().querySelector('strong').textContent = String(impr);
1023
+ }
1024
+ }, 100);
1025
+ },
1026
+ willClose: () => {
1027
+ clearInterval(timerInterval);
1028
+ }
1029
+ },
1030
+ ...opciones
1031
+ };
1032
+ return swal.fire(opciones);
1033
+ }
1034
+ // @ts-ignore
1035
+ function mensajeConfirmacion(tipo, titulo, mensaje, opciones) {
1036
+ opciones = {
1037
+ ...{
1038
+ heightAuto: false,
1039
+ title: titulo,
1040
+ html: mensaje,
1041
+ icon: tipo,
1042
+ showCancelButton: true,
1043
+ // confirmButtonColor: '#3f51b5',
1044
+ // cancelButtonColor: '#ffffff',
1045
+ confirmButtonText: 'Confirmar',
1046
+ cancelButtonText: 'Cancelar',
1047
+ reverseButtons: true,
1048
+ // customClass: {
1049
+ // confirmButton: 'btn btn-lg btn-outline-success mx-2',
1050
+ // cancelButton: 'btn btn-lg btn-outline-dark mx-2'
1051
+ // },
1052
+ // buttonsStyling: false
1053
+ },
1054
+ ...opciones
1055
+ };
1056
+ return swal.fire(opciones);
1057
+ }
1058
+ function mensajeToast(tipo, titulo, mensaje, opciones) {
1059
+ opciones = {
1060
+ ...{
1061
+ heightAuto: false,
1062
+ title: titulo,
1063
+ html: mensaje,
1064
+ icon: tipo,
1065
+ confirmButtonText: 'Aceptar',
1066
+ toast: true,
1067
+ position: 'top-end',
1068
+ showConfirmButton: false,
1069
+ timer: 3000,
1070
+ timerProgressBar: true,
1071
+ },
1072
+ ...opciones
1073
+ };
1074
+ return swal.fire(opciones);
1075
+ }
1076
+
1077
+ function mensajesDeError(error, toast = false) {
1078
+ let msg;
1079
+ if (error.error && error.error instanceof ArrayBuffer) {
1080
+ const msgArrayBuffer = (arrayBuffer) => {
1081
+ try {
1082
+ const mensajeError = JSON.parse(new TextDecoder("utf-8").decode(arrayBuffer));
1083
+ return mensajeError.message || 'Error desconocido';
1084
+ }
1085
+ catch (parseError) {
1086
+ console.error('Error al analizar la respuesta JSON:', parseError);
1087
+ return 'Error al analizar la respuesta JSON';
1088
+ }
1089
+ };
1090
+ msg = msgArrayBuffer(error.error);
1091
+ }
1092
+ else {
1093
+ switch (error.status) {
1094
+ case 0:
1095
+ // msg = error.message;
1096
+ msg = 'El servidor no responde, verifica tu conexion a la red';
1097
+ console.log(error);
1098
+ break;
1099
+ case 401:
1100
+ if (error.error && typeof error.error == 'object') {
1101
+ if (error.error.message) {
1102
+ msg = error.error.message;
1103
+ }
1104
+ else if (error.error.error) {
1105
+ msg = error.error.error;
1106
+ }
1107
+ else {
1108
+ msg = JSON.stringify(error.error);
1109
+ console.log(error);
1110
+ }
1111
+ }
1112
+ else if (error.error && typeof error.error == 'string') {
1113
+ msg = error.error;
1114
+ }
1115
+ else {
1116
+ msg = 'Acceso no autorizado';
1117
+ console.log(error);
1118
+ }
1119
+ break;
1120
+ case 422:
1121
+ let strEr = '';
1122
+ console.log(typeof error.error.errors);
1123
+ console.log(error.error.errors);
1124
+ if (error.error.errors) {
1125
+ Object.keys(error.error.errors).forEach(o => {
1126
+ strEr += '<li>' + error.error.errors[o][0] + '</li>';
1127
+ });
1128
+ msg = (error.error.message ?? '') + '<ul>' + strEr + '</ul>';
1129
+ }
1130
+ else if (error.error.error) {
1131
+ msg = error.error.msg;
1132
+ }
1133
+ break;
1134
+ case 429:
1135
+ case 400:
1136
+ case 500:
1137
+ case 503:
1138
+ msg = error.error.message;
1139
+ break;
1140
+ case 504:
1141
+ msg = 'No se puede conectar al servidor. Comprueba tu conexion a la red - ' + error.statusText;
1142
+ break;
1143
+ default:
1144
+ msg = error?.error?.message ?? 'Error de Sistema';
1145
+ console.log(error);
1146
+ break;
1147
+ }
1148
+ }
1149
+ if (!msg) {
1150
+ msg = error.statusText ?? 'Error inesperado o datos inexistentes.';
1151
+ }
1152
+ let tituloFinal = 'Error!';
1153
+ let mensajeFinal;
1154
+ if (msg.includes('Hmac::doVerify')) {
1155
+ console.log(error, msg);
1156
+ return;
1157
+ }
1158
+ else if (msg == 'Server Error') {
1159
+ console.log(error, msg);
1160
+ return;
1161
+ }
1162
+ else if (msg.includes('[IMSSP]')) {
1163
+ mensajeFinal = 'Error en consulta de registros.';
1164
+ }
1165
+ else if (msg.includes('Tiempo de espera de la')) {
1166
+ mensajeFinal = 'Hubo un error en la solicitud de datos, por favor actualice (SHIFT + F5)';
1167
+ }
1168
+ else {
1169
+ mensajeFinal = msg;
1170
+ }
1171
+ if (toast) {
1172
+ mensajeToast('error', tituloFinal, mensajeFinal);
1173
+ }
1174
+ else {
1175
+ mensajeAlerta('error', tituloFinal, mensajeFinal);
1176
+ }
1177
+ throw new Error(mensajeFinal);
1178
+ }
1179
+
1180
+ let dataSessionStorageKey = {
1181
+ tokenStringKey: 'JVSoftTkn',
1182
+ changePasswordKey: 'chPwd',
1183
+ logoUrl: 'logo_url',
1184
+ logoLogin: 'login-logo',
1185
+ backgroundLogin: 'login-background',
1186
+ favicon: 'favicon',
1187
+ darkMode: 'darkMode',
1188
+ serverTimestamp: 'srvtmstp',
1189
+ apiDataKey: 'reqDt',
1190
+ };
1191
+ let localStorageKeys = dataSessionStorageKey;
1192
+ function inicializarVariablesSessionStorage(datSesion) {
1193
+ dataSessionStorageKey = datSesion;
1194
+ }
1195
+ function setJwtTokenData(data) {
1196
+ localStorage.setItem(dataSessionStorageKey.tokenStringKey, data);
1197
+ }
1198
+ function jwtTokenData(key = dataSessionStorageKey.tokenStringKey) {
1199
+ const tokenObj = localStorage.getItem(key);
1200
+ try {
1201
+ return JSON.parse(tokenObj);
1202
+ }
1203
+ catch (error) {
1204
+ return null;
1205
+ }
1206
+ }
1207
+ function jwtToken(key = dataSessionStorageKey.tokenStringKey) {
1208
+ const varJwtTokenData = jwtTokenData(key);
1209
+ if (varJwtTokenData) {
1210
+ return varJwtTokenData.access_token;
1211
+ }
1212
+ return '';
1213
+ }
1214
+ function jwtTokenExpiracion(key = dataSessionStorageKey.tokenStringKey) {
1215
+ const jwtStr = jwtToken(key);
1216
+ if (!jwtStr)
1217
+ return null;
1218
+ try {
1219
+ const decodedToken = jwtDecode(jwtStr);
1220
+ return decodedToken.exp ? decodedToken.exp * 1000 : null; // Convertir a milisegundos
1221
+ }
1222
+ catch (e) {
1223
+ return null;
1224
+ }
1225
+ }
1226
+ function jwtTokenExpiracionFaltante() {
1227
+ return Math.abs(moment().diff(jwtTokenExpiracion(), 'seconds'));
1228
+ }
1229
+ function setCambiarPwd(accion = true) {
1230
+ localStorage.setItem(dataSessionStorageKey.changePasswordKey, (accion ? 1 : 0).toString());
1231
+ }
1232
+ function getCambiarPwd() {
1233
+ const frmCambioPwd = localStorage.getItem(dataSessionStorageKey.changePasswordKey);
1234
+ if (!frmCambioPwd) {
1235
+ return null;
1236
+ }
1237
+ return frmCambioPwd == '1';
1238
+ }
1239
+ function delLocalStorage(keyElim = [
1240
+ dataSessionStorageKey.tokenStringKey,
1241
+ dataSessionStorageKey.changePasswordKey,
1242
+ dataSessionStorageKey.apiDataKey,
1243
+ ]) {
1244
+ keyElim.forEach(key => {
1245
+ localStorage.removeItem(key);
1246
+ });
1247
+ }
1248
+ function getLocalStorage(key) {
1249
+ return localStorage.getItem(key);
1250
+ }
1251
+ function setLocalStorage(key, value = '') {
1252
+ localStorage.setItem(key, value.toString());
1253
+ }
1254
+
1255
+ function roundToDecimal(number, decimal) {
1256
+ return parseFloat(number.toFixed(decimal));
1257
+ }
1258
+ function numberToWords(num) {
1259
+ if (num === 0)
1260
+ return 'cero';
1261
+ if (num < 0)
1262
+ return 'menos ' + numberToWords(Math.abs(num));
1263
+ if (num > 999999999999)
1264
+ return 'número demasiado grande';
1265
+ const ones = ['', 'un', 'dos', 'tres', 'cuatro', 'cinco', 'seis', 'siete', 'ocho', 'nueve'];
1266
+ const onesFinal = ['', 'uno', 'dos', 'tres', 'cuatro', 'cinco', 'seis', 'siete', 'ocho', 'nueve'];
1267
+ const tens = ['', 'diez', 'veinte', 'treinta', 'cuarenta', 'cincuenta', 'sesenta', 'setenta', 'ochenta', 'noventa'];
1268
+ const teens = ['diez', 'once', 'doce', 'trece', 'catorce', 'quince', 'dieciséis', 'diecisiete', 'dieciocho', 'diecinueve'];
1269
+ const hundreds = ['', 'ciento', 'doscientos', 'trescientos', 'cuatrocientos', 'quinientos', 'seiscientos', 'setecientos', 'ochocientos', 'novecientos'];
1270
+ // Función auxiliar para "un"/"uno"
1271
+ const getOneForm = (n, isFinal) => n === 1 ? (isFinal ? 'uno' : 'un') : onesFinal[n];
1272
+ let words = '';
1273
+ // Miles de millones (ahora sí se ejecuta)
1274
+ if (num >= 1000000000) {
1275
+ const billions = Math.floor(num / 1000000000);
1276
+ words += (billions === 1 ? 'mil' : numberToWords(billions) + ' mil') + ' millones ';
1277
+ num %= 1000000000;
1278
+ }
1279
+ // Millones
1280
+ if (num >= 1000000) {
1281
+ const millions = Math.floor(num / 1000000);
1282
+ words += millions === 1 ? 'un millón ' : numberToWords(millions) + ' millones ';
1283
+ num %= 1000000;
1284
+ }
1285
+ // Miles
1286
+ if (num >= 1000) {
1287
+ const thousands = Math.floor(num / 1000);
1288
+ words += thousands === 1 ? 'mil ' : numberToWords(thousands) + ' mil ';
1289
+ num %= 1000;
1290
+ }
1291
+ // Centenas (con tratamiento especial para "ciento uno")
1292
+ if (num >= 100) {
1293
+ if (num === 100) {
1294
+ words += 'cien';
1295
+ num = 0;
1296
+ }
1297
+ else {
1298
+ words += hundreds[Math.floor(num / 100)];
1299
+ num %= 100;
1300
+ if (num > 0) {
1301
+ words += ' ' + getOneForm(num, true); // Siempre "uno" después de ciento
1302
+ num = 0;
1303
+ }
1304
+ }
1305
+ }
1306
+ // Decenas y unidades
1307
+ if (num > 0) {
1308
+ const isFinalWord = words === '';
1309
+ if (num < 10) {
1310
+ words += getOneForm(num, isFinalWord);
1311
+ }
1312
+ else if (num < 20) {
1313
+ words += teens[num - 10];
1314
+ }
1315
+ else if (num < 30) {
1316
+ if (num === 21)
1317
+ words += 'veintiuno';
1318
+ else if (num === 22)
1319
+ words += 'veintidós';
1320
+ else if (num === 23)
1321
+ words += 'veintitrés';
1322
+ else if (num === 26)
1323
+ words += 'veintiséis';
1324
+ else
1325
+ words += `veinti${onesFinal[num % 10]}`;
1326
+ }
1327
+ else {
1328
+ words += tens[Math.floor(num / 10)];
1329
+ if (num % 10 > 0) {
1330
+ words += ' y ' + getOneForm(num % 10, isFinalWord);
1331
+ }
1332
+ }
1333
+ }
1334
+ return words.trim().replace(/\s+/g, ' ');
1335
+ }
1336
+
1337
+ function objectPropertiesToType(formFields) {
1338
+ Object.keys(formFields).filter(control => !!formFields[control]).forEach(control => {
1339
+ if (/^dt[a-zA-Z]+/.test(control)) {
1340
+ formFields[control] = formatDate(formFields[control], 'yyyy-MM-dd HH:mm', 'es-PE');
1341
+ }
1342
+ else if (control.startsWith('d')) {
1343
+ formFields[control] = formatearFecha(formFields[control]);
1344
+ }
1345
+ else if (control.startsWith('n')) {
1346
+ formFields[control] = Number(formFields[control]);
1347
+ }
1348
+ });
1349
+ return formFields;
1350
+ }
1351
+ function objectPropertiesBoolean(formFields, retorno = 'boolean') {
1352
+ Object.keys(formFields).forEach(control => {
1353
+ const valRetorno = (ctrl) => {
1354
+ switch (retorno) {
1355
+ case 'boolean':
1356
+ formFields[ctrl] = formFields[ctrl] == 1;
1357
+ break;
1358
+ case 'bit':
1359
+ formFields[ctrl] = formFields[ctrl] ? 1 : 0;
1360
+ break;
1361
+ }
1362
+ };
1363
+ if (control.charAt(0) == 'b' || (control.charAt(0) == 'i' && control.indexOf('Estado') !== -1)) {
1364
+ valRetorno(control);
1365
+ }
1366
+ });
1367
+ return formFields;
1368
+ }
1369
+
1370
+ function generateRandomString(length) {
1371
+ let result = '';
1372
+ const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
1373
+ const charactersLength = characters.length;
1374
+ for (let i = 0; i < length; i++) {
1375
+ result += characters.charAt(Math.floor(Math.random() * charactersLength));
1376
+ }
1377
+ return result;
1378
+ }
1379
+ /**
1380
+ * Obtiene el host (hostname) de una URL o cadena host[:port].
1381
+ * Opcionalmente puede devolver también el puerto si está presente.
1382
+ *
1383
+ * - Acepta inputs como:
1384
+ * 'https://example.com/path', 'example.com:3000', 'localhost', 'http://[::1]:4200'
1385
+ * - Usa la API URL cuando es posible (más robusta) y cae a un regex de respaldo.
1386
+ *
1387
+ * @param url Cadena que representa una URL o host
1388
+ * @param options
1389
+ * @param options.includePort Si es true, incluye":puerto" cuando exista (por defecto false)
1390
+ * @param options.includeProtocol Incluye "http://" o "https://" según corresponda (por defecto false)
1391
+ */
1392
+ function obtenerHostDesdeUrl(url, options) {
1393
+ if (!url)
1394
+ return null;
1395
+ const includePort = !!options?.includePort;
1396
+ const includeProtocol = !!options?.includeProtocol;
1397
+ // Intentar con API URL
1398
+ try {
1399
+ const candidate = url.includes('://') ? url : `http://${url}`;
1400
+ const parsed = new URL(candidate);
1401
+ const protocol = includeProtocol ? `${parsed.protocol}//` : '';
1402
+ const hostname = parsed.hostname;
1403
+ const port = parsed.port;
1404
+ if (!hostname)
1405
+ return null;
1406
+ return `${protocol}${hostname}${includePort && port ? `:${port}` : ''}`;
1407
+ }
1408
+ catch {
1409
+ // Regex fallback
1410
+ const regex = /^(?:(?<protocol>[a-z]+):\/\/)?(?:www\.)?(?<host>\[[^\]]+\]|[A-Za-z0-9.-]+)(?::(?<port>\d{1,5}))?/;
1411
+ const match = String(url).match(regex);
1412
+ if (!match?.groups)
1413
+ return null;
1414
+ let host = match.groups['host'];
1415
+ if (host.startsWith('[') && host.endsWith(']')) {
1416
+ host = host.slice(1, -1);
1417
+ }
1418
+ const port = match.groups['port'];
1419
+ const protocol = includeProtocol ? `${match.groups['protocol'] ?? 'http'}://` : '';
1420
+ return `${protocol}${host}${includePort && port ? `:${port}` : ''}`;
1421
+ }
1422
+ }
1423
+ /** @deprecated Alias compatible (deprecated) — preferir usar `obtenerHostDesdeUrl`. */
1424
+ const extraerDominio = (url, options) => obtenerHostDesdeUrl(url, options);
1425
+
1426
+ function verificarRUC(ruc) {
1427
+ const f = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2];
1428
+ const rucArray = ruc.split('');
1429
+ const nArray = f.map((item, idx) => {
1430
+ return item * parseFloat(rucArray[idx]);
1431
+ });
1432
+ const suma = nArray.reduce((a, b) => a + b, 0);
1433
+ const residuo = suma % 11;
1434
+ const residuo2 = 11 - residuo;
1435
+ // @residuo=CONVERT(Integer,Right(CONVERT(VarChar,@residuo),1))
1436
+ const residuo3 = residuo2.toString().charAt(residuo2.toString().length - 1);
1437
+ const ultimoCaracter = ruc.toString().charAt(ruc.toString().length - 1);
1438
+ if (residuo3 == ultimoCaracter) {
1439
+ return true;
1440
+ }
1441
+ mensajeAlerta('error', 'Datos No válidos', ' El número de RUC no es válido');
1442
+ return false;
1443
+ }
1444
+
1445
+ /**
1446
+ * Generated bundle index. Do not edit.
1447
+ */
1448
+
1449
+ export { b64Decode, b64Encode, buscarPorCampo, changeSelect, changeSelectApi, changeSelectData, changeSelectDataApi, changeSelectReformateado, convertirBytes, decodeBase64Object, decodeBase64String, decodeBase64ToBlob, deepClone, deepMerge, delLocalStorage, desencriptar, downLoadFileStream, eliminarColumnaPorIndex, eliminarDuplicados, eliminarElementos, encodeBase64File, encodeBase64Object, encodeBase64String, encriptar, esNumero, establecerQuitarRequired, extraerDominio, 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, toFormData, transformarFechasPorNombreDeCampo, verificarRUC };
1450
+ //# sourceMappingURL=jvsoft-utils-src-functions.mjs.map