npm-pkg-hook 1.12.4 → 1.12.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.
Files changed (316) hide show
  1. package/dist/index.cjs +20089 -0
  2. package/dist/index.js +19854 -0
  3. package/dist/index.mjs +19854 -0
  4. package/package.json +28 -6
  5. package/.babelrc +0 -0
  6. package/.env +0 -5
  7. package/.eslintrc.js +0 -38
  8. package/.eslintrc.json +0 -127
  9. package/.github/pull_request_template.md +0 -18
  10. package/.github/workflows/pepeline.yaml +0 -30
  11. package/expire.json +0 -1
  12. package/jsconfig.json +0 -28
  13. package/script.txt +0 -7
  14. package/src/config/client/errors.js +0 -26
  15. package/src/config/client/index.js +0 -1
  16. package/src/config/content/en.json +0 -5
  17. package/src/config/content/es.json +0 -5
  18. package/src/config/content/index.js +0 -16
  19. package/src/cookies/index.js +0 -3
  20. package/src/hooks/addTenMinutes/index.js +0 -14
  21. package/src/hooks/calculateLogLatHaversine/index.js +0 -30
  22. package/src/hooks/completeSchedules/index.js +0 -22
  23. package/src/hooks/convertToMilitaryTime/index.js +0 -14
  24. package/src/hooks/generateStoreURL/index.js +0 -38
  25. package/src/hooks/generateTemplate/index.js +0 -62
  26. package/src/hooks/getCardType/index.js +0 -24
  27. package/src/hooks/getCategoriesWithProduct/helpers/index.js +0 -7
  28. package/src/hooks/getCategoriesWithProduct/index.js +0 -62
  29. package/src/hooks/getGlobalSession/index.js +0 -49
  30. package/src/hooks/getSession/index.js +0 -18
  31. package/src/hooks/getTodayTimestamps/index.js +0 -64
  32. package/src/hooks/getTotalHours/index.js +0 -48
  33. package/src/hooks/handleLogin/index.js +0 -10
  34. package/src/hooks/index.ts +0 -147
  35. package/src/hooks/isTokenExpired/index.js +0 -17
  36. package/src/hooks/newMessageSubscription/index.js +0 -28
  37. package/src/hooks/newStoreOrderSubscription/index.js +0 -26
  38. package/src/hooks/statusOpenStores/helpers/index.js +0 -101
  39. package/src/hooks/statusOpenStores/index.js +0 -156
  40. package/src/hooks/updateExtProductFoodsOptional/index.js +0 -40
  41. package/src/hooks/useAcumulateDate/index.js +0 -16
  42. package/src/hooks/useAllStoresPendingToRegister/index.js +0 -34
  43. package/src/hooks/useAmountInput/index.ts +0 -117
  44. package/src/hooks/useAnimationFrame/index.js +0 -45
  45. package/src/hooks/useAnimationText/index.jsx +0 -31
  46. package/src/hooks/useAsideCart/helpers/index.js +0 -22
  47. package/src/hooks/useAsideCart/index.js +0 -214
  48. package/src/hooks/useAsideCart/queries.js +0 -10
  49. package/src/hooks/useBanner/index.js +0 -19
  50. package/src/hooks/useCart/index.js +0 -2
  51. package/src/hooks/useCart/queries.js +0 -174
  52. package/src/hooks/useCart/useCart/helpers/index.js +0 -75
  53. package/src/hooks/useCart/useCart/index.js +0 -412
  54. package/src/hooks/useCart/useGetCart/index.js +0 -33
  55. package/src/hooks/useCatWithProduct/index.js +0 -48
  56. package/src/hooks/useCatWithProduct/queries.js +0 -200
  57. package/src/hooks/useCatWithProductClient/index.js +0 -56
  58. package/src/hooks/useCatWithProductClient/queries.js +0 -56
  59. package/src/hooks/useCategoriesProduct/index.js +0 -13
  60. package/src/hooks/useCategoriesProduct/queries.js +0 -16
  61. package/src/hooks/useCategoryInStore/index.js +0 -100
  62. package/src/hooks/useCategoryInStore/queries.js +0 -78
  63. package/src/hooks/useCategoryStore/index.js +0 -7
  64. package/src/hooks/useCategoryStore/queries.js +0 -16
  65. package/src/hooks/useChartData/index.js +0 -170
  66. package/src/hooks/useChartData/useChartData/index.js +0 -199
  67. package/src/hooks/useChartData/useChartDataAllOrders/index.js +0 -94
  68. package/src/hooks/useChatRoomSubscription/index.js +0 -28
  69. package/src/hooks/useCheckbox/index.js +0 -115
  70. package/src/hooks/useCities/index.js +0 -13
  71. package/src/hooks/useCities/queries.js +0 -12
  72. package/src/hooks/useClients/index.js +0 -96
  73. package/src/hooks/useClients/queries.js +0 -212
  74. package/src/hooks/useColorByLetters/helpers/alea.js +0 -54
  75. package/src/hooks/useColorByLetters/helpers/colors.js +0 -45
  76. package/src/hooks/useColorByLetters/helpers/index.js +0 -18
  77. package/src/hooks/useColorByLetters/helpers/mersenne_twister.js +0 -118
  78. package/src/hooks/useColorByLetters/index.js +0 -27
  79. package/src/hooks/useConnection/index.js +0 -24
  80. package/src/hooks/useCountries/index.js +0 -19
  81. package/src/hooks/useCountries/queries.js +0 -12
  82. package/src/hooks/useCreateDeliveryTime/index.js +0 -51
  83. package/src/hooks/useCreateOrderStatusType/index.ts +0 -132
  84. package/src/hooks/useCreateProduct/helpers/index.js +0 -23
  85. package/src/hooks/useCreateProduct/helpers/manageCacheDataCatProduct/index.js +0 -52
  86. package/src/hooks/useCreateProduct/helpers/useEditImageProduct/index.js +0 -176
  87. package/src/hooks/useCreateProduct/index.js +0 -334
  88. package/src/hooks/useCreateStorePendingToRegister/index.js +0 -13
  89. package/src/hooks/useCreateStorePendingToRegister/queries.js +0 -10
  90. package/src/hooks/useDashboardComponents/index.js +0 -50
  91. package/src/hooks/useDeleteExtraProductFoods/index.js +0 -12
  92. package/src/hooks/useDeleteSubProductOptional/index.js +0 -30
  93. package/src/hooks/useDeleteSubProductOptional/queries.js +0 -10
  94. package/src/hooks/useDeliveryTime/index.js +0 -27
  95. package/src/hooks/useDepartments/index.js +0 -13
  96. package/src/hooks/useDepartments/queries.js +0 -13
  97. package/src/hooks/useDessert/helpers/index.js +0 -51
  98. package/src/hooks/useDessert/index.js +0 -525
  99. package/src/hooks/useDessertWithPrice/helpers/index.js +0 -76
  100. package/src/hooks/useDessertWithPrice/index.js +0 -373
  101. package/src/hooks/useDessertWithPrice/queries.js +0 -18
  102. package/src/hooks/useDevWS/index.ts +0 -53
  103. package/src/hooks/useDevices/index.js +0 -2
  104. package/src/hooks/useDevices/queries.js +0 -28
  105. package/src/hooks/useDevices/useGetDevices.js +0 -28
  106. package/src/hooks/useDevices/useRegisterDevices.js +0 -75
  107. package/src/hooks/useDownloadReports/helpers/downloadFileFromResponse.ts +0 -21
  108. package/src/hooks/useDownloadReports/index.ts +0 -2
  109. package/src/hooks/useDownloadReports/useDownloadReportByDay/index.ts +0 -103
  110. package/src/hooks/useDownloadReports/useGetReportByDateRange/index.ts +0 -115
  111. package/src/hooks/useDrag/index.js +0 -63
  112. package/src/hooks/useDropzone/index.js +0 -94
  113. package/src/hooks/useDynamicAuth/index.js +0 -13
  114. package/src/hooks/useDynamicAuth/queries.js +0 -24
  115. package/src/hooks/useEditCategory/index.js +0 -41
  116. package/src/hooks/useEditOneExtProductFoodOptional/index.js +0 -28
  117. package/src/hooks/useEditOneExtProductFoodOptional/queries.js +0 -16
  118. package/src/hooks/useEditSubProductOptional/index.js +0 -11
  119. package/src/hooks/useEditSubProductOptional/queries.js +0 -10
  120. package/src/hooks/useEmployee/index.js +0 -17
  121. package/src/hooks/useEmployee/queries.js +0 -85
  122. package/src/hooks/useEmployee/useCreateEmployee.js +0 -86
  123. package/src/hooks/useEvent/index.js +0 -34
  124. package/src/hooks/useFavoriteStores/index.js +0 -29
  125. package/src/hooks/useFavoriteStores/queries.js +0 -54
  126. package/src/hooks/useFetchJson/index.js +0 -25
  127. package/src/hooks/useFetchMoreInteractions/index.jsx +0 -39
  128. package/src/hooks/useFingerprintjs/index.js +0 -172
  129. package/src/hooks/useFormTools/index.js +0 -116
  130. package/src/hooks/useFormatDate/index.js +0 -86
  131. package/src/hooks/useFormatNumberPhone/index.js +0 -23
  132. package/src/hooks/useFullScreenMode/index.js +0 -65
  133. package/src/hooks/useGenerateNumberArray/index.js +0 -17
  134. package/src/hooks/useGetAllLocationUser/index.js +0 -12
  135. package/src/hooks/useGetAllLocationUser/queries.js +0 -44
  136. package/src/hooks/useGetCookies/index.js +0 -43
  137. package/src/hooks/useGetExtProductFoodsSubOptionalAll/index.js +0 -14
  138. package/src/hooks/useGetFoodRecomended/index.js +0 -32
  139. package/src/hooks/useGetFoodRecomended/queries.js +0 -47
  140. package/src/hooks/useGetMessagesToRoom/index.js +0 -23
  141. package/src/hooks/useGetMinPrice/index.js +0 -12
  142. package/src/hooks/useGetMinPrice/queries.js +0 -7
  143. package/src/hooks/useGetOneStoreRating/index.js +0 -40
  144. package/src/hooks/useGetOneStoreRating/queries.js +0 -18
  145. package/src/hooks/useGetSalesAmountToday/index.js +0 -31
  146. package/src/hooks/useGetStoreCookie/index.js +0 -21
  147. package/src/hooks/useGoogleLogin/index.js +0 -160
  148. package/src/hooks/useGoogleLogin/loadScript.js +0 -15
  149. package/src/hooks/useGoogleLogin/removeScript.js +0 -7
  150. package/src/hooks/useHover/index.js +0 -29
  151. package/src/hooks/useImageOptimization/index.js +0 -28
  152. package/src/hooks/useImageUploaderProduct/helper/canvasUtils.ts +0 -130
  153. package/src/hooks/useImageUploaderProduct/helper/getOrientation.ts +0 -53
  154. package/src/hooks/useImageUploaderProduct/helper/index.ts +0 -5
  155. package/src/hooks/useImageUploaderProduct/index.ts +0 -292
  156. package/src/hooks/useImageWeight/index.js +0 -51
  157. package/src/hooks/useImagesStore/index.js +0 -225
  158. package/src/hooks/useImagesStore/queries.js +0 -193
  159. package/src/hooks/useImagesStore/utils/index.js +0 -4
  160. package/src/hooks/useIncomingOrders/index.js +0 -10
  161. package/src/hooks/useIncomingOrders/queries.js +0 -87
  162. package/src/hooks/useInnerHtml/index.js +0 -39
  163. package/src/hooks/useIntersection/index.js +0 -84
  164. package/src/hooks/useInventory/index.js +0 -2
  165. package/src/hooks/useInventory/queries.js +0 -58
  166. package/src/hooks/useInventory/useGetProductsInStock.js +0 -15
  167. package/src/hooks/useInventory/useUpdateManageStock.js +0 -41
  168. package/src/hooks/useKeypress/index.js +0 -28
  169. package/src/hooks/useLazyScript/index.js +0 -71
  170. package/src/hooks/useLocalBackendIp/index.js +0 -34
  171. package/src/hooks/useLocalSorage/index.js +0 -36
  172. package/src/hooks/useLocationManager/index.js +0 -63
  173. package/src/hooks/useLocationNavigate/index.js +0 -54
  174. package/src/hooks/useLoginEmployeeInStore/index.js +0 -38
  175. package/src/hooks/useLogout/helpers/BroadcastChannel.js +0 -31
  176. package/src/hooks/useLogout/helpers/apiBaseUrl.js +0 -8
  177. package/src/hooks/useLogout/helpers/fetchData.js +0 -28
  178. package/src/hooks/useLogout/helpers/getCsrfToken.js +0 -30
  179. package/src/hooks/useLogout/helpers/index.js +0 -57
  180. package/src/hooks/useLogout/helpers/logger.js +0 -70
  181. package/src/hooks/useLogout/helpers/parseUrl.js +0 -36
  182. package/src/hooks/useLogout/index.js +0 -96
  183. package/src/hooks/useManageNewOrder/helpers/index.js +0 -45
  184. package/src/hooks/useManageNewOrder/helpers/mock.js +0 -0
  185. package/src/hooks/useManageNewOrder/index.js +0 -102
  186. package/src/hooks/useManageQueryParams/index.js +0 -40
  187. package/src/hooks/useMobile/index.js +0 -65
  188. package/src/hooks/useModules/helpers/index.js +0 -1
  189. package/src/hooks/useModules/helpers/validateModules.js +0 -29
  190. package/src/hooks/useModules/index.js +0 -58
  191. package/src/hooks/useMouse/index.ts +0 -50
  192. package/src/hooks/useMutateHeight/index.js +0 -36
  193. package/src/hooks/useOrderClient/index.js +0 -5
  194. package/src/hooks/useOrderStatusTypes/index.ts +0 -2
  195. package/src/hooks/useOrderStatusTypes/useOrderStatusTypes/index.ts +0 -133
  196. package/src/hooks/useOrderStatusTypes/useUpdateOrderStatusPriorities/index.ts +0 -97
  197. package/src/hooks/useOrders/index.js +0 -3
  198. package/src/hooks/useOrders/queries.js +0 -89
  199. package/src/hooks/useOrders/useChangeOrderState/index.ts +0 -125
  200. package/src/hooks/useOrders/useOrdersFromStore/index.ts +0 -77
  201. package/src/hooks/usePWAInstall/index.js +0 -38
  202. package/src/hooks/usePortFetcher/index.ts +0 -33
  203. package/src/hooks/usePrintSaleTicket/index.ts +0 -64
  204. package/src/hooks/useProductsFood/index.js +0 -253
  205. package/src/hooks/useProductsFood/queriesStore.js +0 -964
  206. package/src/hooks/useProductsFood/useEditProduct.js +0 -48
  207. package/src/hooks/useProductsFood/usetagsProducts.js +0 -98
  208. package/src/hooks/useProviders/index.js +0 -3
  209. package/src/hooks/useProviders/queries.js +0 -31
  210. package/src/hooks/useProviders/useProvidersCreateStore/index.js +0 -12
  211. package/src/hooks/useProviders/useProvidersDataStore/index.js +0 -24
  212. package/src/hooks/useProvidersStore/index.js +0 -24
  213. package/src/hooks/useProvidersStore/queries.js +0 -31
  214. package/src/hooks/usePushNotificationOrder/index.js +0 -52
  215. package/src/hooks/usePushNotifications/helpers/index.js +0 -114
  216. package/src/hooks/usePushNotifications/index.js +0 -149
  217. package/src/hooks/useQueryLocationsMap/index.js +0 -19
  218. package/src/hooks/useQueryLocationsMap/queries.js +0 -40
  219. package/src/hooks/useRatingArrayData/index.js +0 -54
  220. package/src/hooks/useRatingArrayData/queries.js +0 -19
  221. package/src/hooks/useReactToPrint/index.js +0 -1223
  222. package/src/hooks/useRemoveExtraProductFoodsOptional/index.js +0 -23
  223. package/src/hooks/useRemoveExtraProductFoodsOptional/queries.js +0 -48
  224. package/src/hooks/useReport/index.js +0 -47
  225. package/src/hooks/useReport/queries.js +0 -123
  226. package/src/hooks/useRestaurant/helpers/index.js +0 -24
  227. package/src/hooks/useRestaurant/helpers/manageStatusOpen.js +0 -26
  228. package/src/hooks/useRestaurant/index.js +0 -69
  229. package/src/hooks/useRestaurant/queries.js +0 -81
  230. package/src/hooks/useRoads/index.js +0 -19
  231. package/src/hooks/useRoads/queries.js +0 -13
  232. package/src/hooks/useRoles/index.js +0 -4
  233. package/src/hooks/useRoles/queries.js +0 -70
  234. package/src/hooks/useRoles/useCreateRole.js +0 -37
  235. package/src/hooks/useRoles/useGetRoles.js +0 -36
  236. package/src/hooks/useRoles/useRemoveRoles.js +0 -40
  237. package/src/hooks/useRoles/useUpdateRolesPriority.js +0 -44
  238. package/src/hooks/useSales/helpers/index.js +0 -55
  239. package/src/hooks/useSales/index.js +0 -1381
  240. package/src/hooks/useSales/queries.js +0 -424
  241. package/src/hooks/useSales/useGetAllSales/index.js +0 -25
  242. package/src/hooks/useSales/useGetSale.js +0 -13
  243. package/src/hooks/useSales/useTotalSales.js +0 -23
  244. package/src/hooks/useSaveAvailableProduct/helpers/index.js +0 -38
  245. package/src/hooks/useSaveAvailableProduct/index.js +0 -31
  246. package/src/hooks/useSaveAvailableProduct/queries.js +0 -10
  247. package/src/hooks/useSaveLocation/index.js +0 -16
  248. package/src/hooks/useSaveLocation/queries.js +0 -19
  249. package/src/hooks/useSchedule/index.js +0 -78
  250. package/src/hooks/useSchedule/index.jsx +0 -22
  251. package/src/hooks/useSchedule/queries.js +0 -43
  252. package/src/hooks/useScheduleData/index.js +0 -123
  253. package/src/hooks/useScroll/index.js +0 -56
  254. package/src/hooks/useScrollRotate/index.js +0 -16
  255. package/src/hooks/useSetImageProducts/index.js +0 -57
  256. package/src/hooks/useSetImageProducts/queries.js +0 -18
  257. package/src/hooks/useSetSession/index.js +0 -44
  258. package/src/hooks/useSetState/index.js +0 -24
  259. package/src/hooks/useSetupSchedule/helpers/index.js +0 -85
  260. package/src/hooks/useSetupSchedule/index.js +0 -272
  261. package/src/hooks/useStatusOpenStore/helpers/index.js +0 -101
  262. package/src/hooks/useStatusOpenStore/index.js +0 -179
  263. package/src/hooks/useStatusOrdersClient/helpers/index.js +0 -14
  264. package/src/hooks/useStatusOrdersClient/index.js +0 -17
  265. package/src/hooks/useStatusOrdersClient/queries.js +0 -80
  266. package/src/hooks/useStockMovements/helpers/index.js +0 -16
  267. package/src/hooks/useStockMovements/index.js +0 -38
  268. package/src/hooks/useStore/index.js +0 -80
  269. package/src/hooks/useStore/queries.js +0 -163
  270. package/src/hooks/useStoreCalendar/index.js +0 -5
  271. package/src/hooks/useStoreContacts/index.js +0 -47
  272. package/src/hooks/useStoreContacts/queries.js +0 -48
  273. package/src/hooks/useStoreTable/index.js +0 -2
  274. package/src/hooks/useStoreTable/queries.js +0 -47
  275. package/src/hooks/useStoreTable/useStoreTableCreate.js +0 -76
  276. package/src/hooks/useStoreTable/useStoreTables.js +0 -14
  277. package/src/hooks/useSubscriptionValidation/index.js +0 -41
  278. package/src/hooks/useTagProducts/index.ts +0 -3
  279. package/src/hooks/useTagProducts/useDeleteOneTag.ts +0 -106
  280. package/src/hooks/useTagProducts/useGetAllTags.ts +0 -68
  281. package/src/hooks/useTagProducts/useRegisterMultipleTags.ts +0 -156
  282. package/src/hooks/useTimeAgo/useTimeAgo.js +0 -39
  283. package/src/hooks/useTokenCards/index.js +0 -41
  284. package/src/hooks/useTopProductsMovements/index.js +0 -27
  285. package/src/hooks/useTotalAllSales/index.js +0 -25
  286. package/src/hooks/useTotalProductsInStock/index.js +0 -23
  287. package/src/hooks/useTotalProductsSold/index.js +0 -23
  288. package/src/hooks/useTotalProductsSolded/index.js +0 -20
  289. package/src/hooks/useUpdateCart/index.js +0 -130
  290. package/src/hooks/useUpdateCartCookie/index.js +0 -43
  291. package/src/hooks/useUpdateDashboardComponent/index.ts +0 -91
  292. package/src/hooks/useUpdateExistingOrders/index.js +0 -85
  293. package/src/hooks/useUpdateExtProductFoodsSubOptional/index.js +0 -60
  294. package/src/hooks/useUpdateModuleOrder/index.js +0 -37
  295. package/src/hooks/useUpdateMultipleExtProduct/index.js +0 -33
  296. package/src/hooks/useUpdateMultipleExtProduct/queries.js +0 -33
  297. package/src/hooks/useUpdateMultipleProducts/index.js +0 -80
  298. package/src/hooks/useUpdateMultipleProducts/queries.js +0 -51
  299. package/src/hooks/useUploadProducts/helpers/index.js +0 -1
  300. package/src/hooks/useUploadProducts/helpers/parseNumber.js +0 -37
  301. package/src/hooks/useUploadProducts/helpers/validateProductDataExcel.js +0 -73
  302. package/src/hooks/useUploadProducts/index.js +0 -422
  303. package/src/hooks/useUpsertGoal/index.js +0 -68
  304. package/src/hooks/useUser/index.js +0 -23
  305. package/src/hooks/useUser/queries.js +0 -131
  306. package/src/hooks/useWeeklyStockMovement/helpers/index.js +0 -32
  307. package/src/hooks/useWeeklyStockMovement/index.js +0 -51
  308. package/src/hooks/useWindowSize/index.js +0 -38
  309. package/src/index.jsx +0 -9
  310. package/src/mock/dessert/index.js +0 -16
  311. package/src/mock/index.js +0 -1
  312. package/src/security/index.js +0 -1
  313. package/src/services/index.js +0 -0
  314. package/src/utils/UtilDateRange.js +0 -31
  315. package/src/utils/index.js +0 -306
  316. package/tsconfig.json +0 -5
@@ -1,1381 +0,0 @@
1
- import {
2
- useApolloClient,
3
- useLazyQuery,
4
- useMutation
5
- } from '@apollo/client'
6
- import {
7
- useCallback,
8
- useEffect,
9
- useReducer,
10
- useMemo,
11
- useState
12
- } from 'react'
13
- import { Cookies } from '../../cookies'
14
- import { RandomCode, getCurrentDomain } from '../../utils'
15
- import { useFormatDate } from '../useFormatDate'
16
- import { useProductsFood } from '../useProductsFood'
17
- import {
18
- GET_ALL_EXTRA_PRODUCT,
19
- GET_EXTRAS_PRODUCT_FOOD_OPTIONAL,
20
- GET_ONE_PRODUCTS_FOOD
21
- } from '../useProductsFood/queriesStore'
22
- import { useStore } from '../useStore'
23
- import {
24
- CREATE_SHOPPING_CARD_TO_USER_STORE,
25
- GET_ALL_COUNT_SALES
26
- } from './queries'
27
- import { updateExistingOrders } from '../useUpdateExistingOrders'
28
- import { useGetSale } from './useGetSale'
29
- import { useCatWithProduct } from './../useCatWithProduct/index'
30
- import { useLogout } from '../useLogout'
31
- import { filterProductsByCarProId, removeFunc } from './helpers'
32
- export * from './useGetAllSales'
33
-
34
- export { GET_ALL_COUNT_SALES } from './queries'
35
-
36
- export const initialState = {
37
- PRODUCT: [],
38
- totalPrice: 0,
39
- sortBy: null,
40
- itemsInCart: 0,
41
- animateType: '',
42
- startAnimateUp: '',
43
- priceRange: 0,
44
- counter: 0,
45
- totalAmount: 0,
46
- payMethodPState: 0
47
- }
48
-
49
- export const initializer = (initialValue = initialState) => {
50
- return (
51
- JSON.parse(
52
- // @ts-ignore
53
- Cookies.get(process.env.LOCAL_SALES_STORE) || JSON.stringify(initialState)
54
- ) || initialValue
55
- )
56
- }
57
-
58
- export const useSales = ({
59
- disabled = false,
60
- router,
61
- sendNotification = (args) => { return args },
62
- setAlertBox = (args) => { return args }
63
- }) => {
64
- const domain = getCurrentDomain()
65
- const [loadingSale, setLoadingSale] = useState(false)
66
- const [errorSale, setErrorSale] = useState(false)
67
- const [onClickLogout] = useLogout({})
68
-
69
- const [modalItem, setModalItem] = useState(false)
70
- const [openCommentModal, setOpenCommentModal] = useState(false)
71
- const keyToSaveData = process.env.LOCAL_SALES_STORE
72
- // @ts-ignore
73
- const saveDataState = JSON.parse(Cookies.get(keyToSaveData) || '[]')
74
- const [search, setSearch] = useState('')
75
- const [datCat] = useCatWithProduct({})
76
- const [categories, setCategories] = useState([])
77
- const [currentPage, setCurrentPage] = useState(1)
78
- useEffect(() => {
79
- setCategories(datCat)
80
- }, [datCat])
81
- const [totalProductPrice, setTotalProductPrice] = useState(0)
82
- const [showMore, setShowMore] = useState(100)
83
- const [inputValue, setInputValue] = useState('')
84
- // eslint-disable-next-line no-unused-vars
85
- const [_, setFilteredList] = useState([])
86
- const [delivery, setDelivery] = useState(false)
87
- const [print, setPrint] = useState(false)
88
- const [errors, setErrors] = useState({})
89
- const [values, setValues] = useState({
90
- comment: '',
91
- change: '',
92
- cliId: '',
93
- valueDelivery: ''
94
- })
95
- const [dataStore] = useStore()
96
- const { createdAt } = dataStore || {}
97
- const [code, setCode] = useState(null)
98
- const [openCurrentSale, setOpenCurrentSale] = useState(null)
99
- const [oneProductToComment, setOneProductToComment] = useState({})
100
- const [sumExtraProducts, setSumExtraProducts] = useState(0)
101
- const { yearMonthDay } = useFormatDate({ date: createdAt })
102
- const [valuesDates, setValuesDates] = useState(() => {
103
- return { fromDate: yearMonthDay, toDate: '' }
104
- })
105
- const [product, setProduct] = useState({
106
- PRODUCT: {}
107
- })
108
- const [loadingExtraProduct, setLoadingExtraProduct] = useState(false)
109
- const [dataOptional, setDataOptional] = useState([])
110
- const [dataExtra, setDataExtra] = useState([])
111
- const [registerSalesStore, { loading: loadingRegisterSale }] = useMutation(
112
- CREATE_SHOPPING_CARD_TO_USER_STORE,
113
- {
114
- onCompleted: (data) => {
115
- const message = `${data?.registerSalesStore?.message}`
116
- const error = data?.registerSalesStore?.success
117
- ? 'Éxito'
118
- : 'Error'
119
- sendNotification({
120
- backgroundColor: error ? 'success' : 'error',
121
- title: error,
122
- description: message
123
- })
124
- setAlertBox({ message, type: 'success' })
125
- if (message === 'Token expired') {
126
- // @ts-ignore
127
- onClickLogout()
128
- }
129
- setOpenCurrentSale(data?.registerSalesStore.success)
130
- },
131
- onError: (error) => {
132
- sendNotification({
133
- backgroundColor: 'error',
134
- title: error ?? 'Lo sentimos',
135
- description: 'ha ocurrido un error'
136
- })
137
- }
138
- }
139
- )
140
-
141
- const [productFoodsOne, { data: dataProduct }] = useLazyQuery(GET_ONE_PRODUCTS_FOOD)
142
-
143
- const [ExtProductFoodsSubOptionalAll, { loading: loadingExtProductFoodsSubOptionalAll }] = useLazyQuery(
144
- GET_EXTRAS_PRODUCT_FOOD_OPTIONAL,
145
- {
146
- onError: () => {
147
- setDataOptional([])
148
- }
149
- }
150
- )
151
- const [ExtProductFoodsAll] = useLazyQuery(GET_ALL_EXTRA_PRODUCT, {
152
- onError: () => {
153
- setDataExtra([])
154
- }
155
- })
156
-
157
- const [productsFood, {
158
- loading,
159
- fetchMore,
160
- pagination,
161
- refetch
162
- }] = useProductsFood({
163
- // @ts-ignore
164
- search: search?.length >= 4 ? search : '',
165
- gender: [],
166
- desc: [],
167
- categories: [],
168
- toDate: valuesDates?.toDate,
169
- fromDate: valuesDates?.fromDate,
170
- max: showMore,
171
- min: 0,
172
- isShopppingCard: true,
173
- dataSale: (Array.isArray(saveDataState?.PRODUCT) && saveDataState?.PRODUCT) ?? [],
174
- callback: () => { return null }
175
- })
176
-
177
- const handlePageChange = (pageNumber) => {
178
- setCurrentPage(pageNumber)
179
- refetch({ page: pageNumber })
180
- }
181
-
182
- const handleChangeCheck = (caId) => {
183
- // @ts-ignore
184
- setCategories((prev) => {
185
- return prev.map((item) => {
186
- // @ts-ignore
187
- return item.carProId === caId
188
- // @ts-ignore
189
- ? { ...item, checked: !item?.checked }
190
- : item
191
- })
192
- })
193
- }
194
- const max = productsFood?.reduce(function (a, b) {
195
- return Math.max(a, b?.ProPrice || 0)
196
- }, 0)
197
- const initialStateSales = {
198
- PRODUCT: [],
199
- totalPrice: 0,
200
- sortBy: null,
201
- itemsInCart: 0,
202
- animateType: '',
203
- startAnimateUp: '',
204
- priceRange: max || 0,
205
- counter: 0,
206
- totalAmount: 0,
207
- payMethodPState: 0
208
- }
209
- // HANDLESS
210
- // FILTER PRODUCT DATA_DB
211
- // @ts-ignore
212
- const handlePrint = () => {
213
- if (disabled) {
214
- return sendNotification({
215
- title: 'Error',
216
- description: 'Esta es la descripción',
217
- backgroundColor: 'error'
218
- })
219
- }
220
- setPrint(!print)
221
- }
222
- const handleChangeFilter = (e) => {
223
- return setSearch(e.target.value)
224
- }
225
- const handleChange = (e, error) => {
226
- const { name, value } = e.target
227
- setErrors({ ...errors, [e.target.name]: error })
228
- setValues((prevValues) => ({
229
- ...prevValues,
230
- [name]: value
231
- }))
232
- }
233
- const onChangeInput = (e) => {
234
- return setValuesDates({ ...valuesDates, [e.target.name]: e.target.value })
235
- }
236
- const handleToggleEditingStatus = (state, action) => {
237
- const { PRODUCT } = state ?? {
238
- PRODUCT: []
239
- }
240
- return {
241
- ...state,
242
- PRODUCT: PRODUCT.map((item) => {
243
- if (item.pId === action.payload.pId) {
244
- return {
245
- ...item,
246
- editing: !item.editing,
247
- oldQuantity: item.ProQuantity
248
- }
249
- }
250
- return item
251
- })
252
- }
253
- }
254
-
255
- const handleChangeFilterProduct = (e) => {
256
- const text = searchedInput(e.target.value)
257
- if (text === undefined || text === '') {
258
- return
259
- }
260
- const filteredData = handleList(text)
261
- setFilteredList(filteredData)
262
- }
263
- const handleComment = (product) => {
264
- if (product) {
265
- setOneProductToComment(product)
266
- setValues({
267
- ...values,
268
- comment: product?.comment ?? ''
269
- })
270
- }
271
- setOpenCommentModal(!openCommentModal)
272
- }
273
- const handleSuccessUpdateQuantity = (state, payload) => {
274
- const { pId } = payload.payload || {
275
- pId: null
276
- }
277
- return {
278
- ...state,
279
- PRODUCT: state?.PRODUCT?.map((items) => {
280
- return items.pId === pId
281
- ? {
282
- ...items,
283
- editing: false,
284
- oldQuantity: items.ProQuantity
285
- }
286
- : items
287
- })
288
- }
289
- }
290
-
291
- /**
292
- * Cancels the update of a product's quantity, resetting it to the previous value.
293
- * @param {Object} state - The current state.
294
- * @param {Object} payload - The payload containing the product ID.
295
- * @returns {Object} - The new state with the updated product quantity and editing status.
296
- */
297
- const handleCancelUpdateQuantity = (state, payload) => {
298
- // Validación de `state`
299
- if (!state || typeof state !== 'object') {
300
- sendNotification({
301
- title: 'Error',
302
- backgroundColor: 'error',
303
- description: 'Ha ocurrido un error al actualizar la cantidad del producto.'
304
- })
305
- return state // Retorna el estado sin cambios si es inválido.
306
- }
307
-
308
- // Validación de `PRODUCT`
309
- if (!Array.isArray(state.PRODUCT)) {
310
- sendNotification({
311
- title: 'Error',
312
- backgroundColor: 'error',
313
- description: 'Ha ocurrido un error al actualizar la cantidad del producto.'
314
- })
315
- return state // Retorna el estado sin cambios si `PRODUCT` no es un array.
316
- }
317
-
318
- // Validación de `payload`
319
- const { pId } = payload.payload || {}
320
- if (!pId) {
321
- sendNotification({
322
- title: 'Error',
323
- backgroundColor: 'error',
324
- description: 'Ha ocurrido un error al actualizar la cantidad del producto.'
325
- })
326
- return state // Retorna el estado sin cambios si falta `pId`.
327
- }
328
-
329
- return {
330
- ...state,
331
- PRODUCT: state.PRODUCT.map((item) => {
332
- // Validación de propiedades en cada item
333
- if (item.pId === pId) {
334
- if (typeof item.oldQuantity !== 'number' || typeof item.unitPrice !== 'number') {
335
- sendNotification({
336
- title: 'Error',
337
- backgroundColor: 'error',
338
- description: 'Ha ocurrido un error al actualizar la cantidad del producto.'
339
- })
340
- return item // Retorna el item sin cambios si las propiedades son inválidas.
341
- }
342
-
343
- return {
344
- ...item,
345
- editing: false,
346
- ProQuantity: item.oldQuantity,
347
- ProPrice: item.oldQuantity * item.unitPrice
348
- }
349
- }
350
-
351
- return item
352
- })
353
- }
354
- }
355
-
356
- const handleChangeNumber = useCallback(
357
- (state, action) => {
358
- const event = action.payload
359
- const { value, index, id } = event || {}
360
-
361
- const productExist = productsFood?.find((items) => items.pId === id)
362
- const OneProduct = state?.PRODUCT.find((items) => items.pId === id)
363
-
364
- if (!productExist) return state // Validar si el producto existe
365
-
366
- // Validar si el stock es 0
367
- if (productExist.stock === 0) {
368
- sendNotification({
369
- title: 'Sin stock',
370
- backgroundColor: 'warning',
371
- description: `El producto ${OneProduct?.pName} está agotado y no puede ser modificado.`
372
- })
373
- return state
374
- }
375
-
376
- // Si el valor ingresado es menor o igual a 0, eliminar el producto del carrito
377
- if (value <= 0) {
378
- dispatch({ type: 'REMOVE_PRODUCT_TO_CART', payload: OneProduct })
379
- return state
380
- }
381
-
382
- // Validar si se intenta superar el stock disponible
383
- const finalQuantity = Math.min(value, productExist.stock)
384
- if ((value > productExist.stock) && productExist.manageStock) {
385
- sendNotification({
386
- title: 'Stock insuficiente',
387
- backgroundColor: 'warning',
388
- description: `No puedes agregar más unidades de ${OneProduct?.pName}, stock disponible: ${productExist.stock}`
389
- })
390
- }
391
-
392
- const ARR_PRODUCT = state?.PRODUCT?.map((items, i) =>
393
- i === index
394
- ? {
395
- ...items,
396
- ProQuantity: finalQuantity,
397
- ProPrice: finalQuantity * productExist?.ProPrice
398
- }
399
- : items
400
- )
401
-
402
- return {
403
- ...state,
404
- PRODUCT: ARR_PRODUCT,
405
- counter: state.counter + 1
406
- }
407
- },
408
- [productsFood]
409
- )
410
-
411
- const paymentMethod = (state, action) => {
412
- return {
413
- ...state,
414
- payMethodPState: action.payload
415
- }
416
- }
417
- const PRODUCT = (state, action) => {
418
- switch (action.type) {
419
- case 'ADD_TO_CART':
420
- return addToCartFunc(state, action) // https://www.npmjs.com/package/@sourcetoad/vision-camera-plugin-barcode-scanner
421
- case 'ADD_PRODUCT':
422
- return {
423
- ...state,
424
- // eslint-disable-next-line
425
- PRODUCT: [...state?.PRODUCT, action?.payload],
426
- }
427
- case 'REMOVE_PRODUCT':
428
- return removeFunc(state, action, productsFood)
429
- case 'REMOVE_PRODUCT_TO_CART':
430
- return {
431
- ...state,
432
- PRODUCT: state?.PRODUCT?.filter((t) => {
433
- return t.pId !== action?.payload.pId
434
- }),
435
- counter: state.counter - action.payload.ProQuantity
436
- }
437
- case 'ON_CHANGE': {
438
- return handleChangeNumber(state, action)
439
- }
440
- case 'UPDATE_SUCCESS_QUANTITY_EDITING_PRODUCT': {
441
- return handleSuccessUpdateQuantity(state, action)
442
- }
443
- case 'CANCEL_UPDATE_QUANTITY_EDITING_PRODUCT': {
444
- return handleCancelUpdateQuantity(state, action)
445
- }
446
- case 'REMOVE_ALL_PRODUCTS':
447
- // @ts-ignore
448
- setValues({
449
- ...values,
450
- comment: '',
451
- change: '',
452
- valueDelivery: ''
453
- })
454
- return {
455
- ...state,
456
- PRODUCT: [],
457
- sortBy: null,
458
- counter: 0
459
- }
460
-
461
- case 'TOGGLE_FREE_PRODUCT':
462
- return toggleFreeProducts(state, action)
463
- case 'TOGGLE_EDITING_PRODUCT': {
464
- return handleToggleEditingStatus(state, action)
465
- }
466
- case 'INCREMENT': {
467
- return {
468
- ...state,
469
- counter: state.counter + 1,
470
- PRODUCT: state?.PRODUCT?.map((items) => {
471
- if (items.pId === action.id) {
472
- const OurProduct = productsFood?.find((item) => item.pId === action.id)
473
- const isFree = items.free
474
- const newQuantity = items.ProQuantity + 1
475
- // Validar si el stock es 0
476
- if (OurProduct?.stock === 0) {
477
- sendNotification({
478
- title: 'Sin stock',
479
- backgroundColor: 'warning',
480
- description: `El producto ${items.pName} está agotado y no puede ser añadido al carrito.`
481
- })
482
- return items // Retornar sin modificar
483
- }
484
-
485
- // Validar si se supera el stock
486
- console.log(OurProduct)
487
- if (newQuantity >= OurProduct?.stock && OurProduct?.manageStock) {
488
- sendNotification({
489
- title: 'Stock insuficiente',
490
- backgroundColor: 'warning',
491
- description: `No puedes agregar más unidades de ${items.pName}, stock disponible: ${OurProduct?.stock}`
492
- })
493
- return items // Retornar el producto sin modificar
494
- }
495
- return {
496
- ...items,
497
- ProQuantity: newQuantity,
498
- ProPrice: isFree ? 0 : newQuantity * OurProduct?.ProPrice
499
- }
500
- }
501
- return items
502
- })
503
- }
504
- }
505
-
506
- case 'PUT_COMMENT':
507
- return commentProducts(state, action)
508
- case 'PUT_EXTRA_PRODUCTS_AND_OPTIONAL_PRODUCT':
509
- return handleUpdateAllExtraAndOptional(state, action)
510
- case 'PRICE_RANGE':
511
- return {
512
- ...state,
513
- priceRange: action.payload
514
- }
515
- case 'SORT':
516
- return { ...state, sortBy: action.payload }
517
- case 'DECREMENT':
518
- return {
519
- ...state
520
- }
521
- case 'PAYMENT_METHOD': return paymentMethod(state, action)
522
-
523
- default:
524
- return state
525
- }
526
- }
527
- const [data, dispatch] = useReducer(PRODUCT, initialStateSales, initializer)
528
-
529
- const handleRemoveValue = useCallback(({ name, value, pId }) => {
530
- setValues({
531
- ...values,
532
- [name]: value ?? ''
533
- })
534
- sendNotification({
535
- backgroundColor: 'sucess',
536
- title: 'Comentario eliminado',
537
- description: 'Has eliminado el comentario!'
538
- })
539
- // @ts-ignore
540
- return dispatch({
541
- type: 'PUT_COMMENT',
542
- payload: pId,
543
- value: ''
544
- })
545
- }, [])
546
- useEffect(() => {
547
- // @ts-ignore
548
- Cookies.set(keyToSaveData, JSON.stringify(data), { domain, path: '/' })
549
- }, [data, domain])
550
-
551
- const handleAddOptional = ({ exOptional = null, codeCategory = null }) => {
552
- if (!exOptional || !codeCategory) return
553
- // @ts-ignore
554
- const item = dataOptional.find((item) => item.code === codeCategory)
555
- if (!item) return
556
- // @ts-ignore
557
- const idx = item.ExtProductFoodsSubOptionalAll.findIndex(
558
- (el) => el.opSubExPid === exOptional
559
- )
560
- if (item && idx !== -1) {
561
- const updatedItem = {
562
- // @ts-ignore
563
- ...item,
564
- ExtProductFoodsSubOptionalAll: [
565
- // @ts-ignore
566
- ...item.ExtProductFoodsSubOptionalAll.slice(0, idx),
567
- {
568
- // @ts-ignore
569
- ...item.ExtProductFoodsSubOptionalAll[idx],
570
- // @ts-ignore
571
- check: !item.ExtProductFoodsSubOptionalAll[idx].check
572
- },
573
- // @ts-ignore
574
- ...item.ExtProductFoodsSubOptionalAll.slice(idx + 1)
575
- ]
576
- }
577
- const newData = dataOptional.map((el) =>
578
- // @ts-ignore
579
- el.code === codeCategory ? updatedItem : el
580
- )
581
- // @ts-ignore
582
- setDataOptional(() => [...newData])
583
- }
584
- }
585
-
586
- function handleUpdateAllExtraAndOptional (state, action) {
587
- return {
588
- ...state,
589
- PRODUCT: state?.PRODUCT?.map((items) => {
590
- return items.pId === action.payload
591
- ? {
592
- ...items,
593
- dataOptional: action.dataOptional || [],
594
- dataExtra: action.dataExtra || []
595
- }
596
- : items
597
- })
598
- }
599
- }
600
-
601
- /**
602
- * Description
603
- * @returns {any}
604
- * */
605
- useEffect(() => {
606
- const arr =
607
- dataExtra?.length > 0
608
- ? dataExtra?.filter((p) => {
609
- // @ts-ignore
610
- return p.quantity !== 0
611
- })
612
- : []
613
- const val = arr.findIndex((item) => item.quantity !== 0)
614
- if (val === -1) {
615
- setSumExtraProducts(0)
616
- }
617
- function sumNewExtraPrice () {
618
- let sum = 0
619
- arr.forEach((obj) => {
620
- sum += obj.newExtraPrice ?? 0
621
- })
622
- if (arr.length === 0) {
623
- setSumExtraProducts(0)
624
- }
625
- setSumExtraProducts(sum)
626
- return sum
627
- }
628
- if (arr.length > 0) {
629
- sumNewExtraPrice()
630
- }
631
- }, [dataExtra])
632
-
633
- function handleUpdateAllExtra () {
634
- try {
635
- if (!product?.PRODUCT?.pId) {
636
- return sendNotification({
637
- title: 'Error',
638
- backgroundColor: 'error',
639
- description: 'Ha ocurrido un error'
640
- })
641
- }
642
- const filteredDataOptional = dataOptional
643
- .map((obj) => {
644
- // @ts-ignore
645
- const filteredSubOptions = obj?.ExtProductFoodsSubOptionalAll?.filter(
646
- (subObj) => subObj?.check === true
647
- )
648
- // Excluya todo el objeto padre si filteredSubOptions está vacío
649
- if (filteredSubOptions?.length === 0) {
650
- return null
651
- }
652
- // @ts-ignore
653
- return { ...obj, ExtProductFoodsSubOptionalAll: filteredSubOptions }
654
- })
655
- .filter((obj) => obj !== null) // Elimine todos los objetos nulos del arreglo
656
- // @ts-ignore
657
- const filteredDataExtra = dataExtra?.filter((p) => p?.quantity !== undefined && p?.quantity !== 0)
658
- if (product?.PRODUCT?.pId) {
659
- // @ts-ignore
660
- dispatch({
661
- type: 'PUT_EXTRA_PRODUCTS_AND_OPTIONAL_PRODUCT',
662
- payload: product.PRODUCT.pId,
663
- dataOptional: filteredDataOptional,
664
- dataExtra: filteredDataExtra
665
- })
666
- const updatesOccurred = (
667
- (dataExtra && dataExtra.length > 0)
668
- )
669
- if (updatesOccurred) {
670
- return sendNotification({
671
- title: 'Success',
672
- backgroundColor: 'success',
673
- description: 'Items subidos al producto'
674
- })
675
- }
676
- }
677
- } catch (_error) {
678
- return sendNotification({
679
- title: 'Error',
680
- backgroundColor: 'error',
681
- description: 'No se puedo actualizar el producto'
682
- })
683
- }
684
- }
685
-
686
- // @ts-ignore
687
- function handleIncrementExtra ({ Adicionales, index }) {
688
- const { pId } = product?.PRODUCT || {}
689
- const exPid = Adicionales?.exPid || null
690
-
691
- if (exPid && pId) {
692
- const newExtra = dataExtra.map((producto) => {
693
- // @ts-ignore
694
- if (exPid === producto.exPid) {
695
- // @ts-ignore
696
- const initialQuantity = producto?.quantity ? producto?.quantity : 0
697
- const newQuantity = initialQuantity + 1
698
- // @ts-ignore
699
- const newExtraPrice = producto.extraPrice * newQuantity
700
-
701
- return {
702
- // @ts-ignore
703
- ...producto,
704
- quantity: newQuantity,
705
- newExtraPrice
706
- }
707
- }
708
- return producto
709
- })
710
-
711
- // @ts-ignore
712
- setDataExtra(newExtra)
713
- }
714
- }
715
-
716
- // @ts-ignore
717
- function handleDecrementExtra ({ Adicionales, index }) {
718
- const { pId } = product?.PRODUCT || {}
719
- const exPid = Adicionales?.exPid || null
720
-
721
- // Comprobar que el objeto Adicionales existe en dataExtra
722
- // @ts-ignore
723
- const extraIndex = dataExtra.findIndex((extra) => extra.exPid === exPid)
724
- if (extraIndex === -1) {
725
- return
726
- }
727
-
728
- if (pId && exPid && extraIndex !== -1) {
729
- // @ts-ignore
730
- const newExtra = dataExtra.map((producto, i) => {
731
- // @ts-ignore
732
- if (exPid === producto.exPid) {
733
- // Desestructura la cantidad y el precio extra del producto o establece valores predeterminados
734
- const { quantity = 0, extraPrice = 0 } = producto
735
-
736
- // Calcula la nueva cantidad, evitando que sea negativa
737
- const newQuantity = Math.max(quantity - 1, 0)
738
-
739
- // Calcula el nuevo precio extra
740
- const newExtraPrice = newQuantity === 0 ? extraPrice : extraPrice * newQuantity
741
-
742
- return {
743
- // @ts-ignore
744
- ...producto,
745
- quantity: newQuantity,
746
- newExtraPrice
747
- }
748
- }
749
- return producto
750
- })
751
-
752
- // Actualiza el estado de dataExtra con el nuevo array
753
- // @ts-ignore
754
- setDataExtra(newExtra)
755
- }
756
- }
757
-
758
- function isStockInsufficient (currentQuantity, stock) {
759
- return currentQuantity >= stock
760
- }
761
-
762
- function sendAlertStock (stock) {
763
- return sendNotification({
764
- title: 'Stock insuficiente',
765
- backgroundColor: 'warning',
766
- description: `Solo hay ${stock} unidades disponibles en el inventario`
767
- })
768
- }
769
-
770
- function addToCartFunc (state, action) {
771
- const {
772
- pId,
773
- pName,
774
- getOneTags,
775
- stock,
776
- ProDescription,
777
- ProImage,
778
- ProPrice
779
- } = action.payload ?? {}
780
- if (stock === 0) {
781
- sendNotification({
782
- title: 'Sin stock',
783
- backgroundColor: 'warning',
784
- description: 'Producto sin stock disponible en tu inventario'
785
- })
786
- return state
787
- }
788
-
789
- const productExist = state?.PRODUCT.find((item) => item.pId === pId)
790
- const OurProduct = productsFood?.find((item) => item.pId === pId)
791
- const isFree = productExist?.free
792
- const currentQuantity = productExist?.ProQuantity || 0
793
-
794
- if (OurProduct?.manageStock && isStockInsufficient(currentQuantity, OurProduct?.stock)) {
795
- sendAlertStock(stock)
796
- return state
797
- }
798
- const updatedProduct = {
799
- pId,
800
- pName,
801
- editing: false,
802
- getOneTags,
803
- unitPrice: OurProduct?.ProPrice,
804
- manageStock: OurProduct?.manageStock ?? false,
805
- ProDescription,
806
- ProImage,
807
- ProPrice,
808
- stock,
809
- ProQuantity: 1
810
- }
811
-
812
- if (!productExist) {
813
- return {
814
- ...state,
815
- counter: state.counter + 1,
816
- totalAmount: state.totalAmount + ProPrice,
817
- startAnimateUp: 'start-animate-up',
818
- PRODUCT: [...state.PRODUCT, updatedProduct]
819
- }
820
- }
821
- return {
822
- ...state,
823
- counter: state.counter + 1,
824
- totalAmount: state.totalAmount + ProPrice,
825
- startAnimateUp: 'start-animate-up',
826
- PRODUCT: state.PRODUCT.map((item) => {
827
- if (item.pId === pId) {
828
- return {
829
- ...item,
830
- getOneTags: OurProduct?.genderTags,
831
- unitPrice: OurProduct?.ProPrice,
832
- editing: false,
833
- oldQuantity: productExist.ProQuantity + +1,
834
- ProPrice: isFree ? 0 : (productExist.ProQuantity + 1) * OurProduct?.ProPrice,
835
- ProQuantity: productExist.ProQuantity + +1,
836
- free: !!isFree
837
- }
838
- }
839
- return item
840
- })
841
- }
842
- }
843
-
844
- // TOGGLE_FREE_PRODUCT
845
- function toggleFreeProducts (state, action) {
846
- const productExist = productsFood.find((items) => {
847
- return items.pId === action.payload.pId
848
- })
849
- return {
850
- ...state,
851
- PRODUCT: state?.PRODUCT?.map((items) => {
852
- return items.pId === action.payload.pId
853
- ? {
854
- ...items,
855
- free: !items.free,
856
- ProPrice: items.ProPrice
857
- ? 0
858
- : items.ProQuantity * productExist?.ProPrice
859
- }
860
- : items
861
- })
862
- }
863
- }
864
-
865
- // COMMENT_FREE_PRODUCT
866
- function commentProducts (state, action, deleteValue) {
867
- if (values.comment) {
868
- sendNotification({
869
- backgroundColor: 'success',
870
- title: deleteValue ? 'Comentario eliminado' : 'Producto comentado',
871
- description: deleteValue ? 'Has eliminado el comentario!' : 'Has comentado!'
872
- })
873
- }
874
- setOpenCommentModal(!openCommentModal)
875
- return {
876
- ...state,
877
- PRODUCT: state?.PRODUCT?.map((items) => {
878
- return items.pId === action.payload
879
- ? {
880
- ...items,
881
- comment: deleteValue ? '' : values.comment
882
- }
883
- : items
884
- })
885
- }
886
- }
887
-
888
- const getSortedProduct = useCallback((data, sort) => {
889
- if (sort && sort === 'PRICE_HIGH_TO_LOW') {
890
- return data.sort((a, b) => {
891
- return b.ProPrice - a.ProPrice
892
- })
893
- }
894
- if (sort && sort === 'PRICE_LOW_TO_HIGH') {
895
- return data.sort((a, b) => {
896
- return a.ProPrice - b.ProPrice
897
- })
898
- }
899
- return data
900
- }, [])
901
-
902
- const PriceRangeFunc = (products, price) => {
903
- return (
904
- products?.length > 0 &&
905
- products?.filter((items) => {
906
- return items?.ProPrice >= price
907
- })
908
- )
909
- }
910
-
911
- const sortedProduct = useMemo(() => {
912
- return getSortedProduct(data.PRODUCT, data.sortBy)
913
- }, [data.PRODUCT, data.sortBy, getSortedProduct])
914
-
915
- const finalFilter = PriceRangeFunc(sortedProduct, data.priceRange)
916
-
917
- const handleList = (text) => {
918
- const inputText = text.toLowerCase()
919
- let dataList = []
920
- dataList = finalFilter.filter((item) => {
921
- return item.pName.toLowerCase().includes(inputText)
922
- })
923
- return dataList
924
- }
925
- const searchedInput = (words) => {
926
- setInputValue(words)
927
- const n = words.split(' ')
928
- if (n.length !== 0) {
929
- if (n[n.length - 1] === '') {
930
- n.pop()
931
- }
932
- return n[n.length - 1]
933
- }
934
- return ''
935
- }
936
- const arrayProduct = data?.PRODUCT?.length > 0
937
- ? data?.PRODUCT?.map((product) => {
938
- const filteredDataExtra =
939
- product?.dataExtra?.map(({ __typename, ...rest }) => rest) ?? []
940
- const dataOptional = product?.dataOptional?.map(
941
- ({ __typename, ...product }) => {
942
- const { ExtProductFoodsSubOptionalAll, ...rest } = product
943
- const adjustedSubOptionalAll = ExtProductFoodsSubOptionalAll?.map(
944
- (subOption) => {
945
- const { __typename, ...subOptionRest } = subOption
946
- return subOptionRest
947
- }
948
- )
949
- return {
950
- ...rest,
951
- ExtProductFoodsSubOptionalAll: adjustedSubOptionalAll
952
- }
953
- }
954
- )
955
- const refCodePid = RandomCode(20)
956
- const shoppingCartRefCode = RandomCode(36)
957
- return {
958
- pId: product?.pId,
959
- refCodePid,
960
- id: values?.cliId,
961
- cantProducts: parseInt(
962
- product?.ProQuantity ? product?.ProQuantity : 0
963
- ),
964
- comments: product?.comment ?? '',
965
- dataOptional: dataOptional ?? [],
966
- dataExtra: filteredDataExtra || [],
967
- ProPrice: product.ProPrice
968
- }
969
- })
970
- : []
971
- const finalArrayProduct = arrayProduct.map((item) => {
972
- const totalExtra = item.dataExtra.reduce(
973
- (accumulator, extra) => accumulator + extra.newExtraPrice,
974
- 0
975
- )
976
- return { ...item, totalExtra }
977
- })
978
-
979
- let totalSale = 0
980
- function sumProPriceAndTotalExtra (data) {
981
- return data.map((item) => {
982
- const totalExtra = item.dataExtra.reduce((acc, curr) => {
983
- const newExtraPrice = parseFloat(curr.newExtraPrice)
984
- if (isNaN(newExtraPrice)) {
985
- return acc
986
- }
987
- return acc + newExtraPrice
988
- }, 0)
989
- const total = item.ProPrice + totalExtra
990
- return { ...item, totalExtra, total }
991
- })
992
- }
993
- useEffect(() => {
994
- const dataCountTotal = sumProPriceAndTotalExtra(finalArrayProduct)
995
- dataCountTotal.forEach((a) => {
996
- const { total } = a || {}
997
- totalSale += total
998
- setTotalProductPrice(Math.abs(totalSale))
999
- })
1000
- if (data.PRODUCT.length === 0) {
1001
- setTotalProductPrice(0)
1002
- }
1003
- }, [totalProductPrice, totalSale, data, finalArrayProduct])
1004
-
1005
- const [discount, setDiscount] = useState({
1006
- price: totalProductPrice || 0,
1007
- discount: 0
1008
- })
1009
-
1010
- function applyDiscount (percentage) {
1011
- const validateCondition =
1012
- isNaN(percentage) || percentage < 0 || percentage > 100
1013
-
1014
- if (validateCondition) {
1015
- return sendNotification({
1016
- title: 'Error',
1017
- backgroundColor: 'error',
1018
- description: 'el descuento debe ser un número entre 0 y 100%'
1019
- })
1020
- }
1021
- const decimal = parseFloat(percentage) / 100
1022
- // @ts-ignore
1023
- const result = decimal * parseFloat(totalProductPrice)
1024
- setDiscount({ price: result, discount: percentage })
1025
-
1026
- return { price: result, discount: percentage }
1027
- }
1028
- const totalProductsPrice = totalProductPrice
1029
- const client = useApolloClient()
1030
- const { getOneSalesStore } = useGetSale()
1031
-
1032
- const handleSubmit = () => {
1033
- // @ts-ignore
1034
- if (errors?.change || errors?.valueDelivery) {
1035
- return sendNotification({
1036
- title: 'error',
1037
- backgroundColor: 'warning',
1038
- description: 'Completa los campos requeridos'
1039
- })
1040
- }
1041
- setLoadingSale(true)
1042
- const code = RandomCode(10)
1043
- // @ts-ignore
1044
- setCode(code)
1045
- function convertInteger (cadena) {
1046
- if (typeof cadena === 'string') {
1047
- const numeroEntero = parseInt(cadena?.replace('.', ''))
1048
- return numeroEntero
1049
- }
1050
- return cadena || 0
1051
- }
1052
- const {
1053
- change,
1054
- valueDelivery,
1055
- tableId
1056
- } = values || {
1057
- change: 0,
1058
- valueDelivery: 0,
1059
- tableId: null,
1060
- cliId: null
1061
- }
1062
-
1063
- const shoppingCartRefCode = `REF-${RandomCode(36)}`
1064
-
1065
- const input = finalArrayProduct.map((item) => {
1066
- return {
1067
- ...item,
1068
- shoppingCartRefCode
1069
- }
1070
- })
1071
- return registerSalesStore({
1072
- variables: {
1073
- input,
1074
- id: values?.cliId,
1075
- pCodeRef: code,
1076
- tableId,
1077
- change: convertInteger(change),
1078
- valueDelivery: convertInteger(valueDelivery),
1079
- payMethodPState: data.payMethodPState,
1080
- pickUp: 1,
1081
- shoppingCartRefCode,
1082
- discount: discount.discount ?? 0,
1083
- totalProductsPrice: convertInteger(totalProductsPrice) || 0
1084
- },
1085
- update (cache) {
1086
- cache.modify({
1087
- fields: {
1088
- productFoodsAll (existingProductFoodsAll = []) {
1089
- return existingProductFoodsAll
1090
- }
1091
- }
1092
- })
1093
- }
1094
- })
1095
- .then((response) => {
1096
- if (response) {
1097
- const { data } = response
1098
- const { registerSalesStore } = data ?? {}
1099
- const { success } = registerSalesStore ?? {}
1100
- if (success) {
1101
- setPrint(false)
1102
- client.query({
1103
- query: GET_ALL_COUNT_SALES,
1104
- fetchPolicy: 'network-only',
1105
- // @ts-ignore
1106
- onCompleted: (data) => {
1107
- client.writeQuery({ query: GET_ALL_COUNT_SALES, data: { getTodaySales: data.countSales.todaySales } })
1108
- }
1109
- })
1110
- setValues({})
1111
- handleChange({ target: { name: 'tableId', value: '' } })
1112
- getOneSalesStore({
1113
- variables: {
1114
- pCodeRef: code || ''
1115
- }
1116
- }).then((responseSale) => {
1117
- if (responseSale?.data?.getOneSalesStore) {
1118
- const currentSale = responseSale?.data?.getOneSalesStore || {}
1119
- const inComingCodeRef = currentSale?.pCodeRef || null
1120
- if (!inComingCodeRef) return
1121
- // client.cache.modify({
1122
- // fields: {
1123
- // getAllOrdersFromStore (existingOrders = []) {
1124
- // try {
1125
- // const newGetAllOrdersFromStore = updateExistingOrders(existingOrders, inComingCodeRef, 4, currentSale)
1126
- // return newGetAllOrdersFromStore
1127
- // } catch (e) {
1128
- // return existingOrders
1129
- // }
1130
- // }
1131
- // }
1132
- // })
1133
- }
1134
- })
1135
- router.push(
1136
- {
1137
- query: {
1138
- ...router.query,
1139
- saleId: code
1140
- }
1141
- },
1142
- undefined,
1143
- { shallow: true }
1144
- )
1145
- }
1146
- }
1147
- setLoadingSale(false)
1148
- })
1149
- .catch(() => {
1150
- setLoadingSale(false)
1151
- setErrorSale(true)
1152
- setPrint(false)
1153
- sendNotification({
1154
- title: 'error',
1155
- backgroundColor: 'error',
1156
- description: 'Lo sentimos, ocurrió un error'
1157
- })
1158
- })
1159
- .finally(() => {
1160
- setPrint(false)
1161
- setLoadingSale(false)
1162
- })
1163
- }
1164
-
1165
- const handleProduct = async (PRODUCT) => {
1166
- setLoadingExtraProduct(true)
1167
- const { pId } = PRODUCT || {}
1168
- try {
1169
- const originalArray = data.PRODUCT.find((item) => {
1170
- return item.pId === pId
1171
- })
1172
- // OPTIONAL
1173
- productFoodsOne({ variables: { pId } })
1174
- const optionalAll = await ExtProductFoodsSubOptionalAll({
1175
- variables: { pId }
1176
- })
1177
- const optionalFetch = optionalAll.data.ExtProductFoodsOptionalAll
1178
- setDataOptional(optionalFetch || [])
1179
- const existOptionalCookies = originalArray?.dataOptional
1180
- const filteredDataOptional = existOptionalCookies?.length
1181
- ? existOptionalCookies
1182
- ?.map((obj) => {
1183
- const filteredSubOptions =
1184
- obj.ExtProductFoodsSubOptionalAll.filter(
1185
- (subObj) => subObj.check === true
1186
- )
1187
- // Excluya todo el objeto padre si filteredSubOptions está vacío
1188
- if (filteredSubOptions.length === 0) {
1189
- return null
1190
- }
1191
- return {
1192
- ...obj,
1193
- ExtProductFoodsSubOptionalAll: filteredSubOptions
1194
- }
1195
- })
1196
- .filter((obj) => obj !== null)
1197
- : []
1198
-
1199
- // Actualizar optionalAll.data.ExtProductFoodsSubOptionalAll con los valores actualizados de originalArray2.ExtProductFoodsSubOptionalAll
1200
- if (optionalFetch && filteredDataOptional) {
1201
- const updateOption = optionalFetch
1202
- .map((obj) => {
1203
- const matchingArray = filteredDataOptional.find(
1204
- (o) => o && o.opExPid === obj.opExPid
1205
- )
1206
- if (!matchingArray) {
1207
- return obj
1208
- }
1209
- const extProductFoodsSubOptionalAll =
1210
- obj.ExtProductFoodsSubOptionalAll || []
1211
- const updateExtProductSubOptionalAll =
1212
- extProductFoodsSubOptionalAll.map((subObj) => {
1213
- const newItem =
1214
- matchingArray.ExtProductFoodsSubOptionalAll.find(
1215
- (newItem) =>
1216
- newItem && newItem.opSubExPid === subObj.opSubExPid
1217
- )
1218
- if (newItem) {
1219
- return {
1220
- ...subObj,
1221
- check: true
1222
- }
1223
- }
1224
- return subObj
1225
- })
1226
- return {
1227
- ...obj,
1228
- ExtProductFoodsSubOptionalAll:
1229
- updateExtProductSubOptionalAll
1230
- }
1231
- })
1232
- .filter((obj) => obj)
1233
- if (existOptionalCookies) {
1234
- setDataOptional(updateOption || [])
1235
- } else {
1236
- setDataOptional(optionalAll.data.ExtProductFoodsOptionalAll || [])
1237
- }
1238
- }
1239
- // NO OPTIONAL
1240
- const extProduct = await ExtProductFoodsAll({ variables: { pId } })
1241
- let finalData
1242
- if (!originalArray?.dataExtra) {
1243
- finalData = extProduct?.data?.ExtProductFoodsAll
1244
- } else {
1245
- const filteredData = originalArray.dataExtra.filter((item) =>
1246
- extProduct?.data?.ExtProductFoodsAll.some(
1247
- (newItem) => newItem.exPid === item.exPid
1248
- )
1249
- )
1250
- finalData = originalArray?.dataExtra?.concat(
1251
- extProduct?.data?.ExtProductFoodsAll?.filter(
1252
- (item) =>
1253
- !filteredData?.some(
1254
- (filteredItem) => filteredItem.exPid === item.exPid
1255
- )
1256
- )
1257
- )
1258
- }
1259
- setDataExtra(finalData)
1260
- setProduct(() => {
1261
- return {
1262
- PRODUCT
1263
- }
1264
- })
1265
- setLoadingExtraProduct(false)
1266
- } catch (error) {
1267
- setLoadingExtraProduct(false)
1268
- sendNotification({
1269
- title: 'error',
1270
- backgroundColor: 'error',
1271
- description: error || 'Lo sentimos, ocurrió un error'
1272
- })
1273
- }
1274
- }
1275
- const handleCleanFilter = () => {
1276
- // @ts-ignore
1277
- setValues({})
1278
- setValuesDates({ fromDate: yearMonthDay, toDate: '' })
1279
- }
1280
-
1281
- const disabledModalItems = (dataOptional?.length > 0 || dataExtra?.length > 0) && !loadingExtProductFoodsSubOptionalAll
1282
-
1283
- /**
1284
- * Filter objects with checked property equal to true.
1285
- * @param {Array} products - Array of objects.
1286
- * @returns {Array} - Array of objects with checked property equal to true.
1287
- */
1288
- function filterChecked (products) {
1289
- if (!Array.isArray(products)) {
1290
- return []
1291
- }
1292
-
1293
- return products.filter(product => product?.checked === true).map(product => product.carProId)
1294
- }
1295
-
1296
- // Obtener los carProIds de productos con checked en true
1297
- const carProIds = filterChecked(categories)
1298
-
1299
- // Filtrar los productos de productsFood por los carProIds obtenidos
1300
- const filteredProducts = filterProductsByCarProId(productsFood, carProIds)
1301
-
1302
- const allProducts = useMemo(() => {
1303
- const productMap = new Map(data.PRODUCT.map(item => [String(item.pId), item.ProQuantity || 0]))
1304
-
1305
- return filteredProducts.map(product => ({
1306
- ...product,
1307
- existsInSale: productMap.has(String(product.pId)),
1308
- ProQuantity: productMap.get(String(product.pId)) || 0
1309
- }))
1310
- }, [data.PRODUCT, filteredProducts])
1311
-
1312
- return {
1313
- loading: loading || loadingSale,
1314
- loadingExtraProduct,
1315
- disabledModalItems: !disabledModalItems,
1316
- loadingRegisterSale,
1317
- errorSale,
1318
- openCurrentSale,
1319
- code,
1320
- totalProductPrice,
1321
- saveDataState,
1322
- product,
1323
- data,
1324
- openCommentModal,
1325
- inputValue,
1326
- arrayProduct,
1327
- delivery,
1328
- valuesDates,
1329
- print,
1330
- finalFilter,
1331
- showMore,
1332
- max,
1333
- search,
1334
- values,
1335
- initialStateSales,
1336
- productsFood: allProducts,
1337
- modalItem,
1338
- sumExtraProducts,
1339
- oneProductToComment: oneProductToComment ?? null,
1340
- dataProduct: dataProduct?.productFoodsOne || {},
1341
- dataOptional: dataOptional || [],
1342
- dataExtra: dataExtra || [],
1343
- fetchMore,
1344
- pagination,
1345
- discount,
1346
- datCat: categories,
1347
- currentPage,
1348
- loadingProduct: loading,
1349
- handleChangeCheck,
1350
- errors,
1351
- handleUpdateAllExtra,
1352
- dispatch,
1353
- handlePageChange,
1354
- handleComment,
1355
- setModalItem,
1356
- handleChangeFilter,
1357
- handleProduct,
1358
- handleChange,
1359
- setOpenCurrentSale,
1360
- setErrors,
1361
- onChangeInput,
1362
- handleRemoveValue,
1363
- applyDiscount,
1364
- setDelivery,
1365
- setValues,
1366
- setShowMore,
1367
- PriceRangeFunc,
1368
- handleCleanFilter,
1369
- handleSubmit,
1370
- handleChangeFilterProduct,
1371
- handleDecrementExtra,
1372
- setTotalProductPrice,
1373
- setInputValue,
1374
- getSortedProduct,
1375
- handleAddOptional,
1376
- handleIncrementExtra,
1377
- setProduct,
1378
- setPrint: handlePrint,
1379
- PRODUCT
1380
- }
1381
- }