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