npm-pkg-hook 1.7.0 → 1.7.3

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
@@ -44,5 +44,5 @@
44
44
  "rm": "rm -rf node_modules package-lock.json && npm i",
45
45
  "test": "echo \"Error: no test specified\" && exit 1"
46
46
  },
47
- "version": "1.7.0"
47
+ "version": "1.7.3"
48
48
  }
@@ -92,7 +92,7 @@ export const statusOpenStores = ({
92
92
  if (findNextDay && findDataNextDay?.schHoSta) {
93
93
  const nameOfDayTomorrow = weekDays[dayOfWeekTomorrow]
94
94
  return handleState(
95
- `Cerrado - Mañana ${nameOfDayTomorrow} ${!!findDataNextDay?.schHoSta && 'a las'} ${
95
+ `Cerrado abre - Mañana ${nameOfDayTomorrow} ${!!findDataNextDay?.schHoSta && 'a las'} ${
96
96
  findDataNextDay?.schHoSta ? findDataNextDay?.schHoSta : ''
97
97
  }`,
98
98
  false
@@ -11,23 +11,36 @@ import { calculateTotalPrice } from './helpers'
11
11
  import { statusOpenStores } from '../statusOpenStores'
12
12
  export * from './helpers'
13
13
 
14
- /**
15
- * Custom hook for managing the shopping cart functionality.
16
- * @param {Object} props - Props to control various UI elements.
17
- * @param {function} props.setCountItemProduct - Function to set the count of items in the cart.
18
- * @param {function} props.setAlertBox - Function to set an alert message.
19
- * @param {function} props.handleMenu - Function to handle cart menu visibility.
20
- * @returns {Object} An object with various shopping cart-related functions and data.
21
- */
22
14
  export const useAsideCart = ({
23
15
  openModalProduct = false,
24
- location = {},
16
+ location = {
17
+ pathname: '',
18
+ push: (props, state, { shallow }) => {
19
+ return { ...props, state, shallow }
20
+ },
21
+ query: {
22
+ plato: ''
23
+ }
24
+ },
25
25
  setCountItemProduct = (number) => { return number },
26
- setAlertBox = () => { },
26
+ setAlertBox = (args) => { return args },
27
27
  setOpenModalProduct = () => { },
28
- handleMenu = () => { }
28
+ handleMenu = (boolean) => { return boolean }
29
29
  } = {
30
-
30
+ openModalProduct: false,
31
+ location: {
32
+ pathname: '',
33
+ push: (props, state, { shallow }) => {
34
+ return { ...props, state, shallow }
35
+ },
36
+ query: {
37
+ plato: ''
38
+ }
39
+ },
40
+ setCountItemProduct: (number) => { return number },
41
+ setAlertBox: () => { },
42
+ setOpenModalProduct: () => { },
43
+ handleMenu: () => { }
31
44
  }) => {
32
45
  const { getOneProduct } = useCart({
33
46
  handleMenu,
@@ -137,9 +150,9 @@ export const useAsideCart = ({
137
150
  */
138
151
  const sumProduct = (ProPrice, ProDelivery, cant) => {
139
152
  // Convertir a números, con manejo de posibles errores
140
- const price = parseInt(ProPrice)
141
- const delivery = parseInt(ProDelivery || 0)
142
- const quantity = parseInt(cant)
153
+ const price = ProPrice
154
+ const delivery = ProDelivery || 0
155
+ const quantity = cant
143
156
 
144
157
  // Verificar si las conversiones fueron exitosas
145
158
  if (isNaN(price) || isNaN(delivery) || isNaN(quantity)) {
@@ -0,0 +1,12 @@
1
+ import { useMutation } from '@apollo/client'
2
+ import { DELETE_EXTRA_PRODUCTS } from '../useDessertWithPrice/queries'
3
+
4
+ export const useDeleteExtraProductFoods = () => {
5
+ const [deleteExtraProductFoods, { loading, error }] = useMutation(DELETE_EXTRA_PRODUCTS)
6
+
7
+ return {
8
+ deleteExtraProductFoods,
9
+ loading,
10
+ error
11
+ }
12
+ }
@@ -0,0 +1,76 @@
1
+ export const transformData = (dataExtra) => {
2
+ const transformedData = dataExtra?.map(item => ({
3
+ extraName: item.extraName || '',
4
+ extraPrice: item?.extraPrice?.toString() || '',
5
+ exState: !!item.exState,
6
+ forEdit: true,
7
+ ...item
8
+ }))
9
+
10
+ return transformedData
11
+ }
12
+
13
+ export const MAX_INTEGER = 2147483647
14
+ /**
15
+ * Validate if a number is within a specified range.
16
+ * @param {number} num - The number to validate.
17
+ * @returns {boolean} - True if the number is within the range, false otherwise.
18
+ */
19
+ export const isWithinRange = (num) => {
20
+ // Verificar si el número está dentro del rango permitido.
21
+ return num >= MAX_INTEGER
22
+ }
23
+
24
+ /**
25
+ * Find objects in the array where the value of 'extraPrice' exceeds the specified range.
26
+ * @param {array} arr - The array to search.
27
+ * @returns {array} - An array containing the indices and objects of the items exceeding the range.
28
+ */
29
+ export const findNumbersExceedingRange = (arr) => {
30
+ return arr.reduce((acc, item, index) => {
31
+ const extraPrice = typeof item.extraPrice === 'number' ? item.extraPrice : parseFloat(item.extraPrice.replace(/\./g, ''))
32
+ if (isWithinRange(extraPrice)) {
33
+ acc.push({ index, item })
34
+ }
35
+ return acc
36
+ }, [])
37
+ }
38
+
39
+ export const updateErrorFieldByIndex = ({
40
+ setLine = (array) => {
41
+ return array
42
+ },
43
+ checkNumberRange = []
44
+ } = {
45
+ setLine: (array) => {
46
+ return array
47
+ },
48
+ checkNumberRange: []
49
+ }) => {
50
+ setLine(prevLineItems => {
51
+ // Crea una copia del estado anterior de LineItems
52
+ const updatedLineItems = { ...prevLineItems }
53
+
54
+ // Utiliza map para iterar sobre cada elemento en checkNumberRange
55
+ const updatedLines = updatedLineItems.Lines.map((line, index) => {
56
+ // Verifica si el índice está dentro del rango de LineItems.Lines
57
+ if (checkNumberRange.some(item => item.index === index)) {
58
+ // Crea una copia del elemento actual
59
+ const updatedLine = { ...line }
60
+
61
+ // Actualiza el campo 'error' del elemento a true
62
+ updatedLine.error = true
63
+ updatedLine.messageError = 'El precio no puede ser mayor a 2147483647.00'
64
+
65
+ // Devuelve el elemento actualizado
66
+ return updatedLine
67
+ }
68
+
69
+ // Si el índice no está en checkNumberRange, devuelve el elemento sin cambios
70
+ return line
71
+ })
72
+
73
+ // Actualiza el array Lines en el estado de LineItems con los elementos actualizados
74
+ return { ...updatedLineItems, Lines: updatedLines }
75
+ })
76
+ }
@@ -1,12 +1,31 @@
1
- import { useCallback, useEffect, useMemo, useRef, useState, createRef } from 'react'
1
+ import {
2
+ useCallback,
3
+ useEffect,
4
+ useMemo,
5
+ useRef,
6
+ useState,
7
+ createRef
8
+ } from 'react'
2
9
  import { useUpdateMultipleExtProductFoods } from '../useUpdateMultipleExtProductFoods'
3
10
  import { useMutation } from '@apollo/client'
4
- import { DELETE_EXTRA_PRODUCTS, EDIT_EXTRA_PRODUCT_FOODS } from './queries'
11
+ import { EDIT_EXTRA_PRODUCT_FOODS } from './queries'
12
+ import { findNumbersExceedingRange, transformData, updateErrorFieldByIndex } from './helpers'
13
+ import { useDeleteExtraProductFoods } from '../useDeleteExtraProductFoods'
5
14
 
6
15
  export const useDessertWithPrice = ({
7
16
  dataExtra = [],
8
- sendNotification = () => { },
9
- setAlertBox = () => { }
17
+ sendNotification = ({
18
+ title,
19
+ description,
20
+ backgroundColor
21
+ }) => {
22
+ return {
23
+ title,
24
+ description,
25
+ backgroundColor
26
+ }
27
+ },
28
+ setAlertBox = ({ message, duration = 10000, success = true }) => { return { message, duration, success } }
10
29
  } = {}) => {
11
30
  const [selected, setSelected] = useState({
12
31
  loading: false,
@@ -34,19 +53,11 @@ export const useDessertWithPrice = ({
34
53
  ]
35
54
  }
36
55
  }, [initialLine])
37
- const transformedData = dataExtra?.map(item => ({
38
- extraName: item.extraName || '',
39
- extraPrice: item?.extraPrice?.toString() || '', // Convierte a string si es necesario
40
- exState: !!item.exState,
41
- forEdit: true,
42
- ...item
43
- }))
56
+ const transformedData = transformData(dataExtra)
57
+
44
58
  const [LineItems, setLine] = useState(
45
59
  Array.isArray(dataExtra) && dataExtra.length > 0 ? { Lines: transformedData } : initialLineItems
46
60
  )
47
- useEffect(() => {
48
- setLine(Array.isArray(dataExtra) && dataExtra.length > 0 ? { Lines: transformedData } : initialLineItems)
49
- }, [dataExtra.length])
50
61
 
51
62
  const inputRefs = useRef(LineItems.Lines.map(() => createRef()))
52
63
 
@@ -58,7 +69,7 @@ export const useDessertWithPrice = ({
58
69
  inputRefs.current[index].current.focus()
59
70
  }
60
71
  } catch (error) {
61
- console.log(error)
72
+ return null
62
73
  }
63
74
  }
64
75
 
@@ -66,11 +77,12 @@ export const useDessertWithPrice = ({
66
77
  // Asegurándote de que las referencias se actualicen si LineItems cambia
67
78
  inputRefs.current = LineItems.Lines.map((_, i) => inputRefs.current[i] || createRef())
68
79
  }, [LineItems])
80
+
69
81
  const handleCleanLines = useCallback(() => {
70
- setLine(initialLineItems)
82
+ setLine(Array.isArray(dataExtra) && dataExtra.length > 0 ? { Lines: transformedData } : initialLineItems)
71
83
  }, [initialLineItems])
72
84
 
73
- const [updateMultipleExtProductFoods, { loading }] = useUpdateMultipleExtProductFoods({ handleCleanLines: () => { } })
85
+ const [updateMultipleExtProductFoods, { loading }] = useUpdateMultipleExtProductFoods({ handleCleanLines: () => { return } })
74
86
  /**
75
87
  * Handles the addition of two new lines to the Lines array in LineItems state.
76
88
  */
@@ -132,11 +144,16 @@ export const useDessertWithPrice = ({
132
144
 
133
145
  setLine({ ...LineItems, Lines: newLines })
134
146
  }
135
- const [deleteExtraProductFoods] = useMutation(DELETE_EXTRA_PRODUCTS)
147
+ const { deleteExtraProductFoods } = useDeleteExtraProductFoods()
136
148
 
149
+ /**
150
+ * Filter out a specific line from the LineItems array.
151
+ * @param {number} index - Index of the line to be filtered out.
152
+ */
137
153
  const filterOneLine = (index) => {
138
- console.log(index)
154
+ // Use optional chaining to safely access nested properties.
139
155
  const Lines = LineItems?.Lines?.filter((_, i) => { return i !== index })
156
+ // Use spread operator to create a new object with the filtered Lines array.
140
157
  return setLine({ ...LineItems, Lines })
141
158
  }
142
159
  const handleRemove = async (i, exPid) => {
@@ -148,13 +165,24 @@ export const useDessertWithPrice = ({
148
165
  variables: {
149
166
  state: 1,
150
167
  id: exPid
168
+ },
169
+ update: (cache) => {
170
+ cache.modify({
171
+ fields: {
172
+ ExtProductFoodsAll: (dataOld = []) => {
173
+ const { success } = data?.data?.deleteextraproductfoods || {}
174
+ if (success && Array.isArray(dataOld)) {
175
+ const transformedData = transformData(dataOld)
176
+ const Lines = transformedData.filter((_, index) => { return index !== i })
177
+ const newCache = dataOld.filter((_, index) => { return index !== i })
178
+ setLine({ ...LineItems, Lines })
179
+ return newCache
180
+ }
181
+ }
182
+ }
183
+ })
151
184
  }
152
185
  })
153
- const { success } = data?.data?.deleteextraproductfoods || {}
154
- if (success) {
155
- console.log(i, exPid)
156
- return filterOneLine(i)
157
- }
158
186
  }
159
187
  }
160
188
  if (!exPid) {
@@ -168,8 +196,10 @@ export const useDessertWithPrice = ({
168
196
  })
169
197
  }
170
198
  }
199
+ useEffect(() => {
200
+ setLine(Array.isArray(dataExtra) && dataExtra.length > 0 ? { Lines: transformedData } : initialLineItems)
201
+ }, [dataExtra.length])
171
202
 
172
- // Prepares and validates data for submission.
173
203
  const prepareAndValidateData = useCallback((pId) => {
174
204
  const dataArr = LineItems?.Lines?.map(({ extraPrice, exState, extraName }) => ({
175
205
  extraPrice: parseFloat(extraPrice),
@@ -179,8 +209,8 @@ export const useDessertWithPrice = ({
179
209
  }))
180
210
 
181
211
  const message = 'Complete los campos vacíos'
182
- const findInputEmpty = dataArr.find(({ extraName }) => extraName === '')
183
- const findInputEmptyPrice = dataArr.find(({ extraPrice }) => isNaN(extraPrice) || extraPrice === '')
212
+ const findInputEmpty = dataArr?.find(({ extraName }) => extraName === '')
213
+ const findInputEmptyPrice = dataArr?.find(({ extraPrice }) => isNaN(extraPrice) || extraPrice === '')
184
214
 
185
215
  if (findInputEmpty || findInputEmptyPrice) {
186
216
  setAlertBox({ message })
@@ -270,6 +300,12 @@ export const useDessertWithPrice = ({
270
300
 
271
301
  const handleSubmit = ({ pId }) => {
272
302
  try {
303
+ const checkNumberRange = findNumbersExceedingRange(LineItems?.Lines)
304
+ updateErrorFieldByIndex({ checkNumberRange, setLine })
305
+ if (checkNumberRange?.length > 0) {
306
+ return setAlertBox({ message: 'El precio no puede ser tan alto', duration: 10000 })
307
+ }
308
+
273
309
  if (!prepareAndValidateData(pId)) return
274
310
  const dataArr = LineItems?.Lines?.map(x => {
275
311
  const extraPrice = stringToInt(x.extraPrice)
@@ -1,4 +1,5 @@
1
1
  import { useEffect } from 'react'
2
+
2
3
  export const on = ({ eventType, callBack }) => {
3
4
  document.addEventListener(eventType, callBack)
4
5
  }
@@ -1,38 +1,46 @@
1
- /* eslint-disable no-void */
2
1
  import { useEffect, useState } from 'react'
3
2
 
4
3
  export const useMobile = (props) => {
5
- const { callBack = () => { return null } } = props || {}
6
- const [innerHeight, setInnerHeight] = useState()
7
- const [innerWidth, setInnerWidth] = useState()
8
- let isMobile = false
9
- useEffect(() => {
10
- setInnerHeight(window.innerHeight)
11
- setInnerWidth(window.innerWidth)
12
- callBack()
13
- }, [])
4
+ const { callBack = () => {} } = props || {}
5
+ const [isMobile, setIsMobile] = useState(false)
6
+ const [isTablet, setIsTablet] = useState(false)
7
+ const [innerHeight, setInnerHeight] = useState(0)
8
+ const [innerWidth, setInnerWidth] = useState(0)
9
+
14
10
  useEffect(() => {
15
11
  const handleResize = () => {
16
- if (!isNaN(window === null || window === void 0 ? void 0 : window.innerHeight) && (window === null || window === void 0 ? void 0 : window.innerHeight) !== innerHeight) {
17
- setInnerHeight(window.innerHeight)
18
- }
19
- if (!isNaN(window.innerWidth) && window.innerWidth !== innerWidth) {
20
- setInnerWidth(window.innerWidth)
12
+ // Verificar si window está disponible (es decir, estamos en el lado del cliente)
13
+ if (typeof window !== 'undefined') {
14
+ const width = window.innerWidth
15
+ const height = window.innerHeight
16
+ setInnerWidth(width)
17
+ setInnerHeight(height)
18
+ callBack()
19
+
20
+ // Determinar el tipo de dispositivo
21
+ if (width <= 768) {
22
+ setIsTablet(true)
23
+ } else if (width <= 960) {
24
+ setIsMobile(true)
25
+ } else {
26
+ setIsMobile(false)
27
+ }
21
28
  }
22
- callBack()
23
- }
24
- if (typeof window !== 'undefined') {
25
- window.addEventListener('resize', handleResize)
26
29
  }
30
+
31
+ // Ejecutar handleResize al cargar y al cambiar el tamaño de la pantalla
32
+ handleResize()
33
+ window.addEventListener('resize', handleResize)
34
+
35
+ // Eliminar el event listener al desmontar el componente
27
36
  return () => {
28
37
  window.removeEventListener('resize', handleResize)
29
38
  }
30
- })
31
- if (typeof window !== 'undefined' && /Mobile/i.test((navigator === null || navigator === void 0 ? void 0 : navigator.userAgent) || (navigator === null || navigator === void 0 ? void 0 : navigator.vendor))) {
32
- isMobile = true
33
- }
39
+ }, [callBack])
40
+
34
41
  return {
35
42
  isMobile,
43
+ isTablet,
36
44
  innerHeight,
37
45
  innerWidth
38
46
  }
@@ -72,7 +72,13 @@ export const useProductsFood = ({
72
72
  ]
73
73
  }
74
74
 
75
- export const useDeleteProductsFood = ({ sendNotification = () => { } } = {}) => {
75
+ export const useDeleteProductsFood = ({
76
+ sendNotification = (asrg) => { return asrg },
77
+ onSuccess = (asrg) => { return asrg }
78
+ } = {
79
+ sendNotification: (asrg) => { return asrg },
80
+ onSuccess: (asrg) => { return asrg }
81
+ }) => {
76
82
  const [updateProductFoods, { data, loading, error }] = useMutation(UPDATE_PRODUCT_FOOD)
77
83
 
78
84
  const handleDelete = async product => {
@@ -130,8 +136,9 @@ export const useDeleteProductsFood = ({ sendNotification = () => { } } = {}) =>
130
136
  })
131
137
  }
132
138
  }).then(() => {
139
+ onSuccess()
133
140
  return sendNotification({
134
- title: 'Success',
141
+ title: 'Exito',
135
142
  description: 'El producto se ha eliminado correctamente',
136
143
  backgroundColor: 'success'
137
144
  })
@@ -56,7 +56,7 @@ const initializer = (initialValue = initialState) => {
56
56
  export const useSales = ({
57
57
  disabled = false,
58
58
  router,
59
- sendNotification = () => { return },
59
+ sendNotification = (arsg) => { return arsg },
60
60
  setAlertBox = () => { return }
61
61
  }) => {
62
62
  const domain = getCurrentDomain()
@@ -104,7 +104,6 @@ export const useSales = ({
104
104
  const [loadingExtraProduct, setLoadingExtraProduct] = useState(false)
105
105
  const [dataOptional, setDataOptional] = useState([])
106
106
  const [dataExtra, setDataExtra] = useState([])
107
-
108
107
  const [registerSalesStore, { loading: loadingRegisterSale }] = useMutation(
109
108
  CREATE_SHOPPING_CARD_TO_USER_STORE,
110
109
  {
@@ -905,6 +904,11 @@ export const useSales = ({
905
904
  setLoadingSale(false)
906
905
  setErrorSale(true)
907
906
  setPrint(false)
907
+ sendNotification({
908
+ title: 'error',
909
+ backgroundColor: 'error',
910
+ description: 'Lo sentimos, ocurrió un error'
911
+ })
908
912
  })
909
913
  .finally(() => {
910
914
  setPrint(false)
@@ -94,7 +94,7 @@ export const useStatusOpenStore = ({ dataSchedules = [] } = {}) => {
94
94
  if (findNextDay && findDataNextDay?.schHoSta) {
95
95
  const nameOfDayTomorrow = weekDays[dayOfWeekTomorrow]
96
96
  return handleMessageHour(
97
- `Cerrado - Mañana ${nameOfDayTomorrow} ${!!findDataNextDay?.schHoSta && 'a las'} ${
97
+ `Cerrado abre Mañana ${nameOfDayTomorrow} ${!!findDataNextDay?.schHoSta && 'a las'} ${
98
98
  findDataNextDay?.schHoSta ? findDataNextDay?.schHoSta : ''
99
99
  }`,
100
100
  false
@@ -4,9 +4,13 @@ import { UPDATE_MULTI_EXTRAS_PRODUCT_FOOD } from './queries'
4
4
  /**
5
5
  * Custom hook para manejar la actualización de múltiples extras de productos alimenticios.
6
6
  * @param {Function} cleanLines - Función para limpiar líneas después de completar la mutación.
7
+ * @param {Function} handleCleanLines - Función.
7
8
  * @returns {Array} Retorna un array con la función de mutación y el estado de carga.
8
9
  */
9
- export const useUpdateMultipleExtProductFoods = ({ cleanLines = () => { } } = {}) => {
10
+ export const useUpdateMultipleExtProductFoods = ({ cleanLines = () => { }, handleCleanLines = () => { } } = {
11
+ cleanLines: () => { },
12
+ handleCleanLines: () => { }
13
+ }) => {
10
14
  const [updateMultipleExtProductFoods, { loading }] = useMutation(UPDATE_MULTI_EXTRAS_PRODUCT_FOOD, {
11
15
  onCompleted: () => {
12
16
  cleanLines()