@zauru-sdk/common 1.0.50 → 1.0.60

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/src/common.ts CHANGED
@@ -1,555 +1,555 @@
1
- import moment from "moment";
2
- import "moment-timezone";
3
- import type {
4
- PayeeGraphQL,
5
- AxiosUtilsResponse,
6
- BasketSchema,
7
- SelectFieldOption,
8
- MonthsType,
9
- } from "@zauru-sdk/types";
10
- import { MONTHS } from "@zauru-sdk/types";
11
-
12
- export const DESTINOS_MUESTRA_OPTIONS: SelectFieldOption[] = [
13
- { label: "Microbiología", value: "microbiologa" },
14
- { label: "Residuos de plaguicidas", value: "residuos_de_plaguicidas" },
15
- ];
16
-
17
- moment.locale("es");
18
-
19
- /**
20
- * Obtener el objeto de canastas en base al string de canastas
21
- * @param basketsString
22
- * @returns
23
- */
24
- export const getBasketsSchema = (basketsString: string): BasketSchema[] => {
25
- //Sacar conteo de canastas y su descripción de colores
26
- //ejemplo: vienen en un campo así: 8-53311-VERDE,3-53315-ROSADA,4-53313-ROJA
27
- const splitedText = basketsString.split(",");
28
- const baskets = splitedText.map((splited: string) => {
29
- const values = splited.split("-");
30
- return {
31
- total: Number(values[0]) ?? 0,
32
- id: Number(values[1]) ?? 0,
33
- color: values[2] ?? "Sin Canasta",
34
- } as BasketSchema;
35
- });
36
-
37
- return baskets;
38
- };
39
-
40
- export function generateClientUUID() {
41
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
42
- const r = (Math.random() * 16) | 0,
43
- v = c == "x" ? r : (r & 0x3) | 0x8;
44
- return v.toString(16);
45
- });
46
- }
47
-
48
- /**
49
- * extractValueBetweenTags
50
- * @param input
51
- * @param tagName
52
- * @returns
53
- */
54
- export function extractValueBetweenTags(
55
- input: string,
56
- tagName: string
57
- ): string {
58
- const regex = new RegExp(`<${tagName}[^>]*>(.*?)<\\/${tagName}>`, "i");
59
- const match = input.match(regex);
60
- return match ? match[1] : "";
61
- }
62
-
63
- /**
64
- * isJsonArray
65
- * @param value
66
- * @returns
67
- */
68
- export function isJsonArray(value: string): boolean {
69
- try {
70
- const parsed = JSON.parse(value);
71
- return Array.isArray(parsed);
72
- } catch (e) {
73
- return false;
74
- }
75
- }
76
-
77
- /**
78
- *
79
- * @param date Recibe el date en formato UTC
80
- */
81
- export const getFechaJuliana = (date: string): string => {
82
- function getDaysInMonth(month: number): number {
83
- return new Date(new Date().getFullYear(), month, 0).getDate();
84
- }
85
-
86
- const getNumberOfDays = (month: number, day: number): number => {
87
- let numberOfDays = day;
88
-
89
- while (month > 0) {
90
- const temp = getDaysInMonth(month);
91
- numberOfDays += temp;
92
- month--;
93
- }
94
-
95
- return numberOfDays;
96
- };
97
-
98
- const dt = moment(date).toDate();
99
- const month = dt.getMonth();
100
- const day = getNumberOfDays(month, dt.getDate());
101
-
102
- return `${dt.getFullYear()}-${day}`;
103
- };
104
-
105
- /**
106
- * Convierte una fecha de tipo 25 de jul de 2022 a Date
107
- * @param date
108
- * @returns
109
- */
110
- export const getNewDateByFormat = (date: string): Date => {
111
- if (!date) {
112
- return new Date();
113
- }
114
- const date_parts: string[] = date.split(" ");
115
-
116
- const new_date = new Date(
117
- parseInt(date_parts[4]),
118
- MONTHS[date_parts[2] as keyof MonthsType],
119
- parseInt(date_parts[0])
120
- );
121
- return new_date;
122
- };
123
-
124
- /**
125
- * Convierte una fecha de tipo 25 de jul de 2022 a YYYY-MM-DD
126
- * @param date
127
- * @returns
128
- */
129
- export const getZauruDateByText = (date: string) => {
130
- const newDate = getNewDateByFormat(date);
131
- return getStringDate(newDate);
132
- };
133
-
134
- /**
135
- * Convierte una fecha de tipo Date a YYYY-MM-DD
136
- * @param date
137
- * @returns
138
- */
139
- export const getStringDate = (date: Date) => {
140
- const year = date.getFullYear();
141
- const month = date.getMonth() + 1;
142
- const day = date.getDay();
143
- return `${year}-${month <= 9 ? `0${month}` : month}-${
144
- day <= 9 ? `0${day}` : day
145
- }`;
146
- };
147
-
148
- export function truncateText(text?: string, maxLength?: number) {
149
- if (!text || !maxLength) {
150
- return "";
151
- }
152
- // Verificar si el texto es más largo que maxLength
153
- if (text.length > maxLength) {
154
- // Si es así, truncar el texto y agregar "..."
155
- return text.substring(0, maxLength - 3) + "...";
156
- } else {
157
- // Si no, devolver el texto completo
158
- return text;
159
- }
160
- }
161
-
162
- export const getTodayDaysDifference = (date: string): number => {
163
- // Crear el objeto de Moment para la fecha de creación
164
- const fechaCreacion = moment(date);
165
- // Crear el objeto de Moment para la fecha actual
166
- const ahora = moment();
167
- // Calcular la diferencia en días
168
- const diferencia = ahora.diff(fechaCreacion, "days");
169
- return diferencia;
170
- };
171
-
172
- export const getTodayMinutesDifference = (date: string): number => {
173
- // Crear el objeto de Moment para la fecha de creación
174
- const fechaCreacion = moment(date);
175
- // Crear el objeto de Moment para la fecha actual
176
- const ahora = moment();
177
- // Calcular la diferencia en minutos
178
- const diferencia = ahora.diff(fechaCreacion, "minutes");
179
- return diferencia;
180
- };
181
-
182
- /**
183
- * Convierte una fecha de tipo Date a DD-MM-YYY HH:mm:ss
184
- * @param date
185
- * @returns
186
- */
187
- export const getStringFullDate = (date: Date) => {
188
- const hour = date.getHours();
189
- const minutes = date.getMinutes();
190
- const seconds = date.getSeconds();
191
- const year = date.getFullYear();
192
- const month = date.getMonth() + 1;
193
- const day = date.getDay();
194
- return `${day <= 9 ? `0${day}` : day}-${
195
- month <= 9 ? `0${month}` : month
196
- }-${year} ${hour}:${minutes}:${seconds}`;
197
- };
198
-
199
- /**
200
- * Convierte una fecha de tipo DD/MM/YYYY a YYYY/MM/DD
201
- * @param dateStr
202
- * @returns
203
- */
204
- export const localDateToUSDate = (dateStr: string) => {
205
- const date = moment(dateStr, "DD/MM/YYYY");
206
- const newDateStr = date.format("YYYY/MM/DD");
207
- return newDateStr;
208
- };
209
-
210
- export const stringDateToParsedUTCDate = (date: string): Date => {
211
- const issueDate = new Date(date);
212
- issueDate.setMinutes(issueDate.getMinutes() - 360);
213
- return issueDate;
214
- };
215
-
216
- /**
217
- * zauruDateToLongString
218
- * @param date
219
- * @returns
220
- */
221
- export function zauruDateToLongString(date: string, hours: boolean = false) {
222
- if (!date) {
223
- return "invalid date:zauruDateToLongString";
224
- }
225
-
226
- // Asume que la fecha de entrada está en UTC y la convierte a la zona horaria local del navegador
227
- const issueDate = moment.utc(date).local();
228
-
229
- let formatString = "dddd, D [de] MMMM [de] YYYY";
230
- if (hours) {
231
- formatString += ", HH:mm a"; // Añade la hora en formato de 12 horas con AM/PM
232
- }
233
-
234
- // Formatea la fecha en el locale español
235
- return issueDate.locale("es").format(formatString);
236
- }
237
-
238
- /**
239
- * todayLongString
240
- * @param date
241
- * @returns
242
- */
243
- export function todayLongString(hours: boolean = false) {
244
- // Analiza la fecha y hora sin ajustes de zona horaria
245
- const issueDate = moment(new Date().toISOString());
246
-
247
- let formatString = "dddd, D [de] MMMM [de] YYYY";
248
- if (hours) {
249
- formatString += ", HH:mm a"; // Añade la hora en formato de 12 horas con AM/PM
250
- }
251
-
252
- // Formatea la fecha en el locale español
253
- return issueDate.locale("es").format(formatString);
254
- }
255
-
256
- export function isToday(dateStr: string): boolean {
257
- // Parsea la fecha dada y la fecha actual a inicio del día (00:00:00)
258
- const givenDate = moment(dateStr).startOf("day");
259
- const today = moment().startOf("day");
260
-
261
- // Compara si son iguales
262
- return givenDate.isSame(today);
263
- }
264
-
265
- export const getDatePickerCurrentDate = () => {
266
- const date = new Date();
267
- const year = date.getFullYear();
268
- const month = String(date.getMonth() + 1).padStart(2, "0"); // Los meses van de 0 a 11, por eso sumamos 1.
269
- const day = String(date.getDate()).padStart(2, "0");
270
-
271
- return `${year}-${month}-${day}`;
272
- };
273
-
274
- export const getTimePickerCurrentTime = () => {
275
- const date = new Date();
276
- const hours = String(date.getHours()).padStart(2, "0");
277
- const minutes = String(date.getMinutes()).padStart(2, "0");
278
-
279
- return `${hours}:${minutes}`;
280
- };
281
-
282
- export const getDateAfterDays = (daysAfterToday: number) => {
283
- const date = new Date();
284
- date.setDate(date.getDate() + daysAfterToday); // Agregamos el número de días a la fecha actual.
285
-
286
- const year = date.getFullYear();
287
- const month = String(date.getMonth() + 1).padStart(2, "0");
288
- const day = String(date.getDate()).padStart(2, "0");
289
-
290
- return `${year}-${month}-${day}`;
291
- };
292
-
293
- export const getPayeeFormated = (payee: PayeeGraphQL) => {
294
- return `<${payee.id_number}> ${payee.tin ? `${payee.tin} | ` : ""}${
295
- payee.name
296
- }`;
297
- };
298
-
299
- export const getPayeeInfoOptions = (
300
- payees: PayeeGraphQL[]
301
- ): (SelectFieldOption & { id: number })[] => {
302
- return payees.map((x) => {
303
- return {
304
- label: `<${x.id_number}> ${x.tin ? `${x.tin} | ` : ""}${x.name}`,
305
- value: `<${x.id_number}> ${x.tin ? `${x.tin} | ` : ""}${x.name}`,
306
- id: x.id,
307
- } as SelectFieldOption & { id: number };
308
- });
309
- };
310
-
311
- export const parsedBaculoFormValue = (value: any) => {
312
- if (value === "false") {
313
- return "No";
314
- } else if (value === "true") {
315
- return "Si";
316
- } else if (DESTINOS_MUESTRA_OPTIONS.some((x) => x.value === value)) {
317
- return DESTINOS_MUESTRA_OPTIONS.find((x) => x.value === value)?.label;
318
- }
319
-
320
- return capitalLetter(value);
321
- };
322
-
323
- export function extractIdFromForm(s: string): number | null {
324
- const match = s.match(/LAB_FORM_(\d+);/);
325
- if (match && match[1]) {
326
- return parseInt(match[1], 10);
327
- }
328
- return null;
329
- }
330
-
331
- /**
332
- * Formatea una fecha de tipo YYYY-MM-DD a 2023-08-07T20:56:00.540245
333
- * @param dateString
334
- * @returns
335
- */
336
- export function formatDateToUTC(dateString: string): string {
337
- const date = new Date(dateString);
338
-
339
- const year = date.getUTCFullYear();
340
- const month = String(date.getUTCMonth() + 1).padStart(2, "0");
341
- const day = String(date.getUTCDate()).padStart(2, "0");
342
- const hours = String(date.getUTCHours()).padStart(2, "0");
343
- const minutes = String(date.getUTCMinutes()).padStart(2, "0");
344
- const seconds = String(date.getUTCSeconds()).padStart(2, "0");
345
- const milliseconds = String(date.getUTCMilliseconds()).padStart(3, "0");
346
-
347
- return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${milliseconds}`;
348
- }
349
-
350
- export const formatDateToDatePicker = (date: Date) => {
351
- const year = date.getFullYear();
352
- const month = `0${date.getMonth() + 1}`.slice(-2); // Los meses van de 0 a 11, así que le sumamos 1
353
- const day = `0${date.getDate()}`.slice(-2);
354
-
355
- return `${year}-${month}-${day}`;
356
- };
357
-
358
- export const formatTimeToTimePicker = (timeString: string) => {
359
- const [hours, minutes] = timeString.split(":").map(Number);
360
-
361
- const date = new Date();
362
- date.setHours(hours, minutes, 0, 0); // Establecemos las horas y minutos, y reseteamos segundos y milisegundos
363
-
364
- return date;
365
- };
366
-
367
- export const toFixedIfNeeded = (value: number) => {
368
- if (!value) {
369
- return "0";
370
- }
371
-
372
- if (Number.isInteger(value)) {
373
- return value.toString().replace(".00", "");
374
- }
375
-
376
- const decimals = (value.toString().split(".")[1] || []).length;
377
-
378
- const decimal = decimals > 2 ? value.toFixed(2) : value.toString();
379
-
380
- return decimal.replace(".00", "");
381
- };
382
-
383
- export const isNumeric = (value: any) => {
384
- return !isNaN(value) && !isNaN(parseFloat(value));
385
- };
386
-
387
- export function incrementString(str: string): string {
388
- // Encuentra la parte numérica de la cadena usando una expresión regular
389
- const match = str.match(/(\D*)(\d+)$/);
390
- if (!match) {
391
- throw new Error("Formato de cadena no válido");
392
- }
393
-
394
- const prefix = match[1];
395
- const numberPart = match[2];
396
-
397
- // Incrementa el número
398
- const incrementedNumber = parseInt(numberPart, 10) + 1;
399
-
400
- // Convierte el número incrementado de nuevo en una cadena y rellena con ceros
401
- const incrementedString = incrementedNumber
402
- .toString()
403
- .padStart(numberPart.length, "0");
404
-
405
- return prefix + incrementedString;
406
- }
407
-
408
- export function getParsedIdFromString(inputString: string): number {
409
- const regex = /<(\d+)>/; // Expresión regular para encontrar el número entre los corchetes
410
-
411
- const match = inputString.match(regex); // Buscar la coincidencia en el string
412
-
413
- let number = 0;
414
- if (match && match[1]) {
415
- number = parseInt(match[1]); // Convertir el número de string a entero
416
- //console.log(number); // Mostrar el número en la consola
417
- } else {
418
- console.log("No se encontró ningún número entre corchetes.");
419
- }
420
-
421
- return number;
422
- }
423
-
424
- export const arrayToObject = (
425
- arr: Array<any> = [],
426
- options?: { withOutId?: boolean }
427
- ): { [key: string]: any } => {
428
- return arr.reduce((acc, cur, idx) => {
429
- const tempVal = cur;
430
- if (options?.withOutId) {
431
- delete tempVal.id;
432
- }
433
- acc[idx.toString()] = tempVal;
434
- return acc;
435
- }, {});
436
- };
437
-
438
- export function convertToFormData(obj: any) {
439
- const formData = new FormData();
440
-
441
- function appendFormData(data: any, root = "") {
442
- if (data && typeof data === "object" && !(data instanceof File)) {
443
- for (const key in data) {
444
- if (data.hasOwnProperty(key)) {
445
- if (root === "") {
446
- // Append nested objects
447
- if (data[key] != undefined && data[key] != null)
448
- appendFormData(data[key], key);
449
- } else {
450
- // Append data with namespaced keys for nested objects
451
- if (data[key] != undefined && data[key] != null)
452
- appendFormData(data[key], `${root}[${key}]`);
453
- }
454
- }
455
- }
456
- } else {
457
- if (data instanceof File) {
458
- formData.append(root, data, data.name);
459
- } else {
460
- formData.append(root, data);
461
- }
462
- }
463
- }
464
-
465
- appendFormData(obj);
466
- return formData;
467
- }
468
-
469
- export const ZAURU_REGEX = {
470
- porcentaje: /^\d{1,2}(\.\d{1,2})?$/,
471
- };
472
-
473
- /**
474
- * Para hacer sumas en los reduce de arreglos enteros
475
- * @param accumulator
476
- * @param a
477
- * @returns
478
- */
479
- export function reduceAdd(accumulator: number, a: number) {
480
- return accumulator + a;
481
- }
482
-
483
- /**
484
- * Truncar decimales, ejemplo: truncateDecimals(43.434340934, 2) => 43.43
485
- * @param number
486
- * @param digits
487
- * @returns
488
- */
489
- export const truncateDecimals = function (
490
- number: number,
491
- digits: number
492
- ): number {
493
- const multiplier = Math.pow(10, digits),
494
- adjustedNum = number * multiplier,
495
- truncatedNum = Math[adjustedNum < 0 ? "ceil" : "floor"](adjustedNum);
496
-
497
- return truncatedNum / multiplier;
498
- };
499
-
500
- /**
501
- * PREFIX - QUEMADOS POR INDICACIONES DE SARTIP
502
- */
503
- //TODO: Falta agregar los demás currencies
504
- export const CURRENCY_PREFIX = [
505
- { id: 1, code: "GTQ", prefix: "Q" },
506
- { id: 2, code: "USD", prefix: "$" },
507
- { id: 3, code: "LHN", prefix: "L" },
508
- { id: 12, code: "MXN", prefix: "$" },
509
- ];
510
-
511
- export const getRandomNum = (): number => {
512
- const randomNum = Math.random() * 10 + 1;
513
- return parseFloat(randomNum.toFixed(2));
514
- };
515
-
516
- //COMMONS DE LABORATORIO
517
- export const labServicePattern = /LAB_SERVICE_\d+;/g;
518
- export const labFormPatter = /LAB_FORM_\d+;/;
519
-
520
- export function capitalLetter(str: string = "") {
521
- if (str.length > 0) {
522
- return str.charAt(0).toUpperCase() + str.slice(1);
523
- }
524
- return str;
525
- }
526
-
527
- export const sortByProperty = (array: any[], property: string) => {
528
- // Crear una copia del array
529
- const arrayCopy = [...array];
530
- return arrayCopy.sort((a, b) => {
531
- if (a[property] > b[property]) {
532
- return 1;
533
- }
534
- if (a[property] < b[property]) {
535
- return -1;
536
- }
537
- return 0;
538
- });
539
- };
540
-
541
- /**
542
- * Handle web app table actions and return a response with a consistent format.
543
- * @param action A function that returns a Promise of type T.
544
- * @returns A Promise of AxiosUtilsResponse<T>.
545
- */
546
- export async function handlePossibleAxiosErrors<T>(
547
- action: () => Promise<T>
548
- ): Promise<AxiosUtilsResponse<T>> {
549
- try {
550
- const result = await action();
551
- return { error: false, data: result } as AxiosUtilsResponse<T>;
552
- } catch (error) {
553
- return { error: true, userMsg: error?.toString() } as AxiosUtilsResponse<T>;
554
- }
555
- }
1
+ import moment from "moment";
2
+ import "moment-timezone";
3
+ import type {
4
+ PayeeGraphQL,
5
+ AxiosUtilsResponse,
6
+ BasketSchema,
7
+ SelectFieldOption,
8
+ MonthsType,
9
+ } from "@zauru-sdk/types";
10
+ import { MONTHS } from "@zauru-sdk/types";
11
+
12
+ export const DESTINOS_MUESTRA_OPTIONS: SelectFieldOption[] = [
13
+ { label: "Microbiología", value: "microbiologa" },
14
+ { label: "Residuos de plaguicidas", value: "residuos_de_plaguicidas" },
15
+ ];
16
+
17
+ moment.locale("es");
18
+
19
+ /**
20
+ * Obtener el objeto de canastas en base al string de canastas
21
+ * @param basketsString
22
+ * @returns
23
+ */
24
+ export const getBasketsSchema = (basketsString: string): BasketSchema[] => {
25
+ //Sacar conteo de canastas y su descripción de colores
26
+ //ejemplo: vienen en un campo así: 8-53311-VERDE,3-53315-ROSADA,4-53313-ROJA
27
+ const splitedText = basketsString.split(",");
28
+ const baskets = splitedText.map((splited: string) => {
29
+ const values = splited.split("-");
30
+ return {
31
+ total: Number(values[0]) ?? 0,
32
+ id: Number(values[1]) ?? 0,
33
+ color: values[2] ?? "Sin Canasta",
34
+ } as BasketSchema;
35
+ });
36
+
37
+ return baskets;
38
+ };
39
+
40
+ export function generateClientUUID() {
41
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
42
+ const r = (Math.random() * 16) | 0,
43
+ v = c == "x" ? r : (r & 0x3) | 0x8;
44
+ return v.toString(16);
45
+ });
46
+ }
47
+
48
+ /**
49
+ * extractValueBetweenTags
50
+ * @param input
51
+ * @param tagName
52
+ * @returns
53
+ */
54
+ export function extractValueBetweenTags(
55
+ input: string,
56
+ tagName: string
57
+ ): string {
58
+ const regex = new RegExp(`<${tagName}[^>]*>(.*?)<\\/${tagName}>`, "i");
59
+ const match = input.match(regex);
60
+ return match ? match[1] : "";
61
+ }
62
+
63
+ /**
64
+ * isJsonArray
65
+ * @param value
66
+ * @returns
67
+ */
68
+ export function isJsonArray(value: string): boolean {
69
+ try {
70
+ const parsed = JSON.parse(value);
71
+ return Array.isArray(parsed);
72
+ } catch (e) {
73
+ return false;
74
+ }
75
+ }
76
+
77
+ /**
78
+ *
79
+ * @param date Recibe el date en formato UTC
80
+ */
81
+ export const getFechaJuliana = (date: string): string => {
82
+ function getDaysInMonth(month: number): number {
83
+ return new Date(new Date().getFullYear(), month, 0).getDate();
84
+ }
85
+
86
+ const getNumberOfDays = (month: number, day: number): number => {
87
+ let numberOfDays = day;
88
+
89
+ while (month > 0) {
90
+ const temp = getDaysInMonth(month);
91
+ numberOfDays += temp;
92
+ month--;
93
+ }
94
+
95
+ return numberOfDays;
96
+ };
97
+
98
+ const dt = moment(date).toDate();
99
+ const month = dt.getMonth();
100
+ const day = getNumberOfDays(month, dt.getDate());
101
+
102
+ return `${dt.getFullYear()}-${day}`;
103
+ };
104
+
105
+ /**
106
+ * Convierte una fecha de tipo 25 de jul de 2022 a Date
107
+ * @param date
108
+ * @returns
109
+ */
110
+ export const getNewDateByFormat = (date: string): Date => {
111
+ if (!date) {
112
+ return new Date();
113
+ }
114
+ const date_parts: string[] = date.split(" ");
115
+
116
+ const new_date = new Date(
117
+ parseInt(date_parts[4]),
118
+ MONTHS[date_parts[2] as keyof MonthsType],
119
+ parseInt(date_parts[0])
120
+ );
121
+ return new_date;
122
+ };
123
+
124
+ /**
125
+ * Convierte una fecha de tipo 25 de jul de 2022 a YYYY-MM-DD
126
+ * @param date
127
+ * @returns
128
+ */
129
+ export const getZauruDateByText = (date: string) => {
130
+ const newDate = getNewDateByFormat(date);
131
+ return getStringDate(newDate);
132
+ };
133
+
134
+ /**
135
+ * Convierte una fecha de tipo Date a YYYY-MM-DD
136
+ * @param date
137
+ * @returns
138
+ */
139
+ export const getStringDate = (date: Date) => {
140
+ const year = date.getFullYear();
141
+ const month = date.getMonth() + 1;
142
+ const day = date.getDay();
143
+ return `${year}-${month <= 9 ? `0${month}` : month}-${
144
+ day <= 9 ? `0${day}` : day
145
+ }`;
146
+ };
147
+
148
+ export function truncateText(text?: string, maxLength?: number) {
149
+ if (!text || !maxLength) {
150
+ return "";
151
+ }
152
+ // Verificar si el texto es más largo que maxLength
153
+ if (text.length > maxLength) {
154
+ // Si es así, truncar el texto y agregar "..."
155
+ return text.substring(0, maxLength - 3) + "...";
156
+ } else {
157
+ // Si no, devolver el texto completo
158
+ return text;
159
+ }
160
+ }
161
+
162
+ export const getTodayDaysDifference = (date: string): number => {
163
+ // Crear el objeto de Moment para la fecha de creación
164
+ const fechaCreacion = moment(date);
165
+ // Crear el objeto de Moment para la fecha actual
166
+ const ahora = moment();
167
+ // Calcular la diferencia en días
168
+ const diferencia = ahora.diff(fechaCreacion, "days");
169
+ return diferencia;
170
+ };
171
+
172
+ export const getTodayMinutesDifference = (date: string): number => {
173
+ // Crear el objeto de Moment para la fecha de creación
174
+ const fechaCreacion = moment(date);
175
+ // Crear el objeto de Moment para la fecha actual
176
+ const ahora = moment();
177
+ // Calcular la diferencia en minutos
178
+ const diferencia = ahora.diff(fechaCreacion, "minutes");
179
+ return diferencia;
180
+ };
181
+
182
+ /**
183
+ * Convierte una fecha de tipo Date a DD-MM-YYY HH:mm:ss
184
+ * @param date
185
+ * @returns
186
+ */
187
+ export const getStringFullDate = (date: Date) => {
188
+ const hour = date.getHours();
189
+ const minutes = date.getMinutes();
190
+ const seconds = date.getSeconds();
191
+ const year = date.getFullYear();
192
+ const month = date.getMonth() + 1;
193
+ const day = date.getDay();
194
+ return `${day <= 9 ? `0${day}` : day}-${
195
+ month <= 9 ? `0${month}` : month
196
+ }-${year} ${hour}:${minutes}:${seconds}`;
197
+ };
198
+
199
+ /**
200
+ * Convierte una fecha de tipo DD/MM/YYYY a YYYY/MM/DD
201
+ * @param dateStr
202
+ * @returns
203
+ */
204
+ export const localDateToUSDate = (dateStr: string) => {
205
+ const date = moment(dateStr, "DD/MM/YYYY");
206
+ const newDateStr = date.format("YYYY/MM/DD");
207
+ return newDateStr;
208
+ };
209
+
210
+ export const stringDateToParsedUTCDate = (date: string): Date => {
211
+ const issueDate = new Date(date);
212
+ issueDate.setMinutes(issueDate.getMinutes() - 360);
213
+ return issueDate;
214
+ };
215
+
216
+ /**
217
+ * zauruDateToLongString
218
+ * @param date
219
+ * @returns
220
+ */
221
+ export function zauruDateToLongString(date: string, hours: boolean = false) {
222
+ if (!date) {
223
+ return "invalid date:zauruDateToLongString";
224
+ }
225
+
226
+ // Asume que la fecha de entrada está en UTC y la convierte a la zona horaria local del navegador
227
+ const issueDate = moment.utc(date).local();
228
+
229
+ let formatString = "dddd, D [de] MMMM [de] YYYY";
230
+ if (hours) {
231
+ formatString += ", HH:mm a"; // Añade la hora en formato de 12 horas con AM/PM
232
+ }
233
+
234
+ // Formatea la fecha en el locale español
235
+ return issueDate.locale("es").format(formatString);
236
+ }
237
+
238
+ /**
239
+ * todayLongString
240
+ * @param date
241
+ * @returns
242
+ */
243
+ export function todayLongString(hours: boolean = false) {
244
+ // Analiza la fecha y hora sin ajustes de zona horaria
245
+ const issueDate = moment(new Date().toISOString());
246
+
247
+ let formatString = "dddd, D [de] MMMM [de] YYYY";
248
+ if (hours) {
249
+ formatString += ", HH:mm a"; // Añade la hora en formato de 12 horas con AM/PM
250
+ }
251
+
252
+ // Formatea la fecha en el locale español
253
+ return issueDate.locale("es").format(formatString);
254
+ }
255
+
256
+ export function isToday(dateStr: string): boolean {
257
+ // Parsea la fecha dada y la fecha actual a inicio del día (00:00:00)
258
+ const givenDate = moment(dateStr).startOf("day");
259
+ const today = moment().startOf("day");
260
+
261
+ // Compara si son iguales
262
+ return givenDate.isSame(today);
263
+ }
264
+
265
+ export const getDatePickerCurrentDate = () => {
266
+ const date = new Date();
267
+ const year = date.getFullYear();
268
+ const month = String(date.getMonth() + 1).padStart(2, "0"); // Los meses van de 0 a 11, por eso sumamos 1.
269
+ const day = String(date.getDate()).padStart(2, "0");
270
+
271
+ return `${year}-${month}-${day}`;
272
+ };
273
+
274
+ export const getTimePickerCurrentTime = () => {
275
+ const date = new Date();
276
+ const hours = String(date.getHours()).padStart(2, "0");
277
+ const minutes = String(date.getMinutes()).padStart(2, "0");
278
+
279
+ return `${hours}:${minutes}`;
280
+ };
281
+
282
+ export const getDateAfterDays = (daysAfterToday: number) => {
283
+ const date = new Date();
284
+ date.setDate(date.getDate() + daysAfterToday); // Agregamos el número de días a la fecha actual.
285
+
286
+ const year = date.getFullYear();
287
+ const month = String(date.getMonth() + 1).padStart(2, "0");
288
+ const day = String(date.getDate()).padStart(2, "0");
289
+
290
+ return `${year}-${month}-${day}`;
291
+ };
292
+
293
+ export const getPayeeFormated = (payee: PayeeGraphQL) => {
294
+ return `<${payee.id_number}> ${payee.tin ? `${payee.tin} | ` : ""}${
295
+ payee.name
296
+ }`;
297
+ };
298
+
299
+ export const getPayeeInfoOptions = (
300
+ payees: PayeeGraphQL[]
301
+ ): (SelectFieldOption & { id: number })[] => {
302
+ return payees.map((x) => {
303
+ return {
304
+ label: `<${x.id_number}> ${x.tin ? `${x.tin} | ` : ""}${x.name}`,
305
+ value: `<${x.id_number}> ${x.tin ? `${x.tin} | ` : ""}${x.name}`,
306
+ id: x.id,
307
+ } as SelectFieldOption & { id: number };
308
+ });
309
+ };
310
+
311
+ export const parsedBaculoFormValue = (value: any) => {
312
+ if (value === "false") {
313
+ return "No";
314
+ } else if (value === "true") {
315
+ return "Si";
316
+ } else if (DESTINOS_MUESTRA_OPTIONS.some((x) => x.value === value)) {
317
+ return DESTINOS_MUESTRA_OPTIONS.find((x) => x.value === value)?.label;
318
+ }
319
+
320
+ return capitalLetter(value);
321
+ };
322
+
323
+ export function extractIdFromForm(s: string): number | null {
324
+ const match = s.match(/LAB_FORM_(\d+);/);
325
+ if (match && match[1]) {
326
+ return parseInt(match[1], 10);
327
+ }
328
+ return null;
329
+ }
330
+
331
+ /**
332
+ * Formatea una fecha de tipo YYYY-MM-DD a 2023-08-07T20:56:00.540245
333
+ * @param dateString
334
+ * @returns
335
+ */
336
+ export function formatDateToUTC(dateString: string): string {
337
+ const date = new Date(dateString);
338
+
339
+ const year = date.getUTCFullYear();
340
+ const month = String(date.getUTCMonth() + 1).padStart(2, "0");
341
+ const day = String(date.getUTCDate()).padStart(2, "0");
342
+ const hours = String(date.getUTCHours()).padStart(2, "0");
343
+ const minutes = String(date.getUTCMinutes()).padStart(2, "0");
344
+ const seconds = String(date.getUTCSeconds()).padStart(2, "0");
345
+ const milliseconds = String(date.getUTCMilliseconds()).padStart(3, "0");
346
+
347
+ return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${milliseconds}`;
348
+ }
349
+
350
+ export const formatDateToDatePicker = (date: Date) => {
351
+ const year = date.getFullYear();
352
+ const month = `0${date.getMonth() + 1}`.slice(-2); // Los meses van de 0 a 11, así que le sumamos 1
353
+ const day = `0${date.getDate()}`.slice(-2);
354
+
355
+ return `${year}-${month}-${day}`;
356
+ };
357
+
358
+ export const formatTimeToTimePicker = (timeString: string) => {
359
+ const [hours, minutes] = timeString.split(":").map(Number);
360
+
361
+ const date = new Date();
362
+ date.setHours(hours, minutes, 0, 0); // Establecemos las horas y minutos, y reseteamos segundos y milisegundos
363
+
364
+ return date;
365
+ };
366
+
367
+ export const toFixedIfNeeded = (value: number) => {
368
+ if (!value) {
369
+ return "0";
370
+ }
371
+
372
+ if (Number.isInteger(value)) {
373
+ return value.toString().replace(".00", "");
374
+ }
375
+
376
+ const decimals = (value.toString().split(".")[1] || []).length;
377
+
378
+ const decimal = decimals > 2 ? value.toFixed(2) : value.toString();
379
+
380
+ return decimal.replace(".00", "");
381
+ };
382
+
383
+ export const isNumeric = (value: any) => {
384
+ return !isNaN(value) && !isNaN(parseFloat(value));
385
+ };
386
+
387
+ export function incrementString(str: string): string {
388
+ // Encuentra la parte numérica de la cadena usando una expresión regular
389
+ const match = str.match(/(\D*)(\d+)$/);
390
+ if (!match) {
391
+ throw new Error("Formato de cadena no válido");
392
+ }
393
+
394
+ const prefix = match[1];
395
+ const numberPart = match[2];
396
+
397
+ // Incrementa el número
398
+ const incrementedNumber = parseInt(numberPart, 10) + 1;
399
+
400
+ // Convierte el número incrementado de nuevo en una cadena y rellena con ceros
401
+ const incrementedString = incrementedNumber
402
+ .toString()
403
+ .padStart(numberPart.length, "0");
404
+
405
+ return prefix + incrementedString;
406
+ }
407
+
408
+ export function getParsedIdFromString(inputString: string): number {
409
+ const regex = /<(\d+)>/; // Expresión regular para encontrar el número entre los corchetes
410
+
411
+ const match = inputString.match(regex); // Buscar la coincidencia en el string
412
+
413
+ let number = 0;
414
+ if (match && match[1]) {
415
+ number = parseInt(match[1]); // Convertir el número de string a entero
416
+ //console.log(number); // Mostrar el número en la consola
417
+ } else {
418
+ console.log("No se encontró ningún número entre corchetes.");
419
+ }
420
+
421
+ return number;
422
+ }
423
+
424
+ export const arrayToObject = (
425
+ arr: Array<any> = [],
426
+ options?: { withOutId?: boolean }
427
+ ): { [key: string]: any } => {
428
+ return arr.reduce((acc, cur, idx) => {
429
+ const tempVal = cur;
430
+ if (options?.withOutId) {
431
+ delete tempVal.id;
432
+ }
433
+ acc[idx.toString()] = tempVal;
434
+ return acc;
435
+ }, {});
436
+ };
437
+
438
+ export function convertToFormData(obj: any) {
439
+ const formData = new FormData();
440
+
441
+ function appendFormData(data: any, root = "") {
442
+ if (data && typeof data === "object" && !(data instanceof File)) {
443
+ for (const key in data) {
444
+ if (data.hasOwnProperty(key)) {
445
+ if (root === "") {
446
+ // Append nested objects
447
+ if (data[key] != undefined && data[key] != null)
448
+ appendFormData(data[key], key);
449
+ } else {
450
+ // Append data with namespaced keys for nested objects
451
+ if (data[key] != undefined && data[key] != null)
452
+ appendFormData(data[key], `${root}[${key}]`);
453
+ }
454
+ }
455
+ }
456
+ } else {
457
+ if (data instanceof File) {
458
+ formData.append(root, data, data.name);
459
+ } else {
460
+ formData.append(root, data);
461
+ }
462
+ }
463
+ }
464
+
465
+ appendFormData(obj);
466
+ return formData;
467
+ }
468
+
469
+ export const ZAURU_REGEX = {
470
+ porcentaje: /^\d{1,2}(\.\d{1,2})?$/,
471
+ };
472
+
473
+ /**
474
+ * Para hacer sumas en los reduce de arreglos enteros
475
+ * @param accumulator
476
+ * @param a
477
+ * @returns
478
+ */
479
+ export function reduceAdd(accumulator: number, a: number) {
480
+ return accumulator + a;
481
+ }
482
+
483
+ /**
484
+ * Truncar decimales, ejemplo: truncateDecimals(43.434340934, 2) => 43.43
485
+ * @param number
486
+ * @param digits
487
+ * @returns
488
+ */
489
+ export const truncateDecimals = function (
490
+ number: number,
491
+ digits: number
492
+ ): number {
493
+ const multiplier = Math.pow(10, digits),
494
+ adjustedNum = number * multiplier,
495
+ truncatedNum = Math[adjustedNum < 0 ? "ceil" : "floor"](adjustedNum);
496
+
497
+ return truncatedNum / multiplier;
498
+ };
499
+
500
+ /**
501
+ * PREFIX - QUEMADOS POR INDICACIONES DE SARTIP
502
+ */
503
+ //TODO: Falta agregar los demás currencies
504
+ export const CURRENCY_PREFIX = [
505
+ { id: 1, code: "GTQ", prefix: "Q" },
506
+ { id: 2, code: "USD", prefix: "$" },
507
+ { id: 3, code: "LHN", prefix: "L" },
508
+ { id: 12, code: "MXN", prefix: "$" },
509
+ ];
510
+
511
+ export const getRandomNum = (): number => {
512
+ const randomNum = Math.random() * 10 + 1;
513
+ return parseFloat(randomNum.toFixed(2));
514
+ };
515
+
516
+ //COMMONS DE LABORATORIO
517
+ export const labServicePattern = /LAB_SERVICE_\d+;/g;
518
+ export const labFormPatter = /LAB_FORM_\d+;/;
519
+
520
+ export function capitalLetter(str: string = "") {
521
+ if (str.length > 0) {
522
+ return str.charAt(0).toUpperCase() + str.slice(1);
523
+ }
524
+ return str;
525
+ }
526
+
527
+ export const sortByProperty = (array: any[], property: string) => {
528
+ // Crear una copia del array
529
+ const arrayCopy = [...array];
530
+ return arrayCopy.sort((a, b) => {
531
+ if (a[property] > b[property]) {
532
+ return 1;
533
+ }
534
+ if (a[property] < b[property]) {
535
+ return -1;
536
+ }
537
+ return 0;
538
+ });
539
+ };
540
+
541
+ /**
542
+ * Handle web app table actions and return a response with a consistent format.
543
+ * @param action A function that returns a Promise of type T.
544
+ * @returns A Promise of AxiosUtilsResponse<T>.
545
+ */
546
+ export async function handlePossibleAxiosErrors<T>(
547
+ action: () => Promise<T>
548
+ ): Promise<AxiosUtilsResponse<T>> {
549
+ try {
550
+ const result = await action();
551
+ return { error: false, data: result } as AxiosUtilsResponse<T>;
552
+ } catch (error) {
553
+ return { error: true, userMsg: error?.toString() } as AxiosUtilsResponse<T>;
554
+ }
555
+ }