@zauru-sdk/common 1.0.6

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