npm-pkg-hook 1.0.8 → 1.1.0

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
@@ -7,7 +7,7 @@
7
7
  "publishConfig": {
8
8
  "registry": "https://registry.npmjs.org/"
9
9
  },
10
- "version": "1.0.8",
10
+ "version": "1.1.0",
11
11
  "description": "description-pkg-hook",
12
12
  "main": "/src/index.jsx",
13
13
  "scripts": {
@@ -9,6 +9,8 @@ export * from './useLogout'
9
9
  export * from './useEmployee'
10
10
  export * from './useCheckbox'
11
11
  export * from './useClients'
12
+ export * from './useOrders'
13
+ export * from './useUpdateExistingOrders'
12
14
  export * from './useConnection'
13
15
  export * from './useCreateProduct'
14
16
  export * from './useCreateProduct/helpers/useEditImageProduct'
@@ -51,7 +51,7 @@ export const useCreateProduct = ({
51
51
 
52
52
  const handleCheck = (e) => {
53
53
  const { name, checked } = e.target
54
- return setCheck({ ...check, [name]: checked ? true : false })
54
+ return setCheck((prev) =>({ ...prev, [name]: checked }))
55
55
  }
56
56
 
57
57
  const handleUpdateBanner = event => {
@@ -120,12 +120,13 @@ export const useCreateProduct = ({
120
120
  alt: files[0].name
121
121
  }
122
122
  : initialState
123
- )
123
+ )
124
124
  }
125
125
  const onTargetClick = () => {
126
126
  fileInputRef.current.click()
127
127
  }
128
128
  const { img } = useEditImageProduct({ sendNotification, initialState })
129
+ console.log(values)
129
130
  const handleRegister = async () => {
130
131
  const {
131
132
  ProPrice,
@@ -141,7 +142,7 @@ export const useCreateProduct = ({
141
142
  if (!ProPrice?.length > 0) {
142
143
  return setErrors({ ...errors, ProPrice: true })
143
144
  }
144
- const ProImage = `${process.env.URL_ADMIN_SERVER}static/platos/${image?.name}`
145
+ const ProImage = `https:${process.env.URL_ADMIN_SERVER}static/platos/${image?.name}`
145
146
  const pCode = RandomCode(9)
146
147
  const formatPrice = ProPrice ? parseFloat(ProPrice.replace(/\./g, '')) : 0
147
148
  try {
@@ -149,9 +150,9 @@ export const useCreateProduct = ({
149
150
  variables: {
150
151
  input: {
151
152
  idStore: dataStore?.getStore?.idStore || '',
152
- ProPrice: check ? 0 : formatPrice,
153
- ProDescuento: check ? 0 : parseInt(ProDescuento),
154
- ValueDelivery: check ? 0 : parseFloat(ValueDelivery),
153
+ ProPrice: check?.desc ? 0 : formatPrice,
154
+ ProDescuento: check?.desc ? 0 : parseInt(ProDescuento),
155
+ ValueDelivery: check?.desc ? 0 : parseFloat(ValueDelivery),
155
156
  ProDescription,
156
157
  pName: names,
157
158
  pCode,
@@ -162,8 +163,8 @@ export const useCreateProduct = ({
162
163
  ProImage,
163
164
  ProHeight: parseFloat(ProHeight),
164
165
  ProWeight,
165
- ProOutstanding: check ? 1 : 0,
166
- ProDelivery: check ? 1 : 0
166
+ ProOutstanding: check?.desc ? 1 : 0,
167
+ ProDelivery: check?.desc ? 1 : 0
167
168
  }
168
169
  },
169
170
  update (cache) {
@@ -275,6 +276,7 @@ export const useCreateProduct = ({
275
276
  setShowMore,
276
277
  onTargetClick,
277
278
  handleAddTag,
279
+ handleCheck,
278
280
  handleCheckFreeShipping,
279
281
  check
280
282
  }
@@ -1,6 +1,7 @@
1
1
  import React, {
2
2
  useEffect,
3
- useRef, useState
3
+ useRef,
4
+ useState
4
5
  } from 'react'
5
6
 
6
7
  export const useFetchMoreInteractions = ({
@@ -12,7 +12,7 @@ import {
12
12
  } from '../useProductsFood/queriesStore';
13
13
  import { GET_ONE_STORE } from '../useStore/queries';
14
14
 
15
- export const useImageStore = (idStore) => {
15
+ export const useImageStore = ({ idStore, sendNotification = () => { return } } = {}) => {
16
16
  // STATES
17
17
  const fileInputRef = useRef(null)
18
18
  const [{ altLogo, srcLogo }, setPreviewImgLogo] = useState({})
@@ -86,13 +86,20 @@ export const useImageStore = (idStore) => {
86
86
  })
87
87
  }
88
88
  }).catch(() => {
89
- console.log({ message: 'No pudimos cargar la imagen', duration: 7000 })
89
+ sendNotification({
90
+ title: 'No pudimos cargar la imagen',
91
+ description: 'Error',
92
+ backgroundColor: 'error'
93
+ })
90
94
  setPreviewImg(initialState)
91
95
  })
92
-
93
96
  } catch {
94
97
  setPreviewImg(initialState)
95
- console.log({ message: 'No pudimos cargar la imagen', duration: 7000 })
98
+ sendNotification({
99
+ title: 'No pudimos cargar la imagen',
100
+ description: 'Error',
101
+ backgroundColor: 'error'
102
+ })
96
103
  }
97
104
  }
98
105
  const handleInputChangeLogo = event => {
@@ -119,7 +126,11 @@ export const useImageStore = (idStore) => {
119
126
  })
120
127
  }
121
128
  }).catch(() => {
122
- console.log({ message: 'No pudimos cargar el banner', duration: 7000 })
129
+ sendNotification({
130
+ title: 'No pudimos cargar la imagen',
131
+ description: 'Error',
132
+ backgroundColor: 'error'
133
+ })
123
134
  setPreviewImgLogo(initialState)
124
135
  })
125
136
  }
@@ -0,0 +1,81 @@
1
+ /* eslint-disable react-hooks/exhaustive-deps */
2
+ import { useQuery } from '@apollo/client'
3
+ import {
4
+ useState
5
+ } from 'react'
6
+ import { GET_ALL_PEDIDOS, GET_ALL_PEDIDOS_FROM_STORE } from './queries'
7
+
8
+ export const useOrders = ({
9
+ refetchWritePolicy = 'merge',
10
+ refetchReadPolicy,
11
+ refetch,
12
+ statusOrder,
13
+ fromDate,
14
+ toDate,
15
+ nextFetchPolicy = 'cache-first',
16
+ fetchPolicy = 'cache-and-network',
17
+ pollInterval = 60000,
18
+ onError
19
+ }) => {
20
+ const { data, loading, error, fetchMore } = useQuery(GET_ALL_PEDIDOS, {
21
+ notifyOnNetworkStatusChange: true,
22
+ refetchWritePolicy: refetchWritePolicy,
23
+ pollInterval,
24
+ fetchPolicy,
25
+ refetch,
26
+ refetchReadPolicy,
27
+ nextFetchPolicy: nextFetchPolicy,
28
+ onError: onError
29
+ ? onError
30
+ : () => {
31
+ return
32
+ },
33
+ variables: {
34
+ statusOrder: statusOrder,
35
+ fromDate,
36
+ toDate
37
+ }
38
+ })
39
+
40
+ return [
41
+ data?.getAllPedidoStoreFinal,
42
+ { loading, error, data, fetchMore }
43
+ ]
44
+ }
45
+
46
+ export const useOrdersFromStore = ({
47
+ idStore,
48
+ cId,
49
+ dId,
50
+ ctId,
51
+ search = '',
52
+ min,
53
+ fromDate,
54
+ toDate,
55
+ max,
56
+ statusOrder
57
+ }) => {
58
+ const {
59
+ data,
60
+ loading,
61
+ error,
62
+ called
63
+ } = useQuery(GET_ALL_PEDIDOS_FROM_STORE, {
64
+ variables: {
65
+ idStore,
66
+ cId,
67
+ dId,
68
+ ctId,
69
+ search,
70
+ min,
71
+ fromDate,
72
+ toDate,
73
+ max,
74
+ statusOrder
75
+ }
76
+ });
77
+
78
+ return [data?.getAllOrdersFromStore || [], { loading: called ? false: loading, error }];
79
+ };
80
+
81
+ export * from './queries'
@@ -0,0 +1,328 @@
1
+ import { gql } from '@apollo/client'
2
+
3
+ export const CHANGE_STATE_STORE_PEDIDO = gql`
4
+ mutation changePPStatePPedido($pPStateP: Int, $pCodeRef: String, $pDatMod: String) {
5
+ changePPStatePPedido(pPStateP: $pPStateP, pCodeRef: $pCodeRef, pDatMod: $pDatMod){
6
+ success
7
+ message
8
+ }
9
+ }
10
+
11
+ `
12
+ export const GET_ALL_PEDIDOS = gql`
13
+ query getAllPedidoStoreFinal($idStore: ID, $search: String, $min: Int, $max: Int, $statusOrder: Int, $fromDate: DateTime, $toDate: DateTime) {
14
+ getAllPedidoStoreFinal(idStore: $idStore, search: $search, min: $min, max: $max, statusOrder: $statusOrder, toDate: $toDate,fromDate: $fromDate ) {
15
+ pdpId
16
+ idStore
17
+ pCodeRef
18
+ payMethodPState
19
+ pPRecoger
20
+ totalProductsPrice
21
+ pSState
22
+ pDatCre
23
+ channel
24
+ locationUser
25
+ pDatMod
26
+ getAllPedidoStore{
27
+ pdpId
28
+ pId
29
+ idStore
30
+ ShoppingCard
31
+ pCodeRef
32
+ pPStateP
33
+ payMethodPState
34
+ pPRecoger
35
+ pDatCre
36
+ pDatMod
37
+ getAllShoppingCard {
38
+ ShoppingCard
39
+ comments
40
+ cantProducts
41
+ pId
42
+ productFood{
43
+ pId
44
+ carProId
45
+ colorId
46
+ idStore
47
+ pName
48
+ ProPrice
49
+ ProDescuento
50
+ ProDescription
51
+ ValueDelivery
52
+ ProImage
53
+ ProStar
54
+ pState
55
+ pDatCre
56
+ pDatMod
57
+ }
58
+ }
59
+ }
60
+ }
61
+ }
62
+ `
63
+
64
+ export const GET_ALL_PEDIDOS_FROM_STORE = gql`
65
+ query getAllOrdersFromStore(
66
+ $idStore: ID
67
+ $cId: ID
68
+ $dId: ID
69
+ $ctId: ID
70
+ $search: String
71
+ $min: Int
72
+ $fromDate: DateTime
73
+ $toDate: DateTime
74
+ $max: Int
75
+ $statusOrder: Int
76
+ ) {
77
+ getAllOrdersFromStore(
78
+ idStore: $idStore
79
+ cId: $cId
80
+ dId: $dId
81
+ ctId: $ctId
82
+ search: $search
83
+ min: $min
84
+ fromDate: $fromDate
85
+ toDate: $toDate
86
+ max: $max
87
+ statusOrder: $statusOrder
88
+ ) {
89
+ ACEPTA {
90
+ pdpId
91
+ idStore
92
+ pCodeRef
93
+ payMethodPState
94
+ pPRecoger
95
+ totalProductsPrice
96
+ pSState
97
+ pDatCre
98
+ channel
99
+ locationUser
100
+ pDatMod
101
+ getAllPedidoStore {
102
+ pdpId
103
+ pId
104
+ idStore
105
+ ShoppingCard
106
+ pCodeRef
107
+ pPStateP
108
+ payMethodPState
109
+ pPRecoger
110
+ pDatCre
111
+ pDatMod
112
+ getAllShoppingCard {
113
+ ShoppingCard
114
+ comments
115
+ cantProducts
116
+ pId
117
+ productFood {
118
+ pId
119
+ carProId
120
+ colorId
121
+ idStore
122
+ pName
123
+ ProPrice
124
+ ProDescuento
125
+ ProDescription
126
+ ValueDelivery
127
+ ProImage
128
+ ProStar
129
+ pState
130
+ pDatCre
131
+ pDatMod
132
+ }
133
+ }
134
+ }
135
+ }
136
+ PROCESSING {
137
+ pdpId
138
+ idStore
139
+ pCodeRef
140
+ payMethodPState
141
+ pPRecoger
142
+ totalProductsPrice
143
+ pSState
144
+ pDatCre
145
+ channel
146
+ locationUser
147
+ pDatMod
148
+ getAllPedidoStore {
149
+ pdpId
150
+ pId
151
+ idStore
152
+ ShoppingCard
153
+ pCodeRef
154
+ pPStateP
155
+ payMethodPState
156
+ pPRecoger
157
+ pDatCre
158
+ pDatMod
159
+ getAllShoppingCard {
160
+ ShoppingCard
161
+ comments
162
+ cantProducts
163
+ pId
164
+ productFood {
165
+ pId
166
+ carProId
167
+ colorId
168
+ idStore
169
+ pName
170
+ ProPrice
171
+ ProDescuento
172
+ ProDescription
173
+ ValueDelivery
174
+ ProImage
175
+ ProStar
176
+ pState
177
+ pDatCre
178
+ pDatMod
179
+ }
180
+ }
181
+ }
182
+ }
183
+ READY {
184
+ pdpId
185
+ idStore
186
+ pCodeRef
187
+ payMethodPState
188
+ pPRecoger
189
+ totalProductsPrice
190
+ pSState
191
+ pDatCre
192
+ channel
193
+ locationUser
194
+ pDatMod
195
+ getAllPedidoStore {
196
+ pdpId
197
+ pId
198
+ idStore
199
+ ShoppingCard
200
+ pCodeRef
201
+ pPStateP
202
+ payMethodPState
203
+ pPRecoger
204
+ pDatCre
205
+ pDatMod
206
+ getAllShoppingCard {
207
+ ShoppingCard
208
+ comments
209
+ cantProducts
210
+ pId
211
+ productFood {
212
+ pId
213
+ carProId
214
+ colorId
215
+ idStore
216
+ pName
217
+ ProPrice
218
+ ProDescuento
219
+ ProDescription
220
+ ValueDelivery
221
+ ProImage
222
+ ProStar
223
+ pState
224
+ pDatCre
225
+ pDatMod
226
+ }
227
+ }
228
+ }
229
+ }
230
+ CONCLUDES {
231
+ pdpId
232
+ idStore
233
+ pCodeRef
234
+ payMethodPState
235
+ pPRecoger
236
+ totalProductsPrice
237
+ pSState
238
+ pDatCre
239
+ channel
240
+ locationUser
241
+ pDatMod
242
+ getAllPedidoStore {
243
+ pdpId
244
+ pId
245
+ idStore
246
+ ShoppingCard
247
+ pCodeRef
248
+ pPStateP
249
+ payMethodPState
250
+ pPRecoger
251
+ pDatCre
252
+ pDatMod
253
+ getAllShoppingCard {
254
+ ShoppingCard
255
+ comments
256
+ cantProducts
257
+ pId
258
+ productFood {
259
+ pId
260
+ carProId
261
+ colorId
262
+ idStore
263
+ pName
264
+ ProPrice
265
+ ProDescuento
266
+ ProDescription
267
+ ValueDelivery
268
+ ProImage
269
+ ProStar
270
+ pState
271
+ pDatCre
272
+ pDatMod
273
+ }
274
+ }
275
+ }
276
+ }
277
+ RECHAZADOS {
278
+ pdpId
279
+ idStore
280
+ pCodeRef
281
+ payMethodPState
282
+ pPRecoger
283
+ totalProductsPrice
284
+ pSState
285
+ pDatCre
286
+ channel
287
+ locationUser
288
+ pDatMod
289
+ getAllPedidoStore {
290
+ pdpId
291
+ pId
292
+ idStore
293
+ ShoppingCard
294
+ pCodeRef
295
+ pPStateP
296
+ payMethodPState
297
+ pPRecoger
298
+ pDatCre
299
+ pDatMod
300
+ getAllShoppingCard {
301
+ ShoppingCard
302
+ comments
303
+ cantProducts
304
+ pId
305
+ productFood {
306
+ pId
307
+ carProId
308
+ colorId
309
+ idStore
310
+ pName
311
+ ProPrice
312
+ ProDescuento
313
+ ProDescription
314
+ ValueDelivery
315
+ ProImage
316
+ ProStar
317
+ pState
318
+ pDatCre
319
+ pDatMod
320
+ }
321
+ }
322
+ }
323
+ }
324
+ }
325
+ }
326
+
327
+
328
+ `
@@ -5,12 +5,14 @@ import {
5
5
  } from '@apollo/client'
6
6
  import { useState } from 'react'
7
7
  import {
8
+ GET_ALL_CATEGORIES_WITH_PRODUCT,
8
9
  GET_ALL_EXTRA_PRODUCT,
9
10
  GET_ALL_PRODUCT_STORE,
10
11
  GET_EXTRAS_PRODUCT_FOOD_OPTIONAL,
11
12
  GET_ONE_PRODUCTS_FOOD,
12
13
  UPDATE_PRODUCT_FOOD
13
14
  } from './queriesStore'
15
+ export * from './useEditProduct'
14
16
 
15
17
  /**
16
18
  * Description
@@ -71,8 +73,8 @@ export const useProductsFood = ({
71
73
  ]
72
74
  }
73
75
 
74
- export const useDeleteProductsFood = () => {
75
- const [updateProductFoods] = useMutation(UPDATE_PRODUCT_FOOD)
76
+ export const useDeleteProductsFood = ({ sendNotification = () => { return } } = {}) => {
77
+ const [updateProductFoods, { data, loading, error }] = useMutation(UPDATE_PRODUCT_FOOD)
76
78
 
77
79
  const handleDelete = product => {
78
80
  const { pId, pState } = product || {}
@@ -98,10 +100,23 @@ export const useDeleteProductsFood = () => {
98
100
  }
99
101
  })
100
102
  }
101
- }).catch(err => { return console.log({ message: `${err}`, duration: 7000 }) })
103
+ }).then(() => {
104
+ return sendNotification({
105
+ title: 'Success',
106
+ description: 'El producto se ha eliminado correctamente',
107
+ backgroundColor: 'success'
108
+ })
109
+ }).catch((e) => {
110
+ console.log(e)
111
+ return sendNotification({
112
+ title: 'Error',
113
+ description: 'Ocurrió un error',
114
+ backgroundColor: 'error'
115
+ })
116
+ })
102
117
  }
103
118
  return {
104
- handleDelete
119
+ handleDelete, data, loading, error
105
120
  }
106
121
  }
107
122
 
@@ -0,0 +1,10 @@
1
+ import { useMutation } from '@apollo/client'
2
+ import React from 'react'
3
+ import { EDIT_PRODUCT } from './queriesStore'
4
+
5
+ export const useEditProduct = () => {
6
+ const [editProductFoods, { loading, error }] = useMutation(EDIT_PRODUCT)
7
+
8
+ return [editProductFoods, { loading: loading, error: error }]
9
+ }
10
+
@@ -72,9 +72,9 @@ export const useSales = ({
72
72
  const [print, setPrint] = useState(false);
73
73
  const [values, setValues] = useState({});
74
74
  const [dataStore] = useStore();
75
+ const { createdAt } = dataStore || {};
75
76
  const [code, setCode] = useState(null);
76
77
  const [openCurrentSale, setOpenCurrentSale] = useState(null);
77
- const { createdAt } = dataStore || {};
78
78
  const [oneProductToComment, setOneProductToComment] = useState({});
79
79
  const [sumExtraProducts, setSumExtraProducts] = useState(0);
80
80
  const { yearMonthDay } = useFormatDate({ date: createdAt });
@@ -489,48 +489,67 @@ export const useSales = ({
489
489
  setDataExtra(newExtra);
490
490
  }
491
491
  }
492
-
492
+ /**
493
+ * Agrega un producto al carrito de compras.
494
+ * @param {Object} state - Estado actual del carrito.
495
+ * @param {Object} action - Acción que contiene los datos del producto a agregar.
496
+ * @param {string} action.payload.pId - ID del producto.
497
+ * @param {string} action.payload.pName - Nombre del producto.
498
+ * @param {string[]} action.payload.getOneTags - Etiquetas del producto.
499
+ * @param {string} action.payload.ProDescription - Descripción del producto.
500
+ * @param {string} action.payload.ProImage - URL de la imagen del producto.
501
+ * @param {number} action.payload.ProPrice - Precio del producto.
502
+ * @returns {Object} Nuevo estado del carrito con el producto agregado.
503
+ */
493
504
  function addToCartFunc(state, action) {
494
- const productExist = state.PRODUCT.find((items) => {
495
- return items.pId === action.payload.pId;
496
- });
497
- const OurProduct = productsFood.find((items) => {
498
- return items.pId === action.payload.pId;
499
- });
505
+ const { pId, pName, getOneTags, ProDescription, ProImage, ProPrice } = action.payload;
506
+
507
+ const productExist = state.PRODUCT.find((item) => item.pId === pId);
508
+ const OurProduct = productsFood.find((item) => item.pId === pId);
500
509
  const isFree = productExist?.free;
510
+
511
+ const updatedProduct = {
512
+ pId,
513
+ pName,
514
+ getOneTags,
515
+ unitPrice: OurProduct?.ProPrice,
516
+ ProDescription,
517
+ ProImage,
518
+ ProPrice,
519
+ ProQuantity: 1,
520
+ };
521
+
522
+ if (!productExist) {
523
+ return {
524
+ ...state,
525
+ counter: state.counter + 1,
526
+ totalAmount: state.totalAmount + ProPrice,
527
+ startAnimateUp: "start-animate-up",
528
+ PRODUCT: [...state.PRODUCT, updatedProduct],
529
+ };
530
+ }
531
+
501
532
  return {
502
533
  ...state,
503
534
  counter: state.counter + 1,
504
- totalAmount: state.totalAmount + action.payload.ProPrice,
535
+ totalAmount: state.totalAmount + ProPrice,
505
536
  startAnimateUp: "start-animate-up",
506
- PRODUCT: !productExist
507
- ? [
508
- ...state.PRODUCT,
509
- {
510
- pId: action.payload.pId,
511
- pName: action.payload.pName,
512
- unitPrice: OurProduct?.ProPrice,
513
- ProDescription: action.payload.ProDescription,
514
- ProImage: action.payload.ProImage,
515
- ProPrice: action.payload.ProPrice,
516
- ProQuantity: 1,
517
- },
518
- ]
519
- : state.PRODUCT.map((items) => {
520
- return items.pId === action.payload.pId
521
- ? {
522
- ...items,
523
- unitPrice: OurProduct?.ProPrice,
524
- ProPrice: isFree
525
- ? 0
526
- : (productExist.ProQuantity + 1) * OurProduct?.ProPrice,
527
- ProQuantity: productExist.ProQuantity + 1,
528
- free: isFree ? true : false,
529
- }
530
- : items;
531
- }),
537
+ PRODUCT: state.PRODUCT.map((item) => {
538
+ if (item.pId === pId) {
539
+ return {
540
+ ...item,
541
+ getOneTags: OurProduct.genderTags,
542
+ unitPrice: OurProduct?.ProPrice,
543
+ ProPrice: isFree ? 0 : (productExist.ProQuantity + 1) * OurProduct?.ProPrice,
544
+ ProQuantity: productExist.ProQuantity + 1,
545
+ free: isFree ? true : false,
546
+ };
547
+ }
548
+ return item;
549
+ }),
532
550
  };
533
551
  }
552
+
534
553
  function removeFunc(state, action) {
535
554
  const productExist = state.PRODUCT.find((items) => {
536
555
  return items.pId === action.payload.pId;
@@ -1,5 +1,4 @@
1
- import { useState } from 'react';
2
- import { useRouter } from 'next/router';
1
+ import { useState, useEffect } from 'react';
3
2
  import { useApolloClient, useQuery } from '@apollo/client';
4
3
  import { GET_ONE_STORE } from './queries'; // Reemplaza con la importación correcta de tu consulta
5
4
  import { errorHandler } from '../../config/client'
@@ -8,16 +7,19 @@ import { useLogout } from '../useLogout'
8
7
  export const useStore = () => {
9
8
  const [store, setStore] = useState({});
10
9
  const client = useApolloClient();
11
- const [onClickLogout, { loading: load, error: err }] = useLogout()
10
+ const [onClickLogout, { loading: load, error: err }] = useLogout();
11
+
12
12
  // Intentar leer los datos de la caché
13
13
  const cachedData = client.readQuery({ query: GET_ONE_STORE });
14
14
 
15
- if (cachedData) {
16
- // Comprobar si los datos de la caché ya están establecidos en el estado
17
- if (!store || Object.keys(store).length === 0) {
18
- setStore(cachedData.getStore);
15
+ useEffect(() => {
16
+ if (cachedData) {
17
+ // Comprobar si los datos de la caché ya están establecidos en el estado
18
+ if (!store || Object.keys(store).length === 0) {
19
+ setStore(cachedData.getStore);
20
+ }
19
21
  }
20
- }
22
+ }, [cachedData, store]);
21
23
 
22
24
  const { loading, error } = useQuery(GET_ONE_STORE, {
23
25
  fetchPolicy: 'cache-first',
@@ -29,19 +31,31 @@ export const useStore = () => {
29
31
  if (err.networkError && err.networkError.result) {
30
32
  const response = errorHandler(err.networkError.result);
31
33
  if (response) {
32
- onClickLogout()
34
+ onClickLogout();
33
35
  }
34
36
  }
35
37
  },
36
38
  });
37
39
 
38
- // Actualizar manualmente la caché después de cada petición exitosa
39
- if (!loading && !error && !cachedData) {
40
- client.writeQuery({
41
- query: GET_ONE_STORE,
42
- data: { getStore: store },
40
+ // Ejecutar la consulta y almacenarla en la caché
41
+ useEffect(() => {
42
+ client.query({ query: GET_ONE_STORE }).then(() => {
43
+ // Leer la consulta desde la caché
44
+ const cacheData = client.readQuery({ query: GET_ONE_STORE });
45
+ setStore(cacheData?.getStore)
43
46
  });
44
- }
47
+ }, [client]);
45
48
 
46
- return [store, { loading, error }];
49
+ // Actualizar manualmente la caché después de cada petición exitosa
50
+ useEffect(() => {
51
+ if (!loading && !error && !cachedData) {
52
+ client.writeQuery({
53
+ query: GET_ONE_STORE,
54
+ data: { getStore: store },
55
+ });
56
+ }
57
+ }, [loading, error, cachedData, client, store]);
58
+
59
+ return [store, { loading: load || loading, error }];
47
60
  };
61
+
@@ -0,0 +1,91 @@
1
+ export const isValidCodeRef = (codeRef) => {
2
+ return typeof codeRef === "string" && codeRef.trim() !== "";
3
+ };
4
+
5
+ export const isValidState = (state) => {
6
+ const validStates = [0, 1, 2, 3, 4, 5];
7
+ return validStates.includes(state);
8
+ };
9
+
10
+ export const updateExistingOrders = (
11
+ existingOrders,
12
+ pCodeRef,
13
+ pSState,
14
+ objectToAdd
15
+ ) => {
16
+ if (typeof existingOrders !== "object" || existingOrders === null) {
17
+ // existingOrders no es un objeto válido
18
+ return existingOrders;
19
+ }
20
+ if (typeof pCodeRef !== "string" || typeof pSState !== "number") {
21
+ // Los tipos de datos de pCodeRef y pSState no son los esperados
22
+ return existingOrders;
23
+ }
24
+ if (!isValidCodeRef(pCodeRef) || !isValidState(pSState)) {
25
+ // Valores de entrada no válidos, devuelve existingOrders sin cambios
26
+ return existingOrders;
27
+ }
28
+
29
+ const updatedExistingOrders = { ...existingOrders }; // Copiar el objeto existente
30
+
31
+ const statusKeys = {
32
+ 1: "ACEPTA",
33
+ 2: "PROCESSING",
34
+ 3: "READY",
35
+ 4: "CONCLUDES",
36
+ 5: "RECHAZADOS",
37
+ };
38
+ const targetArray = statusKeys[pSState];
39
+
40
+ if (!targetArray || !(targetArray in existingOrders)) {
41
+ // El valor de pSState no está mapeado a ninguna propiedad existente en existingOrders
42
+ return existingOrders;
43
+ }
44
+
45
+ Object.keys(updatedExistingOrders).forEach((key) => {
46
+ if (Array.isArray(updatedExistingOrders[key])) {
47
+ const oneSale = updatedExistingOrders[key].find((order) => {
48
+ return order.pCodeRef === pCodeRef;
49
+ });
50
+
51
+ updatedExistingOrders[key] = updatedExistingOrders[key].filter(
52
+ (order) => {
53
+ return order.pCodeRef !== pCodeRef;
54
+ }
55
+ );
56
+
57
+ if (oneSale !== undefined && oneSale !== null) {
58
+ const updatedOneSale = { ...oneSale, pSState };
59
+
60
+ if (!Array.isArray(updatedExistingOrders[targetArray])) {
61
+ updatedExistingOrders[targetArray] = [];
62
+ }
63
+
64
+ updatedExistingOrders[targetArray] = [
65
+ updatedOneSale,
66
+ ...updatedExistingOrders[targetArray],
67
+ ];
68
+ }
69
+ }
70
+ });
71
+
72
+ if (objectToAdd && objectToAdd.pCodeRef === pCodeRef) {
73
+ if (!Array.isArray(updatedExistingOrders[targetArray])) {
74
+ updatedExistingOrders[targetArray] = [];
75
+ }
76
+
77
+ updatedExistingOrders[targetArray] = [
78
+ objectToAdd,
79
+ ...updatedExistingOrders[targetArray],
80
+ ];
81
+ }
82
+
83
+ // Asegurar que todas las propiedades estén presentes
84
+ Object.keys(statusKeys).forEach((statusKey) => {
85
+ if (!(statusKeys[statusKey] in updatedExistingOrders)) {
86
+ updatedExistingOrders[statusKeys[statusKey]] = [];
87
+ }
88
+ });
89
+
90
+ return updatedExistingOrders;
91
+ };