npm-pkg-hook 1.7.1 → 1.7.4

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
@@ -6,7 +6,7 @@
6
6
  "js-cookie": "3.0.1",
7
7
  "lodash": "^4.17.21",
8
8
  "md5": "2.3.0",
9
- "moment": "^2.29.4",
9
+ "moment": "^2.29.4",
10
10
  "react": "18.1.0",
11
11
  "react-dom": "18.1.0",
12
12
  "react-query": "^3.39.2"
@@ -30,7 +30,7 @@
30
30
  },
31
31
  "license": "ISC",
32
32
  "main": "/src/index.jsx",
33
- "name": "npm-pkg-hook",
33
+ "name": "npm-pkg-hook",
34
34
  "publishConfig": {
35
35
  "registry": "https://registry.npmjs.org/"
36
36
  },
@@ -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.1"
47
+ "version": "1.7.4"
48
48
  }
@@ -12,13 +12,16 @@ export const useCatWithProduct = ({
12
12
  gender,
13
13
  desc,
14
14
  speciality
15
- } = searchFilter || {}
15
+ } = searchFilter ?? {}
16
16
  const {
17
17
  data,
18
18
  loading,
19
19
  error,
20
20
  fetchMore
21
21
  } = useQuery(GET_ALL_CATEGORIES_WITH_PRODUCT, {
22
+ onCompleted: (data) => {
23
+ console.log('data', data)
24
+ },
22
25
  fetchPolicy: 'network-only',
23
26
  variables:
24
27
  {
@@ -41,4 +44,4 @@ export const useCatWithProduct = ({
41
44
  totalCount
42
45
  }
43
46
  ]
44
- }
47
+ }
@@ -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)
@@ -9,7 +9,14 @@ import { validationSubmitHooks } from '../../utils'
9
9
  * @description Hook con herramientas de validación y eventos de cambio
10
10
  * @return {Array} devuelve la función onChange a ejecutar y el estado de error de cada input
11
11
  */
12
- export const useFormTools = ({ sendNotification = () => { } } = {}) => {
12
+ export const useFormTools = ({
13
+ sendNotification = ({
14
+ title = '',
15
+ description = '',
16
+ backgroundColor = ''
17
+ }) => { }
18
+ }
19
+ = {}) => {
13
20
  const [dataForm, setDataForm] = useState({})
14
21
  const [errorForm, setErrorForm] = useState({})
15
22
  const [errorSubmit, setErrorSubmit] = useState(false)
@@ -40,7 +47,7 @@ export const useFormTools = ({ sendNotification = () => { } } = {}) => {
40
47
  event,
41
48
  msgError = '',
42
49
  msgSuccess,
43
- action = () => { },
50
+ action = () => { return Promise.resolve() },
44
51
  actionAfterSuccess = () => { }
45
52
  }) => {
46
53
  event.preventDefault()
@@ -78,7 +85,7 @@ export const useFormTools = ({ sendNotification = () => { } } = {}) => {
78
85
  action().then(res => {
79
86
  if (res) {
80
87
  sendNotification({
81
- message: msgSuccess || 'Operación exitosa',
88
+ message: msgSuccess ?? 'Operación exitosa',
82
89
  description: 'Operación exitosa',
83
90
  backgroundColor: 'success'
84
91
  })
@@ -13,20 +13,6 @@ import {
13
13
  } from './queriesStore'
14
14
  export * from './useEditProduct'
15
15
 
16
- /**
17
- * Description
18
- * @param {any} categories
19
- * @param {any} desc
20
- * @param {any} fetchPolicy='network-only'
21
- * @param {any} fromDate
22
- * @param {any} gender
23
- * @param {any} max=50
24
- * @param {any} min
25
- * @param {any} pState
26
- * @param {any} search=null
27
- * @param {any} toDate
28
- * @returns {any}
29
- */
30
16
  export const useProductsFood = ({
31
17
  categories,
32
18
  desc,
@@ -40,7 +26,7 @@ export const useProductsFood = ({
40
26
  toDate
41
27
  }) => {
42
28
  // const [productsFood, setProductsFood] = useState([])
43
- const [showMore, setShowMore] = useState(50)
29
+ const [showMore, setShowMore] = useState(500)
44
30
  const { data, loading, fetchMore, error, called } = useQuery(GET_ALL_PRODUCT_STORE, {
45
31
  fetchPolicy: fetchPolicy ?? 'cache-and-network',
46
32
  notifyOnNetworkStatusChange: true,
@@ -72,7 +58,13 @@ export const useProductsFood = ({
72
58
  ]
73
59
  }
74
60
 
75
- export const useDeleteProductsFood = ({ sendNotification = () => { } } = {}) => {
61
+ export const useDeleteProductsFood = ({
62
+ sendNotification = (asrg) => { return asrg },
63
+ onSuccess = (asrg) => { return asrg }
64
+ } = {
65
+ sendNotification: (asrg) => { return asrg },
66
+ onSuccess: (asrg) => { return asrg }
67
+ }) => {
76
68
  const [updateProductFoods, { data, loading, error }] = useMutation(UPDATE_PRODUCT_FOOD)
77
69
 
78
70
  const handleDelete = async product => {
@@ -130,8 +122,9 @@ export const useDeleteProductsFood = ({ sendNotification = () => { } } = {}) =>
130
122
  })
131
123
  }
132
124
  }).then(() => {
125
+ onSuccess()
133
126
  return sendNotification({
134
- title: 'Success',
127
+ title: 'Exito',
135
128
  description: 'El producto se ha eliminado correctamente',
136
129
  backgroundColor: 'success'
137
130
  })
@@ -101,6 +101,8 @@ export const GET_ALL_PRODUCT_STORE = gql`
101
101
  pId
102
102
  sizeId #Talla
103
103
  colorId #Color
104
+ carProId #Categoria a la cual pertenece el producto
105
+ caId
104
106
  cId #Country
105
107
  dId #Department
106
108
  ctId #Cuidad
@@ -27,7 +27,6 @@ import {
27
27
  import { updateExistingOrders } from '../useUpdateExistingOrders'
28
28
  import { useGetSale } from './useGetSale'
29
29
  import { useCatWithProduct } from './../useCatWithProduct/index'
30
- import { useCheckboxState } from '../useCheckbox'
31
30
  import { useLogout } from '../useLogout'
32
31
  export * from './useGetAllSales'
33
32
  export { GET_ALL_COUNT_SALES } from './queries'
@@ -48,6 +47,7 @@ const initialState = {
48
47
  const initializer = (initialValue = initialState) => {
49
48
  return (
50
49
  JSON.parse(
50
+ // @ts-ignore
51
51
  Cookies.get(process.env.LOCAL_SALES_STORE) || JSON.stringify(initialState)
52
52
  ) || initialValue
53
53
  )
@@ -57,7 +57,7 @@ export const useSales = ({
57
57
  disabled = false,
58
58
  router,
59
59
  sendNotification = (arsg) => { return arsg },
60
- setAlertBox = () => { return }
60
+ setAlertBox = (arsg) => { return arsg }
61
61
  }) => {
62
62
  const domain = getCurrentDomain()
63
63
  const [loadingSale, setLoadingSale] = useState(false)
@@ -67,16 +67,14 @@ export const useSales = ({
67
67
  const [modalItem, setModalItem] = useState(false)
68
68
  const [openCommentModal, setOpenCommentModal] = useState(false)
69
69
  const keyToSaveData = process.env.LOCAL_SALES_STORE
70
+ // @ts-ignore
70
71
  const saveDataState = JSON.parse(Cookies.get(keyToSaveData) || '[]')
71
72
  const [search, setSearch] = useState('')
72
73
  const [datCat] = useCatWithProduct({})
73
- const {
74
- checkedItems,
75
- disabledItems,
76
- setCheckedItems,
77
- handleChangeCheck
78
- } = useCheckboxState(datCat, [], [])
79
- const arr = checkedItems ? Array.from(checkedItems) : []
74
+ const [categories, setCategories] = useState([])
75
+ useEffect(() => {
76
+ setCategories(datCat)
77
+ }, [datCat])
80
78
  const [totalProductPrice, setTotalProductPrice] = useState(0)
81
79
  const [showMore, setShowMore] = useState(100)
82
80
  const [inputValue, setInputValue] = useState('')
@@ -119,6 +117,7 @@ export const useSales = ({
119
117
  })
120
118
  setAlertBox({ message, type: 'success' })
121
119
  if (message === 'Token expired') {
120
+ // @ts-ignore
122
121
  onClickLogout()
123
122
  }
124
123
  setOpenCurrentSale(data?.registerSalesStore?.Response.success)
@@ -152,15 +151,29 @@ export const useSales = ({
152
151
  }
153
152
  })
154
153
  const [productsFood, { loading, fetchMore }] = useProductsFood({
154
+ // @ts-ignore
155
155
  search: search?.length >= 4 ? search : '',
156
156
  gender: [],
157
157
  desc: [],
158
- categories: arr || [],
158
+ categories: [],
159
159
  toDate: valuesDates?.toDate,
160
160
  fromDate: valuesDates?.fromDate,
161
161
  max: showMore,
162
162
  min: 0
163
163
  })
164
+ const handleChangeCheck = (caId) => {
165
+ // @ts-ignore
166
+ setCategories((prev) => {
167
+ return prev.map((item) => {
168
+ // @ts-ignore
169
+ return item.carProId === caId
170
+ // @ts-ignore
171
+ ? { ...item, checked: !item?.checked }
172
+ : item
173
+ })
174
+ })
175
+ }
176
+
164
177
  const max = productsFood?.reduce(function (a, b) {
165
178
  return Math.max(a, b?.ProPrice || 0)
166
179
  }, 0)
@@ -178,6 +191,7 @@ export const useSales = ({
178
191
  }
179
192
  // HANDLESS
180
193
  // FILTER PRODUCT DATA_DB
194
+ // @ts-ignore
181
195
  const handlePrint = ({ callback }) => {
182
196
  if (disabled) {
183
197
  return sendNotification({
@@ -231,6 +245,7 @@ export const useSales = ({
231
245
  return items.pId === id
232
246
  })
233
247
  if (value <= 0) {
248
+ // @ts-ignore
234
249
  dispatch({ type: 'REMOVE_PRODUCT_TO_CART', payload: OneProduct })
235
250
  }
236
251
  const finalQuantity = (state.PRODUCT.ProQuantity = value || 0)
@@ -285,6 +300,7 @@ export const useSales = ({
285
300
  return handleChangeNumber(state, action)
286
301
  }
287
302
  case 'REMOVE_ALL_PRODUCTS':
303
+ // @ts-ignore
288
304
  setValues({
289
305
  comment: '',
290
306
  change: '',
@@ -355,6 +371,7 @@ export const useSales = ({
355
371
  title: 'Comentario eliminado',
356
372
  description: 'Has eliminado el comentario!'
357
373
  })
374
+ // @ts-ignore
358
375
  return dispatch({
359
376
  type: 'PUT_COMMENT',
360
377
  payload: pId,
@@ -362,31 +379,41 @@ export const useSales = ({
362
379
  })
363
380
  }, [])
364
381
  useEffect(() => {
382
+ // @ts-ignore
365
383
  Cookies.set(keyToSaveData, JSON.stringify(data), { domain, path: '/' })
366
384
  }, [data, domain])
367
385
 
368
386
  const handleAddOptional = ({ exOptional = null, codeCategory = null }) => {
369
387
  if (!exOptional || !codeCategory) return
388
+ // @ts-ignore
370
389
  const item = dataOptional.find((item) => item.code === codeCategory)
371
390
  if (!item) return
391
+ // @ts-ignore
372
392
  const idx = item.ExtProductFoodsSubOptionalAll.findIndex(
373
393
  (el) => el.opSubExPid === exOptional
374
394
  )
375
395
  if (item && idx !== -1) {
376
396
  const updatedItem = {
397
+ // @ts-ignore
377
398
  ...item,
378
399
  ExtProductFoodsSubOptionalAll: [
400
+ // @ts-ignore
379
401
  ...item.ExtProductFoodsSubOptionalAll.slice(0, idx),
380
402
  {
403
+ // @ts-ignore
381
404
  ...item.ExtProductFoodsSubOptionalAll[idx],
405
+ // @ts-ignore
382
406
  check: !item.ExtProductFoodsSubOptionalAll[idx].check
383
407
  },
408
+ // @ts-ignore
384
409
  ...item.ExtProductFoodsSubOptionalAll.slice(idx + 1)
385
410
  ]
386
411
  }
387
412
  const newData = dataOptional.map((el) =>
413
+ // @ts-ignore
388
414
  el.code === codeCategory ? updatedItem : el
389
415
  )
416
+ // @ts-ignore
390
417
  setDataOptional(() => [...newData])
391
418
  }
392
419
  }
@@ -414,6 +441,7 @@ export const useSales = ({
414
441
  const arr =
415
442
  dataExtra?.length > 0
416
443
  ? dataExtra?.filter((p) => {
444
+ // @ts-ignore
417
445
  return p.quantity !== 0
418
446
  })
419
447
  : []
@@ -448,6 +476,7 @@ export const useSales = ({
448
476
  }
449
477
  const filteredDataOptional = dataOptional
450
478
  .map((obj) => {
479
+ // @ts-ignore
451
480
  const filteredSubOptions = obj?.ExtProductFoodsSubOptionalAll?.filter(
452
481
  (subObj) => subObj?.check === true
453
482
  )
@@ -455,11 +484,14 @@ export const useSales = ({
455
484
  if (filteredSubOptions?.length === 0) {
456
485
  return null
457
486
  }
487
+ // @ts-ignore
458
488
  return { ...obj, ExtProductFoodsSubOptionalAll: filteredSubOptions }
459
489
  })
460
490
  .filter((obj) => obj !== null) // Elimine todos los objetos nulos del arreglo
491
+ // @ts-ignore
461
492
  const filteredDataExtra = dataExtra?.filter((p) => p?.quantity !== undefined && p?.quantity !== 0)
462
493
  if (product?.PRODUCT?.pId) {
494
+ // @ts-ignore
463
495
  dispatch({
464
496
  type: 'PUT_EXTRA_PRODUCTS_AND_OPTIONAL_PRODUCT',
465
497
  payload: product.PRODUCT.pId,
@@ -476,18 +508,23 @@ export const useSales = ({
476
508
  }
477
509
  }
478
510
 
511
+ // @ts-ignore
479
512
  function handleIncrementExtra ({ Adicionales, index }) {
480
513
  const { pId } = product?.PRODUCT || {}
481
514
  const exPid = Adicionales?.exPid || null
482
515
 
483
516
  if (exPid && pId) {
484
517
  const newExtra = dataExtra.map((producto) => {
518
+ // @ts-ignore
485
519
  if (exPid === producto.exPid) {
520
+ // @ts-ignore
486
521
  const initialQuantity = producto?.quantity ? producto?.quantity : 0
487
522
  const newQuantity = initialQuantity + 1
523
+ // @ts-ignore
488
524
  const newExtraPrice = producto.extraPrice * newQuantity
489
525
 
490
526
  return {
527
+ // @ts-ignore
491
528
  ...producto,
492
529
  quantity: newQuantity,
493
530
  newExtraPrice
@@ -496,22 +533,27 @@ export const useSales = ({
496
533
  return producto
497
534
  })
498
535
 
536
+ // @ts-ignore
499
537
  setDataExtra(newExtra)
500
538
  }
501
539
  }
502
540
 
541
+ // @ts-ignore
503
542
  function handleDecrementExtra ({ Adicionales, index }) {
504
543
  const { pId } = product?.PRODUCT || {}
505
544
  const exPid = Adicionales?.exPid || null
506
545
 
507
546
  // Comprobar que el objeto Adicionales existe en dataExtra
547
+ // @ts-ignore
508
548
  const extraIndex = dataExtra.findIndex((extra) => extra.exPid === exPid)
509
549
  if (extraIndex === -1) {
510
550
  return
511
551
  }
512
552
 
513
553
  if (pId && exPid && extraIndex !== -1) {
554
+ // @ts-ignore
514
555
  const newExtra = dataExtra.map((producto, i) => {
556
+ // @ts-ignore
515
557
  if (exPid === producto.exPid) {
516
558
  // Desestructura la cantidad y el precio extra del producto o establece valores predeterminados
517
559
  const { quantity = 0, extraPrice = 0 } = producto
@@ -523,6 +565,7 @@ export const useSales = ({
523
565
  const newExtraPrice = newQuantity === 0 ? extraPrice : extraPrice * newQuantity
524
566
 
525
567
  return {
568
+ // @ts-ignore
526
569
  ...producto,
527
570
  quantity: newQuantity,
528
571
  newExtraPrice
@@ -532,21 +575,11 @@ export const useSales = ({
532
575
  })
533
576
 
534
577
  // Actualiza el estado de dataExtra con el nuevo array
578
+ // @ts-ignore
535
579
  setDataExtra(newExtra)
536
580
  }
537
581
  }
538
- /**
539
- * Agrega un producto al carrito de compras.
540
- * @param {Object} state - Estado actual del carrito.
541
- * @param {Object} action - Acción que contiene los datos del producto a agregar.
542
- * @param {string} action.payload.pId - ID del producto.
543
- * @param {string} action.payload.pName - Nombre del producto.
544
- * @param {string[]} action.payload.getOneTags - Etiquetas del producto.
545
- * @param {string} action.payload.ProDescription - Descripción del producto.
546
- * @param {string} action.payload.ProImage - URL de la imagen del producto.
547
- * @param {number} action.payload.ProPrice - Precio del producto.
548
- * @returns {Object} Nuevo estado del carrito con el producto agregado.
549
- */
582
+
550
583
  function addToCartFunc (state, action) {
551
584
  const {
552
585
  pId,
@@ -809,6 +842,7 @@ export const useSales = ({
809
842
  })
810
843
  }
811
844
  const decimal = parseFloat(percentage) / 100
845
+ // @ts-ignore
812
846
  const result = decimal * parseFloat(totalProductPrice)
813
847
  setDiscount({ price: result, discount: percentage })
814
848
 
@@ -819,6 +853,7 @@ export const useSales = ({
819
853
  const { getOnePedidoStore } = useGetSale()
820
854
 
821
855
  const handleSubmit = () => {
856
+ // @ts-ignore
822
857
  if (errors?.change || errors?.valueDelivery) {
823
858
  return sendNotification({
824
859
  title: 'error',
@@ -828,6 +863,7 @@ export const useSales = ({
828
863
  }
829
864
  setLoadingSale(true)
830
865
  const code = RandomCode(10)
866
+ // @ts-ignore
831
867
  setCode(code)
832
868
  function convertInteger (cadena) {
833
869
  if (typeof cadena === 'string') {
@@ -859,6 +895,7 @@ export const useSales = ({
859
895
  client.query({
860
896
  query: GET_ALL_COUNT_SALES,
861
897
  fetchPolicy: 'network-only',
898
+ // @ts-ignore
862
899
  onCompleted: (data) => {
863
900
  client.writeQuery({ query: GET_ALL_COUNT_SALES, data: { getTodaySales: data.countSales.todaySales } })
864
901
  }
@@ -904,6 +941,11 @@ export const useSales = ({
904
941
  setLoadingSale(false)
905
942
  setErrorSale(true)
906
943
  setPrint(false)
944
+ sendNotification({
945
+ title: 'error',
946
+ backgroundColor: 'error',
947
+ description: 'Lo sentimos, ocurrió un error'
948
+ })
907
949
  })
908
950
  .finally(() => {
909
951
  setPrint(false)
@@ -1022,10 +1064,48 @@ export const useSales = ({
1022
1064
  }
1023
1065
  }
1024
1066
  const handleCleanFilter = () => {
1067
+ // @ts-ignore
1025
1068
  setValues({})
1026
1069
  setValuesDates({ fromDate: yearMonthDay, toDate: '' })
1027
1070
  }
1028
1071
  const disabledModalItems = dataOptional?.length > 0 || dataExtra?.length > 0
1072
+ /**
1073
+ * Filter products by carProId.
1074
+ * @param {Array} products - Array of products to filter.
1075
+ * @param {Array} carProIds - Array of carProId to filter by.
1076
+ * @returns {Array} - Filtered array of products or all products if no matches found.
1077
+ */
1078
+ function filterProductsByCarProId (products, carProIds) {
1079
+ if (!Array.isArray(products)) {
1080
+ return []
1081
+ }
1082
+
1083
+ if (!Array.isArray(carProIds) || carProIds.length === 0) {
1084
+ return products
1085
+ }
1086
+
1087
+ return products.filter(product => carProIds.includes(product.carProId))
1088
+ }
1089
+
1090
+ /**
1091
+ * Filter objects with checked property equal to true.
1092
+ * @param {Array} products - Array of objects.
1093
+ * @returns {Array} - Array of objects with checked property equal to true.
1094
+ */
1095
+ function filterChecked (products) {
1096
+ if (!Array.isArray(products)) {
1097
+ return []
1098
+ }
1099
+
1100
+ return products.filter(product => product?.checked === true).map(product => product.carProId)
1101
+ }
1102
+
1103
+ // Obtener los carProIds de productos con checked en true
1104
+ const carProIds = filterChecked(categories)
1105
+
1106
+ // Filtrar los productos de productsFood por los carProIds obtenidos
1107
+ const filteredProducts = filterProductsByCarProId(productsFood, carProIds)
1108
+
1029
1109
  return {
1030
1110
  loading: loading || loadingSale,
1031
1111
  loadingExtraProduct,
@@ -1050,7 +1130,7 @@ export const useSales = ({
1050
1130
  search,
1051
1131
  values,
1052
1132
  initialStateSales,
1053
- productsFood,
1133
+ productsFood: filteredProducts,
1054
1134
  modalItem,
1055
1135
  sumExtraProducts,
1056
1136
  oneProductToComment: oneProductToComment ?? null,
@@ -1059,10 +1139,8 @@ export const useSales = ({
1059
1139
  dataExtra: dataExtra || [],
1060
1140
  fetchMore,
1061
1141
  discount,
1062
- checkedItems,
1063
- datCat,
1064
- disabledItems,
1065
- setCheckedItems,
1142
+ datCat: categories,
1143
+ loadingProduct: loading,
1066
1144
  handleChangeCheck,
1067
1145
  errors,
1068
1146
  handleUpdateAllExtra,
@@ -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()
package/src/index.jsx CHANGED
@@ -1,4 +1,4 @@
1
1
  export * from './hooks/index'
2
2
  export * from './utils'
3
3
  export * from './cookies'
4
- export * from './security'
4
+ export * from './security/index'
@@ -0,0 +1 @@
1
+ export const future = null