npm-pkg-hook 1.3.7 → 1.3.8

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.
Files changed (95) hide show
  1. package/.eslintrc.js +38 -38
  2. package/.eslintrc.json +127 -127
  3. package/.github/pull_request_template.md +17 -17
  4. package/.github/workflows/pepeline.yaml +29 -29
  5. package/package.json +46 -46
  6. package/script.txt +6 -6
  7. package/src/config/client/index.js +1 -1
  8. package/src/hooks/getCategoriesWithProduct/helpers/index.js +7 -7
  9. package/src/hooks/getCategoriesWithProduct/index.js +62 -62
  10. package/src/hooks/getSession/index.js +18 -18
  11. package/src/hooks/useAnimationFrame/index.js +45 -45
  12. package/src/hooks/useAsideCart/index.js +155 -155
  13. package/src/hooks/useAsideCart/queries.js +10 -10
  14. package/src/hooks/useCart/index.js +2 -2
  15. package/src/hooks/useCart/queries.js +164 -164
  16. package/src/hooks/useCart/useCart/helpers/index.js +75 -75
  17. package/src/hooks/useCart/useCart/index.js +410 -410
  18. package/src/hooks/useCart/useGetCart/index.js +31 -31
  19. package/src/hooks/useCatWithProductClient/index.js +56 -56
  20. package/src/hooks/useCatWithProductClient/queries.js +55 -55
  21. package/src/hooks/useCategoriesProduct/index.js +12 -12
  22. package/src/hooks/useCategoriesProduct/queries.js +16 -16
  23. package/src/hooks/useCategoryInStore/queries.js +78 -78
  24. package/src/hooks/useChartData/useChartData/index.js +199 -199
  25. package/src/hooks/useChartData/useChartDataAllOrders/index.js +94 -94
  26. package/src/hooks/useCheckbox/index.js +115 -115
  27. package/src/hooks/useCreateProduct/helpers/manageCacheDataCatProduct/index.js +52 -0
  28. package/src/hooks/useCreateProduct/index.js +8 -3
  29. package/src/hooks/useDeleteSubProductOptional/index.js +30 -30
  30. package/src/hooks/useDeleteSubProductOptional/queries.js +10 -10
  31. package/src/hooks/useDessert/helpers/index.js +51 -51
  32. package/src/hooks/useDevices/index.js +35 -35
  33. package/src/hooks/useDevices/queries.js +19 -19
  34. package/src/hooks/useDropzone/index.js +94 -94
  35. package/src/hooks/useDynamicAuth/index.js +13 -13
  36. package/src/hooks/useDynamicAuth/queries.js +24 -24
  37. package/src/hooks/useEditSubProductOptional/queries.js +10 -10
  38. package/src/hooks/useEvent/index.js +33 -33
  39. package/src/hooks/useFavoriteStores/index.js +19 -19
  40. package/src/hooks/useFavoriteStores/queries.js +47 -47
  41. package/src/hooks/useFetchJson/index.js +25 -25
  42. package/src/hooks/useFingerprintjs/index.js +172 -172
  43. package/src/hooks/useFullScreenMode/index.js +65 -65
  44. package/src/hooks/useGenerateNumberArray/index.js +17 -17
  45. package/src/hooks/useGetExtProductFoodsSubOptionalAll/index.js +14 -14
  46. package/src/hooks/useGetFoodRecomended/index.js +32 -33
  47. package/src/hooks/useGetFoodRecomended/queries.js +47 -47
  48. package/src/hooks/useGetMinPrice/index.js +12 -12
  49. package/src/hooks/useGetMinPrice/queries.js +7 -7
  50. package/src/hooks/useGetOneStoreRating/index.js +40 -40
  51. package/src/hooks/useGetOneStoreRating/queries.js +18 -18
  52. package/src/hooks/useGoogleLogin/index.js +160 -160
  53. package/src/hooks/useGoogleLogin/loadScript.js +15 -15
  54. package/src/hooks/useGoogleLogin/removeScript.js +7 -7
  55. package/src/hooks/useHover/index.js +29 -29
  56. package/src/hooks/useImagesStore/index.js +5 -4
  57. package/src/hooks/useInnerHtml/index.js +39 -39
  58. package/src/hooks/useKeypress/index.js +28 -28
  59. package/src/hooks/useLocationNavigate/index.js +54 -54
  60. package/src/hooks/useLogout/index.js +29 -21
  61. package/src/hooks/useManageQueryParams/index.js +37 -36
  62. package/src/hooks/useMobile/index.js +39 -39
  63. package/src/hooks/useOrderClient/index.js +5 -5
  64. package/src/hooks/useProviders/index.js +3 -3
  65. package/src/hooks/useProviders/queries.js +31 -31
  66. package/src/hooks/useProviders/useProvidersCreateStore/index.js +12 -12
  67. package/src/hooks/useProviders/useProvidersDataStore/index.js +24 -24
  68. package/src/hooks/useProvidersStore/index.js +24 -24
  69. package/src/hooks/useProvidersStore/queries.js +31 -31
  70. package/src/hooks/useRatingArrayData/index.js +54 -54
  71. package/src/hooks/useRatingArrayData/queries.js +19 -19
  72. package/src/hooks/useRemoveExtraProductFoodsOptional/index.js +23 -23
  73. package/src/hooks/useRemoveExtraProductFoodsOptional/queries.js +48 -48
  74. package/src/hooks/useRestaurant/index.js +19 -19
  75. package/src/hooks/useRestaurant/queries.js +80 -80
  76. package/src/hooks/useSales/useGetAllSales/index.js +25 -25
  77. package/src/hooks/useSchedule/index.js +72 -72
  78. package/src/hooks/useSchedule/index.jsx +22 -22
  79. package/src/hooks/useSchedule/queries.js +43 -43
  80. package/src/hooks/useScheduleData/index.js +123 -123
  81. package/src/hooks/useScroll/index.js +56 -56
  82. package/src/hooks/useScrollRotate/index.js +16 -16
  83. package/src/hooks/useStatusOpenStore/helpers/index.js +101 -101
  84. package/src/hooks/useStatusOpenStore/index.js +172 -172
  85. package/src/hooks/useStatusOrdersClient/queries.js +80 -80
  86. package/src/hooks/useStore/queries.js +163 -163
  87. package/src/hooks/useStoreCalendar/index.js +5 -5
  88. package/src/hooks/useStoreContacts/queries.js +1 -1
  89. package/src/hooks/useTimeAgo/useTimeAgo.js +39 -39
  90. package/src/hooks/useUpdateExtProductFoodsSubOptional/index.js +38 -38
  91. package/src/hooks/useWindowSize/index.js +38 -38
  92. package/src/mock/dessert/index.js +16 -16
  93. package/src/mock/index.js +1 -1
  94. package/.vscode/extensions.json +0 -6
  95. package/.vscode/settings.json +0 -8
@@ -1,410 +1,410 @@
1
- import { useState, useCallback, useEffect } from 'react'
2
- import { useMutation } from '@apollo/client'
3
- import { CREATE_SHOPPING_CARD, GET_ALL_SHOPPING_CARD } from '../queries'
4
- import { RandomCode, updateCacheMod, numberFormat } from '../../../utils'
5
- import { useExtProductFoodsAll, useGetOneProductsFood } from '../../useProductsFood'
6
- import { useGetExtProductFoodsSubOptionalAll } from '../../useGetExtProductFoodsSubOptionalAll'
7
- import { useGetCart } from '../useGetCart'
8
- import { useRouter } from 'next/router'
9
- import {
10
- filterDataOptional,
11
- filterExtra,
12
- validateExtraProducts,
13
- validateRequirements
14
- } from './helpers'
15
- import { useManageQueryParams } from '../../useManageQueryParams'
16
-
17
- /**
18
- * Custom hook for managing cart functionality.
19
- *
20
- * @param {Object} options - Options object.
21
- * @param {Function} options.setAlertBox - Function to set an alert message.
22
- * @returns {Object} - Object containing cart state and functions.
23
- */
24
- /**
25
- * The `useCart` function is a custom hook in JavaScript that handles the management of a shopping
26
- * cart, including adding products, managing quantities, and handling optional extras.
27
- * @param [] - - `openModalProduct`: A boolean indicating whether the modal for the product is open or
28
- * not. Default value is `false`.
29
- * @returns The `useCart` function returns an object with the following properties and methods:
30
- */
31
- export const useCart = ({
32
- openModalProduct = false,
33
- handleMenu = () => { },
34
- setOpenModalProduct = () => { },
35
- setAlertBox = () => { }
36
- } = {}) => {
37
- // sub products
38
- const { handleCleanQuery } = useManageQueryParams()
39
-
40
- const [dataOptional, setDataOptional] = useState([])
41
- const [dataExtra, setDataExtra] = useState([])
42
- const [quantity, setQuantity] = useState(1)
43
- const [comments, setComments] = useState('')
44
- const location = useRouter()
45
- const queryParamProduct = location.query.plato
46
- const [registerShoppingCard] = useMutation(CREATE_SHOPPING_CARD, {
47
- onError: (error) => {
48
- console.error('Error registering shopping card:', error)
49
- }
50
- })
51
- // CUSTOM HOOKS
52
- const [dataShoppingCard, { loading }] = useGetCart()
53
- const [handleExtProductFoodsAll] = useExtProductFoodsAll()
54
-
55
- const [ExtProductFoodsSubOptionalAll] = useGetExtProductFoodsSubOptionalAll()
56
- const [dataOneProduct, setDataOneProduct] = useState({})
57
- const [handleGetOneProduct,
58
- {
59
- loading: loadingProduct
60
- }
61
- ] = useGetOneProductsFood({ fetchOnlyProduct: true })
62
-
63
- const getOneProduct = async food => {
64
- const { pId, intoCart } = food || {}
65
- const isEditing = intoCart
66
- if (!pId) return {}
67
- setOpenModalProduct(true)
68
- const product = await handleGetOneProduct({ variables: { pId } })
69
- const productFoodsOne = product.data.productFoodsOne || {}
70
- setDataOneProduct(productFoodsOne)
71
-
72
- const matchingItemInShoppingCart = dataShoppingCard?.find((item) => {
73
- return item?.productFood && item?.productFood?.pId === pId
74
- })
75
- const matchingItemInShoppingCartOptional = matchingItemInShoppingCart?.salesExtProductFoodOptional || []
76
- if (matchingItemInShoppingCart && queryParamProduct) {
77
- setDataOneProduct({
78
- ...productFoodsOne,
79
- intoCart: true
80
- })
81
- const comments = matchingItemInShoppingCart?.comments
82
- if (comments) {
83
- setComments(comments || '')
84
- }
85
- const quantityProduct = matchingItemInShoppingCart?.cantProducts
86
- if (quantityProduct) {
87
- setQuantity(quantityProduct || 1)
88
- }
89
- }
90
- const optionalAll = await ExtProductFoodsSubOptionalAll({
91
- variables: { pId }
92
- })
93
- const optionalFetch = optionalAll?.data?.ExtProductFoodsOptionalAll
94
- const shoppingCartOptionalAll = matchingItemInShoppingCart?.ExtProductFoodsAll || []
95
- if (Array.isArray(optionalFetch)) {
96
- // Filtra y procesa los objetos de optionalFetch
97
- const filteredDataOptional = optionalFetch
98
- .map((obj) => {
99
- const filteredSubOptions = (obj.ExtProductFoodsSubOptionalAll || []).filter(
100
- (subObj) => subObj.check !== false
101
- )
102
-
103
- if (filteredSubOptions.length === 0) {
104
- return null
105
- }
106
-
107
- return {
108
- ...obj,
109
- ExtProductFoodsSubOptionalAll: filteredSubOptions
110
- }
111
- })
112
- .filter((obj) => obj !== null)
113
-
114
- if (matchingItemInShoppingCartOptional?.length === 0) {
115
- setDataOptional(filteredDataOptional || [])
116
- }
117
-
118
- if (matchingItemInShoppingCartOptional?.length) {
119
- // Actualiza los objetos de filteredDataOptional con información de matchingItemInShoppingCartOptional
120
- const updateOption = filteredDataOptional?.map((obj) => {
121
- const matchingArray = matchingItemInShoppingCartOptional?.find(
122
- (o) => o && o.opExPid === obj.opExPid
123
- )
124
-
125
- if (!matchingArray) {
126
- return obj
127
- }
128
-
129
- // Actualiza las propiedades específicas
130
- const updatedExtProductFoodsSubOptionalAll = (obj.ExtProductFoodsSubOptionalAll || []).map((subObj) => {
131
- const newItem = matchingArray.saleExtProductFoodsSubOptionalAll?.find((newItem) => newItem && newItem.opSubExPid === subObj.opSubExPid)
132
-
133
- if (newItem) {
134
- return {
135
- ...subObj,
136
- check: true
137
- }
138
- }
139
-
140
- return subObj
141
- })
142
-
143
- return {
144
- ...obj,
145
- ExtProductFoodsSubOptionalAll: updatedExtProductFoodsSubOptionalAll
146
- }
147
- }).filter((obj) => obj)
148
-
149
- setDataOptional(updateOption || [])
150
- }
151
- }
152
- if (!pId || pId === '') return
153
- const resultExtra = await handleExtProductFoodsAll(pId)
154
- const originalArray = resultExtra?.data?.ExtProductFoodsAll
155
-
156
- if (Array.isArray(originalArray) && originalArray?.length) {
157
- const fetchedDataExtra = originalArray?.map(extra => {
158
- const updatedExtra = shoppingCartOptionalAll?.find(updatedItem => updatedItem.exPid === extra.exPid)
159
- if (updatedExtra) {
160
- return {
161
- ...extra,
162
- quantity: updatedExtra?.quantity || 0,
163
- newExtraPrice: updatedExtra?.newExtraPrice || 0
164
- }
165
- }
166
- return {
167
- ...extra,
168
- quantity: 0
169
- }
170
- })
171
-
172
- setDataExtra(fetchedDataExtra || [])
173
- }
174
- }
175
-
176
- /**
177
- * The function `handleIncrementExtra` updates the quantity and price of a specific extra product in
178
- * an array based on the provided index and product ID.
179
- */
180
- function handleIncrementExtra ({ extra, index }) {
181
- // Desestructura las propiedades necesarias de dataOneProduct
182
- const { pId } = dataOneProduct || {}
183
-
184
- // Desestructura exPid de extra o establece un valor predeterminado si no existe
185
- const { exPid = null } = extra
186
-
187
- if (exPid && pId) {
188
- const newExtra = dataExtra.map((producto) => {
189
- if (exPid === producto.exPid) {
190
- // Desestructura la cantidad y el precio extra del producto o establece valores predeterminados
191
- const { quantity = 0, extraPrice = 0 } = producto
192
-
193
- // Calcula la nueva cantidad y el nuevo precio extra
194
- const newQuantity = quantity + 1
195
- const newExtraPrice = extraPrice * newQuantity
196
-
197
- return {
198
- ...producto,
199
- quantity: newQuantity,
200
- newExtraPrice
201
- }
202
- }
203
- return producto
204
- })
205
-
206
- // Actualiza el estado de dataExtra con el nuevo array
207
- setDataExtra(newExtra)
208
- }
209
- }
210
-
211
- function handleDecrementExtra ({ extra, index }) {
212
- // Desestructura las propiedades necesarias de dataOneProduct
213
- const { pId } = dataOneProduct || {}
214
-
215
- // Desestructura exPid de extra o establece un valor predeterminado si no existe
216
- const { exPid = null } = extra
217
-
218
- // Encuentra el índice del objeto extra en dataExtra
219
- const extraIndex = dataExtra.findIndex((item) => item.exPid === exPid)
220
-
221
- if (pId && exPid && extraIndex !== -1) {
222
- const newExtra = dataExtra.map((producto, i) => {
223
- if (exPid === producto.exPid) {
224
- // Desestructura la cantidad y el precio extra del producto o establece valores predeterminados
225
- const { quantity = 0, extraPrice = 0 } = producto
226
-
227
- // Calcula la nueva cantidad, evitando que sea negativa
228
- const newQuantity = Math.max(quantity - 1, 0)
229
-
230
- // Calcula el nuevo precio extra
231
- const newExtraPrice = newQuantity === 0 ? extraPrice : extraPrice * newQuantity
232
-
233
- return {
234
- ...producto,
235
- quantity: newQuantity,
236
- newExtraPrice
237
- }
238
- }
239
- return producto
240
- })
241
-
242
- // Actualiza el estado de dataExtra con el nuevo array
243
- setDataExtra(newExtra)
244
- }
245
- }
246
-
247
- const handleIncrease = () => {
248
- return setQuantity((prev) => { return prev + 1 })
249
- }
250
-
251
- const handleDecrease = () => {
252
- return setQuantity((prev) => { return prev - 1 })
253
- }
254
-
255
- const handleCountProducts = useCallback((ProPrice, quantity) => {
256
- if (!ProPrice || !quantity) {
257
- return 0 // Manejo de valores nulos o no numéricos
258
- }
259
-
260
- const price = parseFloat(ProPrice)
261
- const numericQuantity = parseInt(quantity, 10)
262
-
263
- if (isNaN(price) || isNaN(numericQuantity)) {
264
- return 0 // Manejo de valores no numéricos
265
- }
266
-
267
- if (numericQuantity <= 0 || price <= 0) {
268
- return price // Manejo de cantidades o precios no positivos
269
- }
270
-
271
- const totalPrice = Math.abs(numericQuantity * price)
272
- return numberFormat(totalPrice) // Si es necesario, aplicar formateo aquí
273
- }, [dataOneProduct])
274
-
275
- const handleAddOptional = ({ exOptional = null, codeCategory = null }) => {
276
- if (!exOptional || !codeCategory) return
277
- const item = dataOptional.find((item) => item.code === codeCategory)
278
- if (!item) return
279
- const idx = item.ExtProductFoodsSubOptionalAll.findIndex(
280
- (el) => el.opSubExPid === exOptional
281
- )
282
- if (item && idx !== -1) {
283
- const updatedItem = {
284
- ...item,
285
- ExtProductFoodsSubOptionalAll: [
286
- ...item.ExtProductFoodsSubOptionalAll.slice(0, idx),
287
- {
288
- ...item.ExtProductFoodsSubOptionalAll[idx],
289
- check: !item.ExtProductFoodsSubOptionalAll[idx].check
290
- },
291
- ...item.ExtProductFoodsSubOptionalAll.slice(idx + 1)
292
- ]
293
- }
294
- const newData = dataOptional.map((el) =>
295
- el.code === codeCategory ? updatedItem : el
296
- )
297
- setDataOptional((prevData) => [...newData])
298
- }
299
- }
300
-
301
- const isValidDataExtra = (!dataExtra.length && !dataOneProduct?.pId) ? false : !validateExtraProducts(dataExtra)
302
-
303
- const isValid = (!dataOptional.length && !dataOneProduct?.pId) ? false : validateRequirements(dataOptional)
304
-
305
- const disabled = isValid || isValidDataExtra
306
-
307
- /**
308
- * Handles the addition of products to the cart.
309
- *
310
- * @param {Object} food - The selected food item.
311
- */
312
-
313
- const handleAddProducts = async (food) => {
314
- if (!food) return
315
- const idStore = food?.getStore?.idStore
316
- if (!idStore) {
317
- return
318
- }
319
- const isExistItemInShoppingCart = dataShoppingCard?.find((item) => {
320
- return item?.productFood && item?.productFood?.pId === food.pId
321
- }) ?? null
322
- if (!isExistItemInShoppingCart) handleMenu(1)
323
- const filteredDataOptional = filterDataOptional(dataOptional)
324
-
325
- const dataExtraFiltered = filterExtra(dataExtra)
326
-
327
- const refCodePid = RandomCode(20)
328
-
329
- const idShoppingCart = isExistItemInShoppingCart?.ShoppingCard
330
- try {
331
- const idStore = food?.getStore?.idStore
332
- const response = await registerShoppingCard({
333
- variables: {
334
- input: {
335
- ShoppingCard: idShoppingCart ?? null,
336
- cState: 1,
337
- pId: food.pId,
338
- idStore,
339
- refCodePid: idShoppingCart ? null : refCodePid,
340
- comments,
341
- cName: '',
342
- cantProducts: quantity,
343
- csDescription: '',
344
- dataExtra: dataExtraFiltered || [],
345
- dataOptional: filteredDataOptional || []
346
- },
347
- idSubArray: {
348
- setID: []
349
- }
350
- },
351
- update: (cache, { data: { getAllShoppingCard } }) => {
352
- return updateCacheMod({
353
- cache,
354
- query: GET_ALL_SHOPPING_CARD,
355
- nameFun: 'getAllShoppingCard',
356
- dataNew: getAllShoppingCard
357
- })
358
- }
359
- })
360
-
361
- if (response?.data) {
362
- // Perform actions after adding products to cart
363
- }
364
- } catch (error) {
365
- setAlertBox({ message: 'Ocurrió un error al añadir el producto al carrito' })
366
- }
367
- }
368
-
369
- const handleShowModalProduct = () => {
370
- if (openModalProduct) {
371
- setDataExtra([])
372
- setDataOneProduct({})
373
- setQuantity(1)
374
- setComments('')
375
- setDataOptional([])
376
- }
377
- if (queryParamProduct && openModalProduct) {
378
- handleCleanQuery('plato')
379
- }
380
- return setOpenModalProduct(!openModalProduct)
381
- }
382
-
383
- useEffect(() => {
384
- if (queryParamProduct) {
385
- const product = { pId: queryParamProduct }
386
- getOneProduct(product)
387
- }
388
- }, [queryParamProduct])
389
-
390
- return {
391
- quantity,
392
- disabled,
393
- comments,
394
- loading: loadingProduct || loading,
395
- dataOneProduct,
396
- dataExtra,
397
- dataOptional,
398
- setQuantity,
399
- handleShowModalProduct,
400
- handleDecrease,
401
- handleIncrease,
402
- getOneProduct,
403
- handleIncrementExtra,
404
- handleDecrementExtra,
405
- handleAddOptional,
406
- setComments,
407
- handleCountProducts,
408
- handleAddProducts
409
- }
410
- }
1
+ import { useState, useCallback, useEffect } from 'react'
2
+ import { useMutation } from '@apollo/client'
3
+ import { CREATE_SHOPPING_CARD, GET_ALL_SHOPPING_CARD } from '../queries'
4
+ import { RandomCode, updateCacheMod, numberFormat } from '../../../utils'
5
+ import { useExtProductFoodsAll, useGetOneProductsFood } from '../../useProductsFood'
6
+ import { useGetExtProductFoodsSubOptionalAll } from '../../useGetExtProductFoodsSubOptionalAll'
7
+ import { useGetCart } from '../useGetCart'
8
+ import { useRouter } from 'next/router'
9
+ import {
10
+ filterDataOptional,
11
+ filterExtra,
12
+ validateExtraProducts,
13
+ validateRequirements
14
+ } from './helpers'
15
+ import { useManageQueryParams } from '../../useManageQueryParams'
16
+
17
+ /**
18
+ * Custom hook for managing cart functionality.
19
+ *
20
+ * @param {Object} options - Options object.
21
+ * @param {Function} options.setAlertBox - Function to set an alert message.
22
+ * @returns {Object} - Object containing cart state and functions.
23
+ */
24
+ /**
25
+ * The `useCart` function is a custom hook in JavaScript that handles the management of a shopping
26
+ * cart, including adding products, managing quantities, and handling optional extras.
27
+ * @param [] - - `openModalProduct`: A boolean indicating whether the modal for the product is open or
28
+ * not. Default value is `false`.
29
+ * @returns The `useCart` function returns an object with the following properties and methods:
30
+ */
31
+ export const useCart = ({
32
+ openModalProduct = false,
33
+ handleMenu = () => { },
34
+ setOpenModalProduct = () => { },
35
+ setAlertBox = () => { }
36
+ } = {}) => {
37
+ // sub products
38
+ const { handleCleanQuery } = useManageQueryParams()
39
+
40
+ const [dataOptional, setDataOptional] = useState([])
41
+ const [dataExtra, setDataExtra] = useState([])
42
+ const [quantity, setQuantity] = useState(1)
43
+ const [comments, setComments] = useState('')
44
+ const location = useRouter()
45
+ const queryParamProduct = location.query.plato
46
+ const [registerShoppingCard] = useMutation(CREATE_SHOPPING_CARD, {
47
+ onError: (error) => {
48
+ console.error('Error registering shopping card:', error)
49
+ }
50
+ })
51
+ // CUSTOM HOOKS
52
+ const [dataShoppingCard, { loading }] = useGetCart()
53
+ const [handleExtProductFoodsAll] = useExtProductFoodsAll()
54
+
55
+ const [ExtProductFoodsSubOptionalAll] = useGetExtProductFoodsSubOptionalAll()
56
+ const [dataOneProduct, setDataOneProduct] = useState({})
57
+ const [handleGetOneProduct,
58
+ {
59
+ loading: loadingProduct
60
+ }
61
+ ] = useGetOneProductsFood({ fetchOnlyProduct: true })
62
+
63
+ const getOneProduct = async food => {
64
+ const { pId, intoCart } = food || {}
65
+ const isEditing = intoCart
66
+ if (!pId) return {}
67
+ setOpenModalProduct(true)
68
+ const product = await handleGetOneProduct({ variables: { pId } })
69
+ const productFoodsOne = product.data.productFoodsOne || {}
70
+ setDataOneProduct(productFoodsOne)
71
+
72
+ const matchingItemInShoppingCart = dataShoppingCard?.find((item) => {
73
+ return item?.productFood && item?.productFood?.pId === pId
74
+ })
75
+ const matchingItemInShoppingCartOptional = matchingItemInShoppingCart?.salesExtProductFoodOptional || []
76
+ if (matchingItemInShoppingCart && queryParamProduct) {
77
+ setDataOneProduct({
78
+ ...productFoodsOne,
79
+ intoCart: true
80
+ })
81
+ const comments = matchingItemInShoppingCart?.comments
82
+ if (comments) {
83
+ setComments(comments || '')
84
+ }
85
+ const quantityProduct = matchingItemInShoppingCart?.cantProducts
86
+ if (quantityProduct) {
87
+ setQuantity(quantityProduct || 1)
88
+ }
89
+ }
90
+ const optionalAll = await ExtProductFoodsSubOptionalAll({
91
+ variables: { pId }
92
+ })
93
+ const optionalFetch = optionalAll?.data?.ExtProductFoodsOptionalAll
94
+ const shoppingCartOptionalAll = matchingItemInShoppingCart?.ExtProductFoodsAll || []
95
+ if (Array.isArray(optionalFetch)) {
96
+ // Filtra y procesa los objetos de optionalFetch
97
+ const filteredDataOptional = optionalFetch
98
+ .map((obj) => {
99
+ const filteredSubOptions = (obj.ExtProductFoodsSubOptionalAll || []).filter(
100
+ (subObj) => subObj.check !== false
101
+ )
102
+
103
+ if (filteredSubOptions.length === 0) {
104
+ return null
105
+ }
106
+
107
+ return {
108
+ ...obj,
109
+ ExtProductFoodsSubOptionalAll: filteredSubOptions
110
+ }
111
+ })
112
+ .filter((obj) => obj !== null)
113
+
114
+ if (matchingItemInShoppingCartOptional?.length === 0) {
115
+ setDataOptional(filteredDataOptional || [])
116
+ }
117
+
118
+ if (matchingItemInShoppingCartOptional?.length) {
119
+ // Actualiza los objetos de filteredDataOptional con información de matchingItemInShoppingCartOptional
120
+ const updateOption = filteredDataOptional?.map((obj) => {
121
+ const matchingArray = matchingItemInShoppingCartOptional?.find(
122
+ (o) => o && o.opExPid === obj.opExPid
123
+ )
124
+
125
+ if (!matchingArray) {
126
+ return obj
127
+ }
128
+
129
+ // Actualiza las propiedades específicas
130
+ const updatedExtProductFoodsSubOptionalAll = (obj.ExtProductFoodsSubOptionalAll || []).map((subObj) => {
131
+ const newItem = matchingArray.saleExtProductFoodsSubOptionalAll?.find((newItem) => newItem && newItem.opSubExPid === subObj.opSubExPid)
132
+
133
+ if (newItem) {
134
+ return {
135
+ ...subObj,
136
+ check: true
137
+ }
138
+ }
139
+
140
+ return subObj
141
+ })
142
+
143
+ return {
144
+ ...obj,
145
+ ExtProductFoodsSubOptionalAll: updatedExtProductFoodsSubOptionalAll
146
+ }
147
+ }).filter((obj) => obj)
148
+
149
+ setDataOptional(updateOption || [])
150
+ }
151
+ }
152
+ if (!pId || pId === '') return
153
+ const resultExtra = await handleExtProductFoodsAll(pId)
154
+ const originalArray = resultExtra?.data?.ExtProductFoodsAll
155
+
156
+ if (Array.isArray(originalArray) && originalArray?.length) {
157
+ const fetchedDataExtra = originalArray?.map(extra => {
158
+ const updatedExtra = shoppingCartOptionalAll?.find(updatedItem => updatedItem.exPid === extra.exPid)
159
+ if (updatedExtra) {
160
+ return {
161
+ ...extra,
162
+ quantity: updatedExtra?.quantity || 0,
163
+ newExtraPrice: updatedExtra?.newExtraPrice || 0
164
+ }
165
+ }
166
+ return {
167
+ ...extra,
168
+ quantity: 0
169
+ }
170
+ })
171
+
172
+ setDataExtra(fetchedDataExtra || [])
173
+ }
174
+ }
175
+
176
+ /**
177
+ * The function `handleIncrementExtra` updates the quantity and price of a specific extra product in
178
+ * an array based on the provided index and product ID.
179
+ */
180
+ function handleIncrementExtra ({ extra, index }) {
181
+ // Desestructura las propiedades necesarias de dataOneProduct
182
+ const { pId } = dataOneProduct || {}
183
+
184
+ // Desestructura exPid de extra o establece un valor predeterminado si no existe
185
+ const { exPid = null } = extra
186
+
187
+ if (exPid && pId) {
188
+ const newExtra = dataExtra.map((producto) => {
189
+ if (exPid === producto.exPid) {
190
+ // Desestructura la cantidad y el precio extra del producto o establece valores predeterminados
191
+ const { quantity = 0, extraPrice = 0 } = producto
192
+
193
+ // Calcula la nueva cantidad y el nuevo precio extra
194
+ const newQuantity = quantity + 1
195
+ const newExtraPrice = extraPrice * newQuantity
196
+
197
+ return {
198
+ ...producto,
199
+ quantity: newQuantity,
200
+ newExtraPrice
201
+ }
202
+ }
203
+ return producto
204
+ })
205
+
206
+ // Actualiza el estado de dataExtra con el nuevo array
207
+ setDataExtra(newExtra)
208
+ }
209
+ }
210
+
211
+ function handleDecrementExtra ({ extra, index }) {
212
+ // Desestructura las propiedades necesarias de dataOneProduct
213
+ const { pId } = dataOneProduct || {}
214
+
215
+ // Desestructura exPid de extra o establece un valor predeterminado si no existe
216
+ const { exPid = null } = extra
217
+
218
+ // Encuentra el índice del objeto extra en dataExtra
219
+ const extraIndex = dataExtra.findIndex((item) => item.exPid === exPid)
220
+
221
+ if (pId && exPid && extraIndex !== -1) {
222
+ const newExtra = dataExtra.map((producto, i) => {
223
+ if (exPid === producto.exPid) {
224
+ // Desestructura la cantidad y el precio extra del producto o establece valores predeterminados
225
+ const { quantity = 0, extraPrice = 0 } = producto
226
+
227
+ // Calcula la nueva cantidad, evitando que sea negativa
228
+ const newQuantity = Math.max(quantity - 1, 0)
229
+
230
+ // Calcula el nuevo precio extra
231
+ const newExtraPrice = newQuantity === 0 ? extraPrice : extraPrice * newQuantity
232
+
233
+ return {
234
+ ...producto,
235
+ quantity: newQuantity,
236
+ newExtraPrice
237
+ }
238
+ }
239
+ return producto
240
+ })
241
+
242
+ // Actualiza el estado de dataExtra con el nuevo array
243
+ setDataExtra(newExtra)
244
+ }
245
+ }
246
+
247
+ const handleIncrease = () => {
248
+ return setQuantity((prev) => { return prev + 1 })
249
+ }
250
+
251
+ const handleDecrease = () => {
252
+ return setQuantity((prev) => { return prev - 1 })
253
+ }
254
+
255
+ const handleCountProducts = useCallback((ProPrice, quantity) => {
256
+ if (!ProPrice || !quantity) {
257
+ return 0 // Manejo de valores nulos o no numéricos
258
+ }
259
+
260
+ const price = parseFloat(ProPrice)
261
+ const numericQuantity = parseInt(quantity, 10)
262
+
263
+ if (isNaN(price) || isNaN(numericQuantity)) {
264
+ return 0 // Manejo de valores no numéricos
265
+ }
266
+
267
+ if (numericQuantity <= 0 || price <= 0) {
268
+ return price // Manejo de cantidades o precios no positivos
269
+ }
270
+
271
+ const totalPrice = Math.abs(numericQuantity * price)
272
+ return numberFormat(totalPrice) // Si es necesario, aplicar formateo aquí
273
+ }, [dataOneProduct])
274
+
275
+ const handleAddOptional = ({ exOptional = null, codeCategory = null }) => {
276
+ if (!exOptional || !codeCategory) return
277
+ const item = dataOptional.find((item) => item.code === codeCategory)
278
+ if (!item) return
279
+ const idx = item.ExtProductFoodsSubOptionalAll.findIndex(
280
+ (el) => el.opSubExPid === exOptional
281
+ )
282
+ if (item && idx !== -1) {
283
+ const updatedItem = {
284
+ ...item,
285
+ ExtProductFoodsSubOptionalAll: [
286
+ ...item.ExtProductFoodsSubOptionalAll.slice(0, idx),
287
+ {
288
+ ...item.ExtProductFoodsSubOptionalAll[idx],
289
+ check: !item.ExtProductFoodsSubOptionalAll[idx].check
290
+ },
291
+ ...item.ExtProductFoodsSubOptionalAll.slice(idx + 1)
292
+ ]
293
+ }
294
+ const newData = dataOptional.map((el) =>
295
+ el.code === codeCategory ? updatedItem : el
296
+ )
297
+ setDataOptional((prevData) => [...newData])
298
+ }
299
+ }
300
+
301
+ const isValidDataExtra = (!dataExtra.length && !dataOneProduct?.pId) ? false : !validateExtraProducts(dataExtra)
302
+
303
+ const isValid = (!dataOptional.length && !dataOneProduct?.pId) ? false : validateRequirements(dataOptional)
304
+
305
+ const disabled = isValid || isValidDataExtra
306
+
307
+ /**
308
+ * Handles the addition of products to the cart.
309
+ *
310
+ * @param {Object} food - The selected food item.
311
+ */
312
+
313
+ const handleAddProducts = async (food) => {
314
+ if (!food) return
315
+ const idStore = food?.getStore?.idStore
316
+ if (!idStore) {
317
+ return
318
+ }
319
+ const isExistItemInShoppingCart = dataShoppingCard?.find((item) => {
320
+ return item?.productFood && item?.productFood?.pId === food.pId
321
+ }) ?? null
322
+ if (!isExistItemInShoppingCart) handleMenu(1)
323
+ const filteredDataOptional = filterDataOptional(dataOptional)
324
+
325
+ const dataExtraFiltered = filterExtra(dataExtra)
326
+
327
+ const refCodePid = RandomCode(20)
328
+
329
+ const idShoppingCart = isExistItemInShoppingCart?.ShoppingCard
330
+ try {
331
+ const idStore = food?.getStore?.idStore
332
+ const response = await registerShoppingCard({
333
+ variables: {
334
+ input: {
335
+ ShoppingCard: idShoppingCart ?? null,
336
+ cState: 1,
337
+ pId: food.pId,
338
+ idStore,
339
+ refCodePid: idShoppingCart ? null : refCodePid,
340
+ comments,
341
+ cName: '',
342
+ cantProducts: quantity,
343
+ csDescription: '',
344
+ dataExtra: dataExtraFiltered || [],
345
+ dataOptional: filteredDataOptional || []
346
+ },
347
+ idSubArray: {
348
+ setID: []
349
+ }
350
+ },
351
+ update: (cache, { data: { getAllShoppingCard } }) => {
352
+ return updateCacheMod({
353
+ cache,
354
+ query: GET_ALL_SHOPPING_CARD,
355
+ nameFun: 'getAllShoppingCard',
356
+ dataNew: getAllShoppingCard
357
+ })
358
+ }
359
+ })
360
+
361
+ if (response?.data) {
362
+ // Perform actions after adding products to cart
363
+ }
364
+ } catch (error) {
365
+ setAlertBox({ message: 'Ocurrió un error al añadir el producto al carrito' })
366
+ }
367
+ }
368
+
369
+ const handleShowModalProduct = () => {
370
+ if (openModalProduct) {
371
+ setDataExtra([])
372
+ setDataOneProduct({})
373
+ setQuantity(1)
374
+ setComments('')
375
+ setDataOptional([])
376
+ }
377
+ if (queryParamProduct && openModalProduct) {
378
+ handleCleanQuery('plato')
379
+ }
380
+ return setOpenModalProduct(!openModalProduct)
381
+ }
382
+
383
+ useEffect(() => {
384
+ if (queryParamProduct) {
385
+ const product = { pId: queryParamProduct }
386
+ getOneProduct(product)
387
+ }
388
+ }, [queryParamProduct])
389
+
390
+ return {
391
+ quantity,
392
+ disabled,
393
+ comments,
394
+ loading: loadingProduct || loading,
395
+ dataOneProduct,
396
+ dataExtra,
397
+ dataOptional,
398
+ setQuantity,
399
+ handleShowModalProduct,
400
+ handleDecrease,
401
+ handleIncrease,
402
+ getOneProduct,
403
+ handleIncrementExtra,
404
+ handleDecrementExtra,
405
+ handleAddOptional,
406
+ setComments,
407
+ handleCountProducts,
408
+ handleAddProducts
409
+ }
410
+ }