@jvsoft/utils 0.0.13-alpha.3 → 0.0.13-alpha.4
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/CHANGELOG.md +25 -0
- package/ng-package.json +7 -0
- package/package.json +3 -26
- package/src/classes/data-model.ts +150 -0
- package/src/functions/base64.ts +8 -0
- package/src/functions/browser.ts +20 -0
- package/src/functions/crypto-js.ts +29 -0
- package/src/functions/date.ts +23 -0
- package/src/functions/email.ts +17 -0
- package/src/functions/file.ts +138 -0
- package/src/functions/forms.ts +251 -0
- package/src/functions/http-client.ts +110 -0
- package/src/functions/index.ts +1 -0
- package/src/functions/local-storage.ts +102 -0
- package/src/functions/mat-form-controls/autocomplete.ts +205 -0
- package/src/functions/mat-form-controls/index.ts +6 -0
- package/src/functions/ng-package.json +5 -0
- package/src/functions/number.ts +85 -0
- package/src/functions/object-transformation.ts +37 -0
- package/src/functions/objects-arrays.ts +321 -0
- package/src/functions/public-api.ts +19 -0
- package/src/functions/string.ts +68 -0
- package/src/functions/sweetalert.ts +95 -0
- package/src/functions/utiles.ts +20 -0
- package/{interfaces/datos.d.ts → src/interfaces/datos.ts} +2 -1
- package/src/interfaces/index.ts +1 -0
- package/src/interfaces/ng-package.json +5 -0
- package/src/interfaces/otros.ts +0 -0
- package/src/interfaces/public-api.ts +3 -0
- package/src/interfaces/routes.ts +42 -0
- package/src/pipes/data-en-lista.pipe.ts +40 -0
- package/src/pipes/date-diff-string.pipe.ts +117 -0
- package/src/pipes/filtro.pipe.ts +64 -0
- package/src/pipes/form-control-is-required.pipe.ts +17 -0
- package/src/pipes/index.ts +1 -0
- package/src/pipes/json-parse.pipe.ts +18 -0
- package/src/pipes/ng-package.json +5 -0
- package/src/pipes/no-sanitize.pipe.ts +12 -0
- package/src/pipes/public-api.ts +10 -0
- package/src/pipes/tipo-valor-funcion.pipe.ts +23 -0
- package/src/pipes/zero-fill.pipe.ts +19 -0
- package/src/public-api.ts +12 -0
- package/tsconfig.lib.json +18 -0
- package/tsconfig.lib.prod.json +11 -0
- package/tsconfig.spec.json +15 -0
- package/classes/data-model.d.ts +0 -25
- package/fesm2022/jvsoft-utils-src-functions.mjs +0 -1367
- package/fesm2022/jvsoft-utils-src-functions.mjs.map +0 -1
- package/fesm2022/jvsoft-utils-src-interfaces.mjs +0 -6
- package/fesm2022/jvsoft-utils-src-interfaces.mjs.map +0 -1
- package/fesm2022/jvsoft-utils-src-pipes.mjs +0 -290
- package/fesm2022/jvsoft-utils-src-pipes.mjs.map +0 -1
- package/fesm2022/jvsoft-utils.mjs +0 -1784
- package/fesm2022/jvsoft-utils.mjs.map +0 -1
- package/functions/base64.d.ts +0 -2
- package/functions/browser.d.ts +0 -1
- package/functions/crypto-js.d.ts +0 -2
- package/functions/date.d.ts +0 -3
- package/functions/email.d.ts +0 -2
- package/functions/file.d.ts +0 -10
- package/functions/forms.d.ts +0 -23
- package/functions/http-client.d.ts +0 -2
- package/functions/index.d.ts +0 -1
- package/functions/local-storage.d.ts +0 -29
- package/functions/mat-form-controls/autocomplete.d.ts +0 -21
- package/functions/mat-form-controls/index.d.ts +0 -2
- package/functions/number.d.ts +0 -2
- package/functions/object-transformation.d.ts +0 -2
- package/functions/objects-arrays.d.ts +0 -47
- package/functions/public-api.d.ts +0 -16
- package/functions/string.d.ts +0 -23
- package/functions/sweetalert.d.ts +0 -5
- package/functions/utiles.d.ts +0 -1
- package/index.d.ts +0 -5
- package/interfaces/index.d.ts +0 -1
- package/interfaces/public-api.d.ts +0 -1
- package/pipes/data-en-lista.pipe.d.ts +0 -8
- package/pipes/date-diff-string.pipe.d.ts +0 -17
- package/pipes/filtro.pipe.d.ts +0 -18
- package/pipes/form-control-is-required.pipe.d.ts +0 -9
- package/pipes/index.d.ts +0 -1
- package/pipes/json-parse.pipe.d.ts +0 -7
- package/pipes/no-sanitize.pipe.d.ts +0 -10
- package/pipes/public-api.d.ts +0 -8
- package/pipes/tipo-valor-funcion.pipe.d.ts +0 -9
- package/pipes/zero-fill.pipe.d.ts +0 -8
- package/public-api.d.ts +0 -4
- package/src/functions/base64.d.ts +0 -2
- package/src/functions/browser.d.ts +0 -1
- package/src/functions/crypto-js.d.ts +0 -2
- package/src/functions/date.d.ts +0 -3
- package/src/functions/email.d.ts +0 -2
- package/src/functions/file.d.ts +0 -10
- package/src/functions/forms.d.ts +0 -23
- package/src/functions/http-client.d.ts +0 -2
- package/src/functions/index.d.ts +0 -5
- package/src/functions/local-storage.d.ts +0 -29
- package/src/functions/mat-form-controls/autocomplete.d.ts +0 -21
- package/src/functions/mat-form-controls/index.d.ts +0 -2
- package/src/functions/number.d.ts +0 -2
- package/src/functions/object-transformation.d.ts +0 -2
- package/src/functions/objects-arrays.d.ts +0 -47
- package/src/functions/public-api.d.ts +0 -16
- package/src/functions/string.d.ts +0 -23
- package/src/functions/sweetalert.d.ts +0 -5
- package/src/functions/utiles.d.ts +0 -1
- package/src/interfaces/datos.d.ts +0 -4
- package/src/interfaces/index.d.ts +0 -5
- package/src/interfaces/public-api.d.ts +0 -1
- package/src/pipes/data-en-lista.pipe.d.ts +0 -8
- package/src/pipes/date-diff-string.pipe.d.ts +0 -17
- package/src/pipes/filtro.pipe.d.ts +0 -18
- package/src/pipes/form-control-is-required.pipe.d.ts +0 -9
- package/src/pipes/index.d.ts +0 -5
- package/src/pipes/json-parse.pipe.d.ts +0 -7
- package/src/pipes/no-sanitize.pipe.d.ts +0 -10
- package/src/pipes/public-api.d.ts +0 -8
- package/src/pipes/tipo-valor-funcion.pipe.d.ts +0 -9
- package/src/pipes/zero-fill.pipe.d.ts +0 -8
|
@@ -1,1367 +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
|
-
function mostrarValorEnBusqueda(campos, idxSel) {
|
|
264
|
-
const impDataMostrar = () => {
|
|
265
|
-
let vD;
|
|
266
|
-
if (campos.campoId == '*object*' || campos.campoId == '*objeto*') {
|
|
267
|
-
console.log(campos);
|
|
268
|
-
vD = campos.lista.find((x) => JSON.stringify(x).trim() == JSON.stringify(idxSel).trim());
|
|
269
|
-
console.log(vD);
|
|
270
|
-
}
|
|
271
|
-
else {
|
|
272
|
-
vD = campos.lista.find((x) => x[campos.campoId] == idxSel);
|
|
273
|
-
}
|
|
274
|
-
if (!vD && campos.opcExtra) {
|
|
275
|
-
console.log('eval ', campos.opcExtra);
|
|
276
|
-
if (campos.campoId == '*object*' || campos.campoId == '*objeto*') {
|
|
277
|
-
console.log(campos);
|
|
278
|
-
vD = campos.opcExtra.find((x) => JSON.stringify(x).trim() == JSON.stringify(idxSel).trim());
|
|
279
|
-
console.log(vD);
|
|
280
|
-
}
|
|
281
|
-
else {
|
|
282
|
-
vD = campos.opcExtra.find((x) => x[campos.campoId] == idxSel);
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
if (vD) {
|
|
286
|
-
let txtFinal = '';
|
|
287
|
-
if (Array.isArray(campos.campoValue)) {
|
|
288
|
-
campos.campoValue.forEach((vCampo, idx) => {
|
|
289
|
-
txtFinal += (vD[vCampo] ?? '');
|
|
290
|
-
if (idx < campos.campoValue.length - 1) {
|
|
291
|
-
txtFinal += ' - ';
|
|
292
|
-
}
|
|
293
|
-
});
|
|
294
|
-
}
|
|
295
|
-
else {
|
|
296
|
-
txtFinal = vD[campos.campoValue] ?? '';
|
|
297
|
-
}
|
|
298
|
-
return txtFinal.trim();
|
|
299
|
-
}
|
|
300
|
-
else {
|
|
301
|
-
console.log('ASSSSS ----- SSSS ');
|
|
302
|
-
}
|
|
303
|
-
return '';
|
|
304
|
-
};
|
|
305
|
-
if (esNumero(idxSel)) {
|
|
306
|
-
if (idxSel > 0 && campos.lista?.length > 0) {
|
|
307
|
-
return impDataMostrar();
|
|
308
|
-
}
|
|
309
|
-
else if (idxSel && typeof idxSel == 'object') {
|
|
310
|
-
return impDataMostrar();
|
|
311
|
-
}
|
|
312
|
-
}
|
|
313
|
-
else {
|
|
314
|
-
if (campos.lista?.length > 0) {
|
|
315
|
-
return impDataMostrar();
|
|
316
|
-
}
|
|
317
|
-
}
|
|
318
|
-
return '';
|
|
319
|
-
}
|
|
320
|
-
function changeSelectData(objThis, dataFiltro) {
|
|
321
|
-
objThis['filtrados'][dataFiltro.variableResultado] = dataFiltro.formControl.valueChanges.pipe(untilDestroyed(objThis)).pipe(startWith(''), map(value => {
|
|
322
|
-
const varN = dataFiltro.data;
|
|
323
|
-
if (varN) {
|
|
324
|
-
if (value) {
|
|
325
|
-
return varN.map(x => x).filter(dat => {
|
|
326
|
-
if (Array.isArray(dataFiltro.campoBuscar)) {
|
|
327
|
-
let encontrado = false;
|
|
328
|
-
for (const vCampo of dataFiltro.campoBuscar) {
|
|
329
|
-
// console.log(vCampo, value, dat[vCampo]);
|
|
330
|
-
if (isNaN(Number(value))) {
|
|
331
|
-
// NO ES NUMERO
|
|
332
|
-
if (value && dat[vCampo] && dat[vCampo].toLowerCase().includes(value?.toString().toLowerCase())) {
|
|
333
|
-
encontrado = true;
|
|
334
|
-
break;
|
|
335
|
-
}
|
|
336
|
-
}
|
|
337
|
-
else {
|
|
338
|
-
if (value && dat[vCampo] && dat[vCampo].toString().includes(value?.toString())) {
|
|
339
|
-
encontrado = true;
|
|
340
|
-
break;
|
|
341
|
-
}
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
return encontrado;
|
|
345
|
-
}
|
|
346
|
-
else {
|
|
347
|
-
if (isNaN(Number(value))) {
|
|
348
|
-
return dat[dataFiltro.campoBuscar].toLowerCase().includes(value?.toString().toLowerCase());
|
|
349
|
-
}
|
|
350
|
-
else {
|
|
351
|
-
return dat[dataFiltro.campoBuscar].toString().includes(value?.toString());
|
|
352
|
-
}
|
|
353
|
-
}
|
|
354
|
-
});
|
|
355
|
-
}
|
|
356
|
-
return varN;
|
|
357
|
-
}
|
|
358
|
-
return false;
|
|
359
|
-
}));
|
|
360
|
-
}
|
|
361
|
-
function changeSelect(control, formControl, tipo, campoBuscar, campoFiltro = null) {
|
|
362
|
-
// console.log(formControl);
|
|
363
|
-
// const formGroup = formControl.parent.controls;
|
|
364
|
-
// console.warn( Object.keys(formGroup).find(name => formControl === formGroup[name]) || null );
|
|
365
|
-
if (!campoFiltro) {
|
|
366
|
-
campoFiltro = tipo;
|
|
367
|
-
}
|
|
368
|
-
control['filtrados'][campoFiltro ?? '__'] = formControl.valueChanges.pipe(untilDestroyed(control)).pipe(startWith(''), map(value => {
|
|
369
|
-
// console.warn(value);
|
|
370
|
-
const partes = tipo.split('.');
|
|
371
|
-
let varN;
|
|
372
|
-
if (control['dataServidor']) {
|
|
373
|
-
varN = (partes.length > 1) ? control['dataServidor'][partes[0]][partes[1]] : control['dataServidor'][tipo];
|
|
374
|
-
}
|
|
375
|
-
else if (control['dataServidorSuscripcion']) {
|
|
376
|
-
varN = control['dataServidorSuscripcion'][tipo].getValue();
|
|
377
|
-
}
|
|
378
|
-
if (varN) {
|
|
379
|
-
if (value) {
|
|
380
|
-
return varN.map((x) => x).filter((dat) => {
|
|
381
|
-
if (Array.isArray(campoBuscar)) {
|
|
382
|
-
let encontrado = false;
|
|
383
|
-
for (const vCampo of campoBuscar) {
|
|
384
|
-
// console.log(vCampo, value, dat[vCampo]);
|
|
385
|
-
if (isNaN(Number(value))) {
|
|
386
|
-
// NO ES NUMERO
|
|
387
|
-
if (value && dat[vCampo] && dat[vCampo].toLowerCase().includes(value?.toString().toLowerCase())) {
|
|
388
|
-
encontrado = true;
|
|
389
|
-
break;
|
|
390
|
-
}
|
|
391
|
-
}
|
|
392
|
-
else {
|
|
393
|
-
if (value && dat[vCampo] && dat[vCampo].toString().includes(value?.toString())) {
|
|
394
|
-
encontrado = true;
|
|
395
|
-
break;
|
|
396
|
-
}
|
|
397
|
-
}
|
|
398
|
-
}
|
|
399
|
-
return encontrado;
|
|
400
|
-
}
|
|
401
|
-
else {
|
|
402
|
-
if (isNaN(Number(value))) {
|
|
403
|
-
return dat[campoBuscar].toLowerCase().includes(value?.toString().toLowerCase());
|
|
404
|
-
}
|
|
405
|
-
else {
|
|
406
|
-
return dat[campoBuscar].toString().includes(value?.toString());
|
|
407
|
-
}
|
|
408
|
-
}
|
|
409
|
-
});
|
|
410
|
-
}
|
|
411
|
-
return varN;
|
|
412
|
-
}
|
|
413
|
-
return false;
|
|
414
|
-
}));
|
|
415
|
-
}
|
|
416
|
-
function changeSelectDataApi(objThis, dataFiltro) {
|
|
417
|
-
if (!dataFiltro.variableResultado) {
|
|
418
|
-
dataFiltro.variableResultado = dataFiltro.tipoReq;
|
|
419
|
-
}
|
|
420
|
-
const idFiltrado = dataFiltro.variableResultado;
|
|
421
|
-
dataFiltro.formControl.valueChanges.pipe(debounceTime(500), tap(() => {
|
|
422
|
-
objThis.filtrados[dataFiltro.variableResultado + 'tmp'] = isObservable(objThis.filtrados[idFiltrado]) ? [] : objThis.filtrados[idFiltrado] || [];
|
|
423
|
-
if (objThis.filtrados[idFiltrado] !== objThis.filtrados[idFiltrado + 'tmp']) {
|
|
424
|
-
objThis.filtrados[idFiltrado] = [];
|
|
425
|
-
}
|
|
426
|
-
objThis.isLoading = true;
|
|
427
|
-
}), switchMap(value => {
|
|
428
|
-
if (dataFiltro.campoId) {
|
|
429
|
-
const busquedaActual2 = objThis.filtrados[idFiltrado + 'tmp'].findIndex((item) => item[dataFiltro.campoId ?? '--'] === value);
|
|
430
|
-
if (busquedaActual2 >= 0) {
|
|
431
|
-
return of({ [dataFiltro.tipoReq]: objThis.filtrados[idFiltrado + 'tmp'] });
|
|
432
|
-
}
|
|
433
|
-
}
|
|
434
|
-
return !value || value.length < (dataFiltro.minLength ?? 3) ? [] : (dataFiltro.queryService.getDataMethod('GET', dataFiltro.tipoReq, {
|
|
435
|
-
...(dataFiltro.dataExtra ?? {}),
|
|
436
|
-
...(dataFiltro.dataExtraVariable ? Object.fromEntries(dataFiltro.dataExtraVariable.map((objData) => [objData.campo, objData.ctrlValue.value])) : {}),
|
|
437
|
-
txtBuscar: value,
|
|
438
|
-
}, dataFiltro.anonimo).pipe(finalize(() => objThis.isLoading = false)));
|
|
439
|
-
})).subscribe((data) => {
|
|
440
|
-
objThis.filtrados[idFiltrado] = data[dataFiltro.tipoReq] ?? [];
|
|
441
|
-
});
|
|
442
|
-
}
|
|
443
|
-
function changeSelectApi(control, queryService, formControl, tipo, dataExtra = {}, dataExtraVariable = null, minLength = 1, anonimo = false) {
|
|
444
|
-
formControl.valueChanges.pipe(debounceTime(500), tap((value) => {
|
|
445
|
-
control['filtrados'][tipo + 'tmp'] = isObservable(control['filtrados'][tipo]) ? [] : control['filtrados'][tipo];
|
|
446
|
-
if (control['filtrados'][tipo] != control['filtrados'][tipo + 'tmp']) {
|
|
447
|
-
control['filtrados'][tipo] = [];
|
|
448
|
-
}
|
|
449
|
-
control['isLoading'] = true;
|
|
450
|
-
}), switchMap(value => {
|
|
451
|
-
const formGroup = formControl.parent?.controls;
|
|
452
|
-
const nombreControl = Object.keys(formGroup).find(name => formControl === formGroup[name]) || null;
|
|
453
|
-
if (nombreControl && control['filtrados'][tipo + 'tmp'] && control['filtrados'][tipo + 'tmp'].length > 0) {
|
|
454
|
-
const busquedaActual = control['filtrados'][tipo + 'tmp'].findIndex((item) => item[nombreControl] == value);
|
|
455
|
-
if (busquedaActual >= 0) {
|
|
456
|
-
const vRet = {};
|
|
457
|
-
vRet[tipo] = control['filtrados'][tipo + 'tmp'];
|
|
458
|
-
control['isLoading'] = false;
|
|
459
|
-
return of(vRet);
|
|
460
|
-
}
|
|
461
|
-
}
|
|
462
|
-
if (!value || value.length < minLength) {
|
|
463
|
-
return [];
|
|
464
|
-
}
|
|
465
|
-
const dataExtraVariableData = {};
|
|
466
|
-
if (dataExtraVariable) {
|
|
467
|
-
// @ts-ignore
|
|
468
|
-
for (const objData of dataExtraVariable) {
|
|
469
|
-
dataExtraVariableData[objData.campo] = objData.ctrlValue.value;
|
|
470
|
-
}
|
|
471
|
-
}
|
|
472
|
-
return queryService.getDataMethod('GET', tipo, { ...dataExtra, ...dataExtraVariableData, ...{ txtBuscar: value } }, anonimo).pipe(finalize(() => {
|
|
473
|
-
control['isLoading'] = false;
|
|
474
|
-
}));
|
|
475
|
-
})).subscribe((data) => {
|
|
476
|
-
if (data[tipo] == undefined) {
|
|
477
|
-
control['filtrados'][tipo] = [];
|
|
478
|
-
}
|
|
479
|
-
else {
|
|
480
|
-
control['filtrados'][tipo] = data[tipo];
|
|
481
|
-
}
|
|
482
|
-
});
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
function seleccionarTextoInput(event) {
|
|
486
|
-
event.target.select();
|
|
487
|
-
}
|
|
488
|
-
|
|
489
|
-
function b64Encode(val) {
|
|
490
|
-
return Buffer.from(val, 'binary').toString('base64');
|
|
491
|
-
}
|
|
492
|
-
function b64Decode(val) {
|
|
493
|
-
return Buffer.from(val, 'base64').toString('binary');
|
|
494
|
-
}
|
|
495
|
-
|
|
496
|
-
function getBrowserName() {
|
|
497
|
-
const agent = window.navigator.userAgent.toLowerCase();
|
|
498
|
-
switch (true) {
|
|
499
|
-
case agent.indexOf('edge') > -1:
|
|
500
|
-
return 'edge';
|
|
501
|
-
case agent.indexOf('opr') > -1 && !!window.opr:
|
|
502
|
-
return 'opera';
|
|
503
|
-
case agent.indexOf('chrome') > -1 && !!window.chrome:
|
|
504
|
-
return 'chrome';
|
|
505
|
-
case agent.indexOf('trident') > -1:
|
|
506
|
-
return 'ie';
|
|
507
|
-
case agent.indexOf('firefox') > -1:
|
|
508
|
-
return 'firefox';
|
|
509
|
-
case agent.indexOf('safari') > -1:
|
|
510
|
-
return 'safari';
|
|
511
|
-
default:
|
|
512
|
-
return 'other';
|
|
513
|
-
}
|
|
514
|
-
}
|
|
515
|
-
|
|
516
|
-
// import * as CryptoJS from 'crypto-js';
|
|
517
|
-
// var CryptoJS = require("crypto-js");
|
|
518
|
-
// Clave secreta (debe ser de 16, 24 o 32 caracteres)
|
|
519
|
-
const secretKey = CryptoJS.enc.Utf8.parse('JVSoftSecret@20615178350');
|
|
520
|
-
const iv = CryptoJS.enc.Utf8.parse('AnSalHuaJVSoft07'); // Debe ser de 16 bytes
|
|
521
|
-
// Función para encriptar texto
|
|
522
|
-
function encriptar(text) {
|
|
523
|
-
const encrypted = CryptoJS.AES.encrypt(text, secretKey, {
|
|
524
|
-
iv: iv,
|
|
525
|
-
mode: CryptoJS.mode.CBC,
|
|
526
|
-
padding: CryptoJS.pad.Pkcs7,
|
|
527
|
-
});
|
|
528
|
-
return encrypted.toString(); // Texto cifrado en Base64
|
|
529
|
-
}
|
|
530
|
-
// Función para desencriptar texto
|
|
531
|
-
function desencriptar(ciphertext) {
|
|
532
|
-
const decrypted = CryptoJS.AES.decrypt(ciphertext, secretKey, {
|
|
533
|
-
iv: iv,
|
|
534
|
-
mode: CryptoJS.mode.CBC,
|
|
535
|
-
padding: CryptoJS.pad.Pkcs7,
|
|
536
|
-
});
|
|
537
|
-
return decrypted.toString(CryptoJS.enc.Utf8);
|
|
538
|
-
}
|
|
539
|
-
|
|
540
|
-
function formatearFechaFormato(val, format = 'dd/MM/yyyy') {
|
|
541
|
-
return val ? formatDate(val, format, 'es-PE') : '';
|
|
542
|
-
}
|
|
543
|
-
function formatearFecha(val, hora = '00:00:00') {
|
|
544
|
-
if (val) {
|
|
545
|
-
if (val.length <= 10) {
|
|
546
|
-
val = val + ' ' + hora;
|
|
547
|
-
}
|
|
548
|
-
return new Date(val);
|
|
549
|
-
}
|
|
550
|
-
return val;
|
|
551
|
-
}
|
|
552
|
-
function formatearFechaCadena(fecha) {
|
|
553
|
-
const year = parseInt(fecha.substring(0, 4), 10);
|
|
554
|
-
const month = parseInt(fecha.substring(4, 6), 10) - 1;
|
|
555
|
-
const day = parseInt(fecha.substring(6, 8), 10);
|
|
556
|
-
return new Date(year, month, day);
|
|
557
|
-
}
|
|
558
|
-
|
|
559
|
-
function maskEmail(email) {
|
|
560
|
-
const [user, domain] = email.split("@");
|
|
561
|
-
if (user.length <= 2) {
|
|
562
|
-
return `${user[0]}***@${domain}`; // 🔹 Si el usuario es muy corto, no se oculta nada
|
|
563
|
-
}
|
|
564
|
-
if (user.length <= 4) {
|
|
565
|
-
return `${user[0]}***${user.slice(-1)}@${domain}`; // 🔹 Muestra 1 al inicio y 1 al final
|
|
566
|
-
}
|
|
567
|
-
return `${user.slice(0, 2)}***${user.slice(-2)}@${domain}`; // 🔹 Muestra 2 al inicio y 2 al final
|
|
568
|
-
}
|
|
569
|
-
function isEmail(email) {
|
|
570
|
-
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
|
|
571
|
-
}
|
|
572
|
-
|
|
573
|
-
const mimeTypes = {
|
|
574
|
-
// Imágenes
|
|
575
|
-
'jpg': 'image/jpeg',
|
|
576
|
-
'jpeg': 'image/jpeg',
|
|
577
|
-
'png': 'image/png',
|
|
578
|
-
'gif': 'image/gif',
|
|
579
|
-
'webp': 'image/webp',
|
|
580
|
-
'svg': 'image/svg+xml',
|
|
581
|
-
'ico': 'image/x-icon',
|
|
582
|
-
'bmp': 'image/bmp',
|
|
583
|
-
// Documentos
|
|
584
|
-
'pdf': 'application/pdf',
|
|
585
|
-
'doc': 'application/msword',
|
|
586
|
-
'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
587
|
-
'xls': 'application/vnd.ms-excel',
|
|
588
|
-
'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
589
|
-
'ppt': 'application/vnd.ms-powerpoint',
|
|
590
|
-
'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
|
591
|
-
'txt': 'text/plain',
|
|
592
|
-
'csv': 'text/csv',
|
|
593
|
-
'json': 'application/json',
|
|
594
|
-
'xml': 'application/xml',
|
|
595
|
-
'html': 'text/html',
|
|
596
|
-
// Audio
|
|
597
|
-
'mp3': 'audio/mpeg',
|
|
598
|
-
'wav': 'audio/wav',
|
|
599
|
-
'ogg': 'audio/ogg',
|
|
600
|
-
'm4a': 'audio/mp4',
|
|
601
|
-
// Video
|
|
602
|
-
'mp4': 'video/mp4',
|
|
603
|
-
'avi': 'video/x-msvideo',
|
|
604
|
-
'mov': 'video/quicktime',
|
|
605
|
-
'wmv': 'video/x-ms-wmv',
|
|
606
|
-
'flv': 'video/x-flv',
|
|
607
|
-
'webm': 'video/webm',
|
|
608
|
-
'mkv': 'video/x-matroska',
|
|
609
|
-
// Archivos comprimidos
|
|
610
|
-
'zip': 'application/zip',
|
|
611
|
-
'rar': 'application/vnd.rar',
|
|
612
|
-
'7z': 'application/x-7z-compressed',
|
|
613
|
-
'tar': 'application/x-tar',
|
|
614
|
-
'gz': 'application/gzip',
|
|
615
|
-
'bz2': 'application/x-bzip2',
|
|
616
|
-
// Otros formatos
|
|
617
|
-
'js': 'application/javascript',
|
|
618
|
-
'css': 'text/css',
|
|
619
|
-
'ts': 'application/typescript',
|
|
620
|
-
'md': 'text/markdown',
|
|
621
|
-
'exe': 'application/octet-stream',
|
|
622
|
-
'eot': 'application/vnd.ms-fontobject',
|
|
623
|
-
'woff': 'font/woff',
|
|
624
|
-
'woff2': 'font/woff2',
|
|
625
|
-
'ttf': 'font/ttf',
|
|
626
|
-
'otf': 'font/otf',
|
|
627
|
-
};
|
|
628
|
-
function obtenerMimeType(nombreArchivo) {
|
|
629
|
-
const extension = nombreArchivo.split('.').pop()?.toLowerCase();
|
|
630
|
-
return extension ? mimeTypes[extension] || 'application/octet-stream' : null;
|
|
631
|
-
}
|
|
632
|
-
function sanitizarNombreArchivo(nombre, reemplazo = '_') {
|
|
633
|
-
// 1. Quitar caracteres no válidos para nombres de archivo
|
|
634
|
-
const nombreSanitizado = nombre.replace(/[\/\\:*?"<>|]/g, reemplazo);
|
|
635
|
-
// 2. Reemplazar espacios múltiples o al inicio/final
|
|
636
|
-
const nombreLimpio = nombreSanitizado.trim().replace(/\s+/g, reemplazo);
|
|
637
|
-
// 3. Asegurar longitud máxima (opcional, aquí 255 caracteres)
|
|
638
|
-
return nombreLimpio.substring(0, 255);
|
|
639
|
-
}
|
|
640
|
-
function getDataArchivoFromPath(value, conTimeStamp = false) {
|
|
641
|
-
const partesPath = value.split('/');
|
|
642
|
-
const nombreCompleto = partesPath[partesPath.length - 1];
|
|
643
|
-
let timeStamp = 1;
|
|
644
|
-
let nombreSinTimeStamp = nombreCompleto;
|
|
645
|
-
const partesNombre = nombreCompleto.split('-');
|
|
646
|
-
if (partesNombre.length > 1) {
|
|
647
|
-
timeStamp = partesNombre[0] * 1;
|
|
648
|
-
partesNombre.shift();
|
|
649
|
-
nombreSinTimeStamp = partesNombre.join('-');
|
|
650
|
-
}
|
|
651
|
-
if (conTimeStamp) {
|
|
652
|
-
return {
|
|
653
|
-
nombre: nombreCompleto,
|
|
654
|
-
extension: nombreCompleto.split('.').pop(),
|
|
655
|
-
d: timeStamp,
|
|
656
|
-
fechaSubida: timeStamp ? new Date(timeStamp * 1000) : '',
|
|
657
|
-
};
|
|
658
|
-
}
|
|
659
|
-
return {
|
|
660
|
-
nombre: nombreSinTimeStamp,
|
|
661
|
-
extension: nombreSinTimeStamp.split('.').pop(),
|
|
662
|
-
d: timeStamp,
|
|
663
|
-
fechaSubida: timeStamp ? new Date(timeStamp * 1000) : '',
|
|
664
|
-
};
|
|
665
|
-
}
|
|
666
|
-
function convertirBytes(valor, unidadSalida = null, incluirUnidad = true) {
|
|
667
|
-
const unidades = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
|
|
668
|
-
const indiceEntrada = unidadSalida ? unidades.indexOf(unidadSalida) : 0;
|
|
669
|
-
if (indiceEntrada === -1) {
|
|
670
|
-
// Unidad de entrada no válida
|
|
671
|
-
return null;
|
|
672
|
-
}
|
|
673
|
-
let indiceActual = indiceEntrada;
|
|
674
|
-
let resultado = valor;
|
|
675
|
-
let cont = 0;
|
|
676
|
-
while (cont < 6 && (indiceActual < unidades.length - 1) && (resultado >= 1024)) {
|
|
677
|
-
resultado /= 1024;
|
|
678
|
-
indiceActual++;
|
|
679
|
-
}
|
|
680
|
-
if (incluirUnidad) {
|
|
681
|
-
return `${resultado.toFixed(2)} ${unidades[indiceActual]}`;
|
|
682
|
-
}
|
|
683
|
-
return resultado;
|
|
684
|
-
}
|
|
685
|
-
function downLoadFileStream(data, type, nombreArchivo) {
|
|
686
|
-
const blob = new Blob([data], { type });
|
|
687
|
-
saveAs(blob, nombreArchivo);
|
|
688
|
-
}
|
|
689
|
-
|
|
690
|
-
function establecerQuitarRequired(formulario, establecer = [], quitar = [], camposDisabled = []) {
|
|
691
|
-
establecer.forEach((control) => {
|
|
692
|
-
if (!formulario.get(control)?.hasValidator(Validators.required)) {
|
|
693
|
-
formulario.get(control)?.addValidators([Validators.required]);
|
|
694
|
-
formulario.get(control)?.enable();
|
|
695
|
-
formulario.get(control)?.updateValueAndValidity();
|
|
696
|
-
}
|
|
697
|
-
});
|
|
698
|
-
const deshabilitar = (strControl) => {
|
|
699
|
-
if (camposDisabled == 'todos') {
|
|
700
|
-
formulario.get(strControl)?.disable();
|
|
701
|
-
console.log(strControl);
|
|
702
|
-
}
|
|
703
|
-
else {
|
|
704
|
-
if (camposDisabled.includes(strControl)) {
|
|
705
|
-
formulario.get(strControl)?.disable();
|
|
706
|
-
}
|
|
707
|
-
}
|
|
708
|
-
};
|
|
709
|
-
quitar.forEach(control => {
|
|
710
|
-
if (formulario.get(control)?.hasValidator(Validators.required)) {
|
|
711
|
-
formulario.get(control)?.removeValidators([Validators.required]);
|
|
712
|
-
formulario.get(control)?.updateValueAndValidity();
|
|
713
|
-
}
|
|
714
|
-
deshabilitar(control);
|
|
715
|
-
});
|
|
716
|
-
}
|
|
717
|
-
function getFormValidationErrors(form) {
|
|
718
|
-
const result = [];
|
|
719
|
-
Object.keys(form.controls).forEach(key => {
|
|
720
|
-
const formProperty = form.get(key);
|
|
721
|
-
if (formProperty instanceof FormGroup) {
|
|
722
|
-
result.push(...getFormValidationErrors(formProperty));
|
|
723
|
-
}
|
|
724
|
-
const controlErrors = formProperty?.errors;
|
|
725
|
-
if (controlErrors) {
|
|
726
|
-
Object.keys(controlErrors).forEach(keyError => {
|
|
727
|
-
result.push({
|
|
728
|
-
control: key,
|
|
729
|
-
error: keyError,
|
|
730
|
-
value: controlErrors[keyError]
|
|
731
|
-
});
|
|
732
|
-
});
|
|
733
|
-
}
|
|
734
|
-
});
|
|
735
|
-
return result;
|
|
736
|
-
}
|
|
737
|
-
function mensajesErrorFormControl(control) {
|
|
738
|
-
if (!control || !control.errors || !control.touched)
|
|
739
|
-
return '';
|
|
740
|
-
ReactiveFormConfig.set({
|
|
741
|
-
// RxwebValidators
|
|
742
|
-
validationMessage: {
|
|
743
|
-
required: 'Es requerido',
|
|
744
|
-
numeric: 'Debe ser numérico valido',
|
|
745
|
-
// minLength: 'minimum length is {{1}}',
|
|
746
|
-
// maxLength: 'allowed max length is {{1}}',
|
|
747
|
-
},
|
|
748
|
-
});
|
|
749
|
-
const errorMessages = {
|
|
750
|
-
required: 'Es requerido',
|
|
751
|
-
numeric: 'Debe ser numérico válido',
|
|
752
|
-
min: `Valor mínimo permitido: ${control.errors['min']?.min}`,
|
|
753
|
-
minValue: 'Debe ser positivo',
|
|
754
|
-
minlength: `Mínimo ${control.errors['minlength']?.requiredLength} caracteres.`,
|
|
755
|
-
maxlength: `Caracteres ${control.errors['maxlength']?.actualLength}/${control.errors['maxlength']?.requiredLength}`,
|
|
756
|
-
email: 'No se cumple con el formato de Correo Electrónico',
|
|
757
|
-
isNumeric: 'Debe seleccionar una opción',
|
|
758
|
-
hasNumber: 'Se requiere al menos un número',
|
|
759
|
-
hasCapitalCase: 'Se requiere al menos una mayúscula',
|
|
760
|
-
hasSmallCase: 'Se requiere al menos una minúscula',
|
|
761
|
-
hasSpecialCharacters: 'Se requiere al menos un carácter especial',
|
|
762
|
-
NoPassswordMatch: 'La contraseña no coincide',
|
|
763
|
-
itemSelected: 'Debe seleccionar una opción de la lista',
|
|
764
|
-
inputMask: 'El formato ingresado no es válido',
|
|
765
|
-
};
|
|
766
|
-
// Devuelve el primer mensaje de error encontrado
|
|
767
|
-
for (const errorKey of Object.keys(control.errors)) {
|
|
768
|
-
if (errorMessages[errorKey]) {
|
|
769
|
-
return errorMessages[errorKey];
|
|
770
|
-
}
|
|
771
|
-
}
|
|
772
|
-
// Si el error tiene un mensaje personalizado, usarlo
|
|
773
|
-
return control.errors[Object.keys(control.errors)[0]]?.message || '';
|
|
774
|
-
}
|
|
775
|
-
function toFormData(formValue) {
|
|
776
|
-
const formData = new FormData();
|
|
777
|
-
Object.keys(formValue).forEach((key) => {
|
|
778
|
-
const value = formValue[key];
|
|
779
|
-
if (value === null || value === undefined) {
|
|
780
|
-
return; // Ignorar valores nulos o indefinidos
|
|
781
|
-
}
|
|
782
|
-
if (Array.isArray(value)) {
|
|
783
|
-
value.forEach((item, index) => {
|
|
784
|
-
if (typeof item === 'object' && item !== null) {
|
|
785
|
-
if ('file' in item) {
|
|
786
|
-
formData.append(`${key}[${index}]`, item.file);
|
|
787
|
-
}
|
|
788
|
-
else {
|
|
789
|
-
formData.append(`${key}[${index}]`, JSON.stringify(item));
|
|
790
|
-
}
|
|
791
|
-
}
|
|
792
|
-
else {
|
|
793
|
-
formData.append(`${key}[${index}]`, item.toString());
|
|
794
|
-
}
|
|
795
|
-
});
|
|
796
|
-
}
|
|
797
|
-
else if (typeof value === 'object') {
|
|
798
|
-
// Si es un objeto (pero no un array), convertirlo a JSON
|
|
799
|
-
formData.append(key, JSON.stringify(value));
|
|
800
|
-
}
|
|
801
|
-
else {
|
|
802
|
-
// Para valores primitivos (string, number, boolean)
|
|
803
|
-
formData.append(key, value.toString());
|
|
804
|
-
}
|
|
805
|
-
});
|
|
806
|
-
return formData;
|
|
807
|
-
}
|
|
808
|
-
function markAsTouchedWithoutEmitEvent(control) {
|
|
809
|
-
if (control instanceof FormControl) {
|
|
810
|
-
control.markAsTouched({ onlySelf: true });
|
|
811
|
-
control.updateValueAndValidity({ emitEvent: false });
|
|
812
|
-
}
|
|
813
|
-
else if (control instanceof FormGroup || control instanceof FormArray) {
|
|
814
|
-
Object.values(control.controls).forEach(childControl => {
|
|
815
|
-
markAsTouchedWithoutEmitEvent(childControl);
|
|
816
|
-
});
|
|
817
|
-
control.updateValueAndValidity({ emitEvent: false });
|
|
818
|
-
}
|
|
819
|
-
}
|
|
820
|
-
function setControlDesdeLista(config) {
|
|
821
|
-
const lista = config.lista$?.getValue() ?? [];
|
|
822
|
-
if (!lista.length)
|
|
823
|
-
return;
|
|
824
|
-
let seleccionado;
|
|
825
|
-
if (config.idProp && config.idValor !== undefined) {
|
|
826
|
-
seleccionado = lista.find((item) => item[config.idProp] === config.idValor);
|
|
827
|
-
}
|
|
828
|
-
else if (config.usarPrimeraOpcion) {
|
|
829
|
-
seleccionado = lista[0];
|
|
830
|
-
}
|
|
831
|
-
console.log(seleccionado);
|
|
832
|
-
if (!seleccionado)
|
|
833
|
-
return;
|
|
834
|
-
let valor;
|
|
835
|
-
if (config.selector) {
|
|
836
|
-
valor = config.selector(seleccionado);
|
|
837
|
-
}
|
|
838
|
-
else if (config.idProp) {
|
|
839
|
-
valor = seleccionado[config.idProp];
|
|
840
|
-
}
|
|
841
|
-
else {
|
|
842
|
-
valor = seleccionado;
|
|
843
|
-
}
|
|
844
|
-
if (config.formControl) {
|
|
845
|
-
config.formControl.setValue(valor);
|
|
846
|
-
}
|
|
847
|
-
else if (config.formGroup && config.controlName) {
|
|
848
|
-
const control = config.formGroup.get(config.controlName);
|
|
849
|
-
if (control instanceof FormControl) {
|
|
850
|
-
control.setValue(valor);
|
|
851
|
-
}
|
|
852
|
-
}
|
|
853
|
-
}
|
|
854
|
-
function transformarFechasPorNombreDeCampo(formValue) {
|
|
855
|
-
const retData = {};
|
|
856
|
-
Object.entries(formValue).forEach(([key, value]) => {
|
|
857
|
-
// ✅ No procesar Blob o File
|
|
858
|
-
if (value instanceof Blob || value instanceof File) {
|
|
859
|
-
retData[key] = value;
|
|
860
|
-
return;
|
|
861
|
-
}
|
|
862
|
-
if (value instanceof Date) {
|
|
863
|
-
if (/^d[A-Za-z]+/.test(key)) {
|
|
864
|
-
retData[key] = moment(value).format('YYYY-MM-DD');
|
|
865
|
-
}
|
|
866
|
-
else {
|
|
867
|
-
retData[key] = new Date(Date.UTC(value.getFullYear(), value.getMonth(), value.getDate(), value.getHours(), value.getMinutes(), value.getSeconds()));
|
|
868
|
-
}
|
|
869
|
-
}
|
|
870
|
-
else if (/^dt[A-Za-z]+/.test(key) && typeof value === 'string') {
|
|
871
|
-
if (/\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}\.\d{3}/.test(value)) {
|
|
872
|
-
retData[key] = new Date(value + 'Z');
|
|
873
|
-
}
|
|
874
|
-
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)) {
|
|
875
|
-
retData[key] = new Date(value + ':00.000Z');
|
|
876
|
-
}
|
|
877
|
-
else {
|
|
878
|
-
console.warn('FECHA INVALIDA AL ENVIAR (FormInter):', key, value);
|
|
879
|
-
retData[key] = value;
|
|
880
|
-
}
|
|
881
|
-
}
|
|
882
|
-
else if (Array.isArray(value)) {
|
|
883
|
-
if (value.every(v => v instanceof File || v instanceof Blob)) {
|
|
884
|
-
retData[key] = value;
|
|
885
|
-
}
|
|
886
|
-
else {
|
|
887
|
-
retData[key] = value.map(item => typeof item === 'object' && item !== null
|
|
888
|
-
? transformarFechasPorNombreDeCampo(item)
|
|
889
|
-
: item);
|
|
890
|
-
}
|
|
891
|
-
}
|
|
892
|
-
else if (typeof value === 'object' && value !== null) {
|
|
893
|
-
retData[key] = transformarFechasPorNombreDeCampo(value);
|
|
894
|
-
}
|
|
895
|
-
else {
|
|
896
|
-
retData[key] = value;
|
|
897
|
-
}
|
|
898
|
-
});
|
|
899
|
-
return retData;
|
|
900
|
-
}
|
|
901
|
-
|
|
902
|
-
function mensajeAlerta(tipo, titulo, mensaje, opciones) {
|
|
903
|
-
opciones = {
|
|
904
|
-
...{
|
|
905
|
-
heightAuto: false,
|
|
906
|
-
title: titulo,
|
|
907
|
-
html: mensaje,
|
|
908
|
-
icon: tipo,
|
|
909
|
-
confirmButtonText: 'Aceptar',
|
|
910
|
-
// customClass: {
|
|
911
|
-
// confirmButton: 'btn btn-lg btn-outline-success mx-2',
|
|
912
|
-
// cancelButton: 'btn btn-lg btn-outline-dark mx-2'
|
|
913
|
-
// },
|
|
914
|
-
// buttonsStyling: false
|
|
915
|
-
},
|
|
916
|
-
...opciones
|
|
917
|
-
};
|
|
918
|
-
return swal.fire(opciones);
|
|
919
|
-
}
|
|
920
|
-
function mensajeTimer(tipo, titulo, mensaje, milisegundos = 3000, showLoading = true, opciones) {
|
|
921
|
-
let timerInterval;
|
|
922
|
-
opciones = {
|
|
923
|
-
...{
|
|
924
|
-
heightAuto: false,
|
|
925
|
-
title: titulo,
|
|
926
|
-
html: mensaje + '<br> Se cerrará en <strong> X </strong> segundos.',
|
|
927
|
-
icon: tipo,
|
|
928
|
-
timer: milisegundos,
|
|
929
|
-
showCancelButton: false,
|
|
930
|
-
showConfirmButton: false,
|
|
931
|
-
willOpen: () => {
|
|
932
|
-
if (showLoading) {
|
|
933
|
-
swal.showLoading();
|
|
934
|
-
}
|
|
935
|
-
timerInterval = setInterval(() => {
|
|
936
|
-
const impr = Math.ceil(((swal.getTimerLeft() ?? 1) / 1000));
|
|
937
|
-
if (swal.getHtmlContainer()) {
|
|
938
|
-
// @ts-ignore
|
|
939
|
-
swal.getHtmlContainer().querySelector('strong').textContent = String(impr);
|
|
940
|
-
}
|
|
941
|
-
}, 100);
|
|
942
|
-
},
|
|
943
|
-
willClose: () => {
|
|
944
|
-
clearInterval(timerInterval);
|
|
945
|
-
}
|
|
946
|
-
},
|
|
947
|
-
...opciones
|
|
948
|
-
};
|
|
949
|
-
return swal.fire(opciones);
|
|
950
|
-
}
|
|
951
|
-
// @ts-ignore
|
|
952
|
-
function mensajeConfirmacion(tipo, titulo, mensaje, opciones) {
|
|
953
|
-
opciones = {
|
|
954
|
-
...{
|
|
955
|
-
heightAuto: false,
|
|
956
|
-
title: titulo,
|
|
957
|
-
html: mensaje,
|
|
958
|
-
icon: tipo,
|
|
959
|
-
showCancelButton: true,
|
|
960
|
-
// confirmButtonColor: '#3f51b5',
|
|
961
|
-
// cancelButtonColor: '#ffffff',
|
|
962
|
-
confirmButtonText: 'Confirmar',
|
|
963
|
-
cancelButtonText: 'Cancelar',
|
|
964
|
-
reverseButtons: true,
|
|
965
|
-
// customClass: {
|
|
966
|
-
// confirmButton: 'btn btn-lg btn-outline-success mx-2',
|
|
967
|
-
// cancelButton: 'btn btn-lg btn-outline-dark mx-2'
|
|
968
|
-
// },
|
|
969
|
-
// buttonsStyling: false
|
|
970
|
-
},
|
|
971
|
-
...opciones
|
|
972
|
-
};
|
|
973
|
-
return swal.fire(opciones);
|
|
974
|
-
}
|
|
975
|
-
function mensajeToast(tipo, titulo, mensaje, opciones) {
|
|
976
|
-
opciones = {
|
|
977
|
-
...{
|
|
978
|
-
heightAuto: false,
|
|
979
|
-
title: titulo,
|
|
980
|
-
html: mensaje,
|
|
981
|
-
icon: tipo,
|
|
982
|
-
confirmButtonText: 'Aceptar',
|
|
983
|
-
toast: true,
|
|
984
|
-
position: 'top-end',
|
|
985
|
-
showConfirmButton: false,
|
|
986
|
-
timer: 3000,
|
|
987
|
-
timerProgressBar: true,
|
|
988
|
-
},
|
|
989
|
-
...opciones
|
|
990
|
-
};
|
|
991
|
-
return swal.fire(opciones);
|
|
992
|
-
}
|
|
993
|
-
|
|
994
|
-
function mensajesDeError(error, toast = false) {
|
|
995
|
-
let msg;
|
|
996
|
-
if (error.error && error.error instanceof ArrayBuffer) {
|
|
997
|
-
const msgArrayBuffer = (arrayBuffer) => {
|
|
998
|
-
try {
|
|
999
|
-
const mensajeError = JSON.parse(new TextDecoder("utf-8").decode(arrayBuffer));
|
|
1000
|
-
return mensajeError.message || 'Error desconocido';
|
|
1001
|
-
}
|
|
1002
|
-
catch (parseError) {
|
|
1003
|
-
console.error('Error al analizar la respuesta JSON:', parseError);
|
|
1004
|
-
return 'Error al analizar la respuesta JSON';
|
|
1005
|
-
}
|
|
1006
|
-
};
|
|
1007
|
-
msg = msgArrayBuffer(error.error);
|
|
1008
|
-
}
|
|
1009
|
-
else {
|
|
1010
|
-
switch (error.status) {
|
|
1011
|
-
case 0:
|
|
1012
|
-
// msg = error.message;
|
|
1013
|
-
msg = 'El servidor no responde, verifica tu conexion a la red';
|
|
1014
|
-
console.log(error);
|
|
1015
|
-
break;
|
|
1016
|
-
case 401:
|
|
1017
|
-
if (error.error && typeof error.error == 'object') {
|
|
1018
|
-
if (error.error.message) {
|
|
1019
|
-
msg = error.error.message;
|
|
1020
|
-
}
|
|
1021
|
-
else if (error.error.error) {
|
|
1022
|
-
msg = error.error.error;
|
|
1023
|
-
}
|
|
1024
|
-
else {
|
|
1025
|
-
msg = JSON.stringify(error.error);
|
|
1026
|
-
console.log(error);
|
|
1027
|
-
}
|
|
1028
|
-
}
|
|
1029
|
-
else if (error.error && typeof error.error == 'string') {
|
|
1030
|
-
msg = error.error;
|
|
1031
|
-
}
|
|
1032
|
-
else {
|
|
1033
|
-
msg = 'Acceso no autorizado';
|
|
1034
|
-
console.log(error);
|
|
1035
|
-
}
|
|
1036
|
-
break;
|
|
1037
|
-
case 422:
|
|
1038
|
-
let strEr = '';
|
|
1039
|
-
console.log(typeof error.error.errors);
|
|
1040
|
-
console.log(error.error.errors);
|
|
1041
|
-
if (error.error.errors) {
|
|
1042
|
-
Object.keys(error.error.errors).forEach(o => {
|
|
1043
|
-
strEr += '<li>' + error.error.errors[o][0] + '</li>';
|
|
1044
|
-
});
|
|
1045
|
-
msg = (error.error.message ?? '') + '<ul>' + strEr + '</ul>';
|
|
1046
|
-
}
|
|
1047
|
-
else if (error.error.error) {
|
|
1048
|
-
msg = error.error.msg;
|
|
1049
|
-
}
|
|
1050
|
-
break;
|
|
1051
|
-
case 429:
|
|
1052
|
-
case 400:
|
|
1053
|
-
case 500:
|
|
1054
|
-
case 503:
|
|
1055
|
-
msg = error.error.message;
|
|
1056
|
-
break;
|
|
1057
|
-
case 504:
|
|
1058
|
-
msg = 'No se puede conectar al servidor. Comprueba tu conexion a la red - ' + error.statusText;
|
|
1059
|
-
break;
|
|
1060
|
-
default:
|
|
1061
|
-
msg = error?.error?.message ?? 'Error de Sistema';
|
|
1062
|
-
console.log(error);
|
|
1063
|
-
break;
|
|
1064
|
-
}
|
|
1065
|
-
}
|
|
1066
|
-
if (!msg) {
|
|
1067
|
-
msg = error.statusText ?? 'Error inesperado o datos inexistentes.';
|
|
1068
|
-
}
|
|
1069
|
-
let tituloFinal = 'Error!';
|
|
1070
|
-
let mensajeFinal;
|
|
1071
|
-
if (msg.includes('Hmac::doVerify')) {
|
|
1072
|
-
console.log(error, msg);
|
|
1073
|
-
return;
|
|
1074
|
-
}
|
|
1075
|
-
else if (msg == 'Server Error') {
|
|
1076
|
-
console.log(error, msg);
|
|
1077
|
-
return;
|
|
1078
|
-
}
|
|
1079
|
-
else if (msg.includes('[IMSSP]')) {
|
|
1080
|
-
mensajeFinal = 'Error en consulta de registros.';
|
|
1081
|
-
}
|
|
1082
|
-
else if (msg.includes('Tiempo de espera de la')) {
|
|
1083
|
-
mensajeFinal = 'Hubo un error en la solicitud de datos, por favor actualice (SHIFT + F5)';
|
|
1084
|
-
}
|
|
1085
|
-
else {
|
|
1086
|
-
mensajeFinal = msg;
|
|
1087
|
-
}
|
|
1088
|
-
if (toast) {
|
|
1089
|
-
mensajeToast('error', tituloFinal, mensajeFinal);
|
|
1090
|
-
}
|
|
1091
|
-
else {
|
|
1092
|
-
mensajeAlerta('error', tituloFinal, mensajeFinal);
|
|
1093
|
-
}
|
|
1094
|
-
throw new Error(mensajeFinal);
|
|
1095
|
-
}
|
|
1096
|
-
|
|
1097
|
-
let dataSessionStorageKey = {
|
|
1098
|
-
tokenStringKey: 'JVSoftTkn',
|
|
1099
|
-
changePasswordKey: 'chPwd',
|
|
1100
|
-
logoUrl: 'logo_url',
|
|
1101
|
-
logoLogin: 'login-logo',
|
|
1102
|
-
backgroundLogin: 'login-background',
|
|
1103
|
-
favicon: 'favicon',
|
|
1104
|
-
darkMode: 'darkMode',
|
|
1105
|
-
serverTimestamp: 'srvtmstp',
|
|
1106
|
-
apiDataKey: 'reqDt',
|
|
1107
|
-
};
|
|
1108
|
-
let localStorageKeys = dataSessionStorageKey;
|
|
1109
|
-
function inicializarVariablesSessionStorage(datSesion) {
|
|
1110
|
-
dataSessionStorageKey = datSesion;
|
|
1111
|
-
}
|
|
1112
|
-
function setJwtTokenData(data) {
|
|
1113
|
-
localStorage.setItem(dataSessionStorageKey.tokenStringKey, data);
|
|
1114
|
-
}
|
|
1115
|
-
function jwtTokenData(key = dataSessionStorageKey.tokenStringKey) {
|
|
1116
|
-
const tokenObj = localStorage.getItem(key);
|
|
1117
|
-
try {
|
|
1118
|
-
return JSON.parse(tokenObj);
|
|
1119
|
-
}
|
|
1120
|
-
catch (error) {
|
|
1121
|
-
return null;
|
|
1122
|
-
}
|
|
1123
|
-
}
|
|
1124
|
-
function jwtToken(key = dataSessionStorageKey.tokenStringKey) {
|
|
1125
|
-
const varJwtTokenData = jwtTokenData(key);
|
|
1126
|
-
if (varJwtTokenData) {
|
|
1127
|
-
return varJwtTokenData.access_token;
|
|
1128
|
-
}
|
|
1129
|
-
return '';
|
|
1130
|
-
}
|
|
1131
|
-
function jwtTokenExpiracion(key = dataSessionStorageKey.tokenStringKey) {
|
|
1132
|
-
const jwtStr = jwtToken(key);
|
|
1133
|
-
if (!jwtStr)
|
|
1134
|
-
return null;
|
|
1135
|
-
try {
|
|
1136
|
-
const decodedToken = jwtDecode(jwtStr);
|
|
1137
|
-
return decodedToken.exp ? decodedToken.exp * 1000 : null; // Convertir a milisegundos
|
|
1138
|
-
}
|
|
1139
|
-
catch (e) {
|
|
1140
|
-
return null;
|
|
1141
|
-
}
|
|
1142
|
-
}
|
|
1143
|
-
function jwtTokenExpiracionFaltante() {
|
|
1144
|
-
return Math.abs(moment().diff(jwtTokenExpiracion(), 'seconds'));
|
|
1145
|
-
}
|
|
1146
|
-
function setCambiarPwd(accion = true) {
|
|
1147
|
-
localStorage.setItem(dataSessionStorageKey.changePasswordKey, (accion ? 1 : 0).toString());
|
|
1148
|
-
}
|
|
1149
|
-
function getCambiarPwd() {
|
|
1150
|
-
const frmCambioPwd = localStorage.getItem(dataSessionStorageKey.changePasswordKey);
|
|
1151
|
-
if (!frmCambioPwd) {
|
|
1152
|
-
return null;
|
|
1153
|
-
}
|
|
1154
|
-
return frmCambioPwd == '1';
|
|
1155
|
-
}
|
|
1156
|
-
function delLocalStorage(keyElim = [
|
|
1157
|
-
dataSessionStorageKey.tokenStringKey,
|
|
1158
|
-
dataSessionStorageKey.changePasswordKey,
|
|
1159
|
-
dataSessionStorageKey.apiDataKey,
|
|
1160
|
-
]) {
|
|
1161
|
-
keyElim.forEach(key => {
|
|
1162
|
-
localStorage.removeItem(key);
|
|
1163
|
-
});
|
|
1164
|
-
}
|
|
1165
|
-
function getLocalStorage(key) {
|
|
1166
|
-
return localStorage.getItem(key);
|
|
1167
|
-
}
|
|
1168
|
-
function setLocalStorage(key, value = '') {
|
|
1169
|
-
localStorage.setItem(key, value.toString());
|
|
1170
|
-
}
|
|
1171
|
-
|
|
1172
|
-
function roundToDecimal(number, decimal) {
|
|
1173
|
-
return parseFloat(number.toFixed(decimal));
|
|
1174
|
-
}
|
|
1175
|
-
function numberToWords(num) {
|
|
1176
|
-
if (num === 0)
|
|
1177
|
-
return 'cero';
|
|
1178
|
-
if (num < 0)
|
|
1179
|
-
return 'menos ' + numberToWords(Math.abs(num));
|
|
1180
|
-
if (num > 999999999999)
|
|
1181
|
-
return 'número demasiado grande';
|
|
1182
|
-
const ones = ['', 'un', 'dos', 'tres', 'cuatro', 'cinco', 'seis', 'siete', 'ocho', 'nueve'];
|
|
1183
|
-
const onesFinal = ['', 'uno', 'dos', 'tres', 'cuatro', 'cinco', 'seis', 'siete', 'ocho', 'nueve'];
|
|
1184
|
-
const tens = ['', 'diez', 'veinte', 'treinta', 'cuarenta', 'cincuenta', 'sesenta', 'setenta', 'ochenta', 'noventa'];
|
|
1185
|
-
const teens = ['diez', 'once', 'doce', 'trece', 'catorce', 'quince', 'dieciséis', 'diecisiete', 'dieciocho', 'diecinueve'];
|
|
1186
|
-
const hundreds = ['', 'ciento', 'doscientos', 'trescientos', 'cuatrocientos', 'quinientos', 'seiscientos', 'setecientos', 'ochocientos', 'novecientos'];
|
|
1187
|
-
// Función auxiliar para "un"/"uno"
|
|
1188
|
-
const getOneForm = (n, isFinal) => n === 1 ? (isFinal ? 'uno' : 'un') : onesFinal[n];
|
|
1189
|
-
let words = '';
|
|
1190
|
-
// Miles de millones (ahora sí se ejecuta)
|
|
1191
|
-
if (num >= 1000000000) {
|
|
1192
|
-
const billions = Math.floor(num / 1000000000);
|
|
1193
|
-
words += (billions === 1 ? 'mil' : numberToWords(billions) + ' mil') + ' millones ';
|
|
1194
|
-
num %= 1000000000;
|
|
1195
|
-
}
|
|
1196
|
-
// Millones
|
|
1197
|
-
if (num >= 1000000) {
|
|
1198
|
-
const millions = Math.floor(num / 1000000);
|
|
1199
|
-
words += millions === 1 ? 'un millón ' : numberToWords(millions) + ' millones ';
|
|
1200
|
-
num %= 1000000;
|
|
1201
|
-
}
|
|
1202
|
-
// Miles
|
|
1203
|
-
if (num >= 1000) {
|
|
1204
|
-
const thousands = Math.floor(num / 1000);
|
|
1205
|
-
words += thousands === 1 ? 'mil ' : numberToWords(thousands) + ' mil ';
|
|
1206
|
-
num %= 1000;
|
|
1207
|
-
}
|
|
1208
|
-
// Centenas (con tratamiento especial para "ciento uno")
|
|
1209
|
-
if (num >= 100) {
|
|
1210
|
-
if (num === 100) {
|
|
1211
|
-
words += 'cien';
|
|
1212
|
-
num = 0;
|
|
1213
|
-
}
|
|
1214
|
-
else {
|
|
1215
|
-
words += hundreds[Math.floor(num / 100)];
|
|
1216
|
-
num %= 100;
|
|
1217
|
-
if (num > 0) {
|
|
1218
|
-
words += ' ' + getOneForm(num, true); // Siempre "uno" después de ciento
|
|
1219
|
-
num = 0;
|
|
1220
|
-
}
|
|
1221
|
-
}
|
|
1222
|
-
}
|
|
1223
|
-
// Decenas y unidades
|
|
1224
|
-
if (num > 0) {
|
|
1225
|
-
const isFinalWord = words === '';
|
|
1226
|
-
if (num < 10) {
|
|
1227
|
-
words += getOneForm(num, isFinalWord);
|
|
1228
|
-
}
|
|
1229
|
-
else if (num < 20) {
|
|
1230
|
-
words += teens[num - 10];
|
|
1231
|
-
}
|
|
1232
|
-
else if (num < 30) {
|
|
1233
|
-
if (num === 21)
|
|
1234
|
-
words += 'veintiuno';
|
|
1235
|
-
else if (num === 22)
|
|
1236
|
-
words += 'veintidós';
|
|
1237
|
-
else if (num === 23)
|
|
1238
|
-
words += 'veintitrés';
|
|
1239
|
-
else if (num === 26)
|
|
1240
|
-
words += 'veintiséis';
|
|
1241
|
-
else
|
|
1242
|
-
words += `veinti${onesFinal[num % 10]}`;
|
|
1243
|
-
}
|
|
1244
|
-
else {
|
|
1245
|
-
words += tens[Math.floor(num / 10)];
|
|
1246
|
-
if (num % 10 > 0) {
|
|
1247
|
-
words += ' y ' + getOneForm(num % 10, isFinalWord);
|
|
1248
|
-
}
|
|
1249
|
-
}
|
|
1250
|
-
}
|
|
1251
|
-
return words.trim().replace(/\s+/g, ' ');
|
|
1252
|
-
}
|
|
1253
|
-
|
|
1254
|
-
function objectPropertiesToType(formFields) {
|
|
1255
|
-
Object.keys(formFields).filter(control => !!formFields[control]).forEach(control => {
|
|
1256
|
-
if (/^dt[a-zA-Z]+/.test(control)) {
|
|
1257
|
-
formFields[control] = formatDate(formFields[control], 'yyyy-MM-dd HH:mm', 'es-PE');
|
|
1258
|
-
}
|
|
1259
|
-
else if (control.startsWith('d')) {
|
|
1260
|
-
formFields[control] = formatearFecha(formFields[control]);
|
|
1261
|
-
}
|
|
1262
|
-
else if (control.startsWith('n')) {
|
|
1263
|
-
formFields[control] = Number(formFields[control]);
|
|
1264
|
-
}
|
|
1265
|
-
});
|
|
1266
|
-
return formFields;
|
|
1267
|
-
}
|
|
1268
|
-
function objectPropertiesBoolean(formFields, retorno = 'boolean') {
|
|
1269
|
-
Object.keys(formFields).forEach(control => {
|
|
1270
|
-
const valRetorno = (ctrl) => {
|
|
1271
|
-
switch (retorno) {
|
|
1272
|
-
case 'boolean':
|
|
1273
|
-
formFields[ctrl] = formFields[ctrl] == 1;
|
|
1274
|
-
break;
|
|
1275
|
-
case 'bit':
|
|
1276
|
-
formFields[ctrl] = formFields[ctrl] ? 1 : 0;
|
|
1277
|
-
break;
|
|
1278
|
-
}
|
|
1279
|
-
};
|
|
1280
|
-
if (control.charAt(0) == 'b' || (control.charAt(0) == 'i' && control.indexOf('Estado') !== -1)) {
|
|
1281
|
-
valRetorno(control);
|
|
1282
|
-
}
|
|
1283
|
-
});
|
|
1284
|
-
return formFields;
|
|
1285
|
-
}
|
|
1286
|
-
|
|
1287
|
-
function generateRandomString(length) {
|
|
1288
|
-
let result = '';
|
|
1289
|
-
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
|
1290
|
-
const charactersLength = characters.length;
|
|
1291
|
-
for (let i = 0; i < length; i++) {
|
|
1292
|
-
result += characters.charAt(Math.floor(Math.random() * charactersLength));
|
|
1293
|
-
}
|
|
1294
|
-
return result;
|
|
1295
|
-
}
|
|
1296
|
-
/**
|
|
1297
|
-
* Obtiene el host (hostname) de una URL o cadena host[:port].
|
|
1298
|
-
* Opcionalmente puede devolver también el puerto si está presente.
|
|
1299
|
-
*
|
|
1300
|
-
* - Acepta inputs como:
|
|
1301
|
-
* 'https://example.com/path', 'example.com:3000', 'localhost', 'http://[::1]:4200'
|
|
1302
|
-
* - Usa la API URL cuando es posible (más robusta) y cae a un regex de respaldo.
|
|
1303
|
-
*
|
|
1304
|
-
* @param url Cadena que representa una URL o host
|
|
1305
|
-
* @param options
|
|
1306
|
-
* @param options.includePort Si es true, incluye":puerto" cuando exista (por defecto false)
|
|
1307
|
-
* @param options.includeProtocol Incluye "http://" o "https://" según corresponda (por defecto false)
|
|
1308
|
-
*/
|
|
1309
|
-
function obtenerHostDesdeUrl(url, options) {
|
|
1310
|
-
if (!url)
|
|
1311
|
-
return null;
|
|
1312
|
-
const includePort = !!options?.includePort;
|
|
1313
|
-
const includeProtocol = !!options?.includeProtocol;
|
|
1314
|
-
// Intentar con API URL
|
|
1315
|
-
try {
|
|
1316
|
-
const candidate = url.includes('://') ? url : `http://${url}`;
|
|
1317
|
-
const parsed = new URL(candidate);
|
|
1318
|
-
const protocol = includeProtocol ? `${parsed.protocol}//` : '';
|
|
1319
|
-
const hostname = parsed.hostname;
|
|
1320
|
-
const port = parsed.port;
|
|
1321
|
-
if (!hostname)
|
|
1322
|
-
return null;
|
|
1323
|
-
return `${protocol}${hostname}${includePort && port ? `:${port}` : ''}`;
|
|
1324
|
-
}
|
|
1325
|
-
catch {
|
|
1326
|
-
// Regex fallback
|
|
1327
|
-
const regex = /^(?:(?<protocol>[a-z]+):\/\/)?(?:www\.)?(?<host>\[[^\]]+\]|[A-Za-z0-9.-]+)(?::(?<port>\d{1,5}))?/;
|
|
1328
|
-
const match = String(url).match(regex);
|
|
1329
|
-
if (!match?.groups)
|
|
1330
|
-
return null;
|
|
1331
|
-
let host = match.groups['host'];
|
|
1332
|
-
if (host.startsWith('[') && host.endsWith(']')) {
|
|
1333
|
-
host = host.slice(1, -1);
|
|
1334
|
-
}
|
|
1335
|
-
const port = match.groups['port'];
|
|
1336
|
-
const protocol = includeProtocol ? `${match.groups['protocol'] ?? 'http'}://` : '';
|
|
1337
|
-
return `${protocol}${host}${includePort && port ? `:${port}` : ''}`;
|
|
1338
|
-
}
|
|
1339
|
-
}
|
|
1340
|
-
/** @deprecated Alias compatible (deprecated) — preferir usar `obtenerHostDesdeUrl`. */
|
|
1341
|
-
const extraerDominio = (url, options) => obtenerHostDesdeUrl(url, options);
|
|
1342
|
-
|
|
1343
|
-
function verificarRUC(ruc) {
|
|
1344
|
-
const f = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2];
|
|
1345
|
-
const rucArray = ruc.split('');
|
|
1346
|
-
const nArray = f.map((item, idx) => {
|
|
1347
|
-
return item * parseFloat(rucArray[idx]);
|
|
1348
|
-
});
|
|
1349
|
-
const suma = nArray.reduce((a, b) => a + b, 0);
|
|
1350
|
-
const residuo = suma % 11;
|
|
1351
|
-
const residuo2 = 11 - residuo;
|
|
1352
|
-
// @residuo=CONVERT(Integer,Right(CONVERT(VarChar,@residuo),1))
|
|
1353
|
-
const residuo3 = residuo2.toString().charAt(residuo2.toString().length - 1);
|
|
1354
|
-
const ultimoCaracter = ruc.toString().charAt(ruc.toString().length - 1);
|
|
1355
|
-
if (residuo3 == ultimoCaracter) {
|
|
1356
|
-
return true;
|
|
1357
|
-
}
|
|
1358
|
-
mensajeAlerta('error', 'Datos No válidos', ' El número de RUC no es válido');
|
|
1359
|
-
return false;
|
|
1360
|
-
}
|
|
1361
|
-
|
|
1362
|
-
/**
|
|
1363
|
-
* Generated bundle index. Do not edit.
|
|
1364
|
-
*/
|
|
1365
|
-
|
|
1366
|
-
export { b64Decode, b64Encode, buscarPorCampo, changeSelect, changeSelectApi, changeSelectData, changeSelectDataApi, convertirBytes, deepClone, deepMerge, delLocalStorage, desencriptar, downLoadFileStream, eliminarColumnaPorIndex, eliminarDuplicados, eliminarElementos, encriptar, esNumero, establecerQuitarRequired, extraerDominio, formatearFecha, formatearFechaCadena, formatearFechaFormato, generateRandomString, getBrowserName, getCambiarPwd, getDataArchivoFromPath, getFormValidationErrors, getLocalStorage, getUniqueValues, getUniqueValuesByProperty, groupBy, inicializarVariablesSessionStorage, isEmail, jwtToken, jwtTokenData, jwtTokenExpiracion, jwtTokenExpiracionFaltante, localStorageKeys, markAsTouchedWithoutEmitEvent, maskEmail, mensajeAlerta, mensajeConfirmacion, mensajeTimer, mensajeToast, mensajesDeError, mensajesErrorFormControl, mostrarValorEnBusqueda, nestGroupsBy, numberToWords, objectPropertiesBoolean, objectPropertiesToType, obtenerHostDesdeUrl, obtenerMimeType, obtenerUltimoOrden, ordenarArray, ordenarPorPropiedad, ordenarPorPropiedades, roundToDecimal, sanitizarNombreArchivo, seleccionarTextoInput, setCambiarPwd, setControlDesdeLista, setJwtTokenData, setLocalStorage, sumarObjetos, sumarPropiedades, toFormData, transformarFechasPorNombreDeCampo, verificarRUC };
|
|
1367
|
-
//# sourceMappingURL=jvsoft-utils-src-functions.mjs.map
|