npm-pkg-hook 1.0.5 → 1.0.6

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.
@@ -1,245 +1,285 @@
1
- import { useLazyQuery, useMutation } from '@apollo/client'
1
+ import { useLazyQuery, useMutation } from "@apollo/client";
2
+ import { useCallback, useEffect, useReducer, useState } from "react";
3
+ import { Cookies } from "../../cookies";
2
4
  import {
3
- useCallback,
4
- useEffect,
5
- useReducer,
6
- useState
7
- } from 'react'
8
- import { Cookies } from '../../cookies'
9
- import {
10
- getCurrentDomain,
11
5
  RandomCode,
6
+ getCurrentDomain,
12
7
  updateCacheMod
13
- } from '../../utils'
14
- import { useFormatDate } from '../useFormatDate'
15
- import { useProductsFood } from '../useProductsFood'
8
+ } from "../../utils";
9
+ import { useFormatDate } from "../useFormatDate";
10
+ import { useProductsFood } from "../useProductsFood";
16
11
  import {
17
12
  GET_ALL_EXTRA_PRODUCT,
18
13
  GET_EXTRAS_PRODUCT_FOOD_OPTIONAL,
19
- GET_ONE_PRODUCTS_FOOD
20
- } from '../useProductsFood/queriesStore'
21
- import { useStore } from '../useStore'
14
+ GET_ONE_PRODUCTS_FOOD,
15
+ } from "../useProductsFood/queriesStore";
16
+ import { useStore } from "../useStore";
22
17
  import {
23
18
  CREATE_SHOPPING_CARD_TO_USER_STORE,
24
19
  GET_ALL_COUNT_SALES,
25
20
  GET_ALL_SALES,
26
- GET_ALL_SALES_STATISTICS
27
- } from './queries'
21
+ GET_ALL_SALES_STATISTICS,
22
+ } from "./queries";
28
23
 
29
24
  const initialState = {
30
25
  PRODUCT: [],
31
26
  totalPrice: 0,
32
27
  sortBy: null,
33
28
  itemsInCart: 0,
34
- animateType: '',
35
- startAnimateUp: '',
29
+ animateType: "",
30
+ startAnimateUp: "",
36
31
  priceRange: 0,
37
32
  counter: 0,
38
33
  totalAmount: 0,
39
- payMethodPState: 0
40
- }
34
+ payMethodPState: 0,
35
+ };
41
36
 
42
- const initializer = (initialValue = initialState) => { return JSON.parse(Cookies.get(process.env.LOCAL_SALES_STORE) || JSON.stringify(initialState)) || initialValue }
37
+ const initializer = (initialValue = initialState) => {
38
+ return (
39
+ JSON.parse(
40
+ Cookies.get(process.env.LOCAL_SALES_STORE) || JSON.stringify(initialState)
41
+ ) || initialValue
42
+ );
43
+ };
43
44
 
44
45
  export const useSales = ({
45
46
  disabled,
46
47
  sendNotification,
47
48
  router,
48
- setAlertBox
49
+ setAlertBox,
49
50
  }) => {
50
- const domain = getCurrentDomain()
51
- const [modalItem, setModalItem] = useState(false)
52
- const [openCommentModal, setOpenCommentModal] = useState(false)
53
- const keyToSaveData = process.env.LOCAL_SALES_STORE
54
- const saveDataState = JSON.parse(Cookies.get(keyToSaveData) || '[]')
55
- const [search, setSearch] = useState('')
56
- const [arr] = useState([])
57
- const [totalProductPrice, setTotalProductPrice] = useState(0)
58
- const [showMore, setShowMore] = useState(50)
59
- const [inputValue, setInputValue] = useState('')
51
+ const domain = getCurrentDomain();
52
+ const [loadingSale, setLoadingSale] = useState(false);
53
+ const [errorSale, setErrorSale] = useState(false);
54
+ const [modalItem, setModalItem] = useState(false);
55
+ const [openCommentModal, setOpenCommentModal] = useState(false);
56
+ const keyToSaveData = process.env.LOCAL_SALES_STORE;
57
+ const saveDataState = JSON.parse(Cookies.get(keyToSaveData) || "[]");
58
+ const [search, setSearch] = useState("");
59
+ const [arr, setArrayCategory] = useState([]);
60
+ const [totalProductPrice, setTotalProductPrice] = useState(0);
61
+ const [showMore, setShowMore] = useState(100);
62
+ const [inputValue, setInputValue] = useState("");
60
63
  const [_, setFilteredList] = useState([]);
61
- const [delivery, setDelivery] = useState(false)
62
- const [print, setPrint] = useState(false)
63
- const [values, setValues] = useState({})
64
- const [dataStore] = useStore()
65
- const [code, setCode] = useState(null)
66
- const [openCurrentSale, setOpenCurrentSale] = useState(null)
67
- const { createdAt } = dataStore || {}
68
- const {yearMonthDay} = useFormatDate({ date: createdAt })
69
- const [valuesDates, setValuesDates] = useState(() => { return { fromDate: yearMonthDay, toDate: '' } })
64
+ const [delivery, setDelivery] = useState(false);
65
+ const [print, setPrint] = useState(false);
66
+ const [values, setValues] = useState({});
67
+ const [dataStore] = useStore();
68
+ const [code, setCode] = useState(null);
69
+ const [openCurrentSale, setOpenCurrentSale] = useState(null);
70
+ const { createdAt } = dataStore || {};
71
+ const { yearMonthDay } = useFormatDate({ date: createdAt });
72
+ const [valuesDates, setValuesDates] = useState(() => {
73
+ return { fromDate: yearMonthDay, toDate: "" };
74
+ });
75
+ const [dataOptional, setDataOptional] = useState([]);
76
+ const [dataExtra, setDataExtra] = useState([]);
70
77
 
71
- const [registerSalesStore, { loading: loadingRegisterSale }] = useMutation(CREATE_SHOPPING_CARD_TO_USER_STORE, {
72
- onCompleted: (data) => {
73
- const message = `${data?.registerSalesStore?.Response?.message}`
74
- const error = data?.registerSalesStore?.Response.success ? 'Éxito' : 'Error'
75
- sendNotification({ title: error, description: message })
76
- setAlertBox({ message: message, type: 'success' })
77
- setOpenCurrentSale(data?.registerSalesStore?.Response.success)
78
-
79
- },
80
- onError: (error) => {
81
- console.log('error', error)
78
+ const [registerSalesStore, { loading: loadingRegisterSale }] = useMutation(
79
+ CREATE_SHOPPING_CARD_TO_USER_STORE,
80
+ {
81
+ onCompleted: (data) => {
82
+ const message = `${data?.registerSalesStore?.Response?.message}`;
83
+ const error = data?.registerSalesStore?.Response.success
84
+ ? "Éxito"
85
+ : "Error";
86
+ sendNotification({ title: error, description: message });
87
+ setAlertBox({ message: message, type: "success" });
88
+ setOpenCurrentSale(data?.registerSalesStore?.Response.success);
89
+ },
90
+ onError: (error) => {
91
+ console.log("error", error);
92
+ },
82
93
  }
83
- })
94
+ );
84
95
  const [product, setProduct] = useState({
85
96
  PRODUCT: {},
86
- })
87
- const [productFoodsOne, { data: dataProduct }] = useLazyQuery(GET_ONE_PRODUCTS_FOOD)
88
- const [ExtProductFoodsOptionalAll, { data: dataOptional }] = useLazyQuery(GET_EXTRAS_PRODUCT_FOOD_OPTIONAL)
89
- const [ExtProductFoodsAll, { data: dataExtra }] = useLazyQuery(GET_ALL_EXTRA_PRODUCT)
90
-
97
+ });
98
+ const [productFoodsOne, { data: dataProduct }] = useLazyQuery(
99
+ GET_ONE_PRODUCTS_FOOD
100
+ );
101
+ const [ExtProductFoodsSubOptionalAll] = useLazyQuery(
102
+ GET_EXTRAS_PRODUCT_FOOD_OPTIONAL,
103
+ {
104
+ onError: () => {
105
+ setDataOptional([]);
106
+ },
107
+ }
108
+ );
109
+ const [ExtProductFoodsAll] = useLazyQuery(GET_ALL_EXTRA_PRODUCT, {
110
+ onError: () => {
111
+ setDataExtra([]);
112
+ },
113
+ });
91
114
  const [productsFood, { loading, fetchMore }] = useProductsFood({
92
- search: search?.length >= 4 ? search : '',
115
+ search: search?.length >= 4 ? search : "",
93
116
  gender: [],
94
117
  desc: [],
95
118
  categories: arr || [],
96
119
  toDate: valuesDates?.toDate,
97
120
  fromDate: valuesDates?.fromDate,
98
121
  max: showMore,
99
- min: 0
100
- })
122
+ min: 0,
123
+ });
101
124
  const max = productsFood?.reduce(function (a, b) {
102
- return Math.max(a, b?.ProPrice || 0)
103
- }, 0)
125
+ return Math.max(a, b?.ProPrice || 0);
126
+ }, 0);
104
127
  const initialStateSales = {
105
128
  PRODUCT: [],
106
129
  totalPrice: 0,
107
130
  sortBy: null,
108
131
  itemsInCart: 0,
109
- animateType: '',
110
- startAnimateUp: '',
132
+ animateType: "",
133
+ startAnimateUp: "",
111
134
  priceRange: max || 0,
112
135
  counter: 0,
113
136
  totalAmount: 0,
114
- payMethodPState: 0
115
- }
137
+ payMethodPState: 0,
138
+ };
116
139
  // HANDLESS
117
140
  // FILTER PRODUCT DATA_DB
118
141
  const handlePrint = ({ callback }) => {
119
142
  if (disabled) {
120
- return sendNotification({
121
- title: 'Error',
122
- description: 'Esta es la descr',
123
- backgroundColor: 'red'
124
- })
143
+ return sendNotification({
144
+ title: "Error",
145
+ description: "Esta es la descr",
146
+ backgroundColor: "red",
147
+ });
125
148
  }
126
- setPrint(!print)
127
- }
128
- const handleChangeFilter = (e) => { return setSearch(e.target.value) }
129
- const handleChange = e => { return setValues({ ...values, [e.target.name]: e.target.value }) }
130
- const onChangeInput = (e) => { return setValuesDates({ ...valuesDates, [e.target.name]: e.target.value }) }
149
+ setPrint(!print);
150
+ };
151
+ const handleChangeFilter = (e) => {
152
+ return setSearch(e.target.value);
153
+ };
154
+ const handleChange = (e) => {
155
+ return setValues({ ...values, [e.target.name]: e.target.value });
156
+ };
157
+ const onChangeInput = (e) => {
158
+ return setValuesDates({ ...valuesDates, [e.target.name]: e.target.value });
159
+ };
131
160
  const handleChangeFilterProduct = (e) => {
132
- let text = searchedInput(e.target.value)
133
- if (text === undefined || text === '') {
134
- return
161
+ let text = searchedInput(e.target.value);
162
+ if (text === undefined || text === "") {
163
+ return;
135
164
  }
136
- let filteredData = handleList(text)
137
- setFilteredList(filteredData)
138
- }
139
- const [oneProductToComment, setOneProductToComment] = useState({})
165
+ let filteredData = handleList(text);
166
+ setFilteredList(filteredData);
167
+ };
168
+ const [oneProductToComment, setOneProductToComment] = useState({});
140
169
  const handleComment = (product) => {
141
170
  if (product) {
142
- setOneProductToComment(product)
171
+ setOneProductToComment(product);
143
172
  setValues({
144
173
  ...values,
145
- comment: product?.comment || ''
146
- })
174
+ comment: product?.comment || "",
175
+ });
147
176
  }
148
- setOpenCommentModal(!openCommentModal)
149
- }
150
- const handleChangeNumber = useCallback((state, action) => {
151
- const event = action.payload
152
- const { value, index, id } = event || {}
153
- const productExist = productsFood?.find((items) => {
154
- return items.pId === id
155
- })
156
- const OneProduct = state?.PRODUCT.find((items) => {
157
- return items.pId === id
158
- })
159
- if (value <= 0) {
160
- dispatch({ type: 'REMOVE_PRODUCT_TO_CART', payload: OneProduct })
161
- }
162
- const finalQuantity = state.PRODUCT['ProQuantity'] = value || 0
163
- const ARR_PRODUCT = state?.PRODUCT?.map((items, i) => {
164
- return i === index
165
- ? {
166
- ...items,
167
- ProQuantity: (finalQuantity),
168
- ProPrice: value ? (value * productExist?.ProPrice) : productExist?.ProPrice
169
- }
170
- : items
171
- })
172
- return {
173
- ...state,
174
- PRODUCT: ARR_PRODUCT,
175
- counter: state.counter + 1
176
- }
177
- }, [productsFood])
177
+ setOpenCommentModal(!openCommentModal);
178
+ };
179
+ const handleChangeNumber = useCallback(
180
+ (state, action) => {
181
+ const event = action.payload;
182
+ const { value, index, id } = event || {};
183
+ const productExist = productsFood?.find((items) => {
184
+ return items.pId === id;
185
+ });
186
+ const OneProduct = state?.PRODUCT.find((items) => {
187
+ return items.pId === id;
188
+ });
189
+ if (value <= 0) {
190
+ dispatch({ type: "REMOVE_PRODUCT_TO_CART", payload: OneProduct });
191
+ }
192
+ const finalQuantity = (state.PRODUCT["ProQuantity"] = value || 0);
193
+ const ARR_PRODUCT = state?.PRODUCT?.map((items, i) => {
194
+ return i === index
195
+ ? {
196
+ ...items,
197
+ ProQuantity: finalQuantity,
198
+ ProPrice: value
199
+ ? value * productExist?.ProPrice
200
+ : productExist?.ProPrice,
201
+ }
202
+ : items;
203
+ });
204
+ return {
205
+ ...state,
206
+ PRODUCT: ARR_PRODUCT,
207
+ counter: state.counter + 1,
208
+ };
209
+ },
210
+ [productsFood]
211
+ );
178
212
  const PRODUCT = (state, action) => {
179
213
  const productExist = state.PRODUCT.find((items) => {
180
- return items.pId === action.id
181
- })
214
+ return items.pId === action.id;
215
+ });
182
216
  const OurProduct = productsFood.find((items) => {
183
- return items.pId === action.id
184
- })
185
- const isFree = productExist?.free
217
+ return items.pId === action.id;
218
+ });
219
+ const isFree = productExist?.free;
186
220
 
187
221
  switch (action.type) {
188
- case 'ADD_TO_CART':
189
- return addToCartFunc(state, action)
190
- case 'ADD_PRODUCT':
222
+ case "ADD_TO_CART":
223
+ return addToCartFunc(state, action);
224
+ case "ADD_PRODUCT":
191
225
  return {
192
226
  ...state,
193
227
  // eslint-disable-next-line
194
228
  PRODUCT: [...state?.PRODUCT, action?.payload],
195
- }
196
- case 'REMOVE_PRODUCT':
197
- return removeFunc(state, action)
198
- case 'REMOVE_PRODUCT_TO_CART':
229
+ };
230
+ case "REMOVE_PRODUCT":
231
+ return removeFunc(state, action);
232
+ case "REMOVE_PRODUCT_TO_CART":
199
233
  return {
200
234
  ...state,
201
235
  PRODUCT: state?.PRODUCT?.filter((t) => {
202
- return t.pId !== action?.payload.pId
236
+ return t.pId !== action?.payload.pId;
203
237
  }),
204
- counter: state.counter - action.payload.ProQuantity
205
- }
206
- case 'ON_CHANGE': {
207
- return handleChangeNumber(state, action)
238
+ counter: state.counter - action.payload.ProQuantity,
239
+ };
240
+ case "ON_CHANGE": {
241
+ return handleChangeNumber(state, action);
208
242
  }
209
- case 'REMOVE_ALL_PRODUCTS':
243
+ case "REMOVE_ALL_PRODUCTS":
244
+ setValues({});
210
245
  return {
211
246
  ...state,
212
247
  PRODUCT: [],
213
- counter: 0
214
- }
248
+ counter: 0,
249
+ };
215
250
 
216
- case 'TOGGLE_FREE_PRODUCT':
217
- return toggleFreeProducts(state, action)
218
- case 'INCREMENT':
251
+ case "TOGGLE_FREE_PRODUCT":
252
+ return toggleFreeProducts(state, action);
253
+ case "INCREMENT":
219
254
  return {
220
255
  ...state,
221
256
  counter: state.counter + 1,
222
257
  PRODUCT: state?.PRODUCT?.map((items) => {
223
258
  return items.pId === action.id
224
259
  ? {
225
- ...items,
226
- ProQuantity: items.ProQuantity + 1,
227
- ProPrice: isFree ? 0 : (productExist.ProQuantity + 1) * OurProduct?.ProPrice
228
- }
229
- : items
230
- })
231
- }
232
- case 'PUT_COMMENT': return commentProducts(state, action)
233
- case 'PRICE_RANGE':
260
+ ...items,
261
+ ProQuantity: items.ProQuantity + 1,
262
+ ProPrice: isFree
263
+ ? 0
264
+ : (productExist.ProQuantity + 1) * OurProduct?.ProPrice,
265
+ }
266
+ : items;
267
+ }),
268
+ };
269
+ case "PUT_COMMENT":
270
+ return commentProducts(state, action);
271
+ case "PUT_EXTRA_PRODUCTS_AND_OPTIONAL_PRODUCT":
272
+ return handleUpdateAllExtraAndOptional(state, action);
273
+ case "PRICE_RANGE":
234
274
  return {
235
275
  ...state,
236
- priceRange: action.payload
237
- }
238
- case 'SORT':
239
- return { ...state, sortBy: action.payload }
240
- case 'DECREMENT':
276
+ priceRange: action.payload,
277
+ };
278
+ case "SORT":
279
+ return { ...state, sortBy: action.payload };
280
+ case "DECREMENT":
241
281
  return {
242
- ...state
282
+ ...state,
243
283
  // counter: state.counter - 1,
244
284
  // PRODUCT: state?.PRODUCT?.map((items) => {
245
285
  // return items.pId === action.id ? {
@@ -248,121 +288,265 @@ export const useSales = ({
248
288
  // // ProPrice: ((productExist.ProQuantity + 1) * OurProduct?.ProPrice),
249
289
  // } : items
250
290
  // })
251
- }
252
- case 'PAYMENT_METHOD_TRANSACTION':
291
+ };
292
+ case "PAYMENT_METHOD_TRANSACTION":
253
293
  return {
254
294
  ...state,
255
- payMethodPState: 1
256
- }
257
- case 'PAYMENT_METHOD_MONEY':
295
+ payMethodPState: 1,
296
+ };
297
+ case "PAYMENT_METHOD_MONEY":
258
298
  return {
259
299
  ...state,
260
- payMethodPState: 0
261
- }
300
+ payMethodPState: 0,
301
+ };
262
302
  default:
263
- return state
303
+ return state;
264
304
  }
265
- }
266
- const [data, dispatch] = useReducer(PRODUCT, initialStateSales, initializer)
267
- const handleRemoveValue = useCallback(({name, value, pId}) => {
305
+ };
306
+ const [data, dispatch] = useReducer(PRODUCT, initialStateSales, initializer);
307
+ const handleRemoveValue = useCallback(({ name, value, pId }) => {
268
308
  setValues({
269
309
  ...values,
270
- [name]: value ?? ''
271
- })
310
+ [name]: value ?? "",
311
+ });
272
312
  return dispatch({
273
- type: 'PUT_COMMENT',
313
+ type: "PUT_COMMENT",
274
314
  payload: pId,
275
- value: ''
276
- })
277
- }, [])
315
+ value: "",
316
+ });
317
+ }, []);
278
318
  useEffect(() => {
279
- Cookies.set(keyToSaveData, JSON.stringify(data), { domain, path: '/' })
280
- }, [data, domain])
319
+ Cookies.set(keyToSaveData, JSON.stringify(data), { domain, path: "/" });
320
+ }, [data, domain]);
281
321
 
322
+ const handleAddOptional = ({ exOptional, codeCategory, index }) => {
323
+ const item = dataOptional.find((item) => item.code === codeCategory);
324
+ if (!item) return;
325
+ const idx = item.ExtProductFoodsSubOptionalAll.findIndex(
326
+ (el) => el.opSubExPid === exOptional
327
+ );
328
+ if (item && idx !== -1) {
329
+ const updatedItem = {
330
+ ...item,
331
+ ExtProductFoodsSubOptionalAll: [
332
+ ...item.ExtProductFoodsSubOptionalAll.slice(0, idx),
333
+ {
334
+ ...item.ExtProductFoodsSubOptionalAll[idx],
335
+ check: !item.ExtProductFoodsSubOptionalAll[idx].check,
336
+ },
337
+ ...item.ExtProductFoodsSubOptionalAll.slice(idx + 1),
338
+ ],
339
+ };
340
+ const newData = dataOptional.map((el) =>
341
+ el.code === codeCategory ? updatedItem : el
342
+ );
343
+ setDataOptional((prevData) => [...newData]);
344
+ }
345
+ };
346
+
347
+ function handleUpdateAllExtraAndOptional(state, action) {
348
+ return {
349
+ ...state,
350
+ PRODUCT: state?.PRODUCT?.map((items) => {
351
+ return items.pId === action.payload
352
+ ? {
353
+ ...items,
354
+ dataOptional: action.dataOptional || [],
355
+ dataExtra: action.dataExtra || [],
356
+ }
357
+ : items;
358
+ }),
359
+ };
360
+ }
361
+
362
+ /**
363
+ * Description
364
+ * @returns {any}
365
+ * */
366
+ const [sumExtraProducts, setSumExtraProducts] = useState(0);
367
+ useEffect(() => {
368
+ const arr =
369
+ dataExtra?.length > 0
370
+ ? dataExtra?.filter((p) => {
371
+ return p.quantity !== 0;
372
+ })
373
+ : [];
374
+ const val = arr.findIndex((item) => item.quantity !== 0);
375
+ if (val === -1) {
376
+ setSumExtraProducts(0);
377
+ }
378
+ function sumNewExtraPrice() {
379
+ let sum = 0;
380
+ arr.forEach((obj) => {
381
+ sum += obj.newExtraPrice ?? 0;
382
+ });
383
+ if (arr.length === 0) {
384
+ setSumExtraProducts(0);
385
+ }
386
+ setSumExtraProducts(sum);
387
+ return sum;
388
+ }
389
+ if (arr.length > 0) {
390
+ sumNewExtraPrice();
391
+ }
392
+ }, [dataExtra]);
393
+
394
+ function handleUpdateAllExtra() {
395
+ const { pId } = product?.PRODUCT || {};
396
+ const filteredDataOptional = dataOptional.map((obj) => {
397
+ const filteredSubOptions = obj.ExtProductFoodsSubOptionalAll.filter(
398
+ (subObj) => subObj.check === true
399
+ );
400
+ // Excluya todo el objeto padre si filteredSubOptions está vacío
401
+ if (filteredSubOptions.length === 0) {
402
+ return null;
403
+ }
404
+ return { ...obj, ExtProductFoodsSubOptionalAll: filteredSubOptions };
405
+ }).filter((obj) => obj !== null); // Elimine todos los objetos nulos del arreglo
406
+ const filteredDataExtra = dataExtra.filter((p) => {
407
+ return p.quantity !== 0;
408
+ });
409
+ return dispatch({
410
+ type: "PUT_EXTRA_PRODUCTS_AND_OPTIONAL_PRODUCT",
411
+ payload: pId,
412
+ dataOptional: filteredDataOptional,
413
+ dataExtra: filteredDataExtra,
414
+ });
415
+ }
416
+
417
+ function handleIncrementExtra({ Adicionales, index }) {
418
+ const { pId } = product?.PRODUCT || {};
419
+ const exPid = Adicionales.exPid || null;
420
+ if (exPid && pId) {
421
+ const newExtra = dataExtra.map((producto) => {
422
+ if (exPid === producto.exPid) {
423
+ const initialQuantity = producto?.quantity ? producto?.quantity : 0;
424
+ return {
425
+ ...producto,
426
+ quantity: initialQuantity + 1,
427
+ newExtraPrice: producto.extraPrice * (initialQuantity + 1),
428
+ };
429
+ }
430
+ return producto;
431
+ });
432
+ return setDataExtra(newExtra);
433
+ }
434
+ }
435
+ function handleDecrementExtra({ Adicionales, index }) {
436
+ const { pId } = product?.PRODUCT || {};
437
+ const exPid = Adicionales.exPid || null;
438
+
439
+ // Comprobar que el objeto Adicionales existe en dataExtra
440
+ const extraIndex = dataExtra.findIndex((extra) => extra.exPid === exPid);
441
+ if (extraIndex === -1) {
442
+ return;
443
+ }
444
+
445
+ if (pId && exPid) {
446
+ const newExtra = dataExtra.map((producto, i) => {
447
+ if (exPid === producto.exPid) {
448
+ const initialQuantity = producto?.quantity;
449
+ return {
450
+ ...producto,
451
+ quantity: initialQuantity - 1,
452
+ newExtraPrice: producto.extraPrice * (initialQuantity - 1),
453
+ };
454
+ }
455
+ return producto;
456
+ });
457
+ setDataExtra(newExtra);
458
+ }
459
+ }
282
460
 
283
461
  function addToCartFunc(state, action) {
284
462
  const productExist = state.PRODUCT.find((items) => {
285
- return items.pId === action.payload.pId
286
- })
463
+ return items.pId === action.payload.pId;
464
+ });
287
465
  const OurProduct = productsFood.find((items) => {
288
- return items.pId === action.payload.pId
289
- })
290
- const isFree = productExist?.free
466
+ return items.pId === action.payload.pId;
467
+ });
468
+ const isFree = productExist?.free;
291
469
  return {
292
470
  ...state,
293
471
  counter: state.counter + 1,
294
472
  totalAmount: state.totalAmount + action.payload.ProPrice,
295
- startAnimateUp: 'start-animate-up',
473
+ startAnimateUp: "start-animate-up",
296
474
  PRODUCT: !productExist
297
475
  ? [
298
- ...state.PRODUCT,
299
- {
300
- pId: action.payload.pId,
301
- pName: action.payload.pName,
302
- ProDescription: action.payload.ProDescription,
303
- ProImage: action.payload.ProImage,
304
- ProPrice: action.payload.ProPrice,
305
- ProQuantity: 1
306
- }
307
- ]
476
+ ...state.PRODUCT,
477
+ {
478
+ pId: action.payload.pId,
479
+ pName: action.payload.pName,
480
+ unitPrice: OurProduct?.ProPrice,
481
+ ProDescription: action.payload.ProDescription,
482
+ ProImage: action.payload.ProImage,
483
+ ProPrice: action.payload.ProPrice,
484
+ ProQuantity: 1,
485
+ },
486
+ ]
308
487
  : state.PRODUCT.map((items) => {
309
- return items.pId === action.payload.pId
310
- ? {
311
- ...items,
312
- ProPrice: isFree ? 0 : (productExist.ProQuantity + 1) * OurProduct?.ProPrice,
313
- ProQuantity: productExist.ProQuantity + 1,
314
- free: isFree ? true : false
315
- }
316
- : items
317
- })
318
- }
488
+ return items.pId === action.payload.pId
489
+ ? {
490
+ ...items,
491
+ unitPrice: OurProduct?.ProPrice,
492
+ ProPrice: isFree
493
+ ? 0
494
+ : (productExist.ProQuantity + 1) * OurProduct?.ProPrice,
495
+ ProQuantity: productExist.ProQuantity + 1,
496
+ free: isFree ? true : false,
497
+ }
498
+ : items;
499
+ }),
500
+ };
319
501
  }
320
502
  function removeFunc(state, action) {
321
503
  const productExist = state.PRODUCT.find((items) => {
322
- return items.pId === action.payload.pId
323
- })
504
+ return items.pId === action.payload.pId;
505
+ });
324
506
  const OurProduct = productsFood.find((items) => {
325
- return items.pId === action.payload.pId
326
- })
507
+ return items.pId === action.payload.pId;
508
+ });
327
509
  return {
328
510
  ...state,
329
511
  counter: state.counter - 1,
330
512
  totalAmount: state.totalAmount - action.payload.ProPrice,
331
- PRODUCT: action.payload.ProQuantity > 1
332
- ? state.PRODUCT.map((items) => {
333
- return items.pId === action.payload.pId
334
- ? {
335
- ...items,
336
- pId: action.payload.pId,
337
- ProQuantity: items.ProQuantity - 1,
338
- ProPrice: (productExist.ProPrice - OurProduct?.ProPrice)
339
- }
340
- : items
341
- })
342
- : state.PRODUCT.filter((items) => {
343
- return items.pId !== action.payload.pId
344
- })
345
- }
513
+ PRODUCT:
514
+ action.payload.ProQuantity > 1
515
+ ? state.PRODUCT.map((items) => {
516
+ return items.pId === action.payload.pId
517
+ ? {
518
+ ...items,
519
+ pId: action.payload.pId,
520
+ ProQuantity: items.ProQuantity - 1,
521
+ ProPrice: productExist.ProPrice - OurProduct?.ProPrice,
522
+ }
523
+ : items;
524
+ })
525
+ : state.PRODUCT.filter((items) => {
526
+ return items.pId !== action.payload.pId;
527
+ }),
528
+ };
346
529
  }
530
+
347
531
  // TOGGLE_FREE_PRODUCT
348
532
  function toggleFreeProducts(state, action) {
349
533
  const productExist = productsFood.find((items) => {
350
- return items.pId === action.payload.pId
351
- })
534
+ return items.pId === action.payload.pId;
535
+ });
352
536
  return {
353
537
  ...state,
354
538
  PRODUCT: state?.PRODUCT?.map((items) => {
355
539
  return items.pId === action.payload.pId
356
540
  ? {
357
- ...items,
358
- free: !items.free,
359
- ProPrice: items.ProPrice
360
- ? 0
361
- : items.ProQuantity * productExist?.ProPrice
362
- }
363
- : items
364
- })
365
- }
541
+ ...items,
542
+ free: !items.free,
543
+ ProPrice: items.ProPrice
544
+ ? 0
545
+ : items.ProQuantity * productExist?.ProPrice,
546
+ }
547
+ : items;
548
+ }),
549
+ };
366
550
  }
367
551
 
368
552
  // COMMENT_FREE_PRODUCT
@@ -372,77 +556,92 @@ export const useSales = ({
372
556
  PRODUCT: state?.PRODUCT?.map((items) => {
373
557
  return items.pId === action.payload
374
558
  ? {
375
- ...items,
376
- comment: deleteValue ? '' : values.comment,
377
- }
378
- : items
379
- })
380
- }
559
+ ...items,
560
+ comment: deleteValue ? "" : values.comment,
561
+ }
562
+ : items;
563
+ }),
564
+ };
381
565
  }
382
566
 
383
567
  const getSortedProduct = (sortData, sortBy) => {
384
- if (sortBy && sortBy === 'PRICE_HIGH_TO_LOW') {
568
+ if (sortBy && sortBy === "PRICE_HIGH_TO_LOW") {
385
569
  return (
386
- sortData ??
387
570
  sortData.sort((a, b) => {
388
- return b['ProPrice'] - a['ProPrice']
571
+ return b["ProPrice"] - a["ProPrice"];
389
572
  })
390
- )
573
+ );
391
574
  }
392
- if (sortBy && sortBy === 'PRICE_LOW_TO_HIGH') {
575
+ if (sortBy && sortBy === "PRICE_LOW_TO_HIGH") {
393
576
  return (
394
- sortData ??
395
577
  sortData.sort((a, b) => {
396
- return a['ProPrice'] - b['ProPrice']
578
+ return a["ProPrice"] - b["ProPrice"];
397
579
  })
398
- )
580
+ );
399
581
  }
400
- return sortData
401
- }
582
+ return sortData;
583
+ };
402
584
  const PriceRangeFunc = (products, price) => {
403
585
  return (
404
586
  products?.length > 0 &&
405
587
  products?.filter((items) => {
406
- return items?.ProPrice >= price
588
+ return items?.ProPrice >= price;
407
589
  })
408
- )
409
- }
590
+ );
591
+ };
410
592
 
411
- const sortedProduct = getSortedProduct(data.PRODUCT, data.sortBy)
412
- const finalFilter = PriceRangeFunc(sortedProduct, data.priceRange)
593
+ const sortedProduct = getSortedProduct(data.PRODUCT, data.sortBy);
594
+ const finalFilter = PriceRangeFunc(sortedProduct, data.priceRange);
413
595
 
414
596
  const handleList = (text) => {
415
- let inputText = text.toLowerCase()
416
- let dataList = []
597
+ let inputText = text.toLowerCase();
598
+ let dataList = [];
417
599
  dataList = finalFilter.filter((item) => {
418
- return item.pName.toLowerCase().includes(inputText)
419
- })
420
- return dataList
421
- }
600
+ return item.pName.toLowerCase().includes(inputText);
601
+ });
602
+ return dataList;
603
+ };
422
604
  const searchedInput = (words) => {
423
- setInputValue(words)
424
- let n = words.split(' ')
605
+ setInputValue(words);
606
+ let n = words.split(" ");
425
607
  if (n.length !== 0) {
426
- if (n[n.length - 1] === '') {
427
- n.pop()
608
+ if (n[n.length - 1] === "") {
609
+ n.pop();
428
610
  }
429
- return n[n.length - 1]
611
+ return n[n.length - 1];
430
612
  }
431
- return ''
432
- }
613
+ return "";
614
+ };
433
615
  const newArrayProducts =
434
- data?.PRODUCT?.length > 0 &&
616
+ data?.PRODUCT?.length > 0 ?
435
617
  data?.PRODUCT?.map((product) => {
618
+ const filteredDataExtra = product?.dataExtra?.map(({__typename, ...rest}) => rest) ?? [];
619
+ const dataOptional = product?.dataOptional?.map(({ __typename, ...product}) => {
620
+ const {ExtProductFoodsSubOptionalAll, ...rest} = product;
621
+ const adjustedSubOptionalAll = ExtProductFoodsSubOptionalAll?.map(subOption => {
622
+ const {__typename, ...subOptionRest} = subOption;
623
+ return subOptionRest;
624
+ });
625
+ return {...rest, ExtProductFoodsSubOptionalAll: adjustedSubOptionalAll};
626
+ });
436
627
  return {
437
628
  pId: product?.pId,
438
629
  id: values?.cliId,
439
- cantProducts: parseInt(product?.ProQuantity ? product?.ProQuantity : 0),
440
- comments: product?.comment ?? ''
441
- }
442
- })
630
+ cantProducts: parseInt(product?.ProQuantity ? product?.ProQuantity : 0),
631
+ comments: product?.comment ?? "",
632
+ dataOptional: dataOptional ?? [],
633
+ dataExtra: filteredDataExtra || []
634
+ };
635
+ }) : [];
443
636
  const handleSubmit = () => {
444
- const code = RandomCode(10)
445
- setCode(code)
637
+ if (!values?.cliId)
638
+ return sendNotification({
639
+ title: "Error",
640
+ description: "Elije primero un cliente",
641
+ });
642
+ setLoadingSale(true);
643
+ const code = RandomCode(10);
644
+ setCode(code);
446
645
  return registerSalesStore({
447
646
  variables: {
448
647
  input: newArrayProducts || [],
@@ -452,96 +651,178 @@ export const useSales = ({
452
651
  valueDelivery: parseInt(values.valueDelivery),
453
652
  payMethodPState: data.payMethodPState,
454
653
  pickUp: 1,
455
- totalProductsPrice: totalProductPrice || 0
654
+ totalProductsPrice: totalProductPrice || 0,
655
+ },
656
+ update: (
657
+ cache,
658
+ { data: { getAllSalesStoreStatistic, getTodaySales, getAllSalesStore } }
659
+ ) => {
660
+ updateCacheMod({
661
+ cache,
662
+ query: GET_ALL_SALES,
663
+ nameFun: "getAllSalesStore",
664
+ dataNew: getAllSalesStore,
665
+ });
666
+ updateCacheMod({
667
+ cache,
668
+ query: GET_ALL_COUNT_SALES,
669
+ nameFun: "getTodaySales",
670
+ dataNew: getTodaySales,
671
+ });
672
+ updateCacheMod({
673
+ cache,
674
+ query: GET_ALL_SALES_STATISTICS,
675
+ nameFun: "getAllSalesStoreStatistic",
676
+ dataNew: getAllSalesStoreStatistic
677
+ });
456
678
  },
457
- update: (cache, { data: {
458
- getAllSalesStoreStatistic,
459
- getTodaySales,
460
- getAllSalesStore
461
- } }) => {
462
- updateCacheMod(
463
- {
464
- cache,
465
- query: GET_ALL_SALES,
466
- nameFun: 'getAllSalesStore',
467
- dataNew: getAllSalesStore,
468
- })
469
- updateCacheMod(
470
- {
471
- cache,
472
- query: GET_ALL_COUNT_SALES,
473
- nameFun: 'getTodaySales',
474
- dataNew: getTodaySales,
475
- })
476
- return updateCacheMod(
477
- {
478
- cache,
479
- query: GET_ALL_SALES_STATISTICS,
480
- nameFun: 'getAllSalesStoreStatistic',
481
- dataNew: getAllSalesStoreStatistic,
482
- type: 2
483
- }
484
- )
485
- }
486
679
  })
487
680
  .then((responseRegisterR) => {
488
681
  if (responseRegisterR) {
489
- const { data } = responseRegisterR || {}
490
- const { registerSalesStore } = data || {}
491
- const { Response } = registerSalesStore || {}
492
- console.log(Response)
682
+ const { data } = responseRegisterR || {};
683
+ const { registerSalesStore } = data || {};
684
+ const { Response } = registerSalesStore || {};
493
685
  if (Response && Response.success === true) {
494
686
  // dispatch({ type: 'REMOVE_ALL_PRODUCTS' })
495
687
  router.push(
496
688
  {
497
689
  query: {
498
690
  ...router.query,
499
- saleId: code
500
- }
691
+ saleId: code,
692
+ },
501
693
  },
502
694
  undefined,
503
- { shallow: true }
504
- )
505
- setValues({})
695
+ { shallow: true }
696
+ );
697
+ // setValues({})
506
698
  }
507
699
  }
700
+ setLoadingSale(false);
508
701
  })
509
- }
510
- let suma = 0
511
- let total = 0
702
+ .catch(() => {
703
+ setLoadingSale(false);
704
+ setErrorSale(true);
705
+ })
706
+ .finally(() => {
707
+ setLoadingSale(false);
708
+ });
709
+ };
710
+ let suma = 0;
711
+ let total = 0;
512
712
 
513
713
  useEffect(() => {
514
714
  data.PRODUCT.forEach((a) => {
515
- const { ProPrice } = a || {}
516
- suma += ProPrice
517
- setTotalProductPrice(Math.abs(suma))
518
- })
715
+ const { ProPrice } = a || {};
716
+ suma += ProPrice;
717
+ setTotalProductPrice(Math.abs(suma));
718
+ });
519
719
  if (data.PRODUCT.length === 0) {
520
- setTotalProductPrice(0)
720
+ setTotalProductPrice(0);
521
721
  }
522
- }, [totalProductPrice, suma, total, data])
523
-
722
+ }, [totalProductPrice, suma, total, data]);
723
+ const [loadingExtraProduct, setLoadingExtraProduct] = useState(false);
524
724
 
525
- const handleProduct = (PRODUCT) => {
526
- const { pId } = PRODUCT || {}
725
+ const handleProduct = async (PRODUCT) => {
726
+ setLoadingExtraProduct(true)
727
+ const { pId } = PRODUCT || {};
527
728
  try {
729
+ const originalArray = data.PRODUCT.find((item) => {
730
+ return item.pId === pId;
731
+ });
732
+ // OPTIONAL
528
733
  productFoodsOne({ variables: { pId } })
529
- ExtProductFoodsOptionalAll({ variables: { pId } })
530
- ExtProductFoodsAll({ variables: { pId } })
734
+ const optionalAll = await ExtProductFoodsSubOptionalAll({ variables: { pId } })
735
+ const optionalFetch = optionalAll.data.ExtProductFoodsOptionalAll
736
+ setDataOptional(optionalFetch || [])
737
+ const existOptionalCookies = originalArray?.dataOptional
738
+ const filteredDataOptional = existOptionalCookies?.length ? existOptionalCookies?.map((obj) => {
739
+ const filteredSubOptions = obj.ExtProductFoodsSubOptionalAll.filter(
740
+ (subObj) => subObj.check === true
741
+ );
742
+ // Excluya todo el objeto padre si filteredSubOptions está vacío
743
+ if (filteredSubOptions.length === 0) {
744
+ return null;
745
+ }
746
+ return { ...obj, ExtProductFoodsSubOptionalAll: filteredSubOptions };
747
+ }).filter((obj) => obj !== null) : [];
748
+
749
+ // Actualizar optionalAll.data.ExtProductFoodsSubOptionalAll con los valores actualizados de originalArray2.ExtProductFoodsSubOptionalAll
750
+ if (optionalFetch && filteredDataOptional) {
751
+ const updateOption = optionalFetch.map((obj) => {
752
+ const matchingArray = filteredDataOptional.find((o) => o && o.opExPid === obj.opExPid);
753
+ if (!matchingArray) {
754
+ return obj;
755
+ }
756
+ const extProductFoodsSubOptionalAll = obj.ExtProductFoodsSubOptionalAll || [];
757
+ const updateExtProductFoodsSubOptionalAll = extProductFoodsSubOptionalAll.map((subObj) => {
758
+ const newItem = matchingArray.ExtProductFoodsSubOptionalAll.find(
759
+ (newItem) => newItem && newItem.opSubExPid === subObj.opSubExPid
760
+ );
761
+ if (newItem) {
762
+ return {
763
+ ...subObj,
764
+ check: true
765
+ };
766
+ }
767
+ return subObj;
768
+ });
769
+ return {
770
+ ...obj,
771
+ ExtProductFoodsSubOptionalAll: updateExtProductFoodsSubOptionalAll
772
+ };
773
+ }).filter(obj => obj);
774
+ if (existOptionalCookies) {
775
+ setDataOptional(updateOption || [])
776
+ } else {
777
+ setDataOptional(optionalAll.data.ExtProductFoodsOptionalAll || [])
778
+ }
779
+ }
780
+ // NO OPTIONAL
781
+ const extProduct = await ExtProductFoodsAll({ variables: { pId } });
782
+ let finalData;
783
+ if (!originalArray?.dataExtra) {
784
+ finalData = extProduct?.data?.ExtProductFoodsAll;
785
+ } else {
786
+ const filteredData = originalArray.dataExtra.filter((item) =>
787
+ extProduct?.data?.ExtProductFoodsAll.some(
788
+ (newItem) => newItem.exPid === item.exPid
789
+ )
790
+ );
791
+ finalData = originalArray?.dataExtra?.concat(
792
+ extProduct?.data?.ExtProductFoodsAll?.filter(
793
+ (item) =>
794
+ !filteredData?.some(
795
+ (filteredItem) => filteredItem.exPid === item.exPid
796
+ )
797
+ )
798
+ );
799
+ }
800
+ setDataExtra(finalData);
531
801
  setProduct(() => {
532
802
  return {
533
803
  PRODUCT,
534
- }})
804
+ };
805
+ });
806
+ setLoadingExtraProduct(false)
535
807
  } catch (error) {
536
- console.log({ message: 'Lo sentimos, ocurrió un error' })
808
+ setLoadingExtraProduct(false)
809
+ console.log({ message: error || "Lo sentimos, ocurrió un error" });
537
810
  }
538
- }
539
-
811
+ };
812
+ const handleCleanFilter = () => {
813
+ setArrayCategory([]);
814
+ setValues({});
815
+ setValuesDates({ fromDate: yearMonthDay, toDate: "" });
816
+ };
817
+ const disabledModalItems = dataOptional?.length > 0 || dataExtra?.length > 0
540
818
  return {
541
- loading,
819
+ // loading: loading || loadingSale,
820
+ loading: false,
821
+ loadingExtraProduct,
822
+ disabledModalItems: !disabledModalItems,
542
823
  loadingRegisterSale,
824
+ errorSale,
543
825
  openCurrentSale,
544
- fetchMore,
545
826
  code,
546
827
  totalProductPrice,
547
828
  saveDataState,
@@ -556,16 +837,20 @@ export const useSales = ({
556
837
  finalFilter,
557
838
  showMore,
558
839
  max,
840
+ search,
559
841
  values,
560
842
  initialStateSales,
561
843
  productsFood,
562
844
  modalItem,
845
+ sumExtraProducts,
563
846
  oneProductToComment: oneProductToComment ?? null,
564
847
  dataProduct: dataProduct?.productFoodsOne || {},
565
- dataOptional: dataOptional?.ExtProductFoodsOptionalAll || [],
566
- dataExtra: dataExtra?.ExtProductFoodsAll || [],
567
-
848
+ dataOptional: dataOptional || [],
849
+ dataExtra: dataExtra || [],
850
+ fetchMore,
851
+ handleUpdateAllExtra,
568
852
  dispatch,
853
+ setArrayCategory,
569
854
  handleComment,
570
855
  setModalItem,
571
856
  handleChangeFilter,
@@ -578,12 +863,17 @@ export const useSales = ({
578
863
  setValues,
579
864
  setShowMore,
580
865
  PriceRangeFunc,
866
+ handleCleanFilter,
581
867
  handleSubmit,
582
868
  handleChangeFilterProduct,
869
+ handleDecrementExtra,
583
870
  setTotalProductPrice,
584
871
  setInputValue,
585
872
  getSortedProduct,
873
+ handleAddOptional,
874
+ handleIncrementExtra,
875
+ setProduct,
586
876
  setPrint: handlePrint,
587
- PRODUCT
588
- }
589
- }
877
+ PRODUCT,
878
+ };
879
+ };