@jvsoft/utils 0.0.13-alpha.1 → 0.0.13-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/classes/data-model.d.ts +25 -0
- package/fesm2022/jvsoft-utils-src-functions.mjs +1109 -0
- package/fesm2022/jvsoft-utils-src-functions.mjs.map +1 -0
- package/fesm2022/jvsoft-utils-src-interfaces.mjs +6 -0
- package/fesm2022/jvsoft-utils-src-interfaces.mjs.map +1 -0
- package/fesm2022/jvsoft-utils-src-pipes.mjs +290 -0
- package/fesm2022/jvsoft-utils-src-pipes.mjs.map +1 -0
- package/fesm2022/jvsoft-utils.mjs +1526 -0
- package/fesm2022/jvsoft-utils.mjs.map +1 -0
- package/functions/base64.d.ts +2 -0
- package/functions/browser.d.ts +1 -0
- package/functions/crypto-js.d.ts +2 -0
- package/functions/date.d.ts +3 -0
- package/functions/email.d.ts +2 -0
- package/functions/file.d.ts +10 -0
- package/functions/forms.d.ts +10 -0
- package/functions/http-client.d.ts +2 -0
- package/functions/index.d.ts +1 -0
- package/functions/local-storage.d.ts +29 -0
- package/functions/mat-form-controls/autocomplete.d.ts +21 -0
- package/functions/mat-form-controls/index.d.ts +2 -0
- package/functions/number.d.ts +1 -0
- package/functions/object-transformation.d.ts +2 -0
- package/functions/objects-arrays.d.ts +37 -0
- package/functions/public-api.d.ts +16 -0
- package/functions/string.d.ts +1 -0
- package/functions/sweetalert.d.ts +5 -0
- package/functions/utiles.d.ts +1 -0
- package/index.d.ts +5 -0
- package/{src/interfaces/datos.ts → interfaces/datos.d.ts} +1 -2
- package/interfaces/index.d.ts +1 -0
- package/interfaces/public-api.d.ts +1 -0
- package/package.json +25 -2
- package/pipes/data-en-lista.pipe.d.ts +8 -0
- package/pipes/date-diff-string.pipe.d.ts +17 -0
- package/pipes/filtro.pipe.d.ts +18 -0
- package/pipes/form-control-is-required.pipe.d.ts +9 -0
- package/pipes/index.d.ts +1 -0
- package/pipes/json-parse.pipe.d.ts +7 -0
- package/pipes/no-sanitize.pipe.d.ts +10 -0
- package/pipes/public-api.d.ts +8 -0
- package/pipes/tipo-valor-funcion.pipe.d.ts +9 -0
- package/pipes/zero-fill.pipe.d.ts +8 -0
- package/public-api.d.ts +4 -0
- package/src/functions/base64.d.ts +2 -0
- package/src/functions/browser.d.ts +1 -0
- package/src/functions/crypto-js.d.ts +2 -0
- package/src/functions/date.d.ts +3 -0
- package/src/functions/email.d.ts +2 -0
- package/src/functions/file.d.ts +10 -0
- package/src/functions/forms.d.ts +10 -0
- package/src/functions/http-client.d.ts +2 -0
- package/src/functions/index.d.ts +5 -0
- package/src/functions/local-storage.d.ts +29 -0
- package/src/functions/mat-form-controls/autocomplete.d.ts +21 -0
- package/src/functions/mat-form-controls/index.d.ts +2 -0
- package/src/functions/number.d.ts +1 -0
- package/src/functions/object-transformation.d.ts +2 -0
- package/src/functions/objects-arrays.d.ts +37 -0
- package/src/functions/public-api.d.ts +16 -0
- package/src/functions/string.d.ts +1 -0
- package/src/functions/sweetalert.d.ts +5 -0
- package/src/functions/utiles.d.ts +1 -0
- package/src/interfaces/datos.d.ts +4 -0
- package/src/interfaces/index.d.ts +5 -0
- package/src/interfaces/public-api.d.ts +1 -0
- package/src/pipes/data-en-lista.pipe.d.ts +8 -0
- package/src/pipes/date-diff-string.pipe.d.ts +17 -0
- package/src/pipes/filtro.pipe.d.ts +18 -0
- package/src/pipes/form-control-is-required.pipe.d.ts +9 -0
- package/src/pipes/index.d.ts +5 -0
- package/src/pipes/json-parse.pipe.d.ts +7 -0
- package/src/pipes/no-sanitize.pipe.d.ts +10 -0
- package/src/pipes/public-api.d.ts +8 -0
- package/src/pipes/tipo-valor-funcion.pipe.d.ts +9 -0
- package/src/pipes/zero-fill.pipe.d.ts +8 -0
- package/CHANGELOG.md +0 -13
- package/ng-package.json +0 -7
- package/src/classes/data-model.ts +0 -150
- package/src/functions/base64.ts +0 -8
- package/src/functions/browser.ts +0 -20
- package/src/functions/crypto-js.ts +0 -29
- package/src/functions/date.ts +0 -23
- package/src/functions/email.ts +0 -17
- package/src/functions/file.ts +0 -138
- package/src/functions/forms.ts +0 -145
- package/src/functions/http-client.ts +0 -110
- package/src/functions/index.ts +0 -1
- package/src/functions/local-storage.ts +0 -102
- package/src/functions/mat-form-controls/autocomplete.ts +0 -275
- package/src/functions/mat-form-controls/index.ts +0 -6
- package/src/functions/ng-package.json +0 -5
- package/src/functions/number.ts +0 -3
- package/src/functions/object-transformation.ts +0 -37
- package/src/functions/objects-arrays.ts +0 -243
- package/src/functions/public-api.ts +0 -19
- package/src/functions/string.ts +0 -9
- package/src/functions/sweetalert.ts +0 -95
- package/src/functions/utiles.ts +0 -20
- package/src/interfaces/index.ts +0 -1
- package/src/interfaces/ng-package.json +0 -5
- package/src/interfaces/otros.ts +0 -0
- package/src/interfaces/public-api.ts +0 -3
- package/src/interfaces/routes.ts +0 -42
- package/src/pipes/data-en-lista.pipe.ts +0 -40
- package/src/pipes/date-diff-string.pipe.ts +0 -117
- package/src/pipes/filtro.pipe.ts +0 -64
- package/src/pipes/form-control-is-required.pipe.ts +0 -17
- package/src/pipes/index.ts +0 -1
- package/src/pipes/json-parse.pipe.ts +0 -18
- package/src/pipes/ng-package.json +0 -5
- package/src/pipes/no-sanitize.pipe.ts +0 -12
- package/src/pipes/public-api.ts +0 -10
- package/src/pipes/tipo-valor-funcion.pipe.ts +0 -23
- package/src/pipes/zero-fill.pipe.ts +0 -19
- package/src/public-api.ts +0 -12
- package/tsconfig.lib.json +0 -17
- package/tsconfig.lib.prod.json +0 -11
- package/tsconfig.spec.json +0 -15
|
@@ -0,0 +1,1109 @@
|
|
|
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 swal from 'sweetalert2';
|
|
11
|
+
import moment from 'moment';
|
|
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
|
+
function mostrarValorEnBusqueda(campos, idxSel) {
|
|
211
|
+
const impDataMostrar = () => {
|
|
212
|
+
let vD;
|
|
213
|
+
if (campos.campoId == '*object*' || campos.campoId == '*objeto*') {
|
|
214
|
+
console.log(campos);
|
|
215
|
+
vD = campos.lista.find((x) => JSON.stringify(x).trim() == JSON.stringify(idxSel).trim());
|
|
216
|
+
console.log(vD);
|
|
217
|
+
}
|
|
218
|
+
else {
|
|
219
|
+
vD = campos.lista.find((x) => x[campos.campoId] == idxSel);
|
|
220
|
+
}
|
|
221
|
+
if (!vD && campos.opcExtra) {
|
|
222
|
+
console.log('eval ', campos.opcExtra);
|
|
223
|
+
if (campos.campoId == '*object*' || campos.campoId == '*objeto*') {
|
|
224
|
+
console.log(campos);
|
|
225
|
+
vD = campos.opcExtra.find((x) => JSON.stringify(x).trim() == JSON.stringify(idxSel).trim());
|
|
226
|
+
console.log(vD);
|
|
227
|
+
}
|
|
228
|
+
else {
|
|
229
|
+
vD = campos.opcExtra.find((x) => x[campos.campoId] == idxSel);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
if (vD) {
|
|
233
|
+
let txtFinal = '';
|
|
234
|
+
if (Array.isArray(campos.campoValue)) {
|
|
235
|
+
campos.campoValue.forEach((vCampo, idx) => {
|
|
236
|
+
txtFinal += (vD[vCampo] ?? '');
|
|
237
|
+
if (idx < campos.campoValue.length - 1) {
|
|
238
|
+
txtFinal += ' - ';
|
|
239
|
+
}
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
else {
|
|
243
|
+
txtFinal = vD[campos.campoValue] ?? '';
|
|
244
|
+
}
|
|
245
|
+
return txtFinal.trim();
|
|
246
|
+
}
|
|
247
|
+
else {
|
|
248
|
+
console.log('ASSSSS ----- SSSS ');
|
|
249
|
+
}
|
|
250
|
+
return '';
|
|
251
|
+
};
|
|
252
|
+
if (esNumero(idxSel)) {
|
|
253
|
+
if (idxSel > 0 && campos.lista?.length > 0) {
|
|
254
|
+
return impDataMostrar();
|
|
255
|
+
}
|
|
256
|
+
else if (idxSel && typeof idxSel == 'object') {
|
|
257
|
+
return impDataMostrar();
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
else {
|
|
261
|
+
if (campos.lista?.length > 0) {
|
|
262
|
+
return impDataMostrar();
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
return '';
|
|
266
|
+
}
|
|
267
|
+
function changeSelectData(objThis, dataFiltro) {
|
|
268
|
+
objThis['filtrados'][dataFiltro.variableResultado] = dataFiltro.formControl.valueChanges.pipe(untilDestroyed(objThis)).pipe(startWith(''), map(value => {
|
|
269
|
+
const varN = dataFiltro.data;
|
|
270
|
+
if (varN) {
|
|
271
|
+
if (value) {
|
|
272
|
+
return varN.map(x => x).filter(dat => {
|
|
273
|
+
if (Array.isArray(dataFiltro.campoBuscar)) {
|
|
274
|
+
let encontrado = false;
|
|
275
|
+
for (const vCampo of dataFiltro.campoBuscar) {
|
|
276
|
+
// console.log(vCampo, value, dat[vCampo]);
|
|
277
|
+
if (isNaN(Number(value))) {
|
|
278
|
+
// NO ES NUMERO
|
|
279
|
+
if (value && dat[vCampo] && dat[vCampo].toLowerCase().includes(value?.toString().toLowerCase())) {
|
|
280
|
+
encontrado = true;
|
|
281
|
+
break;
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
else {
|
|
285
|
+
if (value && dat[vCampo] && dat[vCampo].toString().includes(value?.toString())) {
|
|
286
|
+
encontrado = true;
|
|
287
|
+
break;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
return encontrado;
|
|
292
|
+
}
|
|
293
|
+
else {
|
|
294
|
+
if (isNaN(Number(value))) {
|
|
295
|
+
return dat[dataFiltro.campoBuscar].toLowerCase().includes(value?.toString().toLowerCase());
|
|
296
|
+
}
|
|
297
|
+
else {
|
|
298
|
+
return dat[dataFiltro.campoBuscar].toString().includes(value?.toString());
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
return varN;
|
|
304
|
+
}
|
|
305
|
+
return false;
|
|
306
|
+
}));
|
|
307
|
+
}
|
|
308
|
+
function changeSelect(control, formControl, tipo, campoBuscar, campoFiltro = null) {
|
|
309
|
+
// console.log(formControl);
|
|
310
|
+
// const formGroup = formControl.parent.controls;
|
|
311
|
+
// console.warn( Object.keys(formGroup).find(name => formControl === formGroup[name]) || null );
|
|
312
|
+
if (!campoFiltro) {
|
|
313
|
+
campoFiltro = tipo;
|
|
314
|
+
}
|
|
315
|
+
control['filtrados'][campoFiltro ?? '__'] = formControl.valueChanges.pipe(untilDestroyed(control)).pipe(startWith(''), map(value => {
|
|
316
|
+
// console.warn(value);
|
|
317
|
+
const partes = tipo.split('.');
|
|
318
|
+
let varN;
|
|
319
|
+
if (control['dataServidor']) {
|
|
320
|
+
varN = (partes.length > 1) ? control['dataServidor'][partes[0]][partes[1]] : control['dataServidor'][tipo];
|
|
321
|
+
}
|
|
322
|
+
else if (control['dataServidorSuscripcion']) {
|
|
323
|
+
varN = control['dataServidorSuscripcion'][tipo].getValue();
|
|
324
|
+
}
|
|
325
|
+
if (varN) {
|
|
326
|
+
if (value) {
|
|
327
|
+
return varN.map((x) => x).filter((dat) => {
|
|
328
|
+
if (Array.isArray(campoBuscar)) {
|
|
329
|
+
let encontrado = false;
|
|
330
|
+
for (const vCampo of campoBuscar) {
|
|
331
|
+
// console.log(vCampo, value, dat[vCampo]);
|
|
332
|
+
if (isNaN(Number(value))) {
|
|
333
|
+
// NO ES NUMERO
|
|
334
|
+
if (value && dat[vCampo] && dat[vCampo].toLowerCase().includes(value?.toString().toLowerCase())) {
|
|
335
|
+
encontrado = true;
|
|
336
|
+
break;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
else {
|
|
340
|
+
if (value && dat[vCampo] && dat[vCampo].toString().includes(value?.toString())) {
|
|
341
|
+
encontrado = true;
|
|
342
|
+
break;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
return encontrado;
|
|
347
|
+
}
|
|
348
|
+
else {
|
|
349
|
+
if (isNaN(Number(value))) {
|
|
350
|
+
return dat[campoBuscar].toLowerCase().includes(value?.toString().toLowerCase());
|
|
351
|
+
}
|
|
352
|
+
else {
|
|
353
|
+
return dat[campoBuscar].toString().includes(value?.toString());
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
return varN;
|
|
359
|
+
}
|
|
360
|
+
return false;
|
|
361
|
+
}));
|
|
362
|
+
}
|
|
363
|
+
function changeSelectDataApi(objThis, dataFiltro) {
|
|
364
|
+
if (!dataFiltro.variableResultado) {
|
|
365
|
+
dataFiltro.variableResultado = dataFiltro.tipoReq;
|
|
366
|
+
}
|
|
367
|
+
const idFiltrado = dataFiltro.variableResultado;
|
|
368
|
+
dataFiltro.formControl.valueChanges.pipe(debounceTime(500), tap(() => {
|
|
369
|
+
objThis.filtrados[dataFiltro.variableResultado + 'tmp'] = isObservable(objThis.filtrados[idFiltrado]) ? [] : objThis.filtrados[idFiltrado] || [];
|
|
370
|
+
if (objThis.filtrados[idFiltrado] !== objThis.filtrados[idFiltrado + 'tmp']) {
|
|
371
|
+
objThis.filtrados[idFiltrado] = [];
|
|
372
|
+
}
|
|
373
|
+
objThis.isLoading = true;
|
|
374
|
+
}), switchMap(value => {
|
|
375
|
+
if (dataFiltro.campoId) {
|
|
376
|
+
const busquedaActual2 = objThis.filtrados[idFiltrado + 'tmp'].findIndex((item) => item[dataFiltro.campoId ?? '--'] === value);
|
|
377
|
+
if (busquedaActual2 >= 0) {
|
|
378
|
+
return of({ [dataFiltro.tipoReq]: objThis.filtrados[idFiltrado + 'tmp'] });
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
return !value || value.length < (dataFiltro.minLength ?? 3) ? [] : (dataFiltro.queryService.getDataMethod('GET', dataFiltro.tipoReq, {
|
|
382
|
+
...(dataFiltro.dataExtra ?? {}),
|
|
383
|
+
...(dataFiltro.dataExtraVariable ? Object.fromEntries(dataFiltro.dataExtraVariable.map((objData) => [objData.campo, objData.ctrlValue.value])) : {}),
|
|
384
|
+
txtBuscar: value,
|
|
385
|
+
}, dataFiltro.anonimo).pipe(finalize(() => objThis.isLoading = false)));
|
|
386
|
+
})).subscribe((data) => {
|
|
387
|
+
objThis.filtrados[idFiltrado] = data[dataFiltro.tipoReq] ?? [];
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
function changeSelectApi(control, queryService, formControl, tipo, dataExtra = {}, dataExtraVariable = null, minLength = 1, anonimo = false) {
|
|
391
|
+
formControl.valueChanges.pipe(debounceTime(500), tap((value) => {
|
|
392
|
+
control['filtrados'][tipo + 'tmp'] = isObservable(control['filtrados'][tipo]) ? [] : control['filtrados'][tipo];
|
|
393
|
+
if (control['filtrados'][tipo] != control['filtrados'][tipo + 'tmp']) {
|
|
394
|
+
control['filtrados'][tipo] = [];
|
|
395
|
+
}
|
|
396
|
+
control['isLoading'] = true;
|
|
397
|
+
}), switchMap(value => {
|
|
398
|
+
const formGroup = formControl.parent?.controls;
|
|
399
|
+
const nombreControl = Object.keys(formGroup).find(name => formControl === formGroup[name]) || null;
|
|
400
|
+
if (nombreControl && control['filtrados'][tipo + 'tmp'] && control['filtrados'][tipo + 'tmp'].length > 0) {
|
|
401
|
+
const busquedaActual = control['filtrados'][tipo + 'tmp'].findIndex((item) => item[nombreControl] == value);
|
|
402
|
+
if (busquedaActual >= 0) {
|
|
403
|
+
const vRet = {};
|
|
404
|
+
vRet[tipo] = control['filtrados'][tipo + 'tmp'];
|
|
405
|
+
control['isLoading'] = false;
|
|
406
|
+
return of(vRet);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
if (!value || value.length < minLength) {
|
|
410
|
+
return [];
|
|
411
|
+
}
|
|
412
|
+
const dataExtraVariableData = {};
|
|
413
|
+
if (dataExtraVariable) {
|
|
414
|
+
// @ts-ignore
|
|
415
|
+
for (const objData of dataExtraVariable) {
|
|
416
|
+
dataExtraVariableData[objData.campo] = objData.ctrlValue.value;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
return queryService.getDataMethod('GET', tipo, { ...dataExtra, ...dataExtraVariableData, ...{ txtBuscar: value } }, anonimo).pipe(finalize(() => {
|
|
420
|
+
control['isLoading'] = false;
|
|
421
|
+
}));
|
|
422
|
+
})).subscribe((data) => {
|
|
423
|
+
if (data[tipo] == undefined) {
|
|
424
|
+
control['filtrados'][tipo] = [];
|
|
425
|
+
}
|
|
426
|
+
else {
|
|
427
|
+
control['filtrados'][tipo] = data[tipo];
|
|
428
|
+
}
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
function seleccionarTextoInput(event) {
|
|
433
|
+
event.target.select();
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
function b64Encode(val) {
|
|
437
|
+
return Buffer.from(val, 'binary').toString('base64');
|
|
438
|
+
}
|
|
439
|
+
function b64Decode(val) {
|
|
440
|
+
return Buffer.from(val, 'base64').toString('binary');
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
function getBrowserName() {
|
|
444
|
+
const agent = window.navigator.userAgent.toLowerCase();
|
|
445
|
+
switch (true) {
|
|
446
|
+
case agent.indexOf('edge') > -1:
|
|
447
|
+
return 'edge';
|
|
448
|
+
case agent.indexOf('opr') > -1 && !!window.opr:
|
|
449
|
+
return 'opera';
|
|
450
|
+
case agent.indexOf('chrome') > -1 && !!window.chrome:
|
|
451
|
+
return 'chrome';
|
|
452
|
+
case agent.indexOf('trident') > -1:
|
|
453
|
+
return 'ie';
|
|
454
|
+
case agent.indexOf('firefox') > -1:
|
|
455
|
+
return 'firefox';
|
|
456
|
+
case agent.indexOf('safari') > -1:
|
|
457
|
+
return 'safari';
|
|
458
|
+
default:
|
|
459
|
+
return 'other';
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
// import * as CryptoJS from 'crypto-js';
|
|
464
|
+
// var CryptoJS = require("crypto-js");
|
|
465
|
+
// Clave secreta (debe ser de 16, 24 o 32 caracteres)
|
|
466
|
+
const secretKey = CryptoJS.enc.Utf8.parse('JVSoftSecret@20615178350');
|
|
467
|
+
const iv = CryptoJS.enc.Utf8.parse('AnSalHuaJVSoft07'); // Debe ser de 16 bytes
|
|
468
|
+
// Función para encriptar texto
|
|
469
|
+
function encriptar(text) {
|
|
470
|
+
const encrypted = CryptoJS.AES.encrypt(text, secretKey, {
|
|
471
|
+
iv: iv,
|
|
472
|
+
mode: CryptoJS.mode.CBC,
|
|
473
|
+
padding: CryptoJS.pad.Pkcs7,
|
|
474
|
+
});
|
|
475
|
+
return encrypted.toString(); // Texto cifrado en Base64
|
|
476
|
+
}
|
|
477
|
+
// Función para desencriptar texto
|
|
478
|
+
function desencriptar(ciphertext) {
|
|
479
|
+
const decrypted = CryptoJS.AES.decrypt(ciphertext, secretKey, {
|
|
480
|
+
iv: iv,
|
|
481
|
+
mode: CryptoJS.mode.CBC,
|
|
482
|
+
padding: CryptoJS.pad.Pkcs7,
|
|
483
|
+
});
|
|
484
|
+
return decrypted.toString(CryptoJS.enc.Utf8);
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
function formatearFechaFormato(val, format = 'dd/MM/yyyy') {
|
|
488
|
+
return val ? formatDate(val, format, 'es-PE') : '';
|
|
489
|
+
}
|
|
490
|
+
function formatearFecha(val, hora = '00:00:00') {
|
|
491
|
+
if (val) {
|
|
492
|
+
if (val.length <= 10) {
|
|
493
|
+
val = val + ' ' + hora;
|
|
494
|
+
}
|
|
495
|
+
return new Date(val);
|
|
496
|
+
}
|
|
497
|
+
return val;
|
|
498
|
+
}
|
|
499
|
+
function formatearFechaCadena(fecha) {
|
|
500
|
+
const year = parseInt(fecha.substring(0, 4), 10);
|
|
501
|
+
const month = parseInt(fecha.substring(4, 6), 10) - 1;
|
|
502
|
+
const day = parseInt(fecha.substring(6, 8), 10);
|
|
503
|
+
return new Date(year, month, day);
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
function maskEmail(email) {
|
|
507
|
+
const [user, domain] = email.split("@");
|
|
508
|
+
if (user.length <= 2) {
|
|
509
|
+
return `${user[0]}***@${domain}`; // 🔹 Si el usuario es muy corto, no se oculta nada
|
|
510
|
+
}
|
|
511
|
+
if (user.length <= 4) {
|
|
512
|
+
return `${user[0]}***${user.slice(-1)}@${domain}`; // 🔹 Muestra 1 al inicio y 1 al final
|
|
513
|
+
}
|
|
514
|
+
return `${user.slice(0, 2)}***${user.slice(-2)}@${domain}`; // 🔹 Muestra 2 al inicio y 2 al final
|
|
515
|
+
}
|
|
516
|
+
function isEmail(email) {
|
|
517
|
+
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
const mimeTypes = {
|
|
521
|
+
// Imágenes
|
|
522
|
+
'jpg': 'image/jpeg',
|
|
523
|
+
'jpeg': 'image/jpeg',
|
|
524
|
+
'png': 'image/png',
|
|
525
|
+
'gif': 'image/gif',
|
|
526
|
+
'webp': 'image/webp',
|
|
527
|
+
'svg': 'image/svg+xml',
|
|
528
|
+
'ico': 'image/x-icon',
|
|
529
|
+
'bmp': 'image/bmp',
|
|
530
|
+
// Documentos
|
|
531
|
+
'pdf': 'application/pdf',
|
|
532
|
+
'doc': 'application/msword',
|
|
533
|
+
'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
534
|
+
'xls': 'application/vnd.ms-excel',
|
|
535
|
+
'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
536
|
+
'ppt': 'application/vnd.ms-powerpoint',
|
|
537
|
+
'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
|
538
|
+
'txt': 'text/plain',
|
|
539
|
+
'csv': 'text/csv',
|
|
540
|
+
'json': 'application/json',
|
|
541
|
+
'xml': 'application/xml',
|
|
542
|
+
'html': 'text/html',
|
|
543
|
+
// Audio
|
|
544
|
+
'mp3': 'audio/mpeg',
|
|
545
|
+
'wav': 'audio/wav',
|
|
546
|
+
'ogg': 'audio/ogg',
|
|
547
|
+
'm4a': 'audio/mp4',
|
|
548
|
+
// Video
|
|
549
|
+
'mp4': 'video/mp4',
|
|
550
|
+
'avi': 'video/x-msvideo',
|
|
551
|
+
'mov': 'video/quicktime',
|
|
552
|
+
'wmv': 'video/x-ms-wmv',
|
|
553
|
+
'flv': 'video/x-flv',
|
|
554
|
+
'webm': 'video/webm',
|
|
555
|
+
'mkv': 'video/x-matroska',
|
|
556
|
+
// Archivos comprimidos
|
|
557
|
+
'zip': 'application/zip',
|
|
558
|
+
'rar': 'application/vnd.rar',
|
|
559
|
+
'7z': 'application/x-7z-compressed',
|
|
560
|
+
'tar': 'application/x-tar',
|
|
561
|
+
'gz': 'application/gzip',
|
|
562
|
+
'bz2': 'application/x-bzip2',
|
|
563
|
+
// Otros formatos
|
|
564
|
+
'js': 'application/javascript',
|
|
565
|
+
'css': 'text/css',
|
|
566
|
+
'ts': 'application/typescript',
|
|
567
|
+
'md': 'text/markdown',
|
|
568
|
+
'exe': 'application/octet-stream',
|
|
569
|
+
'eot': 'application/vnd.ms-fontobject',
|
|
570
|
+
'woff': 'font/woff',
|
|
571
|
+
'woff2': 'font/woff2',
|
|
572
|
+
'ttf': 'font/ttf',
|
|
573
|
+
'otf': 'font/otf',
|
|
574
|
+
};
|
|
575
|
+
function obtenerMimeType(nombreArchivo) {
|
|
576
|
+
const extension = nombreArchivo.split('.').pop()?.toLowerCase();
|
|
577
|
+
return extension ? mimeTypes[extension] || 'application/octet-stream' : null;
|
|
578
|
+
}
|
|
579
|
+
function sanitizarNombreArchivo(nombre, reemplazo = '_') {
|
|
580
|
+
// 1. Quitar caracteres no válidos para nombres de archivo
|
|
581
|
+
const nombreSanitizado = nombre.replace(/[\/\\:*?"<>|]/g, reemplazo);
|
|
582
|
+
// 2. Reemplazar espacios múltiples o al inicio/final
|
|
583
|
+
const nombreLimpio = nombreSanitizado.trim().replace(/\s+/g, reemplazo);
|
|
584
|
+
// 3. Asegurar longitud máxima (opcional, aquí 255 caracteres)
|
|
585
|
+
return nombreLimpio.substring(0, 255);
|
|
586
|
+
}
|
|
587
|
+
function getDataArchivoFromPath(value, conTimeStamp = false) {
|
|
588
|
+
const partesPath = value.split('/');
|
|
589
|
+
const nombreCompleto = partesPath[partesPath.length - 1];
|
|
590
|
+
let timeStamp = 1;
|
|
591
|
+
let nombreSinTimeStamp = nombreCompleto;
|
|
592
|
+
const partesNombre = nombreCompleto.split('-');
|
|
593
|
+
if (partesNombre.length > 1) {
|
|
594
|
+
timeStamp = partesNombre[0] * 1;
|
|
595
|
+
partesNombre.shift();
|
|
596
|
+
nombreSinTimeStamp = partesNombre.join('-');
|
|
597
|
+
}
|
|
598
|
+
if (conTimeStamp) {
|
|
599
|
+
return {
|
|
600
|
+
nombre: nombreCompleto,
|
|
601
|
+
extension: nombreCompleto.split('.').pop(),
|
|
602
|
+
d: timeStamp,
|
|
603
|
+
fechaSubida: timeStamp ? new Date(timeStamp * 1000) : '',
|
|
604
|
+
};
|
|
605
|
+
}
|
|
606
|
+
return {
|
|
607
|
+
nombre: nombreSinTimeStamp,
|
|
608
|
+
extension: nombreSinTimeStamp.split('.').pop(),
|
|
609
|
+
d: timeStamp,
|
|
610
|
+
fechaSubida: timeStamp ? new Date(timeStamp * 1000) : '',
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
function convertirBytes(valor, unidadSalida = null, incluirUnidad = true) {
|
|
614
|
+
const unidades = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
|
|
615
|
+
const indiceEntrada = unidadSalida ? unidades.indexOf(unidadSalida) : 0;
|
|
616
|
+
if (indiceEntrada === -1) {
|
|
617
|
+
// Unidad de entrada no válida
|
|
618
|
+
return null;
|
|
619
|
+
}
|
|
620
|
+
let indiceActual = indiceEntrada;
|
|
621
|
+
let resultado = valor;
|
|
622
|
+
let cont = 0;
|
|
623
|
+
while (cont < 6 && (indiceActual < unidades.length - 1) && (resultado >= 1024)) {
|
|
624
|
+
resultado /= 1024;
|
|
625
|
+
indiceActual++;
|
|
626
|
+
}
|
|
627
|
+
if (incluirUnidad) {
|
|
628
|
+
return `${resultado.toFixed(2)} ${unidades[indiceActual]}`;
|
|
629
|
+
}
|
|
630
|
+
return resultado;
|
|
631
|
+
}
|
|
632
|
+
function downLoadFileStream(data, type, nombreArchivo) {
|
|
633
|
+
const blob = new Blob([data], { type });
|
|
634
|
+
saveAs(blob, nombreArchivo);
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
function establecerQuitarRequired(formulario, establecer = [], quitar = [], camposDisabled = []) {
|
|
638
|
+
establecer.forEach((control) => {
|
|
639
|
+
if (!formulario.get(control)?.hasValidator(Validators.required)) {
|
|
640
|
+
formulario.get(control)?.addValidators([Validators.required]);
|
|
641
|
+
formulario.get(control)?.enable();
|
|
642
|
+
formulario.get(control)?.updateValueAndValidity();
|
|
643
|
+
}
|
|
644
|
+
});
|
|
645
|
+
const deshabilitar = (strControl) => {
|
|
646
|
+
if (camposDisabled == 'todos') {
|
|
647
|
+
formulario.get(strControl)?.disable();
|
|
648
|
+
console.log(strControl);
|
|
649
|
+
}
|
|
650
|
+
else {
|
|
651
|
+
if (camposDisabled.includes(strControl)) {
|
|
652
|
+
formulario.get(strControl)?.disable();
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
};
|
|
656
|
+
quitar.forEach(control => {
|
|
657
|
+
if (formulario.get(control)?.hasValidator(Validators.required)) {
|
|
658
|
+
formulario.get(control)?.removeValidators([Validators.required]);
|
|
659
|
+
formulario.get(control)?.updateValueAndValidity();
|
|
660
|
+
}
|
|
661
|
+
deshabilitar(control);
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
function getFormValidationErrors(form) {
|
|
665
|
+
const result = [];
|
|
666
|
+
Object.keys(form.controls).forEach(key => {
|
|
667
|
+
const formProperty = form.get(key);
|
|
668
|
+
if (formProperty instanceof FormGroup) {
|
|
669
|
+
result.push(...getFormValidationErrors(formProperty));
|
|
670
|
+
}
|
|
671
|
+
const controlErrors = formProperty?.errors;
|
|
672
|
+
if (controlErrors) {
|
|
673
|
+
Object.keys(controlErrors).forEach(keyError => {
|
|
674
|
+
result.push({
|
|
675
|
+
control: key,
|
|
676
|
+
error: keyError,
|
|
677
|
+
value: controlErrors[keyError]
|
|
678
|
+
});
|
|
679
|
+
});
|
|
680
|
+
}
|
|
681
|
+
});
|
|
682
|
+
return result;
|
|
683
|
+
}
|
|
684
|
+
function mensajesErrorFormControl(control) {
|
|
685
|
+
if (!control || !control.errors || !control.touched)
|
|
686
|
+
return '';
|
|
687
|
+
ReactiveFormConfig.set({
|
|
688
|
+
// RxwebValidators
|
|
689
|
+
validationMessage: {
|
|
690
|
+
required: 'Es requerido',
|
|
691
|
+
numeric: 'Debe ser numérico valido',
|
|
692
|
+
// minLength: 'minimum length is {{1}}',
|
|
693
|
+
// maxLength: 'allowed max length is {{1}}',
|
|
694
|
+
},
|
|
695
|
+
});
|
|
696
|
+
const errorMessages = {
|
|
697
|
+
required: 'Es requerido',
|
|
698
|
+
numeric: 'Debe ser numérico válido',
|
|
699
|
+
min: `Valor mínimo permitido: ${control.errors['min']?.min}`,
|
|
700
|
+
minValue: 'Debe ser positivo',
|
|
701
|
+
minlength: `Mínimo ${control.errors['minlength']?.requiredLength} caracteres.`,
|
|
702
|
+
maxlength: `Caracteres ${control.errors['maxlength']?.actualLength}/${control.errors['maxlength']?.requiredLength}`,
|
|
703
|
+
email: 'No se cumple con el formato de Correo Electrónico',
|
|
704
|
+
isNumeric: 'Debe seleccionar una opción',
|
|
705
|
+
hasNumber: 'Se requiere al menos un número',
|
|
706
|
+
hasCapitalCase: 'Se requiere al menos una mayúscula',
|
|
707
|
+
hasSmallCase: 'Se requiere al menos una minúscula',
|
|
708
|
+
hasSpecialCharacters: 'Se requiere al menos un carácter especial',
|
|
709
|
+
NoPassswordMatch: 'La contraseña no coincide',
|
|
710
|
+
itemSelected: 'Debe seleccionar una opción de la lista',
|
|
711
|
+
inputMask: 'El formato ingresado no es válido',
|
|
712
|
+
};
|
|
713
|
+
// Devuelve el primer mensaje de error encontrado
|
|
714
|
+
for (const errorKey of Object.keys(control.errors)) {
|
|
715
|
+
if (errorMessages[errorKey]) {
|
|
716
|
+
return errorMessages[errorKey];
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
// Si el error tiene un mensaje personalizado, usarlo
|
|
720
|
+
return control.errors[Object.keys(control.errors)[0]]?.message || '';
|
|
721
|
+
}
|
|
722
|
+
function toFormData(formValue) {
|
|
723
|
+
const formData = new FormData();
|
|
724
|
+
Object.keys(formValue).forEach((key) => {
|
|
725
|
+
const value = formValue[key];
|
|
726
|
+
if (value === null || value === undefined) {
|
|
727
|
+
return; // Ignorar valores nulos o indefinidos
|
|
728
|
+
}
|
|
729
|
+
if (Array.isArray(value)) {
|
|
730
|
+
value.forEach((item, index) => {
|
|
731
|
+
if (typeof item === 'object' && item !== null) {
|
|
732
|
+
if ('file' in item) {
|
|
733
|
+
formData.append(`${key}[${index}]`, item.file);
|
|
734
|
+
}
|
|
735
|
+
else {
|
|
736
|
+
formData.append(`${key}[${index}]`, JSON.stringify(item));
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
else {
|
|
740
|
+
formData.append(`${key}[${index}]`, item.toString());
|
|
741
|
+
}
|
|
742
|
+
});
|
|
743
|
+
}
|
|
744
|
+
else if (typeof value === 'object') {
|
|
745
|
+
// Si es un objeto (pero no un array), convertirlo a JSON
|
|
746
|
+
formData.append(key, JSON.stringify(value));
|
|
747
|
+
}
|
|
748
|
+
else {
|
|
749
|
+
// Para valores primitivos (string, number, boolean)
|
|
750
|
+
formData.append(key, value.toString());
|
|
751
|
+
}
|
|
752
|
+
});
|
|
753
|
+
return formData;
|
|
754
|
+
}
|
|
755
|
+
function markAsTouchedWithoutEmitEvent(control) {
|
|
756
|
+
if (control instanceof FormControl) {
|
|
757
|
+
control.markAsTouched({ onlySelf: true });
|
|
758
|
+
control.updateValueAndValidity({ emitEvent: false });
|
|
759
|
+
}
|
|
760
|
+
else if (control instanceof FormGroup || control instanceof FormArray) {
|
|
761
|
+
Object.values(control.controls).forEach(childControl => {
|
|
762
|
+
markAsTouchedWithoutEmitEvent(childControl);
|
|
763
|
+
});
|
|
764
|
+
control.updateValueAndValidity({ emitEvent: false });
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
function mensajeAlerta(tipo, titulo, mensaje, opciones) {
|
|
769
|
+
opciones = {
|
|
770
|
+
...{
|
|
771
|
+
heightAuto: false,
|
|
772
|
+
title: titulo,
|
|
773
|
+
html: mensaje,
|
|
774
|
+
icon: tipo,
|
|
775
|
+
confirmButtonText: 'Aceptar',
|
|
776
|
+
// customClass: {
|
|
777
|
+
// confirmButton: 'btn btn-lg btn-outline-success mx-2',
|
|
778
|
+
// cancelButton: 'btn btn-lg btn-outline-dark mx-2'
|
|
779
|
+
// },
|
|
780
|
+
// buttonsStyling: false
|
|
781
|
+
},
|
|
782
|
+
...opciones
|
|
783
|
+
};
|
|
784
|
+
return swal.fire(opciones);
|
|
785
|
+
}
|
|
786
|
+
function mensajeTimer(tipo, titulo, mensaje, milisegundos = 3000, showLoading = true, opciones) {
|
|
787
|
+
let timerInterval;
|
|
788
|
+
opciones = {
|
|
789
|
+
...{
|
|
790
|
+
heightAuto: false,
|
|
791
|
+
title: titulo,
|
|
792
|
+
html: mensaje + '<br> Se cerrará en <strong> X </strong> segundos.',
|
|
793
|
+
icon: tipo,
|
|
794
|
+
timer: milisegundos,
|
|
795
|
+
showCancelButton: false,
|
|
796
|
+
showConfirmButton: false,
|
|
797
|
+
willOpen: () => {
|
|
798
|
+
if (showLoading) {
|
|
799
|
+
swal.showLoading();
|
|
800
|
+
}
|
|
801
|
+
timerInterval = setInterval(() => {
|
|
802
|
+
const impr = Math.ceil(((swal.getTimerLeft() ?? 1) / 1000));
|
|
803
|
+
if (swal.getHtmlContainer()) {
|
|
804
|
+
// @ts-ignore
|
|
805
|
+
swal.getHtmlContainer().querySelector('strong').textContent = String(impr);
|
|
806
|
+
}
|
|
807
|
+
}, 100);
|
|
808
|
+
},
|
|
809
|
+
willClose: () => {
|
|
810
|
+
clearInterval(timerInterval);
|
|
811
|
+
}
|
|
812
|
+
},
|
|
813
|
+
...opciones
|
|
814
|
+
};
|
|
815
|
+
return swal.fire(opciones);
|
|
816
|
+
}
|
|
817
|
+
// @ts-ignore
|
|
818
|
+
function mensajeConfirmacion(tipo, titulo, mensaje, opciones) {
|
|
819
|
+
opciones = {
|
|
820
|
+
...{
|
|
821
|
+
heightAuto: false,
|
|
822
|
+
title: titulo,
|
|
823
|
+
html: mensaje,
|
|
824
|
+
icon: tipo,
|
|
825
|
+
showCancelButton: true,
|
|
826
|
+
// confirmButtonColor: '#3f51b5',
|
|
827
|
+
// cancelButtonColor: '#ffffff',
|
|
828
|
+
confirmButtonText: 'Confirmar',
|
|
829
|
+
cancelButtonText: 'Cancelar',
|
|
830
|
+
reverseButtons: true,
|
|
831
|
+
// customClass: {
|
|
832
|
+
// confirmButton: 'btn btn-lg btn-outline-success mx-2',
|
|
833
|
+
// cancelButton: 'btn btn-lg btn-outline-dark mx-2'
|
|
834
|
+
// },
|
|
835
|
+
// buttonsStyling: false
|
|
836
|
+
},
|
|
837
|
+
...opciones
|
|
838
|
+
};
|
|
839
|
+
return swal.fire(opciones);
|
|
840
|
+
}
|
|
841
|
+
function mensajeToast(tipo, titulo, mensaje, opciones) {
|
|
842
|
+
opciones = {
|
|
843
|
+
...{
|
|
844
|
+
heightAuto: false,
|
|
845
|
+
title: titulo,
|
|
846
|
+
html: mensaje,
|
|
847
|
+
icon: tipo,
|
|
848
|
+
confirmButtonText: 'Aceptar',
|
|
849
|
+
toast: true,
|
|
850
|
+
position: 'top-end',
|
|
851
|
+
showConfirmButton: false,
|
|
852
|
+
timer: 3000,
|
|
853
|
+
timerProgressBar: true,
|
|
854
|
+
},
|
|
855
|
+
...opciones
|
|
856
|
+
};
|
|
857
|
+
return swal.fire(opciones);
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
function mensajesDeError(error, toast = false) {
|
|
861
|
+
let msg;
|
|
862
|
+
if (error.error && error.error instanceof ArrayBuffer) {
|
|
863
|
+
const msgArrayBuffer = (arrayBuffer) => {
|
|
864
|
+
try {
|
|
865
|
+
const mensajeError = JSON.parse(new TextDecoder("utf-8").decode(arrayBuffer));
|
|
866
|
+
return mensajeError.message || 'Error desconocido';
|
|
867
|
+
}
|
|
868
|
+
catch (parseError) {
|
|
869
|
+
console.error('Error al analizar la respuesta JSON:', parseError);
|
|
870
|
+
return 'Error al analizar la respuesta JSON';
|
|
871
|
+
}
|
|
872
|
+
};
|
|
873
|
+
msg = msgArrayBuffer(error.error);
|
|
874
|
+
}
|
|
875
|
+
else {
|
|
876
|
+
switch (error.status) {
|
|
877
|
+
case 0:
|
|
878
|
+
// msg = error.message;
|
|
879
|
+
msg = 'El servidor no responde, verifica tu conexion a la red';
|
|
880
|
+
console.log(error);
|
|
881
|
+
break;
|
|
882
|
+
case 401:
|
|
883
|
+
if (error.error && typeof error.error == 'object') {
|
|
884
|
+
if (error.error.message) {
|
|
885
|
+
msg = error.error.message;
|
|
886
|
+
}
|
|
887
|
+
else if (error.error.error) {
|
|
888
|
+
msg = error.error.error;
|
|
889
|
+
}
|
|
890
|
+
else {
|
|
891
|
+
msg = JSON.stringify(error.error);
|
|
892
|
+
console.log(error);
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
else if (error.error && typeof error.error == 'string') {
|
|
896
|
+
msg = error.error;
|
|
897
|
+
}
|
|
898
|
+
else {
|
|
899
|
+
msg = 'Acceso no autorizado';
|
|
900
|
+
console.log(error);
|
|
901
|
+
}
|
|
902
|
+
break;
|
|
903
|
+
case 422:
|
|
904
|
+
let strEr = '';
|
|
905
|
+
console.log(typeof error.error.errors);
|
|
906
|
+
console.log(error.error.errors);
|
|
907
|
+
if (error.error.errors) {
|
|
908
|
+
Object.keys(error.error.errors).forEach(o => {
|
|
909
|
+
strEr += '<li>' + error.error.errors[o][0] + '</li>';
|
|
910
|
+
});
|
|
911
|
+
msg = (error.error.message ?? '') + '<ul>' + strEr + '</ul>';
|
|
912
|
+
}
|
|
913
|
+
else if (error.error.error) {
|
|
914
|
+
msg = error.error.msg;
|
|
915
|
+
}
|
|
916
|
+
break;
|
|
917
|
+
case 429:
|
|
918
|
+
case 400:
|
|
919
|
+
case 500:
|
|
920
|
+
case 503:
|
|
921
|
+
msg = error.error.message;
|
|
922
|
+
break;
|
|
923
|
+
case 504:
|
|
924
|
+
msg = 'No se puede conectar al servidor. Comprueba tu conexion a la red - ' + error.statusText;
|
|
925
|
+
break;
|
|
926
|
+
default:
|
|
927
|
+
msg = error?.error?.message ?? 'Error de Sistema';
|
|
928
|
+
console.log(error);
|
|
929
|
+
break;
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
if (!msg) {
|
|
933
|
+
msg = error.statusText ?? 'Error inesperado o datos inexistentes.';
|
|
934
|
+
}
|
|
935
|
+
let tituloFinal = 'Error!';
|
|
936
|
+
let mensajeFinal;
|
|
937
|
+
if (msg.includes('Hmac::doVerify')) {
|
|
938
|
+
console.log(error, msg);
|
|
939
|
+
return;
|
|
940
|
+
}
|
|
941
|
+
else if (msg == 'Server Error') {
|
|
942
|
+
console.log(error, msg);
|
|
943
|
+
return;
|
|
944
|
+
}
|
|
945
|
+
else if (msg.includes('[IMSSP]')) {
|
|
946
|
+
mensajeFinal = 'Error en consulta de registros.';
|
|
947
|
+
}
|
|
948
|
+
else if (msg.includes('Tiempo de espera de la')) {
|
|
949
|
+
mensajeFinal = 'Hubo un error en la solicitud de datos, por favor actualice (SHIFT + F5)';
|
|
950
|
+
}
|
|
951
|
+
else {
|
|
952
|
+
mensajeFinal = msg;
|
|
953
|
+
}
|
|
954
|
+
if (toast) {
|
|
955
|
+
mensajeToast('error', tituloFinal, mensajeFinal);
|
|
956
|
+
}
|
|
957
|
+
else {
|
|
958
|
+
mensajeAlerta('error', tituloFinal, mensajeFinal);
|
|
959
|
+
}
|
|
960
|
+
throw new Error(mensajeFinal);
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
let dataSessionStorageKey = {
|
|
964
|
+
tokenStringKey: 'JVSoftTkn',
|
|
965
|
+
changePasswordKey: 'chPwd',
|
|
966
|
+
logoUrl: 'logo_url',
|
|
967
|
+
logoLogin: 'login-logo',
|
|
968
|
+
backgroundLogin: 'login-background',
|
|
969
|
+
favicon: 'favicon',
|
|
970
|
+
darkMode: 'darkMode',
|
|
971
|
+
serverTimestamp: 'srvtmstp',
|
|
972
|
+
apiDataKey: 'reqDt',
|
|
973
|
+
};
|
|
974
|
+
let localStorageKeys = dataSessionStorageKey;
|
|
975
|
+
function inicializarVariablesSessionStorage(datSesion) {
|
|
976
|
+
dataSessionStorageKey = datSesion;
|
|
977
|
+
}
|
|
978
|
+
function setJwtTokenData(data) {
|
|
979
|
+
localStorage.setItem(dataSessionStorageKey.tokenStringKey, data);
|
|
980
|
+
}
|
|
981
|
+
function jwtTokenData(key = dataSessionStorageKey.tokenStringKey) {
|
|
982
|
+
const tokenObj = localStorage.getItem(key);
|
|
983
|
+
try {
|
|
984
|
+
return JSON.parse(tokenObj);
|
|
985
|
+
}
|
|
986
|
+
catch (error) {
|
|
987
|
+
return null;
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
function jwtToken(key = dataSessionStorageKey.tokenStringKey) {
|
|
991
|
+
const varJwtTokenData = jwtTokenData(key);
|
|
992
|
+
if (varJwtTokenData) {
|
|
993
|
+
return varJwtTokenData.access_token;
|
|
994
|
+
}
|
|
995
|
+
return '';
|
|
996
|
+
}
|
|
997
|
+
function jwtTokenExpiracion(key = dataSessionStorageKey.tokenStringKey) {
|
|
998
|
+
const jwtStr = jwtToken(key);
|
|
999
|
+
if (!jwtStr)
|
|
1000
|
+
return null;
|
|
1001
|
+
try {
|
|
1002
|
+
const decodedToken = jwtDecode(jwtStr);
|
|
1003
|
+
return decodedToken.exp ? decodedToken.exp * 1000 : null; // Convertir a milisegundos
|
|
1004
|
+
}
|
|
1005
|
+
catch (e) {
|
|
1006
|
+
return null;
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
function jwtTokenExpiracionFaltante() {
|
|
1010
|
+
return Math.abs(moment().diff(jwtTokenExpiracion(), 'seconds'));
|
|
1011
|
+
}
|
|
1012
|
+
function setCambiarPwd(accion = true) {
|
|
1013
|
+
localStorage.setItem(dataSessionStorageKey.changePasswordKey, (accion ? 1 : 0).toString());
|
|
1014
|
+
}
|
|
1015
|
+
function getCambiarPwd() {
|
|
1016
|
+
const frmCambioPwd = localStorage.getItem(dataSessionStorageKey.changePasswordKey);
|
|
1017
|
+
if (!frmCambioPwd) {
|
|
1018
|
+
return null;
|
|
1019
|
+
}
|
|
1020
|
+
return frmCambioPwd == '1';
|
|
1021
|
+
}
|
|
1022
|
+
function delLocalStorage(keyElim = [
|
|
1023
|
+
dataSessionStorageKey.tokenStringKey,
|
|
1024
|
+
dataSessionStorageKey.changePasswordKey,
|
|
1025
|
+
dataSessionStorageKey.apiDataKey,
|
|
1026
|
+
]) {
|
|
1027
|
+
keyElim.forEach(key => {
|
|
1028
|
+
localStorage.removeItem(key);
|
|
1029
|
+
});
|
|
1030
|
+
}
|
|
1031
|
+
function getLocalStorage(key) {
|
|
1032
|
+
return localStorage.getItem(key);
|
|
1033
|
+
}
|
|
1034
|
+
function setLocalStorage(key, value = '') {
|
|
1035
|
+
localStorage.setItem(key, value.toString());
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
function roundToDecimal(number, decimal) {
|
|
1039
|
+
return parseFloat(number.toFixed(decimal));
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
function objectPropertiesToType(formFields) {
|
|
1043
|
+
Object.keys(formFields).filter(control => !!formFields[control]).forEach(control => {
|
|
1044
|
+
if (/^dt[a-zA-Z]+/.test(control)) {
|
|
1045
|
+
formFields[control] = formatDate(formFields[control], 'yyyy-MM-dd HH:mm', 'es-PE');
|
|
1046
|
+
}
|
|
1047
|
+
else if (control.startsWith('d')) {
|
|
1048
|
+
formFields[control] = formatearFecha(formFields[control]);
|
|
1049
|
+
}
|
|
1050
|
+
else if (control.startsWith('n')) {
|
|
1051
|
+
formFields[control] = Number(formFields[control]);
|
|
1052
|
+
}
|
|
1053
|
+
});
|
|
1054
|
+
return formFields;
|
|
1055
|
+
}
|
|
1056
|
+
function objectPropertiesBoolean(formFields, retorno = 'boolean') {
|
|
1057
|
+
Object.keys(formFields).forEach(control => {
|
|
1058
|
+
const valRetorno = (ctrl) => {
|
|
1059
|
+
switch (retorno) {
|
|
1060
|
+
case 'boolean':
|
|
1061
|
+
formFields[ctrl] = formFields[ctrl] == 1;
|
|
1062
|
+
break;
|
|
1063
|
+
case 'bit':
|
|
1064
|
+
formFields[ctrl] = formFields[ctrl] ? 1 : 0;
|
|
1065
|
+
break;
|
|
1066
|
+
}
|
|
1067
|
+
};
|
|
1068
|
+
if (control.charAt(0) == 'b' || (control.charAt(0) == 'i' && control.indexOf('Estado') !== -1)) {
|
|
1069
|
+
valRetorno(control);
|
|
1070
|
+
}
|
|
1071
|
+
});
|
|
1072
|
+
return formFields;
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
function generateRandomString(length) {
|
|
1076
|
+
let result = '';
|
|
1077
|
+
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
|
1078
|
+
const charactersLength = characters.length;
|
|
1079
|
+
for (let i = 0; i < length; i++) {
|
|
1080
|
+
result += characters.charAt(Math.floor(Math.random() * charactersLength));
|
|
1081
|
+
}
|
|
1082
|
+
return result;
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
function verificarRUC(ruc) {
|
|
1086
|
+
const f = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2];
|
|
1087
|
+
const rucArray = ruc.split('');
|
|
1088
|
+
const nArray = f.map((item, idx) => {
|
|
1089
|
+
return item * parseFloat(rucArray[idx]);
|
|
1090
|
+
});
|
|
1091
|
+
const suma = nArray.reduce((a, b) => a + b, 0);
|
|
1092
|
+
const residuo = suma % 11;
|
|
1093
|
+
const residuo2 = 11 - residuo;
|
|
1094
|
+
// @residuo=CONVERT(Integer,Right(CONVERT(VarChar,@residuo),1))
|
|
1095
|
+
const residuo3 = residuo2.toString().charAt(residuo2.toString().length - 1);
|
|
1096
|
+
const ultimoCaracter = ruc.toString().charAt(ruc.toString().length - 1);
|
|
1097
|
+
if (residuo3 == ultimoCaracter) {
|
|
1098
|
+
return true;
|
|
1099
|
+
}
|
|
1100
|
+
mensajeAlerta('error', 'Datos No válidos', ' El número de RUC no es válido');
|
|
1101
|
+
return false;
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
/**
|
|
1105
|
+
* Generated bundle index. Do not edit.
|
|
1106
|
+
*/
|
|
1107
|
+
|
|
1108
|
+
export { b64Decode, b64Encode, buscarPorCampo, changeSelect, changeSelectApi, changeSelectData, changeSelectDataApi, convertirBytes, deepClone, deepMerge, delLocalStorage, desencriptar, downLoadFileStream, encriptar, esNumero, establecerQuitarRequired, 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, objectPropertiesBoolean, objectPropertiesToType, obtenerMimeType, obtenerUltimoOrden, ordenarArray, ordenarPorPropiedad, ordenarPorPropiedades, roundToDecimal, sanitizarNombreArchivo, seleccionarTextoInput, setCambiarPwd, setJwtTokenData, setLocalStorage, sumarObjetos, sumarPropiedades, toFormData, verificarRUC };
|
|
1109
|
+
//# sourceMappingURL=jvsoft-utils-src-functions.mjs.map
|