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