npm-pkg-hook 1.9.7 → 1.9.9

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/package.json CHANGED
@@ -47,5 +47,5 @@
47
47
  "rm": "rm -rf node_modules package-lock.json && npm i",
48
48
  "test": "echo \"Error: no test specified\" && exit 1"
49
49
  },
50
- "version": "1.9.7"
50
+ "version": "1.9.9"
51
51
  }
@@ -54,7 +54,7 @@ export class GenerateReport {
54
54
  */
55
55
  GenExcelReportFileName (type) {
56
56
  const fileNames = {
57
- 1: 'report.xlsx'
57
+ 1: `report_${new Date().toISOString().replace(/[:.]/g, '-')}.xlsx`
58
58
  }
59
59
 
60
60
  return fileNames[type] ? fileNames[type] : null
@@ -22,6 +22,7 @@ export * from './useUploadProducts'
22
22
  export * from './useAmountInput'
23
23
  export * from './useColorByLetters'
24
24
  export * from './newMessageSubscription'
25
+ export * from './usePWAInstall'
25
26
  export * from './useGetCookies'
26
27
  export * from './generateTemplate'
27
28
  export * from './isTokenExpired'
@@ -5,6 +5,8 @@ import { CREATE_ONE_EMPLOYEE_STORE_AND_USER } from './queries'
5
5
  /**
6
6
  * Custom hook to handle the createOneEmployeeStoreAndUser mutation.
7
7
  *
8
+ * @param
9
+ * @param {Object}
8
10
  * @returns {{
9
11
  * createEmployeeStoreAndUser: (input: IEmployeeStore) => Promise<void>,
10
12
  * loading: boolean,
@@ -23,15 +25,29 @@ export const useCreateEmployeeStoreAndUser = ({
23
25
  onCompleted = () => {
24
26
  return {
25
27
  }
28
+ },
29
+ onError = () => {
30
+ return {
31
+ }
26
32
  }
27
33
  } = {}) => {
28
34
  const [createEmployeeStoreAndUserMutation, { loading, error, data }] = useMutation(CREATE_ONE_EMPLOYEE_STORE_AND_USER, {
35
+ onError: () => {
36
+ sendNotification({
37
+ description: 'Error creando empleado',
38
+ title: 'Error',
39
+ backgroundColor: 'error'
40
+ })
41
+ },
29
42
  onCompleted: (response) => {
30
43
  console.log(response)
31
44
  const { createOneEmployeeStoreAndUser } = response ?? {}
32
45
  const { message, success } = createOneEmployeeStoreAndUser ?? {}
46
+ if (success === false) {
47
+ onError(response)
48
+ }
33
49
  if (success) {
34
- onCompleted()
50
+ onCompleted(response)
35
51
  }
36
52
  sendNotification({
37
53
  description: message,
@@ -60,8 +60,8 @@ export const useFormTools = ({
60
60
  }
61
61
  if (errSub) {
62
62
  sendNotification({
63
- title: 'Completa los campos requeridos',
64
- description: 'Error',
63
+ description: 'Completa los campos requeridos',
64
+ title: 'Error',
65
65
  backgroundColor: 'error'
66
66
  })
67
67
  }
@@ -0,0 +1,38 @@
1
+ import { useState, useEffect } from 'react';
2
+
3
+ export const usePWAInstall = () => {
4
+ const [deferredPrompt, setDeferredPrompt] = useState(null);
5
+ const [isInstallable, setIsInstallable] = useState(false);
6
+
7
+ useEffect(() => {
8
+ const handleBeforeInstallPrompt = (e) => {
9
+ e.preventDefault(); // Evita que el navegador muestre el diálogo automáticamente
10
+ setDeferredPrompt(e); // Almacena el evento para que puedas llamarlo más tarde
11
+ setIsInstallable(true); // Marca que la PWA es instalable
12
+ };
13
+
14
+ window.addEventListener('beforeinstallprompt', handleBeforeInstallPrompt);
15
+
16
+ return () => {
17
+ window.removeEventListener('beforeinstallprompt', handleBeforeInstallPrompt);
18
+ };
19
+ }, []);
20
+
21
+ const installPWA = () => {
22
+ if (deferredPrompt) {
23
+ deferredPrompt.prompt();
24
+
25
+ deferredPrompt.userChoice.then((choiceResult) => {
26
+ if (choiceResult.outcome === 'accepted') {
27
+ console.log('User accepted the install prompt');
28
+ } else {
29
+ console.log('User dismissed the install prompt');
30
+ }
31
+ setDeferredPrompt(null); // Limpia el evento después de usarlo
32
+ setIsInstallable(false); // Oculta el botón de instalación
33
+ });
34
+ }
35
+ };
36
+
37
+ return { isInstallable, installPWA };
38
+ };
@@ -1,17 +1,20 @@
1
1
  import { useMutation } from '@apollo/client'
2
2
  import { UPDATE_MULTIPLE_PRODUCTS } from './queries'
3
- import { CATEGORY_EMPTY, RandomCode } from '../../utils/index'
3
+ import { CATEGORY_EMPTY } from '../../utils/index'
4
4
  import { useCategoriesProduct } from '../useCategoriesProduct'
5
5
 
6
6
  export const useUpdateMultipleProducts = ({
7
7
  sendNotification = () => { }
8
8
  }) => {
9
- const [updateMultipleProducts, { data, loading, error }] = useMutation(UPDATE_MULTIPLE_PRODUCTS)
9
+ const [updateMultipleProducts, {
10
+ data,
11
+ loading,
12
+ error
13
+ }] = useMutation(UPDATE_MULTIPLE_PRODUCTS)
10
14
  const [dataCategoriesProducts] = useCategoriesProduct()
11
15
  const findEmptyCategory = dataCategoriesProducts?.find(category => category.pName === CATEGORY_EMPTY)
12
16
  const updateProducts = async (products) => {
13
17
  const newProducts = products.map(product => {
14
- const code = RandomCode(9)
15
18
  return {
16
19
  idStore: '',
17
20
  ProPrice: product.PRECIO_AL_PUBLICO,
@@ -19,12 +22,12 @@ export const useUpdateMultipleProducts = ({
19
22
  ValueDelivery: 0,
20
23
  ProDescription: product.DESCRIPCION,
21
24
  pName: product.NOMBRE,
22
- pCode: code,
25
+ pCode: product.pCode,
23
26
  carProId: findEmptyCategory?.carProId ?? null,
24
27
  pState: 1,
25
28
  sTateLogistic: 1,
26
29
  ProStar: 0,
27
- ProImage: 'https:http://localhost:8080',
30
+ ProImage: null,
28
31
  ProHeight: null,
29
32
  ProWeight: '',
30
33
  ProOutstanding: 0,
@@ -0,0 +1 @@
1
+ export * from './parseNumber'
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Parses a formatted number (string or number) and converts it into a float with two decimal places.
3
+ * @param {string|number} value - The number to parse (e.g., "1.500,00", "1500.00", 1500).
4
+ * @returns {string} Parsed number as a string in the format "1500.00".
5
+ * @throws Will throw an error if the input is not a valid formatted number.
6
+ */
7
+ export const parseNumber = (value) => {
8
+ // Convert value to string if it's a number
9
+ const stringValue = typeof value === 'number' ? value.toString() : value
10
+
11
+ if (typeof stringValue !== 'string') {
12
+ throw new Error('Input must be a string or number')
13
+ }
14
+
15
+ // Remove thousands separators and adjust decimal separator
16
+ const sanitizedValue = stringValue
17
+ .replace(/\./g, '') // Removes thousands separators (.)
18
+ .replace(',', '.') // Changes comma to period for decimal
19
+
20
+ // Parse the sanitized value as a float
21
+ const parsedNumber = parseFloat(sanitizedValue)
22
+ if (isNaN(parsedNumber)) {
23
+ throw new Error('Invalid number format')
24
+ }
25
+
26
+ // Format the number with two decimal places
27
+ return parsedNumber.toFixed(2)
28
+ }
29
+
30
+ // Example usage:
31
+ console.log(parseNumber('1.500,00')) // "1500.00"
32
+ console.log(parseNumber('1500.00')) // "1500.00"
33
+ console.log(parseNumber('1,500.50')) // "1500.50"
34
+ console.log(parseNumber('500')) // "500.00"
35
+ console.log(parseNumber('0,50')) // "0.50"
36
+ console.log(parseNumber(1500)) // "1500.00"
37
+ console.log(parseNumber(1500.5)) // "1500.50"
@@ -1,15 +1,24 @@
1
1
  import { useState } from 'react'
2
2
  import * as XLSX from 'xlsx'
3
+ import { RandomCode } from '../../utils'
3
4
 
4
- export const useUploadProducts = () => {
5
- const [data, setData] = useState([])
5
+ const STEPS = {
6
+ UPLOAD_FILE: 0,
7
+ UPLOAD_PRODUCTS: 1
8
+ }
6
9
 
7
- const [active, setActive] = useState(0)
8
- const [overActive, setOverActive] = useState(0)
10
+ export const useUploadProducts = ({
11
+ sendNotification = () => { return null }
12
+ } = {}) => {
13
+ const [data, setData] = useState([])
14
+ const [isLoading, setIsLoading] = useState(false)
15
+ const [active, setActive] = useState(STEPS.UPLOAD_FILE)
16
+ const [overActive, setOverActive] = useState(STEPS.UPLOAD_FILE)
9
17
 
10
18
  const handleOverActive = (index) => {
11
19
  setOverActive(index)
12
20
  }
21
+
13
22
  const readExcelFile = (file) => {
14
23
  return new Promise((resolve, reject) => {
15
24
  const reader = new FileReader()
@@ -27,17 +36,351 @@ export const useUploadProducts = () => {
27
36
  }
28
37
 
29
38
  const onChangeFiles = async (files) => {
30
- const filePromises = Array.from(files).map(file => readExcelFile(file))
31
- const data = await Promise.all(filePromises)
32
- setData(data.flat())
39
+ setIsLoading(true) // Activa el loader al inicio
40
+ try {
41
+ const filePromises = Array.from(files).map(file => readExcelFile(file))
42
+ const newData = await Promise.all(filePromises)
43
+
44
+ const newProducts = newData.flat().map((product) => {
45
+ const PRECIO_AL_PUBLICO = isNaN(product.PRECIO_AL_PUBLICO) ? 0.00 : product.PRECIO_AL_PUBLICO
46
+ const VALOR_DE_COMPRA = isNaN(product.VALOR_DE_COMPRA) ? 0.00 : product.VALOR_DE_COMPRA
47
+ const code = RandomCode(9)
48
+ return {
49
+ ...product,
50
+ CANTIDAD: isNaN(product.CANTIDAD) ? 1 : product.CANTIDAD,
51
+ ORIGINAL_CANTIDAD: isNaN(product.CANTIDAD) ? 1 : product.CANTIDAD,
52
+ free: false,
53
+ pCode: code,
54
+ editing: false,
55
+ PRECIO_AL_PUBLICO,
56
+ VALOR_DE_COMPRA
57
+ }
58
+ })
59
+
60
+ // Validar el número total de productos antes de actualizar el estado
61
+ setData(prevData => {
62
+ const currentLength = prevData.length
63
+ const totalProducts = currentLength + newProducts.length
64
+
65
+ if (totalProducts > 100) {
66
+ sendNotification({
67
+ description: 'Cannot add more products. You have reached the 100-product limit.',
68
+ title: 'Error',
69
+ backgroundColor: 'error'
70
+ })
71
+
72
+ // Calcular la cantidad de productos que se pueden agregar sin exceder el límite
73
+ const remainingSlots = 100 - currentLength
74
+ const productsToAdd = newProducts.slice(0, remainingSlots)
75
+ return [...prevData, ...productsToAdd]
76
+ } else {
77
+ // Agregar todos los nuevos productos si no se excede el límite
78
+ return [...prevData, ...newProducts]
79
+ }
80
+ })
81
+ } catch (error) {
82
+ sendNotification({
83
+ description: 'Un errro a ocurrido mientras se cargaba el archivo de productos.',
84
+ title: 'Error',
85
+ backgroundColor: 'error'
86
+ })
87
+ } finally {
88
+ setIsLoading(false)
89
+ }
90
+ }
91
+
92
+ const handleSetActive = (index) => {
93
+ if (typeof index !== 'number' || index < 0 || index >= Object.keys(STEPS).length) {
94
+ sendNotification({
95
+ description: 'Invalid step index',
96
+ title: 'Error',
97
+ backgroundColor: 'error'
98
+ })
99
+ return
100
+ }
101
+ if (active === STEPS.UPLOAD_FILE && Boolean(!data.length)) return setActive(0)
102
+ if (active === STEPS.UPLOAD_FILE && Boolean(data.length)) return setActive(STEPS.UPLOAD_PRODUCTS)
33
103
  }
34
104
 
105
+ const updateProductQuantity = (index, quantityChange) => {
106
+ // Validar el índice
107
+ if (index < 0 || index >= data.length) {
108
+ console.warn('Invalid product index:', index)
109
+ return
110
+ }
111
+
112
+ const newData = [...data]
113
+ const newQuantity = newData[index].CANTIDAD + quantityChange
114
+
115
+ // Actualizar la cantidad solo si es mayor o igual a 0
116
+ if (newQuantity < 0) {
117
+ console.warn('Quantity cannot be negative, no update performed.')
118
+ return // No permitir cantidades negativas
119
+ }
120
+
121
+ // Actualizar la cantidad
122
+ newData[index].CANTIDAD = newQuantity
123
+ newData[index].ORIGINAL_CANTIDAD = newQuantity
124
+ // Eliminar el producto si la nueva cantidad es 0
125
+ if (newData[index].CANTIDAD === 0) {
126
+ newData.splice(index, 1)
127
+
128
+ // Verificar si no quedan más productos
129
+ if (newData.length === 0) {
130
+ setActive(STEPS.UPLOAD_FILE) // Restablecer el estado activo a 0 si no hay productos
131
+ }
132
+ }
133
+
134
+ setData(newData)
135
+ }
136
+ /**
137
+ * Toggle the 'free' status of a specific product in the data array.
138
+ * Performs validation to ensure the product index is valid.
139
+ *
140
+ * @param {number} productIndex - The index of the product to update.
141
+ */
142
+ const handleCheckFree = (productIndex) => {
143
+ setData((prevData) => {
144
+ // Validar que el índice es un número válido
145
+ if (typeof productIndex !== 'number' || productIndex < 0 || productIndex >= prevData.length) {
146
+ console.warn('Invalid product index:', productIndex)
147
+ return prevData // Retorna el estado anterior si el índice es inválido
148
+ }
149
+
150
+ // Validar que el producto existe y que tiene la propiedad 'free'
151
+ const product = prevData[productIndex]
152
+ if (!product || typeof product.free === 'undefined') {
153
+ console.warn('Product or "free" property not found for index:', productIndex)
154
+ return prevData // Retorna el estado anterior si no se encuentra el producto
155
+ }
156
+
157
+ // Evitar cambios innecesarios si el estado de 'free' no cambia
158
+ const updatedFreeStatus = !product.free
159
+ if (product.free === updatedFreeStatus) {
160
+ console.info('Product "free" status is already:', updatedFreeStatus)
161
+ return prevData // No actualiza si el estado es el mismo
162
+ }
163
+
164
+ // Crear una nueva copia de los datos actualizando solo el producto específico
165
+ return prevData.map((product, index) =>
166
+ index === productIndex
167
+ ? {
168
+ ...product,
169
+ free: updatedFreeStatus,
170
+ PRECIO_AL_PUBLICO: updatedFreeStatus ? 0 : product.oldPrice,
171
+ oldPrice: product.PRECIO_AL_PUBLICO
172
+ }
173
+ : product
174
+ )
175
+ })
176
+ }
177
+ const handleCleanAllProducts = () => {
178
+ setData([])
179
+ setActive(STEPS.UPLOAD_FILE)
180
+ }
181
+ /**
182
+ * Toggle the 'editing' status of a specific product in the data array.
183
+ * Validates the product index and only updates if necessary.
184
+ *
185
+ * @param {number} productIndex - The index of the product to update.
186
+ */
187
+ const handleToggleEditingStatus = (productIndex) => {
188
+ setData((prevData) => {
189
+ // Validar que el índice es un número válido
190
+ if (typeof productIndex !== 'number' || productIndex < 0 || productIndex >= prevData.length) {
191
+ console.warn('Invalid product index:', productIndex)
192
+ return prevData // Retorna el estado anterior si el índice es inválido
193
+ }
194
+
195
+ // Validar que el producto existe y tiene la propiedad 'editing'
196
+ const product = prevData[productIndex]
197
+ if (!product || typeof product.editing === 'undefined') {
198
+ console.warn('Product or "editing" property not found for index:', productIndex)
199
+ return prevData // Retorna el estado anterior si no se encuentra el producto
200
+ }
201
+
202
+ // Evitar cambios innecesarios si el estado de 'editing' no cambia
203
+ const updatedEditingStatus = !product.editing
204
+ if (product.editing === updatedEditingStatus) {
205
+ console.info('Product "editing" status is already:', updatedEditingStatus)
206
+ return prevData // No actualiza si el estado es el mismo
207
+ }
208
+
209
+ // Crear una nueva copia de los datos actualizando solo el producto específico
210
+ return prevData.map((product, index) => {
211
+ console.log(index === productIndex)
212
+ return index === productIndex
213
+ ? {
214
+ ...product,
215
+ editing: updatedEditingStatus
216
+ }
217
+ : product
218
+ }
219
+ )
220
+ })
221
+ }
222
+
223
+ /**
224
+ * Confirm and update the quantity of a product in the data array.
225
+ * Only updates when the button is clicked.
226
+ *
227
+ * @param {number} productIndex - The index of the product to update.
228
+ */
229
+ const handleSuccessUpdateQuantity = (productIndex) => {
230
+ setData((prevData) => {
231
+ // Validar que `CANTIDAD` sea un número entero
232
+ const product = prevData[productIndex]
233
+ if (!Number.isInteger(product?.CANTIDAD)) {
234
+ sendNotification({
235
+ description: 'Quantity must be an integer value.',
236
+ title: 'Error',
237
+ backgroundColor: 'error'
238
+ })
239
+ return prevData // Retorna el estado anterior si `CANTIDAD` no es entero
240
+ }
241
+
242
+ // Crear una copia actualizada de prevData donde se actualiza `CANTIDAD` si es necesario
243
+ const updatedData = prevData.map((product, index) =>
244
+ index === productIndex
245
+ ? { ...product, editing: false, ORIGINAL_CANTIDAD: product.CANTIDAD } // Actualización o cambio de estado
246
+ : product
247
+ )
248
+
249
+ // Filtrar productos con CANTIDAD mayor a 0
250
+ const filteredData = updatedData.filter(product => product.CANTIDAD > 0)
251
+
252
+ // Cambiar el estado a `STEPS.UPLOAD_FILE` si no quedan productos
253
+ if (filteredData.length === 0) {
254
+ setActive(STEPS.UPLOAD_FILE)
255
+ }
256
+
257
+ return filteredData
258
+ })
259
+
260
+ sendNotification({
261
+ description: `Quantity updated successfully for product index ${productIndex}`,
262
+ title: 'Success',
263
+ backgroundColor: 'success'
264
+ })
265
+ }
266
+
267
+ const handleChangeQuantity = (event, productIndex) => {
268
+ const { value } = event.target
269
+ setData((prevData) => {
270
+ if (typeof productIndex !== 'number' || productIndex < 0 || productIndex >= prevData.length) {
271
+ console.warn('Invalid product index:', productIndex)
272
+ return prevData // Retorna el estado anterior si el índice es inválido
273
+ }
274
+
275
+ // Obtener la cantidad temporal para el producto
276
+ const newQuantity = value
277
+ if (isNaN(newQuantity) || newQuantity < 0) {
278
+ console.warn('Quantity must be a valid non-negative number.')
279
+ return prevData // Retorna sin cambios si la cantidad no es válida
280
+ }
281
+
282
+ // Actualiza el array `data` con la nueva cantidad
283
+ return prevData.map((product, index) =>
284
+ index === productIndex
285
+ ? { ...product, CANTIDAD: newQuantity }
286
+ : product
287
+ )
288
+ })
289
+ }
290
+ /**
291
+ * Restore the 'CANTIDAD' value to 'ORIGINAL_CANTIDAD' for a specific product.
292
+ * Validates the product index and only updates if necessary.
293
+ *
294
+ * @param {number} productIndex - The index of the product to restore quantity for.
295
+ */
296
+ const handleCancelUpdateQuantity = (productIndex) => {
297
+ setData((prevData) => {
298
+ // Validar que el índice es un número válido
299
+ if (typeof productIndex !== 'number' || productIndex < 0 || productIndex >= prevData.length) {
300
+ console.warn('Invalid product index:', productIndex)
301
+ return prevData // Retorna el estado anterior si el índice es inválido
302
+ }
303
+
304
+ // Validar que el producto existe y tiene las propiedades 'CANTIDAD' y 'ORIGINAL_CANTIDAD'
305
+ const product = prevData[productIndex]
306
+ if (!product || typeof product.ORIGINAL_CANTIDAD === 'undefined') {
307
+ console.warn('Product or "ORIGINAL_CANTIDAD" property not found for index:', productIndex)
308
+ return prevData // Retorna el estado anterior si no se encuentra el producto o propiedad
309
+ }
310
+
311
+ // Crear una nueva copia de los datos actualizando solo el producto específico
312
+ return prevData.map((product, index) =>
313
+ index === productIndex
314
+ ? { ...product, CANTIDAD: product.ORIGINAL_CANTIDAD, editing: false }
315
+ : product
316
+ )
317
+ })
318
+ }
319
+ /**
320
+ * Filters products with a quantity of 0 or less from the data array.
321
+ * Sends a notification if any products are found with invalid quantities.
322
+ */
323
+ const filterInvalidQuantityProducts = () => {
324
+ setData((prevData) => {
325
+ // Filtrar productos con `CANTIDAD` mayor a 0
326
+ const validProducts = prevData.filter(product => product.CANTIDAD > 0)
327
+
328
+ // Notificar si hubo productos con cantidad no válida
329
+ if (validProducts.length < prevData.length) {
330
+ sendNotification({
331
+ description: 'Some products had a quantity of 0 or less and were removed.',
332
+ title: 'Invalid Products Removed',
333
+ backgroundColor: 'warning'
334
+ })
335
+ }
336
+
337
+ return validProducts
338
+ })
339
+ }
340
+
341
+ /**
342
+ * Compares uploaded products against response data to determine which were successfully uploaded.
343
+ * @param {Array} data - Original array of products with their details.
344
+ * @param {Array} response - Array of response objects from the `updateProducts` function.
345
+ * @returns {Object} Object containing arrays of successfully and unsuccessfully uploaded products.
346
+ */
347
+ const getUploadResults = (data, response) => {
348
+ const uploadedCodes = new Set(
349
+ response
350
+ .filter((product) => product.success)
351
+ .map((product) => product.data.pCode)
352
+ )
353
+
354
+ const successfullyUploaded = data.filter((product) =>
355
+ uploadedCodes.has(product.pCode)
356
+ )
357
+
358
+ const failedUploads = data.filter(
359
+ (product) => !uploadedCodes.has(product.pCode)
360
+ )
361
+
362
+ return {
363
+ successfullyUploaded,
364
+ failedUploads
365
+ }
366
+ }
35
367
  return {
36
368
  active,
369
+ STEPS,
370
+ isLoading,
37
371
  data,
38
372
  overActive,
39
373
  handleOverActive,
374
+ handleCheckFree,
375
+ getUploadResults,
40
376
  onChangeFiles,
41
- setActive
377
+ handleChangeQuantity,
378
+ handleCancelUpdateQuantity,
379
+ handleToggleEditingStatus,
380
+ filterInvalidQuantityProducts,
381
+ handleSuccessUpdateQuantity,
382
+ updateProductQuantity,
383
+ handleCleanAllProducts,
384
+ setActive: handleSetActive
42
385
  }
43
386
  }
package/src/index.jsx CHANGED
@@ -2,3 +2,6 @@ export * from './hooks/index'
2
2
  export * from './utils'
3
3
  export * from './cookies'
4
4
  export * from './security/index'
5
+
6
+ // version
7
+ export { version } from '../package.json'