npm-pkg-hook 1.12.4 → 1.12.8

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 (354) hide show
  1. package/dist/index.js +57529 -0
  2. package/dist/index.js.map +1 -0
  3. package/dist/index.mjs +57315 -0
  4. package/dist/index.mjs.map +1 -0
  5. package/eslint.config.mts +153 -0
  6. package/package.json +30 -45
  7. package/src/config/client/errors.ts +39 -0
  8. package/src/hooks/addTenMinutes/{index.js → index.ts} +4 -4
  9. package/src/hooks/calculateLogLatHaversine/{index.js → index.ts} +15 -4
  10. package/src/hooks/completeSchedules/{index.js → index.ts} +4 -4
  11. package/src/hooks/convertToMilitaryTime/index.ts +18 -0
  12. package/src/hooks/generateStoreURL/index.ts +41 -0
  13. package/src/hooks/generateTemplate/{index.js → index.ts} +15 -11
  14. package/src/hooks/getCardType/{index.js → index.ts} +1 -1
  15. package/src/hooks/getCategoriesWithProduct/{index.js → index.ts} +7 -7
  16. package/src/hooks/getGlobalSession/index.ts +69 -0
  17. package/src/hooks/getSession/index.ts +72 -0
  18. package/src/hooks/getTodayTimestamps/{index.js → index.ts} +18 -12
  19. package/src/hooks/getTotalHours/index.ts +76 -0
  20. package/src/hooks/handleLogin/{index.js → index.ts} +4 -0
  21. package/src/hooks/index.ts +8 -2
  22. package/src/hooks/statusOpenStores/helpers/{index.js → index.ts} +24 -1
  23. package/src/hooks/statusOpenStores/index.ts +221 -0
  24. package/src/hooks/updateExtProductFoodsOptional/{index.js → index.ts} +12 -3
  25. package/src/hooks/useAcumulateDate/index.ts +18 -0
  26. package/src/hooks/useAllStoresPendingToRegister/{index.js → index.ts} +3 -0
  27. package/src/hooks/useAmountInput/index.ts +42 -32
  28. package/src/hooks/useAnimationText/{index.jsx → index.ts} +2 -2
  29. package/src/hooks/useAsideCart/{index.js → index.ts} +22 -19
  30. package/src/hooks/useBanner/{index.js → index.ts} +2 -1
  31. package/src/hooks/useCart/useCart/helpers/{index.js → index.ts} +10 -6
  32. package/src/hooks/useCart/useCart/{index.js → index.ts} +29 -17
  33. package/src/hooks/useCart/useGetCart/{index.js → index.ts} +2 -1
  34. package/src/hooks/useCatWithProduct/{index.js → index.ts} +11 -5
  35. package/src/hooks/useCatWithProduct/types/index.ts +104 -0
  36. package/src/hooks/useCatWithProductClient/{index.js → index.ts} +3 -2
  37. package/src/hooks/useCategoriesProduct/{index.js → index.ts} +2 -1
  38. package/src/hooks/useCategoryInStore/index.ts +167 -0
  39. package/src/hooks/useCategoryStore/{index.js → index.ts} +2 -1
  40. package/src/hooks/useCategoryStore/{queries.js → queries.ts} +2 -2
  41. package/src/hooks/useChartData/{index.js → index.ts} +9 -8
  42. package/src/hooks/useChartData/useChartData/{index.js → index.ts} +31 -30
  43. package/src/hooks/useChartData/useChartDataAllOrders/{index.js → index.ts} +2 -2
  44. package/src/hooks/useCheckbox/{index.js → index.ts} +1 -1
  45. package/src/hooks/useCities/{index.js → index.ts} +2 -1
  46. package/src/hooks/useClients/{index.js → index.ts} +2 -1
  47. package/src/hooks/useClients/{queries.js → queries.ts} +7 -4
  48. package/src/hooks/useColorByLetters/helpers/{alea.js → alea.ts} +19 -0
  49. package/src/hooks/useColorByLetters/helpers/{index.js → index.ts} +5 -1
  50. package/src/hooks/useColorByLetters/helpers/{mersenne_twister.js → mersenne_twister.ts} +1 -1
  51. package/src/hooks/useColorByLetters/{index.js → index.ts} +3 -6
  52. package/src/hooks/useConnection/{index.js → index.ts} +3 -3
  53. package/src/hooks/useCountries/{index.js → index.ts} +2 -1
  54. package/src/hooks/useCreateOrderStatusType/index.ts +8 -6
  55. package/src/hooks/useCreateProduct/helpers/{index.js → index.ts} +1 -1
  56. package/src/hooks/useCreateProduct/helpers/manageCacheDataCatProduct/{index.js → index.ts} +1 -1
  57. package/src/hooks/useCreateProduct/helpers/useEditImageProduct/{index.js → index.ts} +14 -8
  58. package/src/hooks/useCreateProduct/{index.js → index.ts} +22 -19
  59. package/src/hooks/useCreateStorePendingToRegister/{index.js → index.ts} +5 -1
  60. package/src/hooks/useDeleteExtraProductFoods/{index.js → index.ts} +2 -1
  61. package/src/hooks/useDeleteSubProductOptional/{index.js → index.ts} +5 -3
  62. package/src/hooks/useDeliveryTime/{index.js → index.ts} +3 -1
  63. package/src/hooks/useDepartments/{index.js → index.ts} +2 -1
  64. package/src/hooks/useDessert/{index.js → index.ts} +56 -52
  65. package/src/hooks/useDessertWithPrice/helpers/{index.js → index.ts} +4 -4
  66. package/src/hooks/useDessertWithPrice/{index.js → index.ts} +34 -26
  67. package/src/hooks/useDevWS/index.ts +43 -43
  68. package/src/hooks/useDevices/{useGetDevices.js → useGetDevices.ts} +3 -3
  69. package/src/hooks/useDevices/{useRegisterDevices.js → useRegisterDevices.ts} +5 -5
  70. package/src/hooks/useDownloadReports/helpers/downloadFileFromResponse.ts +17 -17
  71. package/src/hooks/useDownloadReports/useDownloadReportByDay/index.ts +4 -2
  72. package/src/hooks/useDownloadReports/useGetReportByDateRange/index.ts +3 -2
  73. package/src/hooks/useDrag/{index.js → index.ts} +16 -0
  74. package/src/hooks/useDropzone/{index.js → index.ts} +2 -2
  75. package/src/hooks/useDynamicAuth/{index.js → index.ts} +2 -1
  76. package/src/hooks/useEditCategory/{index.js → index.ts} +5 -5
  77. package/src/hooks/useEditOneExtProductFoodOptional/index.ts +28 -0
  78. package/src/hooks/useEditOneExtProductFoodOptional/{queries.js → queries.ts} +2 -2
  79. package/src/hooks/useEditSubProductOptional/index.ts +12 -0
  80. package/src/hooks/useEmployee/{index.js → index.ts} +2 -1
  81. package/src/hooks/useEmployee/{queries.js → queries.ts} +1 -1
  82. package/src/hooks/useEmployee/{useCreateEmployee.js → useCreateEmployee.ts} +6 -2
  83. package/src/hooks/useFavoriteStores/{index.js → index.ts} +5 -3
  84. package/src/hooks/useFetchMoreInteractions/index.jsx +26 -26
  85. package/src/hooks/useFilterConfigs/index.ts +173 -0
  86. package/src/hooks/useFingerprintjs/{index.js → index.ts} +29 -4
  87. package/src/hooks/useFormTools/{index.js → index.ts} +38 -11
  88. package/src/hooks/useFormatDate/{index.js → index.ts} +10 -5
  89. package/src/hooks/useFullScreenMode/{index.js → index.ts} +1 -5
  90. package/src/hooks/useGetAllLocationUser/{index.js → index.ts} +2 -1
  91. package/src/hooks/useGetAllLocationUser/{queries.js → queries.ts} +2 -2
  92. package/src/hooks/{useSales/useGetAllSales/index.js → useGetAllSales/index.ts} +3 -2
  93. package/src/hooks/useGetExtProductFoodsSubOptionalAll/{index.js → index.ts} +2 -1
  94. package/src/hooks/useGetFoodRecomended/{index.js → index.ts} +2 -1
  95. package/src/hooks/useGetMinPrice/{index.js → index.ts} +2 -1
  96. package/src/hooks/useGetOneStoreRating/{index.js → index.ts} +2 -1
  97. package/src/hooks/useGetStoreCookie/{index.js → index.ts} +1 -1
  98. package/src/hooks/useGoogleLogin/{index.js → index.ts} +14 -5
  99. package/src/hooks/useHover/{index.js → index.ts} +3 -0
  100. package/src/hooks/useImageOptimization/{index.js → index.ts} +4 -0
  101. package/src/hooks/useImageUploaderProduct/helper/canvasUtils.ts +25 -9
  102. package/src/hooks/useImageUploaderProduct/helper/getOrientation.ts +5 -4
  103. package/src/hooks/useImageUploaderProduct/index.ts +227 -224
  104. package/src/hooks/useImageWeight/{index.js → index.ts} +4 -0
  105. package/src/hooks/useImagesStore/{index.js → index.ts} +7 -5
  106. package/src/hooks/useImagesStore/{queries.js → queries.ts} +1 -1
  107. package/src/hooks/useIncomingOrders/{index.js → index.ts} +2 -1
  108. package/src/hooks/useIncomingOrders/{queries.js → queries.ts} +1 -1
  109. package/src/hooks/useIntersection/{index.js → index.ts} +1 -1
  110. package/src/hooks/useInventory/{queries.js → queries.ts} +2 -2
  111. package/src/hooks/useInventory/{useGetProductsInStock.js → useGetProductsInStock.ts} +2 -1
  112. package/src/hooks/useLazyScript/{index.js → index.ts} +3 -0
  113. package/src/hooks/useLocalSorage/{index.js → index.ts} +3 -3
  114. package/src/hooks/useLocationManager/{index.js → index.ts} +3 -3
  115. package/src/hooks/useLoginEmployeeInStore/{index.js → index.ts} +1 -1
  116. package/src/hooks/useLogout/helpers/BroadcastChannel.ts +74 -0
  117. package/src/hooks/useLogout/helpers/{apiBaseUrl.js → apiBaseUrl.ts} +4 -0
  118. package/src/hooks/useLogout/helpers/{fetchData.js → fetchData.ts} +10 -1
  119. package/src/hooks/useLogout/helpers/{getCsrfToken.js → getCsrfToken.ts} +8 -1
  120. package/src/hooks/useLogout/helpers/{index.js → index.ts} +14 -6
  121. package/src/hooks/useLogout/helpers/{logger.js → logger.ts} +26 -8
  122. package/src/hooks/useLogout/helpers/{parseUrl.js → parseUrl.ts} +5 -2
  123. package/src/hooks/useLogout/{index.js → index.ts} +29 -20
  124. package/src/hooks/useManageNewOrder/helpers/{index.js → index.ts} +1 -1
  125. package/src/hooks/useManageNewOrder/{index.js → index.ts} +6 -4
  126. package/src/hooks/useManageQueryParams/index.ts +120 -0
  127. package/src/hooks/useModules/helpers/{validateModules.js → validateModules.ts} +1 -1
  128. package/src/hooks/useModules/index.ts +124 -0
  129. package/src/hooks/useMouse/index.ts +23 -18
  130. package/src/hooks/useOrderStatusTypes/useOrderStatusTypes/index.ts +1 -1
  131. package/src/hooks/useOrderStatusTypes/useUpdateOrderStatusPriorities/index.ts +7 -5
  132. package/src/hooks/useOrders/{queries.js → queries.ts} +30 -20
  133. package/src/hooks/useOrders/useChangeOrderState/index.ts +79 -76
  134. package/src/hooks/useOrders/useOrdersFromStore/index.ts +4 -3
  135. package/src/hooks/usePaymentMethod/index.ts +3 -0
  136. package/src/hooks/usePaymentMethod/paymentMethod.gql.ts +62 -0
  137. package/src/hooks/usePaymentMethod/paymentMethod.types.ts +28 -0
  138. package/src/hooks/usePaymentMethod/useCreatePaymentMethod/index.ts +25 -0
  139. package/src/hooks/usePaymentMethod/useGetAllPaymentMethods/index.ts +19 -0
  140. package/src/hooks/usePaymentMethod/useGetPaymentMethod/index.ts +26 -0
  141. package/src/hooks/usePrintSaleTicket/index.ts +4 -0
  142. package/src/hooks/useProductsFood/{index.js → index.ts} +115 -27
  143. package/src/hooks/useProductsFood/{queriesStore.js → queriesStore.ts} +1 -1
  144. package/src/hooks/useProductsFood/{useEditProduct.js → useEditProduct.ts} +2 -1
  145. package/src/hooks/useProductsFood/{usetagsProducts.js → usetagsProducts.ts} +6 -3
  146. package/src/hooks/useProviders/useProvidersCreateStore/{index.js → index.ts} +2 -1
  147. package/src/hooks/useProviders/useProvidersDataStore/{index.js → index.ts} +2 -1
  148. package/src/hooks/useProvidersStore/{index.js → index.ts} +2 -1
  149. package/src/hooks/usePushNotificationOrder/{index.js → index.ts} +1 -1
  150. package/src/hooks/usePushNotifications/helpers/{index.js → index.ts} +9 -0
  151. package/src/hooks/usePushNotifications/{index.js → index.ts} +2 -1
  152. package/src/hooks/useQueryLocationsMap/{index.js → index.ts} +2 -1
  153. package/src/hooks/useRatingArrayData/{index.js → index.ts} +4 -4
  154. package/src/hooks/useRatingArrayData/{queries.js → queries.ts} +1 -1
  155. package/src/hooks/useRemoveExtraProductFoodsOptional/{index.js → index.ts} +2 -1
  156. package/src/hooks/useReport/{index.js → index.ts} +2 -1
  157. package/src/hooks/useReport/{queries.js → queries.ts} +2 -53
  158. package/src/hooks/useRestaurant/helpers/{index.js → index.ts} +4 -0
  159. package/src/hooks/useRestaurant/helpers/{manageStatusOpen.js → manageStatusOpen.ts} +1 -1
  160. package/src/hooks/useRestaurant/{index.js → index.ts} +5 -3
  161. package/src/hooks/useRoads/{index.js → index.ts} +2 -1
  162. package/src/hooks/useRoles/{queries.js → queries.ts} +1 -1
  163. package/src/hooks/useRoles/{useCreateRole.js → useCreateRole.ts} +4 -1
  164. package/src/hooks/useRoles/{useGetRoles.js → useGetRoles.ts} +2 -1
  165. package/src/hooks/useSales/helpers/add-product.utils.ts +120 -0
  166. package/src/hooks/useSales/helpers/apply-discount-to-cart.utils.ts +292 -0
  167. package/src/hooks/useSales/helpers/comment-product.utils.ts +41 -0
  168. package/src/hooks/useSales/helpers/constants/index.ts +38 -0
  169. package/src/hooks/useSales/helpers/extras.utils.ts +42 -0
  170. package/src/hooks/useSales/helpers/filterProductsByCarProId.utils.ts +17 -0
  171. package/src/hooks/useSales/helpers/increment-product-quantity.utils.ts +76 -0
  172. package/src/hooks/useSales/helpers/index.ts +3 -0
  173. package/src/hooks/useSales/helpers/initializer.utils.ts +22 -0
  174. package/src/hooks/useSales/helpers/isStockInsufficient.ts +3 -0
  175. package/src/hooks/useSales/helpers/remove-product.utils.test.ts +49 -0
  176. package/src/hooks/useSales/helpers/remove-product.utils.ts +34 -0
  177. package/src/hooks/useSales/helpers/resolveProduct.ts +29 -0
  178. package/src/hooks/useSales/helpers/useAddToCart.ts +64 -0
  179. package/src/hooks/useSales/{index.js → index.ts} +559 -522
  180. package/src/hooks/useSales/{queries.js → queries.ts} +187 -79
  181. package/src/hooks/useSales/types/index.ts +206 -0
  182. package/src/hooks/useSales/types/use-sales.types.ts +8 -0
  183. package/src/hooks/useSales/{useGetSale.js → useGetSale.ts} +10 -2
  184. package/src/hooks/useSales/{useTotalSales.js → useTotalSales.ts} +2 -1
  185. package/src/hooks/useSaveAvailableProduct/helpers/{index.js → index.ts} +4 -4
  186. package/src/hooks/useSaveAvailableProduct/{index.js → index.ts} +2 -1
  187. package/src/hooks/useSaveLocation/{index.js → index.ts} +2 -1
  188. package/src/hooks/useSaveLocation/{queries.js → queries.ts} +1 -1
  189. package/src/hooks/useSchedule/{index.jsx → index.ts} +14 -1
  190. package/src/hooks/useSchedule/{index.js → schedule.ts} +2 -1
  191. package/src/hooks/useScheduleData/{index.js → index.ts} +21 -9
  192. package/src/hooks/useSetImageProducts/{index.js → index.ts} +4 -2
  193. package/src/hooks/useSetupSchedule/{index.js → index.ts} +40 -28
  194. package/src/hooks/useStatusOpenStore/helpers/{index.js → index.ts} +24 -1
  195. package/src/hooks/useStatusOpenStore/{index.js → index.ts} +30 -14
  196. package/src/hooks/useStatusOrdersClient/{index.js → index.ts} +3 -2
  197. package/src/hooks/useStatusOrdersClient/{queries.js → queries.ts} +2 -2
  198. package/src/hooks/useStock/index.ts +1 -0
  199. package/src/hooks/useStock/useStockUpdatedAllSubscription.ts +40 -0
  200. package/src/hooks/useStockMovements/helpers/{index.js → index.ts} +1 -1
  201. package/src/hooks/useStockMovements/{index.js → index.ts} +4 -3
  202. package/src/hooks/useStore/{index.js → index.ts} +30 -27
  203. package/src/hooks/useStoreContacts/{index.js → index.ts} +11 -5
  204. package/src/hooks/useStoreTable/{useStoreTableCreate.js → useStoreTableCreate.ts} +3 -2
  205. package/src/hooks/useStoreTable/{useStoreTables.js → useStoreTables.ts} +2 -1
  206. package/src/hooks/useSubscriptionValidation/index.ts +112 -0
  207. package/src/hooks/useTagProducts/useDeleteOneTag.ts +66 -66
  208. package/src/hooks/useTagProducts/useGetAllTags.ts +2 -2
  209. package/src/hooks/useTagProducts/useRegisterMultipleTags.ts +27 -26
  210. package/src/hooks/useTheme/index.ts +65 -0
  211. package/src/hooks/useTimeAgo/{useTimeAgo.js → useTimeAgo.ts} +7 -7
  212. package/src/hooks/useTokenCards/{index.js → index.ts} +7 -3
  213. package/src/hooks/useUpdateCart/{index.js → index.ts} +3 -2
  214. package/src/hooks/useUpdateCartCookie/{index.js → index.ts} +23 -6
  215. package/src/hooks/useUpdateDashboardComponent/index.ts +11 -11
  216. package/src/hooks/useUpdateExtProductFoodsSubOptional/{index.js → index.ts} +2 -1
  217. package/src/hooks/useUpdateModuleOrder/{index.js → index.ts} +2 -2
  218. package/src/hooks/useUpdateMultipleExtProduct/{index.js → index.ts} +2 -1
  219. package/src/hooks/useUpdateMultipleProducts/{index.js → index.ts} +57 -20
  220. package/src/hooks/useUploadProducts/helpers/{parseNumber.js → parseNumber.ts} +3 -3
  221. package/src/hooks/useUploadProducts/{index.js → index.ts} +89 -69
  222. package/src/hooks/useUpsertGoal/{index.js → index.ts} +1 -1
  223. package/src/hooks/useUser/{index.js → index.ts} +5 -4
  224. package/src/hooks/useWeeklyStockMovement/helpers/{index.js → index.ts} +3 -3
  225. package/src/hooks/useWeeklyStockMovement/{index.js → index.ts} +4 -3
  226. package/src/hooks/useWindowSize/{index.js → index.ts} +9 -2
  227. package/src/index.ts +13 -0
  228. package/src/security/index.ts +1 -0
  229. package/src/services/index.ts +1 -0
  230. package/src/utils/UtilDateRange.ts +56 -0
  231. package/src/utils/generateCode.ts +222 -0
  232. package/src/utils/index.ts +2 -0
  233. package/src/utils/{index.js → utils.ts} +69 -31
  234. package/tsconfig.eslint.json +16 -0
  235. package/tsconfig.json +18 -2
  236. package/tsup.config.ts +24 -0
  237. package/.eslintrc.js +0 -38
  238. package/.eslintrc.json +0 -127
  239. package/src/config/client/errors.js +0 -26
  240. package/src/hooks/convertToMilitaryTime/index.js +0 -14
  241. package/src/hooks/generateStoreURL/index.js +0 -38
  242. package/src/hooks/getGlobalSession/index.js +0 -49
  243. package/src/hooks/getSession/index.js +0 -18
  244. package/src/hooks/getTotalHours/index.js +0 -48
  245. package/src/hooks/statusOpenStores/index.js +0 -156
  246. package/src/hooks/useAcumulateDate/index.js +0 -16
  247. package/src/hooks/useCategoryInStore/index.js +0 -100
  248. package/src/hooks/useEditOneExtProductFoodOptional/index.js +0 -28
  249. package/src/hooks/useEditSubProductOptional/index.js +0 -11
  250. package/src/hooks/useLogout/helpers/BroadcastChannel.js +0 -31
  251. package/src/hooks/useManageQueryParams/index.js +0 -40
  252. package/src/hooks/useModules/index.js +0 -58
  253. package/src/hooks/useSales/helpers/index.js +0 -55
  254. package/src/hooks/useSubscriptionValidation/index.js +0 -41
  255. package/src/index.jsx +0 -9
  256. package/src/security/index.js +0 -1
  257. package/src/utils/UtilDateRange.js +0 -31
  258. /package/src/config/client/{index.js → index.ts} +0 -0
  259. /package/src/config/content/{index.js → index.ts} +0 -0
  260. /package/src/cookies/{index.js → index.ts} +0 -0
  261. /package/src/hooks/getCategoriesWithProduct/helpers/{index.js → index.ts} +0 -0
  262. /package/src/hooks/isTokenExpired/{index.js → index.ts} +0 -0
  263. /package/src/hooks/newMessageSubscription/{index.js → index.ts} +0 -0
  264. /package/src/hooks/newStoreOrderSubscription/{index.js → index.ts} +0 -0
  265. /package/src/hooks/useAnimationFrame/{index.js → index.ts} +0 -0
  266. /package/src/hooks/useAsideCart/helpers/{index.js → index.ts} +0 -0
  267. /package/src/hooks/useAsideCart/{queries.js → queries.ts} +0 -0
  268. /package/src/hooks/useCart/{index.js → index.ts} +0 -0
  269. /package/src/hooks/useCart/{queries.js → queries.ts} +0 -0
  270. /package/src/hooks/useCatWithProduct/{queries.js → queries.ts} +0 -0
  271. /package/src/hooks/useCatWithProductClient/{queries.js → queries.ts} +0 -0
  272. /package/src/hooks/useCategoriesProduct/{queries.js → queries.ts} +0 -0
  273. /package/src/hooks/useCategoryInStore/{queries.js → queries.ts} +0 -0
  274. /package/src/hooks/useChatRoomSubscription/{index.js → index.ts} +0 -0
  275. /package/src/hooks/useCities/{queries.js → queries.ts} +0 -0
  276. /package/src/hooks/useColorByLetters/helpers/{colors.js → colors.ts} +0 -0
  277. /package/src/hooks/useCountries/{queries.js → queries.ts} +0 -0
  278. /package/src/hooks/useCreateDeliveryTime/{index.js → index.ts} +0 -0
  279. /package/src/hooks/useCreateStorePendingToRegister/{queries.js → queries.ts} +0 -0
  280. /package/src/hooks/useDashboardComponents/{index.js → index.ts} +0 -0
  281. /package/src/hooks/useDeleteSubProductOptional/{queries.js → queries.ts} +0 -0
  282. /package/src/hooks/useDepartments/{queries.js → queries.ts} +0 -0
  283. /package/src/hooks/useDessert/helpers/{index.js → index.ts} +0 -0
  284. /package/src/hooks/useDessertWithPrice/{queries.js → queries.ts} +0 -0
  285. /package/src/hooks/useDevices/{index.js → index.ts} +0 -0
  286. /package/src/hooks/useDevices/{queries.js → queries.ts} +0 -0
  287. /package/src/hooks/useDynamicAuth/{queries.js → queries.ts} +0 -0
  288. /package/src/hooks/useEditSubProductOptional/{queries.js → queries.ts} +0 -0
  289. /package/src/hooks/useEvent/{index.js → index.ts} +0 -0
  290. /package/src/hooks/useFavoriteStores/{queries.js → queries.ts} +0 -0
  291. /package/src/hooks/useFetchJson/{index.js → index.ts} +0 -0
  292. /package/src/hooks/useFormatNumberPhone/{index.js → index.ts} +0 -0
  293. /package/src/hooks/useGenerateNumberArray/{index.js → index.ts} +0 -0
  294. /package/src/hooks/useGetCookies/{index.js → index.ts} +0 -0
  295. /package/src/hooks/useGetFoodRecomended/{queries.js → queries.ts} +0 -0
  296. /package/src/hooks/useGetMessagesToRoom/{index.js → index.ts} +0 -0
  297. /package/src/hooks/useGetMinPrice/{queries.js → queries.ts} +0 -0
  298. /package/src/hooks/useGetOneStoreRating/{queries.js → queries.ts} +0 -0
  299. /package/src/hooks/useGetSalesAmountToday/{index.js → index.ts} +0 -0
  300. /package/src/hooks/useGoogleLogin/{loadScript.js → loadScript.ts} +0 -0
  301. /package/src/hooks/useGoogleLogin/{removeScript.js → removeScript.ts} +0 -0
  302. /package/src/hooks/useImagesStore/utils/{index.js → index.ts} +0 -0
  303. /package/src/hooks/useInnerHtml/{index.js → index.ts} +0 -0
  304. /package/src/hooks/useInventory/{index.js → index.ts} +0 -0
  305. /package/src/hooks/useInventory/{useUpdateManageStock.js → useUpdateManageStock.ts} +0 -0
  306. /package/src/hooks/useKeypress/{index.js → index.ts} +0 -0
  307. /package/src/hooks/useLocalBackendIp/{index.js → index.ts} +0 -0
  308. /package/src/hooks/useLocationNavigate/{index.js → index.ts} +0 -0
  309. /package/src/hooks/useManageNewOrder/helpers/{mock.js → mock.ts} +0 -0
  310. /package/src/hooks/useMobile/{index.js → index.ts} +0 -0
  311. /package/src/hooks/useModules/helpers/{index.js → index.ts} +0 -0
  312. /package/src/hooks/useMutateHeight/{index.js → index.ts} +0 -0
  313. /package/src/hooks/useOrderClient/{index.js → index.ts} +0 -0
  314. /package/src/hooks/useOrders/{index.js → index.ts} +0 -0
  315. /package/src/hooks/usePWAInstall/{index.js → index.ts} +0 -0
  316. /package/src/{services/index.js → hooks/useProductsFood/types/index.ts} +0 -0
  317. /package/src/hooks/useProviders/{index.js → index.ts} +0 -0
  318. /package/src/hooks/useProviders/{queries.js → queries.ts} +0 -0
  319. /package/src/hooks/useProvidersStore/{queries.js → queries.ts} +0 -0
  320. /package/src/hooks/useQueryLocationsMap/{queries.js → queries.ts} +0 -0
  321. /package/src/hooks/useReactToPrint/{index.js → index.txt} +0 -0
  322. /package/src/hooks/useRemoveExtraProductFoodsOptional/{queries.js → queries.ts} +0 -0
  323. /package/src/hooks/useRestaurant/{queries.js → queries.ts} +0 -0
  324. /package/src/hooks/useRoads/{queries.js → queries.ts} +0 -0
  325. /package/src/hooks/useRoles/{index.js → index.ts} +0 -0
  326. /package/src/hooks/useRoles/{useRemoveRoles.js → useRemoveRoles.ts} +0 -0
  327. /package/src/hooks/useRoles/{useUpdateRolesPriority.js → useUpdateRolesPriority.ts} +0 -0
  328. /package/src/hooks/useSaveAvailableProduct/{queries.js → queries.ts} +0 -0
  329. /package/src/hooks/useSchedule/{queries.js → queries.ts} +0 -0
  330. /package/src/hooks/useScroll/{index.js → index.ts} +0 -0
  331. /package/src/hooks/useScrollRotate/{index.js → index.ts} +0 -0
  332. /package/src/hooks/useSetImageProducts/{queries.js → queries.ts} +0 -0
  333. /package/src/hooks/useSetSession/{index.js → index.ts} +0 -0
  334. /package/src/hooks/useSetState/{index.js → index.ts} +0 -0
  335. /package/src/hooks/useSetupSchedule/helpers/{index.js → index.ts} +0 -0
  336. /package/src/hooks/useStatusOrdersClient/helpers/{index.js → index.ts} +0 -0
  337. /package/src/hooks/useStore/{queries.js → queries.ts} +0 -0
  338. /package/src/hooks/useStoreCalendar/{index.js → index.ts} +0 -0
  339. /package/src/hooks/useStoreContacts/{queries.js → queries.ts} +0 -0
  340. /package/src/hooks/useStoreTable/{index.js → index.ts} +0 -0
  341. /package/src/hooks/useStoreTable/{queries.js → queries.ts} +0 -0
  342. /package/src/hooks/useTopProductsMovements/{index.js → index.ts} +0 -0
  343. /package/src/hooks/useTotalAllSales/{index.js → index.ts} +0 -0
  344. /package/src/hooks/useTotalProductsInStock/{index.js → index.ts} +0 -0
  345. /package/src/hooks/useTotalProductsSold/{index.js → index.ts} +0 -0
  346. /package/src/hooks/useTotalProductsSolded/{index.js → index.ts} +0 -0
  347. /package/src/hooks/useUpdateExistingOrders/{index.js → index.ts} +0 -0
  348. /package/src/hooks/useUpdateMultipleExtProduct/{queries.js → queries.ts} +0 -0
  349. /package/src/hooks/useUpdateMultipleProducts/{queries.js → queries.ts} +0 -0
  350. /package/src/hooks/useUploadProducts/helpers/{index.js → index.ts} +0 -0
  351. /package/src/hooks/useUploadProducts/helpers/{validateProductDataExcel.js → validateProductDataExcel.ts} +0 -0
  352. /package/src/hooks/useUser/{queries.js → queries.ts} +0 -0
  353. /package/src/mock/dessert/{index.js → index.ts} +0 -0
  354. /package/src/mock/{index.js → index.ts} +0 -0
@@ -9,105 +9,108 @@ import {
9
9
  useReducer,
10
10
  useMemo,
11
11
  useState
12
- } from 'react'
12
+ } from 'react'
13
+
13
14
  import { Cookies } from '../../cookies'
14
15
  import { RandomCode, getCurrentDomain } from '../../utils'
16
+ import { generateTicket } from '../../utils/generateCode'
17
+ import { useCatWithProduct } from '../useCatWithProduct'
18
+ import { CatProductWithProduct, GetCatProductsWithProductResponse } from '../useCatWithProduct/types'
15
19
  import { useFormatDate } from '../useFormatDate'
16
- import { useProductsFood } from '../useProductsFood'
20
+ import { useLogout } from '../useLogout'
21
+ import { useGetOneProductsFood, useProductsFood } from '../useProductsFood'
17
22
  import {
18
23
  GET_ALL_EXTRA_PRODUCT,
19
24
  GET_EXTRAS_PRODUCT_FOOD_OPTIONAL,
20
25
  GET_ONE_PRODUCTS_FOOD
21
26
  } from '../useProductsFood/queriesStore'
22
- import { useStore } from '../useStore'
27
+ import { useStore } from '../useStore'
28
+
29
+ // import { updateExistingOrders } from '../useUpdateExistingOrders'
30
+
31
+ import { addToCartFunc } from './helpers/add-product.utils'
32
+ import { applyDiscountToCart } from './helpers/apply-discount-to-cart.utils'
33
+ import { initialStateSales, SalesActionTypes } from './helpers/constants'
34
+ import { decrementExtra } from './helpers/extras.utils'
35
+ import { filterProductsByCarProId } from './helpers/filterProductsByCarProId.utils'
36
+ import { handleRemoveProduct } from './helpers/remove-product.utils'
37
+ import { incrementProductQuantity } from './helpers/increment-product-quantity.utils'
23
38
  import {
24
39
  CREATE_SHOPPING_CARD_TO_USER_STORE,
25
40
  GET_ALL_COUNT_SALES
26
41
  } from './queries'
27
- import { updateExistingOrders } from '../useUpdateExistingOrders'
42
+ import { SalesReducerAction, SalesState, ValuesState } from './types'
43
+ import { UseSalesProps } from './types/use-sales.types'
44
+ import { initializer } from './helpers/initializer.utils'
28
45
  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
46
 
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
47
 
58
48
  export const useSales = ({
59
49
  disabled = false,
60
50
  router,
61
51
  sendNotification = (args) => { return args },
62
52
  setAlertBox = (args) => { return args }
63
- }) => {
53
+ }: UseSalesProps) => {
54
+ const keyToSaveData = String(process.env.NEXT_LOCAL_SALES_STORE)
55
+ const saveDataState = JSON.parse(Cookies.get(keyToSaveData) ?? '[]')
64
56
  const domain = getCurrentDomain()
65
57
  const [loadingSale, setLoadingSale] = useState(false)
66
58
  const [errorSale, setErrorSale] = useState(false)
67
59
  const [onClickLogout] = useLogout({})
68
-
69
60
  const [modalItem, setModalItem] = useState(false)
70
61
  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
62
  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
63
+ const [categories, setCategories] = useState<CatProductWithProduct[]>([])
64
+
65
+ useCatWithProduct({
66
+ max: Infinity,
67
+ callback: (data: GetCatProductsWithProductResponse) => {
68
+ return setCategories(data.getCatProductsWithProduct?.catProductsWithProduct || [])
69
+ }
70
+ })
71
+ const [currentPage, setCurrentPage] = useState<number>(1)
72
+ const [totalProductPrice, setTotalProductPrice] = useState<number>(0)
73
+ const [showMore, setShowMore] = useState<number>(100)
74
+ const [inputValue, setInputValue] = useState<string>('')
75
+
85
76
  const [_, setFilteredList] = useState([])
86
- const [delivery, setDelivery] = useState(false)
87
- const [print, setPrint] = useState(false)
77
+ const [delivery, setDelivery] = useState<boolean>(false)
78
+ const [print, setPrint] = useState<boolean>(false)
88
79
  const [errors, setErrors] = useState({})
89
- const [values, setValues] = useState({
90
- comment: '',
80
+
81
+ const initialValuesState: ValuesState = {
91
82
  change: '',
92
83
  cliId: '',
84
+ comment: '',
85
+ tableId: '',
93
86
  valueDelivery: ''
94
- })
87
+ }
88
+ const [values, setValues] = useState<ValuesState>(initialValuesState)
89
+
95
90
  const [dataStore] = useStore()
96
- const { createdAt } = dataStore || {}
91
+ const { createdAt, idStore } = dataStore ?? {
92
+ createdAt: null,
93
+ idStore: null
94
+ }
97
95
  const [code, setCode] = useState(null)
98
96
  const [openCurrentSale, setOpenCurrentSale] = useState(null)
99
97
  const [oneProductToComment, setOneProductToComment] = useState({})
100
98
  const [sumExtraProducts, setSumExtraProducts] = useState(0)
101
99
  const { yearMonthDay } = useFormatDate({ date: createdAt })
100
+ const [handleGetOneProduct] = useGetOneProductsFood()
102
101
  const [valuesDates, setValuesDates] = useState(() => {
103
102
  return { fromDate: yearMonthDay, toDate: '' }
104
103
  })
104
+
105
105
  const [product, setProduct] = useState({
106
- PRODUCT: {}
106
+ PRODUCT: {
107
+ pId: null
108
+ }
107
109
  })
110
+
108
111
  const [loadingExtraProduct, setLoadingExtraProduct] = useState(false)
109
- const [dataOptional, setDataOptional] = useState([])
110
- const [dataExtra, setDataExtra] = useState([])
112
+ const [dataOptional, setDataOptional] = useState<any[]>([])
113
+ const [dataExtra, setDataExtra] = useState<any[]>([])
111
114
  const [registerSalesStore, { loading: loadingRegisterSale }] = useMutation(
112
115
  CREATE_SHOPPING_CARD_TO_USER_STORE,
113
116
  {
@@ -131,7 +134,7 @@ export const useSales = ({
131
134
  onError: (error) => {
132
135
  sendNotification({
133
136
  backgroundColor: 'error',
134
- title: error ?? 'Lo sentimos',
137
+ title: typeof error === 'string' ? error : 'Lo sentimos',
135
138
  description: 'ha ocurrido un error'
136
139
  })
137
140
  }
@@ -170,42 +173,42 @@ export const useSales = ({
170
173
  max: showMore,
171
174
  min: 0,
172
175
  isShopppingCard: true,
176
+ idStore: idStore ?? '',
173
177
  dataSale: (Array.isArray(saveDataState?.PRODUCT) && saveDataState?.PRODUCT) ?? [],
174
- callback: () => { return null }
178
+ callback: () => { return }
175
179
  })
176
180
 
177
- const handlePageChange = (pageNumber) => {
181
+ const handlePageChange = (pageNumber: number) => {
178
182
  setCurrentPage(pageNumber)
179
183
  refetch({ page: pageNumber })
180
184
  }
181
185
 
182
- const handleChangeCheck = (caId) => {
183
- // @ts-ignore
186
+ /**
187
+ * Toggles the `checked` field of a category with maximum performance.
188
+ * @param {string} caId - Category ID to toggle.
189
+ */
190
+ const handleChangeCheck = (caId: string) => {
184
191
  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
+ if (!prev || prev.length === 0) return prev
193
+
194
+ const index = prev.findIndex((item) => {return item.carProId === caId})
195
+ if (index === -1) return prev // nothing to update → no rerender
196
+
197
+ const target = prev[index]
198
+
199
+ const updatedItem = {
200
+ ...target,
201
+ checked: !target.checked
202
+ }
203
+
204
+ const newList = [...prev] // clone array ONCE
205
+ newList[index] = updatedItem
206
+
207
+ return newList
192
208
  })
193
209
  }
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
- }
210
+
211
+
209
212
  // HANDLESS
210
213
  // FILTER PRODUCT DATA_DB
211
214
  // @ts-ignore
@@ -219,40 +222,64 @@ export const useSales = ({
219
222
  }
220
223
  setPrint(!print)
221
224
  }
222
- const handleChangeFilter = (e) => {
223
- return setSearch(e.target.value)
225
+
226
+ const handleChangeFilter = (value: string): void => {
227
+ return setSearch(value)
224
228
  }
225
- const handleChange = (e, error) => {
226
- const { name, value } = e.target
227
- setErrors({ ...errors, [e.target.name]: error })
228
- setValues((prevValues) => ({
229
+
230
+ const handleChange = (
231
+ e: React.ChangeEvent<HTMLInputElement> | { target: { name: string; value: any } },
232
+ error: boolean
233
+ ) => {
234
+ const target: any = (e as any).target
235
+ const { name, value } = target
236
+ setErrors({ ...errors, [name]: error })
237
+ setValues((prevValues) => {return {
229
238
  ...prevValues,
230
239
  [name]: value
231
- }))
240
+ }})
232
241
  }
233
- const onChangeInput = (e) => {
242
+
243
+ const onChangeInput = (e: React.ChangeEvent<HTMLInputElement>) => {
234
244
  return setValuesDates({ ...valuesDates, [e.target.name]: e.target.value })
235
245
  }
236
- const handleToggleEditingStatus = (state, action) => {
237
- const { PRODUCT } = state ?? {
238
- PRODUCT: []
246
+
247
+ /**
248
+ * Toggles editing state of a product with maximum performance.
249
+ * @param {any} state - Current reducer state.
250
+ * @param {any} action - Payload with product ID.
251
+ * @returns {any} New updated state.
252
+ */
253
+ const handleToggleEditingStatus = (state: any, action: any) => {
254
+ const pId = action?.payload?.pId
255
+ if (!pId) return state
256
+
257
+ const list = state.PRODUCT
258
+ const index = list.findIndex((item: any) => {return item.pId === pId})
259
+
260
+ // If no match, nothing changes → no re-render
261
+ if (index === -1) return state
262
+
263
+ const target = list[index]
264
+
265
+ const updatedItem = {
266
+ ...target,
267
+ editing: !target.editing,
268
+ oldQuantity: target.ProQuantity ?? 0
239
269
  }
270
+
271
+ // Clone the array only once
272
+ const newList = [...list]
273
+ newList[index] = updatedItem
274
+
240
275
  return {
241
276
  ...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
- })
277
+ PRODUCT: newList
252
278
  }
253
279
  }
254
280
 
255
- const handleChangeFilterProduct = (e) => {
281
+
282
+ const handleChangeFilterProduct = (e: React.ChangeEvent<HTMLInputElement>) => {
256
283
  const text = searchedInput(e.target.value)
257
284
  if (text === undefined || text === '') {
258
285
  return
@@ -260,7 +287,8 @@ export const useSales = ({
260
287
  const filteredData = handleList(text)
261
288
  setFilteredList(filteredData)
262
289
  }
263
- const handleComment = (product) => {
290
+
291
+ const handleComment = (product: any) => {
264
292
  if (product) {
265
293
  setOneProductToComment(product)
266
294
  setValues({
@@ -270,31 +298,52 @@ export const useSales = ({
270
298
  }
271
299
  setOpenCommentModal(!openCommentModal)
272
300
  }
273
- const handleSuccessUpdateQuantity = (state, payload) => {
274
- const { pId } = payload.payload || {
275
- pId: null
301
+
302
+ /**
303
+ * Updates a single product inside the PRODUCT array with maximum performance.
304
+ * @param {any} state - Current state.
305
+ * @param {any} payload - Action payload.
306
+ * @returns {any} New updated state.
307
+ */
308
+ const handleSuccessUpdateQuantity = (state: any, payload: any) => {
309
+ const pId = payload?.payload?.pId
310
+ if (!pId) return state
311
+
312
+ const list = state.PRODUCT
313
+ const index = list.findIndex((item: any) => {return item.pId === pId})
314
+
315
+ // If no match → no state changes → no rerender
316
+ if (index === -1) return state
317
+
318
+ const target = list[index]
319
+ const updatedItem = {
320
+ ...target,
321
+ editing: false,
322
+ oldQuantity: target.ProQuantity ?? 0
276
323
  }
324
+
325
+ // Clone array ONCE
326
+ const newList = [...list]
327
+ newList[index] = updatedItem
328
+ sendNotification({
329
+ title: 'Cantidad actualizada',
330
+ backgroundColor: 'success',
331
+ description: `La cantidad de ${target.pName} ha sido actualizada a ${updatedItem.ProQuantity}.`
332
+ })
277
333
  return {
278
334
  ...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
- })
335
+ PRODUCT: newList
288
336
  }
289
337
  }
290
338
 
339
+
291
340
  /**
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) => {
341
+ * Cancels the update of a product's quantity, resetting it to the previous value.
342
+ * @param {Object} state - The current state.
343
+ * @param {Object} payload - The payload containing the product ID.
344
+ * @returns {Object} - The new state with the updated product quantity and editing status.
345
+ */
346
+ const handleCancelUpdateQuantity = (state: any, payload: any) => {
298
347
  // Validación de `state`
299
348
  if (!state || typeof state !== 'object') {
300
349
  sendNotification({
@@ -312,7 +361,7 @@ export const useSales = ({
312
361
  backgroundColor: 'error',
313
362
  description: 'Ha ocurrido un error al actualizar la cantidad del producto.'
314
363
  })
315
- return state // Retorna el estado sin cambios si `PRODUCT` no es un array.
364
+ return state
316
365
  }
317
366
 
318
367
  // Validación de `payload`
@@ -328,7 +377,7 @@ export const useSales = ({
328
377
 
329
378
  return {
330
379
  ...state,
331
- PRODUCT: state.PRODUCT.map((item) => {
380
+ PRODUCT: state.PRODUCT.map((item: any) => {
332
381
  // Validación de propiedades en cada item
333
382
  if (item.pId === pId) {
334
383
  if (typeof item.oldQuantity !== 'number' || typeof item.unitPrice !== 'number') {
@@ -353,97 +402,77 @@ export const useSales = ({
353
402
  }
354
403
  }
355
404
 
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) => {
405
+ const paymentMethod = (state: any, action: any) => {
412
406
  return {
413
407
  ...state,
414
- payMethodPState: action.payload
408
+ payId: action.payload
409
+ }
410
+ }
411
+
412
+
413
+ const handleAddProduct = async (product: any) => {
414
+ const pId = String(product?.pId)
415
+ const memo = productsFood.find((item: any) => {return String(item.pId) === pId})
416
+ if (!memo) {
417
+ const response = await handleGetOneProduct({ pId })
418
+ if (response.data?.productFoodsOne == null) {return sendNotification({
419
+ title: 'Error',
420
+ backgroundColor: 'error',
421
+ description: 'No se pudo obtener el producto'
422
+ })}
423
+ const productData = response.data?.productFoodsOne ?? { pId: null }
424
+ return dispatch({
425
+ type: SalesActionTypes.ADD_TO_CART,
426
+ payload: productData
427
+ })
415
428
  }
429
+ return dispatch({
430
+ type: SalesActionTypes.ADD_TO_CART,
431
+ payload: memo
432
+ })
416
433
  }
417
- const PRODUCT = (state, action) => {
434
+
435
+ const PRODUCT = (state: any, action: any) => {
418
436
  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':
437
+ case SalesActionTypes.ADD_TO_CART:
438
+ return addToCartFunc({
439
+ state,
440
+ action,
441
+ product: action.payload,
442
+ sendAlertStock,
443
+ sendNotification
444
+ })
445
+ case SalesActionTypes.ADD_PRODUCT:
422
446
  return {
423
447
  ...state,
424
448
  // eslint-disable-next-line
425
449
  PRODUCT: [...state?.PRODUCT, action?.payload],
426
450
  }
427
- case 'REMOVE_PRODUCT':
428
- return removeFunc(state, action, productsFood)
429
- case 'REMOVE_PRODUCT_TO_CART':
451
+ case SalesActionTypes.REMOVE_PRODUCT:
452
+ return handleRemoveProduct(state, action, productsFood)
453
+ case SalesActionTypes.REMOVE_PRODUCT_TO_CART:
430
454
  return {
431
455
  ...state,
432
- PRODUCT: state?.PRODUCT?.filter((t) => {
456
+ PRODUCT: state?.PRODUCT?.filter((t: any) => {
433
457
  return t.pId !== action?.payload.pId
434
458
  }),
435
459
  counter: state.counter - action.payload.ProQuantity
436
460
  }
437
- case 'ON_CHANGE': {
438
- return handleChangeNumber(state, action)
461
+ case SalesActionTypes.ON_CHANGE: {
462
+ return handleChangeNumber(
463
+ state,
464
+ action,
465
+ productsFood,
466
+ sendNotification
467
+ )
439
468
  }
440
- case 'UPDATE_SUCCESS_QUANTITY_EDITING_PRODUCT': {
469
+ case SalesActionTypes.UPDATE_SUCCESS_QUANTITY_EDITING_PRODUCT: {
441
470
  return handleSuccessUpdateQuantity(state, action)
442
471
  }
443
- case 'CANCEL_UPDATE_QUANTITY_EDITING_PRODUCT': {
472
+ case SalesActionTypes.CANCEL_UPDATE_QUANTITY_EDITING_PRODUCT: {
444
473
  return handleCancelUpdateQuantity(state, action)
445
474
  }
446
- case 'REMOVE_ALL_PRODUCTS':
475
+ case SalesActionTypes.REMOVE_ALL_PRODUCTS:
447
476
  // @ts-ignore
448
477
  setValues({
449
478
  ...values,
@@ -458,104 +487,75 @@ export const useSales = ({
458
487
  counter: 0
459
488
  }
460
489
 
461
- case 'TOGGLE_FREE_PRODUCT':
490
+ case SalesActionTypes.TOGGLE_FREE_PRODUCT:
462
491
  return toggleFreeProducts(state, action)
463
- case 'TOGGLE_EDITING_PRODUCT': {
492
+ case SalesActionTypes.TOGGLE_EDITING_PRODUCT: {
464
493
  return handleToggleEditingStatus(state, action)
465
494
  }
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
- }
495
+ case SalesActionTypes.INCREMENT: {
496
+ return incrementProductQuantity({
497
+ state,
498
+ productId: action.id,
499
+ productsFood,
500
+ sendNotification
501
+ })
504
502
  }
505
503
 
506
- case 'PUT_COMMENT':
504
+ case SalesActionTypes.PUT_COMMENT:
507
505
  return commentProducts(state, action)
508
- case 'PUT_EXTRA_PRODUCTS_AND_OPTIONAL_PRODUCT':
506
+ case SalesActionTypes.PUT_EXTRA_PRODUCTS_AND_OPTIONAL_PRODUCT:
509
507
  return handleUpdateAllExtraAndOptional(state, action)
510
- case 'PRICE_RANGE':
508
+ case SalesActionTypes.PRICE_RANGE:
511
509
  return {
512
510
  ...state,
513
511
  priceRange: action.payload
514
512
  }
515
- case 'SORT':
513
+ case SalesActionTypes.SORT:
516
514
  return { ...state, sortBy: action.payload }
517
- case 'DECREMENT':
515
+ case SalesActionTypes.DECREMENT:
518
516
  return {
519
517
  ...state
520
518
  }
521
- case 'PAYMENT_METHOD': return paymentMethod(state, action)
519
+ case SalesActionTypes.PAYMENT_METHOD: return paymentMethod(state, action)
522
520
 
521
+ case SalesActionTypes.APPLY_DISCOUNT: {
522
+ return applyDiscountToCart(
523
+ state,
524
+ action.payload,
525
+ sendNotification
526
+ )
527
+ }
523
528
  default:
524
529
  return state
525
530
  }
526
531
  }
527
- const [data, dispatch] = useReducer(PRODUCT, initialStateSales, initializer)
528
532
 
529
- const handleRemoveValue = useCallback(({ name, value, pId }) => {
533
+ const [data, dispatch] = useReducer<React.Reducer<SalesState, SalesReducerAction>, SalesState>(PRODUCT, initialStateSales, initializer)
534
+
535
+ const handleRemoveValue = useCallback(({ name, value, pId }: { name: string; value: string | null; pId: string }) => {
530
536
  setValues({
531
537
  ...values,
532
538
  [name]: value ?? ''
533
539
  })
534
540
  sendNotification({
535
- backgroundColor: 'sucess',
541
+ backgroundColor: 'success',
536
542
  title: 'Comentario eliminado',
537
543
  description: 'Has eliminado el comentario!'
538
544
  })
539
545
  // @ts-ignore
540
546
  return dispatch({
541
- type: 'PUT_COMMENT',
547
+ type: SalesActionTypes.PUT_COMMENT,
542
548
  payload: pId,
543
549
  value: ''
544
550
  })
545
551
  }, [])
546
- useEffect(() => {
547
- // @ts-ignore
548
- Cookies.set(keyToSaveData, JSON.stringify(data), { domain, path: '/' })
549
- }, [data, domain])
550
552
 
551
553
  const handleAddOptional = ({ exOptional = null, codeCategory = null }) => {
552
554
  if (!exOptional || !codeCategory) return
553
- // @ts-ignore
554
- const item = dataOptional.find((item) => item.code === codeCategory)
555
+ const item = dataOptional.find((item) => {return item.code === codeCategory})
555
556
  if (!item) return
556
- // @ts-ignore
557
557
  const idx = item.ExtProductFoodsSubOptionalAll.findIndex(
558
- (el) => el.opSubExPid === exOptional
558
+ (el: any) => {return el.opSubExPid === exOptional}
559
559
  )
560
560
  if (item && idx !== -1) {
561
561
  const updatedItem = {
@@ -575,24 +575,29 @@ export const useSales = ({
575
575
  ]
576
576
  }
577
577
  const newData = dataOptional.map((el) =>
578
- // @ts-ignore
579
- el.code === codeCategory ? updatedItem : el
578
+ // @ts-ignore
579
+ {return el.code === codeCategory ? updatedItem : el}
580
580
  )
581
581
  // @ts-ignore
582
- setDataOptional(() => [...newData])
582
+ setDataOptional(() => {return [...newData]})
583
583
  }
584
584
  }
585
585
 
586
- function handleUpdateAllExtraAndOptional (state, action) {
586
+ /**
587
+ *
588
+ * @param state
589
+ * @param action
590
+ */
591
+ function handleUpdateAllExtraAndOptional(state: any, action: any) {
587
592
  return {
588
593
  ...state,
589
- PRODUCT: state?.PRODUCT?.map((items) => {
594
+ PRODUCT: state?.PRODUCT?.map((items: any) => {
590
595
  return items.pId === action.payload
591
596
  ? {
592
- ...items,
593
- dataOptional: action.dataOptional || [],
594
- dataExtra: action.dataExtra || []
595
- }
597
+ ...items,
598
+ dataOptional: action.dataOptional || [],
599
+ dataExtra: action.dataExtra || []
600
+ }
596
601
  : items
597
602
  })
598
603
  }
@@ -610,13 +615,16 @@ export const useSales = ({
610
615
  return p.quantity !== 0
611
616
  })
612
617
  : []
613
- const val = arr.findIndex((item) => item.quantity !== 0)
618
+ const val = arr.findIndex((item: any) => {return item.quantity !== 0})
614
619
  if (val === -1) {
615
620
  setSumExtraProducts(0)
616
621
  }
617
- function sumNewExtraPrice () {
622
+ /**
623
+ *
624
+ */
625
+ function sumNewExtraPrice() {
618
626
  let sum = 0
619
- arr.forEach((obj) => {
627
+ arr.forEach((obj: any) => {
620
628
  sum += obj.newExtraPrice ?? 0
621
629
  })
622
630
  if (arr.length === 0) {
@@ -630,7 +638,10 @@ export const useSales = ({
630
638
  }
631
639
  }, [dataExtra])
632
640
 
633
- function handleUpdateAllExtra () {
641
+ /**
642
+ *
643
+ */
644
+ function handleUpdateAllExtra() {
634
645
  try {
635
646
  if (!product?.PRODUCT?.pId) {
636
647
  return sendNotification({
@@ -643,7 +654,7 @@ export const useSales = ({
643
654
  .map((obj) => {
644
655
  // @ts-ignore
645
656
  const filteredSubOptions = obj?.ExtProductFoodsSubOptionalAll?.filter(
646
- (subObj) => subObj?.check === true
657
+ (subObj: any) => {return subObj?.check === true}
647
658
  )
648
659
  // Excluya todo el objeto padre si filteredSubOptions está vacío
649
660
  if (filteredSubOptions?.length === 0) {
@@ -652,13 +663,13 @@ export const useSales = ({
652
663
  // @ts-ignore
653
664
  return { ...obj, ExtProductFoodsSubOptionalAll: filteredSubOptions }
654
665
  })
655
- .filter((obj) => obj !== null) // Elimine todos los objetos nulos del arreglo
666
+ .filter((obj) => {return obj !== null}) // Elimine todos los objetos nulos del arreglo
656
667
  // @ts-ignore
657
- const filteredDataExtra = dataExtra?.filter((p) => p?.quantity !== undefined && p?.quantity !== 0)
668
+ const filteredDataExtra = dataExtra?.filter((p) => {return p?.quantity !== undefined && p?.quantity !== 0})
658
669
  if (product?.PRODUCT?.pId) {
659
670
  // @ts-ignore
660
671
  dispatch({
661
- type: 'PUT_EXTRA_PRODUCTS_AND_OPTIONAL_PRODUCT',
672
+ type: SalesActionTypes.PUT_EXTRA_PRODUCTS_AND_OPTIONAL_PRODUCT,
662
673
  payload: product.PRODUCT.pId,
663
674
  dataOptional: filteredDataOptional,
664
675
  dataExtra: filteredDataExtra
@@ -684,7 +695,13 @@ export const useSales = ({
684
695
  }
685
696
 
686
697
  // @ts-ignore
687
- function handleIncrementExtra ({ Adicionales, index }) {
698
+ /**
699
+ *
700
+ * @param root0
701
+ * @param root0.Adicionales
702
+ * @param root0.index
703
+ */
704
+ function handleIncrementExtra({ Adicionales, index }) {
688
705
  const { pId } = product?.PRODUCT || {}
689
706
  const exPid = Adicionales?.exPid || null
690
707
 
@@ -712,54 +729,18 @@ export const useSales = ({
712
729
  setDataExtra(newExtra)
713
730
  }
714
731
  }
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
- }
732
+ const handleDecrementExtra = ({ Adicionales }: { Adicionales: any }) => {
733
+ const exPid = Adicionales?.exPid
734
+ if (!exPid) return
735
+ setDataExtra((prev) => {return decrementExtra(prev as any, exPid)})
756
736
  }
757
737
 
758
- function isStockInsufficient (currentQuantity, stock) {
759
- return currentQuantity >= stock
760
- }
761
738
 
762
- function sendAlertStock (stock) {
739
+ /**
740
+ *
741
+ * @param stock
742
+ */
743
+ function sendAlertStock(stock: number) {
763
744
  return sendNotification({
764
745
  title: 'Stock insuficiente',
765
746
  backgroundColor: 'warning',
@@ -767,103 +748,58 @@ export const useSales = ({
767
748
  })
768
749
  }
769
750
 
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
751
+ /**
752
+ * Toggles free mode for a product and recalculates its price
753
+ * with maximum performance.
754
+ * @param {any} state - Current reducer state.
755
+ * @param {any} action - Payload containing pId.
756
+ * @returns {any} Updated state.
757
+ */
758
+ function toggleFreeProducts(state: any, action: any) {
759
+ const pId = action?.payload?.pId
760
+ if (!pId) return state
761
+
762
+ // Find the reference product price only once
763
+ const referenceProduct = productsFood.find((item: any) => {return item.pId === pId})
764
+ if (!referenceProduct) return state
765
+
766
+ const list = state.PRODUCT
767
+ const index = list.findIndex((item: any) => {return item.pId === pId})
768
+
769
+ // If no match, skip re-render
770
+ if (index === -1) return state
771
+
772
+ const target = list[index]
773
+
774
+ const newFreeState = !target.free
775
+
776
+ const updatedItem = {
777
+ ...target,
778
+ free: newFreeState,
779
+ ProPrice: newFreeState
780
+ ? 0
781
+ : (target.ProQuantity ?? 1) * (referenceProduct.ProPrice ?? 0)
787
782
  }
788
783
 
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
- }
784
+ // Clone array ONCE
785
+ const newList = [...list]
786
+ newList[index] = updatedItem
811
787
 
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
788
  return {
822
789
  ...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
- })
790
+ PRODUCT: newList
841
791
  }
842
792
  }
843
793
 
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
794
 
865
795
  // COMMENT_FREE_PRODUCT
866
- function commentProducts (state, action, deleteValue) {
796
+ /**
797
+ *
798
+ * @param state
799
+ * @param action
800
+ * @param deleteValue
801
+ */
802
+ function commentProducts(state: any, action: any, deleteValue = false) {
867
803
  if (values.comment) {
868
804
  sendNotification({
869
805
  backgroundColor: 'success',
@@ -874,18 +810,18 @@ export const useSales = ({
874
810
  setOpenCommentModal(!openCommentModal)
875
811
  return {
876
812
  ...state,
877
- PRODUCT: state?.PRODUCT?.map((items) => {
813
+ PRODUCT: state?.PRODUCT?.map((items: any) => {
878
814
  return items.pId === action.payload
879
815
  ? {
880
- ...items,
881
- comment: deleteValue ? '' : values.comment
882
- }
816
+ ...items,
817
+ comment: deleteValue ? '' : values.comment
818
+ }
883
819
  : items
884
820
  })
885
821
  }
886
822
  }
887
823
 
888
- const getSortedProduct = useCallback((data, sort) => {
824
+ const getSortedProduct = useCallback((data: any[], sort: string | null) => {
889
825
  if (sort && sort === 'PRICE_HIGH_TO_LOW') {
890
826
  return data.sort((a, b) => {
891
827
  return b.ProPrice - a.ProPrice
@@ -899,7 +835,7 @@ export const useSales = ({
899
835
  return data
900
836
  }, [])
901
837
 
902
- const PriceRangeFunc = (products, price) => {
838
+ const PriceRangeFunc = (products: any[], price: number) => {
903
839
  return (
904
840
  products?.length > 0 &&
905
841
  products?.filter((items) => {
@@ -914,7 +850,7 @@ export const useSales = ({
914
850
 
915
851
  const finalFilter = PriceRangeFunc(sortedProduct, data.priceRange)
916
852
 
917
- const handleList = (text) => {
853
+ const handleList = (text: string) => {
918
854
  const inputText = text.toLowerCase()
919
855
  let dataList = []
920
856
  dataList = finalFilter.filter((item) => {
@@ -922,7 +858,8 @@ export const useSales = ({
922
858
  })
923
859
  return dataList
924
860
  }
925
- const searchedInput = (words) => {
861
+
862
+ const searchedInput = (words: string) => {
926
863
  setInputValue(words)
927
864
  const n = words.split(' ')
928
865
  if (n.length !== 0) {
@@ -933,51 +870,42 @@ export const useSales = ({
933
870
  }
934
871
  return ''
935
872
  }
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)
873
+
874
+ const arrayProduct = useMemo(() => {
875
+ if (!Array.isArray(data.PRODUCT) || data.PRODUCT.length === 0) return []
876
+ return data.PRODUCT.map((product: any) => {
877
+ const filteredDataExtra = (product?.dataExtra ?? []).map(({ __typename, ...rest }) => {return rest})
878
+ const dataOptional = (product?.dataOptional ?? []).map(({ __typename, ...rest }) => {
879
+ const { ExtProductFoodsSubOptionalAll, ...r } = rest
880
+ const adjusted = (ExtProductFoodsSubOptionalAll ?? []).map(({ __typename, ...s }) => {return s})
881
+ return { ...r, ExtProductFoodsSubOptionalAll: adjusted }
882
+ })
957
883
  return {
958
- pId: product?.pId,
959
- refCodePid,
884
+ pId: product.pId,
885
+ refCodePid: RandomCode(20),
960
886
  id: values?.cliId,
961
- cantProducts: parseInt(
962
- product?.ProQuantity ? product?.ProQuantity : 0
963
- ),
887
+ cantProducts: parseInt(String(product?.ProQuantity ?? 0)),
964
888
  comments: product?.comment ?? '',
965
889
  dataOptional: dataOptional ?? [],
966
- dataExtra: filteredDataExtra || [],
890
+ dataExtra: filteredDataExtra,
967
891
  ProPrice: product.ProPrice
968
892
  }
969
893
  })
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
- })
894
+ }, [data.PRODUCT, values?.cliId])
895
+
896
+ const finalArrayProduct = useMemo(() => {
897
+ return arrayProduct.map((item: any) => {
898
+ const totalExtra = (item.dataExtra ?? []).reduce((acc: number, ex: any) => {return acc + (Number(ex.newExtraPrice) || 0)}, 0)
899
+ return { ...item, totalExtra }
900
+ })
901
+ }, [arrayProduct])
978
902
 
979
903
  let totalSale = 0
980
- function sumProPriceAndTotalExtra (data) {
904
+ /**
905
+ *
906
+ * @param data
907
+ */
908
+ function sumProPriceAndTotalExtra(data) {
981
909
  return data.map((item) => {
982
910
  const totalExtra = item.dataExtra.reduce((acc, curr) => {
983
911
  const newExtraPrice = parseFloat(curr.newExtraPrice)
@@ -1002,33 +930,9 @@ export const useSales = ({
1002
930
  }
1003
931
  }, [totalProductPrice, totalSale, data, finalArrayProduct])
1004
932
 
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
933
  const client = useApolloClient()
1030
934
  const { getOneSalesStore } = useGetSale()
1031
-
935
+ console.log(data)
1032
936
  const handleSubmit = () => {
1033
937
  // @ts-ignore
1034
938
  if (errors?.change || errors?.valueDelivery) {
@@ -1039,10 +943,39 @@ export const useSales = ({
1039
943
  })
1040
944
  }
1041
945
  setLoadingSale(true)
1042
- const code = RandomCode(10)
946
+ const {
947
+ code,
948
+ success,
949
+ error
950
+ } = generateTicket({
951
+ length: 8,
952
+ strategy: 'numeric',
953
+ prefix: 'T-',
954
+ timestamp: true
955
+ })
956
+ if (error) {
957
+ setLoadingSale(false)
958
+ return sendNotification({
959
+ title: 'error',
960
+ backgroundColor: 'error',
961
+ description: 'Lo sentimos, ocurrió un error'
962
+ })
963
+ }
964
+ if (!success) {
965
+ setLoadingSale(false)
966
+ return sendNotification({
967
+ title: 'error',
968
+ backgroundColor: 'error',
969
+ description: 'Lo sentimos, ocurrió un error'
970
+ })
971
+ }
1043
972
  // @ts-ignore
1044
973
  setCode(code)
1045
- function convertInteger (cadena) {
974
+ /**
975
+ *
976
+ * @param cadena
977
+ */
978
+ function convertInteger(cadena: string | number) {
1046
979
  if (typeof cadena === 'string') {
1047
980
  const numeroEntero = parseInt(cadena?.replace('.', ''))
1048
981
  return numeroEntero
@@ -1062,7 +995,7 @@ export const useSales = ({
1062
995
 
1063
996
  const shoppingCartRefCode = `REF-${RandomCode(36)}`
1064
997
 
1065
- const input = finalArrayProduct.map((item) => {
998
+ const input = finalArrayProduct.map((item: any) => {
1066
999
  return {
1067
1000
  ...item,
1068
1001
  shoppingCartRefCode
@@ -1076,16 +1009,19 @@ export const useSales = ({
1076
1009
  tableId,
1077
1010
  change: convertInteger(change),
1078
1011
  valueDelivery: convertInteger(valueDelivery),
1079
- payMethodPState: data.payMethodPState,
1012
+ payId: data.payId,
1080
1013
  pickUp: 1,
1081
1014
  shoppingCartRefCode,
1082
- discount: discount.discount ?? 0,
1015
+ discount: {
1016
+ type: String(data.discountType),
1017
+ value: 2
1018
+ },
1083
1019
  totalProductsPrice: convertInteger(totalProductsPrice) || 0
1084
1020
  },
1085
- update (cache) {
1021
+ update(cache) {
1086
1022
  cache.modify({
1087
1023
  fields: {
1088
- productFoodsAll (existingProductFoodsAll = []) {
1024
+ productFoodsAll(existingProductFoodsAll = []) {
1089
1025
  return existingProductFoodsAll
1090
1026
  }
1091
1027
  }
@@ -1107,17 +1043,17 @@ export const useSales = ({
1107
1043
  client.writeQuery({ query: GET_ALL_COUNT_SALES, data: { getTodaySales: data.countSales.todaySales } })
1108
1044
  }
1109
1045
  })
1110
- setValues({})
1111
- handleChange({ target: { name: 'tableId', value: '' } })
1046
+ setValues(initialValuesState)
1047
+ handleChange({ target: { name: 'tableId', value: '' } }, false)
1112
1048
  getOneSalesStore({
1113
1049
  variables: {
1114
1050
  pCodeRef: code || ''
1115
1051
  }
1116
- }).then((responseSale) => {
1052
+ }).then((responseSale: any) => {
1117
1053
  if (responseSale?.data?.getOneSalesStore) {
1118
1054
  const currentSale = responseSale?.data?.getOneSalesStore || {}
1119
1055
  const inComingCodeRef = currentSale?.pCodeRef || null
1120
- if (!inComingCodeRef) return
1056
+ if (!inComingCodeRef) return null
1121
1057
  // client.cache.modify({
1122
1058
  // fields: {
1123
1059
  // getAllOrdersFromStore (existingOrders = []) {
@@ -1162,11 +1098,11 @@ export const useSales = ({
1162
1098
  })
1163
1099
  }
1164
1100
 
1165
- const handleProduct = async (PRODUCT) => {
1101
+ const handleProduct = async (PRODUCT: any) => {
1166
1102
  setLoadingExtraProduct(true)
1167
1103
  const { pId } = PRODUCT || {}
1168
1104
  try {
1169
- const originalArray = data.PRODUCT.find((item) => {
1105
+ const originalArray = data.PRODUCT.find((item: any) => {
1170
1106
  return item.pId === pId
1171
1107
  })
1172
1108
  // OPTIONAL
@@ -1179,10 +1115,10 @@ export const useSales = ({
1179
1115
  const existOptionalCookies = originalArray?.dataOptional
1180
1116
  const filteredDataOptional = existOptionalCookies?.length
1181
1117
  ? existOptionalCookies
1182
- ?.map((obj) => {
1118
+ ?.map((obj: any) => {
1183
1119
  const filteredSubOptions =
1184
1120
  obj.ExtProductFoodsSubOptionalAll.filter(
1185
- (subObj) => subObj.check === true
1121
+ (subObj: any) => {return subObj.check === true}
1186
1122
  )
1187
1123
  // Excluya todo el objeto padre si filteredSubOptions está vacío
1188
1124
  if (filteredSubOptions.length === 0) {
@@ -1193,15 +1129,15 @@ export const useSales = ({
1193
1129
  ExtProductFoodsSubOptionalAll: filteredSubOptions
1194
1130
  }
1195
1131
  })
1196
- .filter((obj) => obj !== null)
1132
+ .filter((obj: any) => {return obj !== null})
1197
1133
  : []
1198
1134
 
1199
1135
  // Actualizar optionalAll.data.ExtProductFoodsSubOptionalAll con los valores actualizados de originalArray2.ExtProductFoodsSubOptionalAll
1200
1136
  if (optionalFetch && filteredDataOptional) {
1201
1137
  const updateOption = optionalFetch
1202
- .map((obj) => {
1138
+ .map((obj: any) => {
1203
1139
  const matchingArray = filteredDataOptional.find(
1204
- (o) => o && o.opExPid === obj.opExPid
1140
+ (o: any) => {return o && o.opExPid === obj.opExPid}
1205
1141
  )
1206
1142
  if (!matchingArray) {
1207
1143
  return obj
@@ -1209,11 +1145,11 @@ export const useSales = ({
1209
1145
  const extProductFoodsSubOptionalAll =
1210
1146
  obj.ExtProductFoodsSubOptionalAll || []
1211
1147
  const updateExtProductSubOptionalAll =
1212
- extProductFoodsSubOptionalAll.map((subObj) => {
1148
+ extProductFoodsSubOptionalAll.map((subObj: any) => {
1213
1149
  const newItem =
1214
1150
  matchingArray.ExtProductFoodsSubOptionalAll.find(
1215
- (newItem) =>
1216
- newItem && newItem.opSubExPid === subObj.opSubExPid
1151
+ (newItem: any) =>
1152
+ {return newItem && newItem.opSubExPid === subObj.opSubExPid}
1217
1153
  )
1218
1154
  if (newItem) {
1219
1155
  return {
@@ -1229,7 +1165,7 @@ export const useSales = ({
1229
1165
  updateExtProductSubOptionalAll
1230
1166
  }
1231
1167
  })
1232
- .filter((obj) => obj)
1168
+ .filter((obj: any) => {return obj})
1233
1169
  if (existOptionalCookies) {
1234
1170
  setDataOptional(updateOption || [])
1235
1171
  } else {
@@ -1242,17 +1178,17 @@ export const useSales = ({
1242
1178
  if (!originalArray?.dataExtra) {
1243
1179
  finalData = extProduct?.data?.ExtProductFoodsAll
1244
1180
  } else {
1245
- const filteredData = originalArray.dataExtra.filter((item) =>
1246
- extProduct?.data?.ExtProductFoodsAll.some(
1247
- (newItem) => newItem.exPid === item.exPid
1248
- )
1181
+ const filteredData = originalArray.dataExtra.filter((item: any) =>
1182
+ {return extProduct?.data?.ExtProductFoodsAll.some(
1183
+ (newItem: any) => {return newItem.exPid === item.exPid}
1184
+ )}
1249
1185
  )
1250
1186
  finalData = originalArray?.dataExtra?.concat(
1251
1187
  extProduct?.data?.ExtProductFoodsAll?.filter(
1252
- (item) =>
1253
- !filteredData?.some(
1254
- (filteredItem) => filteredItem.exPid === item.exPid
1255
- )
1188
+ (item: any) =>
1189
+ {return !filteredData?.some(
1190
+ (filteredItem: any) => {return filteredItem.exPid === item.exPid}
1191
+ )}
1256
1192
  )
1257
1193
  )
1258
1194
  }
@@ -1265,32 +1201,35 @@ export const useSales = ({
1265
1201
  setLoadingExtraProduct(false)
1266
1202
  } catch (error) {
1267
1203
  setLoadingExtraProduct(false)
1268
- sendNotification({
1269
- title: 'error',
1270
- backgroundColor: 'error',
1271
- description: error || 'Lo sentimos, ocurrió un error'
1272
- })
1204
+ if (error instanceof Error) {
1205
+ return sendNotification({
1206
+ title: 'error',
1207
+ backgroundColor: 'error',
1208
+ description: error.message ?? 'Lo sentimos, ocurrió un error'
1209
+ })
1210
+ }
1273
1211
  }
1274
1212
  }
1275
- const handleCleanFilter = () => {
1276
- // @ts-ignore
1277
- setValues({})
1213
+
1214
+ const handleCleanFilter = (): null => {
1215
+ setValues(initialValuesState)
1278
1216
  setValuesDates({ fromDate: yearMonthDay, toDate: '' })
1217
+ return null
1279
1218
  }
1280
1219
 
1281
1220
  const disabledModalItems = (dataOptional?.length > 0 || dataExtra?.length > 0) && !loadingExtProductFoodsSubOptionalAll
1282
1221
 
1283
1222
  /**
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) {
1223
+ * Filter objects with checked property equal to true.
1224
+ * @param {Array} products - Array of objects.
1225
+ * @returns {Array} - Array of objects with checked property equal to true.
1226
+ */
1227
+ function filterChecked(products: any[]) {
1289
1228
  if (!Array.isArray(products)) {
1290
1229
  return []
1291
1230
  }
1292
1231
 
1293
- return products.filter(product => product?.checked === true).map(product => product.carProId)
1232
+ return products.filter(product => {return product?.checked === true})?.map(product => {return product?.carProId})
1294
1233
  }
1295
1234
 
1296
1235
  // Obtener los carProIds de productos con checked en true
@@ -1300,15 +1239,113 @@ export const useSales = ({
1300
1239
  const filteredProducts = filterProductsByCarProId(productsFood, carProIds)
1301
1240
 
1302
1241
  const allProducts = useMemo(() => {
1303
- const productMap = new Map(data.PRODUCT.map(item => [String(item.pId), item.ProQuantity || 0]))
1242
+ const productMap = new Map(data?.PRODUCT?.map((item: any) => {return [String(item.pId), item.ProQuantity || 0]}))
1304
1243
 
1305
- return filteredProducts.map(product => ({
1244
+ return filteredProducts.map(product => {return {
1306
1245
  ...product,
1307
1246
  existsInSale: productMap.has(String(product.pId)),
1308
1247
  ProQuantity: productMap.get(String(product.pId)) || 0
1309
- }))
1248
+ }})
1310
1249
  }, [data.PRODUCT, filteredProducts])
1311
1250
 
1251
+ const totalProductsPrice = useMemo(() => { return finalArrayProduct.reduce((acc: number, item: any) => {return acc + (Number(item.ProPrice) || 0) + (Number(item.totalExtra) || 0)}, 0) }, [finalArrayProduct])
1252
+
1253
+ const handleAddAllProductsToCart = () => {
1254
+ for (const product of allProducts) {
1255
+ const existsInCart = data.PRODUCT.some((item: any) => {return item.pId === product.pId})
1256
+ if (!existsInCart) {
1257
+ dispatch({ type: SalesActionTypes.ADD_TO_CART, payload: product })
1258
+ } else {
1259
+ dispatch({ type: SalesActionTypes.INCREMENT, id: product.pId })
1260
+ }
1261
+ }
1262
+ }
1263
+
1264
+ /**
1265
+ * handleChangeNumber
1266
+ * Updates product quantity from input change with full validations.
1267
+ * @param {any} state - Current reducer state
1268
+ * @param {any} action - Action with payload { value, index, id }
1269
+ * @param {any[]} productsFood - Products memory source
1270
+ * @param {(n:{title:string,backgroundColor:string,description?:string})=>void} sendNotification
1271
+ * @param {(a:any)=>void} dispatch
1272
+ * @returns {any} Updated state
1273
+ */
1274
+ function handleChangeNumber(
1275
+ state: any,
1276
+ action: any,
1277
+ productsFood: any[] = [],
1278
+ sendNotification: Function
1279
+ ) {
1280
+ const event = action?.payload ?? {}
1281
+ const { value, index, id } = event
1282
+
1283
+ if (!id || index === undefined) return state
1284
+
1285
+ const productExist = productsFood.find((item: any) => {return item.pId === id})
1286
+ const oneProduct = state?.PRODUCT?.find((item: any) => {return item.pId === id})
1287
+
1288
+ // Product not found
1289
+ if (!productExist || !oneProduct) return state
1290
+
1291
+ // No stock
1292
+ if (productExist.stock === 0) {
1293
+ sendNotification({
1294
+ title: 'Sin stock',
1295
+ backgroundColor: 'warning',
1296
+ description: 'Producto sin stock disponible'
1297
+ })
1298
+ return state
1299
+ }
1300
+
1301
+ // Remove product if quantity <= 0
1302
+ if (value <= 0) {
1303
+ sendNotification({
1304
+ title: 'Producto eliminado',
1305
+ backgroundColor: 'info',
1306
+ description: `Has eliminado ${oneProduct.pName} del carrito.`
1307
+ })
1308
+ return {
1309
+ ...state,
1310
+ PRODUCT: state.PRODUCT.filter((t: any) => {return t.pId !== id}),
1311
+ counter: (state.counter ?? 0) - (oneProduct.ProQuantity || 0)
1312
+ }
1313
+ }
1314
+
1315
+ const safeValue = Number(value) || 0
1316
+ const maxStock = productExist.manageStock ? productExist.stock : safeValue
1317
+ const finalQuantity = Math.min(safeValue, maxStock)
1318
+
1319
+ // Stock exceeded
1320
+ if (safeValue > productExist.stock && productExist.manageStock) {
1321
+ sendNotification({
1322
+ title: 'Stock insuficiente',
1323
+ backgroundColor: 'warning',
1324
+ description: `No puedes agregar más unidades de ${oneProduct.pName}. Stock disponible: ${productExist.stock}`
1325
+ })
1326
+ }
1327
+
1328
+ const updatedProducts = state.PRODUCT.map((item: any, i: number) =>
1329
+ {return i === index
1330
+ ? {
1331
+ ...item,
1332
+ ProQuantity: finalQuantity,
1333
+ ProPrice: finalQuantity * (productExist.ProPrice ?? 0)
1334
+ }
1335
+ : item}
1336
+ )
1337
+
1338
+ return {
1339
+ ...state,
1340
+ PRODUCT: updatedProducts,
1341
+ counter: (state.counter ?? 0) + 1
1342
+ }
1343
+ }
1344
+
1345
+ useEffect(() => {
1346
+ Cookies.set(keyToSaveData, JSON.stringify(data), { domain, path: '/' })
1347
+ }, [data, domain])
1348
+
1312
1349
  return {
1313
1350
  loading: loading || loadingSale,
1314
1351
  loadingExtraProduct,
@@ -1329,7 +1366,6 @@ export const useSales = ({
1329
1366
  print,
1330
1367
  finalFilter,
1331
1368
  showMore,
1332
- max,
1333
1369
  search,
1334
1370
  values,
1335
1371
  initialStateSales,
@@ -1342,13 +1378,14 @@ export const useSales = ({
1342
1378
  dataExtra: dataExtra || [],
1343
1379
  fetchMore,
1344
1380
  pagination,
1345
- discount,
1381
+ discount: 0,
1346
1382
  datCat: categories,
1347
1383
  currentPage,
1348
1384
  loadingProduct: loading,
1349
1385
  handleChangeCheck,
1350
1386
  errors,
1351
1387
  handleUpdateAllExtra,
1388
+ handleAddAllProductsToCart,
1352
1389
  dispatch,
1353
1390
  handlePageChange,
1354
1391
  handleComment,
@@ -1359,8 +1396,8 @@ export const useSales = ({
1359
1396
  setOpenCurrentSale,
1360
1397
  setErrors,
1361
1398
  onChangeInput,
1399
+ handleAddProduct,
1362
1400
  handleRemoveValue,
1363
- applyDiscount,
1364
1401
  setDelivery,
1365
1402
  setValues,
1366
1403
  setShowMore,