@zauru-sdk/utils 1.0.9 → 1.0.13

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