@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
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
export function roundToDecimal(number: number, decimal: number): number {
|
|
2
|
+
return parseFloat(number.toFixed(decimal));
|
|
3
|
+
}
|
|
4
|
+
|
|
5
|
+
export function numberToWords(num: number): string {
|
|
6
|
+
if (num === 0) return 'cero';
|
|
7
|
+
if (num < 0) return 'menos ' + numberToWords(Math.abs(num));
|
|
8
|
+
if (num > 999999999999) return 'número demasiado grande';
|
|
9
|
+
|
|
10
|
+
const ones = ['', 'un', 'dos', 'tres', 'cuatro', 'cinco', 'seis', 'siete', 'ocho', 'nueve'];
|
|
11
|
+
const onesFinal = ['', 'uno', 'dos', 'tres', 'cuatro', 'cinco', 'seis', 'siete', 'ocho', 'nueve'];
|
|
12
|
+
const tens = ['', 'diez', 'veinte', 'treinta', 'cuarenta', 'cincuenta', 'sesenta', 'setenta', 'ochenta', 'noventa'];
|
|
13
|
+
const teens = ['diez', 'once', 'doce', 'trece', 'catorce', 'quince', 'dieciséis', 'diecisiete', 'dieciocho', 'diecinueve'];
|
|
14
|
+
const hundreds = ['', 'ciento', 'doscientos', 'trescientos', 'cuatrocientos', 'quinientos', 'seiscientos', 'setecientos', 'ochocientos', 'novecientos'];
|
|
15
|
+
|
|
16
|
+
// Función auxiliar para "un"/"uno"
|
|
17
|
+
const getOneForm = (n: number, isFinal: boolean): string =>
|
|
18
|
+
n === 1 ? (isFinal ? 'uno':'un'):onesFinal[n];
|
|
19
|
+
|
|
20
|
+
let words = '';
|
|
21
|
+
|
|
22
|
+
// Miles de millones (ahora sí se ejecuta)
|
|
23
|
+
if (num >= 1000000000) {
|
|
24
|
+
const billions = Math.floor(num / 1000000000);
|
|
25
|
+
words += (billions === 1 ? 'mil':numberToWords(billions) + ' mil') + ' millones ';
|
|
26
|
+
num %= 1000000000;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Millones
|
|
30
|
+
if (num >= 1000000) {
|
|
31
|
+
const millions = Math.floor(num / 1000000);
|
|
32
|
+
words += millions === 1 ? 'un millón ':numberToWords(millions) + ' millones ';
|
|
33
|
+
num %= 1000000;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// Miles
|
|
37
|
+
if (num >= 1000) {
|
|
38
|
+
const thousands = Math.floor(num / 1000);
|
|
39
|
+
words += thousands === 1 ? 'mil ':numberToWords(thousands) + ' mil ';
|
|
40
|
+
num %= 1000;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Centenas (con tratamiento especial para "ciento uno")
|
|
44
|
+
if (num >= 100) {
|
|
45
|
+
if (num === 100) {
|
|
46
|
+
words += 'cien';
|
|
47
|
+
num = 0;
|
|
48
|
+
}
|
|
49
|
+
else {
|
|
50
|
+
words += hundreds[Math.floor(num / 100)];
|
|
51
|
+
num %= 100;
|
|
52
|
+
if (num > 0) {
|
|
53
|
+
words += ' ' + getOneForm(num, true); // Siempre "uno" después de ciento
|
|
54
|
+
num = 0;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Decenas y unidades
|
|
60
|
+
if (num > 0) {
|
|
61
|
+
const isFinalWord = words === '';
|
|
62
|
+
|
|
63
|
+
if (num < 10) {
|
|
64
|
+
words += getOneForm(num, isFinalWord);
|
|
65
|
+
}
|
|
66
|
+
else if (num < 20) {
|
|
67
|
+
words += teens[num - 10];
|
|
68
|
+
}
|
|
69
|
+
else if (num < 30) {
|
|
70
|
+
if (num === 21) words += 'veintiuno';
|
|
71
|
+
else if (num === 22) words += 'veintidós';
|
|
72
|
+
else if (num === 23) words += 'veintitrés';
|
|
73
|
+
else if (num === 26) words += 'veintiséis';
|
|
74
|
+
else words += `veinti${onesFinal[num % 10]}`;
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
words += tens[Math.floor(num / 10)];
|
|
78
|
+
if (num % 10 > 0) {
|
|
79
|
+
words += ' y ' + getOneForm(num % 10, isFinalWord);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
return words.trim().replace(/\s+/g, ' ');
|
|
85
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import {formatDate} from '@angular/common';
|
|
2
|
+
import {formatearFecha} from './date';
|
|
3
|
+
|
|
4
|
+
export function objectPropertiesToType(formFields: Record<string, any>) {
|
|
5
|
+
Object.keys(formFields).filter(control => !!formFields[control]).forEach(control => {
|
|
6
|
+
if (/^dt[a-zA-Z]+/.test(control)) {
|
|
7
|
+
formFields[control] = formatDate(formFields[control], 'yyyy-MM-dd HH:mm', 'es-PE');
|
|
8
|
+
}
|
|
9
|
+
else if (control.startsWith('d')) {
|
|
10
|
+
formFields[control] = formatearFecha(formFields[control]);
|
|
11
|
+
}
|
|
12
|
+
else if (control.startsWith('n')) {
|
|
13
|
+
formFields[control] = Number(formFields[control]);
|
|
14
|
+
}
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
return formFields;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function objectPropertiesBoolean(formFields: Record<string, any>, retorno: 'boolean' | 'bit' = 'boolean') {
|
|
21
|
+
Object.keys(formFields).forEach(control => {
|
|
22
|
+
const valRetorno = (ctrl: any) => {
|
|
23
|
+
switch (retorno) {
|
|
24
|
+
case 'boolean':
|
|
25
|
+
formFields[ctrl] = formFields[ctrl] == 1;
|
|
26
|
+
break;
|
|
27
|
+
case 'bit':
|
|
28
|
+
formFields[ctrl] = formFields[ctrl] ? 1:0;
|
|
29
|
+
break;
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
if (control.charAt(0) == 'b' || (control.charAt(0) == 'i' && control.indexOf('Estado') !== -1)) {
|
|
33
|
+
valRetorno(control);
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
return formFields;
|
|
37
|
+
}
|
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
export function deepMerge(source: any, target: any): any {
|
|
2
|
+
// Crea un clon profundo sin usar JSON.parse(JSON.stringify)
|
|
3
|
+
let cloneSource = deepClone(source);
|
|
4
|
+
|
|
5
|
+
if (typeof target !== 'object' || target === null) {
|
|
6
|
+
return target;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
if (typeof cloneSource !== 'object' || cloneSource === null) {
|
|
10
|
+
cloneSource = Array.isArray(target) ? [] : {};
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
for (const key of Object.keys(target)) {
|
|
14
|
+
const targetValue = target[key];
|
|
15
|
+
const sourceValue = cloneSource[key];
|
|
16
|
+
|
|
17
|
+
if (typeof targetValue === 'object' && targetValue !== null && !Array.isArray(targetValue)) {
|
|
18
|
+
cloneSource[key] = deepMerge(sourceValue, targetValue);
|
|
19
|
+
} else {
|
|
20
|
+
cloneSource[key] = targetValue;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return cloneSource; // Retorna el clon y no modifica el original
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Función de clonación profunda que maneja funciones, fechas y otros tipos especiales
|
|
27
|
+
export function deepClone(obj: any): any {
|
|
28
|
+
if (obj === null || typeof obj !== 'object') {
|
|
29
|
+
return obj; // Devuelve el valor si no es un objeto
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// Manejar instancias de Date
|
|
33
|
+
if (obj instanceof Date) {
|
|
34
|
+
return new Date(obj.getTime());
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Manejar funciones devolviendo una copia directa
|
|
38
|
+
if (typeof obj === 'function') {
|
|
39
|
+
return obj.bind({}); // Devuelve una copia de la función enlazada a un contexto vacío
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Crear un nuevo objeto o array
|
|
43
|
+
const clonedObj: Record<string, any> = Array.isArray(obj) ? [] : {};
|
|
44
|
+
|
|
45
|
+
// Clonar recursivamente las propiedades del objeto
|
|
46
|
+
for (const key in obj) {
|
|
47
|
+
if (Object.prototype.hasOwnProperty.call(obj, key)) {
|
|
48
|
+
clonedObj[key] = deepClone(obj[key]);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return clonedObj;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Busca un elemento en un array o jerarquía de objetos según un campo y valor especificado.
|
|
57
|
+
*
|
|
58
|
+
* @returns El elemento encontrado o undefined si no existe.
|
|
59
|
+
*/
|
|
60
|
+
export function buscarPorCampo<T>(datosFn: {
|
|
61
|
+
items: T[];
|
|
62
|
+
campo: keyof T;
|
|
63
|
+
valor: any;
|
|
64
|
+
campoHijo?: string; // Campo opcional para búsqueda recursiva
|
|
65
|
+
}): T | undefined {
|
|
66
|
+
for (const item of datosFn.items) {
|
|
67
|
+
// Verifica si el campo coincide con el valor
|
|
68
|
+
if (item[datosFn.campo] === datosFn.valor) {
|
|
69
|
+
return item;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Verifica si hay un campo hijo y si es un array
|
|
73
|
+
if (datosFn.campoHijo && item[datosFn.campoHijo as keyof T] && Array.isArray(item[datosFn.campoHijo as keyof T])) {
|
|
74
|
+
// Realiza la búsqueda recursiva en el campo hijo
|
|
75
|
+
const encontrado = buscarPorCampo({
|
|
76
|
+
items: item[datosFn.campoHijo as keyof T] as T[], // Asegura el tipo correcto
|
|
77
|
+
campo: datosFn.campo,
|
|
78
|
+
valor: datosFn.valor,
|
|
79
|
+
campoHijo: datosFn.campoHijo,
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
// Si se encuentra el valor en el campo hijo, retorna el resultado
|
|
83
|
+
if (encontrado) {
|
|
84
|
+
return encontrado;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Si no se encuentra nada, retorna undefined
|
|
90
|
+
return undefined;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function sumarPropiedades(item: Record<string, any>, campos: string[]) {
|
|
94
|
+
const datosSumar = campos.map(campo => (item[campo] * 1));
|
|
95
|
+
return datosSumar.reduce((a, b) => a + b, 0);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function esNumero(value: any): boolean {
|
|
99
|
+
return !isNaN(Number(value));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function sumarObjetos(arrayObjetos: any[], campos: string[]): Record<string, number> {
|
|
103
|
+
return arrayObjetos.reduce((accumulator: Record<string, number>, item: any) => {
|
|
104
|
+
campos.forEach(campo => {
|
|
105
|
+
const valor = Number(item[campo]);
|
|
106
|
+
if (!isNaN(valor)) {
|
|
107
|
+
accumulator[campo] = (accumulator[campo] ?? 0) + valor;
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
return accumulator;
|
|
111
|
+
}, {});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function getUniqueValues(array: any[]) {
|
|
115
|
+
return array.filter((currentValue, index, arr) => (
|
|
116
|
+
arr.indexOf(currentValue) === index
|
|
117
|
+
));
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function getUniqueValuesByProperty<T>(objetos: T[], campo: string): T[] {
|
|
121
|
+
const objetosUnicos: {[key: string]: T} = {};
|
|
122
|
+
|
|
123
|
+
objetos.forEach(objeto => {
|
|
124
|
+
// Verificar si el objeto tiene el campo especificado
|
|
125
|
+
// @ts-ignore
|
|
126
|
+
if (objeto.hasOwnProperty(campo)) {
|
|
127
|
+
// @ts-ignore
|
|
128
|
+
const valorCampo = objeto[campo];
|
|
129
|
+
|
|
130
|
+
// Utilizar el valor del campo como clave en un objeto para asegurar que no haya duplicados
|
|
131
|
+
objetosUnicos[valorCampo] = objeto;
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
// Convertir el objeto de claves únicas de vuelta a una lista de objetos
|
|
136
|
+
return Object.values(objetosUnicos);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
export function ordenarArray(array: any[], numeros = false, sentido: 'ASC' | 'DESC' = 'ASC'): any[] {
|
|
141
|
+
if (numeros) {
|
|
142
|
+
if (sentido != 'ASC') {
|
|
143
|
+
return array.sort((a: any, b: any) => b - a);
|
|
144
|
+
}
|
|
145
|
+
return array.sort((a: any, b: any) => a - b);
|
|
146
|
+
}
|
|
147
|
+
return array.sort((a, b) => (a > b) ? 1:((b > a) ? -1:0));
|
|
148
|
+
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export function ordenarPorPropiedad(objData: any, propiedad: string, /**@deprecated*/ numeros = false) {
|
|
152
|
+
return ordenarPorPropiedades(objData, {propiedades: [propiedad], direcciones:['asc']});
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export function ordenarPorPropiedades<T>(arr: T[], options: {
|
|
156
|
+
propiedades: (keyof T)[],
|
|
157
|
+
direcciones?: ('asc' | 'desc' | '')[],
|
|
158
|
+
}): T[] {
|
|
159
|
+
const {propiedades, direcciones = []} = options;
|
|
160
|
+
const orden = direcciones.map(d => d === 'desc' ? -1:1);
|
|
161
|
+
|
|
162
|
+
return [...arr].sort((a, b) => {
|
|
163
|
+
return propiedades.reduce((acc, propiedad, index) => {
|
|
164
|
+
if (acc !== 0) return acc; // Si ya hay diferencia, no seguir comparando
|
|
165
|
+
|
|
166
|
+
const aValue = a[propiedad];
|
|
167
|
+
const bValue = b[propiedad];
|
|
168
|
+
|
|
169
|
+
if (typeof aValue === 'string' && typeof bValue === 'string') {
|
|
170
|
+
return aValue.localeCompare(bValue) * orden[index]; // 🔹 Comparación alfabética
|
|
171
|
+
}
|
|
172
|
+
if (typeof aValue === 'number' && typeof bValue === 'number') {
|
|
173
|
+
return (aValue - bValue) * orden[index]; // 🔹 Comparación numérica
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
return 0; // En caso de valores no comparables
|
|
177
|
+
}, 0);
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export function groupBy<T extends Record<string, any>, K extends keyof T>(
|
|
182
|
+
array: T[],
|
|
183
|
+
key: K | ((obj: T) => string)
|
|
184
|
+
): Record<string, T[]> {
|
|
185
|
+
const keyFn = key instanceof Function ? key:(obj: T) => obj[key];
|
|
186
|
+
return array.reduce((objectsByKeyValue, obj) => {
|
|
187
|
+
const value = keyFn(obj);
|
|
188
|
+
objectsByKeyValue[value] = (objectsByKeyValue[value] || []).concat(obj);
|
|
189
|
+
return objectsByKeyValue;
|
|
190
|
+
}, {} as Record<string, T[]>);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export function nestGroupsBy(arr: any, properties: any) {
|
|
194
|
+
const fnGroupBy = (conversions: any, property2: any) => {
|
|
195
|
+
return conversions.reduce((acc: any, obj: any) => {
|
|
196
|
+
const key = obj[property2];
|
|
197
|
+
if (!acc[key]) {
|
|
198
|
+
acc[key] = [];
|
|
199
|
+
}
|
|
200
|
+
acc[key].push(obj);
|
|
201
|
+
return acc;
|
|
202
|
+
}, {});
|
|
203
|
+
};
|
|
204
|
+
properties = Array.from(properties);
|
|
205
|
+
if (properties.length === 1) {
|
|
206
|
+
return fnGroupBy(arr, properties[0]);
|
|
207
|
+
}
|
|
208
|
+
const property = properties.shift();
|
|
209
|
+
const grouped = fnGroupBy(arr, property);
|
|
210
|
+
Object.keys(grouped).forEach(key => {
|
|
211
|
+
grouped[key] = nestGroupsBy(grouped[key], Array.from(properties));
|
|
212
|
+
});
|
|
213
|
+
return grouped;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Obtiene un valor de un objeto usando una ruta de propiedad anidada.
|
|
219
|
+
*
|
|
220
|
+
* @param obj - Objeto de entrada.
|
|
221
|
+
* @param path - Ruta en formato punto (ej: "cliente.orden").
|
|
222
|
+
* @returns El valor encontrado o undefined si no existe.
|
|
223
|
+
*/
|
|
224
|
+
function getValueByPath(obj: any, path: string): any {
|
|
225
|
+
return path.split('.').reduce((acc, key) => acc?.[key], obj);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Retorna el valor máximo del campo especificado (incluso anidado) en un arreglo de objetos.
|
|
230
|
+
*
|
|
231
|
+
* @param data - Lista de objetos a procesar.
|
|
232
|
+
* @param campo - Nombre del campo a evaluar, puede ser anidado (ej. "campo.orden").
|
|
233
|
+
* @param incrementar - Si es true, retorna el valor máximo + 1. Por defecto es true.
|
|
234
|
+
* @returns El valor máximo encontrado, posiblemente incrementado.
|
|
235
|
+
*/
|
|
236
|
+
export function obtenerUltimoOrden(data: any[], campo: string, incrementar: boolean = true): number {
|
|
237
|
+
const max = data.reduce((mayor, item) => {
|
|
238
|
+
const valor = Number(getValueByPath(item, campo)) || 0;
|
|
239
|
+
return valor > mayor ? valor:mayor;
|
|
240
|
+
}, 0);
|
|
241
|
+
|
|
242
|
+
return incrementar ? max + 1:max;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Elimina una o varias columnas específicas (por índice) de una tabla representada como array de arrays.
|
|
248
|
+
*
|
|
249
|
+
* @param data - Array de filas (cada fila debe ser un array).
|
|
250
|
+
* @param columnIndex - Índice o lista de índices de las columnas a eliminar.
|
|
251
|
+
* @returns Nuevo array con las columnas eliminadas.
|
|
252
|
+
*/
|
|
253
|
+
export function eliminarColumnaPorIndex<T extends unknown[][]>(
|
|
254
|
+
data: T,
|
|
255
|
+
columnIndex: number | number[]
|
|
256
|
+
): T {
|
|
257
|
+
if (!Array.isArray(data)) return [] as unknown as T;
|
|
258
|
+
|
|
259
|
+
// Normalizar a array único y ordenado (descendente para evitar reindexación al splicing)
|
|
260
|
+
const indices: number[] = Array.isArray(columnIndex)
|
|
261
|
+
? [...new Set(columnIndex)].filter((i) => (typeof i === 'number' && i >= 0)).sort((a, b) => b - a)
|
|
262
|
+
:[columnIndex];
|
|
263
|
+
|
|
264
|
+
return data.map((row) => {
|
|
265
|
+
if (!Array.isArray(row)) return row;
|
|
266
|
+
|
|
267
|
+
const newRow = [...row];
|
|
268
|
+
|
|
269
|
+
for (const index of indices) {
|
|
270
|
+
if (index >= 0 && index < newRow.length) {
|
|
271
|
+
newRow.splice(index, 1);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
return newRow as typeof row;
|
|
276
|
+
}) as T;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
export function eliminarDuplicados<T extends object>(
|
|
282
|
+
array: T[],
|
|
283
|
+
claves?: (keyof T)[]
|
|
284
|
+
): T[] {
|
|
285
|
+
const unicos = new Map<string, T>();
|
|
286
|
+
|
|
287
|
+
for (const item of array) {
|
|
288
|
+
const claveUnica = claves && claves.length > 0
|
|
289
|
+
? claves.map(k => item[k]).join('|')
|
|
290
|
+
: JSON.stringify(item);
|
|
291
|
+
|
|
292
|
+
if (!unicos.has(claveUnica)) {
|
|
293
|
+
unicos.set(claveUnica, item);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
return Array.from(unicos.values());
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
export function eliminarElementos<T extends object>(
|
|
301
|
+
origen: T[],
|
|
302
|
+
elementosAEliminar: T[],
|
|
303
|
+
claves?: (keyof T)[]
|
|
304
|
+
): T[] {
|
|
305
|
+
const clavesSet = new Set<string>();
|
|
306
|
+
|
|
307
|
+
for (const item of elementosAEliminar) {
|
|
308
|
+
const key = claves && claves.length > 0
|
|
309
|
+
? claves.map(k => item[k]).join('|')
|
|
310
|
+
: JSON.stringify(item);
|
|
311
|
+
clavesSet.add(key);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
return origen.filter(item => {
|
|
315
|
+
const key = claves && claves.length > 0
|
|
316
|
+
? claves.map(k => item[k]).join('|')
|
|
317
|
+
: JSON.stringify(item);
|
|
318
|
+
return !clavesSet.has(key);
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export * from './mat-form-controls';
|
|
2
|
+
|
|
3
|
+
export * from './base64'
|
|
4
|
+
export * from './browser'
|
|
5
|
+
export * from './crypto-js';
|
|
6
|
+
export * from './date';
|
|
7
|
+
export * from './email';
|
|
8
|
+
export * from './file'
|
|
9
|
+
export * from './forms'
|
|
10
|
+
export * from './http-client'
|
|
11
|
+
export * from './local-storage';
|
|
12
|
+
export * from './number';
|
|
13
|
+
export * from './object-transformation'
|
|
14
|
+
export * from './objects-arrays'
|
|
15
|
+
export * from './string'
|
|
16
|
+
export * from './sweetalert'
|
|
17
|
+
export * from './utiles'
|
|
18
|
+
|
|
19
|
+
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
export function generateRandomString(length: number) {
|
|
2
|
+
let result = '';
|
|
3
|
+
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
|
4
|
+
const charactersLength = characters.length;
|
|
5
|
+
for (let i = 0; i < length; i++) {
|
|
6
|
+
result += characters.charAt(Math.floor(Math.random() * charactersLength));
|
|
7
|
+
}
|
|
8
|
+
return result;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Obtiene el host (hostname) de una URL o cadena host[:port].
|
|
13
|
+
* Opcionalmente puede devolver también el puerto si está presente.
|
|
14
|
+
*
|
|
15
|
+
* - Acepta inputs como:
|
|
16
|
+
* 'https://example.com/path', 'example.com:3000', 'localhost', 'http://[::1]:4200'
|
|
17
|
+
* - Usa la API URL cuando es posible (más robusta) y cae a un regex de respaldo.
|
|
18
|
+
*
|
|
19
|
+
* @param url Cadena que representa una URL o host
|
|
20
|
+
* @param options
|
|
21
|
+
* @param options.includePort Si es true, incluye":puerto" cuando exista (por defecto false)
|
|
22
|
+
* @param options.includeProtocol Incluye "http://" o "https://" según corresponda (por defecto false)
|
|
23
|
+
*/
|
|
24
|
+
export function obtenerHostDesdeUrl(
|
|
25
|
+
url: string | null | undefined,
|
|
26
|
+
options?: { includePort?: boolean; includeProtocol?: boolean }
|
|
27
|
+
): string | null {
|
|
28
|
+
if (!url) return null;
|
|
29
|
+
|
|
30
|
+
const includePort = !!options?.includePort;
|
|
31
|
+
const includeProtocol = !!options?.includeProtocol;
|
|
32
|
+
|
|
33
|
+
// Intentar con API URL
|
|
34
|
+
try {
|
|
35
|
+
const candidate = url.includes('://') ? url : `http://${url}`;
|
|
36
|
+
const parsed = new URL(candidate);
|
|
37
|
+
|
|
38
|
+
const protocol = includeProtocol ? `${parsed.protocol}//` : '';
|
|
39
|
+
const hostname = parsed.hostname;
|
|
40
|
+
const port = parsed.port;
|
|
41
|
+
|
|
42
|
+
if (!hostname) return null;
|
|
43
|
+
|
|
44
|
+
return `${protocol}${hostname}${includePort && port ? `:${port}` : ''}`;
|
|
45
|
+
} catch {
|
|
46
|
+
// Regex fallback
|
|
47
|
+
const regex =
|
|
48
|
+
/^(?:(?<protocol>[a-z]+):\/\/)?(?:www\.)?(?<host>\[[^\]]+\]|[A-Za-z0-9.-]+)(?::(?<port>\d{1,5}))?/;
|
|
49
|
+
const match = String(url).match(regex);
|
|
50
|
+
if (!match?.groups) return null;
|
|
51
|
+
|
|
52
|
+
let host = match.groups['host'];
|
|
53
|
+
if (host.startsWith('[') && host.endsWith(']')) {
|
|
54
|
+
host = host.slice(1, -1);
|
|
55
|
+
}
|
|
56
|
+
const port = match.groups['port'];
|
|
57
|
+
const protocol = includeProtocol ? `${match.groups['protocol'] ?? 'http'}://` : '';
|
|
58
|
+
|
|
59
|
+
return `${protocol}${host}${includePort && port ? `:${port}` : ''}`;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
/** @deprecated Alias compatible (deprecated) — preferir usar `obtenerHostDesdeUrl`. */
|
|
65
|
+
export const extraerDominio = (
|
|
66
|
+
url: string | null | undefined,
|
|
67
|
+
options?: { includePort?: boolean; includeProtocol?: boolean }
|
|
68
|
+
) => obtenerHostDesdeUrl(url, options);
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import swal, {SweetAlertOptions, SweetAlertResult} from 'sweetalert2';
|
|
2
|
+
|
|
3
|
+
export function mensajeAlerta(tipo: 'success' | 'error' | 'info' | 'warning' | 'question', titulo: string, mensaje: string, opciones?: SweetAlertOptions) {
|
|
4
|
+
opciones = {
|
|
5
|
+
...{
|
|
6
|
+
heightAuto: false,
|
|
7
|
+
title: titulo,
|
|
8
|
+
html: mensaje,
|
|
9
|
+
icon: tipo,
|
|
10
|
+
confirmButtonText: 'Aceptar',
|
|
11
|
+
// customClass: {
|
|
12
|
+
// confirmButton: 'btn btn-lg btn-outline-success mx-2',
|
|
13
|
+
// cancelButton: 'btn btn-lg btn-outline-dark mx-2'
|
|
14
|
+
// },
|
|
15
|
+
// buttonsStyling: false
|
|
16
|
+
},
|
|
17
|
+
...opciones
|
|
18
|
+
};
|
|
19
|
+
return swal.fire(opciones);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function mensajeTimer(tipo: 'success' | 'error' | 'info' | 'warning' | 'question', titulo: string, mensaje: string, milisegundos = 3000, showLoading = true, opciones?: SweetAlertOptions) {
|
|
23
|
+
let timerInterval: any;
|
|
24
|
+
opciones = {
|
|
25
|
+
...{
|
|
26
|
+
heightAuto: false,
|
|
27
|
+
title: titulo,
|
|
28
|
+
html: mensaje + '<br> Se cerrará en <strong> X </strong> segundos.',
|
|
29
|
+
icon: tipo,
|
|
30
|
+
timer: milisegundos,
|
|
31
|
+
showCancelButton: false,
|
|
32
|
+
showConfirmButton: false,
|
|
33
|
+
willOpen: () => {
|
|
34
|
+
if (showLoading) {
|
|
35
|
+
swal.showLoading();
|
|
36
|
+
}
|
|
37
|
+
timerInterval = setInterval(() => {
|
|
38
|
+
const impr = Math.ceil(((swal.getTimerLeft() ?? 1)/ 1000));
|
|
39
|
+
if (swal.getHtmlContainer()) {
|
|
40
|
+
// @ts-ignore
|
|
41
|
+
swal.getHtmlContainer().querySelector('strong').textContent = String(impr);
|
|
42
|
+
}
|
|
43
|
+
}, 100);
|
|
44
|
+
},
|
|
45
|
+
willClose: () => {
|
|
46
|
+
clearInterval(timerInterval);
|
|
47
|
+
}
|
|
48
|
+
},
|
|
49
|
+
...opciones
|
|
50
|
+
};
|
|
51
|
+
return swal.fire(opciones);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// @ts-ignore
|
|
55
|
+
export function mensajeConfirmacion(tipo: 'success' | 'error' | 'info' | 'warning' | 'question', titulo, mensaje, opciones?: SweetAlertOptions): Promise<SweetAlertResult<Awaited<any>>> {
|
|
56
|
+
opciones = {
|
|
57
|
+
...{
|
|
58
|
+
heightAuto: false,
|
|
59
|
+
title: titulo,
|
|
60
|
+
html: mensaje,
|
|
61
|
+
icon: tipo,
|
|
62
|
+
showCancelButton: true,
|
|
63
|
+
// confirmButtonColor: '#3f51b5',
|
|
64
|
+
// cancelButtonColor: '#ffffff',
|
|
65
|
+
confirmButtonText: 'Confirmar',
|
|
66
|
+
cancelButtonText: 'Cancelar',
|
|
67
|
+
reverseButtons: true,
|
|
68
|
+
// customClass: {
|
|
69
|
+
// confirmButton: 'btn btn-lg btn-outline-success mx-2',
|
|
70
|
+
// cancelButton: 'btn btn-lg btn-outline-dark mx-2'
|
|
71
|
+
// },
|
|
72
|
+
// buttonsStyling: false
|
|
73
|
+
},
|
|
74
|
+
...opciones
|
|
75
|
+
};
|
|
76
|
+
return swal.fire(opciones);
|
|
77
|
+
}
|
|
78
|
+
export function mensajeToast(tipo: 'success' | 'error' | 'info' | 'warning' | 'question', titulo: string, mensaje: string, opciones?: SweetAlertOptions) {
|
|
79
|
+
opciones = {
|
|
80
|
+
...{
|
|
81
|
+
heightAuto: false,
|
|
82
|
+
title: titulo,
|
|
83
|
+
html: mensaje,
|
|
84
|
+
icon: tipo,
|
|
85
|
+
confirmButtonText: 'Aceptar',
|
|
86
|
+
toast: true,
|
|
87
|
+
position: 'top-end',
|
|
88
|
+
showConfirmButton: false,
|
|
89
|
+
timer: 3000,
|
|
90
|
+
timerProgressBar: true,
|
|
91
|
+
},
|
|
92
|
+
...opciones
|
|
93
|
+
};
|
|
94
|
+
return swal.fire(opciones);
|
|
95
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import {mensajeAlerta} from './sweetalert';
|
|
2
|
+
|
|
3
|
+
export function verificarRUC(ruc: string) {
|
|
4
|
+
const f = [5, 4, 3, 2, 7, 6, 5, 4, 3, 2];
|
|
5
|
+
const rucArray = ruc.split('');
|
|
6
|
+
const nArray = f.map((item, idx) => {
|
|
7
|
+
return item * parseFloat(rucArray[idx]);
|
|
8
|
+
});
|
|
9
|
+
const suma = nArray.reduce((a, b) => a + b, 0);
|
|
10
|
+
const residuo = suma % 11;
|
|
11
|
+
const residuo2 = 11 - residuo;
|
|
12
|
+
// @residuo=CONVERT(Integer,Right(CONVERT(VarChar,@residuo),1))
|
|
13
|
+
const residuo3 = residuo2.toString().charAt(residuo2.toString().length - 1);
|
|
14
|
+
const ultimoCaracter = ruc.toString().charAt(ruc.toString().length - 1);
|
|
15
|
+
if (residuo3 == ultimoCaracter) {
|
|
16
|
+
return true;
|
|
17
|
+
}
|
|
18
|
+
mensajeAlerta('error', 'Datos No válidos', ' El número de RUC no es válido');
|
|
19
|
+
return false;
|
|
20
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './public-api'
|
|
File without changes
|