npm-pkg-hook 1.0.5 → 1.0.7

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