From ca22cced44accc03b2f3e6f9fa98bcb4ee705325 Mon Sep 17 00:00:00 2001 From: workashrafi77-web Date: Sun, 18 Jan 2026 16:03:27 +0330 Subject: [PATCH] main --- .../advanced-table-page/AdvancedTablePage.js | 4 +- .../advanced-table/AdvancedTable.js | 4 +- .../InspectionDetailsModal.js | 30 +- .../responsive-table/ResponsiveTable.js | 4 +- .../hooks/useSelectedSubUser.js | 26 - .../services/getUserRoleInfo.js | 23 - .../AvicultureActiveRequests.js | 2 +- .../AvicultureFreeSaleNewRequest.js | 2 +- .../AvicultureNewRequest.js | 4 +- .../ProvinceFreeSaleNewRequest.js | 2 +- .../services/aviculture-get-hatching-data.js | 8 +- .../CityHatchingShowTableDetail.js | 14 +- .../CityHatchingUnassigned.js | 2 +- .../CityHatchingsArchive.js | 2 +- .../CityHatchingsTotal.js | 2 +- .../city-hatchings/CityHatchings.js | 2 +- .../CityIncreaseHatching.js | 3 +- .../CityNewKillRequest.js | 2 +- .../city-poultry-farms/CityPoultryFarms.js | 16 +- .../NationalInfoTransports.js | 2 +- .../NationalInfoHatchingDetails.js | 2 +- .../BarChartSection.js | 10 +- .../DailyKillingReport .js | 520 +- .../InventorySection.js | 103 +- .../PieChartSection.js | 9 +- .../PriceChartSection.js | 12 +- .../dashboard-slaughter/SlaughterDashboard.js | 7 +- .../components/dashboard-tab/DashboardTab.js | 10 +- .../WarehouseInfoSection.js | 167 +- .../YesterdayKillingReport.js | 349 +- .../components/dashboard/Dashboard.js | 182 +- .../check-request-item/CheckRequestItem.js | 41 +- .../SlaughterEnterBarItem.js | 16 +- .../SlaughterEnterBarWeight.js | 17 +- .../services/getAcceptedSlaughterRequest.js | 3 +- .../services/slaughterGetExlusiveKillers.js | 5 +- .../components/GuildReceiveBarOperation.js | 43 +- .../RegisterEditDeliveryNumberAndWeight.js | 12 +- .../components/StewardAllocationToGuild.js | 113 +- .../guild/components/StewardDailyList.js | 26 +- .../guild/components/StewardSegmant.js | 29 +- .../StewardSegmentSubmitOperation.js | 292 +- .../guild-psp-devices/AddAccessLevelModal.js | 141 - .../guild-psp-devices/AssignSubUserModal.js | 354 -- .../guild-psp-devices/DeviceOperations.js | 266 - .../guild-psp-devices/EditSubSectionsModal.js | 202 - .../guild-psp-devices/GuildPspDevices.js | 284 - .../services/guild-get-inventory-allocated.js | 2 +- .../services/guild-get-inventory-stock.js | 2 +- .../services/guild-sales-info-dashboard.js | 24 - .../services/senf-get-allocation-dashboard.js | 15 - .../services/senf-get-inventory-allocated.js | 10 +- .../services/senf-get-inventory-stock.js | 2 +- .../services/steward-get-out-dashboard.js | 2 - .../services/steward-get-sell-out-service.js | 9 +- .../services/steward-sell-out-get-buyers.js | 8 +- .../steward-sell-out-get-dashboard.js | 1 - ...rovinceJahadBranDistributionsAllocation.js | 2 +- .../ProvinceJahadBranDistributionsPolicy.js | 2 +- .../ProvinceJahadHerds.js | 2 +- .../ProvinceJahadRanchers.js | 2 +- .../ProvinceJahadTransactions.js | 2 +- .../components/create-guilds/CreateGuilds.js | 1897 ++++++- .../components/ConfirmationDialog.js | 45 - .../create-guilds/components/FormActions.js | 69 - .../components/GuildInfoAccordionItem.js | 97 - .../components/GuildInfoSection.js | 566 -- .../create-guilds/components/InfoBox.js | 23 - .../create-guilds/components/InquiryForm.js | 34 - .../components/PersonalInfoSection.js | 369 -- .../components/UpdateFromExternalButton.js | 19 - .../components/create-guilds/constants.js | 17 - .../create-guilds/utils/dataMapping.js | 232 - .../create-guilds/utils/dateUtils.js | 158 - .../create-guilds/utils/formUtils.js | 95 - .../create-guilds/utils/submitHandlers.js | 45 - .../guild-limitaion/GuildLimitaion.js | 26 +- .../guilds-operations/GuildsOperations.js | 12 +- .../ManageGuildDistributions.js | 2 +- .../components/manage-guilds/ManageGuilds.js | 45 +- .../manage-poultries/ManagePoultries.js | 2 +- .../poultries-details/PoultriesDetails.js | 2 +- .../ProvinceAllocateRequests.js | 6 +- .../ProvinceAllocatedRequests.js | 27 +- .../ProvinceAutoAllocationArchive.js | 93 +- .../ProvinceBarDifferenceRequests.js | 20 +- .../ProvinceBuyersAllocations.js | 2 +- .../ProvinceChickenDistributionsAndSales.js | 2 +- .../ProvinceChickenStewardSales.js | 2 +- ...inceDispenserAcceptedSaleWithInProvince.js | 6 +- ...inceDispenserRejectedSaleWithInProvince.js | 6 +- ...inceDispenserReturnedSaleWithInProvince.js | 6 +- .../ProvinceDispenserSegmentation.js | 2 +- .../ProvinceDispensersSellCarcassSellOut.js | 2 +- .../ProvinceFreeSalesTransactions.js | 2 +- .../ProvinceGetDeletedAllocatedRequests.js | 29 +- .../ProvinceManageCars.js | 33 +- .../ProvinceManageContradictions.js | 2 +- .../ProvinceNationalInfoSlaughterhouse.js | 2 +- .../ProvinceNationalInfoFarm.js | 2 +- .../ProvinceNeedRequests.js | 2 +- .../ProvincePaymentByWeightKillhouses.js | 2 +- .../ProvincePaymentByWeightOverview.js | 29 +- .../ProvincePolicyMobileMessage.js | 2 +- .../ProvinceRegisterCarForm.js | 4 +- .../ProvinceReturnPurchases.js | 27 +- .../ProvinceReturnedAllocated.js | 10 +- .../ProvinceReturnedCargo.js | 11 +- .../ProvinceSaleInDispenser.js | 6 +- .../ProvinceSegmentation.js | 2 +- .../ProvinceSettlementPdfKillRequest.js | 11 +- .../ProvinceSettlementSubmitDocument.js | 25 +- .../province-settlement/ProvinceSettlement.js | 75 +- .../ProvinceSubmitBarDifference.js | 50 +- .../ProvinceTradePanelMarketRequest.js | 60 +- .../ProvinceTradePanel.js | 563 +- .../province-trade-panel/TradePanelChart.js | 72 - .../TradePanelSearchBar.js | 45 - .../province-trade-panel/TradePanelTable.js | 117 - .../province-trade-panel/TradePanelTabs.js | 25 - .../TradeTimeRangeInfo.js | 20 - .../province-trade-panel/constants.js | 15 - .../province-trade-panel/useTradePanelData.js | 169 - .../useTradePanelFilters.js | 105 - .../TotalCargoInformation.js | 2 +- .../trade-panel-details/TradepanelDetails.js | 13 +- .../TradePanelPurchaseModal.js | 36 +- .../province/services/deactivate-guild.js | 20 - .../province/services/free-buying-payment.js | 11 +- .../services/get-approved-price-state.js | 8 +- .../get-dahsnoard-province-kill-request.js | 2 - .../province/services/getDocumentStates.js | 4 +- .../main-get-guilds-for-update-or-create.js | 41 - .../services/payment-get-deadlines.js | 6 +- .../services/province-cars-dashboard.js | 1 - ...nce-dashboard-bar-diffrence-get-request.js | 1 - .../province-get-allocated-requests.js | 1 - .../province/services/province-get-cars.js | 1 - ...province-get-deleted-allocated-requests.js | 1 - ...ince-get-direct-buying-poultry-requests.js | 1 + .../services/province-get-total-guilds.js | 8 +- .../province-policy-edit-trade-time-range.js | 7 +- ...olicy-get-slaughter-buying-price-status.js | 5 +- .../province-policy-get-weight-range.js | 4 +- .../services/province-policy-upload-image.js | 4 +- ...policy-validate-poultry-wth-sms-service.js | 4 +- ...nce-trade-panel-market-request-overview.js | 15 +- .../province/services/trade-panel-chat.js | 10 +- .../update-guild-by-national-id-new.js | 24 - .../components/psp-devices-v2/PspDevicesV2.js | 777 --- .../components/psp-devices/PspDevices.js | 87 +- .../psp-operations/PspOperations.js | 18 - .../senf/components/SenfEnterToWarehouse.js | 5 - .../senf/components/SenfInventoryOperation.js | 26 +- .../senf/components/SenfSegmentaion.js | 320 -- src/features/senf/components/SenfStock.js | 322 +- .../slaughter-house-vet-new-requests.js | 1 - .../EnterAggregateLoadInformation.js | 787 +-- .../EnterLoadInformation.js | 493 +- .../SlaughterAddDailyList.js | 15 +- ...SlaughterAllocatedCarToRequestOperation.js | 19 +- .../SlaughterAllocateCarToRequests.js | 33 +- .../SlaughterAllocateForFreezing.js | 75 +- .../SlaughterAllocateToColdHouse.js | 35 +- .../SlaughterAllocateToGuild.js | 298 +- .../SlaughterAllocatedCheckRequests.js | 16 +- .../SlaughterBalanceStatusButton.js | 5 +- .../slaughter-bars/SlaughterBars.js | 40 +- .../SlaughterColdHouseBars.js | 45 +- .../SlaughterDailyList.js | 28 +- .../SlaughterEnterNoneReciept.js | 561 +- .../slaughter-export/SlaughterExport.js | 41 +- .../SlaughterFreeBuyArchive.js | 55 +- .../SlaughterFreeBuyBars.js | 75 +- .../slaughter-free-buy/SlaughterFreeBuy.js | 93 +- .../DelegatesLimitationForm.js | 131 - .../DelegatesOperations.js | 139 - .../KillHouseDelegatesTab.js | 199 - .../SlaughterHouseDelegates.js | 27 - .../StewardDelegatesTab.js | 199 - .../SlaughterHouseDispensersOperations.js | 27 - .../AllDispensersEditForm.js | 264 - .../AllDispensersOperations.js | 79 - .../AllDispensersTab.js | 162 - .../DispenserInfoLimitationForm.js | 135 - .../DispenserInfoOperations.js | 140 - .../KillHouseDispensersTab.js | 199 - .../SlaughterHouseDispensers.js | 30 - .../StewardDispensersTab.js | 199 - .../SlaughterInventoryFreeBuyBarsAlives.js | 36 +- .../SlaughterInventoryFreeBuyBars.js | 45 +- .../SlaughterInventoryInProvinceBars.js | 21 +- .../SlaughterInventorySummary.js | 18 +- .../slaughter-inventory/SlaughterInventory.js | 16 +- .../SlaughterManageBars.js | 846 ++- .../SlaughterManageDelegates.js | 249 - .../SlaughterManageDelegatesForm.js | 165 - .../SlaughterManageDelegatesLimitationForm.js | 133 - .../SlaughterManageDelegatesOperations.js | 114 - .../SlaughterManageDispensers.js | 118 +- .../SlaughterManageDispensersForm.js | 18 +- ...SlaughterManageDispensersLimitationForm.js | 133 - .../SlaughterManageDispensersOperations.js | 82 - .../SlaughterMorgueView.js | 20 +- .../SlaughterNewRequestForm.js | 857 +-- .../slaughter-orders/SlaughterOrders.js | 35 +- .../SlaughterPspDevices.js | 5 - .../slaughter-requests/SlaughterRequests.js | 21 +- .../SlaughterSegmentation.js | 31 +- .../ProvinceSellCarcassInProvince.js | 57 +- .../SlaughterSellCarcassOutProvinceBuyers.js | 20 +- .../SlaughterSellCarcassOutProvinceSell.js | 32 +- ...terSellCarcassOutProvinceSellSubmitSell.js | 41 +- .../SlaughterSellCarcassOutProvince.js | 25 +- .../SlaughterSellCarcass.js | 19 +- .../SlaughterShowProducts.js | 12 +- .../slaughter-stock/SlaughterStock.js | 9 +- .../SlaughterSubmitChickenPrice.js | 10 +- .../SlaughterSubmitExport.js | 55 +- .../SlaughterSubmitFreeBar.js | 49 +- .../SlaughterSubmitFreeBuy.js | 103 +- .../handle-fetch-slaughter-products.js | 40 +- .../services/payment-get-deadlines.js | 6 +- .../services/salughter-delete-allocated.js | 1 - .../services/salughter-get-requests.js | 1 - .../services/slaughetr-morgue-services.js | 1 - .../services/slaughter-bar-dashbored.js | 1 - .../services/slaughter-edit-dispenser-info.js | 24 - ...er-enter-load-information-get-dashboard.js | 1 - .../services/slaughter-get-active-requests.js | 19 +- .../services/slaughter-get-allocated-cars.js | 1 - .../services/slaughter-get-countries.js | 6 +- .../services/slaughter-get-delegates-info.js | 33 - .../slaughter-get-delegates-service.js | 47 - .../services/slaughter-get-dispenser-info.js | 5 +- .../slaughter-get-dispenser-service.js | 32 - .../slaughter-get-dispenser-user-info.js | 11 +- .../slaughter-get-distribution-info.js | 6 +- .../slaughter-get-export-allow-state.js | 1 - .../slaughter-get-free-buy-requests.js | 32 - .../slaughter-get-guilds-for-allocate.js | 15 - .../slaughter-get-killers-killhouses.js | 8 +- .../slaughter-get-killhouse-remain-weight.js | 4 +- .../services/slaughter-get-killhouses.js | 4 +- .../slaughter-get-premisson-to-vet.js | 6 +- .../services/slaughter-get-profile.js | 6 +- ...laughter-house-submit-dispenser-service.js | 10 +- .../services/slaughter-inventory-gets.js | 9 +- .../slaughter-sell-carcass-out-province.js | 1 - .../services/slaughter-submit-delegate.js | 44 - .../StewardSellOutOfProvinceAddBuyer.js | 46 +- .../StewardSellOutOfProvinceSubmitSell.js | 62 +- .../StewardPurchaseOutProvince.js | 57 +- .../StewardSellInProvince.js | 33 +- .../StewardSellOutOfProvinceBuyers.js | 22 +- .../StewardSellOutOfProvinceSells.js | 93 +- .../StewardSellOutOfProvince.js | 15 +- .../StewardShowAllocationsOperations.js | 32 +- .../StewardShowAllocations.js | 32 +- .../StewardShowProducts.js | 12 +- .../components/steward-stock/StewardStock.js | 13 +- .../StewardSubmitFreeBar.js | 54 +- .../services/handle-fetch-steward-products.js | 10 +- .../steward/services/steward-get-bars-info.js | 1 - .../SuperAdminSubmitBarStatus.js | 19 +- .../SupporterSettlemetModal.js | 8 +- .../ParentCompanyOutOfProvince.js | 2 +- .../ParentCompanyVetFarmOperation.js | 2 +- .../vet-farm-cancel-bar/VetFarmCancelBar.js | 26 +- .../VetFarmDeletedBars.js | 36 +- .../vet-farm-operation/VetFarmOperation.js | 2 +- .../VetFarmOperationOptions.js | 15 +- .../VetFarmOutOfProvince.js | 2 +- .../services/vet-farm-get-allocated.js | 1 - .../services/vet-farm-get-bars-overview.js | 1 - .../services/vet-farm-get-deleted-bars.js | 1 - .../VisorStaticsPrediction.js | 3 +- .../header-operations/HeaderOperations.js | 14 +- src/layouts/sidebar/SidebarMenuItem.js | 2 +- .../components/CollapsibleMenuSection.js | 70 - .../sidebar/components/LogoutButton.js | 78 - src/layouts/sidebar/components/MenuItem.js | 67 - .../sidebar/components/RoleAccordion.js | 103 - .../sidebar/components/RoleMenuRenderer.js | 64 - .../sidebar/components/SidebarHeader.js | 137 - .../sidebar/constants/menuItemHelpers.js | 140 - .../sidebar/constants/roleMenuConfigs.js | 620 --- .../sidebar/hooks/useResponsiveSidebar.js | 22 - src/layouts/sidebar/hooks/useSidebarState.js | 86 - src/layouts/sidebar/sidebar.js | 4872 ++++++++++++++++- src/layouts/site-map/SiteMap.js | 317 +- src/lib/redux/slices/generalExtraReducers.js | 8 - src/lib/redux/slices/userExtraReducers.js | 21 - src/lib/redux/slices/userReducers.js | 9 - src/lib/redux/slices/userSlice.js | 6 - src/pages/AcessDashboardV2.js | 1434 ----- src/pages/DashboardPage.js | 28 +- src/pages/DiffrenceKillerPage.js | 22 +- src/pages/GeneralDashboard.js | 6 +- src/pages/ProvinceManageStewards.js | 92 - src/pages/ProvinceRequests.js | 10 +- src/pages/PspCompany.js | 12 +- src/pages/SenfInventoryPage.js | 70 +- src/pages/SlaughterHouseDispenserDashboard.js | 12 - src/pages/SlaughterInventoryPage.js | 32 +- src/pages/SlaughterMorgue.js | 21 +- src/pages/SlaughterSubUnits.js | 66 - src/pages/StewardInventoryPage.js | 47 +- src/routes/managerRouting.js | 30 +- src/routes/posCompanyRouting.js | 17 +- src/routes/routes.js | 45 +- src/routes/senfRouting.js | 27 +- src/routes/slaughterRouting.js | 39 - src/routes/stewardRouting.js | 39 - src/utils/checkPathStartsWith.js | 7 - src/utils/getFaUserRole.js | 2 - src/utils/getRoleFromUrl.js | 2 - src/utils/getRolesItems.js | 97 +- src/utils/getSelectedSubUserKey.js | 11 - src/version.txt | 2 +- vite.config.js | 2 +- 321 files changed, 10738 insertions(+), 17770 deletions(-) delete mode 100644 src/features/authentication/hooks/useSelectedSubUser.js delete mode 100644 src/features/authentication/services/getUserRoleInfo.js delete mode 100644 src/features/guild/components/guild-psp-devices/AddAccessLevelModal.js delete mode 100644 src/features/guild/components/guild-psp-devices/AssignSubUserModal.js delete mode 100644 src/features/guild/components/guild-psp-devices/DeviceOperations.js delete mode 100644 src/features/guild/components/guild-psp-devices/EditSubSectionsModal.js delete mode 100644 src/features/guild/components/guild-psp-devices/GuildPspDevices.js delete mode 100644 src/features/guild/services/guild-sales-info-dashboard.js delete mode 100644 src/features/guild/services/senf-get-allocation-dashboard.js delete mode 100644 src/features/province/components/create-guilds/components/ConfirmationDialog.js delete mode 100644 src/features/province/components/create-guilds/components/FormActions.js delete mode 100644 src/features/province/components/create-guilds/components/GuildInfoAccordionItem.js delete mode 100644 src/features/province/components/create-guilds/components/GuildInfoSection.js delete mode 100644 src/features/province/components/create-guilds/components/InfoBox.js delete mode 100644 src/features/province/components/create-guilds/components/InquiryForm.js delete mode 100644 src/features/province/components/create-guilds/components/PersonalInfoSection.js delete mode 100644 src/features/province/components/create-guilds/components/UpdateFromExternalButton.js delete mode 100644 src/features/province/components/create-guilds/constants.js delete mode 100644 src/features/province/components/create-guilds/utils/dataMapping.js delete mode 100644 src/features/province/components/create-guilds/utils/dateUtils.js delete mode 100644 src/features/province/components/create-guilds/utils/formUtils.js delete mode 100644 src/features/province/components/create-guilds/utils/submitHandlers.js delete mode 100644 src/features/province/components/province-trade-panel/TradePanelChart.js delete mode 100644 src/features/province/components/province-trade-panel/TradePanelSearchBar.js delete mode 100644 src/features/province/components/province-trade-panel/TradePanelTable.js delete mode 100644 src/features/province/components/province-trade-panel/TradePanelTabs.js delete mode 100644 src/features/province/components/province-trade-panel/TradeTimeRangeInfo.js delete mode 100644 src/features/province/components/province-trade-panel/constants.js delete mode 100644 src/features/province/components/province-trade-panel/useTradePanelData.js delete mode 100644 src/features/province/components/province-trade-panel/useTradePanelFilters.js delete mode 100644 src/features/province/services/deactivate-guild.js delete mode 100644 src/features/province/services/main-get-guilds-for-update-or-create.js delete mode 100644 src/features/province/services/update-guild-by-national-id-new.js delete mode 100644 src/features/psp-company/components/psp-devices-v2/PspDevicesV2.js delete mode 100644 src/features/senf/components/SenfEnterToWarehouse.js delete mode 100644 src/features/senf/components/SenfSegmentaion.js delete mode 100644 src/features/slaughter-house/components/slaughter-house-delegates/DelegatesLimitationForm.js delete mode 100644 src/features/slaughter-house/components/slaughter-house-delegates/DelegatesOperations.js delete mode 100644 src/features/slaughter-house/components/slaughter-house-delegates/KillHouseDelegatesTab.js delete mode 100644 src/features/slaughter-house/components/slaughter-house-delegates/SlaughterHouseDelegates.js delete mode 100644 src/features/slaughter-house/components/slaughter-house-delegates/StewardDelegatesTab.js delete mode 100644 src/features/slaughter-house/components/slaughter-house-dispensers-v2/AllDispensersEditForm.js delete mode 100644 src/features/slaughter-house/components/slaughter-house-dispensers-v2/AllDispensersOperations.js delete mode 100644 src/features/slaughter-house/components/slaughter-house-dispensers-v2/AllDispensersTab.js delete mode 100644 src/features/slaughter-house/components/slaughter-house-dispensers-v2/DispenserInfoLimitationForm.js delete mode 100644 src/features/slaughter-house/components/slaughter-house-dispensers-v2/DispenserInfoOperations.js delete mode 100644 src/features/slaughter-house/components/slaughter-house-dispensers-v2/KillHouseDispensersTab.js delete mode 100644 src/features/slaughter-house/components/slaughter-house-dispensers-v2/SlaughterHouseDispensers.js delete mode 100644 src/features/slaughter-house/components/slaughter-house-dispensers-v2/StewardDispensersTab.js delete mode 100644 src/features/slaughter-house/components/slaughter-manage-delegates/SlaughterManageDelegates.js delete mode 100644 src/features/slaughter-house/components/slaughter-manage-delegates/SlaughterManageDelegatesForm.js delete mode 100644 src/features/slaughter-house/components/slaughter-manage-delegates/SlaughterManageDelegatesLimitationForm.js delete mode 100644 src/features/slaughter-house/components/slaughter-manage-delegates/SlaughterManageDelegatesOperations.js delete mode 100644 src/features/slaughter-house/components/slaughter-manage-dispensers/SlaughterManageDispensersLimitationForm.js delete mode 100644 src/features/slaughter-house/components/slaughter-manage-dispensers/SlaughterManageDispensersOperations.js delete mode 100644 src/features/slaughter-house/components/slaughter-psp-devices/SlaughterPspDevices.js delete mode 100644 src/features/slaughter-house/services/slaughter-edit-dispenser-info.js delete mode 100644 src/features/slaughter-house/services/slaughter-get-delegates-info.js delete mode 100644 src/features/slaughter-house/services/slaughter-get-delegates-service.js delete mode 100644 src/features/slaughter-house/services/slaughter-get-dispenser-service.js delete mode 100644 src/features/slaughter-house/services/slaughter-get-free-buy-requests.js delete mode 100644 src/features/slaughter-house/services/slaughter-submit-delegate.js delete mode 100644 src/layouts/sidebar/components/CollapsibleMenuSection.js delete mode 100644 src/layouts/sidebar/components/LogoutButton.js delete mode 100644 src/layouts/sidebar/components/MenuItem.js delete mode 100644 src/layouts/sidebar/components/RoleAccordion.js delete mode 100644 src/layouts/sidebar/components/RoleMenuRenderer.js delete mode 100644 src/layouts/sidebar/components/SidebarHeader.js delete mode 100644 src/layouts/sidebar/constants/menuItemHelpers.js delete mode 100644 src/layouts/sidebar/constants/roleMenuConfigs.js delete mode 100644 src/layouts/sidebar/hooks/useResponsiveSidebar.js delete mode 100644 src/layouts/sidebar/hooks/useSidebarState.js delete mode 100644 src/pages/AcessDashboardV2.js delete mode 100644 src/pages/ProvinceManageStewards.js delete mode 100644 src/pages/SlaughterSubUnits.js delete mode 100644 src/utils/checkPathStartsWith.js delete mode 100644 src/utils/getSelectedSubUserKey.js diff --git a/src/components/advanced-table-page/AdvancedTablePage.js b/src/components/advanced-table-page/AdvancedTablePage.js index 099553a..008eb98 100644 --- a/src/components/advanced-table-page/AdvancedTablePage.js +++ b/src/components/advanced-table-page/AdvancedTablePage.js @@ -38,7 +38,7 @@ function AdvancedTablePage({ columns, list, api }) { setPage(0); }; - const codeList = eval(list); + let codeList = eval(list); function replacePlaceholders(inputHTML, item) { const replacedHTML = inputHTML.replace( @@ -60,7 +60,7 @@ function AdvancedTablePage({ columns, list, api }) { useEffect(() => { const d = tableData?.map((item) => { - const result = codeList.map((option) => { + const result = codeList.map((option, i) => { const properties = option.split("."); let value = item; for (const property of properties) { diff --git a/src/components/advanced-table/AdvancedTable.js b/src/components/advanced-table/AdvancedTable.js index b25244e..75ae95d 100644 --- a/src/components/advanced-table/AdvancedTable.js +++ b/src/components/advanced-table/AdvancedTable.js @@ -19,8 +19,8 @@ export const AdvancedTable = ({ columns, data, name, pagination }) => { }, [data]); useEffect(() => { - const d = data?.map((item) => { - return item?.map((row) => { + const d = data?.map((item, i) => { + return item?.map((row, index) => { if (!row && row !== 0) { return ""; } else { diff --git a/src/components/inspection-details-modal/InspectionDetailsModal.js b/src/components/inspection-details-modal/InspectionDetailsModal.js index bf854e9..c391f87 100644 --- a/src/components/inspection-details-modal/InspectionDetailsModal.js +++ b/src/components/inspection-details-modal/InspectionDetailsModal.js @@ -4,8 +4,6 @@ import { Grid } from "../grid/Grid"; import { SPACING } from "../../data/spacing"; import { LabelField } from "../label-field/LabelField"; import CloseIcon from "@mui/icons-material/Close"; -import PictureAsPdfIcon from "@mui/icons-material/PictureAsPdf"; -import axios from "axios"; export const InspectionDetailsModal = ({ item }) => { const [statusTab, setStatusTab] = useState(0); @@ -23,12 +21,6 @@ export const InspectionDetailsModal = ({ item }) => { setFullscreenMedia(null); }; - const handleDownloadPdf = () => { - const baseUrl = axios.defaults.baseURL || ""; - const url = `${baseUrl}poultry_science_report_pdf/?key=${item?.key}`; - window.open(url, "_blank"); - }; - const formatDate = (dateString) => { if (!dateString) return "---"; try { @@ -433,25 +425,9 @@ export const InspectionDetailsModal = ({ item }) => { p: 2, }} > - - - اطلاعات - - - - - + + اطلاعات + {renderInformationTab()} diff --git a/src/components/responsive-table/ResponsiveTable.js b/src/components/responsive-table/ResponsiveTable.js index 98fef92..2b54081 100644 --- a/src/components/responsive-table/ResponsiveTable.js +++ b/src/components/responsive-table/ResponsiveTable.js @@ -224,7 +224,7 @@ const ResponsiveTable = ({ justifyContent="space-between" xs={12} style={{ - width: "100%", + width: "85vw", }} > @@ -442,7 +442,7 @@ const ResponsiveTable = ({ id="startoftable" display={{ xs: "none", sm: "grid" }} style={{ - width: customWidth ? customWidth : "100%", + width: customWidth ? customWidth : "85vw", }} > { - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); - return selectedSubUser; -}; - -/** - * Hook to get only the selected sub user key - * @returns {string|null} - The sub user key or null - */ -export const useSelectedSubUserKey = () => { - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); - return selectedSubUser?.key || null; -}; - -export default useSelectedSubUser; - diff --git a/src/features/authentication/services/getUserRoleInfo.js b/src/features/authentication/services/getUserRoleInfo.js deleted file mode 100644 index cb0fc59..0000000 --- a/src/features/authentication/services/getUserRoleInfo.js +++ /dev/null @@ -1,23 +0,0 @@ -import { createAsyncThunk } from "@reduxjs/toolkit"; -import axios from "axios"; -import { LOADING_END, LOADING_START } from "../../../lib/redux/slices/appSlice"; - -export const getUserRoleInfo = createAsyncThunk( - "GET_USER_ROLE_INFO", - async ({ userKey, role }, { dispatch }) => { - try { - dispatch(LOADING_START()); - const { data, status } = await axios.get("user-role-info/", { - params: { - user_key: userKey, - role: role, - }, - }); - dispatch(LOADING_END()); - return { data, status }; - } catch (error) { - dispatch(LOADING_END()); - throw error; - } - } -); diff --git a/src/features/aviculture/components/aviculture-active-requests/AvicultureActiveRequests.js b/src/features/aviculture/components/aviculture-active-requests/AvicultureActiveRequests.js index 89bd86e..43aadfa 100644 --- a/src/features/aviculture/components/aviculture-active-requests/AvicultureActiveRequests.js +++ b/src/features/aviculture/components/aviculture-active-requests/AvicultureActiveRequests.js @@ -39,7 +39,7 @@ export const AvicultureActiveRequests = () => { const filteredData = Array.isArray(avicultureRequests) && avicultureRequests?.filter( - (item) => + (item, i) => (item.stateProcess === "accepted" || item.stateProcess === "pending") && item.finalState !== "archive" diff --git a/src/features/aviculture/components/aviculture-free-sale-new-request/AvicultureFreeSaleNewRequest.js b/src/features/aviculture/components/aviculture-free-sale-new-request/AvicultureFreeSaleNewRequest.js index 2b6041c..b8af05a 100644 --- a/src/features/aviculture/components/aviculture-free-sale-new-request/AvicultureFreeSaleNewRequest.js +++ b/src/features/aviculture/components/aviculture-free-sale-new-request/AvicultureFreeSaleNewRequest.js @@ -365,7 +365,7 @@ export const AvicultureFreeSaleNewRequest = () => { useEffect(() => { if (poultryKey) { dispatch(LOADING_START()); - dispatch(avicultureGetHatchingData({ key: poultryKey })).then((r) => { + dispatch(avicultureGetHatchingData(poultryKey)).then((r) => { if (r.payload.data) { setHatchingData(r.payload.data); diff --git a/src/features/aviculture/components/aviculture-new-request/AvicultureNewRequest.js b/src/features/aviculture/components/aviculture-new-request/AvicultureNewRequest.js index 4292cb2..a070268 100644 --- a/src/features/aviculture/components/aviculture-new-request/AvicultureNewRequest.js +++ b/src/features/aviculture/components/aviculture-new-request/AvicultureNewRequest.js @@ -170,7 +170,7 @@ export const AvicultureNewRequest = () => { } }; - const removeInput = () => { + const removeInput = (e) => { const number = arr.length - 1; if (number !== 0) { @@ -381,7 +381,7 @@ export const AvicultureNewRequest = () => { useEffect(() => { if (poultryKey) { dispatch(LOADING_START()); - dispatch(avicultureGetHatchingData({ key: poultryKey })).then((r) => { + dispatch(avicultureGetHatchingData(poultryKey)).then((r) => { if (r.payload.data) { setHatchingData(r.payload.data); diff --git a/src/features/aviculture/components/province-free-sale-new-request/ProvinceFreeSaleNewRequest.js b/src/features/aviculture/components/province-free-sale-new-request/ProvinceFreeSaleNewRequest.js index 3bb18bc..a3dcc1f 100644 --- a/src/features/aviculture/components/province-free-sale-new-request/ProvinceFreeSaleNewRequest.js +++ b/src/features/aviculture/components/province-free-sale-new-request/ProvinceFreeSaleNewRequest.js @@ -487,7 +487,7 @@ export const ProvinceFreeSaleNewRequest = ({ fetchApiData }) => { useEffect(() => { if (poultryKey) { dispatch(LOADING_START()); - dispatch(avicultureGetHatchingData({ key: poultryKey })).then((r) => { + dispatch(avicultureGetHatchingData(poultryKey)).then((r) => { if (r.payload.data) { setHatchingData(r.payload.data); diff --git a/src/features/aviculture/services/aviculture-get-hatching-data.js b/src/features/aviculture/services/aviculture-get-hatching-data.js index 5e37ed0..fc8b386 100644 --- a/src/features/aviculture/services/aviculture-get-hatching-data.js +++ b/src/features/aviculture/services/aviculture-get-hatching-data.js @@ -3,12 +3,8 @@ import axios from "axios"; export const avicultureGetHatchingData = createAsyncThunk( "VET_GET_HATCHING", - async (d) => { - const { data, status } = await axios.get("poultry_hatching/", { - params: { - key: d.key || "", - }, - }); + async (key) => { + const { data, status } = await axios.get("poultry_hatching/?key=" + key); return { data, status }; } ); diff --git a/src/features/city/components/city-hatching-show-table-detail/CityHatchingShowTableDetail.js b/src/features/city/components/city-hatching-show-table-detail/CityHatchingShowTableDetail.js index c4a0cd4..7c0f86e 100644 --- a/src/features/city/components/city-hatching-show-table-detail/CityHatchingShowTableDetail.js +++ b/src/features/city/components/city-hatching-show-table-detail/CityHatchingShowTableDetail.js @@ -864,7 +864,7 @@ export const CityHatchingShowTableDetail = ({ keyItem }) => { - + }> اطلاعات بارهای قرنطینه @@ -895,7 +895,7 @@ export const CityHatchingShowTableDetail = ({ keyItem }) => { - + }> اطلاعات بارهای بازگشتی @@ -942,7 +942,7 @@ export const CityHatchingShowTableDetail = ({ keyItem }) => { - + }> اطلاعات تخصیصات بازگشتی @@ -982,7 +982,7 @@ export const CityHatchingShowTableDetail = ({ keyItem }) => { - + }> اطلاعات بارهای خارج استان @@ -1016,7 +1016,7 @@ export const CityHatchingShowTableDetail = ({ keyItem }) => { - + }> مدیریت بار زنجیره @@ -1052,7 +1052,7 @@ export const CityHatchingShowTableDetail = ({ keyItem }) => { - + }> اختلاف کشتار @@ -1086,7 +1086,7 @@ export const CityHatchingShowTableDetail = ({ keyItem }) => { - + }> گزارش تلفات diff --git a/src/features/city/components/city-hatching-unassigned/CityHatchingUnassigned.js b/src/features/city/components/city-hatching-unassigned/CityHatchingUnassigned.js index 2cd4601..b9ef3b7 100644 --- a/src/features/city/components/city-hatching-unassigned/CityHatchingUnassigned.js +++ b/src/features/city/components/city-hatching-unassigned/CityHatchingUnassigned.js @@ -556,7 +556,7 @@ export const CityHatchingUnassigned = ({ readOnly }) => { return ( - + { return ( - + { return ( - + { return ( - + { const [tableData, setTableData] = useState([]); const fetchApiData = async (page) => { + let response; dispatch(LOADING_START()); - const response = await axios.get( + response = await axios.get( `hatching-increase-request/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}` ); dispatch(LOADING_END()); diff --git a/src/features/city/components/city-new-kill-request/CityNewKillRequest.js b/src/features/city/components/city-new-kill-request/CityNewKillRequest.js index 941c366..bf00bb5 100644 --- a/src/features/city/components/city-new-kill-request/CityNewKillRequest.js +++ b/src/features/city/components/city-new-kill-request/CityNewKillRequest.js @@ -668,7 +668,7 @@ export const CityNewKillRequest = ({ ); } }); - dispatch(avicultureGetHatchingData({ key: poultryKey })).then((r) => { + dispatch(avicultureGetHatchingData(poultryKey)).then((r) => { if (r.payload.data) { setHatchingData(r.payload.data); } else { diff --git a/src/features/city/components/city-poultry-farms/CityPoultryFarms.js b/src/features/city/components/city-poultry-farms/CityPoultryFarms.js index 024a7d1..077c317 100644 --- a/src/features/city/components/city-poultry-farms/CityPoultryFarms.js +++ b/src/features/city/components/city-poultry-farms/CityPoultryFarms.js @@ -1,4 +1,5 @@ import { + Card, Grid, IconButton, List, @@ -7,7 +8,7 @@ import { ListItemText, Popover, } from "@mui/material"; -import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable"; +import { AdvancedTable } from "../../../../components/advanced-table/AdvancedTable"; import { SPACING } from "../../../../data/spacing"; import { useDispatch, useSelector } from "react-redux"; @@ -186,12 +187,13 @@ export const CityPoultryFarms = () => { gap={SPACING.SMALL} mt={SPACING.MEDIUM} > - + + + ); }; diff --git a/src/features/city/components/national-info-bars/NationalInfoTransports.js b/src/features/city/components/national-info-bars/NationalInfoTransports.js index 9ef1283..5158307 100644 --- a/src/features/city/components/national-info-bars/NationalInfoTransports.js +++ b/src/features/city/components/national-info-bars/NationalInfoTransports.js @@ -326,7 +326,7 @@ export const NationalInfoTransports = () => { - + { - + { return ( { flexDirection: "column", boxSizing: "border-box", overflow: "hidden", - maxHeight: "fit-content", }} > گزارش انبار کشتارگاه diff --git a/src/features/dashboard/components/dashboard-daily-killing-report/DailyKillingReport .js b/src/features/dashboard/components/dashboard-daily-killing-report/DailyKillingReport .js index baa9ff3..15c66a6 100644 --- a/src/features/dashboard/components/dashboard-daily-killing-report/DailyKillingReport .js +++ b/src/features/dashboard/components/dashboard-daily-killing-report/DailyKillingReport .js @@ -1,74 +1,17 @@ import { Box, Typography } from "@mui/material"; import { SPACING } from "../../../../data/spacing"; -const reportItems = [ - { label: "حجم درخواست کشتار مرغدار:", key: "quantity" }, - { label: "وزن درخواست کشتار مرغدار:", key: "totalWeight" }, - { label: "حجم خرید های مستقیم :", key: "killRequestQuantity" }, - { label: "وزن خرید های مستقیم :", key: "killRequestWeight" }, - { - label: "حجم خرید های خارج از استان (زنده) :", - key: "quantityKillHouseFreeBarLive", - }, - { - label: "وزن خرید های خارج از استان (زنده) :", - key: "WeightKillHouseFreeBarLive", - }, - { - label: "وزن خرید های خارج از استان (لاشه) :", - key: "WeightKillHouseFreeBarCarcass", - }, - { - label: "حجم کل تخصیصات (خرید مستقیم/ مرغدار ):", - key: "provinceKillRequestQuantity", - }, - { - label: "وزن کل تخصیصات (خرید مستقیم/ مرغدار ):", - key: "provinceKillRequestWeightCarcass", - }, - { label: "حجم فروش به خارج استان:", key: "poultryOutProvinceQuantity" }, - { label: "وزن فروش به خارج استان:", key: "poultryOutProvinceWeight" }, - { label: "حجم بارها:", key: "KillHouseRequestQuantity" }, - { label: "وزن بارها:", key: "KillHouseRequestWeight" }, - { - label: "لاشه تولیدی امروز با احتساب 25درصد افت کشتار :", - key: "totalLossWeight", - }, -]; - -const ReportRow = ({ label, value }) => ( - - - {label} - - - {value?.toLocaleString() || 0} - - -); - export const DailykillingReport = ({ boxStats }) => ( ( display: "flex", flexDirection: "column", gap: 2, + height: "600px", }} > گزارش کشتار امروز مرغ گوشتی استان + ( gap: 1, overflowY: "auto", flex: 1, - maxHeight: "500px", }} > - {reportItems.map((item) => ( - - ))} + + + حجم درخواست کشتار مرغدار: + + + {boxStats?.killing?.quantity?.toLocaleString() || 0} + + + + + وزن درخواست کشتار مرغدار: + + + {boxStats?.killing?.totalWeight?.toLocaleString() || 0} + + + + + + حجم خرید های مستقیم : + + + {boxStats?.killing?.killRequestQuantity?.toLocaleString() || 0} + + + + + وزن خرید های مستقیم : + + + {boxStats?.killing?.killRequestWeight?.toLocaleString() || 0} + + + + + + حجم خرید های خارج از استان (زنده) : + + + {boxStats?.killing?.quantityKillHouseFreeBarLive?.toLocaleString() || + 0} + + + + + + وزن خرید های خارج از استان (زنده) : + + + {boxStats?.killing?.WeightKillHouseFreeBarLive?.toLocaleString() || 0} + + + + + + وزن خرید های خارج از استان (لاشه) : + + + {boxStats?.killing?.WeightKillHouseFreeBarCarcass?.toLocaleString() || + 0} + + + + + + حجم کل تخصیصات (خرید مستقیم/ مرغدار ): + + + {boxStats?.killing?.provinceKillRequestQuantity?.toLocaleString() || + 0} + + + + + وزن کل تخصیصات (خرید مستقیم/ مرغدار ): + + + {boxStats?.killing?.provinceKillRequestWeightCarcass?.toLocaleString() || + 0} + + + + + حجم فروش به خارج استان: + + + {boxStats?.killing?.poultryOutProvinceQuantity?.toLocaleString() || 0} + + + + + وزن فروش به خارج استان: + + + {boxStats?.killing?.poultryOutProvinceWeight?.toLocaleString() || 0} + + + + + حجم بارها: + + + {boxStats?.killing?.KillHouseRequestQuantity?.toLocaleString() || 0} + + + + + وزن بارها: + + + {boxStats?.killing?.KillHouseRequestWeight?.toLocaleString() || 0} + + + + + لاشه تولیدی امروز با احتساب 25درصد افت کشتار : + + + {boxStats?.killing?.totalLossWeight?.toLocaleString() || 0} + + ); diff --git a/src/features/dashboard/components/dashboard-inventory-section/InventorySection.js b/src/features/dashboard/components/dashboard-inventory-section/InventorySection.js index 871d41f..55ac2da 100644 --- a/src/features/dashboard/components/dashboard-inventory-section/InventorySection.js +++ b/src/features/dashboard/components/dashboard-inventory-section/InventorySection.js @@ -1,87 +1,60 @@ import { Box, Typography } from "@mui/material"; import { SPACING } from "../../../../data/spacing"; -const inventoryItems = [ - { - label: "حجم آماده کشتار بزرگتر از 40 روز (قطعه) :", - key: "leftOverBetweenFortySeventyFive", - }, - { - label: "وزن تقریبی کشتار بزرگتر از 40 روز (کیلوگرم) :", - key: "weightBetweenFortySeventyFive", - }, - { - label: "میانگین وزن مرغداری‌های آماده کشتار:", - key: "aveWeight", - suffix: " کیلوگرم", - }, - { label: "وزن گوشت قابل تولید:", key: "carcassWeight", suffix: " کیلوگرم" }, -]; - -const InventoryRow = ({ label, value, suffix = "" }) => ( +export const InventorySection = ({ boxStats }) => ( - - {label} - - - {value?.toLocaleString() || 0} - {suffix} - - -); - -export const InventorySection = ({ boxStats, sx }) => ( - موجودی - - {inventoryItems.map((item) => ( - - ))} - + + حجم آماده کشتار بزرگتر از 40 روز (قطعه) : + + + {boxStats?.inventory?.leftOverBetweenFortySeventyFive?.toLocaleString() || + 0} + + + + وزن تقریبی کشتار بزرگتر از 40 روز (کیلوگرم) : + + + {boxStats?.inventory?.weightBetweenFortySeventyFive?.toLocaleString() || + 0} + + + + میانگین وزن مرغداری‌های آماده کشتار: + + + {boxStats?.inventory?.aveWeight?.toLocaleString() || 0} کیلوگرم + + + + وزن گوشت قابل تولید: + + + {boxStats?.inventory?.carcassWeight?.toLocaleString() || 0} کیلوگرم + ); diff --git a/src/features/dashboard/components/dashboard-pie-chart-section/PieChartSection.js b/src/features/dashboard/components/dashboard-pie-chart-section/PieChartSection.js index c9f5f8f..3a8694d 100644 --- a/src/features/dashboard/components/dashboard-pie-chart-section/PieChartSection.js +++ b/src/features/dashboard/components/dashboard-pie-chart-section/PieChartSection.js @@ -87,7 +87,8 @@ export const PieChartSection = ({ boxStats }) => { { > آمار روز گذشته کشتار مرغ گوشتی استان diff --git a/src/features/dashboard/components/dashboard-price-chart-section/PriceChartSection.js b/src/features/dashboard/components/dashboard-price-chart-section/PriceChartSection.js index 803223a..8bc2e04 100644 --- a/src/features/dashboard/components/dashboard-price-chart-section/PriceChartSection.js +++ b/src/features/dashboard/components/dashboard-price-chart-section/PriceChartSection.js @@ -13,18 +13,12 @@ export const PriceChartSection = ({ boxStats }) => ( border: "1px solid", borderColor: "divider", p: 2, + mt: 3, }} > نمودار قیمت مرغ در هفته گذشته (میانگین قیمت) diff --git a/src/features/dashboard/components/dashboard-slaughter/SlaughterDashboard.js b/src/features/dashboard/components/dashboard-slaughter/SlaughterDashboard.js index 681c469..6240e46 100644 --- a/src/features/dashboard/components/dashboard-slaughter/SlaughterDashboard.js +++ b/src/features/dashboard/components/dashboard-slaughter/SlaughterDashboard.js @@ -120,7 +120,12 @@ export const SlaughterDashboard = () => { ]; return ( - + { setValue(newValue); }; return ( - + { {/* */} - + {value === 0 && } {value === 1 && } {value === 2 && } diff --git a/src/features/dashboard/components/dashboard-ware-house-info-section/WarehouseInfoSection.js b/src/features/dashboard/components/dashboard-ware-house-info-section/WarehouseInfoSection.js index 2cd2805..ed06e68 100644 --- a/src/features/dashboard/components/dashboard-ware-house-info-section/WarehouseInfoSection.js +++ b/src/features/dashboard/components/dashboard-ware-house-info-section/WarehouseInfoSection.js @@ -1,65 +1,26 @@ import { Box, Typography } from "@mui/material"; -const warehouseItems = [ - { label: "وزن ورودی به انبار:", key: "enterWarehouseWeight" }, - { label: "وزن فروش به خارج استان:", key: "outSellWeight" }, - { label: "وزن توزیع به داخل استان:", key: "allocationWeight" }, - { label: "وزن مانده در انبار کشتارگاه:", key: "leftOverWarehouseWeight" }, -]; - -const WarehouseRow = ({ label, value }) => ( +export const WarehouseInfoSection = ({ boxStats }) => ( - - {label} - - - - {value?.toLocaleString() || 0} - - - کیلوگرم - - - -); - -export const WarehouseInfoSection = ({ boxStats, sx }) => ( - اطلاعات انبار و توزیع امروز @@ -70,16 +31,114 @@ export const WarehouseInfoSection = ({ boxStats, sx }) => ( display: "flex", flexDirection: "column", gap: 1, + overflowY: "auto", flex: 1, + pr: 1, }} > - {warehouseItems.map((item) => ( - - ))} + + + وزن ورودی به انبار: + + + + {boxStats?.warehouseInformation?.enterWarehouseWeight?.toLocaleString() || + 0} + + کیلوگرم + + + + + + وزن فروش به خارج استان: + + + + {boxStats?.warehouseInformation?.outSellWeight?.toLocaleString() || + 0} + + کیلوگرم + + + + + + وزن توزیع به داخل استان: + + + + {boxStats?.warehouseInformation?.allocationWeight?.toLocaleString() || + 0} + + کیلوگرم + + + + + + وزن مانده در انبار کشتارگاه: + + + + {boxStats?.warehouseInformation?.leftOverWarehouseWeight?.toLocaleString() || + 0} + + کیلوگرم + + ); diff --git a/src/features/dashboard/components/dashboard-yesterday-killing-report/YesterdayKillingReport.js b/src/features/dashboard/components/dashboard-yesterday-killing-report/YesterdayKillingReport.js index 92f10ab..ee61969 100644 --- a/src/features/dashboard/components/dashboard-yesterday-killing-report/YesterdayKillingReport.js +++ b/src/features/dashboard/components/dashboard-yesterday-killing-report/YesterdayKillingReport.js @@ -1,80 +1,17 @@ import { Box, Typography } from "@mui/material"; import { SPACING } from "../../../../data/spacing"; -const reportItems = [ - { label: "حجم درخواست کشتار مرغدار:", key: "quantityYesterday" }, - { label: "وزن درخواست کشتار مرغدار:", key: "totalWeightYesterday" }, - { label: "حجم خرید های مستقیم :", key: "killRequestQuantityYesterday" }, - { label: "وزن خرید های مستقیم :", key: "killRequestWeightYesterday" }, - { - label: "حجم خرید های خارج از استان (زنده) :", - key: "quantityKillHouseFreeBarLiveYesterday", - }, - { - label: "وزن خرید های خارج از استان (زنده) :", - key: "WeightKillHouseFreeBarLiveYesterday", - }, - { - label: "وزن خرید های خارج از استان (لاشه) :", - key: "WeightKillHouseFreeBarCarcassYesterday", - }, - { - label: "حجم کل تخصیصات (خرید مستقیم/ مرغدار ):", - key: "provinceKillRequestQuantityYesterday", - }, - { - label: "وزن کل تخصیصات (خرید مستقیم/ مرغدار ):", - key: "provinceKillRequestWeightCarcassYesterday", - }, - { - label: "حجم فروش به خارج استان:", - key: "poultryOutProvinceQuantityYesterday", - }, - { - label: "وزن فروش به خارج استان:", - key: "poultryOutProvinceWeightYesterday", - }, - { label: "حجم بارها:", key: "KillHouseRequestQuantityYesterday" }, - { label: "وزن بارها:", key: "KillHouseRequestWeightYesterday" }, - { - label: "لاشه تولیدی با احتساب 25درصد افت کشتار :", - key: "totalLossWeightYesterday", - }, -]; - -const ReportRow = ({ label, value }) => ( - - - {label} - - - {value?.toLocaleString() || 0} - - -); - export const YesterdayKillingReport = ({ boxStats }) => ( ( display: "flex", flexDirection: "column", gap: 2, + height: "700px", }} > - + گزارش کشتار دیروز مرغ گوشتی استان @@ -101,16 +34,262 @@ export const YesterdayKillingReport = ({ boxStats }) => ( gap: 1, overflowY: "auto", flex: 1, - maxHeight: "500px", }} > - {reportItems.map((item, index) => ( - - ))} + + حجم درخواست کشتار مرغدار: + + {boxStats?.killingYesterday?.quantityYesterday?.toLocaleString() || 0} + + + + وزن درخواست کشتار مرغدار: + + {boxStats?.killingYesterday?.totalWeightYesterday?.toLocaleString() || + 0} + + + + + حجم خرید های مستقیم : + + {boxStats?.killingYesterday?.killRequestQuantityYesterday?.toLocaleString() || + 0} + + + + وزن خرید های مستقیم : + + {boxStats?.killingYesterday?.killRequestWeightYesterday?.toLocaleString() || + 0} + + + + + + حجم خرید های خارج از استان (زنده) : + + + {boxStats?.killingYesterday?.quantityKillHouseFreeBarLiveYesterday?.toLocaleString() || + 0} + + + + + + وزن خرید های خارج از استان (زنده) : + + + {boxStats?.killingYesterday?.WeightKillHouseFreeBarLiveYesterday?.toLocaleString() || + 0} + + + + + + وزن خرید های خارج از استان (لاشه) : + + + {boxStats?.killingYesterday?.WeightKillHouseFreeBarCarcassYesterday?.toLocaleString() || + 0} + + + + + + حجم کل تخصیصات (خرید مستقیم/ مرغدار ): + + + {boxStats?.killingYesterday?.provinceKillRequestQuantityYesterday?.toLocaleString() || + 0} + + + + + وزن کل تخصیصات (خرید مستقیم/ مرغدار ): + + + {boxStats?.killingYesterday?.provinceKillRequestWeightCarcassYesterday?.toLocaleString() || + 0} + + + + حجم فروش به خارج استان: + + {boxStats?.killingYesterday?.poultryOutProvinceQuantityYesterday?.toLocaleString() || + 0} + + + + وزن فروش به خارج استان: + + {boxStats?.killingYesterday?.poultryOutProvinceWeightYesterday?.toLocaleString() || + 0} + + + + حجم بارها: + + {boxStats?.killingYesterday?.KillHouseRequestQuantityYesterday?.toLocaleString() || + 0} + + + + وزن بارها: + + {boxStats?.killingYesterday?.KillHouseRequestWeightYesterday?.toLocaleString() || + 0} + + + + + لاشه تولیدی با احتساب 25درصد افت کشتار : + + + {boxStats?.killingYesterday?.totalLossWeightYesterday?.toLocaleString() || + 0} + + ); diff --git a/src/features/dashboard/components/dashboard/Dashboard.js b/src/features/dashboard/components/dashboard/Dashboard.js index 03f2ee4..38dc03e 100644 --- a/src/features/dashboard/components/dashboard/Dashboard.js +++ b/src/features/dashboard/components/dashboard/Dashboard.js @@ -154,6 +154,7 @@ export const Dashboard = () => { return ( { {notification.title} - + {notification.message} @@ -450,16 +445,14 @@ export const Dashboard = () => { }} > آمار جوجه ریزی استان @@ -496,95 +489,94 @@ export const Dashboard = () => { ))} - - - - - - - } - data={[ - [ - boxStats?.hatching?.totalLeftOverLt35?.toLocaleString() || "0", - boxStats?.hatching?.totalLeftOverBetween3540?.toLocaleString() || - "0", - boxStats?.hatching?.totalLeftOverBetween4045?.toLocaleString() || - "0", - boxStats?.hatching?.totalLeftOverBetween4550?.toLocaleString() || - "0", - boxStats?.hatching?.totalLeftOverBetween5055?.toLocaleString() || - "0", - boxStats?.hatching?.totalLeftOverBetween5560?.toLocaleString() || - "0", - boxStats?.hatching?.totalLeftOverBetween6065?.toLocaleString() || - "0", - boxStats?.hatching?.totalLeftOverBetween6570?.toLocaleString() || - "0", - boxStats?.hatching?.totalLeftOverGt70?.toLocaleString() || "0", - ], - ]} - allColors={{ color: "#244CCC", text: "#fff" }} - columns={[ - "کمتر از 35 روز", - "بین 35 تا 40 روز", - "بین 40 تا 45 روز", - "بین 45 تا 50 روز", - "بین 50 تا 55 روز", - "بین 55 تا 60 روز", - "بین 60 تا 65 روز", - "بین 65 تا 70 روز", - "بیش از 70 روز", - ]} - title="مانده در سالن (قطعه)" - /> - - - - - - - - - - - - - - - + + + + + + + } + data={[ + [ + boxStats?.hatching?.totalLeftOverLt35?.toLocaleString() || "0", + boxStats?.hatching?.totalLeftOverBetween3540?.toLocaleString() || + "0", + boxStats?.hatching?.totalLeftOverBetween4045?.toLocaleString() || + "0", + boxStats?.hatching?.totalLeftOverBetween4550?.toLocaleString() || + "0", + boxStats?.hatching?.totalLeftOverBetween5055?.toLocaleString() || + "0", + boxStats?.hatching?.totalLeftOverBetween5560?.toLocaleString() || + "0", + boxStats?.hatching?.totalLeftOverBetween6065?.toLocaleString() || + "0", + boxStats?.hatching?.totalLeftOverBetween6570?.toLocaleString() || + "0", + boxStats?.hatching?.totalLeftOverGt70?.toLocaleString() || "0", + ], + ]} + allColors={{ color: "#244CCC", text: "#fff" }} + columns={[ + "کمتر از 35 روز", + "بین 35 تا 40 روز", + "بین 40 تا 45 روز", + "بین 45 تا 50 روز", + "بین 50 تا 55 روز", + "بین 55 تا 60 روز", + "بین 60 تا 65 روز", + "بین 65 تا 70 روز", + "بیش از 70 روز", + ]} + title="مانده در سالن (قطعه)" + /> + - - - - - - - - - + + + + + + + + + + + ); }; diff --git a/src/features/file/components/check-request-item/CheckRequestItem.js b/src/features/file/components/check-request-item/CheckRequestItem.js index 655fd20..992c02d 100644 --- a/src/features/file/components/check-request-item/CheckRequestItem.js +++ b/src/features/file/components/check-request-item/CheckRequestItem.js @@ -12,7 +12,7 @@ import { import { checkRequestBySlaughter } from "../../services/checkRequestBySlaughter"; import { useFormik } from "formik"; import { Yup } from "../../../../lib/yup/yup"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; import { PropTypes } from "prop-types"; import { getAllocationInformation } from "../../services/get-allocation-information"; import { Grid } from "../../../../components/grid/Grid"; @@ -22,16 +22,13 @@ import { useContext } from "react"; import { AppContext } from "../../../../contexts/AppContext"; import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl"; import { slaughterGetActiveRequests } from "../../../slaughter-house/services/slaughter-get-active-requests"; -import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; export default function CheckRequestItem({ reqKey, poultryRequestKey }) { const [openNotif] = useContext(AppContext); const [isDenyed, setisDenyed] = useState(false); const dispatch = useDispatch(); const { id } = useParams(); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); + const [, , selectedDate1, , selectedDate2] = useContext(AppContext); const formik = useFormik({ @@ -134,30 +131,17 @@ export default function CheckRequestItem({ reqKey, poultryRequestKey }) { }) ); // getFileFromApi(roles, id, dispatch); - dispatch( - getAcceptedSlaughterRequest({ - id, - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) - ); + dispatch(getAcceptedSlaughterRequest({ id })); setisDenyed(false); dispatch( getAllocationInformation({ key: poultryRequestKey, - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", }) ); dispatch( slaughterGetActiveRequests({ selectedDate1, selectedDate2, - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", }) ); openNotif({ @@ -215,29 +199,14 @@ export default function CheckRequestItem({ reqKey, poultryRequestKey }) { content: null, }) ); + dispatch(getAcceptedSlaughterRequest({ id })); dispatch( - getAcceptedSlaughterRequest({ - id, - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) - ); - dispatch( - getAllocationInformation({ - key: poultryRequestKey, - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) + getAllocationInformation({ key: poultryRequestKey }) ); dispatch( slaughterGetActiveRequests({ selectedDate1, selectedDate2, - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", }) ); openNotif({ diff --git a/src/features/file/components/slaughter-enter-bar-item/SlaughterEnterBarItem.js b/src/features/file/components/slaughter-enter-bar-item/SlaughterEnterBarItem.js index 2ede861..12f4630 100644 --- a/src/features/file/components/slaughter-enter-bar-item/SlaughterEnterBarItem.js +++ b/src/features/file/components/slaughter-enter-bar-item/SlaughterEnterBarItem.js @@ -26,7 +26,6 @@ import { NumberInput } from "../../../../components/number-format-custom/NumberF import { resizeImage } from "../../../../utils/resizeImage"; import { slaughterGetExlusiveKillers } from "../../services/slaughterGetExlusiveKillers"; import { isValidIndexWeight } from "../../../../utils/isValidIndexWeight"; -import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; export const SlaughterEnterBarItem = ({ data, @@ -42,9 +41,7 @@ export const SlaughterEnterBarItem = ({ const [weightWithBarImages, setWeightWithBarImages] = React.useState([]); const [weightWithBarImg, setWeightWithBarImg] = React.useState(null); const { weightRange } = useSelector((state) => state.provinceSlice); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); + const weightWithBarImgHandler = (imageList) => { setWeightWithBarImages(imageList); formik.setFieldValue("weightWithBarImg", ""); @@ -147,18 +144,11 @@ export const SlaughterEnterBarItem = ({ const [exclusiveKillers, setExclusiveKillers] = useState(); const [selectedOption, setSelectedOption] = useState(); - useEffect(() => { - dispatch( - slaughterGetExlusiveKillers({ - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) - ).then((r) => { + dispatch(slaughterGetExlusiveKillers()).then((r) => { setExclusiveKillers(r.payload.data); }); - }, [selectedSubUser?.key]); + }, []); const handleOptionChange = (event) => { setSelectedOption(event?.target.value); diff --git a/src/features/file/components/slaughter-enter-bar-weight/SlaughterEnterBarWeight.js b/src/features/file/components/slaughter-enter-bar-weight/SlaughterEnterBarWeight.js index 01e0a09..b01448f 100644 --- a/src/features/file/components/slaughter-enter-bar-weight/SlaughterEnterBarWeight.js +++ b/src/features/file/components/slaughter-enter-bar-weight/SlaughterEnterBarWeight.js @@ -13,14 +13,10 @@ import TimelineItem from "@mui/lab/TimelineItem"; import { SlaughterEnterBarItem } from "../slaughter-enter-bar-item/SlaughterEnterBarItem"; import { format } from "date-fns-jalali"; import { provincePolicyGetWeightRange } from "../../../province/services/province-policy-get-weight-range"; -import { useDispatch, useSelector } from "react-redux"; -import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; +import { useDispatch } from "react-redux"; export const SlaughterEnterBarWeight = ({ item, updateTable }) => { const dispatch = useDispatch(); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); const sum = item?.acceptedRealWeight / item?.acceptedRealQuantity; const data = [ [ @@ -41,15 +37,8 @@ export const SlaughterEnterBarWeight = ({ item, updateTable }) => { ]; useEffect(() => { - dispatch( - provincePolicyGetWeightRange({ - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) - ); - }, [selectedSubUser?.key]); - + dispatch(provincePolicyGetWeightRange()); + }, []); return ( diff --git a/src/features/file/services/getAcceptedSlaughterRequest.js b/src/features/file/services/getAcceptedSlaughterRequest.js index 3a16e67..533b6e8 100644 --- a/src/features/file/services/getAcceptedSlaughterRequest.js +++ b/src/features/file/services/getAcceptedSlaughterRequest.js @@ -4,12 +4,11 @@ import { getRoleFromUrl } from "../../../utils/getRoleFromUrl"; export const getAcceptedSlaughterRequest = createAsyncThunk( "GET_ACCEPTED_SLAUGHTER_REQUEST", - async ({ id, role_key }) => { + async ({ id }) => { const { data, status } = await axios.get("province_kill_request", { params: { id, role: getRoleFromUrl(), - role_key: role_key || "", }, }); return { data, status }; diff --git a/src/features/file/services/slaughterGetExlusiveKillers.js b/src/features/file/services/slaughterGetExlusiveKillers.js index 34bf8a4..6c710d8 100644 --- a/src/features/file/services/slaughterGetExlusiveKillers.js +++ b/src/features/file/services/slaughterGetExlusiveKillers.js @@ -7,10 +7,7 @@ export const slaughterGetExlusiveKillers = createAsyncThunk( async (d, { dispatch }) => { dispatch(LOADING_START()); const { data, status } = await axios.get( - "kill_house/?exclusive-killers=true", - { - params: d, - } + "kill_house/?exclusive-killers=true" ); dispatch(LOADING_END()); return { data, status }; diff --git a/src/features/guild/components/GuildReceiveBarOperation.js b/src/features/guild/components/GuildReceiveBarOperation.js index fd2fb6e..0a989c6 100644 --- a/src/features/guild/components/GuildReceiveBarOperation.js +++ b/src/features/guild/components/GuildReceiveBarOperation.js @@ -42,7 +42,7 @@ export const GuildReceiveBarOperation = ({ item }) => { authCode: Yup.string().required("کداحراز اجباری است"), }); - const onSubmit = () => { + const onSubmit = (values) => { // Handle form submission here // console.log("Form submitted with values:", values); }; @@ -65,6 +65,9 @@ export const GuildReceiveBarOperation = ({ item }) => { weight: "", }, validationSchema: Yup.object({ + number: Yup.number() + .required("این فیلد اجباری است!") + .typeError("لطفا عدد وارد کنید!"), weight: Yup.number() .required("این فیلد اجباری است!") .typeError("لطفا وزن را وارد کنید!"), @@ -114,7 +117,6 @@ export const GuildReceiveBarOperation = ({ item }) => { size="small" label="وزن" variant="outlined" - fullWidth disabled={!isChecked} onChange={formikRealInfo.handleChange} onBlur={formikRealInfo.handleBlur} @@ -130,6 +132,27 @@ export const GuildReceiveBarOperation = ({ item }) => { } /> + + + @@ -181,7 +204,9 @@ export const GuildReceiveBarOperation = ({ item }) => { if (getRoleFromUrl() === "senf") { reqObj = { guild_check_allocation: true, - receiver_real_number_of_carcasses: 0, + receiver_real_number_of_carcasses: formikRealInfo.values.number + ? formikRealInfo.values.number + : item.numberOfCarcasses, receiver_real_weight_of_carcasses: formikRealInfo.values.weight ? formikRealInfo.values.weight : item.weightOfCarcasses, @@ -193,7 +218,9 @@ export const GuildReceiveBarOperation = ({ item }) => { reqObj = { steward_check_allocation: true, allocation_key: item.key, - receiver_real_number_of_carcasses: 0, + receiver_real_number_of_carcasses: formikRealInfo.values.number + ? formikRealInfo.values.number + : item.numberOfCarcasses, receiver_real_weight_of_carcasses: formikRealInfo.values.weight ? formikRealInfo.values.weight : item.weightOfCarcasses, @@ -206,7 +233,9 @@ export const GuildReceiveBarOperation = ({ item }) => { reqObj = { guild_check_allocation: true, allocation_key: item.key, - receiver_real_number_of_carcasses: 0, + receiver_real_number_of_carcasses: formikRealInfo.values.number + ? formikRealInfo.values.number + : item.numberOfCarcasses, receiver_real_weight_of_carcasses: formikRealInfo.values.weight ? formikRealInfo.values.weight : item.weightOfCarcasses, @@ -216,7 +245,9 @@ export const GuildReceiveBarOperation = ({ item }) => { reqObj = { steward_check_allocation: true, allocation_key: item.key, - receiver_real_number_of_carcasses: 0, + receiver_real_number_of_carcasses: formikRealInfo.values.number + ? formikRealInfo.values.number + : item.numberOfCarcasses, receiver_real_weight_of_carcasses: formikRealInfo.values.weight ? formikRealInfo.values.weight : item.weightOfCarcasses, diff --git a/src/features/guild/components/RegisterEditDeliveryNumberAndWeight.js b/src/features/guild/components/RegisterEditDeliveryNumberAndWeight.js index fd62700..6bbde6d 100644 --- a/src/features/guild/components/RegisterEditDeliveryNumberAndWeight.js +++ b/src/features/guild/components/RegisterEditDeliveryNumberAndWeight.js @@ -4,7 +4,7 @@ import { Button, InputAdornment, TextField } from "@mui/material"; import { Yup } from "../../../lib/yup/yup"; import { useContext, useEffect } from "react"; import { SPACING } from "../../../data/spacing"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; import { guildUpdateAllocatedStockService } from "../services/guild-update-allocated-stock"; import { AppContext } from "../../../contexts/AppContext"; import { guildGetInventoryStockService } from "../services/guild-get-inventory-stock"; @@ -13,7 +13,6 @@ import { CLOSE_MODAL } from "../../../lib/redux/slices/appSlice"; import { getRoleFromUrl } from "../../../utils/getRoleFromUrl"; import { senfGetInventoryStockService } from "../services/senf-get-inventory-stock"; import { senfGetInventoryAllocatedService } from "../services/senf-get-inventory-allocated"; -import { checkPathStartsWith } from "../../../utils/checkPathStartsWith"; const schema = Yup.object().shape({ quantity: Yup.number().required("وارد کردن تعداد اجباری است"), @@ -24,9 +23,6 @@ export const RegisterEditDeliveryNumberAndWeight = ({ item }) => { const [openNotif] = useContext(AppContext); const [, , selectedDate1] = useContext(AppContext); const dispatch = useDispatch(); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); const formik = useFormik({ initialValues: { quantity: item?.receiverRealNumberOfCarcasses, @@ -65,17 +61,11 @@ export const RegisterEditDeliveryNumberAndWeight = ({ item }) => { dispatch( guildGetInventoryStockService({ date: selectedDate1, - role_key: checkPathStartsWith("senf") - ? selectedSubUser?.key - : "", }) ); dispatch( guildGetInventoryAllocatedService({ date: selectedDate1, - role_key: checkPathStartsWith("senf") - ? selectedSubUser?.key - : "", }) ); } diff --git a/src/features/guild/components/StewardAllocationToGuild.js b/src/features/guild/components/StewardAllocationToGuild.js index 77ca761..10588a2 100644 --- a/src/features/guild/components/StewardAllocationToGuild.js +++ b/src/features/guild/components/StewardAllocationToGuild.js @@ -11,7 +11,7 @@ import { TextField, Typography, } from "@mui/material"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; import { useFormik } from "formik"; import { DatePicker } from "@mui/x-date-pickers"; import moment from "moment"; @@ -36,7 +36,6 @@ import PersianDate from "persian-date"; import axios from "axios"; import { LabelField } from "../../../components/label-field/LabelField"; import { SPACING } from "../../../data/spacing"; -import { checkPathStartsWith } from "../../../utils/checkPathStartsWith"; export const StewardAllocationToGuild = ({ item, @@ -80,9 +79,6 @@ export const StewardAllocationToGuild = ({ const [selectedDate1, setSelectedDate1] = useState( moment(new Date()).format("YYYY-MM-DD") ); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); const handleChange = (event) => { setValue(event.target.value); @@ -164,10 +160,13 @@ export const StewardAllocationToGuild = ({ return transformedData; }, []); - const updateCalendarData = useCallback((dataArray) => { - const transformed = transformCalendarData(dataArray); - setCalendarDayData(transformed); - }, []); + const updateCalendarData = useCallback( + (dataArray) => { + const transformed = transformCalendarData(dataArray); + setCalendarDayData(transformed); + }, + [transformCalendarData] + ); const fetchCalendarData = useCallback( async (dateParam = selectedDate1) => { @@ -175,9 +174,6 @@ export const StewardAllocationToGuild = ({ const response = await axios.get("/steward-remain-weight/", { params: { date: dateParam, - role_key: checkPathStartsWith("steward") - ? selectedSubUser?.key - : "", }, }); if (response.data) { @@ -195,7 +191,7 @@ export const StewardAllocationToGuild = ({ console.error("Error fetching calendar data:", error); } }, - [selectedInventory, updateCalendarData, selectedDate1, selectedSubUser] + [selectedInventory, updateCalendarData, selectedDate1] ); const [buyerData, setBuyerData] = useState({ @@ -213,7 +209,7 @@ export const StewardAllocationToGuild = ({ useEffect(() => { fetchCalendarData(selectedDate1); - }, [selectedDate1]); + }, [fetchCalendarData, selectedDate1]); useEffect(() => { if ( @@ -229,41 +225,30 @@ export const StewardAllocationToGuild = ({ setProductionDate(null); setSelectedDateAmount(null); } - }, [selectedInventory, calendarRawData]); + }, [selectedInventory, calendarRawData, updateCalendarData]); useEffect(() => { - dispatch( - provincePolicyGetUploadImageService({ - role_key: checkPathStartsWith("steward") ? selectedSubUser?.key : "", - }) - ).then((r) => { + dispatch(provincePolicyGetUploadImageService()).then((r) => { if (r.payload?.data) { setImageUploadLimit(r.payload.data.killHouseAllocation); } }); if (!editData) { - dispatch( - slaughterGetProductsService({ - role_key: checkPathStartsWith("steward") ? selectedSubUser?.key : "", - }) - ).then((r) => { + dispatch(slaughterGetProductsService()).then((r) => { setProductData(r.payload.data); }); if (!item) { dispatch( slaughterGetGuildsForAllocateService({ free: value === "free" ? true : false, - role_key: checkPathStartsWith("steward") - ? selectedSubUser?.key - : "", }) ).then((r) => { setGuildsData(r.payload.data); }); } } - }, [value, selectedSubUser?.key]); + }, [dispatch, value]); const validationSchema = Yup.object({ mobile: Yup.string().when([], { @@ -350,11 +335,14 @@ export const StewardAllocationToGuild = ({ }, [formik.values.price, formik.values.weight]); const successSubmit = () => { - dispatch( - fetchSlaughterBroadcastAndProducts({ - role_key: checkPathStartsWith("steward") ? selectedSubUser?.key : "", - }) - ); + dispatch(CLOSE_MODAL()); + openNotif({ + vertical: "top", + horizontal: "center", + msg: "عملیات با موفقیت انجام شد.", + severity: "success", + }); + dispatch(fetchSlaughterBroadcastAndProducts()); dispatch( DRAWER({ right: false, @@ -366,13 +354,6 @@ export const StewardAllocationToGuild = ({ fetchApiData && fetchApiData(1); updateTable && updateTable(); fetchData && fetchData(1); - dispatch(CLOSE_MODAL()); - openNotif({ - vertical: "top", - horizontal: "center", - msg: "عملیات با موفقیت انجام شد.", - severity: "success", - }); }; const [dateRangeError, setDateRangeError] = useState(null); @@ -472,9 +453,13 @@ export const StewardAllocationToGuild = ({ } - label="اختصاصی" + label="صنوف اختصاصی" + /> + } + label="صنوف آزاد" /> - } label="آزاد" /> @@ -492,7 +477,9 @@ export const StewardAllocationToGuild = ({ ? guildsData.map((i) => { return { data: i, - label: `${i?.guildsName} ${i?.user?.fullname} (${i?.user?.mobile})`, + label: `${i?.steward ? "مباشر" : "صنف"} ${ + i?.guildsName + } ${i?.user?.fullname} (${i?.user?.mobile})`, }; }) : [] @@ -501,8 +488,10 @@ export const StewardAllocationToGuild = ({ setBuyerData({ item: value?.data, key: value?.data?.key, - allocationType: "steward_guild", - buyerType: "Guild", + allocationType: value?.data?.steward + ? "steward_steward" + : "steward_guild", + buyerType: value?.data?.steward ? "Steward" : "Guild", }); formik.setFieldValue("mobile", value?.data?.user?.mobile); formik.setFieldTouched("mobile", true, false); @@ -513,7 +502,7 @@ export const StewardAllocationToGuild = ({ } }} renderInput={(params) => ( - + )} /> @@ -538,7 +527,7 @@ export const StewardAllocationToGuild = ({ checked={changeMobile} onChange={() => setChangeMobile(!changeMobile)} /> - از این قسمت میتوانید تلفن صنف را ویرایش کنید. + از این قسمت میتوانید تلفن مباشر/صنف را ویرایش کنید. {buyerData?.key && changeMobile && ( @@ -786,21 +775,31 @@ export const StewardAllocationToGuild = ({ weight_of_carcasses: formik.values.weight, amount: formik.values.price, total_amount: formik.values.wholePrice, - role_key: checkPathStartsWith("steward") - ? selectedSubUser?.key || "" - : "", distribution_type: "web", ...(imageChanged && { image: formik.values.image }), }; } else if (!editData) { req = { seller_type: sellerType, - buyer_type: "Guild", - guild_key: buyerData?.item?.key, + buyer_type: buyerData?.buyerType, + guild_key: + buyerData?.buyerType === "Guild" + ? buyerData?.item?.key + : null, + steward_key: + buyerData?.buyerType === "Steward" + ? buyerData?.item?.key + : null, + kill_house_key: + buyerData?.buyerType === "KillHouse" + ? buyerData?.item?.key + : null, cold_house_key: coldHouseKey || null, product_key: coldHouseKey ? null : productKey.key, type: "manual", - allocation_type: coldHouseKey ? "ColdHouse" : "steward_guild", + allocation_type: coldHouseKey + ? "ColdHouse" + : buyerData?.allocationType, number_of_carcasses: 0, weight_of_carcasses: formik.values.weight, sell_type: sellType, @@ -811,9 +810,6 @@ export const StewardAllocationToGuild = ({ quota: selectedInventory, date: selectedDate1, production_date: productionDate, - role_key: checkPathStartsWith("steward") - ? selectedSubUser?.key || "" - : "", distribution_type: "web", ...(buyerData?.item?.user?.mobile !== formik.values.mobile ? { interface_number: formik.values.mobile } @@ -831,9 +827,6 @@ export const StewardAllocationToGuild = ({ number_of_carcasses: 0, weight_of_carcasses: formik.values.weight, amount: formik.values.price, - role_key: checkPathStartsWith("steward") - ? selectedSubUser?.key || "" - : "", total_amount: formik.values.wholePrice, distribution_type: "web", ...(imageChanged && { image: formik.values.image }), diff --git a/src/features/guild/components/StewardDailyList.js b/src/features/guild/components/StewardDailyList.js index d14d97e..bed4cc3 100644 --- a/src/features/guild/components/StewardDailyList.js +++ b/src/features/guild/components/StewardDailyList.js @@ -1,5 +1,5 @@ import React, { useContext, useEffect, useRef, useState } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; import InfoIcon from "@mui/icons-material/Info"; import TextField from "@mui/material/TextField"; import InputAdornment from "@mui/material/InputAdornment"; @@ -35,7 +35,6 @@ import { Grid } from "../../../components/grid/Grid"; import { NumberInput } from "../../../components/number-format-custom/NumberFormatCustom"; import ResponsiveTable from "../../../components/responsive-table/ResponsiveTable"; import { AppContext } from "../../../contexts/AppContext"; -import { checkPathStartsWith } from "../../../utils/checkPathStartsWith"; export const StewardDailyList = () => { const [productsTable, setProductsTable] = useState(); @@ -49,9 +48,7 @@ export const StewardDailyList = () => { const [filteredData, setFilteredData] = useState([]); const [openNotif] = useContext(AppContext); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); + const priceRefs = useRef([]); const weightRefs = useRef([]); @@ -138,25 +135,16 @@ export const StewardDailyList = () => { } }; const fetchPriceStatus = async () => { - dispatch( - slaughterGetPriceService({ - role: getRoleFromUrl(), - role_key: checkPathStartsWith("steward") ? selectedSubUser?.key : "", - }) - ).then((r) => { + dispatch(slaughterGetPriceService({ role: getRoleFromUrl() })).then((r) => { setPriceState(r.payload.data); }); }; - const fetchApiData = async () => { + const fetchApiData = async (page) => { dispatch(LOADING_START()); try { const response = await axios.get( - `commonly-used/?search=filter&value=&role=${getRoleFromUrl()}${ - checkPathStartsWith("steward") - ? `&role_key=${selectedSubUser?.key}` - : "" - }&page=1&page_size=10000` + `commonly-used/?search=filter&value=&role=${getRoleFromUrl()}&page=1&page_size=10000` ); setrendered(true); setData(response.data.results || []); @@ -222,10 +210,10 @@ export const StewardDailyList = () => { dispatch(slaughterGetProductsService()).then((r) => { setSlaughterProducts(r.payload.data); }); - }, [selectedSubUser?.key]); + }, []); useEffect(() => { - const d = slaughterProducts?.map((item) => { + const d = slaughterProducts?.map((item, i) => { return [item?.name, item?.totalRemainWeight?.toLocaleString()]; }); diff --git a/src/features/guild/components/StewardSegmant.js b/src/features/guild/components/StewardSegmant.js index af8e597..845e788 100644 --- a/src/features/guild/components/StewardSegmant.js +++ b/src/features/guild/components/StewardSegmant.js @@ -1,6 +1,6 @@ import { useContext, useEffect, useState } from "react"; import { AppContext } from "../../../contexts/AppContext"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; import ResponsiveTable from "../../../components/responsive-table/ResponsiveTable"; import { Grid } from "../../../components/grid/Grid"; import moment from "moment"; @@ -20,7 +20,6 @@ import { stewardGetOutSellService } from "../services/steward-get-sell-out-servi import { formatJustDate, formatTime } from "../../../utils/formatTime"; import { StewardSegmentOperation } from "./StewardSegmentOperation"; import { stawardGetSegmentDashboardService } from "../services/steward-get-dashboard-service"; -import { checkPathStartsWith } from "../../../utils/checkPathStartsWith"; export const StewardSegmant = () => { const [data, setData] = useState([]); @@ -34,9 +33,6 @@ export const StewardSegmant = () => { const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] = useContext(AppContext); const dispatch = useDispatch(); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); // const userKey = useSelector((state) => state.userSlice.userProfile.key); @@ -46,7 +42,6 @@ export const StewardSegmant = () => { value: textValue, date1: selectedDate1, date2: selectedDate2, - role_key: checkPathStartsWith("steward") ? selectedSubUser?.key : "", }) ).then((r) => { setDashboardData(r.payload.data); @@ -62,11 +57,7 @@ export const StewardSegmant = () => { const fetchApiData = async (page) => { dispatch(LOADING_START()); const response = await axios.get( - `app-segmentation/?search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${perPage}&role=${getRoleFromUrl()}${ - checkPathStartsWith("steward") - ? `&role_key=${selectedSubUser?.key}` - : "" - }` + `app-segmentation/?search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${perPage}&role=${getRoleFromUrl()}` ); getDashboardData(); @@ -98,14 +89,10 @@ export const StewardSegmant = () => { useEffect(() => { fetchApiData(1); - dispatch( - stewardGetOutSellService({ - role_key: checkPathStartsWith("steward") ? selectedSubUser?.key : "", - }) - ).then((r) => { + dispatch(stewardGetOutSellService()).then((r) => { setProducts(r.payload.data); }); - }, [selectedSubUser?.key]); + }, []); useEffect(() => { const d = data?.map((item, i) => { @@ -157,11 +144,7 @@ export const StewardSegmant = () => { dispatch(LOADING_START()); try { const response = await axios.get( - `app-segmentation/?search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&role=${getRoleFromUrl()}${ - checkPathStartsWith("steward") - ? `&role_key=${selectedSubUser?.key}` - : "" - }` + `app-segmentation/?search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&role=${getRoleFromUrl()}` ); setData(response.data.results); setTotalRows(response.data.count); @@ -181,7 +164,7 @@ export const StewardSegmant = () => { gap={SPACING.SMALL} justifyContent="flex-start" > - + Yup.object().shape({ @@ -59,22 +54,13 @@ export const StewardSegmentSubmitOperation = ({ }) => { const dispatch = useDispatch(); const [openNotif] = useContext(AppContext); + const [stewardData, setStewardData] = useState([]); const [segmentType, setSegmentType] = useState("own"); const [selectedInventory] = useState("free"); const [approvedStatus, setApprovedStatus] = useState("governmental"); - const [buyerCategory, setBuyerCategory] = useState(""); // "stewards" or "guilds" - const [guildsData, setGuildsData] = useState([]); - const [stewardsData, setStewardsData] = useState([]); - const [buyerData, setBuyerData] = useState({ - key: "", - item: "", - buyerType: "", - allocationType: "", - }); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); + const [selectedBuyer, setSelectedBuyer] = useState(null); + // Calendar states const [selectedCalendarDate, setSelectedCalendarDate] = useState(null); const [calendarDayData, setCalendarDayData] = useState({}); const [productionDate, setProductionDate] = useState(null); @@ -130,7 +116,7 @@ export const StewardSegmentSubmitOperation = ({ distribution_type: "web", }; } else { - if (!buyerData?.key) { + if (!selectedBuyer) { openNotif({ vertical: "top", horizontal: "center", @@ -141,9 +127,7 @@ export const StewardSegmentSubmitOperation = ({ } req = { - guild_key: buyerData?.buyerType === "Guild" ? buyerData?.key : null, - steward_key: - buyerData?.buyerType === "Steward" ? buyerData?.key : null, + guild_key: selectedBuyer.key, weight: values.weight, product_key: productKey || "", sale_type: selectedInventory, @@ -151,9 +135,6 @@ export const StewardSegmentSubmitOperation = ({ production_date: productionDate, distribution_type: "web", }; - req = Object.fromEntries( - Object.entries(req).filter(([, val]) => val !== null) - ); } dispatch(stewardSegmentSubmitService(req)).then((r) => { @@ -195,19 +176,6 @@ export const StewardSegmentSubmitOperation = ({ setApprovedStatus(newType); }; - const handleBuyerCategoryChange = (event) => { - const newCategory = event.target.value; - setBuyerCategory(newCategory); - setBuyerData({ - key: "", - item: "", - buyerType: "", - allocationType: "", - }); - setGuildsData([]); - setStewardsData([]); - }; - // Calendar functions const handleDateSelect = (dateInfo) => { if (dateInfo && dateInfo.formattedDate) { @@ -216,6 +184,7 @@ export const StewardSegmentSubmitOperation = ({ // Get the data for the selected date const data = calendarDayData[dateInfo.formattedDate]; + // Use the original Gregorian date from the API data for production_date if (data && data.originalDay) { setProductionDate(data.originalDay); } @@ -229,24 +198,30 @@ export const StewardSegmentSubmitOperation = ({ } }; + // Transform calendar data from array format to object format + // Input: [{day: "2025-10-10", amount: 100}] + // Output: {"1404/07/19": {value1: 100, originalDay: "2025-10-10"}} const transformCalendarData = useCallback((dataArray) => { if (!Array.isArray(dataArray)) return {}; const transformedData = {}; dataArray.forEach((item) => { if (item.day && item.amount !== undefined) { + // Convert Gregorian date to Persian date const persianDate = new PersianDate(new Date(item.day)); const persianDateStr = persianDate.format("YYYY/MM/DD"); + // Calendar expects 'value1' property, also store the original day transformedData[persianDateStr] = { value1: item.amount, - originalDay: item.day, - active: item.active === true, + originalDay: item.day, // Store the original Gregorian date + active: item.active === true, // Store active status }; } }); return transformedData; }, []); + // Function to update calendar data from API response const updateCalendarData = useCallback( (dataArray) => { const transformed = transformCalendarData(dataArray); @@ -258,30 +233,17 @@ export const StewardSegmentSubmitOperation = ({ // Fetch calendar data from API const fetchCalendarData = useCallback(async () => { try { - const currentRole = getRoleFromUrl(); - console.log(getRoleFromUrl()); - let remainWeightEndpoint = "kill-house-remain-weight"; - if (currentRole === "Steward") { - remainWeightEndpoint = "steward-remain-weight"; - } else if (currentRole === "Guilds") { - remainWeightEndpoint = "guild-remain-weight"; - } - - const response = await axios.get(`${remainWeightEndpoint}/`, { - params: { - role_key: - checkPathStartsWith("slaughter") || - checkPathStartsWith("steward") || - checkPathStartsWith("senf") - ? selectedSubUser?.key || "" - : "", - }, - }); + const response = await axios.get( + `/${ + getRoleFromUrl() === "Steward" ? "steward" : "kill-house" + }-remain-weight/` + ); if (response.data) { setCalendarRawData({ governmental: response.data.governmental || [], free: response.data.free || [], }); + // Update calendar based on current inventory type const dataToShow = approvedStatus === "governmental" ? response.data.governmental @@ -291,42 +253,21 @@ export const StewardSegmentSubmitOperation = ({ } catch (error) { console.error("Error fetching calendar data:", error); } - }, [approvedStatus, updateCalendarData, selectedSubUser]); + }, [approvedStatus, updateCalendarData]); useEffect(() => { - fetchCalendarData(); - }, []); - - useEffect(() => { - if (!editData && buyerCategory) { - if (buyerCategory === "guilds") { - dispatch( - slaughterGetGuildsForAllocateService({ - free: true, - role_key: - checkPathStartsWith("slaughter") || checkPathStartsWith("steward") - ? selectedSubUser?.key || "" - : "", - }) - ).then((r) => { - setGuildsData(r.payload.data || []); - }); - } else if (buyerCategory === "stewards") { - dispatch( - slaughterGetStewardsForAllocateService({ - free: true, - role_key: - checkPathStartsWith("slaughter") || checkPathStartsWith("steward") - ? selectedSubUser?.key || "" - : "", - }) - ).then((r) => { - setStewardsData(r.payload.data || []); - }); - } + if (!editData) { + dispatch(stawardGetSegmantRoleService({ role: getRoleFromUrl() })).then( + (r) => { + setStewardData(r.payload.data); + } + ); } - }, [buyerCategory, selectedSubUser?.key, editData]); + // Fetch calendar data on mount + fetchCalendarData(); + }, [dispatch, editData, fetchCalendarData]); + // Update calendar when inventory type changes useEffect(() => { if ( calendarRawData.governmental.length > 0 || @@ -337,25 +278,18 @@ export const StewardSegmentSubmitOperation = ({ ? calendarRawData.governmental : calendarRawData.free; updateCalendarData(dataToShow); + // Reset selected date when inventory type changes setSelectedCalendarDate(null); setProductionDate(null); setSelectedDateAmount(null); } }, [approvedStatus, calendarRawData, updateCalendarData]); + // Validate form when selectedDateAmount changes useEffect(() => { formik.validateForm(); }, [selectedDateAmount]); - // Set segmentType to "own" for Guilds role - useEffect(() => { - const currentRole = getRoleFromUrl(); - if (currentRole === "Guilds" && !editData) { - setSegmentType("own"); - formik.setFieldValue("segmentType", "own"); - } - }, [editData]); - return ( @@ -367,7 +301,7 @@ export const StewardSegmentSubmitOperation = ({ gap: SPACING.LARGE + 4, }} > - {!editData && getRoleFromUrl() !== "Guilds" && ( + {!editData && ( - - - - } - label="مباشرین" - /> - } - label="اصناف" - /> - - - - - {buyerCategory && ( - - {(() => { - const currentData = - buyerCategory === "guilds" ? guildsData : stewardsData; - const isEmpty = !currentData || currentData.length === 0; - - if (isEmpty) { - return ( - - {buyerCategory === "guilds" - ? "هیچ صنفی یافت نشد" - : "هیچ مباشری یافت نشد"} - - ); - } - - return ( - { - return { - data: i, - label: `${i?.guildsName} ${i?.user?.fullname} (${i?.user?.mobile})`, - }; - }) - : stewardsData.map((i) => { - return { - data: i, - label: `${i?.name || ""} - ${ - i?.user?.fullname || "" - } (${i?.user?.mobile || ""})`, - }; - }) - } - onChange={(event, value) => { - if (buyerCategory === "guilds") { - setBuyerData({ - item: value?.data, - key: value?.data?.key, - allocationType: value?.data?.steward - ? "steward_steward" - : "steward_guild", - buyerType: value?.data?.steward - ? "Steward" - : "Guild", - }); - } else if (buyerCategory === "stewards") { - setBuyerData({ - item: value?.data, - key: value?.data?.key, - allocationType: "steward_steward", - buyerType: "Steward", - }); - } - }} - renderInput={(params) => ( - - )} - /> - ); - })()} - - )} - + + { + return { + data: i, + label: `${i?.steward ? "مباشر" : "صنف"} ${ + i?.guildsName + } ${i?.user?.fullname} (${i?.user?.mobile})`, + }; + }) + : [] + } + onChange={(event, value) => { + if (value) { + setSelectedBuyer({ + item: value?.data, + key: value?.data?.key, + }); + } else { + setSelectedBuyer(null); + } + }} + renderInput={(params) => ( + + )} + /> + )} {/* {!editData && ( @@ -625,8 +484,7 @@ export const StewardSegmentSubmitOperation = ({ !editData && (!productionDate || (selectedDateAmount && - formik.values.weight > selectedDateAmount) || - (segmentType === "free" && !buyerData?.key)) + formik.values.weight > selectedDateAmount)) } > {editData ? "ویرایش" : "ثبت"} diff --git a/src/features/guild/components/guild-psp-devices/AddAccessLevelModal.js b/src/features/guild/components/guild-psp-devices/AddAccessLevelModal.js deleted file mode 100644 index f3db663..0000000 --- a/src/features/guild/components/guild-psp-devices/AddAccessLevelModal.js +++ /dev/null @@ -1,141 +0,0 @@ -import { useContext, useState } from "react"; -import { useDispatch } from "react-redux"; -import { - Button, - FormControl, - Grid, - InputLabel, - MenuItem, - Select, - Typography, -} from "@mui/material"; -import axios from "axios"; -import { AppContext } from "../../../../contexts/AppContext"; -import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice"; -import { SPACING } from "../../../../data/spacing"; -import { getFaUserRole } from "../../../../utils/getFaUserRole"; - -export const AddAccessLevelModal = ({ device, onSuccess }) => { - const dispatch = useDispatch(); - const [openNotif] = useContext(AppContext); - const [selectedAccessLevel, setSelectedAccessLevel] = useState(""); - const [submitting, setSubmitting] = useState(false); - - const accessLevelOptions = ["Steward", "KillHouse", "Guilds"]; - - const handleCloseModal = () => { - dispatch(CLOSE_MODAL()); - }; - - const handleSubmit = async () => { - if (!selectedAccessLevel) { - openNotif({ - vertical: "top", - horizontal: "center", - severity: "error", - msg: "لطفاً یک سطح دسترسی را انتخاب کنید.", - }); - return; - } - - if (!device?.key && !device?.id) { - openNotif({ - vertical: "top", - horizontal: "center", - severity: "error", - msg: "شناسه دستگاه یافت نشد. لطفاً دوباره تلاش کنید.", - }); - return; - } - - setSubmitting(true); - try { - const payload = { - pos_key: device?.key || device?.id, - name: selectedAccessLevel, - }; - - await axios.post("/pos-access-level/", payload); - - openNotif({ - vertical: "top", - horizontal: "center", - severity: "success", - msg: "سطح دسترسی با موفقیت افزوده شد.", - }); - - if (onSuccess) { - onSuccess(); - } - handleCloseModal(); - } catch (error) { - openNotif({ - vertical: "top", - horizontal: "center", - severity: "error", - msg: - error?.response?.data?.result || - error?.response?.data?.detail || - "افزودن سطح دسترسی با خطا مواجه شد.", - }); - } finally { - setSubmitting(false); - } - }; - - return ( - - - دستگاه انتخاب شده:{" "} - {device?.serial || - device?.pos_unique_id || - device?.pos_id || - device?.posId || - "-"} - - - سطح دسترسی - - - - - - - - ); -}; diff --git a/src/features/guild/components/guild-psp-devices/AssignSubUserModal.js b/src/features/guild/components/guild-psp-devices/AssignSubUserModal.js deleted file mode 100644 index 7446ef9..0000000 --- a/src/features/guild/components/guild-psp-devices/AssignSubUserModal.js +++ /dev/null @@ -1,354 +0,0 @@ -import { useContext, useEffect, useState } from "react"; -import { useDispatch, useSelector } from "react-redux"; -import { - Autocomplete, - Button, - CircularProgress, - FormControl, - FormControlLabel, - Grid, - MenuItem, - Radio, - RadioGroup, - Select, - TextField, - Typography, -} from "@mui/material"; -import axios from "axios"; -import { AppContext } from "../../../../contexts/AppContext"; -import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice"; -import { LabelField } from "../../../../components/label-field/LabelField"; -import { SPACING } from "../../../../data/spacing"; -import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl"; -import { getFaUserRole } from "../../../../utils/getFaUserRole"; -import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; - -export const AssignSubUserModal = ({ device, onSuccess }) => { - const dispatch = useDispatch(); - const [openNotif] = useContext(AppContext); - const [options, setOptions] = useState([]); - const [selectedUser, setSelectedUser] = useState(null); - const [selectedAccessLevel, setSelectedAccessLevel] = useState(""); - const [loading, setLoading] = useState(false); - const [submitting, setSubmitting] = useState(false); - const [fetchError, setFetchError] = useState(""); - const [userType, setUserType] = useState("delegate"); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); - useEffect(() => { - let isMounted = true; - - const fetchUsers = async () => { - setLoading(true); - setFetchError(""); - setSelectedUser(null); - setSelectedAccessLevel(""); - try { - let response; - const role = getRoleFromUrl(); - - if (userType === "delegate") { - response = await axios.get( - `/get_representatives/?role=${role}${ - checkPathStartsWith("slaughter") || checkPathStartsWith("steward") - ? `&role_key=${selectedSubUser?.key}` - : "" - }` - ); - } else { - response = await axios.get( - `/get_dispensers/?role=${role}${ - checkPathStartsWith("slaughter") || checkPathStartsWith("steward") - ? `&role_key=${selectedSubUser?.key}` - : "" - }` - ); - } - - if (isMounted) { - const rawOptions = Array.isArray(response?.data?.results) - ? response?.data?.results - : Array.isArray(response?.data) - ? response?.data - : Array.isArray(response?.data?.data) - ? response?.data?.data - : Array.isArray(response) - ? response - : []; - - // Normalize the data - both delegates and dispensers have the same structure - const normalizedOptions = rawOptions.map((item) => { - const fullname = item?.fullname || "-"; - const mobile = item?.mobile || ""; - const mobileLabel = mobile ? ` (${mobile})` : ""; - const label = `${fullname}${mobileLabel}`; - - return { - ...item, - label: label || "-", - }; - }); - - setOptions(normalizedOptions); - } - } catch (error) { - if (isMounted) { - setFetchError("دریافت لیست کاربران با خطا مواجه شد."); - console.error("Error fetching users:", error); - } - } finally { - if (isMounted) { - setLoading(false); - } - } - }; - - fetchUsers(); - - return () => { - isMounted = false; - }; - }, [userType, selectedSubUser?.key]); - - const handleCloseModal = () => { - dispatch(CLOSE_MODAL()); - }; - - const getSubAccessLevels = (user) => { - if (!user) return []; - - const subAccessLevels = []; - - // Common excluded boolean fields that are not access levels - const excludedFields = [ - "active", - "trash", - "deleted", - "isActive", - "isDeleted", - ]; - - // Get all boolean fields that represent sub access levels - // These are fields in the object that are boolean and indicate sub access levels - Object.keys(user).forEach((key) => { - if (typeof user[key] === "boolean" && user[key] === true) { - // Exclude common boolean fields that aren't access levels - if (!excludedFields.includes(key.toLowerCase())) { - // Use getFaUserRole to get the Persian translation - const translatedLabel = getFaUserRole(key); - subAccessLevels.push({ - key: key, - label: translatedLabel || key, - }); - } - } - }); - - return subAccessLevels; - }; - - const handleSubmit = async () => { - if (!selectedUser) { - openNotif({ - vertical: "top", - horizontal: "center", - severity: "error", - msg: "لطفاً یک کاربر را انتخاب کنید.", - }); - return; - } - - if (!device?.key && !device?.id) { - openNotif({ - vertical: "top", - horizontal: "center", - severity: "error", - msg: "شناسه دستگاه یافت نشد. لطفاً دوباره تلاش کنید.", - }); - return; - } - - setSubmitting(true); - try { - const payload = { - key: device?.key || device?.id, - recipient_type: - userType === "delegate" ? "representative" : "dispenser", - recipient_key: selectedUser?.key || selectedUser?.id, - }; - - await axios.put("/user-pos-machine/0/", payload); - - openNotif({ - vertical: "top", - horizontal: "center", - severity: "success", - msg: "دستگاه با موفقیت به کاربر فرعی اختصاص داده شد.", - }); - - if (onSuccess) { - onSuccess(); - } - handleCloseModal(); - } catch (error) { - openNotif({ - vertical: "top", - horizontal: "center", - severity: "error", - msg: - error?.response?.data?.result || - error?.response?.data?.detail || - "اختصاص دستگاه با خطا مواجه شد.", - }); - } finally { - setSubmitting(false); - } - }; - - const selectedUserSubAccessLevels = selectedUser - ? getSubAccessLevels(selectedUser) - : []; - - return ( - - - دستگاه انتخاب شده:{" "} - {device?.serial || - device?.pos_unique_id || - device?.pos_id || - device?.posId || - "-"} - - - - setUserType(e.target.value)} - > - } - label="نماینده‌ها" - /> - } - label="پخش‌کنندگان" - /> - - - - {loading ? ( - - - - ) : ( - { - setSelectedUser(value); - setSelectedAccessLevel(""); - }} - isOptionEqualToValue={(option, value) => - option?.key === value?.key || option?.id === value?.id - } - getOptionLabel={(option) => option?.label || ""} - renderOption={(props, option) => { - if (!option) return null; - return ( -
  • - - - {option?.label || "-"} - - {option?.city && ( - - {option.city} - - )} - -
  • - ); - }} - renderInput={(params) => ( - - {loading ? ( - - ) : null} - {params.InputProps.endAdornment} - - ), - }} - /> - )} - /> - )} - {fetchError && ( - - {fetchError} - - )} - {selectedUser && selectedUserSubAccessLevels.length > 0 && ( - - - - )} - - - - -
    - ); -}; diff --git a/src/features/guild/components/guild-psp-devices/DeviceOperations.js b/src/features/guild/components/guild-psp-devices/DeviceOperations.js deleted file mode 100644 index cb4ac01..0000000 --- a/src/features/guild/components/guild-psp-devices/DeviceOperations.js +++ /dev/null @@ -1,266 +0,0 @@ -import { useContext, useState } from "react"; -import { useDispatch } from "react-redux"; -import { - Box, - Grid, - IconButton, - List, - ListItemButton, - ListItemIcon, - ListItemText, - Popover, - Typography, - Button, -} from "@mui/material"; -import TuneIcon from "@mui/icons-material/Tune"; -import PersonAddAlt1RoundedIcon from "@mui/icons-material/PersonAddAlt1Rounded"; -import AddIcon from "@mui/icons-material/Add"; -import EditIcon from "@mui/icons-material/Edit"; -import DeleteIcon from "@mui/icons-material/Delete"; -import { AppContext } from "../../../../contexts/AppContext"; -import { - LOADING_START, - LOADING_END, - CLOSE_MODAL, - OPEN_MODAL, -} from "../../../../lib/redux/slices/appSlice"; -import axios from "axios"; -import { getFaUserRole } from "../../../../utils/getFaUserRole"; -import { AssignSubUserModal } from "./AssignSubUserModal"; -import { AddAccessLevelModal } from "./AddAccessLevelModal"; -import { EditSubSectionsModal } from "./EditSubSectionsModal"; - -export const DeviceOperations = ({ - device, - onSubUserAssigned, - fetchApiData, - page, -}) => { - const [anchorEl, setAnchorEl] = useState(null); - const dispatch = useDispatch(); - const [openNotif] = useContext(AppContext); - - const handleOpen = (event) => { - setAnchorEl(event.currentTarget); - }; - - const handleClose = () => { - setAnchorEl(null); - }; - - const handleAssignSubUser = () => { - handleClose(); - dispatch( - OPEN_MODAL({ - title: "اختصاص دستگاه به کاربر فرعی", - width: "auto", - content: ( - - ), - }) - ); - }; - - const handleAddAccessLevel = () => { - handleClose(); - dispatch( - OPEN_MODAL({ - title: "افزودن سطح دسترسی", - width: "auto", - content: ( - - ), - }) - ); - }; - - const handleEditSubSections = (accessLevel) => { - handleClose(); - dispatch( - OPEN_MODAL({ - title: "ویرایش زیربخش‌های سطح دسترسی", - width: "auto", - content: ( - fetchApiData(page)} - /> - ), - }) - ); - }; - - const handleDeleteAccessLevel = (accessLevel) => { - handleClose(); - dispatch( - OPEN_MODAL({ - title: "حذف سطح دسترسی", - size: 320, - content: ( - - - - آیا از حذف سطح دسترسی{" "} - {getFaUserRole(accessLevel?.name) || accessLevel?.name} مطمئن - هستید؟ - - - - - - - - - - ), - }) - ); - }; - - const open = Boolean(anchorEl); - const id = open ? "device-operations-popover" : undefined; - - const accessLevels = Array.isArray(device?.accessLevels) - ? device.accessLevels.filter((level) => !level?.trash) - : []; - - return ( - <> - - - - - - - - - - - - - - - - - - {accessLevels.length > 0 && ( - <> - - - مدیریت سطح دسترسی: - - - {accessLevels.map((level, idx) => ( - - - - {getFaUserRole(level?.name) || level?.name || "-"} - - - handleEditSubSections(level)} - > - - - handleDeleteAccessLevel(level)} - > - - - - - - ))} - - )} - - - - ); -}; diff --git a/src/features/guild/components/guild-psp-devices/EditSubSectionsModal.js b/src/features/guild/components/guild-psp-devices/EditSubSectionsModal.js deleted file mode 100644 index 3cc4cd1..0000000 --- a/src/features/guild/components/guild-psp-devices/EditSubSectionsModal.js +++ /dev/null @@ -1,202 +0,0 @@ -import { useContext, useState } from "react"; -import { useDispatch } from "react-redux"; -import { - Button, - Checkbox, - FormControlLabel, - Grid, - Typography, -} from "@mui/material"; -import axios from "axios"; -import { AppContext } from "../../../../contexts/AppContext"; -import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice"; -import { LabelField } from "../../../../components/label-field/LabelField"; -import { SPACING } from "../../../../data/spacing"; -import { getFaUserRole } from "../../../../utils/getFaUserRole"; - -export const EditSubSectionsModal = ({ accessLevel, device, onSuccess }) => { - const dispatch = useDispatch(); - const [openNotif] = useContext(AppContext); - const [submitting, setSubmitting] = useState(false); - const [values, setValues] = useState({ - in_province_sale: accessLevel?.in_province_sale || false, - out_province_sale: accessLevel?.out_province_sale || false, - cutting: accessLevel?.cutting || false, - freezing: accessLevel?.freezing || false, - warehouse: accessLevel?.warehouse || false, - retail: accessLevel?.retail || false, - }); - - const handleCloseModal = () => { - dispatch(CLOSE_MODAL()); - }; - - const handleChange = (field) => (event) => { - setValues((prev) => ({ - ...prev, - [field]: event.target.checked, - })); - }; - - const handleSubmit = async () => { - if (!accessLevel?.key) { - openNotif({ - vertical: "top", - horizontal: "center", - severity: "error", - msg: "شناسه سطح دسترسی یافت نشد. لطفاً دوباره تلاش کنید.", - }); - return; - } - - setSubmitting(true); - try { - const payload = { - key: accessLevel.key, - in_province_sale: values.in_province_sale, - out_province_sale: values.out_province_sale, - cutting: values.cutting, - freezing: values.freezing, - warehouse: values.warehouse, - retail: values.retail, - }; - - await axios.put("/pos-access-level/0/", payload); - - openNotif({ - vertical: "top", - horizontal: "center", - severity: "success", - msg: "زیربخش‌های سطح دسترسی با موفقیت ویرایش شد.", - }); - - if (onSuccess) { - onSuccess(); - } - handleCloseModal(); - } catch (error) { - openNotif({ - vertical: "top", - horizontal: "center", - severity: "error", - msg: - error?.response?.data?.result || - error?.response?.data?.detail || - "ویرایش زیربخش‌ها با خطا مواجه شد.", - }); - } finally { - setSubmitting(false); - } - }; - - return ( - - - سطح دسترسی:{" "} - {getFaUserRole(accessLevel?.name) || accessLevel?.name || "-"} - - - دستگاه:{" "} - {device?.serial || - device?.pos_unique_id || - device?.pos_id || - device?.posId || - "-"} - - - - - - } - label="فروش داخل استان" - /> - - - - } - label="فروش خارج استان" - /> - - - - } - label="قطعه بندی" - /> - - - - } - label="انجماد" - /> - - - - } - label="انبار" - /> - - - - } - label="خرده‌فروشی" - /> - - - - - - - - - ); -}; diff --git a/src/features/guild/components/guild-psp-devices/GuildPspDevices.js b/src/features/guild/components/guild-psp-devices/GuildPspDevices.js deleted file mode 100644 index d639e0b..0000000 --- a/src/features/guild/components/guild-psp-devices/GuildPspDevices.js +++ /dev/null @@ -1,284 +0,0 @@ -import { useEffect, useState } from "react"; -import { useDispatch, useSelector } from "react-redux"; -import { - LOADING_END, - LOADING_START, -} from "../../../../lib/redux/slices/appSlice"; -import axios from "axios"; -import { Grid } from "../../../../components/grid/Grid"; -import { SPACING } from "../../../../data/spacing"; -import { BackButton } from "../../../../components/back-button/BackButton"; -import { Autocomplete, Button, TextField, Box, Chip } from "@mui/material"; -import { RiSearchLine } from "react-icons/ri"; -import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable"; -import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl"; -import { formatJustDate } from "../../../../utils/formatTime"; -import { getFaUserRole } from "../../../../utils/getFaUserRole"; -import { DeviceOperations } from "./DeviceOperations"; -import { Lock } from "@mui/icons-material"; -import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; - -const GuildPspDevices = () => { - const [data, setData] = useState([]); - const [totalRows, setTotalRows] = useState(0); - const [perPage, setPerPage] = useState(10); - const [textValue, setTextValue] = useState(""); - const [page, setPage] = useState(1); - const [tableData, setTableData] = useState([]); - const [brands, setBrands] = useState([]); - const [selectedBrand, setSelectedBrand] = useState(""); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); - const dispatch = useDispatch(); - - const fetchBrands = async () => { - try { - dispatch(LOADING_START()); - const response = await axios.get( - `/get_all_pos_company/?role=${getRoleFromUrl()}${ - checkPathStartsWith("slaughter") || checkPathStartsWith("steward") - ? `&role_key=${selectedSubUser?.key}` - : "" - }` - ); - setBrands(response.data); - dispatch(LOADING_END()); - } catch (error) { - console.error("Error fetching brands:", error); - dispatch(LOADING_END()); - } - }; - - const canDoAction = (item) => { - if (item?.owner?.role?.includes("KillHouse")) { - return getRoleFromUrl() === "KillHouse"; - } - if (item?.owner?.includes("Steward")) { - return getRoleFromUrl() === "Steward"; - } - return false; - }; - - const fetchApiData = async (page) => { - try { - dispatch(LOADING_START()); - let url = `/user-pos-machine/?search=filter&value=${textValue}&role=${getRoleFromUrl()}${ - checkPathStartsWith("slaughter") || checkPathStartsWith("steward") - ? `&role_key=${selectedSubUser?.key}` - : "" - }&page=${page}&page_size=${perPage}`; - if (selectedBrand) { - url += `&company=${selectedBrand}`; - } - const response = await axios.get(url); - - setData(response.data?.results || []); - setTotalRows(response.data?.count || 0); - } catch (error) { - console.error("Error fetching devices:", error); - } finally { - dispatch(LOADING_END()); - } - }; - - const handlePageChange = (page) => { - fetchApiData(page); - setPage(page); - }; - - const handlePerRowsChange = (perRows) => { - setPerPage(perRows); - setPage(1); - }; - - const handleTextChange = (event) => { - setTextValue(event.target.value); - }; - - useEffect(() => { - const d = data?.map((item, i) => { - const owner = item?.owner || {}; - const posCompany = item?.posCompany || {}; - - // Format recipient information - const recipientDisplay = item?.recipient - ? `${item?.recipient?.firstName || ""} ${ - item?.recipient?.lastName || "" - }`.trim() + - (item?.recipient?.mobile - ? ` (${item?.recipient?.mobile} - ${ - item?.recipient?.agentType === "dispenser" - ? "توزیع کننده" - : "نماینده" - })` - : "") - : "-"; - - // Format access_levels to display as chips only (filter out trash items) - const activeAccessLevels = Array.isArray(item?.accessLevels) - ? item.accessLevels.filter((level) => !level?.trash) - : []; - const accessLevelsDisplay = - activeAccessLevels.length > 0 ? ( - - {activeAccessLevels.map((level, idx) => ( - - ))} - - ) : ( - "-" - ); - - return [ - page === 1 ? i + 1 : i + perPage * (page - 1) + 1, - posCompany?.name || "-", - item?.serial ?? "-", - item?.receiverNumber ?? "-", - item?.terminalNumber ?? "-", - item?.password ?? "-", - item?.posUniqueId || item?.posId || "-", - owner?.fullname ? `${owner?.fullname} (${owner?.mobile ?? "-"})` : "-", - owner?.nationalId || owner?.nationalCode || "-", - item?.createDate ? formatJustDate(item?.createDate) : "-", - accessLevelsDisplay, - recipientDisplay, - item?.active ? "فعال" : "غیرفعال", - canDoAction(item) ? ( - - ) : ( - - ), - ]; - }); - - setTableData(d); - }, [data, page, perPage]); - - useEffect(() => { - fetchBrands(); - }, [dispatch, selectedSubUser?.key]); - - useEffect(() => { - fetchApiData(page); - }, [selectedBrand, perPage, selectedSubUser?.key]); - - const handleSubmit = async (event) => { - event.preventDefault(); - fetchApiData(1); - }; - - const tableTitle = ( - - - - { - return { - data: i, - label: `${i?.name || ""}`, - }; - }) - : [] - } - onChange={(event, value) => { - setSelectedBrand(value?.data?.key); - }} - renderInput={(params) => ( - - )} - /> - - - - - - - - - - ); - - return ( - - - - {tableTitle} - - - - ); -}; - -export default GuildPspDevices; diff --git a/src/features/guild/services/guild-get-inventory-allocated.js b/src/features/guild/services/guild-get-inventory-allocated.js index 9c4378a..9e567aa 100644 --- a/src/features/guild/services/guild-get-inventory-allocated.js +++ b/src/features/guild/services/guild-get-inventory-allocated.js @@ -7,7 +7,7 @@ export const guildGetInventoryAllocatedService = createAsyncThunk( async (d, { dispatch }) => { dispatch(LOADING_START()); const { data, status } = await axios.get("steward-allocation/", { - params: { date: d.date, steward: true, role_key: d.role_key || "" }, + params: { date: d.date, steward: true }, }); dispatch(LOADING_END()); return { data, status }; diff --git a/src/features/guild/services/guild-get-inventory-stock.js b/src/features/guild/services/guild-get-inventory-stock.js index 5fc9aa2..45798c5 100644 --- a/src/features/guild/services/guild-get-inventory-stock.js +++ b/src/features/guild/services/guild-get-inventory-stock.js @@ -7,7 +7,7 @@ export const guildGetInventoryStockService = createAsyncThunk( async (d, { dispatch }) => { dispatch(LOADING_START()); const { data, status } = await axios.get("steward_warehouse/", { - params: { date: d.date, role_key: d.role_key || "" }, + params: { date: d.date }, }); dispatch(LOADING_END()); return { data, status }; diff --git a/src/features/guild/services/guild-sales-info-dashboard.js b/src/features/guild/services/guild-sales-info-dashboard.js deleted file mode 100644 index ec43597..0000000 --- a/src/features/guild/services/guild-sales-info-dashboard.js +++ /dev/null @@ -1,24 +0,0 @@ -import { createAsyncThunk } from "@reduxjs/toolkit"; -import axios from "axios"; -import { LOADING_END, LOADING_START } from "../../../lib/redux/slices/appSlice"; -import { getRoleFromUrl } from "../../../utils/getRoleFromUrl"; - -export const guildSalesInfoDashboardService = createAsyncThunk( - "GUILD_SALES_INFO_DASHBOARD_SERVICE", - async (d, { dispatch }) => { - dispatch(LOADING_START()); - try { - const { data, status } = await axios.get("guild-sales-info-dashboard/", { - params: { - role: d.role || getRoleFromUrl(), - role_key: d.role_key || "", - }, - }); - dispatch(LOADING_END()); - return { data, status }; - } catch (e) { - dispatch(LOADING_END()); - return { error: e.response?.data?.result }; - } - } -); diff --git a/src/features/guild/services/senf-get-allocation-dashboard.js b/src/features/guild/services/senf-get-allocation-dashboard.js deleted file mode 100644 index 239d67c..0000000 --- a/src/features/guild/services/senf-get-allocation-dashboard.js +++ /dev/null @@ -1,15 +0,0 @@ -import { createAsyncThunk } from "@reduxjs/toolkit"; -import axios from "axios"; -import { LOADING_END, LOADING_START } from "../../../lib/redux/slices/appSlice"; - -export const senfGetAllocationDashboardService = createAsyncThunk( - "SENF_GET_ALLOCATION_DASHBOARD_SERVICE", - async (d, { dispatch }) => { - dispatch(LOADING_START()); - const { data, status } = await axios.get("guild-allocation-dashbord/", { - params: d, - }); - dispatch(LOADING_END()); - return { data, status }; - } -); diff --git a/src/features/guild/services/senf-get-inventory-allocated.js b/src/features/guild/services/senf-get-inventory-allocated.js index a5ae66a..424de44 100644 --- a/src/features/guild/services/senf-get-inventory-allocated.js +++ b/src/features/guild/services/senf-get-inventory-allocated.js @@ -1,21 +1,13 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; import axios from "axios"; import { LOADING_END, LOADING_START } from "../../../lib/redux/slices/appSlice"; -import { getRoleFromUrl } from "../../../utils/getRoleFromUrl"; export const senfGetInventoryAllocatedService = createAsyncThunk( "SENF_GET_INVENTORY_ALLOCATED_SERVICE", async (d, { dispatch }) => { dispatch(LOADING_START()); const { data, status } = await axios.get("steward-allocation/", { - params: { - date1: d.date1, - date2: d.date2, - type: d.type || "", - role_key: d.role_key || "", - role: getRoleFromUrl(), - search: d.search, - }, + params: { date: d.date, guild: true }, }); dispatch(LOADING_END()); return { data, status }; diff --git a/src/features/guild/services/senf-get-inventory-stock.js b/src/features/guild/services/senf-get-inventory-stock.js index 0022790..9aea666 100644 --- a/src/features/guild/services/senf-get-inventory-stock.js +++ b/src/features/guild/services/senf-get-inventory-stock.js @@ -7,7 +7,7 @@ export const senfGetInventoryStockService = createAsyncThunk( async (d, { dispatch }) => { dispatch(LOADING_START()); const { data, status } = await axios.get("guilds_warehouse/", { - params: d, + params: { date: d.date }, }); dispatch(LOADING_END()); return { data, status }; diff --git a/src/features/guild/services/steward-get-out-dashboard.js b/src/features/guild/services/steward-get-out-dashboard.js index 50d45dd..1760123 100644 --- a/src/features/guild/services/steward-get-out-dashboard.js +++ b/src/features/guild/services/steward-get-out-dashboard.js @@ -1,7 +1,6 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; import { LOADING_END, LOADING_START } from "../../../lib/redux/slices/appSlice"; import axios from "axios"; -import { getRoleFromUrl } from "../../../utils/getRoleFromUrl"; export const stawardGetOutDashboardService = createAsyncThunk( "STEWARD-GET-OUT_DASHBOARD_SERVICE", @@ -10,7 +9,6 @@ export const stawardGetOutDashboardService = createAsyncThunk( const { data, status } = await axios.get("steward_free_bar_dashboard", { params: { ...d, - role: getRoleFromUrl(), }, }); dispatch(LOADING_END()); diff --git a/src/features/guild/services/steward-get-sell-out-service.js b/src/features/guild/services/steward-get-sell-out-service.js index 5208da9..2e666eb 100644 --- a/src/features/guild/services/steward-get-sell-out-service.js +++ b/src/features/guild/services/steward-get-sell-out-service.js @@ -7,12 +7,9 @@ export const stewardGetOutSellService = createAsyncThunk( "STEWRD_GET_OUT_SELL_SERVICE", async (d, { dispatch }) => { dispatch(LOADING_START()); - const { data, status } = await axios.get("roles-products", { - params: { - role: getRoleFromUrl(), - ...d, - }, - }); + const { data, status } = await axios.get( + "roles-products/?role=" + getRoleFromUrl() + ); dispatch(LOADING_END()); return { data, status }; } diff --git a/src/features/guild/services/steward-sell-out-get-buyers.js b/src/features/guild/services/steward-sell-out-get-buyers.js index a0cdcc6..a700baf 100644 --- a/src/features/guild/services/steward-sell-out-get-buyers.js +++ b/src/features/guild/services/steward-sell-out-get-buyers.js @@ -5,14 +5,10 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; export const stewardSellOutGetBuyers = createAsyncThunk( "STEWARD_GET_BUYERS_SELL_OUT", - async (d, { dispatch }) => { + async (id, { dispatch }) => { dispatch(LOADING_START()); const { data, status } = await axios.get("out-province-carcasses-buyer/", { - params: { - role: getRoleFromUrl(), - role_key: d?.role_key || "", - mobile: d?.mobile, - }, + params: { role: getRoleFromUrl() }, }); dispatch(LOADING_END()); return { data, status }; diff --git a/src/features/guild/services/steward-sell-out-get-dashboard.js b/src/features/guild/services/steward-sell-out-get-dashboard.js index 92ec464..105f9b5 100644 --- a/src/features/guild/services/steward-sell-out-get-dashboard.js +++ b/src/features/guild/services/steward-sell-out-get-dashboard.js @@ -14,7 +14,6 @@ export const stewardSellOutGetDashboard = createAsyncThunk( date1: d.selectedDate1, date2: d.selectedDate2, role: getRoleFromUrl(), - role_key: d.role_key || "", }, } ); diff --git a/src/features/province-jahad/components/province-jahad-bran-distributions-allocation/ProvinceJahadBranDistributionsAllocation.js b/src/features/province-jahad/components/province-jahad-bran-distributions-allocation/ProvinceJahadBranDistributionsAllocation.js index b777ed9..d1a8497 100644 --- a/src/features/province-jahad/components/province-jahad-bran-distributions-allocation/ProvinceJahadBranDistributionsAllocation.js +++ b/src/features/province-jahad/components/province-jahad-bran-distributions-allocation/ProvinceJahadBranDistributionsAllocation.js @@ -57,7 +57,7 @@ export const ProvinceJahadBranDistributionsAllocation = ({ product }) => { return ( - + { return ( {getRoleFromUrl() === "LiveStockProvinceJahad" && ( - + { - + { - + { - + { + if (!gregorianDateString || typeof gregorianDateString !== "string") { + return ""; + } + + // Check if the date is already in Persian format (YYYY/MM/DD with year < 1500) + const persianPattern = /^\d{4}\/\d{2}\/\d{2}$/; + if (persianPattern.test(gregorianDateString)) { + const year = parseInt(gregorianDateString.split("/")[0]); + // If year is < 1500, it's likely Persian, return as is + if (year < 1500) { + return gregorianDateString; + } + } + + // Try to convert using convertToIranianTime + try { + return convertToIranianTime(gregorianDateString); + } catch (error) { + console.error("Error converting Gregorian date to Persian:", error); + return gregorianDateString; // Return original on error + } +}; + +const convertPersianToGregorian = (persianDateString) => { + if (!persianDateString || typeof persianDateString !== "string") { + return ""; + } + + const normalizedDateString = + convertPersianToEnglishNumerals(persianDateString); + + const gregorianPattern = /^\d{4}[-/]\d{2}[-/]\d{2}$/; + if (gregorianPattern.test(normalizedDateString)) { + const year = parseInt(normalizedDateString.split(/[-/]/)[0]); + if (year > 1500) { + return normalizedDateString.replace(/\//g, "-"); + } + } + + const parts = normalizedDateString.split("/"); + if (parts.length !== 3) { + return persianDateString; + } + + const py = parseInt(parts[0]); + const pm = parseInt(parts[1]); + const pd = parseInt(parts[2]); + + if (isNaN(py) || isNaN(pm) || isNaN(pd)) { + return persianDateString; + } + + try { + const gregorianDate = fromJalali(py, pm, pd); + const year = gregorianDate.getFullYear(); + const month = String(gregorianDate.getMonth() + 1).padStart(2, "0"); + const day = String(gregorianDate.getDate()).padStart(2, "0"); + return `${year}-${month}-${day}`; + } catch (error) { + console.error("Error converting Persian date to Gregorian:", error); + return persianDateString; + } +}; + +const normalizeExternalApiDate = (dateString) => { + if (!dateString || typeof dateString !== "string") { + return ""; + } + return convertPersianToEnglishNumerals(dateString); +}; + +const normalizeDatabaseDate = (dateString) => { + if (!dateString || typeof dateString !== "string") { + return ""; + } + const first10Chars = dateString.substring(0, 10); + const normalizedDate = first10Chars.replace(/-/g, "/"); + return convertToIranianTime(normalizedDate); +}; + +const formatDateForSubmitExternal = (dateString) => { + if (!dateString || typeof dateString !== "string") { + return ""; + } + return convertPersianToEnglishNumerals(dateString); +}; + +const formatDateForSubmitDatabase = (dateString) => { + if (!dateString || typeof dateString !== "string") { + return ""; + } + + const normalizedDate = convertPersianToEnglishNumerals(dateString); + const persianPattern = /^\d{4}\/\d{2}\/\d{2}$/; + + if (persianPattern.test(normalizedDate)) { + const year = parseInt(normalizedDate.split("/")[0]); + if (year < 1500) { + const parts = normalizedDate.split("/"); + const py = parseInt(parts[0]); + const pm = parseInt(parts[1]); + const pd = parseInt(parts[2]); + + if (!isNaN(py) && !isNaN(pm) && !isNaN(pd)) { + try { + const gregorianDate = fromJalali(py, pm, pd); + const gy = gregorianDate.getFullYear(); + const gm = String(gregorianDate.getMonth() + 1).padStart(2, "0"); + const gd = String(gregorianDate.getDate()).padStart(2, "0"); + return `${gy}/${gm}/${gd}`; + } catch (error) { + console.error("Error converting Persian to Gregorian:", error); + } + } + } + } + + const gregorianPattern = /^\d{4}[-/]\d{2}[-/]\d{2}$/; + if (gregorianPattern.test(normalizedDate)) { + const year = parseInt(normalizedDate.split(/[-/]/)[0]); + if (year > 1900) { + return normalizedDate.replace(/-/g, "/"); + } + } + + try { + const date = new Date(normalizedDate); + if (!isNaN(date.getTime())) { + const year = date.getFullYear(); + const month = String(date.getMonth() + 1).padStart(2, "0"); + const day = String(date.getDate()).padStart(2, "0"); + return `${year}/${month}/${day}`; + } + } catch (error) { + console.error("Error formatting database date:", error); + } + + return normalizedDate.replace(/-/g, "/"); +}; + +const getValidationSchema = (isEditMode) => + yup.object({ + national_id: yup + .string() + .required("کد ملی الزامی است") + .matches(/^[0-9]{10}$/, "کد ملی باید 10 رقم باشد"), + mobile: isEditMode + ? yup + .string() + .nullable() + .test( + "mobile-format", + "شماره تلفن باید 11 رقم باشد", + (value) => !value || /^[0-9]{11}$/.test(value) + ) + : yup + .string() + .required("شماره تلفن الزامی است") + .matches(/^[0-9]{11}$/, "شماره تلفن باید 11 رقم باشد"), + first_name: yup.string(), + last_name: yup.string(), + guild_name: yup.string(), + guild_category: yup.string(), + state: yup.string(), + city: yup.string(), + address: yup.string(), + license_expire_date: yup.string(), + license_status: yup.string(), + union_name: yup.string(), + postal_code: yup.string(), + guild_national_id: yup.string(), + is_foreigner: yup.string(), + national_code: yup.string(), + has_steward: yup.string(), + has_partner: yup.string(), + license_number: yup.string(), + isAccepted: yup + .boolean() + .test("req", "باید تعهد نامه را بپذیرید!", (val) => { + return val === true; + }) + .required("این فیلد اجباری است!"), + }); + +const getInitialValues = (guild) => ({ + first_name: guild?.user?.firstName || "", + last_name: guild?.user?.lastName || "", + corporation_name: guild?.companyName || "", + national_id: guild?.user?.nationalId || "", + national_code: guild?.user?.nationalCode || "", + birth_date: normalizeDatabaseDate(guild?.user?.birthday || ""), + father_name: guild?.user?.fatherName || "", + gender: guild?.user?.gender || "", + person_city: guild?.user?.city || "", + is_alive: guild?.user?.isAlive || "", + guild_name: guild?.guildsName || "", + area_activity: guild?.areaActivity || "", + state: guild?.address?.province?.name || "", + city: guild?.address?.city?.name || "", + address: guild?.address?.address || "", + license_expire_date: normalizeDatabaseDate(guild?.licenseExpireDate || ""), + license_status: guild?.licenseStatus || "", + license_type: guild?.licenseType || "", + union_name: guild?.unionName || "", + postal_code: guild?.address?.postalCode || "", + phone_number: guild?.phoneNumber || "", + mobile: guild?.user?.mobile || "", + is_foreigner: guild?.is_foreign_national || "", + has_steward: guild?.hasSteward || "", + has_partner: guild?.hasPartner || "", + license_number: guild?.licenseNumber || "", + isAccepted: guild?.provinceAcceptState === "accepted" || false, + steward: guild?.steward || false, + verify_mobile: guild?.verifyMobile || false, + guild_national_id: guild?.nationalId || "", + license_issue_date: normalizeDatabaseDate(guild?.licenseIssueDate || ""), + company_name: guild?.companyName || "", + company_identifier: guild?.companyIdentifier || "", + type_activity_name: guild?.typeActivityName || "", + active: guild?.active ?? null, +}); + +const formatDateForSubmit = (dateString, isExternalApi = false) => { + if (!dateString || typeof dateString !== "string") { + return ""; + } + + if (isExternalApi) { + return formatDateForSubmitExternal(dateString); + } else { + return formatDateForSubmitDatabase(dateString); + } +}; + +const prepareSubmitData = (values, guild, originalPhoneNumber, hasInquiry) => { + const baseData = { + national_id: values.national_id, + mobile: values.mobile, + mobilenumber: values.mobile, + steward: !!values.steward, + active_register_code: !!values.verify_mobile, + firstName: values.first_name || "", + lastName: values.last_name || "", + fatherName: values.father_name || "", + gender: values.gender || "", + identityNo: values.national_code || "", + isLive: values.is_alive === "بلی" || values.is_alive === true, + birthDate: formatDateForSubmit( + values.birth_date || "", + hasInquiry === true + ), + city: values.city || "", + address: values.address || "", + postalcode: values.postal_code || "", + licenseNumber: values.license_number || "", + licenseExpireDate: formatDateForSubmit( + values.license_expire_date || "", + hasInquiry === true + ), + licenseIssueDate: formatDateForSubmit( + values.license_issue_date || "", + hasInquiry === true + ), + licenseType: values.license_type || "", + licenseStatus: values.license_status || "", + isicname: values.area_activity || "", + corporationName: values.corporation_name || "", + nationalId: values.guild_national_id || "", + unionName: values.union_name || "", + phonenumber: values.phone_number || "", + hasPartner: values.has_partner === true || values.has_partner === "بلی", + isForeigner: values.is_foreigner === true || values.is_foreigner === "بلی", + title: values.guild_name || "", + role: getRoleFromUrl(), + has_inquiry: hasInquiry !== null ? hasInquiry : false, + ...(values.active !== null && { active: values.active }), + }; + + if (guild) { + baseData.guilds_key = guild.key; + if (values.mobile !== originalPhoneNumber) { + baseData.mobile = values.mobile; + baseData.mobilenumber = values.mobile; + } + } + + return baseData; +}; + +const mapResponseDataToFormFields = ( + responseData, + inquiryNationalCode, + formik +) => { + const isExternalApi = responseData.dbRegister === false; + + const userData = responseData.user || {}; + const guildData = responseData.guild || {}; + const layerTwo = guildData.layerTwo || {}; + const addressData = responseData.address || {}; + const provinceData = addressData.province || {}; + const cityData = addressData.city || {}; + + const nationalIdValue = isExternalApi + ? String( + layerTwo.nationalcode || userData.nationalCode || inquiryNationalCode + ).trim() + : String(userData.nationalId || inquiryNationalCode).trim(); + + const birthDatePersian = isExternalApi + ? normalizeExternalApiDate(userData.birthDate || "") + : normalizeDatabaseDate(userData.birthday || ""); + + const licenseExpireDatePersian = isExternalApi + ? normalizeExternalApiDate(guildData.licenseExpireDate || "") + : normalizeDatabaseDate(responseData.licenseExpireDate || ""); + + const licenseIssueDatePersian = isExternalApi + ? normalizeExternalApiDate(layerTwo.licenseIssueDate || "") + : normalizeDatabaseDate(responseData.licenseIssueDate || ""); + + const genderValue = isExternalApi + ? userData.gender === true + ? "True" + : userData.gender === false + ? "False" + : "" + : userData.gender || ""; + + const isAliveValue = isExternalApi + ? userData.isLive === true + ? "بلی" + : userData.isLive === false + ? "خیر" + : "" + : userData.isAlive === false + ? "خیر" + : userData.isAlive === true + ? "بلی" + : ""; + + const isForeignerValue = isExternalApi + ? layerTwo.isForeigner === "خیر" + ? false + : layerTwo.isForeigner === "بلی" + ? true + : "" + : responseData.isForeignNational === false + ? false + : responseData.isForeignNational === true + ? true + : ""; + + const hasStewardValue = isExternalApi + ? layerTwo.hasSteward === "خیر" + ? false + : layerTwo.hasSteward === "بلی" + ? true + : "" + : responseData.steward === false + ? false + : responseData.steward === true + ? true + : ""; + + const hasPartnerValue = isExternalApi + ? layerTwo.hasPartner === "خیر" + ? false + : layerTwo.hasPartner === "بلی" + ? true + : "" + : responseData.hasPartner === false + ? false + : responseData.hasPartner === true + ? true + : ""; + + const values = { + first_name: userData.firstName || "", + last_name: userData.lastName || "", + national_id: nationalIdValue, + national_code: isExternalApi + ? userData.identityNo || "" + : userData.nationalCode || "", + birth_date: birthDatePersian, + father_name: userData.fatherName || "", + gender: genderValue, + person_city: userData.city || "", + is_alive: isAliveValue, + guild_name: isExternalApi + ? guildData.title || "" + : responseData.guildsName || "", + area_activity: isExternalApi + ? guildData.isicname || "" + : responseData.areaActivity || "", + state: isExternalApi ? guildData.state || "" : provinceData.name || "", + city: isExternalApi ? guildData.city || "" : cityData.name || "", + address: isExternalApi + ? guildData.address || "" + : addressData.address || "", + license_expire_date: licenseExpireDatePersian, + license_status: isExternalApi + ? guildData.licenseStatus || "" + : responseData.licenseStatus || "", + license_type: isExternalApi + ? guildData.licenseType || "" + : responseData.licenseType || "", + license_number: isExternalApi + ? guildData.licenseNumber || "" + : responseData.licenseNumber || "", + union_name: isExternalApi + ? layerTwo.unionName || "" + : responseData.unionName || "", + postal_code: isExternalApi + ? layerTwo.postalcode || "" + : addressData.postalCode || "", + phone_number: isExternalApi + ? layerTwo.phonenumber || "" + : responseData.phoneNumber || "", + mobile: isExternalApi ? layerTwo.mobilenumber || "" : userData.mobile || "", + guild_national_id: isExternalApi + ? layerTwo.nationalId || "" + : responseData.nationalCode || "", + is_foreigner: isForeignerValue, + corporation_name: isExternalApi + ? layerTwo.corporationName || "" + : responseData.companyName || "", + has_steward: hasStewardValue, + has_partner: hasPartnerValue, + steward: isExternalApi ? false : responseData.steward || false, + license_issue_date: licenseIssueDatePersian, + ...(isExternalApi + ? {} + : { + company_name: responseData.companyName || "", + company_identifier: responseData.companyIdentifier || "", + type_activity_name: responseData.typeActivity || "", + }), + }; + + formik.setValues({ ...formik.values, ...values }); +}; + +const handleSubmitSuccess = ( + dispatch, + openNotif, + updateTable, + values, + responseData +) => { + updateTable(); + openNotif({ + vertical: "top", + horizontal: "center", + msg: "عملیات با موفقیت انجام شد.", + severity: "success", + }); + dispatch(CLOSE_MODAL()); + + if (values.verify_mobile && responseData) { + dispatch( + OPEN_MODAL({ + title: "ثبت کد احراز", + content: ( + + ), + }) + ); + } +}; + +const handleSubmitError = (openNotif, error) => { + openNotif({ + vertical: "top", + horizontal: "center", + msg: error, + severity: "error", + }); +}; + +const InfoBox = ({ icon: Icon, label, value, iconSx }) => ( + + + + + {label} + + {value || "-"} + + +); + +const PersonalInfoSection = ({ + formik, + guild, + hasInquiry, + isAdmin, + isSuperAdmin, + isKillHouse, +}) => { + const getGenderDisplay = (gender) => { + if (gender === "True" || gender === true) return GENDER_VALUES.MALE; + if (gender === "False" || gender === false) return GENDER_VALUES.FEMALE; + return "-"; + }; + + const getAliveStatusDisplay = (isAlive) => { + if (isAlive === ALIVE_STATUS.YES || isAlive === true) + return ALIVE_STATUS.YES; + if (isAlive === ALIVE_STATUS.NO || isAlive === false) + return ALIVE_STATUS.NO; + return "-"; + }; + + const getBirthDateDisplay = () => { + return formik.values.birth_date || "-"; + }; -const DeleteConfirmationDialog = ({ open, onClose, onConfirm, isDeleting }) => { return ( - - آیا مطمئن هستید؟ - - - آیا از حذف این صنف مطمئن هستید؟ این عمل قابل بازگشت نیست. - - - - + + ); +}; + +const UpdateFromExternalButton = ({ onUpdate, disabled }) => { + return ( + + + + ); +}; + +const ConfirmationDialog = ({ isAccepted, onAccept, onReject }) => { + return ( + + + + + + + + + + + } + actions={ + + + + + } + btnTitle="تایید صحت اطلاعات" + isAccepted={isAccepted} + /> + + ); +}; + +const FormActions = ({ formik, onClose, showCloseButton, isKillHouse }) => { + if (showCloseButton) { + return ( + + + + ); + } + + // For KillHouse: check if area_activity contains "مرغ" + const isAreaActivityValid = isKillHouse + ? formik.values.area_activity && formik.values.area_activity.includes("مرغ") + : true; + + return ( + <> + + + + + } + label="مباشر" + /> + + + + } + label="احراز شماره موبایل" + /> + + + + - - + {isKillHouse && !isAreaActivityValid && ( + + رسته واحد صنفی باید شامل کلمه "مرغ" باشد + + )} + + ); }; @@ -77,20 +1562,8 @@ export const CreateGuilds = ({ guild, updateTable }) => { const [dbRegister, setDbRegister] = useState(null); const [hasInquiry, setHasInquiry] = useState(null); const [guildActive, setGuildActive] = useState(null); - const [guildsList, setGuildsList] = useState(() => (guild ? [guild] : [])); - const [expandedAccordion, setExpandedAccordion] = useState(0); - const [guildsFormValues, setGuildsFormValues] = useState(() => { - // Initialize with guild data if editing - if (guild) { - return [getInitialValues(guild)]; - } - return []; - }); const [cities, setCities] = useState([]); const [typeActivities, setTypeActivities] = useState([]); - const [deleteDialogOpen, setDeleteDialogOpen] = useState(false); - const [deleteDialogIndex, setDeleteDialogIndex] = useState(null); - const [isDeletingGuild, setIsDeletingGuild] = useState(false); const originalPhoneNumber = guild?.phoneNumber || null; @@ -104,35 +1577,26 @@ export const CreateGuilds = ({ guild, updateTable }) => { validationSchema: getValidationSchema(!!guild), validateOnMount: true, onSubmit: (values) => { - const guildsDataArray = guildsList.map((guildItem, index) => { - const guildValues = guildsFormValues[index] || values; - const combinedValues = { - ...values, // Personal info (shared) - ...guildValues, // Guild-specific info (overrides if same keys exist) - }; - return prepareSubmitData( - combinedValues, - guildItem, - originalPhoneNumber, - hasInquiry - ); - }); - - dispatch(updateGuildByNationalIdNewService(guildsDataArray)).then( - (result) => { - if (result.payload.error) { - handleSubmitError(openNotif, result.payload.error); - } else { - handleSubmitSuccess( - dispatch, - openNotif, - updateTable, - values, - result.payload?.data - ); - } - } + const dataToSend = prepareSubmitData( + values, + guild, + originalPhoneNumber, + hasInquiry ); + + dispatch(provinceCreateGuildService(dataToSend)).then((r) => { + if (r.payload.error) { + handleSubmitError(openNotif, r.payload.error); + } else { + handleSubmitSuccess( + dispatch, + openNotif, + updateTable, + values, + r.payload.data + ); + } + }); }, }); @@ -151,6 +1615,7 @@ export const CreateGuilds = ({ guild, updateTable }) => { dispatch(provinceGetTypeActivity()).then((r) => { setTypeActivities(r.payload.data || []); }); + // eslint-disable-next-line react-hooks/exhaustive-deps }, []); useEffect(() => { @@ -159,10 +1624,6 @@ export const CreateGuilds = ({ guild, updateTable }) => { const mapResponseToFormFields = useCallback( (responseData) => { - const guildsData = Array.isArray(responseData.guilds) - ? responseData.guilds - : []; - mapResponseDataToFormFields(responseData, inquiryNationalCode, formik); if (responseData.dbRegister === false) { @@ -170,29 +1631,11 @@ export const CreateGuilds = ({ guild, updateTable }) => { setHasInquiry(null); } else { setHasInquiry(responseData.hasInquiry ?? null); - const firstGuild = guildsData.length > 0 ? guildsData[0] : null; - const activeStatus = firstGuild?.active ?? responseData.active ?? null; - setGuildActive(activeStatus); - formik.setFieldValue("active", activeStatus); + setGuildActive(responseData.active ?? null); + formik.setFieldValue("active", responseData.active ?? null); setDbRegister(true); } - if (guildsData.length > 0) { - setGuildsList(guildsData); - const initialGuildValues = guildsData.map((guildItem) => { - const combinedGuild = { - ...guildItem, - user: responseData.user || {}, - }; - return getInitialValues(combinedGuild); - }); - setGuildsFormValues(initialGuildValues); - setExpandedAccordion(0); - } else { - setGuildsList([]); - setGuildsFormValues([]); - } - setTimeout(() => { formik.validateField("mobile"); formik.validateField("national_id"); @@ -223,7 +1666,7 @@ export const CreateGuilds = ({ guild, updateTable }) => { } dispatch( - mainGetGuildsForUpdateOrCreateService({ + provinceGetGuildsForUpdateOrCreateService({ national_code: inquiryNationalCode, update: false, }) @@ -293,7 +1736,7 @@ export const CreateGuilds = ({ guild, updateTable }) => { } dispatch( - mainGetGuildsForUpdateOrCreateService({ + provinceGetGuildsForUpdateOrCreateService({ national_code: formik.values.national_id, update: true, }) @@ -329,103 +1772,6 @@ export const CreateGuilds = ({ guild, updateTable }) => { }); }, [dispatch, formik.values.national_id, openNotif, mapResponseToFormFields]); - const handleAddGuild = () => { - const newIndex = guildsList.length; - setGuildsList([...guildsList, null]); - setGuildsFormValues([...guildsFormValues, getInitialValues(null)]); - setExpandedAccordion(newIndex); - }; - - const handleDeleteGuild = (index) => { - const guildToDelete = guildsList[index]; - if (guildToDelete?.key) { - setDeleteDialogIndex(index); - setDeleteDialogOpen(true); - return; - } - if (guildsList.length > 1) { - setGuildsList(guildsList.filter((_, i) => i !== index)); - setGuildsFormValues(guildsFormValues.filter((_, i) => i !== index)); - if (expandedAccordion === index) { - setExpandedAccordion(0); - } else if (expandedAccordion > index) { - setExpandedAccordion(expandedAccordion - 1); - } - } - }; - - const handleConfirmDelete = () => { - if (deleteDialogIndex === null) return; - - const guildToDelete = guildsList[deleteDialogIndex]; - if (!guildToDelete?.key) return; - - setIsDeletingGuild(true); - dispatch(deactivateGuildService(guildToDelete.key)).then((r) => { - setIsDeletingGuild(false); - setDeleteDialogOpen(false); - setDeleteDialogIndex(null); - - if (r.payload?.error) { - openNotif({ - vertical: "top", - horizontal: "center", - msg: r.payload.error, - severity: "error", - }); - } else { - openNotif({ - vertical: "top", - horizontal: "center", - msg: "صنف با موفقیت حذف شد", - severity: "success", - }); - // Remove from list after successful deletion - if (guildsList.length > 1) { - setGuildsList(guildsList.filter((_, i) => i !== deleteDialogIndex)); - setGuildsFormValues( - guildsFormValues.filter((_, i) => i !== deleteDialogIndex) - ); - // If deleted accordion was expanded, expand the first one - if (expandedAccordion === deleteDialogIndex) { - setExpandedAccordion(0); - } else if (expandedAccordion > deleteDialogIndex) { - // Adjust expanded index if deleted item was before it - setExpandedAccordion(expandedAccordion - 1); - } - } - if (updateTable) { - updateTable(); - } - } - }); - }; - - const handleCloseDeleteDialog = () => { - if (!isDeletingGuild) { - setDeleteDialogOpen(false); - setDeleteDialogIndex(null); - } - }; - - const handleGuildValuesChange = useCallback((index, fieldName, value) => { - setGuildsFormValues((prev) => { - const newValues = [...prev]; - if (!newValues[index]) { - newValues[index] = getInitialValues(null); - } - newValues[index] = { - ...newValues[index], - [fieldName]: value, - }; - return newValues; - }); - }, []); - - const handleAccordionChange = (index) => (event, isExpanded) => { - setExpandedAccordion(isExpanded ? index : false); - }; - const shouldShowUpdateButton = formik?.values?.national_id && (isAdmin || @@ -469,106 +1815,53 @@ export const CreateGuilds = ({ guild, updateTable }) => { )} {shouldShowFormContent && ( - <> - - + + - - - - - اطلاعات صنفی - - + - - {guildsList.map((guildItem, index) => ( - - handleDeleteGuild(index)} - canDelete={ - (guildsList.length > 1 || !guild) && isAdmin - } - guildFormValues={guildsFormValues[index]} - onGuildValuesChange={handleGuildValuesChange} - expanded={expandedAccordion === index} - onChange={handleAccordionChange(index)} - /> - - ))} - - {isAdmin && ( - - - - )} - - - - - {hasRegisterCode && - (!(!guild && hasInquiry === true) || - isAdmin || - isSuperAdmin || - isKillHouse) && ( - formik.setFieldValue("isAccepted", true)} - onReject={() => formik.setFieldValue("isAccepted", false)} - /> - )} + {hasRegisterCode && + (!(!guild && hasInquiry === true) || + isAdmin || + isSuperAdmin || + isKillHouse) && ( + formik.setFieldValue("isAccepted", true)} + onReject={() => formik.setFieldValue("isAccepted", false)} + /> + )} - dispatch(CLOSE_MODAL())} - showCloseButton={ - !guild && - hasInquiry === true && - !isAdmin && - !isSuperAdmin && - !isKillHouse - } - isKillHouse={isKillHouse} - onSubmit={formik.handleSubmit} - /> - - + dispatch(CLOSE_MODAL())} + showCloseButton={ + !guild && + hasInquiry === true && + !isAdmin && + !isSuperAdmin && + !isKillHouse + } + isKillHouse={isKillHouse} + /> + )} - ); }; diff --git a/src/features/province/components/create-guilds/components/ConfirmationDialog.js b/src/features/province/components/create-guilds/components/ConfirmationDialog.js deleted file mode 100644 index 9274cf3..0000000 --- a/src/features/province/components/create-guilds/components/ConfirmationDialog.js +++ /dev/null @@ -1,45 +0,0 @@ -import React from "react"; -import { - Button, - Typography, - ListItem, - ListItemIcon, - ListItemText, -} from "@mui/material"; -import { Grid } from "../../../../../components/grid/Grid"; -import { SPACING } from "../../../../../data/spacing"; -import { DialogAlert } from "../../../../../components/dialog-alert/DialogAlert"; -import { Done } from "@mui/icons-material"; - -export const ConfirmationDialog = ({ isAccepted, onAccept, onReject }) => { - return ( - - - - - - - - - - - } - actions={ - - - - - } - btnTitle="تایید صحت اطلاعات" - isAccepted={isAccepted} - /> - - ); -}; diff --git a/src/features/province/components/create-guilds/components/FormActions.js b/src/features/province/components/create-guilds/components/FormActions.js deleted file mode 100644 index 3fdabae..0000000 --- a/src/features/province/components/create-guilds/components/FormActions.js +++ /dev/null @@ -1,69 +0,0 @@ -import React from "react"; -import { Button, Typography, Checkbox, FormControlLabel } from "@mui/material"; -import { Grid } from "../../../../../components/grid/Grid"; - -export const FormActions = ({ - formik, - onClose, - showCloseButton, - isKillHouse, - onSubmit, -}) => { - if (showCloseButton) { - return ( - - - - ); - } - - // For KillHouse: check if area_activity contains "مرغ" - const isAreaActivityValid = isKillHouse - ? formik.values.area_activity && formik.values.area_activity.includes("مرغ") - : true; - - return ( - <> - - - } - label="احراز شماره موبایل" - /> - - - - {isKillHouse && !isAreaActivityValid && ( - - رسته واحد صنفی باید شامل کلمه "مرغ" باشد - - )} - - - ); -}; diff --git a/src/features/province/components/create-guilds/components/GuildInfoAccordionItem.js b/src/features/province/components/create-guilds/components/GuildInfoAccordionItem.js deleted file mode 100644 index 4fbec3d..0000000 --- a/src/features/province/components/create-guilds/components/GuildInfoAccordionItem.js +++ /dev/null @@ -1,97 +0,0 @@ -import React from "react"; -import { - Accordion, - AccordionSummary, - AccordionDetails, - Typography, - IconButton, -} from "@mui/material"; -import { - ExpandMore as ExpandMoreIcon, - Delete as DeleteIcon, -} from "@mui/icons-material"; -import { GuildInfoSection } from "./GuildInfoSection"; - -export const GuildInfoAccordionItem = ({ - guildIndex, - guildData, - guildActive, - isAdmin, - cities, - typeActivities, - onDelete, - canDelete, - guildFormValues, - onGuildValuesChange, - expanded, - onChange, -}) => { - // Create a formik-like object for this guild's values - const guildFormik = { - values: guildFormValues || {}, - setFieldValue: (fieldName, value) => { - onGuildValuesChange(guildIndex, fieldName, value); - }, - handleChange: (e) => { - onGuildValuesChange(guildIndex, e.target.name, e.target.value); - }, - handleBlur: () => {}, - errors: {}, - touched: {}, - }; - const getGuildTitle = () => { - if (guildData?.guildsName) { - return guildData.guildsName; - } - if (guildData?.title) { - return guildData.title; - } - if (guildFormik.values.guild_name) { - return guildFormik.values.guild_name; - } - return `واحد صنفی ${guildIndex + 1}`; - }; - - return ( - - } - sx={{ - "& .MuiAccordionSummary-content": { - alignItems: "center", - justifyContent: "space-between", - }, - }} - > - - {getGuildTitle()} - - {canDelete && ( - { - e.stopPropagation(); - onDelete(); - }} - color="error" - size="small" - sx={{ mr: 1 }} - > - - - )} - - - - - - ); -}; diff --git a/src/features/province/components/create-guilds/components/GuildInfoSection.js b/src/features/province/components/create-guilds/components/GuildInfoSection.js deleted file mode 100644 index 27b354a..0000000 --- a/src/features/province/components/create-guilds/components/GuildInfoSection.js +++ /dev/null @@ -1,566 +0,0 @@ -import React from "react"; -import { - TextField, - Typography, - RadioGroup, - FormControl, - Radio, - FormControlLabel, - Select, - MenuItem, - InputLabel, - Checkbox, -} from "@mui/material"; -import { DatePicker } from "@mui/x-date-pickers"; -import moment from "moment"; -import BusinessIcon from "@mui/icons-material/Business"; -import PublicIcon from "@mui/icons-material/Public"; -import LocationCityIcon from "@mui/icons-material/LocationCity"; -import DateRangeIcon from "@mui/icons-material/DateRange"; -import ConfirmationNumberIcon from "@mui/icons-material/ConfirmationNumber"; -import AccountBalanceIcon from "@mui/icons-material/AccountBalance"; -import LocalPostOfficeIcon from "@mui/icons-material/LocalPostOffice"; -import PhoneIcon from "@mui/icons-material/Phone"; -import BadgeIcon from "@mui/icons-material/Badge"; -import CheckCircleIcon from "@mui/icons-material/CheckCircle"; -import HomeIcon from "@mui/icons-material/Home"; -import CorporateFareIcon from "@mui/icons-material/CorporateFare"; -import { Grid } from "../../../../../components/grid/Grid"; -import { SPACING } from "../../../../../data/spacing"; -import { LabelField } from "../../../../../components/label-field/LabelField"; -import { InfoBox } from "./InfoBox"; -import { STATUS_VALUES } from "../constants"; -import { - convertPersianToGregorian, - convertGregorianToPersian, -} from "../utils/dateUtils"; - -export const GuildInfoSection = ({ - formik, - guild, - guildActive, - isAdmin, - cities, - typeActivities, - hideTitle = false, - noGridWrapper = false, -}) => { - const getForeignerDisplay = (isForeigner) => { - if (isForeigner === STATUS_VALUES.NO || isForeigner === false) - return STATUS_VALUES.NO; - if (isForeigner === STATUS_VALUES.YES || isForeigner === true) - return STATUS_VALUES.YES; - return "-"; - }; - - const getLicenseExpireDateDisplay = () => { - return formik.values.license_expire_date || "-"; - }; - - const getActiveStatusDisplay = () => { - const activeValue = - formik.values.active !== null - ? formik.values.active - : guild?.active === true || guildActive === true; - return activeValue === true ? "فعال" : "غیر فعال"; - }; - - const content = ( - - {!hideTitle && ( - - - اطلاعات صنفی - - - )} - - - - {isAdmin ? ( - - ) : ( - - )} - - - {isAdmin ? ( - - - رسته واحد صنفی - - - - ) : ( - - )} - - - {isAdmin ? ( - - ) : ( - - )} - - - {isAdmin ? ( - - شهرستان - - - ) : ( - - )} - - - {isAdmin ? ( - { - if (newValue) { - const gregorianDate = moment(newValue).format("YYYY-MM-DD"); - const persianDate = - convertGregorianToPersian(gregorianDate); - formik.setFieldValue("license_expire_date", persianDate); - } else { - formik.setFieldValue("license_expire_date", ""); - } - }} - renderInput={(params) => ( - - )} - /> - ) : ( - - )} - - - {isAdmin ? ( - - ) : ( - - )} - - - {isAdmin ? ( - - ) : ( - - )} - - - {isAdmin ? ( - - - { - formik.setFieldValue( - "active", - e.target.value === "true" ? true : false - ); - }} - sx={{ justifyContent: "space-around" }} - > - } - label="فعال" - /> - } - label="غیر فعال" - /> - - - - ) : ( - - )} - - - - - {isAdmin ? ( - - ) : ( - - )} - - - {isAdmin ? ( - - ) : ( - - )} - - - {isAdmin ? ( - - - { - formik.setFieldValue( - "is_foreigner", - e.target.value === "بلی" ? "بلی" : "خیر" - ); - }} - sx={{ justifyContent: "space-around" }} - > - } - label="بلی" - /> - } - label="خیر" - /> - - - - ) : ( - - )} - - - {isAdmin ? ( - - ) : ( - - )} - - - {isAdmin ? ( - - ) : ( - - )} - - - {isAdmin ? ( - - ) : ( - - )} - - - {isAdmin ? ( - - ) : ( - - )} - - - - - {isAdmin ? ( - <> - - formik.setFieldValue("steward", e.target.checked) - } - name="steward" - color="primary" - /> - } - label="مباشر" - /> - - formik.setFieldValue("guild", e.target.checked) - } - name="guild" - color="primary" - /> - } - label="صنف" - /> - - ) : ( - <> - - - - )} - - - ); - - if (noGridWrapper) { - return <>{content}; - } - - return ( - - {content} - - ); -}; diff --git a/src/features/province/components/create-guilds/components/InfoBox.js b/src/features/province/components/create-guilds/components/InfoBox.js deleted file mode 100644 index 197787d..0000000 --- a/src/features/province/components/create-guilds/components/InfoBox.js +++ /dev/null @@ -1,23 +0,0 @@ -import React from "react"; -import { Box, Typography } from "@mui/material"; - -export const InfoBox = ({ icon: Icon, label, value, iconSx }) => ( - - - - - {label} - - {value || "-"} - - -); - diff --git a/src/features/province/components/create-guilds/components/InquiryForm.js b/src/features/province/components/create-guilds/components/InquiryForm.js deleted file mode 100644 index aed5934..0000000 --- a/src/features/province/components/create-guilds/components/InquiryForm.js +++ /dev/null @@ -1,34 +0,0 @@ -import React from "react"; -import { TextField, Button } from "@mui/material"; - -export const InquiryForm = ({ - inquiryNationalCode, - setInquiryNationalCode, - onInquiry, - isAdmin, -}) => { - return ( - <> - setInquiryNationalCode(e.target.value)} - placeholder={ - isAdmin ? "کد ملی را وارد کنید" : "کد ملی 10 رقمی را وارد کنید" - } - inputProps={isAdmin ? {} : { maxLength: 10 }} - /> - - - ); -}; diff --git a/src/features/province/components/create-guilds/components/PersonalInfoSection.js b/src/features/province/components/create-guilds/components/PersonalInfoSection.js deleted file mode 100644 index cf634a3..0000000 --- a/src/features/province/components/create-guilds/components/PersonalInfoSection.js +++ /dev/null @@ -1,369 +0,0 @@ -import React from "react"; -import { - TextField, - Typography, - RadioGroup, - FormControl, - Radio, - FormControlLabel, -} from "@mui/material"; -import { DatePicker } from "@mui/x-date-pickers"; -import moment from "moment"; -import PersonIcon from "@mui/icons-material/Person"; -import PhoneIcon from "@mui/icons-material/Phone"; -import BadgeIcon from "@mui/icons-material/Badge"; -import CakeIcon from "@mui/icons-material/Cake"; -import FaceIcon from "@mui/icons-material/Face"; -import LocationCityIcon from "@mui/icons-material/LocationCity"; -import FavoriteIcon from "@mui/icons-material/Favorite"; -import { Grid } from "../../../../../components/grid/Grid"; -import { SPACING } from "../../../../../data/spacing"; -import { LabelField } from "../../../../../components/label-field/LabelField"; -import { InfoBox } from "./InfoBox"; -import { GENDER_VALUES, ALIVE_STATUS } from "../constants"; -import { - convertPersianToGregorian, - convertGregorianToPersian, -} from "../utils/dateUtils"; - -export const PersonalInfoSection = ({ - formik, - guild, - hasInquiry, - isAdmin, - isSuperAdmin, - isKillHouse, -}) => { - const getGenderDisplay = (gender) => { - if (gender === "True" || gender === true) return GENDER_VALUES.MALE; - if (gender === "False" || gender === false) return GENDER_VALUES.FEMALE; - return "-"; - }; - - const getAliveStatusDisplay = (isAlive) => { - if (isAlive === ALIVE_STATUS.YES || isAlive === true) - return ALIVE_STATUS.YES; - if (isAlive === ALIVE_STATUS.NO || isAlive === false) - return ALIVE_STATUS.NO; - return "-"; - }; - - const getBirthDateDisplay = () => { - return formik.values.birth_date || "-"; - }; - - return ( - - - - - اطلاعات شخصی - - - - - - {guild || isAdmin ? ( - - ) : ( - - )} - - - {isAdmin ? ( - - ) : ( - - )} - - - {isAdmin ? ( - - ) : ( - - )} - - - {isAdmin ? ( - - ) : ( - - )} - - - {isAdmin ? ( - - - { - formik.setFieldValue( - "is_alive", - e.target.value === "بلی" ? "بلی" : "خیر" - ); - }} - sx={{ justifyContent: "space-around" }} - > - } - label="بلی" - /> - } - label="خیر" - /> - - - - ) : ( - - )} - - - - - {isAdmin ? ( - { - if (newValue) { - const gregorianDate = - moment(newValue).format("YYYY-MM-DD"); - const persianDate = - convertGregorianToPersian(gregorianDate); - formik.setFieldValue("birth_date", persianDate); - } else { - formik.setFieldValue("birth_date", ""); - } - }} - renderInput={(params) => ( - - )} - /> - ) : ( - - )} - - - {isAdmin ? ( - - ) : ( - - )} - - - {isAdmin ? ( - - - { - formik.setFieldValue("gender", e.target.value); - }} - sx={{ justifyContent: "space-around" }} - > - } - label="مرد" - /> - } - label="زن" - /> - - - - ) : ( - - )} - - - {isAdmin ? ( - - ) : ( - - )} - - - {!guild && - hasInquiry && - !isAdmin && - !isSuperAdmin && - !isKillHouse ? ( - - ) : isKillHouse && - formik.values.mobile && - /^[0-9]{11}$/.test(formik.values.mobile) ? ( - - ) : ( - - )} - - - - - - ); -}; diff --git a/src/features/province/components/create-guilds/components/UpdateFromExternalButton.js b/src/features/province/components/create-guilds/components/UpdateFromExternalButton.js deleted file mode 100644 index a13e138..0000000 --- a/src/features/province/components/create-guilds/components/UpdateFromExternalButton.js +++ /dev/null @@ -1,19 +0,0 @@ -import React from "react"; -import { Button } from "@mui/material"; -import { Refresh } from "@mui/icons-material"; -import { Grid } from "../../../../../components/grid/Grid"; - -export const UpdateFromExternalButton = ({ onUpdate, disabled }) => { - return ( - - - - ); -}; diff --git a/src/features/province/components/create-guilds/constants.js b/src/features/province/components/create-guilds/constants.js deleted file mode 100644 index 0a1b96b..0000000 --- a/src/features/province/components/create-guilds/constants.js +++ /dev/null @@ -1,17 +0,0 @@ -export const STATUS_VALUES = { - YES: "بلی", - NO: "خیر", - TRUE: "True", - FALSE: "False", -}; - -export const GENDER_VALUES = { - MALE: "مرد", - FEMALE: "زن", -}; - -export const ALIVE_STATUS = { - YES: "بلی", - NO: "خیر", -}; - diff --git a/src/features/province/components/create-guilds/utils/dataMapping.js b/src/features/province/components/create-guilds/utils/dataMapping.js deleted file mode 100644 index aa02a38..0000000 --- a/src/features/province/components/create-guilds/utils/dataMapping.js +++ /dev/null @@ -1,232 +0,0 @@ -import { getRoleFromUrl } from "../../../../../utils/getRoleFromUrl"; -import { normalizeExternalApiDate, normalizeDatabaseDate } from "./dateUtils"; -import { formatDateForSubmit } from "./dateUtils"; - -export const prepareSubmitData = ( - values, - guild, - originalPhoneNumber, - hasInquiry -) => { - const baseData = { - national_id: values.national_id, - mobile: values.mobile, - mobilenumber: values.mobile, - steward: !!values.steward, - guild: !!values.guild, - active_register_code: !!values.verify_mobile, - firstName: values.first_name || "", - lastName: values.last_name || "", - fatherName: values.father_name || "", - gender: values.gender || "", - identityNo: values.national_code || "", - isLive: values.is_alive === "بلی" || values.is_alive === true, - birthDate: formatDateForSubmit( - values.birth_date || "", - hasInquiry === true - ), - city: values.city || "", - address: values.address || "", - postalcode: values.postal_code || "", - licenseNumber: values.license_number || "", - licenseExpireDate: formatDateForSubmit( - values.license_expire_date || "", - hasInquiry === true - ), - licenseIssueDate: formatDateForSubmit( - values.license_issue_date || "", - hasInquiry === true - ), - licenseType: values.license_type || "", - licenseStatus: values.license_status || "", - isicname: values.area_activity || "", - corporationName: values.corporation_name || "", - nationalId: values.guild_national_id || "", - unionName: values.union_name || "", - phonenumber: values.phone_number || "", - hasPartner: values.has_partner === true || values.has_partner === "بلی", - isForeigner: values.is_foreigner === true || values.is_foreigner === "بلی", - title: values.guild_name || "", - role: getRoleFromUrl(), - has_inquiry: hasInquiry !== null ? hasInquiry : false, - ...(values.active !== null && { active: values.active }), - }; - - if (guild) { - baseData.guilds_key = guild.key; - if (values.mobile !== originalPhoneNumber) { - baseData.mobile = values.mobile; - baseData.mobilenumber = values.mobile; - } - } - - return baseData; -}; - -export const mapResponseDataToFormFields = ( - responseData, - inquiryNationalCode, - formik -) => { - const isExternalApi = responseData.dbRegister === false; - - // New structure: user is at top level, guilds is an array - const userData = responseData.user || {}; - // For personal info, we use the first guild's data if available, or empty - const firstGuild = - Array.isArray(responseData.guilds) && responseData.guilds.length > 0 - ? responseData.guilds[0] - : {}; - const guildData = firstGuild || {}; - const layerTwo = guildData.layerTwo || {}; - const addressData = firstGuild?.address || guildData.address || {}; - const provinceData = addressData.province || {}; - const cityData = addressData.city || {}; - - const nationalIdValue = isExternalApi - ? String( - layerTwo.nationalcode || userData.nationalCode || inquiryNationalCode - ).trim() - : String(userData.nationalId || inquiryNationalCode).trim(); - - const birthDatePersian = isExternalApi - ? normalizeExternalApiDate(userData.birthDate || "") - : normalizeDatabaseDate(userData.birthday || ""); - - const licenseExpireDatePersian = isExternalApi - ? normalizeExternalApiDate(guildData.licenseExpireDate || "") - : normalizeDatabaseDate(firstGuild.licenseExpireDate || ""); - - const licenseIssueDatePersian = isExternalApi - ? normalizeExternalApiDate(layerTwo.licenseIssueDate || "") - : normalizeDatabaseDate(responseData.licenseIssueDate || ""); - - const genderValue = isExternalApi - ? userData.gender === true - ? "True" - : userData.gender === false - ? "False" - : "" - : userData.gender || ""; - - const isAliveValue = isExternalApi - ? userData.isLive === true - ? "بلی" - : userData.isLive === false - ? "خیر" - : "" - : userData.isAlive === false - ? "خیر" - : userData.isAlive === true - ? "بلی" - : ""; - - const isForeignerValue = isExternalApi - ? layerTwo.isForeigner === "خیر" - ? false - : layerTwo.isForeigner === "بلی" - ? true - : "" - : responseData.isForeignNational === false - ? false - : responseData.isForeignNational === true - ? true - : ""; - - const hasStewardValue = isExternalApi - ? layerTwo.hasSteward === "خیر" - ? false - : layerTwo.hasSteward === "بلی" - ? true - : "" - : responseData.steward === false - ? false - : responseData.steward === true - ? true - : ""; - - const hasPartnerValue = isExternalApi - ? layerTwo.hasPartner === "خیر" - ? false - : layerTwo.hasPartner === "بلی" - ? true - : "" - : responseData.hasPartner === false - ? false - : responseData.hasPartner === true - ? true - : ""; - - const values = { - first_name: userData.firstName || "", - last_name: userData.lastName || "", - national_id: nationalIdValue, - national_code: isExternalApi - ? userData.identityNo || "" - : userData.nationalCode || "", - birth_date: birthDatePersian, - father_name: userData.fatherName || "", - gender: genderValue, - person_city: userData.city || "", - is_alive: isAliveValue, - // Guild fields - will be set per guild in accordion, so we set empty or first guild's data - guild_name: isExternalApi - ? guildData.title || "" - : firstGuild.guildsName || "", - area_activity: isExternalApi - ? guildData.isicname || "" - : firstGuild.areaActivity || "", - state: isExternalApi ? guildData.state || "" : provinceData.name || "", - city: isExternalApi ? guildData.city || "" : cityData.name || "", - address: isExternalApi - ? guildData.address || "" - : addressData.address || "", - license_expire_date: licenseExpireDatePersian, - license_status: isExternalApi - ? guildData.licenseStatus || "" - : firstGuild.licenseStatus || "", - license_type: isExternalApi - ? guildData.licenseType || "" - : firstGuild.licenseType || "", - license_number: isExternalApi - ? guildData.licenseNumber || "" - : firstGuild.licenseNumber || "", - union_name: isExternalApi - ? layerTwo.unionName || "" - : firstGuild.unionName || "", - postal_code: isExternalApi - ? layerTwo.postalcode || "" - : addressData.postalCode || "", - phone_number: isExternalApi - ? layerTwo.phonenumber || "" - : firstGuild.phoneNumber || "", - mobile: isExternalApi ? layerTwo.mobilenumber || "" : userData.mobile || "", - guild_national_id: isExternalApi - ? layerTwo.nationalId || "" - : firstGuild.nationalCode || "", - is_foreigner: isForeignerValue, - corporation_name: isExternalApi - ? layerTwo.corporationName || "" - : firstGuild.companyName || "", - has_steward: hasStewardValue, - has_partner: hasPartnerValue, - steward: isExternalApi ? false : firstGuild.isSteward || false, - guild: isExternalApi - ? typeof guildData.guild === "boolean" - ? guildData.guild - : false - : typeof firstGuild.guild === "boolean" - ? firstGuild.guild - : false, - license_issue_date: licenseIssueDatePersian, - ...(isExternalApi - ? {} - : { - company_name: firstGuild.companyName || "", - company_identifier: firstGuild.companyIdentifier || "", - type_activity_name: firstGuild.typeActivity || "", - }), - }; - - formik.setValues({ ...formik.values, ...values }); -}; diff --git a/src/features/province/components/create-guilds/utils/dateUtils.js b/src/features/province/components/create-guilds/utils/dateUtils.js deleted file mode 100644 index 76b0982..0000000 --- a/src/features/province/components/create-guilds/utils/dateUtils.js +++ /dev/null @@ -1,158 +0,0 @@ -import { - convertToIranianTime, - convertPersianToEnglishNumerals, -} from "../../../../../utils/formatTime"; -import { fromJalali } from "../../../../../utils/jalali"; - -export const convertGregorianToPersian = (gregorianDateString) => { - if (!gregorianDateString || typeof gregorianDateString !== "string") { - return ""; - } - - // Check if the date is already in Persian format (YYYY/MM/DD with year < 1500) - const persianPattern = /^\d{4}\/\d{2}\/\d{2}$/; - if (persianPattern.test(gregorianDateString)) { - const year = parseInt(gregorianDateString.split("/")[0]); - // If year is < 1500, it's likely Persian, return as is - if (year < 1500) { - return gregorianDateString; - } - } - - // Try to convert using convertToIranianTime - try { - return convertToIranianTime(gregorianDateString); - } catch (error) { - console.error("Error converting Gregorian date to Persian:", error); - return gregorianDateString; // Return original on error - } -}; - -export const convertPersianToGregorian = (persianDateString) => { - if (!persianDateString || typeof persianDateString !== "string") { - return ""; - } - - const normalizedDateString = - convertPersianToEnglishNumerals(persianDateString); - - const gregorianPattern = /^\d{4}[-/]\d{2}[-/]\d{2}$/; - if (gregorianPattern.test(normalizedDateString)) { - const year = parseInt(normalizedDateString.split(/[-/]/)[0]); - if (year > 1500) { - return normalizedDateString.replace(/\//g, "-"); - } - } - - const parts = normalizedDateString.split("/"); - if (parts.length !== 3) { - return persianDateString; - } - - const py = parseInt(parts[0]); - const pm = parseInt(parts[1]); - const pd = parseInt(parts[2]); - - if (isNaN(py) || isNaN(pm) || isNaN(pd)) { - return persianDateString; - } - - try { - const gregorianDate = fromJalali(py, pm, pd); - const year = gregorianDate.getFullYear(); - const month = String(gregorianDate.getMonth() + 1).padStart(2, "0"); - const day = String(gregorianDate.getDate()).padStart(2, "0"); - return `${year}-${month}-${day}`; - } catch (error) { - console.error("Error converting Persian date to Gregorian:", error); - return persianDateString; - } -}; - -export const normalizeExternalApiDate = (dateString) => { - if (!dateString || typeof dateString !== "string") { - return ""; - } - return convertPersianToEnglishNumerals(dateString); -}; - -export const normalizeDatabaseDate = (dateString) => { - if (!dateString || typeof dateString !== "string") { - return ""; - } - const first10Chars = dateString.substring(0, 10); - const normalizedDate = first10Chars.replace(/-/g, "/"); - return convertToIranianTime(normalizedDate); -}; - -export const formatDateForSubmitExternal = (dateString) => { - if (!dateString || typeof dateString !== "string") { - return ""; - } - return convertPersianToEnglishNumerals(dateString); -}; - -export const formatDateForSubmitDatabase = (dateString) => { - if (!dateString || typeof dateString !== "string") { - return ""; - } - - const normalizedDate = convertPersianToEnglishNumerals(dateString); - const persianPattern = /^\d{4}\/\d{2}\/\d{2}$/; - - if (persianPattern.test(normalizedDate)) { - const year = parseInt(normalizedDate.split("/")[0]); - if (year < 1500) { - const parts = normalizedDate.split("/"); - const py = parseInt(parts[0]); - const pm = parseInt(parts[1]); - const pd = parseInt(parts[2]); - - if (!isNaN(py) && !isNaN(pm) && !isNaN(pd)) { - try { - const gregorianDate = fromJalali(py, pm, pd); - const gy = gregorianDate.getFullYear(); - const gm = String(gregorianDate.getMonth() + 1).padStart(2, "0"); - const gd = String(gregorianDate.getDate()).padStart(2, "0"); - return `${gy}/${gm}/${gd}`; - } catch (error) { - console.error("Error converting Persian to Gregorian:", error); - } - } - } - } - - const gregorianPattern = /^\d{4}[-/]\d{2}[-/]\d{2}$/; - if (gregorianPattern.test(normalizedDate)) { - const year = parseInt(normalizedDate.split(/[-/]/)[0]); - if (year > 1900) { - return normalizedDate.replace(/-/g, "/"); - } - } - - try { - const date = new Date(normalizedDate); - if (!isNaN(date.getTime())) { - const year = date.getFullYear(); - const month = String(date.getMonth() + 1).padStart(2, "0"); - const day = String(date.getDate()).padStart(2, "0"); - return `${year}/${month}/${day}`; - } - } catch (error) { - console.error("Error formatting database date:", error); - } - - return normalizedDate.replace(/-/g, "/"); -}; - -export const formatDateForSubmit = (dateString, isExternalApi = false) => { - if (!dateString || typeof dateString !== "string") { - return ""; - } - - if (isExternalApi) { - return formatDateForSubmitExternal(dateString); - } else { - return formatDateForSubmitDatabase(dateString); - } -}; diff --git a/src/features/province/components/create-guilds/utils/formUtils.js b/src/features/province/components/create-guilds/utils/formUtils.js deleted file mode 100644 index 8287371..0000000 --- a/src/features/province/components/create-guilds/utils/formUtils.js +++ /dev/null @@ -1,95 +0,0 @@ -import * as yup from "yup"; -import { normalizeDatabaseDate } from "./dateUtils"; - -export const getValidationSchema = (isEditMode) => - yup.object({ - national_id: yup - .string() - .required("کد ملی الزامی است") - .matches(/^[0-9]{10}$/, "کد ملی باید 10 رقم باشد"), - mobile: isEditMode - ? yup - .string() - .nullable() - .test( - "mobile-format", - "شماره تلفن باید 11 رقم باشد", - (value) => !value || /^[0-9]{11}$/.test(value) - ) - : yup - .string() - .required("شماره تلفن الزامی است") - .matches(/^[0-9]{11}$/, "شماره تلفن باید 11 رقم باشد"), - first_name: yup.string(), - last_name: yup.string(), - guild_name: yup.string(), - guild_category: yup.string(), - state: yup.string(), - city: yup.string(), - address: yup.string(), - license_expire_date: yup.string(), - license_status: yup.string(), - union_name: yup.string(), - postal_code: yup.string(), - guild_national_id: yup.string(), - is_foreigner: yup.string(), - national_code: yup.string(), - has_steward: yup.string(), - has_partner: yup.string(), - license_number: yup.string(), - isAccepted: yup - .boolean() - .test("req", "باید تعهد نامه را بپذیرید!", (val) => { - return val === true; - }) - .required("این فیلد اجباری است!"), - }); - -export const getInitialValues = (guild) => ({ - first_name: guild?.user?.firstName || "", - last_name: guild?.user?.lastName || "", - corporation_name: guild?.companyName || "", - national_id: guild?.user?.nationalId || "", - national_code: guild?.user?.nationalCode || "", - birth_date: normalizeDatabaseDate(guild?.user?.birthday || ""), - father_name: guild?.user?.fatherName || "", - gender: guild?.user?.gender || "", - person_city: guild?.user?.city || "", - is_alive: guild?.user?.isAlive || "", - guild_name: guild?.guildsName || "", - area_activity: guild?.areaActivity || "", - state: guild?.address?.province?.name || "", - city: guild?.address?.city?.name || "", - address: guild?.address?.address || "", - license_expire_date: normalizeDatabaseDate(guild?.licenseExpireDate || ""), - license_status: guild?.licenseStatus || "", - license_type: guild?.licenseType || "", - union_name: guild?.unionName || "", - postal_code: guild?.address?.postalCode || "", - phone_number: guild?.phoneNumber || "", - mobile: guild?.user?.mobile || "", - is_foreigner: guild?.is_foreign_national || "", - has_steward: guild?.hasSteward || "", - has_partner: guild?.hasPartner || "", - license_number: guild?.licenseNumber || "", - isAccepted: guild?.provinceAcceptState === "accepted" || false, - steward: - typeof guild?.steward === "boolean" - ? guild.steward - : typeof guild?.isSteward === "boolean" - ? guild.isSteward - : false, - guild: - typeof guild?.guild === "boolean" - ? guild.guild - : typeof guild?.isGuild === "boolean" - ? guild.isGuild - : false, - verify_mobile: guild?.verifyMobile || false, - guild_national_id: guild?.nationalId || "", - license_issue_date: normalizeDatabaseDate(guild?.licenseIssueDate || ""), - company_name: guild?.companyName || "", - company_identifier: guild?.companyIdentifier || "", - type_activity_name: guild?.typeActivityName || "", - active: guild?.active ?? null, -}); diff --git a/src/features/province/components/create-guilds/utils/submitHandlers.js b/src/features/province/components/create-guilds/utils/submitHandlers.js deleted file mode 100644 index da6ac30..0000000 --- a/src/features/province/components/create-guilds/utils/submitHandlers.js +++ /dev/null @@ -1,45 +0,0 @@ -import { - CLOSE_MODAL, - OPEN_MODAL, -} from "../../../../../lib/redux/slices/appSlice"; -import { ProvinceManageGuildsSubmitRegisterCode } from "../../province-manage-guilds-submit-register-code/ProvinceManageGuildsSubmitRegisterCode"; - -export const handleSubmitSuccess = ( - dispatch, - openNotif, - updateTable, - values, - responseData -) => { - updateTable(); - openNotif({ - vertical: "top", - horizontal: "center", - msg: "عملیات با موفقیت انجام شد.", - severity: "success", - }); - dispatch(CLOSE_MODAL()); - - if (values.verify_mobile && responseData) { - dispatch( - OPEN_MODAL({ - title: "ثبت کد احراز", - content: ( - - ), - }) - ); - } -}; - -export const handleSubmitError = (openNotif, error) => { - openNotif({ - vertical: "top", - horizontal: "center", - msg: error, - severity: "error", - }); -}; diff --git a/src/features/province/components/guild-limitaion/GuildLimitaion.js b/src/features/province/components/guild-limitaion/GuildLimitaion.js index d56d658..56bceac 100644 --- a/src/features/province/components/guild-limitaion/GuildLimitaion.js +++ b/src/features/province/components/guild-limitaion/GuildLimitaion.js @@ -19,7 +19,6 @@ import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl"; import { provinceChangeActiveGuildService } from "../../services/province-change-active-guild"; import { provinceGetBuyersService } from "../../services/province-get-buyers"; import { provinceGetStewardsService } from "../../services/province-get-stewards"; -import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; const validationSchema = Yup.object().shape({ // agreed: Yup.boolean().oneOf([true], 'You must agree to the terms and conditions'), @@ -29,9 +28,6 @@ export const GuildLimitaion = ({ guild, updateTable }) => { const { provinceGetStewardsOptions, provinceGetBuyersOptions } = useSelector( (state) => state.provinceSlice ); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); const [warehouses, setWarehouses] = useState( guild.centersAllocation ? guild.centersAllocation : [] ); @@ -81,21 +77,9 @@ export const GuildLimitaion = ({ guild, updateTable }) => { }); useEffect(() => { - dispatch( - provinceGetStewardsService({ - role_key: checkPathStartsWith("province") - ? selectedSubUser?.key || "" - : "", - }) - ); - dispatch( - provinceGetBuyersService({ - role_key: checkPathStartsWith("province") - ? selectedSubUser?.key || "" - : "", - }) - ); - }, [selectedSubUser?.key]); + dispatch(provinceGetStewardsService()); + dispatch(provinceGetBuyersService()); + }, []); return (
    @@ -161,7 +145,7 @@ export const GuildLimitaion = ({ guild, updateTable }) => { {!warehouses.length && ( محدودیتی وجود ندارد )} - {warehouses?.map((item) => { + {warehouses?.map((item, i) => { return ( <> {item !== null && ( @@ -220,7 +204,7 @@ export const GuildLimitaion = ({ guild, updateTable }) => { {!buyers.length && ( محدودیتی وجود ندارد )} - {buyers?.map((item) => { + {buyers?.map((item, i) => { return ( <> {item !== null && ( diff --git a/src/features/province/components/guilds-operations/GuildsOperations.js b/src/features/province/components/guilds-operations/GuildsOperations.js index 0545c00..9275562 100644 --- a/src/features/province/components/guilds-operations/GuildsOperations.js +++ b/src/features/province/components/guilds-operations/GuildsOperations.js @@ -4,19 +4,25 @@ import { NavLink } from "../../../../components/nav-link/NavLink"; import { useLocation } from "react-router-dom"; import { // ROUTE_ADMINX_ROUTE_GUILDS, + ROUTE_ADMINX_ROUTE_IN_PROVINCE_GUILDS_DISTRIBUTIONS, ROUTE_ADMINX_ROUTE_IN_PROVINCE_GUILDS_REQUESTS, ROUTE_ADMINX_ROUTE_IN_PROVINCE_GUILDS, ROUTE_ADMINX_ROUTE_MANAGE_GUILDS, ROUTE_ADMINX_ROUTE_OUT_PROVINCE_GUILDS, + ROUTE_ADMINX_ROUTE_IN_PROVINCE_STEWARDS, + ROUTE_PROVINCE_ROUTE_GUILDS, ROUTE_PROVINCE_ROUTE_IN_PROVINCE_GUILDS_REQUESTS, ROUTE_PROVINCE_ROUTE_IN_PROVINCE_GUILDS, ROUTE_PROVINCE_ROUTE_MANAGE_GUILDS, ROUTE_PROVINCE_ROUTE_OUT_PROVINCE_GUILDS, + ROUTE_PROVINCE_ROUTE_IN_PROVINCE_STEWARDS, // ROUTE_SUPER_ADMIN_ROUTE_GUILDS, + ROUTE_SUPER_ADMIN_ROUTE_IN_PROVINCE_GUILDS_DISTRIBUTIONS, ROUTE_SUPER_ADMIN_ROUTE_IN_PROVINCE_GUILDS_REQUESTS, ROUTE_SUPER_ADMIN_ROUTE_IN_PROVINCE_GUILDS, ROUTE_SUPER_ADMIN_ROUTE_MANAGE_GUILDS, ROUTE_SUPER_ADMIN_ROUTE_OUT_PROVINCE_GUILDS, + ROUTE_SUPER_ADMIN_ROUTE_IN_PROVINCE_STEWARDS, ROUTE_SUPER_ADMIN_ROUTE_OUT_PROVINCE_TRUE_GUILDS, ROUTE_ADMINX_ROUTE_OUT_PROVINCE_TRUE_GUILDS, ROUTE_PROVINCE_ROUTE_OUT_PROVINCE_TRUE_GUILDS, @@ -32,7 +38,9 @@ import { } from "../../../../routes/routes"; import LinkItem from "../../../../components/link-item/LinkItem"; import { MdCorporateFare } from "react-icons/md"; +import { IoIosPeople } from "react-icons/io"; import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl"; +import { VscLiveShare } from "react-icons/vsc"; import { BackButton } from "../../../../components/back-button/BackButton"; export const GuildsOperations = () => { @@ -156,7 +164,7 @@ export const GuildsOperations = () => { title="اصناف حقوقی" /> - {/* { title="مدیریت مباشرین" /> - )} */} + )} )} diff --git a/src/features/province/components/manage-guild-distributions/ManageGuildDistributions.js b/src/features/province/components/manage-guild-distributions/ManageGuildDistributions.js index caeb679..7058f69 100644 --- a/src/features/province/components/manage-guild-distributions/ManageGuildDistributions.js +++ b/src/features/province/components/manage-guild-distributions/ManageGuildDistributions.js @@ -315,7 +315,7 @@ export const ManageGuildDistributions = () => { return ( - + { const userKey = useSelector((state) => state.userSlice?.userProfile?.key); const dispatch = useDispatch(); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); + const [data, setData] = useState([]); const [totalRows, setTotalRows] = useState(0); const [perPage, setPerPage] = useState(10); const [textValue, setTextValue] = useState(""); const [page, setPage] = useState(1); const [tableData, setTableData] = useState([]); + const [isSteward, setIsSteward] = useState(false); const [activeState, setActiveState] = useState("active"); const handleTextChange = (e) => setTextValue(e.target.value); - // const handleCheckboxChange = () => setIsSteward(!isSteward); + const handleCheckboxChange = () => setIsSteward(!isSteward); const fetchApiData = async (page) => { const response = await dispatch( @@ -38,12 +43,9 @@ export const MaangeGuilds = () => { value: textValue, page: page, page_size: perPage, - steward: false, + steward: isSteward, active_state: activeState, is_real_person: true, - role_key: checkPathStartsWith("province") - ? selectedSubUser?.key || "" - : "", }) ); @@ -73,7 +75,7 @@ export const MaangeGuilds = () => { useEffect(() => { fetchApiData(1); - }, [perPage, selectedSubUser?.key, activeState]); + }, [dispatch, isSteward, activeState]); useEffect(() => { if (!data || !Array.isArray(data)) { @@ -205,6 +207,10 @@ export const MaangeGuilds = () => { setTableData(d); }, [data]); + useEffect(() => { + fetchApiData(1); + }, [perPage]); + const handleSubmit = async (e) => { e.preventDefault(); const response = await dispatch( @@ -213,12 +219,9 @@ export const MaangeGuilds = () => { value: textValue, page: page, page_size: perPage, - steward: false, + steward: isSteward, active_state: activeState, is_real_person: true, - role_key: checkPathStartsWith("province") - ? selectedSubUser?.key || "" - : "", }) ); @@ -250,7 +253,7 @@ export const MaangeGuilds = () => { > - {["KillHouse", "GuildRoom"].includes(getRoleFromUrl()) && ( + {["GuildRoom", "KillHouse"].includes(getRoleFromUrl()) && ( { /> - - + + + + + + + + + + + + + + + + + + + +
    )} - - { - marketRequestUpdateRef.current = updateFn; - }} - /> - + {value === 1 && ( + + + + )} {value === 2 && ( diff --git a/src/features/province/components/province-trade-panel/TradePanelChart.js b/src/features/province/components/province-trade-panel/TradePanelChart.js deleted file mode 100644 index 8a15bd3..0000000 --- a/src/features/province/components/province-trade-panel/TradePanelChart.js +++ /dev/null @@ -1,72 +0,0 @@ -import { useMemo } from "react"; -import { Grid } from "../../../../components/grid/Grid"; -import { AdvancedChart } from "../../../../components/advanced-chart/AdvancedChart"; -import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl"; -import { ProvinceTradePanelMarketRequest } from "../province-trade-panel-market-request/ProvinceTradePanelMarketRequest"; - -export const TradePanelChart = ({ chartsData, updateTable }) => { - const chartOptions = useMemo(() => { - if (!chartsData || !Array.isArray(chartsData) || !chartsData[0]) { - return []; - } - - const firstItem = chartsData[0]; - if (!firstItem?.category || !Array.isArray(firstItem.category)) { - return [ - { - name: "تعداد کل", - data: chartsData.map((item) => item?.totalQuantity || 0), - }, - ]; - } - - const formatCategoryName = (category) => - `بین ${category?.minValue || 0} تا ${category?.maxValue || 0}`; - - return [ - { - name: "تعداد کل", - data: chartsData.map((item) => item?.totalQuantity || 0), - }, - ...firstItem.category.map((cat, index) => ({ - name: formatCategoryName(cat), - data: chartsData.map((item) => { - if (!item?.category || !Array.isArray(item.category)) return 0; - return item.category[index]?.quantity || 0; - }), - })), - ]; - }, [chartsData]); - - const chartSeparator = - chartsData && Array.isArray(chartsData) - ? chartsData.map((item) => item?.city || "") - : []; - - const isKillHouse = getRoleFromUrl() === "KillHouse"; - - return ( - - - - - {isKillHouse && ( - - - - )} - - ); -}; diff --git a/src/features/province/components/province-trade-panel/TradePanelSearchBar.js b/src/features/province/components/province-trade-panel/TradePanelSearchBar.js deleted file mode 100644 index b726878..0000000 --- a/src/features/province/components/province-trade-panel/TradePanelSearchBar.js +++ /dev/null @@ -1,45 +0,0 @@ -import { Button, TextField, Tooltip } from "@mui/material"; -import axios from "axios"; -import { RiFileExcel2Fill, RiSearchLine } from "react-icons/ri"; -import { Grid } from "../../../../components/grid/Grid"; -import { SPACING } from "../../../../data/spacing"; - -export const TradePanelSearchBar = ({ - textValue, - onTextChange, - onSubmit, - excelUrlParams, -}) => { - return ( - -
    - - - - - - - - - - - -
    -
    - ); -}; diff --git a/src/features/province/components/province-trade-panel/TradePanelTable.js b/src/features/province/components/province-trade-panel/TradePanelTable.js deleted file mode 100644 index c14401b..0000000 --- a/src/features/province/components/province-trade-panel/TradePanelTable.js +++ /dev/null @@ -1,117 +0,0 @@ -import { useEffect, useState } from "react"; -import { Grid } from "../../../../components/grid/Grid"; -import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable"; -import { formatJustDate } from "../../../../utils/formatTime"; -import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl"; -import { TradepanelDetails } from "../trade-panel-details/TradepanelDetails"; -import { TradePanelPurchaseOperation } from "../trade-panel-purchase-operation/TradePanelPurchaseOperation"; -import { TradePanelFilters } from "../trade-panel-filter/TradePanelFilter"; -import { CHICKEN_BREEDS } from "./constants"; - -export const TradePanelTable = ({ - data, - page, - perPage, - totalRows, - filters, - cities, - onFilterUpdate, - onCityChange, - onBreedChange, - onPriceFilterSubmit, - onAgeFilterSubmit, - onPageChange, - onPerRowsChange, - updateTable, -}) => { - const [tableData, setTableData] = useState([]); - - useEffect(() => { - if (!data || !Array.isArray(data)) { - setTableData([]); - return; - } - - const formatNumber = (num) => { - if (num === null || num === undefined) return "0"; - return num.toLocaleString(); - }; - - const rowNumber = (index) => { - const currentPage = page || 1; - const currentPerPage = perPage || 20; - return currentPage === 1 - ? index + 1 - : index + currentPerPage * (currentPage - 1) + 1; - }; - - const tableRows = data.map((item, i) => [ - rowNumber(i), - , - `${item?.poultry?.fullname || ""} (${item?.poultry?.mobile || ""})`, - item?.poultry?.city || "-", - item?.chickenBreed || "-", - item?.age?.age || "-", - item?.IndexWeight || "-", - item?.sendDate ? formatJustDate(item.sendDate) : "-", - item?.quantity || "-", - formatNumber(item?.remainQuantity), - formatNumber(item?.totalAllocated), - formatNumber(item?.amount), - , - ]); - - setTableData(tableRows); - }, [data, page, perPage, updateTable]); - - const columns = [ - "ردیف", - "جزئیات", - "نام و نام خانوادگی (تلفن)", - "استان / شهر", - "نژاد", - "سن جوجه", - "میانگین وزنی (کیلوگرم) ", - "تاریخ کشتار", - "تعداد قطعه", - "مانده قابل خرید", - "فروش رفته ", - "مبلغ هر کیلو (ریال)", - ...(getRoleFromUrl() === "KillHouse" ? ["خرید"] : []), - ]; - - return ( - - - - - - - - - - ); -}; diff --git a/src/features/province/components/province-trade-panel/TradePanelTabs.js b/src/features/province/components/province-trade-panel/TradePanelTabs.js deleted file mode 100644 index 032af1b..0000000 --- a/src/features/province/components/province-trade-panel/TradePanelTabs.js +++ /dev/null @@ -1,25 +0,0 @@ -import { Tab, Tabs } from "@mui/material"; -import { Grid } from "../../../../components/grid/Grid"; -import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl"; - -export const TradePanelTabs = ({ value, onChange }) => { - if (getRoleFromUrl() === "KillHouse") { - return null; - } - - return ( - - - - - - - - ); -}; diff --git a/src/features/province/components/province-trade-panel/TradeTimeRangeInfo.js b/src/features/province/components/province-trade-panel/TradeTimeRangeInfo.js deleted file mode 100644 index 0b8853e..0000000 --- a/src/features/province/components/province-trade-panel/TradeTimeRangeInfo.js +++ /dev/null @@ -1,20 +0,0 @@ -import { Typography } from "@mui/material"; -import InfoIcon from "@mui/icons-material/Info"; -import { Grid } from "../../../../components/grid/Grid"; - -export const TradeTimeRangeInfo = ({ range }) => { - if (!range?.allow) { - return null; - } - - return ( - - - - زمان فعالیت پنل معاملات: از ساعت{" "} - {range?.start_time ? range.start_time.slice(0, 5) : "-"} الی ساعت{" "} - {range?.end_time ? range.end_time.slice(0, 5) : "-"} - - - ); -}; diff --git a/src/features/province/components/province-trade-panel/constants.js b/src/features/province/components/province-trade-panel/constants.js deleted file mode 100644 index fa1293d..0000000 --- a/src/features/province/components/province-trade-panel/constants.js +++ /dev/null @@ -1,15 +0,0 @@ -export const CHICKEN_BREEDS = ["آرین", "راس", "کاب", "*ترکیبی"]; - -export const INITIAL_FILTERS = { - showRemaining: false, - selectedCities: [], - selectedBreeds: [], - minPrice: "", - maxPrice: "", - tempMinPrice: "", - tempMaxPrice: "", - minAge: "", - maxAge: "", - tempMinAge: "", - tempMaxAge: "", -}; diff --git a/src/features/province/components/province-trade-panel/useTradePanelData.js b/src/features/province/components/province-trade-panel/useTradePanelData.js deleted file mode 100644 index 441d7a8..0000000 --- a/src/features/province/components/province-trade-panel/useTradePanelData.js +++ /dev/null @@ -1,169 +0,0 @@ -import { useEffect, useState, useCallback, useRef, useMemo } from "react"; -import { useDispatch, useSelector } from "react-redux"; -import axios from "axios"; -import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; -import { tradePanelChart } from "../../services/trade-panel-chat"; -import { provincePolicyGetTradeTimeRagnge } from "../../services/province-policy-edit-trade-time-range"; -import { provinceGetDirectBuyingPoultryRequests } from "../../services/province-get-direct-buying-poultry-requests"; - -export const useTradePanelData = () => { - const dispatch = useDispatch(); - const userKey = useSelector((state) => state.userSlice.userProfile.key); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); - - const [range, setRange] = useState(); - const [chartsData, setChartsData] = useState([]); - const [data, setData] = useState([]); - const [totalRows, setTotalRows] = useState(0); - const [cities, setCities] = useState([]); - - const isInitialMount = useRef(true); - const lastRequestPayload = useRef(null); - const isFetching = useRef(false); - - const roleKey = useMemo( - () => (checkPathStartsWith("slaughter") ? selectedSubUser?.key || "" : ""), - [selectedSubUser?.key] - ); - - useEffect(() => { - const fetchCities = async () => { - try { - const response = await axios.get("/cities"); - setCities(response.data); - } catch (error) { - console.error("خطا در دریافت اطلاعات", error); - } - }; - fetchCities(); - }, []); - - const fetchTradeTimeRange = useCallback(async () => { - const r = await dispatch(provincePolicyGetTradeTimeRagnge()); - if (r?.payload?.data) { - const { startTime, endTime, allow } = r.payload.data; - setRange({ start_time: startTime, end_time: endTime, allow }); - } - }, [dispatch, roleKey]); - - const fetchChartData = useCallback(async () => { - const r = await dispatch( - tradePanelChart({ - role_key: checkPathStartsWith("slaughter") ? roleKey || "" : "", - }) - ); - if (r?.payload?.data) { - setChartsData(r.payload.data); - } - }, [dispatch, roleKey]); - - const fetchApiData = useCallback( - async (pageNumber, searchValue, filters, perPage, forceFetch = false) => { - const { - selectedBreeds = [], - selectedCities = [], - showRemaining = false, - minPrice = "", - maxPrice = "", - minAge = "", - maxAge = "", - } = filters || {}; - - const payload = { - selectedBreeds: [...(selectedBreeds || [])].sort().join(","), - selectedCities: [...(selectedCities || [])].sort().join(","), - showRemaining, - minPrice: minPrice || "", - maxPrice: maxPrice || "", - minAge: minAge || "", - maxAge: maxAge || "", - textValue: searchValue || "", - page: pageNumber || 1, - perPage: perPage || 20, - }; - - const payloadKey = JSON.stringify(payload); - - if (!forceFetch && lastRequestPayload.current === payloadKey) { - return; - } - - if (isFetching.current) { - return; - } - - isFetching.current = true; - lastRequestPayload.current = payloadKey; - - try { - const r = await dispatch( - provinceGetDirectBuyingPoultryRequests({ - selectedBreeds: selectedBreeds || [], - selectedCities: selectedCities || [], - showRemaining, - minPrice: minPrice || "", - maxPrice: maxPrice || "", - minAge: minAge || "", - maxAge: maxAge || "", - textValue: searchValue || "", - page: pageNumber || 1, - perPage: perPage || 20, - }) - ); - if (r?.payload?.error) { - console.error("Error fetching data:", r.payload.error); - setData([]); - setTotalRows(0); - } else if (r?.payload?.data) { - setData(r.payload.data.results || []); - setTotalRows(r.payload.data.count || 0); - } - } catch (error) { - console.error("Error in fetchApiData:", error); - setData([]); - setTotalRows(0); - } finally { - isFetching.current = false; - } - }, - [dispatch, roleKey] - ); - - const initializeData = useCallback( - async (textValue, filters, perPage) => { - if (isInitialMount.current) { - isInitialMount.current = false; - lastRequestPayload.current = null; - try { - await Promise.all([ - fetchTradeTimeRange(), - fetchChartData(), - fetchApiData(1, textValue, filters, perPage, true), - ]); - } catch (error) { - console.error("Error in initial fetch:", error); - } - } - }, - [fetchTradeTimeRange, fetchChartData, fetchApiData] - ); - - const resetPayload = useCallback(() => { - lastRequestPayload.current = null; - }, []); - - return { - range, - chartsData, - data, - totalRows, - cities, - roleKey, - userKey, - fetchApiData, - initializeData, - resetPayload, - }; -}; diff --git a/src/features/province/components/province-trade-panel/useTradePanelFilters.js b/src/features/province/components/province-trade-panel/useTradePanelFilters.js deleted file mode 100644 index 3b61be9..0000000 --- a/src/features/province/components/province-trade-panel/useTradePanelFilters.js +++ /dev/null @@ -1,105 +0,0 @@ -import { useState, useMemo } from "react"; -import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl"; -import { INITIAL_FILTERS } from "./constants"; - -export const useTradePanelFilters = () => { - const [filters, setFilters] = useState(INITIAL_FILTERS); - - const updateFilter = (key, value) => { - setFilters((prev) => ({ ...prev, [key]: value })); - }; - - const toggleArrayItem = (array, item) => - array.includes(item) ? array.filter((i) => i !== item) : [...array, item]; - - const handleCityChange = (city) => { - setFilters((prev) => ({ - ...prev, - selectedCities: toggleArrayItem(prev.selectedCities, city), - })); - }; - - const handleBreedChange = (breed) => { - setFilters((prev) => ({ - ...prev, - selectedBreeds: toggleArrayItem(prev.selectedBreeds, breed), - })); - }; - - const handlePriceFilterSubmit = () => { - setFilters((prev) => ({ - ...prev, - minPrice: prev.tempMinPrice, - maxPrice: prev.tempMaxPrice, - })); - }; - - const handleAgeFilterSubmit = () => { - setFilters((prev) => ({ - ...prev, - minAge: prev.tempMinAge, - maxAge: prev.tempMaxAge, - })); - }; - - const { - selectedCities, - selectedBreeds, - showRemaining, - minPrice, - maxPrice, - minAge, - maxAge, - } = filters; - - const getExcelUrlParams = useMemo(() => { - return (userKey, roleKey, textValue, page, perPage) => { - const params = new URLSearchParams({ - key: userKey || "", - breed: selectedBreeds?.join(",") || "", - remain: showRemaining, - min_age: minAge || "", - max_age: maxAge || "", - role: getRoleFromUrl() || "", - search: "filter", - value: textValue || "", - page: page?.toString() || "1", - page_size: perPage?.toString() || "20", - }); - - if (selectedCities?.length > 0) { - params.append("city", selectedCities.join(",")); - } - if (minPrice) params.append("min_amount", minPrice); - if (maxPrice) params.append("max_amount", maxPrice); - if (roleKey) params.append("role_key", roleKey); - - return params.toString(); - }; - }, [ - selectedBreeds, - selectedCities, - showRemaining, - minPrice, - maxPrice, - minAge, - maxAge, - ]); - - return { - filters, - updateFilter, - handleCityChange, - handleBreedChange, - handlePriceFilterSubmit, - handleAgeFilterSubmit, - selectedCities, - selectedBreeds, - showRemaining, - minPrice, - maxPrice, - minAge, - maxAge, - getExcelUrlParams, - }; -}; diff --git a/src/features/province/components/total-cargo-information/TotalCargoInformation.js b/src/features/province/components/total-cargo-information/TotalCargoInformation.js index cd9ccd9..44fbd64 100644 --- a/src/features/province/components/total-cargo-information/TotalCargoInformation.js +++ b/src/features/province/components/total-cargo-information/TotalCargoInformation.js @@ -516,7 +516,7 @@ export const TotalCargoInformation = () => {
    {dashboardInformation && ( - + { const dispatch = useDispatch(); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); const handleOpenModal = async () => { try { const response = await dispatch( - tradePanelGetDetails({ - hatching_key: details_key, - role_key: checkPathStartsWith("province") - ? selectedSubUser?.key || "" - : "", - }) + tradePanelGetDetails({ hatching_key: details_key }) ); if (response.payload?.data) { diff --git a/src/features/province/components/trade-panel-purchase-modal/TradePanelPurchaseModal.js b/src/features/province/components/trade-panel-purchase-modal/TradePanelPurchaseModal.js index 2efe7dc..c60b600 100644 --- a/src/features/province/components/trade-panel-purchase-modal/TradePanelPurchaseModal.js +++ b/src/features/province/components/trade-panel-purchase-modal/TradePanelPurchaseModal.js @@ -1,7 +1,7 @@ import { useContext, useEffect, useState } from "react"; import { Button, TextField } from "@mui/material"; import { Grid } from "../../../../components/grid/Grid"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; import { AppContext } from "../../../../contexts/AppContext"; import { useFormik } from "formik"; import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice"; @@ -10,14 +10,11 @@ import { provinceEditMarketRequestService } from "../../services/trade-panel-edi import { ProvinceMarketRequestService } from "../../services/trade-panel-market-request"; import { paymentGetDeadLines } from "../../services/payment-get-deadlines"; import { useProvinceName } from "../../../../utils/getProvinceName"; -import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; function TradePanelPurchaseModal({ item, updateTable, isEdit = false }) { const [paymentDeadlineDays, setPaymentDeadlineDays] = useState(null); const [fullyRendered, setFullyRendered] = useState(false); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); + const dispatch = useDispatch(); const [openNotif] = useContext(AppContext); @@ -47,13 +44,7 @@ function TradePanelPurchaseModal({ item, updateTable, isEdit = false }) { }); useEffect(() => { - dispatch( - paymentGetDeadLines({ - role_key: checkPathStartsWith("province") - ? selectedSubUser?.key || "" - : "", - }) - ).then((r) => { + dispatch(paymentGetDeadLines()).then((r) => { setFullyRendered(true); const isEnabled = r?.payload?.data?.paymentDeadline; @@ -63,8 +54,7 @@ function TradePanelPurchaseModal({ item, updateTable, isEdit = false }) { setPaymentDeadlineDays(days); } }); - }, [selectedSubUser?.key]); - + }, [dispatch]); const provinceName = useProvinceName(); useEffect(() => { @@ -100,7 +90,11 @@ function TradePanelPurchaseModal({ item, updateTable, isEdit = false }) { if (errorMessage) { // Error occurred (e.g., "باقی مانده اعلام نیاز مرغدار کمتر از درخواست شماست!") + // Close modal and refresh data to get updated information dispatch(CLOSE_MODAL()); + if (updateTable && typeof updateTable === "function") { + updateTable(); + } openNotif({ vertical: "top", horizontal: "center", @@ -114,11 +108,8 @@ function TradePanelPurchaseModal({ item, updateTable, isEdit = false }) { msg: `عملیات با موفقیت انجام شد. برای نهایی کردن خرید ${remainTime} دقیقه فرصت دارد در غیر اینصورت خرید شما حذف می شود.`, severity: "success", }); + updateTable(); dispatch(CLOSE_MODAL()); - // Call updateTable after successful submit to refresh all tables - if (updateTable && typeof updateTable === "function") { - updateTable(); - } } }) .catch((error) => { @@ -128,6 +119,7 @@ function TradePanelPurchaseModal({ item, updateTable, isEdit = false }) { error?.message || "مشکلی پیش آمده است!"; + // Close modal and refresh data dispatch(CLOSE_MODAL()); openNotif({ vertical: "top", @@ -139,6 +131,14 @@ function TradePanelPurchaseModal({ item, updateTable, isEdit = false }) { }, }); + useEffect(() => { + return () => { + if (updateTable && typeof updateTable === "function") { + updateTable(); + } + }; + }, []); + return ( { - try { - dispatch(LOADING_START()); - const { data, status } = await axios.get( - `deactivate_guild/?key=${key}&guild=true` - ); - dispatch(LOADING_END()); - return { data, status }; - } catch (e) { - dispatch(LOADING_END()); - return { error: e.response?.data?.result || e.message }; - } - } -); diff --git a/src/features/province/services/free-buying-payment.js b/src/features/province/services/free-buying-payment.js index e927311..f198c58 100644 --- a/src/features/province/services/free-buying-payment.js +++ b/src/features/province/services/free-buying-payment.js @@ -4,15 +4,12 @@ import { LOADING_END, LOADING_START } from "../../../lib/redux/slices/appSlice"; export const freeBuyingPayment = createAsyncThunk( "FREE_BUYING_PAYMENT", - async (d, { dispatch }) => { + async (modal_key, { dispatch }) => { try { dispatch(LOADING_START()); - const { data, status } = await axios.get(`direct-buying-payment`, { - params: { - province_kill_request_key: d.province_kill_request_key, - role_key: d.role_key || "", - }, - }); + const { data, status } = await axios.get( + `direct-buying-payment/?province_kill_request_key=${modal_key}` + ); dispatch(LOADING_END()); return { data, status }; } catch (e) { diff --git a/src/features/province/services/get-approved-price-state.js b/src/features/province/services/get-approved-price-state.js index 409462f..cf5f531 100644 --- a/src/features/province/services/get-approved-price-state.js +++ b/src/features/province/services/get-approved-price-state.js @@ -6,9 +6,7 @@ export const getApprovedPriceState = createAsyncThunk( "GET_APPROVED_PRICE_STATE", async (d, { dispatch }) => { dispatch(LOADING_START()); - const { data, status } = await axios.get("approved-price", { - params: d, - }); + const { data, status } = await axios.get("approved-price/"); dispatch(LOADING_END()); return { data, status }; } @@ -18,9 +16,7 @@ export const getKillhouseApprovedPriceState = createAsyncThunk( "GET_KILLHOUSE_APPROVED_PRICE_STATE", async (d, { dispatch }) => { dispatch(LOADING_START()); - const { data, status } = await axios.get("broadcast-price", { - params: d, - }); + const { data, status } = await axios.get("broadcast-price/"); dispatch(LOADING_END()); return { data, status }; } diff --git a/src/features/province/services/get-dahsnoard-province-kill-request.js b/src/features/province/services/get-dahsnoard-province-kill-request.js index 1045978..42f3112 100644 --- a/src/features/province/services/get-dahsnoard-province-kill-request.js +++ b/src/features/province/services/get-dahsnoard-province-kill-request.js @@ -11,7 +11,6 @@ export const provinceGetDashboardKillRequestService = createAsyncThunk( date1: d.selectedDate1, date2: d.selectedDate2, role: getRoleFromUrl(), - role_key: d.role_key || "", filter: "search", value: d.textValue, }; @@ -40,7 +39,6 @@ export const provinceGetDashboardDeletedKillRequestService = createAsyncThunk( date1: d.selectedDate1, date2: d.selectedDate2, role: getRoleFromUrl(), - role_key: d.role_key || "", deleted_object: true, filter: "search", value: d.textValue, diff --git a/src/features/province/services/getDocumentStates.js b/src/features/province/services/getDocumentStates.js index cef9110..c631a00 100644 --- a/src/features/province/services/getDocumentStates.js +++ b/src/features/province/services/getDocumentStates.js @@ -6,9 +6,7 @@ export const getDocumentStates = createAsyncThunk( "GET_DOCUMENT_STATES", async (d, { dispatch }) => { dispatch(LOADING_START()); - const { data, status } = await axios.get("bar-documents-status/", { - params: d, - }); + const { data, status } = await axios.get("bar-documents-status/"); dispatch(LOADING_END()); return { data, status }; } diff --git a/src/features/province/services/main-get-guilds-for-update-or-create.js b/src/features/province/services/main-get-guilds-for-update-or-create.js deleted file mode 100644 index 46de9a7..0000000 --- a/src/features/province/services/main-get-guilds-for-update-or-create.js +++ /dev/null @@ -1,41 +0,0 @@ -import { createAsyncThunk } from "@reduxjs/toolkit"; -import axios from "axios"; -import { LOADING_END, LOADING_START } from "../../../lib/redux/slices/appSlice"; -import { getRoleFromUrl } from "../../../utils/getRoleFromUrl"; - -export const mainGetGuildsForUpdateOrCreateService = createAsyncThunk( - "MAIN_GET_GUILDS_FOR_UPDATE_OR_CREATE_SERVICE", - async (payload, { dispatch }) => { - dispatch(LOADING_START()); - try { - const { data, status } = await axios.get( - "main_get_guilds_for_update_or_create/", - { - params: { - national_code: payload.national_code, - update: payload.update || false, - role: getRoleFromUrl(), - }, - } - ); - dispatch(LOADING_END()); - return { data, status }; - } catch (e) { - dispatch(LOADING_END()); - - if (e.response?.status === 403) { - const errorMessage = - e.response?.data?.result || - e.response?.data?.message || - "دسترسی غیرمجاز"; - return { error: errorMessage, status: 403 }; - } - - const errorMessage = - e.response?.data?.result || - e.response?.data?.message || - "خطا در دریافت اطلاعات"; - return { error: errorMessage }; - } - } -); diff --git a/src/features/province/services/payment-get-deadlines.js b/src/features/province/services/payment-get-deadlines.js index e363313..7412771 100644 --- a/src/features/province/services/payment-get-deadlines.js +++ b/src/features/province/services/payment-get-deadlines.js @@ -3,10 +3,8 @@ import axios from "axios"; export const paymentGetDeadLines = createAsyncThunk( "PAYMENT_GET_DEADLINES", - async (d) => { - const { data, status } = await axios.get("direct-buying-verification/", { - params: d, - }); + async () => { + const { data, status } = await axios.get("direct-buying-verification/"); return { data, status }; } ); diff --git a/src/features/province/services/province-cars-dashboard.js b/src/features/province/services/province-cars-dashboard.js index 07c456d..6af4087 100644 --- a/src/features/province/services/province-cars-dashboard.js +++ b/src/features/province/services/province-cars-dashboard.js @@ -12,7 +12,6 @@ export const provinceCarsDashboardService = createAsyncThunk( { params: { role: getRoleFromUrl(), - ...data, }, } ); diff --git a/src/features/province/services/province-dashboard-bar-diffrence-get-request.js b/src/features/province/services/province-dashboard-bar-diffrence-get-request.js index 4775054..8b0fd81 100644 --- a/src/features/province/services/province-dashboard-bar-diffrence-get-request.js +++ b/src/features/province/services/province-dashboard-bar-diffrence-get-request.js @@ -12,7 +12,6 @@ export const provinceGetDashboardBarDiffrenceRequest = createAsyncThunk( { params: { role: getRoleFromUrl(), - role_key: d.role_key || "", state: d.state, filter: "search", value: d.value, diff --git a/src/features/province/services/province-get-allocated-requests.js b/src/features/province/services/province-get-allocated-requests.js index db30b0a..b5c78f2 100644 --- a/src/features/province/services/province-get-allocated-requests.js +++ b/src/features/province/services/province-get-allocated-requests.js @@ -9,7 +9,6 @@ export const provinceGetAllocatedRequestsService = createAsyncThunk( const params = { role: getRoleFromUrl(), - role_key: d.role_key || "", date1: d.selectedDate1, date2: d.selectedDate2, filter: "search", diff --git a/src/features/province/services/province-get-cars.js b/src/features/province/services/province-get-cars.js index 40bc2b8..c30054a 100644 --- a/src/features/province/services/province-get-cars.js +++ b/src/features/province/services/province-get-cars.js @@ -8,7 +8,6 @@ export const provinceGetCars = createAsyncThunk( const { data, status } = await axios.get("kill_house_driver/", { params: { role: getRoleFromUrl(), - ...data, }, }); return { data, status }; diff --git a/src/features/province/services/province-get-deleted-allocated-requests.js b/src/features/province/services/province-get-deleted-allocated-requests.js index 134204f..d87d476 100644 --- a/src/features/province/services/province-get-deleted-allocated-requests.js +++ b/src/features/province/services/province-get-deleted-allocated-requests.js @@ -12,7 +12,6 @@ export const provinceGetDeletedAllocatedRequestsService = createAsyncThunk( { params: { role: getRoleFromUrl(), - role_key: d.role_key || "", date1: d.selectedDate1, date2: d.selectedDate2, filter: "search", diff --git a/src/features/province/services/province-get-direct-buying-poultry-requests.js b/src/features/province/services/province-get-direct-buying-poultry-requests.js index 08abf7c..9dd2442 100644 --- a/src/features/province/services/province-get-direct-buying-poultry-requests.js +++ b/src/features/province/services/province-get-direct-buying-poultry-requests.js @@ -41,3 +41,4 @@ export const provinceGetDirectBuyingPoultryRequests = createAsyncThunk( } } ); + diff --git a/src/features/province/services/province-get-total-guilds.js b/src/features/province/services/province-get-total-guilds.js index 41d9b0c..07dd8ab 100644 --- a/src/features/province/services/province-get-total-guilds.js +++ b/src/features/province/services/province-get-total-guilds.js @@ -14,7 +14,6 @@ export const provinceGetTotalGuildsService = createAsyncThunk( steward = false, active_state = "active", is_real_person = true, - role_key = "", }, { dispatch } ) => { @@ -30,7 +29,6 @@ export const provinceGetTotalGuildsService = createAsyncThunk( steward, active_state, is_real_person, - role_key: role_key, }, }); dispatch(LOADING_END()); @@ -38,11 +36,9 @@ export const provinceGetTotalGuildsService = createAsyncThunk( } catch (e) { dispatch(LOADING_END()); return { - error: - e.response?.data?.result || - e.response?.data || - "خطا در دریافت اطلاعات", + error: e.response?.data?.result || e.response?.data || "خطا در دریافت اطلاعات", }; } } ); + diff --git a/src/features/province/services/province-policy-edit-trade-time-range.js b/src/features/province/services/province-policy-edit-trade-time-range.js index 4d088fe..e34a93f 100644 --- a/src/features/province/services/province-policy-edit-trade-time-range.js +++ b/src/features/province/services/province-policy-edit-trade-time-range.js @@ -1,7 +1,6 @@ import { createAsyncThunk } from "@reduxjs/toolkit"; import axios from "axios"; import { LOADING_END, LOADING_START } from "../../../lib/redux/slices/appSlice"; -import { getRoleFromUrl } from "../../../utils/getRoleFromUrl"; export const provincePolicyEditTradeTimeRange = createAsyncThunk( "PROVINCE_POLICY_EDIT_TRADE_TIME_RANGE", @@ -17,11 +16,7 @@ export const provincePolicyGetTradeTimeRagnge = createAsyncThunk( "PROVINCE_POLICY_GET_TRADE_TIME_RANGE", async (d, { dispatch }) => { dispatch(LOADING_START()); - const { data, status } = await axios.get("show-market-requests", { - params: { - role: getRoleFromUrl(), - }, - }); + const { data, status } = await axios.get("show-market-requests/"); dispatch(LOADING_END()); return { data, status }; } diff --git a/src/features/province/services/province-policy-get-slaughter-buying-price-status.js b/src/features/province/services/province-policy-get-slaughter-buying-price-status.js index ce2e777..6d03a15 100644 --- a/src/features/province/services/province-policy-get-slaughter-buying-price-status.js +++ b/src/features/province/services/province-policy-get-slaughter-buying-price-status.js @@ -9,10 +9,7 @@ export const provincePolicyGetSLaughterSubmitBuyingPriceStatus = try { dispatch(LOADING_START()); const { data, status } = await axios.get( - "kill-house-price-permission/", - { - params: d, - } + "kill-house-price-permission/" ); dispatch(LOADING_END()); return { data, status }; diff --git a/src/features/province/services/province-policy-get-weight-range.js b/src/features/province/services/province-policy-get-weight-range.js index 73a5ad3..f3c19f7 100644 --- a/src/features/province/services/province-policy-get-weight-range.js +++ b/src/features/province/services/province-policy-get-weight-range.js @@ -6,9 +6,7 @@ export const provincePolicyGetWeightRange = createAsyncThunk( "PROVINCE_POLICY_GET_WEIGHT_RANGE", async (d, { dispatch }) => { dispatch(LOADING_START()); - const { data, status } = await axios.get("management_hatching_age_range/", { - params: d, - }); + const { data, status } = await axios.get("management_hatching_age_range/"); dispatch(LOADING_END()); return { data, status }; } diff --git a/src/features/province/services/province-policy-upload-image.js b/src/features/province/services/province-policy-upload-image.js index 48724c2..456a1d8 100644 --- a/src/features/province/services/province-policy-upload-image.js +++ b/src/features/province/services/province-policy-upload-image.js @@ -7,9 +7,7 @@ export const provincePolicyGetUploadImageService = createAsyncThunk( async (d, { dispatch }) => { try { dispatch(LOADING_START()); - const { data, status } = await axios.get("/upload-image-limit/", { - params: d, - }); + const { data, status } = await axios.get("/upload-image-limit/"); dispatch(LOADING_END()); return { data, status }; } catch (e) { diff --git a/src/features/province/services/province-policy-validate-poultry-wth-sms-service.js b/src/features/province/services/province-policy-validate-poultry-wth-sms-service.js index 0ebda5f..e8c4d0e 100644 --- a/src/features/province/services/province-policy-validate-poultry-wth-sms-service.js +++ b/src/features/province/services/province-policy-validate-poultry-wth-sms-service.js @@ -8,9 +8,7 @@ export const provincePolicyValidatePoultryWithSmsStatusService = async (d, { dispatch }) => { try { dispatch(LOADING_START()); - const { data, status } = await axios.get("price-confirmation", { - params: d, - }); + const { data, status } = await axios.get("price-confirmation/"); dispatch(LOADING_END()); return { data, status }; } catch (e) { diff --git a/src/features/province/services/province-trade-panel-market-request-overview.js b/src/features/province/services/province-trade-panel-market-request-overview.js index c445cb3..f474f5f 100644 --- a/src/features/province/services/province-trade-panel-market-request-overview.js +++ b/src/features/province/services/province-trade-panel-market-request-overview.js @@ -4,11 +4,14 @@ import { getRoleFromUrl } from "../../../utils/getRoleFromUrl"; export const provinceTradePanelMarketRequestOverview = createAsyncThunk( "PROVINCE_GET_TRADE_PANEL_MARKET_REQUEST", - async (d) => { + async (d, { dispatch }) => { try { - const { data, status } = await axios.get(`kill-house-market-info`, { - params: { ...d, role: getRoleFromUrl() || "" }, - }); + const { data, status } = await axios.get( + `kill-house-market-info/?role=${getRoleFromUrl()}`, + { + params: d, + } + ); return { data, status }; } catch (e) { return { error: e.response.data.result }; @@ -18,12 +21,12 @@ export const provinceTradePanelMarketRequestOverview = createAsyncThunk( export const provinceTradePanelMarketRequestAdminOverview = createAsyncThunk( "PROVINCE_GET_TRADE_PANEL_ADMIN_MARKET_REQUEST", - async (d) => { + async (d, { dispatch }) => { try { const { data, status } = await axios.get( `kill-house-market-info-dashboard`, { - params: { ...d, role: getRoleFromUrl() || "" }, + params: d, } ); return { data, status }; diff --git a/src/features/province/services/trade-panel-chat.js b/src/features/province/services/trade-panel-chat.js index 7c8a5e9..1dcd5cb 100644 --- a/src/features/province/services/trade-panel-chat.js +++ b/src/features/province/services/trade-panel-chat.js @@ -4,16 +4,10 @@ import { getRoleFromUrl } from "../../../utils/getRoleFromUrl"; export const tradePanelChart = createAsyncThunk( "TRADE_PANEL_CHART", - async (d) => { + async (d, { dispatch }) => { try { const { data, status } = await axios.get( - `/direct-buying-poultry-requests-chart`, - { - params: { - role: getRoleFromUrl(), - role_key: d?.role_key || "", - }, - } + `/direct-buying-poultry-requests-chart/?role=${getRoleFromUrl()}` ); return { data, status }; } catch (e) { diff --git a/src/features/province/services/update-guild-by-national-id-new.js b/src/features/province/services/update-guild-by-national-id-new.js deleted file mode 100644 index 749662e..0000000 --- a/src/features/province/services/update-guild-by-national-id-new.js +++ /dev/null @@ -1,24 +0,0 @@ -import { createAsyncThunk } from "@reduxjs/toolkit"; -import axios from "axios"; -import { LOADING_END, LOADING_START } from "../../../lib/redux/slices/appSlice"; -import { provinceGetGuildsService } from "./province-get-guilds"; -import { getRoleFromUrl } from "../../../utils/getRoleFromUrl"; - -export const updateGuildByNationalIdNewService = createAsyncThunk( - "UPDATE_GUILD_BY_NATIONAL_ID_NEW_SERVICE", - async (d, { dispatch }) => { - try { - dispatch(LOADING_START()); - const { data, status } = await axios.post( - "update_guild_by_national_id_new/?role=" + getRoleFromUrl(), - d - ); - dispatch(provinceGetGuildsService()); - dispatch(LOADING_END()); - return { data, status }; - } catch (e) { - dispatch(LOADING_END()); - return { error: e.response.data.result }; - } - } -); diff --git a/src/features/psp-company/components/psp-devices-v2/PspDevicesV2.js b/src/features/psp-company/components/psp-devices-v2/PspDevicesV2.js deleted file mode 100644 index 86ec829..0000000 --- a/src/features/psp-company/components/psp-devices-v2/PspDevicesV2.js +++ /dev/null @@ -1,777 +0,0 @@ -import { useContext, useEffect, useState } from "react"; -import { useDispatch } from "react-redux"; -import { - LOADING_END, - LOADING_START, - CLOSE_MODAL, - OPEN_MODAL, - DRAWER, -} from "../../../../lib/redux/slices/appSlice"; -import axios from "axios"; -import { Grid } from "../../../../components/grid/Grid"; -import { SPACING } from "../../../../data/spacing"; -import { - Autocomplete, - Button, - CircularProgress, - IconButton, - List, - ListItem, - ListItemIcon, - ListItemButton, - ListItemText, - Popover, - Switch, - TextField, - Typography, - Box, -} from "@mui/material"; -import { RiSearchLine } from "react-icons/ri"; -import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable"; -import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl"; -import { formatJustDate } from "../../../../utils/formatTime"; -import TuneIcon from "@mui/icons-material/Tune"; -import PersonAddAlt1RoundedIcon from "@mui/icons-material/PersonAddAlt1Rounded"; -import SwapHorizRoundedIcon from "@mui/icons-material/SwapHorizRounded"; -import AddRoundedIcon from "@mui/icons-material/AddRounded"; -import { AppContext } from "../../../../contexts/AppContext"; -import { BackButton } from "../../../../components/back-button/BackButton"; - -const PspDevicesV2 = () => { - const [data, setData] = useState([]); - const [totalRows, setTotalRows] = useState(0); - const [perPage, setPerPage] = useState(10); - const [textValue, setTextValue] = useState(""); - const [page, setPage] = useState(1); - const [tableData, setTableData] = useState([]); - const [companies, setCompanies] = useState([]); - const [selectedCompany, setSelectedCompany] = useState(""); - const dispatch = useDispatch(); - - const fetchCompanies = async () => { - try { - dispatch(LOADING_START()); - const response = await axios.get( - `/get_all_pos_company/?role=${getRoleFromUrl()}` - ); - setCompanies(response.data); - dispatch(LOADING_END()); - } catch (error) { - console.error("Error fetching companies:", error); - dispatch(LOADING_END()); - } - }; - - const fetchApiData = async (page) => { - try { - dispatch(LOADING_START()); - let url = `/user-pos-machine/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}`; - if (selectedCompany) { - url += `&company=${selectedCompany}`; - } - const response = await axios.get(url); - - setData(response.data?.results || []); - setTotalRows(response.data?.count || 0); - } catch (error) { - console.error("Error fetching devices:", error); - } finally { - dispatch(LOADING_END()); - } - }; - - const handlePageChange = (page) => { - fetchApiData(page); - setPage(page); - }; - - const handlePerRowsChange = (perRows) => { - setPerPage(perRows); - setPage(1); - }; - - const handleTextChange = (event) => { - setTextValue(event.target.value); - }; - // const clearFilters = () => { - // setSelectedCompany(""); - // setTextValue(""); - // setPage(1); - // fetchApiData(1); - // }; - - useEffect(() => { - const d = data?.map((item, i) => { - const owner = item?.owner || {}; - const posCompany = item?.pos_company || {}; - const hasOwner = !!item?.owner; - return [ - page === 1 ? i + 1 : i + perPage * (page - 1) + 1, - posCompany?.name || "-", - item?.serial ?? "-", - item?.receiverNumber ?? "-", - item?.terminalNumber ?? "-", - item?.password ?? "-", - item?.posUniqueId || item?.posId || "-", - owner?.fullname ? `${owner?.fullname} (${owner?.mobile ?? "-"})` : "-", - owner?.nationalId || owner?.nationalCode || "-", - item?.createDate ? formatJustDate(item?.createDate) : "-", - item?.active ? "فعال" : "غیرفعال", - { - fetchApiData(page); - }} - />, - ]; - }); - - setTableData(d); - }, [data, page, perPage]); - - useEffect(() => { - fetchCompanies(); - }, [dispatch]); - - useEffect(() => { - fetchApiData(page); - }, [selectedCompany, perPage]); - - const handleSubmit = async (event) => { - event.preventDefault(); - fetchApiData(1); - }; - - const handleDeviceCreated = () => { - setPage(1); - fetchApiData(1); - }; - - const handleOpenCreateDevice = () => { - const isMobile = window.innerWidth <= 600; - dispatch( - DRAWER({ - title: "ایجاد دستگاه", - right: !isMobile, - bottom: isMobile, - content: , - }) - ); - }; - - const tableTitle = ( - - - - {getRoleFromUrl() !== "PosCompany" && ( - { - return { - data: i, - label: `${i?.name || ""}`, - }; - }) - : [] - } - onChange={(event, value) => { - setSelectedCompany(value?.data?.key); - }} - renderInput={(params) => ( - - )} - /> - )} - - - - - - - - - - - - - - ); - - return ( - - - - {tableTitle} - - - - ); -}; - -const DeviceOperations = ({ device, hasOwner, onOwnerAssigned }) => { - const [anchorEl, setAnchorEl] = useState(null); - const [updatingStatus] = useState(false); - const [localActive, setLocalActive] = useState(!!device?.active); - const dispatch = useDispatch(); - const [openNotif] = useContext(AppContext); - - useEffect(() => { - setLocalActive(!!device?.active); - }, [device?.active]); - - const handleOpen = (event) => { - setAnchorEl(event.currentTarget); - }; - - const handleClose = () => { - setAnchorEl(null); - }; - - const handleAddOwner = () => { - handleClose(); - dispatch( - OPEN_MODAL({ - title: hasOwner ? "تغییر مالک" : "افزودن مالک", - width: "auto", - content: ( - - ), - }) - ); - }; - - const open = Boolean(anchorEl); - const id = open ? "device-operations-popover" : undefined; - const actionLabel = hasOwner ? "تغییر مالک" : "افزودن مالک"; - const ActionIcon = hasOwner ? SwapHorizRoundedIcon : PersonAddAlt1RoundedIcon; - const actionColor = hasOwner ? "warning.main" : "success.main"; - const deviceKey = device?.key || device?.id; - - const handleToggleActive = async (event) => { - event.stopPropagation(); - event.preventDefault(); - - if (!deviceKey) { - openNotif({ - vertical: "top", - horizontal: "center", - severity: "error", - msg: "شناسه دستگاه یافت نشد.", - }); - return; - } - }; - - return ( - <> - - - - - - - - - - - - - - - - - - - ); -}; - -const AssignOwnerModal = ({ device, onSuccess }) => { - const dispatch = useDispatch(); - const [openNotif] = useContext(AppContext); - const [options, setOptions] = useState([]); - const [selectedOption, setSelectedOption] = useState(null); - const [loading, setLoading] = useState(false); - const [submitting, setSubmitting] = useState(false); - const [fetchError, setFetchError] = useState(""); - - useEffect(() => { - let isMounted = true; - - const fetchOwners = async () => { - setLoading(true); - setFetchError(""); - setSelectedOption(null); - try { - const response = await axios.get("/users_for_pos/"); - - if (isMounted) { - const rawOptions = Array.isArray(response?.data?.results) - ? response?.data?.results - : Array.isArray(response?.data) - ? response?.data - : []; - - // Normalize the data - const normalizedOptions = rawOptions.map((item) => { - const fullname = item?.fullname || "-"; - const mobile = item?.mobile || ""; - const mobileLabel = mobile ? ` (${mobile})` : ""; - const label = `${fullname}${mobileLabel}`; - - return { - ...item, - label: label || "-", - }; - }); - - setOptions(normalizedOptions); - setSelectedOption( - normalizedOptions.find( - (option) => option?.mobile === device?.owner?.mobile - ) - ); - } - } catch (error) { - if (isMounted) { - setFetchError("دریافت لیست کاربران با خطا مواجه شد."); - console.error("Error fetching users:", error); - } - } finally { - if (isMounted) { - setLoading(false); - } - } - }; - - fetchOwners(); - - return () => { - isMounted = false; - }; - }, [device]); - - const handleCloseModal = () => { - dispatch(CLOSE_MODAL()); - }; - - const handleSubmit = async () => { - if (!selectedOption) { - return; - } - - if (!device?.key && !device?.id) { - openNotif({ - vertical: "top", - horizontal: "center", - severity: "error", - msg: "شناسه دستگاه یافت نشد. لطفاً دوباره تلاش کنید.", - }); - return; - } - - setSubmitting(true); - try { - const payload = { - key: device?.key || device?.id, - recipient_type: "owner", - recipient_key: selectedOption?.key || selectedOption?.id, - }; - - await axios.put("/user-pos-machine/0/", payload); - - openNotif({ - vertical: "top", - horizontal: "center", - severity: "success", - msg: "مالک با موفقیت ثبت شد.", - }); - - if (onSuccess) { - onSuccess(); - } - handleCloseModal(); - } catch (error) { - openNotif({ - vertical: "top", - horizontal: "center", - severity: "error", - msg: - error?.response?.data?.result || - error?.response?.data?.detail || - "ثبت مالک با خطا مواجه شد.", - }); - } finally { - setSubmitting(false); - } - }; - - return ( - - - دستگاه انتخاب شده:{" "} - {device?.serial || - device?.posUniqueId || - device?.posId || - device?.pos_unique_id || - device?.pos_id || - "-"} - - {loading ? ( - - - - ) : ( - option?.group || ""} - loading={loading} - loadingText="در حال دریافت..." - noOptionsText="موردی یافت نشد." - onChange={(event, value) => setSelectedOption(value)} - isOptionEqualToValue={(option, value) => option?.key === value?.key} - getOptionLabel={(option) => option?.label || ""} - renderOption={(props, option) => { - if (!option) return null; - return ( -
  • - - - {option?.label || "-"} - - {option?.city && ( - - {option.city} - - )} - -
  • - ); - }} - renderInput={(params) => ( - - {loading ? ( - - ) : null} - {params.InputProps.endAdornment} - - ), - }} - /> - )} - /> - )} - {fetchError && ( - - {fetchError} - - )} - - - - -
    - ); -}; - -const CreateDeviceDrawer = ({ onSuccess }) => { - const dispatch = useDispatch(); - const [openNotif] = useContext(AppContext); - const [values, setValues] = useState({ - receiver_number: "", - terminal_number: "", - password: "", - serial: "", - }); - const [errors, setErrors] = useState({}); - const [submitting, setSubmitting] = useState(false); - - const closeDrawer = () => { - dispatch(DRAWER({ right: false, bottom: false, content: null })); - }; - - const handleChange = (event) => { - const { name, value } = event.target; - setValues((prev) => ({ ...prev, [name]: value })); - if (errors[name]) { - setErrors((prev) => ({ ...prev, [name]: "" })); - } - }; - - const validate = () => { - const newErrors = {}; - if (!values.receiver_number?.trim()) { - newErrors.receiver_number = "وارد کردن شماره پذیرنده الزامی است."; - } - if (!values.terminal_number?.trim()) { - newErrors.terminal_number = "وارد کردن شماره ترمینال الزامی است."; - } - if (!values.password?.trim()) { - newErrors.password = "وارد کردن رمز عبور الزامی است."; - } - if (!values.serial?.trim()) { - newErrors.serial = "وارد کردن سریال دستگاه الزامی است."; - } - - setErrors(newErrors); - return Object.keys(newErrors).length === 0; - }; - - const handleSubmit = async (event) => { - event.preventDefault(); - if (!validate()) { - return; - } - - setSubmitting(true); - try { - await axios.post("/new-pos-machine/", { - receiver_number: values.receiver_number.trim(), - terminal_number: values.terminal_number.trim(), - password: values.password.trim(), - serial: values.serial.trim(), - }); - - openNotif({ - vertical: "top", - horizontal: "center", - severity: "success", - msg: "دستگاه با موفقیت ایجاد شد.", - }); - - if (onSuccess) { - onSuccess(); - } - closeDrawer(); - } catch (error) { - openNotif({ - vertical: "top", - horizontal: "center", - severity: "error", - msg: - error?.response?.data?.result || - error?.response?.data?.detail || - "ایجاد دستگاه با خطا مواجه شد.", - }); - } finally { - setSubmitting(false); - } - }; - - return ( - - - - - - - - - - - ); -}; - -export default PspDevicesV2; diff --git a/src/features/psp-company/components/psp-devices/PspDevices.js b/src/features/psp-company/components/psp-devices/PspDevices.js index b6f10b9..3f8d051 100644 --- a/src/features/psp-company/components/psp-devices/PspDevices.js +++ b/src/features/psp-company/components/psp-devices/PspDevices.js @@ -79,8 +79,8 @@ export const PspDevices = () => { } const response = await axios.get(url); - setData(response.data?.results || []); - setTotalRows(response.data?.count || 0); + setData(response.data.results); + setTotalRows(response.data.count); } catch (error) { console.error("Error fetching devices:", error); } finally { @@ -201,11 +201,11 @@ export const PspDevices = () => { disablePortal id="session" options={ - Array.isArray(companies) + companies ? companies.map((i) => { return { data: i, - label: `${i?.name || ""}`, + label: `${i?.name}`, }; }) : [] @@ -602,48 +602,43 @@ const AssignOwnerModal = ({ device, onSuccess }) => { onChange={(event, value) => setSelectedOption(value)} isOptionEqualToValue={(option, value) => option?.key === value?.key} getOptionLabel={(option) => option?.label || ""} - renderOption={(props, option) => { - if (!option) return null; - return ( -
  • - - {ownerType === "kill_house" ? ( - <> - - {`${option?.unitName || option?.fullname || ""}${ - option?.mobile ? ` (${option.mobile})` : "" - }`} - - - {`${option?.meta || ""}${ - option?.city ? ` | ${option.city}` : "" - }`.replace(/^ \| /, "")} - - - ) : ( - <> - - {`${option?.guildsName || ""}${ - option?.user?.mobile ? ` (${option.user.mobile})` : "" - }`} - - - {`${option?.typeActivity || ""}${ - option?.areaActivity - ? ` | ${option.areaActivity}` - : "" - }${option?.user?.city ? ` | ${option.user.city}` : ""}${ - option?.licenseNumber - ? ` | شناسه : ${option.licenseNumber}` - : "" - }`.replace(/^ \| /, "")} - - - )} - -
  • - ); - }} + renderOption={(props, option) => ( +
  • + + {ownerType === "kill_house" ? ( + <> + + {`${option?.unitName || option?.fullname || ""}${ + option?.mobile ? ` (${option.mobile})` : "" + }`} + + + {`${option?.meta || ""}${ + option?.city ? ` | ${option.city}` : "" + }`.replace(/^ \| /, "")} + + + ) : ( + <> + + {`${option?.guildsName || ""}${ + option?.user?.mobile ? ` (${option.user.mobile})` : "" + }`} + + + {`${option?.typeActivity || ""}${ + option?.areaActivity ? ` | ${option.areaActivity}` : "" + }${option?.user?.city ? ` | ${option.user.city}` : ""}${ + option?.licenseNumber + ? ` | شناسه : ${option.licenseNumber}` + : "" + }`.replace(/^ \| /, "")} + + + )} + +
  • + )} renderInput={(params) => ( { direction={{ xs: "column", md: "row" }} justifyContent="center" > - - } - title="دستگاه‌ها دوم" - /> - { - return ; -}; diff --git a/src/features/senf/components/SenfInventoryOperation.js b/src/features/senf/components/SenfInventoryOperation.js index 4a5ee26..2f50d1e 100644 --- a/src/features/senf/components/SenfInventoryOperation.js +++ b/src/features/senf/components/SenfInventoryOperation.js @@ -4,11 +4,7 @@ import { Grid } from "../../../components/grid/Grid"; import LinkItem from "../../../components/link-item/LinkItem"; import { NavLink } from "../../../components/nav-link/NavLink"; import { SPACING } from "../../../data/spacing"; -import { - ROUTE_SENF_INVENTORY_SEGMENTATION, - ROUTE_SENF_INVENTORY_STOCK, -} from "../../../routes/routes"; -import ContentCutIcon from "@mui/icons-material/ContentCut"; +import { ROUTE_SENF_INVENTORY_STOCK } from "../../../routes/routes"; export const SenfInventoryOperation = () => { const { pathname } = useLocation(); @@ -28,25 +24,7 @@ export const SenfInventoryOperation = () => { > } - title="ورود به انبار" - /> - - {/* - } - title="ورود به انبار" - /> - */} - - } - title="قطعه بندی" + title="موجودی انبار" />
    diff --git a/src/features/senf/components/SenfSegmentaion.js b/src/features/senf/components/SenfSegmentaion.js deleted file mode 100644 index d00e8ef..0000000 --- a/src/features/senf/components/SenfSegmentaion.js +++ /dev/null @@ -1,320 +0,0 @@ -import { useContext, useEffect, useState } from "react"; -import { useDispatch, useSelector } from "react-redux"; -import moment from "moment"; -import { Button, TextField, Typography } from "@mui/material"; -import { DatePicker } from "@mui/x-date-pickers"; -import { RiSearchLine } from "react-icons/ri"; -import axios from "axios"; -import { AppContext } from "../../../contexts/AppContext"; -import { - DRAWER, - LOADING_END, - LOADING_START, -} from "../../../lib/redux/slices/appSlice"; -import { formatJustDate, formatTime } from "../../../utils/formatTime"; -import { StewardSegmentOperation } from "../../guild/components/StewardSegmentOperation"; -import { getRoleFromUrl } from "../../../utils/getRoleFromUrl"; -import { Grid } from "../../../components/grid/Grid"; -import { SPACING } from "../../../data/spacing"; -import ResponsiveTable from "../../../components/responsive-table/ResponsiveTable"; -import { checkPathStartsWith } from "../../../utils/checkPathStartsWith"; -import { stawardGetSegmentDashboardService } from "../../guild/services/steward-get-dashboard-service"; -import { stewardGetOutSellService } from "../../guild/services/steward-get-sell-out-service"; -import { StewardSegmentSubmitOperation } from "../../guild/components/StewardSegmentSubmitOperation"; - -export const SenfSegmentaion = () => { - const [data, setData] = useState([]); - const [products, setProducts] = useState([]); - const [tableData, setTableData] = useState([]); - const [totalRows, setTotalRows] = useState(0); - const [perPage, setPerPage] = useState(10); - const [textValue, setTextValue] = useState(""); - const [page, setPage] = useState(1); - const [dashboardData, setDashboardData] = useState([]); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); - const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] = - useContext(AppContext); - const dispatch = useDispatch(); - - // const userKey = useSelector((state) => state.userSlice.userProfile.key); - - const getDashboardData = () => { - dispatch( - stawardGetSegmentDashboardService({ - value: textValue, - date1: selectedDate1, - date2: selectedDate2, - role: getRoleFromUrl(), - role_key: - checkPathStartsWith("slaughter") || checkPathStartsWith("senf") - ? selectedSubUser?.key - : "", - }) - ).then((r) => { - setDashboardData(r.payload.data); - }); - }; - - useEffect(() => { - const currentDate = moment(new Date()).format("YYYY-MM-DD"); - setSelectedDate1(currentDate); - setSelectedDate2(currentDate); - }, []); - - const fetchApiData = async (page) => { - dispatch(LOADING_START()); - const response = await axios.get( - `app-segmentation/?search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${perPage}&role=${getRoleFromUrl()}${ - checkPathStartsWith("slaughter") || checkPathStartsWith("senf") - ? `&role_key=${selectedSubUser?.key}` - : "" - }` - ); - - getDashboardData(); - dispatch(LOADING_END()); - setData(response.data.results); - setTotalRows(response.data.count); - }; - - const handlePageChange = (page) => { - fetchApiData(page); - setPage(page); - }; - const updateTable = () => { - fetchApiData(page); - }; - - const handlePerRowsChange = (perRows) => { - setPerPage(perRows); - setPage(1); - }; - - const handleTextChange = (event) => { - setTextValue(event.target.value); - }; - - useEffect(() => { - fetchApiData(1); - dispatch( - stewardGetOutSellService({ - role_key: - checkPathStartsWith("slaughter") || checkPathStartsWith("senf") - ? selectedSubUser?.key || "" - : "", - }) - ).then((r) => { - setProducts(r.payload.data); - }); - }, []); - - useEffect(() => { - const d = data?.map((item, i) => { - return [ - page === 1 ? i + 1 : i + perPage * (page - 1) + 1, - item?.productionDate ? formatTime(item?.productionDate) : "-", - item?.distributionType === "web" - ? "سایت" - : item?.distributionType === "app" - ? "موبایل" - : item?.distributionType === "pos" - ? "پوز" - : item?.distributionType || "-", - `${item?.buyer?.fullname}(${item?.buyer?.mobile})`, - item?.toGuild - ? `به قطعه بند - ${item?.toGuild?.user?.fullname}(${item?.toGuild?.user?.mobile})` - : "قطعه بندی توسط کشتارگاه", - item?.date ? formatJustDate(item?.date) : "-", - item?.weight, - item?.quota === "governmental" - ? "دولتی" - : item?.quota === "free" - ? "آزاد" - : "-", - item?.saleType === "governmental" - ? "دولتی" - : item?.saleType === "free" - ? "آزاد" - : "-", - , - ]; - }); - - setTableData(d); - }, [data]); - - useEffect(() => { - fetchApiData(1); - }, [selectedDate1, selectedDate2, perPage, selectedSubUser?.key]); - - const handleSubmit = async (event) => { - event.preventDefault(); - dispatch(LOADING_START()); - try { - const response = await axios.get( - `app-segmentation/?search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&role=${getRoleFromUrl()}${ - checkPathStartsWith("slaughter") || checkPathStartsWith("senf") - ? `&role_key=${selectedSubUser?.key}` - : "" - }` - ); - setData(response.data.results); - setTotalRows(response.data.count); - getDashboardData(); - dispatch(LOADING_END()); - } catch (error) { - console.error("Error fetching data:", error); - } - }; - - return ( - - - ثبت قطعه بندی - - - - - -
    - - - - - - - ( - - )} - value={selectedDate1} - onChange={(e) => - setSelectedDate1(moment(e).format("YYYY-MM-DD")) - } - /> - - - ( - - )} - value={selectedDate2} - onChange={(e) => - setSelectedDate2(moment(e).format("YYYY-MM-DD")) - } - /> - - {/* - - */} - -
    - - -
    -
    - ); -}; diff --git a/src/features/senf/components/SenfStock.js b/src/features/senf/components/SenfStock.js index cefa26c..f438c3c 100644 --- a/src/features/senf/components/SenfStock.js +++ b/src/features/senf/components/SenfStock.js @@ -1,71 +1,45 @@ -import { Button, TextField, Typography, Tabs, Tab } from "@mui/material"; +import { Button, TextField, Typography } from "@mui/material"; import { DatePicker } from "@mui/x-date-pickers"; import moment from "moment/moment"; import { useContext, useEffect, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { Grid } from "../../../components/grid/Grid"; +import { SimpleTable } from "../../../components/simple-table/SimpleTable"; import { AppContext } from "../../../contexts/AppContext"; import { SPACING } from "../../../data/spacing"; -import { - LOADING_END, - LOADING_START, - OPEN_MODAL, -} from "../../../lib/redux/slices/appSlice"; +import { AdvancedTable } from "../../../components/advanced-table/AdvancedTable"; +import { OPEN_MODAL } from "../../../lib/redux/slices/appSlice"; +import { RegisterEditDeliveryNumberAndWeight } from "../../guild/components/RegisterEditDeliveryNumberAndWeight"; import { GuildReceiveBarOperation } from "../../guild/components/GuildReceiveBarOperation"; -import { senfGetAllocationDashboardService } from "../../guild/services/senf-get-allocation-dashboard"; +import { senfGetInventoryStockService } from "../../guild/services/senf-get-inventory-stock"; import { senfGetInventoryAllocatedService } from "../../guild/services/senf-get-inventory-allocated"; -import { guildSalesInfoDashboardService } from "../../guild/services/guild-sales-info-dashboard"; import { getFaUserRole } from "../../../utils/getFaUserRole"; import { formatJustDate } from "../../../utils/formatTime"; -import { checkPathStartsWith } from "../../../utils/checkPathStartsWith"; -import ResponsiveTable from "../../../components/responsive-table/ResponsiveTable"; -import { RiSearchLine } from "react-icons/ri"; export const SenfStock = () => { const dispatch = useDispatch(); const [dataTable, setDataTable] = useState([]); - const [statusTab, setStatusTab] = useState("pending"); - const [text, setText] = useState(""); - const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] = - useContext(AppContext); - const { - senfGetInventoryStock, - senfGetInventoryAllocated, - guildSalesInfoDashboard, - } = useSelector((state) => state.generalSlice); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser + const [, , selectedDate1, setSelectedDate1] = useContext(AppContext); + const { senfGetInventoryStock, senfGetInventoryAllocated } = useSelector( + (state) => state.generalSlice ); + useEffect(() => { dispatch( - senfGetAllocationDashboardService({ - date1: selectedDate1, - date2: selectedDate2, - role_key: checkPathStartsWith("senf") ? selectedSubUser?.key : "", - search: text, + senfGetInventoryStockService({ + date: selectedDate1, }) ); dispatch( senfGetInventoryAllocatedService({ - date1: selectedDate1, - date2: selectedDate2, - role_key: checkPathStartsWith("senf") ? selectedSubUser?.key : "", - type: statusTab, - search: text, + date: selectedDate1, }) ); - dispatch( - guildSalesInfoDashboardService({ - role_key: checkPathStartsWith("senf") ? selectedSubUser?.key : "", - }) - ); - }, [selectedDate1, selectedDate2, selectedSubUser?.key, statusTab, dispatch]); + }, [selectedDate1]); useEffect(() => { - const items = senfGetInventoryAllocated?.results || []; - - if (items.length > 0) { - const d = items.map((item, i) => { + if (senfGetInventoryAllocated?.length > 0) { + const d = senfGetInventoryAllocated?.map((item, i) => { let state = ""; if (item?.receiverState === "accepted") { state = "تحویل گرفته شده"; @@ -75,24 +49,14 @@ export const SenfStock = () => { state = "در انتظار تحویل"; } - const sellerRoleFa = getFaUserRole(item?.seller_type); - const sellerName = - item?.stewards?.user?.fullname || - item?.stewards?.name || - item?.killHouse?.name || - item?.toKillHouse?.name || - "-"; - const sellerMobile = - item?.stewards?.user?.mobile || - item?.killHouse?.user?.mobile || - item?.toKillHouse?.user?.mobile || - "-"; - return [ i + 1, - `${sellerRoleFa} ${sellerName} (${sellerMobile})`, - formatJustDate(item.date), - (item?.weightOfCarcasses || 0).toLocaleString() + " کیلوگرم", + `${getFaUserRole(item?.seller?.sellerRole)} - ${ + item?.seller?.sellerName + } (${item?.seller?.sellerMobile})`, + formatJustDate(item.createDate), + item?.numberOfCarcasses?.toLocaleString() + " قطعه", + item?.weightOfCarcasses?.toLocaleString() + " کیلوگرم", {item?.receiverRealNumberOfCarcasses && ( <> @@ -106,7 +70,7 @@ export const SenfStock = () => { )} - {/* {item?.receiverState === "pending" && ( + {item?.receiverState === "pending" && ( - )} */} + )} , {item.receiverState === "pending" ? ( @@ -147,193 +111,69 @@ export const SenfStock = () => { }); setDataTable(d); - } else { - setDataTable([]); } - }, [senfGetInventoryAllocated, dispatch]); - - const handleSubmit = async (event) => { - event.preventDefault(); - dispatch(LOADING_START()); - try { - dispatch( - senfGetAllocationDashboardService({ - date1: selectedDate1, - date2: selectedDate2, - role_key: checkPathStartsWith("senf") ? selectedSubUser?.key : "", - search: text, - }) - ); - dispatch( - senfGetInventoryAllocatedService({ - date1: selectedDate1, - date2: selectedDate2, - role_key: checkPathStartsWith("senf") ? selectedSubUser?.key : "", - type: statusTab, - search: text, - }) - ); - } catch (error) { - console.error("Error fetching data:", error); - } finally { - dispatch(LOADING_END()); - } - }; + }, [senfGetInventoryAllocated]); return ( - - - - - ( - - )} - value={selectedDate1} - onChange={(e) => { - setSelectedDate1(moment(e).format("YYYY-MM-DD")); - }} - /> - ( - - )} - value={selectedDate2} - onChange={(e) => { - setSelectedDate2(moment(e).format("YYYY-MM-DD")); - }} - /> -
    - setText(e.target.value)} - /> - - -
    + + موجودی انبار + ( + + )} + value={selectedDate1} + onChange={(e) => { + setSelectedDate1(moment(e).format("YYYY-MM-DD")); + }} + /> + +
    + } + columns={[ + "تعداد بار تخصیصی", + "وزن لاشه تخصیصی", + "حجم لاشه تخصیصی", + "وزن لاشه تحویلی", + "حجم لاشه تحویلی", + ]} + data={[ + [ + senfGetInventoryStock?.barQuantity, + senfGetInventoryStock?.weightOfCarcasses + " کیلوگرم", + senfGetInventoryStock?.numberOfCarcasses + " قطعه", + senfGetInventoryStock?.realWeightOfCarcasses + " کیلوگرم", + senfGetInventoryStock?.realNumberOfCarcasses + " قطعه", + ], + ]} + />
    - - {/* Tabs for filtering by receiver state */} - - setStatusTab(value)} - sx={{ borderBottom: 1, borderColor: "divider", mb: 1 }} - > - - - + + - - row.slice(0, -1)) - : dataTable - } - /> ); }; diff --git a/src/features/slaughter-house-vet/services/slaughter-house-vet-new-requests.js b/src/features/slaughter-house-vet/services/slaughter-house-vet-new-requests.js index 5d291d8..a72d413 100644 --- a/src/features/slaughter-house-vet/services/slaughter-house-vet-new-requests.js +++ b/src/features/slaughter-house-vet/services/slaughter-house-vet-new-requests.js @@ -12,7 +12,6 @@ export const slaughterHouseVetNewRequests = createAsyncThunk( params: { date1: d.selectedDate1, date2: d.selectedDate2, - role_key: d.role_key || "", }, } ); diff --git a/src/features/slaughter-house/components/enter-aggregate-load-information/EnterAggregateLoadInformation.js b/src/features/slaughter-house/components/enter-aggregate-load-information/EnterAggregateLoadInformation.js index a9ff9e8..2953aea 100644 --- a/src/features/slaughter-house/components/enter-aggregate-load-information/EnterAggregateLoadInformation.js +++ b/src/features/slaughter-house/components/enter-aggregate-load-information/EnterAggregateLoadInformation.js @@ -6,7 +6,7 @@ import { Typography, } from "@mui/material"; import axios from "axios"; -import { useContext, useEffect, useState, useMemo, useCallback } from "react"; +import { useContext, useEffect, useState } from "react"; import moment from "moment"; import { DatePicker } from "@mui/x-date-pickers"; import { AppContext } from "../../../../contexts/AppContext"; @@ -34,276 +34,126 @@ import EditIcon from "@mui/icons-material/Edit"; import AddCircleOutlineIcon from "@mui/icons-material/AddCircleOutline"; import { provincePolicyGetWeightRange } from "../../../province/services/province-policy-get-weight-range"; import { isValidIndexWeight } from "../../../../utils/isValidIndexWeight"; -import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; - -// Constants -const ROLES = { - PROVINCE_OPERATOR: "ProvinceOperator", - SUPER_ADMIN: "SuperAdmin", - ADMIN_X: "AdminX", - SUPPORTER: "Supporter", - VET_SUPERVISOR: "VetSupervisor", - VET_FARM: "VetFarm", - CITY_VET: "CityVet", -}; - -const KILL_TYPES = { - FREEZING: "انجماد", - EXPORT: "صادرات", - NORMAL: "عادی", -}; - -const DEFAULT_PER_PAGE = 10; -const DEFAULT_PAGE = 1; - -// Helper functions -const formatDate = (date) => { - if (!date) return "-"; - return format(new Date(date), "yyyy/MM/dd"); -}; - -const formatCurrency = (value) => { - return value ? `${value.toLocaleString()} ﷼` : "-"; -}; - -const formatNumber = (value) => { - return value ? value.toLocaleString() : "-"; -}; - -const formatUserInfo = (name, mobile) => { - return name && mobile ? `${name} (${mobile})` : "-"; -}; - -const getKillType = (item) => { - if (item?.poultryRequest?.freezing) return KILL_TYPES.FREEZING; - if (item?.poultryRequest?.export) return KILL_TYPES.EXPORT; - return KILL_TYPES.NORMAL; -}; - -const buildApiUrl = (params) => { - const { textValue, role, date1, date2, page, perPage, roleKey } = params; - const baseUrl = "kill_house_request_aggregate_load/"; - const queryParams = new URLSearchParams({ - check: "", - search: "filter", - value: textValue || "", - role: role || "", - date1: date1 || "", - date2: date2 || "", - page: page || DEFAULT_PAGE, - page_size: perPage || DEFAULT_PER_PAGE, - }); - - if (roleKey) { - queryParams.append("role_key", roleKey); - } - - return `${baseUrl}?${queryParams.toString()}`; -}; - -const buildExcelUrl = (params) => { - const { baseURL, date1, date2, role, roleKey, userKey, textValue } = params; - const queryParams = new URLSearchParams({ - start: date1 || "", - end: date2 || "", - role: role || "", - state: "bar_pending", - key: userKey || "", - search: "filter", - value: textValue || "", - }); - - if (roleKey) { - queryParams.append("role_key", roleKey); - } - - return `${baseURL}bar_excel/?${queryParams.toString()}`; -}; - -const isTrafficCodeEditable = (role, item) => { - const adminRoles = [ - ROLES.PROVINCE_OPERATOR, - ROLES.SUPER_ADMIN, - ROLES.ADMIN_X, - ROLES.SUPPORTER, - ROLES.VET_SUPERVISOR, - ]; - - if (adminRoles.includes(role)) { - return true; - } - - const vetRoles = [ROLES.VET_FARM, ROLES.CITY_VET]; - return ( - item.trash !== true && - item.assignmentStateArchive === "pending" && - !item?.clearanceCode && - vetRoles.includes(role) - ); -}; export const EnterAggregateLoadInformation = () => { - const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] = - useContext(AppContext); - - // Redux const userKey = useSelector((state) => state.userSlice.userProfile.key); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); - const dispatch = useDispatch(); - // State const [data, setData] = useState([]); const [totalRows, setTotalRows] = useState(0); - const [perPage, setPerPage] = useState(DEFAULT_PER_PAGE); + const [perPage, setPerPage] = useState(10); const [textValue, setTextValue] = useState(""); - const [page, setPage] = useState(DEFAULT_PAGE); + const [page, setPage] = useState(1); const [tableData, setTableData] = useState([]); - const [dashboardData, setDashboardData] = useState([]); - // Memoized values - const currentRole = useMemo(() => getRoleFromUrl(), []); - const roleKey = useMemo( - () => (checkPathStartsWith("slaughter") ? selectedSubUser?.key || "" : ""), - [selectedSubUser?.key] - ); - - // Initialize dates - useEffect(() => { - const currentDate = moment(new Date()).format("YYYY-MM-DD"); - setSelectedDate1(currentDate); - setSelectedDate2(currentDate); - }, [setSelectedDate1, setSelectedDate2]); - - // Fetch API data - const fetchApiData = useCallback( - async (pageNumber = page) => { - dispatch(LOADING_START()); - try { - const url = buildApiUrl({ - textValue, - role: currentRole, - date1: selectedDate1, - date2: selectedDate2, - page: pageNumber, - perPage, - roleKey, - }); - - const response = await axios.get(url); - setData(response.data.results); - setTotalRows(response.data.count); - } catch (error) { - console.error("Error fetching data:", error); - } finally { - dispatch(LOADING_END()); - } - }, - [ - textValue, - currentRole, - selectedDate1, - selectedDate2, - perPage, - roleKey, - page, - dispatch, - ] - ); - - // Fetch dashboard data - const fetchDashboardData = useCallback(() => { - dispatch( - slaughterEnterLoadInformationGetDashboard({ - selectedDate1, - selectedDate2, - text: textValue, - role_key: roleKey, - }) - ).then((r) => { - setDashboardData(r.payload.data); - }); - }, [selectedDate1, selectedDate2, textValue, roleKey, dispatch]); - - // Handlers - const handlePageChange = (newPage) => { - fetchApiData(newPage); - setPage(newPage); - }; - - const handlePerRowsChange = (newPerRows) => { - setPerPage(newPerRows); - setPage(DEFAULT_PAGE); - }; - - const handleSubmit = async (event) => { - event.preventDefault(); - await fetchApiData(DEFAULT_PAGE); - fetchDashboardData(); - setPage(DEFAULT_PAGE); - }; + const dispatch = useDispatch(); const handleTextChange = (event) => { setTextValue(event.target.value); }; - const handleDateChange1 = (date) => { - if (date) { - setSelectedDate1(moment(date).format("YYYY-MM-DD")); - } - }; + const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] = + useContext(AppContext); - const handleDateChange2 = (date) => { - if (date) { - setSelectedDate2(moment(date).format("YYYY-MM-DD")); - } - }; - - const handleOpenModal = useCallback( - (item) => { - dispatch( - OPEN_MODAL({ - title: "ثبت اطلاعات بار", - content: , - }) - ); - }, - [dispatch, fetchApiData] - ); - - // Initial data fetch useEffect(() => { - fetchApiData(DEFAULT_PAGE); - fetchDashboardData(); - // eslint-disable-next-line react-hooks/exhaustive-deps + const currentDate = moment(new Date()).format("YYYY-MM-DD"); + setSelectedDate1(currentDate); + setSelectedDate2(currentDate); }, []); - // Refetch when filters change - useEffect(() => { - fetchApiData(DEFAULT_PAGE); - fetchDashboardData(); - setPage(DEFAULT_PAGE); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [selectedDate1, selectedDate2, perPage, roleKey]); + const fetchApiData = async (page) => { + dispatch(LOADING_START()); + const response = await axios.get( + `kill_house_request_aggregate_load/?check&search=filter&value=${textValue}&role=${getRoleFromUrl()}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${perPage}` + ); + dispatch(LOADING_END()); + setData(response.data.results); + setTotalRows(response.data.count); - // Transform data to table format - useEffect(() => { - const transformedData = data?.map((item, i) => { - const rowNumber = - page === DEFAULT_PAGE ? i + 1 : i + perPage * (page - 1) + 1; - const hasAssignmentInfo = !!item?.assignmentInfo?.realQuantity; + dispatch(LOADING_END()); + }; + const handlePageChange = (page) => { + fetchApiData(page); + setPage(page); + }; + + const handlePerRowsChange = (perRows) => { + setPage(1); + setPerPage(perRows, fetchApiData(1)); + }; + + // const updateTable = () => { + // fetchApiData(page !== 0 ? page : 1); + // }; + + useEffect(() => { + fetchApiData(1); + }, []); + + const handleSubmit = async (event) => { + event.preventDefault(); + dispatch(LOADING_START()); + + try { + const response = await axios.get( + `kill_house_request_aggregate_load/?check&role=${getRoleFromUrl()}&search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${1}&page_size=${perPage}` + ); + setData(response.data.results); + setTotalRows(response.data.count); + dispatch(LOADING_END()); + } catch (error) { + console.error("Error fetching data:", error); + } + }; + + useEffect(() => { + fetchApiData(1); + }, [selectedDate1, selectedDate2, perPage]); + + const [dashboardData, setDashboardData] = useState([]); + + useEffect(() => { + dispatch( + slaughterEnterLoadInformationGetDashboard({ + selectedDate1, + selectedDate2, + text: textValue, + }) + ).then((r) => { + setDashboardData(r.payload.data); + }); + }, [selectedDate1, selectedDate2]); + + useEffect(() => { + const d = data?.map((item, i) => { return [ - rowNumber, - hasAssignmentInfo ? ( - - {formatNumber(item?.assignmentInfo?.realQuantity)} قطعه - {formatNumber(item?.assignmentInfo?.netWeight)} کیلوگرم + page === 1 ? i + 1 : i + perPage * (page - 1) + 1, + item?.assignmentInfo?.realQuantity ? ( + + + {item?.assignmentInfo?.realQuantity?.toLocaleString()} قطعه + + + {item?.assignmentInfo?.netWeight?.toLocaleString()} کیلوگرم + handleOpenModal(item)} + onClick={() => { + dispatch( + OPEN_MODAL({ + title: "ثبت اطلاعات بار", + content: ( + + ), + }) + ); + }} size="small" > @@ -311,148 +161,111 @@ export const EnterAggregateLoadInformation = () => { ) : ( - + handleOpenModal(item)} + onClick={() => { + dispatch( + OPEN_MODAL({ + title: "ثبت اطلاعات بار", + content: ( + + ), + }) + ); + }} size="small" > ), - item?.assingmentInformation?.carWeightWithLoadImage ? ( - - + <> + {item?.assingmentInformation?.carWeightWithLoadImage ? ( + + + + + + ) : ( - - ) : ( - - ), - , - , + )} + , + , + , {item.barCode} , - , - formatCurrency(item?.amount), - formatDate(item?.poultryRequest?.sendDate), - formatUserInfo( - item.killhouseUser?.name, - item.killhouseUser?.killHouseOperator?.user?.mobile - ), - item?.killer - ? formatUserInfo( - item.killer?.name, - item.killer?.killHouseOperator?.user?.mobile - ) + <> + + , + item?.amount?.toLocaleString() + " ﷼", + item?.poultryRequest.sendDate + ? format(new Date(item?.poultryRequest.sendDate), "yyyy/MM/dd") : "-", - formatUserInfo( - item.poultryRequest?.poultry?.unitName, - item.poultryRequest?.poultry?.user?.mobile - ), - item?.poultryRequest?.age || "-", - formatNumber(item.quantity), - formatNumber(item?.weightInfo?.weight), - formatCurrency(item?.poultryRequest?.amount), - formatCurrency(item?.weightInfo?.killHousePrice), - `${item.addCar?.driver?.typeCar || ""} ${ - item.addCar?.driver?.pelak || "" - }`.trim() || "-", - formatUserInfo( - item.addCar?.driver?.driverName, - item.addCar?.driver?.driverMobile - ), - formatNumber(item.vetAcceptedRealQuantity), - formatNumber(item.vetAcceptedRealWeight), - item?.poultryRequest?.orderCode || "-", - item?.finalBarState || "-", - getKillType(item), + `${item.killhouseUser?.name} (${item.killhouseUser?.killHouseOperator?.user?.mobile})`, + item?.killer + ? `${item?.killer?.name} (${item?.killer?.killHouseOperator?.user?.mobile})` + : "-", + `${item.poultryRequest?.poultry?.unitName} (${item.poultryRequest.poultry?.user?.mobile})`, + item?.poultryRequest?.age, + item.quantity?.toLocaleString(), + item?.weightInfo?.weight?.toLocaleString(), + item?.poultryRequest?.amount?.toLocaleString() + " ﷼", + item?.weightInfo?.killHousePrice?.toLocaleString() + " ﷼", + `${item.addCar.driver.typeCar} ${item.addCar.driver.pelak}`, + `${item.addCar.driver.driverName} (${item.addCar.driver.driverMobile})`, + item.vetAcceptedRealQuantity?.toLocaleString(), + item.vetAcceptedRealWeight?.toLocaleString(), + item?.poultryRequest.orderCode, + item?.finalBarState, + + item?.poultryRequest?.freezing + ? "انجماد" + : item?.poultryRequest?.export + ? "صادرات" + : "عادی", ]; }); - setTableData(transformedData || []); - }, [data, page, perPage, currentRole, handleOpenModal, fetchApiData]); - - // Table columns - const dashboardColumns = [ - "تعداد بار", - "مجموع تعداد اولیه", - "مجموع وزن اولیه (کیلوگرم)", - "مجموع تعداد تحویلی دامپزشک", - "مجموع وزن تحویلی دامپزشک (کیلوگرم)", - ]; - - const tableColumns = [ - "ردیف", - "تعداد/وزن خالص", - "سند", - "بارنامه خالی", - "بارنامه پر", - "کدبار", - "کد بهداشتی حمل و نقل", - "قیمت مرغ زنده‌ی بار", - "تاریخ کشتار", - "خریدار", - "کشتارکن اختصاصی", - "مرغدار", - "سن مرغ", - "تعداد اولیه", - "وزن اولیه بار (کیلوگرم)", - "قیمت مرغدار", - "قیمت کشتارگاه", - "ماشین", - "راننده", - "تحویلی دامپزشک (قطعه)", - "وزن تحویلی دامپزشک (کیلوگرم)", - "کدسفارش کشتار", - "وضعیت بار", - "نوع کشتار", - ]; - - const dashboardRow = [ - formatNumber(dashboardData?.lenKillHouseRequest), - formatNumber(dashboardData?.firstQuantity), - formatNumber(dashboardData?.firstWeight), - formatNumber(dashboardData?.vetAcceptedRealQuantity), - formatNumber(dashboardData?.vetAcceptedRealWeight), - ]; - - const excelUrl = buildExcelUrl({ - baseURL: axios.defaults.baseURL, - date1: selectedDate1, - date2: selectedDate2, - role: currentRole, - roleKey, - userKey, - textValue, - }); + setTableData(d); + }, [data]); return ( @@ -468,6 +281,7 @@ export const EnterAggregateLoadInformation = () => { ( { /> )} value={selectedDate1} - onChange={handleDateChange1} + onChange={(e) => { + setSelectedDate1(moment(e).format("YYYY-MM-DD")); + }} /> ( { /> )} value={selectedDate2} - onChange={handleDateChange2} + onChange={(e) => { + setSelectedDate2(moment(e).format("YYYY-MM-DD")); + }} />
    - {!!data?.length && ( - + @@ -520,19 +349,58 @@ export const EnterAggregateLoadInformation = () => { )}
    - + { const Operation = ({ item, fetchApiData }) => { const [openNotif] = useContext(AppContext); const { weightRange } = useSelector((state) => state.provinceSlice); - const dispatch = useDispatch(); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); - const currentRole = useMemo(() => getRoleFromUrl(), []); - - // Fetch weight range on mount useEffect(() => { - dispatch( - provincePolicyGetWeightRange({ - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) - ); - }, [selectedSubUser?.key]); - - // Validation helpers - const validateNumeric = (value) => /^\d+$/.test(value); - - const checkVolumeLimits = (quantity) => { - const { maximumLoadVolumeReduction, maximumLoadVolumeIncrease } = - item?.killhouseUser || {}; - const acceptedQuantity = item?.acceptedRealQuantity || 0; - - if ( - maximumLoadVolumeReduction !== 0 && - quantity < acceptedQuantity * (1 - maximumLoadVolumeReduction / 100) - ) { - return { - isValid: false, - message: - "حجم وارد شده با مجوز حداکثر افزایش/کاهش ورود اطلاعات بار مطابقت ندارد!", - }; - } - - if ( - maximumLoadVolumeIncrease !== 0 && - quantity > acceptedQuantity * (1 + maximumLoadVolumeIncrease / 100) - ) { - return { - isValid: false, - message: - "حجم وارد شده با مجوز حداکثر افزایش/کاهش ورود اطلاعات بار مطابقت ندارد!", - }; - } - - return { isValid: true }; - }; - - const checkWeightValidation = (weight, quantity) => { - const adminRoles = [ROLES.SUPER_ADMIN, ROLES.ADMIN_X]; - if (adminRoles.includes(currentRole)) { - return { isValid: true }; - } - - const averageWeight = parseInt(weight) / parseInt(quantity); - if ( - !isValidIndexWeight(weightRange, item?.poultryRequest?.age, averageWeight) - ) { - return { - isValid: false, - message: - "میانگین وزنی با احراز سنی مطابقت ندارد. لطفا با اتحادیه تماس بگیرید.", - }; - } - - return { isValid: true }; - }; - + dispatch(provincePolicyGetWeightRange()); + }, []); + const dispatch = useDispatch(); const formik = useFormik({ initialValues: { quantity: "", weight: "", }, - onSubmit: async (values) => { - // Validate volume limits - const volumeCheck = checkVolumeLimits(parseInt(values.quantity)); - if (!volumeCheck.isValid) { + onSubmit: (values) => { + // Handle form submission + if ( + (item?.killhouseUser?.maximumLoadVolumeReduction !== 0 && + formik.values.quantity < + item?.acceptedRealQuantity * + (1 - item?.killhouseUser?.maximumLoadVolumeReduction / 100)) || + (item?.killhouseUser?.maximumLoadVolumeIncrease !== 0 && + formik.values.quantity > + item?.acceptedRealQuantity * + (1 + item?.killhouseUser?.maximumLoadVolumeIncrease / 100)) + ) { openNotif({ vertical: "top", horizontal: "center", - msg: volumeCheck.message, + msg: "حجم وارد شده با مجوز حداکثر افزایش/کاهش ورود اطلاعات بار مطابقت ندارد!", severity: "error", }); - return; - } - - // Validate weight - const weightCheck = checkWeightValidation(values.weight, values.quantity); - if (!weightCheck.isValid) { + } else if ( + getRoleFromUrl() !== "SuperAdmin" && + getRoleFromUrl() !== "AdminX" && + !isValidIndexWeight( + weightRange, + item?.poultryRequest?.age, + parseInt(formik.values.weight) / parseInt(formik.values.quantity) + ) + ) { openNotif({ vertical: "top", horizontal: "center", - msg: weightCheck.message, - severity: "error", - }); - return; - } - - // Submit data - const result = await dispatch( - salughterAggregateQuantityService({ - kill_house_request_key: item.key, - role: currentRole, - net_weight: values.weight, - exploited_carcass: 0, - real_quantity: values.quantity, - }) - ); - - if (result.payload.error) { - openNotif({ - vertical: "top", - horizontal: "center", - msg: result.payload.error, + msg: "میانگین وزنی با احراز سنی مطابقت ندارد. لطفا با اتحادیه تماس بگیرید.", severity: "error", }); } else { - openNotif({ - vertical: "top", - horizontal: "center", - msg: "عملیات با موفقیت انجام شد.", - severity: "success", + dispatch( + salughterAggregateQuantityService({ + kill_house_request_key: item.key, + role: getRoleFromUrl(), + net_weight: values.weight, + exploited_carcass: 0, + real_quantity: values.quantity, + }) + ).then((r) => { + if (r.payload.error) { + openNotif({ + vertical: "top", + horizontal: "center", + msg: r.payload.error, + severity: "error", + }); + } else { + openNotif({ + vertical: "top", + horizontal: "center", + msg: "عملیات با موفقیت انجام شد.", + severity: "success", + }); + dispatch(CLOSE_MODAL()); + fetchApiData(1); + } }); - dispatch(CLOSE_MODAL()); - fetchApiData(DEFAULT_PAGE); } }, validate: (values) => { const errors = {}; - if (!validateNumeric(values.weight)) { + if (!/^\d+$/.test(values.weight)) { errors.weight = "لطفا عدد وارد کنید"; } - if (!validateNumeric(values.quantity)) { + if (!/^\d+$/.test(values.quantity)) { errors.quantity = "لطفا عدد وارد کنید"; } return errors; diff --git a/src/features/slaughter-house/components/enter-load-information/EnterLoadInformation.js b/src/features/slaughter-house/components/enter-load-information/EnterLoadInformation.js index ee26b87..7d7431e 100644 --- a/src/features/slaughter-house/components/enter-load-information/EnterLoadInformation.js +++ b/src/features/slaughter-house/components/enter-load-information/EnterLoadInformation.js @@ -1,4 +1,4 @@ -import { useContext, useEffect, useState, useMemo, useCallback } from "react"; +import { useContext, useEffect, useState } from "react"; import { AppContext } from "../../../../contexts/AppContext"; import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl"; import { slaughterGetPermissionToVetService } from "../../services/slaughter-get-premisson-to-vet"; @@ -11,7 +11,7 @@ import { LOADING_END, LOADING_START, } from "../../../../lib/redux/slices/appSlice"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; import { format } from "date-fns-jalali"; import axios from "axios"; import { VetFarmEditTrafficCode } from "../../../vet-farm/components/vet-farm-edit-traffic-code/VetFarmEditTrafficCode"; @@ -20,348 +20,185 @@ import { slaughterEnterLoadInformationGetDashboard } from "../../services/slaugh import { Grid } from "../../../../components/grid/Grid"; import { RiSearchLine } from "react-icons/ri"; import { SlaughterEnterInformationOperation } from "../slaughter-enter-information-operation/SlaughterEnterInformationOperation"; -import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; - -// Constants -const ROLES = { - KILL_HOUSE: "KillHouse", - PROVINCE_OPERATOR: "ProvinceOperator", - SUPER_ADMIN: "SuperAdmin", - VET_SUPERVISOR: "VetSupervisor", - VET_FARM: "VetFarm", - CITY_VET: "CityVet", -}; - -const DEFAULT_PER_PAGE = 10; -const DEFAULT_PAGE = 1; - -// Helper functions -const formatDate = (date) => { - if (!date) return "-"; - return format(new Date(date), "yyyy/MM/dd"); -}; - -const formatCurrency = (value) => { - return value ? `${value.toLocaleString()} ﷼` : "-"; -}; - -const formatNumber = (value) => { - return value ? value.toLocaleString() : "-"; -}; - -const formatUserInfo = (name, mobile) => { - return name && mobile ? `${name} (${mobile})` : "-"; -}; - -const buildApiUrl = (params) => { - const { textValue, role, date1, date2, page, perPage, roleKey } = params; - const baseUrl = "kill_house_request_complete_information/"; - const queryParams = new URLSearchParams({ - search: "filter", - value: textValue || "", - role: role || "", - date1: date1 || "", - date2: date2 || "", - page: page || DEFAULT_PAGE, - page_size: perPage || DEFAULT_PER_PAGE, - }); - - if (roleKey) { - queryParams.append("role_key", roleKey); - } - - return `${baseUrl}?${queryParams.toString()}`; -}; - -const isTrafficCodeEditable = (role, item) => { - const adminRoles = [ - ROLES.PROVINCE_OPERATOR, - ROLES.SUPER_ADMIN, - ROLES.VET_SUPERVISOR, - ]; - - if (adminRoles.includes(role)) { - return true; - } - - const vetRoles = [ROLES.VET_FARM, ROLES.CITY_VET]; - return ( - item.trash !== true && - item.assignmentStateArchive === "pending" && - !item?.clearanceCode && - vetRoles.includes(role) - ); -}; export const EnterLoadInformation = () => { const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] = useContext(AppContext); - - // State const [checked, setChecked] = useState(false); const [data, setData] = useState([]); const [totalRows, setTotalRows] = useState(0); - const [perPage, setPerPage] = useState(DEFAULT_PER_PAGE); + const [perPage, setPerPage] = useState(10); const [textValue, setTextValue] = useState(""); - const [page, setPage] = useState(DEFAULT_PAGE); + const [page, setPage] = useState(1); const [tableData, setTableData] = useState([]); - const [dashboardData, setDashboardData] = useState([]); - // Redux - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); const dispatch = useDispatch(); - // Memoized values - const currentRole = useMemo(() => getRoleFromUrl(), []); - const isKillHouse = useMemo( - () => currentRole === ROLES.KILL_HOUSE, - [currentRole] - ); - const roleKey = useMemo( - () => (checkPathStartsWith("slaughter") ? selectedSubUser?.key || "" : ""), - [selectedSubUser?.key] - ); - - // Initialize dates useEffect(() => { const currentDate = moment(new Date()).format("YYYY-MM-DD"); setSelectedDate1(currentDate); setSelectedDate2(currentDate); - }, [setSelectedDate1, setSelectedDate2]); - - // Fetch permission for KillHouse role - useEffect(() => { - if (isKillHouse) { - dispatch( - slaughterGetPermissionToVetService({ - role_key: roleKey, - }) - ).then((r) => { - setChecked(r.payload.data?.[0]?.allow || false); - }); - } - }, [isKillHouse, selectedSubUser?.key, dispatch]); - - // Fetch API data - const fetchApiData = useCallback( - async (pageNumber = page) => { - dispatch(LOADING_START()); - try { - const url = buildApiUrl({ - textValue, - role: currentRole, - date1: selectedDate1, - date2: selectedDate2, - page: pageNumber, - perPage, - roleKey, - }); - - const response = await axios.get(url); - setData(response.data.results); - setTotalRows(response.data.count); - } catch (error) { - console.error("Error fetching data:", error); - } finally { - dispatch(LOADING_END()); - } - }, - [ - textValue, - currentRole, - selectedDate1, - selectedDate2, - perPage, - roleKey, - page, - dispatch, - ] - ); - - // Fetch dashboard data - const fetchDashboardData = useCallback(() => { - dispatch( - slaughterEnterLoadInformationGetDashboard({ - selectedDate1, - selectedDate2, - text: textValue, - role_key: roleKey, - }) - ).then((r) => { - setDashboardData(r.payload.data); - }); - }, [selectedDate1, selectedDate2, textValue, roleKey, dispatch]); - - // Update table data - const updateTable = useCallback(() => { - fetchDashboardData(); - fetchApiData(DEFAULT_PAGE); - setPage(DEFAULT_PAGE); - }, [fetchDashboardData, fetchApiData]); - - // Transform data to table format - useEffect(() => { - const transformedData = data?.map((item, i) => [ - , - - {item.barCode} - , - , - formatDate(item?.poultryRequest?.sendDate), - formatUserInfo( - item.killhouseUser?.name, - item.killhouseUser?.killHouseOperator?.user?.mobile - ), - item?.killer - ? formatUserInfo( - item.killer?.name, - item.killer?.killHouseOperator?.user?.mobile - ) - : "-", - formatUserInfo( - item.poultryRequest?.poultry?.unitName, - item.poultryRequest?.poultry?.user?.mobile - ), - item?.poultryRequest?.age || "-", - formatNumber(item.quantity), - formatNumber(item?.weightInfo?.weight), - `${item.addCar?.driver?.typeCar || ""} ${ - item.addCar?.driver?.pelak || "" - }`.trim() || "-", - formatUserInfo( - item.addCar?.driver?.driverName, - item.addCar?.driver?.driverMobile - ), - formatCurrency(item?.poultryRequest?.amount), - formatCurrency(item?.weightInfo?.killHousePrice), - formatNumber(item.vetAcceptedRealQuantity), - formatNumber(item.vetAcceptedRealWeight), - item?.poultryRequest?.orderCode || "-", - item?.barDocumentStatus?.title || "-", - item?.finalBarState || "-", - item?.poultryRequest?.freezing ? "انجماد" : "عادی", - ]); - - setTableData(transformedData || []); - }, [data, currentRole, updateTable, fetchApiData]); - - // Initial data fetch - useEffect(() => { - fetchApiData(DEFAULT_PAGE); - fetchDashboardData(); }, []); - // Refetch when filters change useEffect(() => { - fetchApiData(DEFAULT_PAGE); - fetchDashboardData(); - setPage(DEFAULT_PAGE); - }, [selectedDate1, selectedDate2, perPage, selectedSubUser?.keys]); + if (getRoleFromUrl() === "KillHouse") { + dispatch(slaughterGetPermissionToVetService()).then((r) => { + if (r.payload.data?.length) { + setChecked(r.payload.data[0]?.allow); + } else { + setChecked(false); + } + }); + } + }, []); - // Handlers - const handlePageChange = (newPage) => { - fetchApiData(newPage); - setPage(newPage); + const fetchApiData = async (page) => { + let response; + dispatch(LOADING_START()); + response = await axios.get( + `kill_house_request_complete_information/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${perPage}` + ); + dispatch(LOADING_END()); + setData(response.data.results); + setTotalRows(response.data.count); }; - const handlePerRowsChange = (newPerRows) => { - setPerPage(newPerRows); - setPage(DEFAULT_PAGE); + const handlePageChange = (page) => { + fetchApiData(page); + setPage(page); + }; + + const handlePerRowsChange = (perRows) => { + setPerPage(perRows); + setPage(1); }; const handleSubmit = async (event) => { event.preventDefault(); - await fetchApiData(DEFAULT_PAGE); - fetchDashboardData(); - setPage(DEFAULT_PAGE); + dispatch(LOADING_START()); + + try { + const response = await axios.get( + `kill_house_request_complete_information/?role=${getRoleFromUrl()}&search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${1}&page_size=${perPage}` + ); + setData(response.data.results); + setTotalRows(response.data.count); + dispatch(LOADING_END()); + } catch (error) { + console.error("Error fetching data:", error); + } }; + const updateTable = () => { + fetchDashboardData(); + fetchApiData(1); + }; const handleTextChange = (event) => { setTextValue(event.target.value); }; const handleDateChange1 = (date) => { - if (date) { - setSelectedDate1(moment(date).format("YYYY-MM-DD")); - } + setSelectedDate1(date); }; const handleDateChange2 = (date) => { - if (date) { - setSelectedDate2(moment(date).format("YYYY-MM-DD")); - } + setSelectedDate2(date); }; - const handleSwitchChange = () => { - const newValue = !checked; + useEffect(() => { + fetchApiData(1); + }, []); + + useEffect(() => { + fetchApiData(1); + fetchDashboardData(); + }, [selectedDate1, selectedDate2, perPage]); + + const handleChange = () => { dispatch( slaughterPermissionToVetService({ - allow: newValue, + allow: !checked, }) ); - setChecked(newValue); + setChecked(!checked); }; - // Table columns - const dashboardColumns = [ - "تعداد بار", - "مجموع تعداد اولیه", - "مجموع وزن اولیه (کیلوگرم)", - "مجموع تعداد تحویلی دامپزشک", - "مجموع وزن تحویلی دامپزشک (کیلوگرم)", - ]; + useEffect(() => { + const d = data?.map((item, i) => { + return [ + , + + {item.barCode} + , + , + item?.poultryRequest.sendDate + ? format(new Date(item?.poultryRequest.sendDate), "yyyy/MM/dd") + : "-", + `${item.killhouseUser?.name} (${item.killhouseUser?.killHouseOperator?.user?.mobile})`, + item?.killer + ? `${item?.killer?.name} (${item?.killer?.killHouseOperator?.user?.mobile})` + : "-", + `${item.poultryRequest?.poultry?.unitName} (${item.poultryRequest.poultry?.user?.mobile})`, + item?.poultryRequest?.age, + item.quantity?.toLocaleString(), + item?.weightInfo?.weight?.toLocaleString(), + `${item.addCar.driver.typeCar} ${item.addCar.driver.pelak}`, + `${item.addCar.driver.driverName} (${item.addCar.driver.driverMobile})`, + item?.poultryRequest?.amount?.toLocaleString() + " ﷼", + item?.weightInfo?.killHousePrice?.toLocaleString() + " ﷼", + item.vetAcceptedRealQuantity?.toLocaleString(), + item.vetAcceptedRealWeight?.toLocaleString(), + item?.poultryRequest.orderCode, + item?.barDocumentStatus?.title ? item?.barDocumentStatus?.title : "-", + item?.finalBarState, + item?.poultryRequest?.freezing ? "انجماد" : "عادی", + ]; + }); - const tableColumns = [ - "عملیات", - "کدبار", - "کدبهداشتی حمل و نقل", - "تاریخ کشتار", - "خریدار", - "کشتارکن اختصاصی", - "مرغدار", - "سن مرغ", - "تعداد اولیه", - "وزن اولیه بار(کیلوگرم)", - "ماشین", - "راننده", - "قیمت مرغدار", - "قیمت کشتارگاه", - "تحویلی دامپزشک (قطعه)", - "وزن تحویلی دامپزشک(کیلوگرم)", - "کد سفارش کشتار", - "وضعیت سند", - "وضعیت بار", - "نوع کشتار", - ]; + setTableData(d); + }, [data]); - const dashboardRow = [ - formatNumber(dashboardData?.lenKillHouseRequest), - formatNumber(dashboardData?.firstQuantity), - formatNumber(dashboardData?.firstWeight), - formatNumber(dashboardData?.vetAcceptedRealQuantity), - formatNumber(dashboardData?.vetAcceptedRealWeight), - ]; + const [dashboardData, setDashboardData] = useState([]); + + const fetchDashboardData = () => { + dispatch( + slaughterEnterLoadInformationGetDashboard({ + selectedDate1, + selectedDate2, + text: textValue, + }) + ).then((r) => { + setDashboardData(r.payload.data); + }); + }; return ( - {isKillHouse && ( - - + {getRoleFromUrl() === "KillHouse" && ( + + دسترسی دامپزشک برای وارد کردن اطلاعات بار @@ -370,7 +207,7 @@ export const EnterLoadInformation = () => { @@ -378,22 +215,27 @@ export const EnterLoadInformation = () => { )} - } value={selectedDate1} - onChange={handleDateChange1} + onChange={(e) => { + handleDateChange1(moment(e).format("YYYY-MM-DD")); + }} /> } value={selectedDate2} - onChange={handleDateChange2} + onChange={(e) => { + handleDateChange2(moment(e).format("YYYY-MM-DD")); + }} />
    @@ -404,9 +246,13 @@ export const EnterLoadInformation = () => { variant="outlined" style={{ width: 250 }} onChange={handleTextChange} - value={textValue} /> -
    @@ -419,19 +265,54 @@ export const EnterLoadInformation = () => { xs={12} mt={2} > - + { const [openNotif] = useContext(AppContext); const dispatch = useDispatch(); const [guildsData, setGuildsData] = useState([]); const [selectedItems, setSelectedItems] = useState([]); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); useEffect(() => { const fetchGuilds = async () => { - dispatch( - slaughterGetGuildsService({ - role_key: - checkPathStartsWith("slaughter") || checkPathStartsWith("steward") - ? selectedSubUser?.key || "" - : "", - }) - ).then((r) => { + dispatch(slaughterGetGuildsService()).then((r) => { setGuildsData(r.payload.data); }); }; diff --git a/src/features/slaughter-house/components/slaughter-allocate-car-to-request-operation/SlaughterAllocatedCarToRequestOperation.js b/src/features/slaughter-house/components/slaughter-allocate-car-to-request-operation/SlaughterAllocatedCarToRequestOperation.js index bfc1b0a..80f9205 100644 --- a/src/features/slaughter-house/components/slaughter-allocate-car-to-request-operation/SlaughterAllocatedCarToRequestOperation.js +++ b/src/features/slaughter-house/components/slaughter-allocate-car-to-request-operation/SlaughterAllocatedCarToRequestOperation.js @@ -23,7 +23,7 @@ import { slaughterRemoveAllocateCarService } from "../../services/slaughter-remo import { slaughterGetActiveRequests } from "../../services/slaughter-get-active-requests"; import { slaughterGetAllocatedCarsService } from "../../services/slaughter-get-allocated-cars"; import { AppContext } from "../../../../contexts/AppContext"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; import { OPEN_MODAL, CLOSE_MODAL, @@ -33,7 +33,6 @@ import { SlaughterEditAllocatedCar } from "../slaughter-edit-allocated-car/Slaug import { SlaughterSubmitChickenPrice } from "../slaughter-submit-chicken-price/SlaughterSubmitChickenPrice"; import SlaughterAssignCar from "../../../file/components/slaughter-assign-car/SlaughterAssignCar"; import { SPACING } from "../../../../data/spacing"; -import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; export const SlaughterAllocatedCarToRequestOperation = ({ item, @@ -46,9 +45,7 @@ export const SlaughterAllocatedCarToRequestOperation = ({ const [anchorEl, setAnchorEl] = useState(null); const [openNotif, , contextDate1, , contextDate2] = useContext(AppContext); const dispatch = useDispatch(); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); + // Use prop dates if provided, otherwise use context dates const date1 = selectedDate1 || contextDate1; const date2 = selectedDate2 || contextDate2; @@ -89,18 +86,12 @@ export const SlaughterAllocatedCarToRequestOperation = ({ isCar: true, selectedDate1: date1, selectedDate2: date2, - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", }) ); dispatch( slaughterGetAllocatedCarsService({ selectedDate1: date1, selectedDate2: date2, - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", }) ); if (updateTable) updateTable(); @@ -165,18 +156,12 @@ export const SlaughterAllocatedCarToRequestOperation = ({ isCar: true, selectedDate1: date1, selectedDate2: date2, - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", }) ); dispatch( slaughterGetAllocatedCarsService({ selectedDate1: date1, selectedDate2: date2, - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", }) ); if (updateTable) updateTable(); diff --git a/src/features/slaughter-house/components/slaughter-allocate-car-to-requests/SlaughterAllocateCarToRequests.js b/src/features/slaughter-house/components/slaughter-allocate-car-to-requests/SlaughterAllocateCarToRequests.js index 4ae1731..cb721d3 100644 --- a/src/features/slaughter-house/components/slaughter-allocate-car-to-requests/SlaughterAllocateCarToRequests.js +++ b/src/features/slaughter-house/components/slaughter-allocate-car-to-requests/SlaughterAllocateCarToRequests.js @@ -22,13 +22,9 @@ import ResponsiveTable from "../../../../components/responsive-table/ResponsiveT import { provincePolicyGetSLaughterSubmitBuyingPriceStatus } from "../../../province/services/province-policy-get-slaughter-buying-price-status"; import { SlaughterSubmitChickenPrice } from "../slaughter-submit-chicken-price/SlaughterSubmitChickenPrice"; import { SlaughterAllocatedCarToRequestOperation } from "../slaughter-allocate-car-to-request-operation/SlaughterAllocatedCarToRequestOperation"; -import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; - export const SlaughterAllocateCarToRequests = () => { const componentRef = useRef(); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); + const [data, setData] = useState(); const [dataTable, setDataTable] = useState([]); const [allocatedDataTable, setAllocatedDataTable] = useState([]); @@ -45,38 +41,19 @@ export const SlaughterAllocateCarToRequests = () => { const fetchData = () => { dispatch( - slaughterGetActiveRequests({ - isCar: true, - selectedDate1, - selectedDate2, - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) + slaughterGetActiveRequests({ isCar: true, selectedDate1, selectedDate2 }) ); dispatch( - slaughterGetAllocatedCarsService({ - selectedDate1, - selectedDate2, - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) + slaughterGetAllocatedCarsService({ selectedDate1, selectedDate2 }) ); - dispatch( - provincePolicyGetSLaughterSubmitBuyingPriceStatus({ - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) - ).then((r) => { + dispatch(provincePolicyGetSLaughterSubmitBuyingPriceStatus()).then((r) => { SetSubmitStatus(r.payload.data.allow); }); }; useEffect(() => { fetchData(); - }, [selectedDate1, selectedDate2, selectedSubUser?.key]); + }, [selectedDate1, selectedDate2]); const printPDF = useReactToPrint({ content: () => componentRef.current, diff --git a/src/features/slaughter-house/components/slaughter-allocate-for-freezing/SlaughterAllocateForFreezing.js b/src/features/slaughter-house/components/slaughter-allocate-for-freezing/SlaughterAllocateForFreezing.js index e8c970f..65b6b27 100644 --- a/src/features/slaughter-house/components/slaughter-allocate-for-freezing/SlaughterAllocateForFreezing.js +++ b/src/features/slaughter-house/components/slaughter-allocate-for-freezing/SlaughterAllocateForFreezing.js @@ -10,7 +10,7 @@ import { TextField, Typography, } from "@mui/material"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; import { slaughterGetProductsService } from "../../services/slaughter-inventory-gets"; import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom"; import { useFormik } from "formik"; @@ -28,17 +28,17 @@ import { fetchSlaughterBroadcastAndProducts } from "../../services/handle-fetch- import MonthlyDataCalendar from "../../../../components/date-picker/MonthlyDataCalendar"; import PersianDate from "persian-date"; import axios from "axios"; -import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; import { LabelField } from "../../../../components/label-field/LabelField"; export const SlaughterAllocateForFreezing = ({ sellerType, + fetchData, // eslint-disable-line no-unused-vars sellType, updateTable, fetchApiData, editData, + priceInfo, // eslint-disable-line no-unused-vars remainWeight, - priceInfo, }) => { const dispatch = useDispatch(); const [productData, setProductData] = useState([]); @@ -49,9 +49,7 @@ export const SlaughterAllocateForFreezing = ({ const [approvedStatus, setApprovedStatus] = useState( priceInfo?.active === false ? false : true ); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); + const [openNotif] = useContext(AppContext); // Calendar states @@ -64,24 +62,31 @@ export const SlaughterAllocateForFreezing = ({ free: [], }); + // Calendar functions - Define BEFORE useEffect + // Transform calendar data from array format to object format + // Input: [{day: "2025-10-10", amount: 100}] + // Output: {"1404/07/19": {value1: 100, originalDay: "2025-10-10"}} const transformCalendarData = useCallback((dataArray) => { if (!Array.isArray(dataArray)) return {}; const transformedData = {}; dataArray.forEach((item) => { if (item.day && item.amount !== undefined) { + // Convert Gregorian date to Persian date const persianDate = new PersianDate(new Date(item.day)); const persianDateStr = persianDate.format("YYYY/MM/DD"); + // Calendar expects 'value1' property, also store the original day transformedData[persianDateStr] = { value1: item.amount, - originalDay: item.day, - active: item.active === true, + originalDay: item.day, // Store the original Gregorian date + active: item.active === true, // Store active status }; } }); return transformedData; }, []); + // Function to update calendar data from API response const updateCalendarData = useCallback( (dataArray) => { const transformed = transformCalendarData(dataArray); @@ -97,9 +102,6 @@ export const SlaughterAllocateForFreezing = ({ const response = await axios.get("/kill-house-remain-weight/", { params: { date: dateParam, - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", }, }); if (response.data) { @@ -107,6 +109,7 @@ export const SlaughterAllocateForFreezing = ({ governmental: response.data.governmental || [], free: response.data.free || [], }); + // Update calendar based on current inventory type const dataToShow = selectedInventory === "governmental" ? response.data.governmental @@ -117,17 +120,20 @@ export const SlaughterAllocateForFreezing = ({ console.error("Error fetching calendar data:", error); } }, - [selectedInventory, updateCalendarData, selectedSubUser] + [selectedInventory, updateCalendarData] ); const handleDateSelect = (dateInfo) => { if (dateInfo && dateInfo.formattedDate) { setSelectedCalendarDate(dateInfo.formattedDate); + // Get the data for the selected date const data = calendarDayData[dateInfo.formattedDate]; + // Use the original Gregorian date from the API data for production_date if (data && data.originalDay) { const selectedOriginalDay = data.originalDay; + // Prevent choosing a production date after the main form date if ( selectedDate1 && moment(selectedOriginalDay).isAfter(moment(selectedDate1), "day") @@ -141,6 +147,7 @@ export const SlaughterAllocateForFreezing = ({ setProductionDate(selectedOriginalDay); } + // Get the amount for the selected date if (data && data.value1 !== undefined) { setSelectedDateAmount(data.value1); } else { @@ -197,13 +204,7 @@ export const SlaughterAllocateForFreezing = ({ msg: "عملیات با موفقیت انجام شد.", severity: "success", }); - dispatch( - fetchSlaughterBroadcastAndProducts({ - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) - ); + dispatch(fetchSlaughterBroadcastAndProducts()); fetchApiData(); updateTable(); }; @@ -220,39 +221,24 @@ export const SlaughterAllocateForFreezing = ({ useEffect(() => { if (!editData) { - dispatch( - slaughterGetProductsService({ - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) - ).then((r) => { + dispatch(slaughterGetProductsService()).then((r) => { setProductData(r.payload.data); }); - dispatch( - liveStockGetInventoryData({ - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) - ).then((r) => { + dispatch(liveStockGetInventoryData()).then((r) => { setColdHouseData(r.payload.data); }); } + // Fetch calendar data on mount with initial date fetchCalendarData(selectedDate1); - }, [ - dispatch, - editData, - fetchCalendarData, - selectedDate1, - selectedSubUser?.key, - ]); + }, [dispatch, editData, fetchCalendarData, selectedDate1]); + // Refetch calendar data when selected date changes useEffect(() => { fetchCalendarData(selectedDate1); - }, [selectedDate1, fetchCalendarData, selectedSubUser?.key]); + }, [selectedDate1, fetchCalendarData]); + // Update calendar when inventory type changes useEffect(() => { if ( calendarRawData.governmental.length > 0 || @@ -263,6 +249,7 @@ export const SlaughterAllocateForFreezing = ({ ? calendarRawData.governmental : calendarRawData.free; updateCalendarData(dataToShow); + // Reset selected date when inventory type changes setSelectedCalendarDate(null); setProductionDate(null); setSelectedDateAmount(null); @@ -540,9 +527,6 @@ export const SlaughterAllocateForFreezing = ({ sell_type: sellType, buyer_type: "ColdHouse", cold_house_key: coldHouseKey, - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", allocation_type: "ColdHouse", date: selectedDate1, production_date: productionDate, @@ -553,9 +537,6 @@ export const SlaughterAllocateForFreezing = ({ weight_of_carcasses: formik.values.weight, allocation_key: editData?.key, distribution_type: "web", - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", }; } diff --git a/src/features/slaughter-house/components/slaughter-allocate-to-coldhouse/SlaughterAllocateToColdHouse.js b/src/features/slaughter-house/components/slaughter-allocate-to-coldhouse/SlaughterAllocateToColdHouse.js index 3899d10..3606778 100644 --- a/src/features/slaughter-house/components/slaughter-allocate-to-coldhouse/SlaughterAllocateToColdHouse.js +++ b/src/features/slaughter-house/components/slaughter-allocate-to-coldhouse/SlaughterAllocateToColdHouse.js @@ -11,7 +11,7 @@ import { TextField, Typography, } from "@mui/material"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; import { slaughterGetProductsService } from "../../services/slaughter-inventory-gets"; import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom"; import { useFormik } from "formik"; @@ -33,7 +33,6 @@ import { ImageUpload } from "../../../../components/image-upload/ImageUpload"; import { fixBase64 } from "../../../../utils/toBase64"; import { provincePolicyGetUploadImageService } from "../../../province/services/province-policy-upload-image"; import { fetchSlaughterBroadcastAndProducts } from "../../services/handle-fetch-slaughter-products"; -import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; export const SlaughterAllocateToColdHouse = ({ item, @@ -67,9 +66,6 @@ export const SlaughterAllocateToColdHouse = ({ const [value, setValue] = useState("own"); const [imageUploadLimit, setImageUploadLimit] = useState(1); const [imageChanged, setImageChanged] = useState(false); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); const handleChange = (event) => { setValue(event.target.value); @@ -109,40 +105,25 @@ export const SlaughterAllocateToColdHouse = ({ }); if (!editData) { - dispatch( - slaughterGetProductsService({ - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) - ).then((r) => { + dispatch(slaughterGetProductsService()).then((r) => { setProductData(r.payload.data); }); if (!item) { if (value === "cold") { - dispatch( - slaughterGetColdHousesForAllocateService({ - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) - ).then((r) => { + dispatch(slaughterGetColdHousesForAllocateService()).then((r) => { setColdHouseData(r.payload.data); }); } dispatch( slaughterGetGuildsForAllocateService({ free: value === "free" ? true : false, - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", }) ).then((r) => { setGuildsData(r.payload.data); }); } } - }, [dispatch, value, selectedSubUser?.key]); + }, [dispatch, value]); const validationSchema = Yup.object({ weight: Yup.number() @@ -226,13 +207,7 @@ export const SlaughterAllocateToColdHouse = ({ msg: "عملیات با موفقیت انجام شد.", severity: "success", }); - dispatch( - fetchSlaughterBroadcastAndProducts({ - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) - ); + dispatch(fetchSlaughterBroadcastAndProducts()); fetchApiData && fetchApiData(1); updateTable && updateTable(); diff --git a/src/features/slaughter-house/components/slaughter-allocate-to-guild/SlaughterAllocateToGuild.js b/src/features/slaughter-house/components/slaughter-allocate-to-guild/SlaughterAllocateToGuild.js index 9e99f92..2e2103c 100644 --- a/src/features/slaughter-house/components/slaughter-allocate-to-guild/SlaughterAllocateToGuild.js +++ b/src/features/slaughter-house/components/slaughter-allocate-to-guild/SlaughterAllocateToGuild.js @@ -12,7 +12,7 @@ import { TextField, Typography, } from "@mui/material"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; import { slaughterGetProductsService } from "../../services/slaughter-inventory-gets"; import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom"; import { useFormik } from "formik"; @@ -23,10 +23,7 @@ import { } from "../../services/slaughter-allocate-steward"; import { AppContext } from "../../../../contexts/AppContext"; import { CLOSE_MODAL, DRAWER } from "../../../../lib/redux/slices/appSlice"; -import { - slaughterGetGuildsForAllocateService, - slaughterGetStewardsForAllocateService, -} from "../../services/slaughter-get-guilds-for-allocate"; +import { slaughterGetGuildsForAllocateService } from "../../services/slaughter-get-guilds-for-allocate"; import { DatePicker } from "@mui/x-date-pickers"; import moment from "moment"; import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl"; @@ -39,7 +36,6 @@ import PersianDate from "persian-date"; import axios from "axios"; import { LabelField } from "../../../../components/label-field/LabelField"; import { SPACING } from "../../../../data/spacing"; -import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; export const SlaughterAllocateToGuild = ({ item, @@ -60,7 +56,6 @@ export const SlaughterAllocateToGuild = ({ const dispatch = useDispatch(); const [productData, setProductData] = useState([]); const [guildsData, setGuildsData] = useState([]); - const [stewardsData, setStewardsData] = useState([]); const [selectedInventory, setSelectedInventory] = useState("governmental"); const [approvedStatus, setApprovedStatus] = useState("true"); const [productKey, setProductKey] = useState(null); @@ -69,8 +64,7 @@ export const SlaughterAllocateToGuild = ({ editData?.image ? [{ data_url: editData.image }] : [] ); - const [buyerCategory, setBuyerCategory] = useState(""); // "stewards" or "guilds" - const [value, setValue] = useState(""); + const [value, setValue] = useState("own"); const [imageUploadLimit, setImageUploadLimit] = useState(1); const [imageChanged, setImageChanged] = useState(false); const [changeMobile, setChangeMobile] = useState(false); @@ -82,27 +76,11 @@ export const SlaughterAllocateToGuild = ({ governmental: [], free: [], }); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); const [selectedDate1, setSelectedDate1] = useState( moment(new Date()).format("YYYY-MM-DD") ); const [dateRangeError, setDateRangeError] = useState(null); - const handleBuyerCategoryChange = (event) => { - const newCategory = event.target.value; - setBuyerCategory(newCategory); - setBuyerData({ - key: "", - item: "", - buyerType: "", - allocationType: "", - }); - setGuildsData([]); - setStewardsData([]); - }; - const handleChange = (event) => { setValue(event.target.value); setBuyerData({ @@ -111,8 +89,6 @@ export const SlaughterAllocateToGuild = ({ buyerType: "", allocationType: "", }); - setGuildsData([]); - setStewardsData([]); }; const handleSellType = (event) => { @@ -189,11 +165,6 @@ export const SlaughterAllocateToGuild = ({ const response = await axios.get("/kill-house-remain-weight/", { params: { date: selectedDate1, - role: getRoleFromUrl(), - role_key: - checkPathStartsWith("slaughter") || checkPathStartsWith("steward") - ? selectedSubUser?.key || "" - : "", }, }); if (response.data) { @@ -210,7 +181,7 @@ export const SlaughterAllocateToGuild = ({ } catch (error) { console.error("Error fetching calendar data:", error); } - }, [selectedInventory, updateCalendarData, selectedDate1, selectedSubUser]); + }, [selectedInventory, updateCalendarData, selectedDate1]); const [buyerData, setBuyerData] = useState({ key, @@ -224,7 +195,7 @@ export const SlaughterAllocateToGuild = ({ setValue("free"); } fetchCalendarData(); - }, [selectedSubUser?.key]); + }, [fetchCalendarData]); useEffect(() => { if ( @@ -240,64 +211,30 @@ export const SlaughterAllocateToGuild = ({ setProductionDate(null); setSelectedDateAmount(null); } - }, [selectedInventory, calendarRawData]); + }, [selectedInventory, calendarRawData, updateCalendarData]); useEffect(() => { - dispatch( - provincePolicyGetUploadImageService({ - role_key: - checkPathStartsWith("slaughter") || checkPathStartsWith("steward") - ? selectedSubUser?.key || "" - : "", - }) - ).then((r) => { + dispatch(provincePolicyGetUploadImageService()).then((r) => { if (r.payload?.data) { setImageUploadLimit(r.payload.data.killHouseAllocation); } }); if (!editData) { - dispatch( - slaughterGetProductsService({ - role_key: - checkPathStartsWith("slaughter") || checkPathStartsWith("steward") - ? selectedSubUser?.key || "" - : "", - }) - ).then((r) => { + dispatch(slaughterGetProductsService()).then((r) => { setProductData(r.payload.data); }); - if (!item && buyerCategory && value) { - if (buyerCategory === "guilds") { - dispatch( - slaughterGetGuildsForAllocateService({ - free: value === "free" ? true : false, - role_key: - checkPathStartsWith("slaughter") || - checkPathStartsWith("steward") - ? selectedSubUser?.key || "" - : "", - }) - ).then((r) => { - setGuildsData(r.payload.data); - }); - } else if (buyerCategory === "stewards") { - dispatch( - slaughterGetStewardsForAllocateService({ - free: value === "free" ? true : false, - role_key: - checkPathStartsWith("slaughter") || - checkPathStartsWith("steward") - ? selectedSubUser?.key || "" - : "", - }) - ).then((r) => { - setStewardsData(r.payload.data); - }); - } + if (!item) { + dispatch( + slaughterGetGuildsForAllocateService({ + free: value === "free" ? true : false, + }) + ).then((r) => { + setGuildsData(r.payload.data); + }); } } - }, [buyerCategory, value, selectedSubUser?.key]); + }, [dispatch, value]); const validationSchema = Yup.object({ mobile: Yup.string().when([], { @@ -419,14 +356,7 @@ export const SlaughterAllocateToGuild = ({ msg: "عملیات با موفقیت انجام شد.", severity: "success", }); - dispatch( - fetchSlaughterBroadcastAndProducts({ - role_key: - checkPathStartsWith("slaughter") || checkPathStartsWith("steward") - ? selectedSubUser?.key || "" - : "", - }) - ); + dispatch(fetchSlaughterBroadcastAndProducts()); dispatch( DRAWER({ right: false, @@ -519,36 +449,8 @@ export const SlaughterAllocateToGuild = ({ - } - label="مباشرین" - /> - } - label="اصناف" - /> - - -
    - )} - - {!editData && buyerCategory && ( - - - } - label="اختصاصی" + label="صنوف اختصاصی" /> } - label="آزاد" + label="صنوف آزاد" disabled={disableFreeOptions} /> @@ -571,113 +473,59 @@ export const SlaughterAllocateToGuild = ({ )} - {!item && !editData && buyerCategory && value && ( + {!item && !editData && ( - {(() => { - const currentData = - buyerCategory === "guilds" ? guildsData : stewardsData; - const isEmpty = !currentData || currentData.length === 0; - - if (isEmpty) { - return ( - - {buyerCategory === "guilds" - ? "هیچ صنفی یافت نشد" - : "هیچ مباشری یافت نشد"} - - ); + { + return { + data: i, + label: `${i?.steward ? "مباشر" : "صنف"} ${ + i?.guildsName + } ${i?.user?.fullname} (${i?.user?.mobile})`, + }; + }) + : [] } - - return ( - { - return { - data: i, - label: `${i?.steward ? "مباشر" : "صنف"} ${ - i?.guildsName - } ${i?.user?.fullname} (${i?.user?.mobile})`, - }; - }) - : stewardsData.map((i) => { - return { - data: i, - label: `${i?.name || ""} - ${ - i?.user?.fullname || "" - } (${i?.user?.mobile || ""})`, - }; - }) - } - onChange={(event, value) => { - if (buyerCategory === "guilds") { - setBuyerData({ - item: value?.data, - key: value?.data?.key, - allocationType: value?.data?.steward - ? "killhouse_steward" - : "killhouse_guild", - buyerType: value?.data?.steward ? "Steward" : "Guild", - }); - formik.setFieldValue("mobile", value?.data?.user?.mobile); - } else if (buyerCategory === "stewards") { - setBuyerData({ - item: value?.data, - key: value?.data?.key, - allocationType: "killhouse_steward", - buyerType: "Steward", - }); - formik.setFieldValue("mobile", value?.data?.user?.mobile); - } - formik.setFieldTouched("mobile", true, false); - formik.validateField("mobile"); - const reg = new RegExp(/^09\d{9}$/); - if ( - value?.data?.user?.mobile && - !reg.test(value?.data?.user?.mobile) - ) { - setChangeMobile(true); - } - }} - renderInput={(params) => ( - - )} - /> - ); - })()} + onChange={(event, value) => { + setBuyerData({ + item: value?.data, + key: value?.data?.key, + allocationType: value?.data?.steward + ? "killhouse_steward" + : "killhouse_guild", + buyerType: value?.data?.steward ? "Steward" : "Guild", + }); + formik.setFieldValue("mobile", value?.data?.user?.mobile); + formik.setFieldTouched("mobile", true, false); + formik.validateField("mobile"); + const reg = new RegExp(/^09\d{9}$/); + if (!reg.test(value?.data?.user?.mobile)) { + setChangeMobile(true); + } + }} + renderInput={(params) => ( + + )} + /> )} - {!item && !editData && buyerData?.key && ( + {!item && !editData && ( @@ -686,15 +534,12 @@ export const SlaughterAllocateToGuild = ({ checked={changeMobile} onChange={() => setChangeMobile(!changeMobile)} /> - {buyerCategory === "stewards" - ? "از این قسمت میتوانید تلفن مباشر را ویرایش کنید." - : buyerCategory === "guilds" - ? "از این قسمت میتوانید تلفن صنف را ویرایش کنید." - : "از این قسمت میتوانید تلفن مباشر/صنف را ویرایش کنید."} + از این قسمت میتوانید تلفن مباشر/صنف را ویرایش کنید. - {changeMobile && ( + {buyerData?.key && changeMobile && ( { const navigate = useNavigate(); @@ -27,9 +26,6 @@ export const SlaughterAllocatedCheckRequests = () => { const dispatch = useDispatch(); const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] = useContext(AppContext); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); useEffect(() => { const currentDate = moment(new Date()).format("YYYY-MM-DD"); @@ -38,16 +34,8 @@ export const SlaughterAllocatedCheckRequests = () => { }, []); useEffect(() => { - dispatch( - slaughterGetActiveRequests({ - selectedDate1, - selectedDate2, - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) - ); - }, [selectedDate1, selectedDate2, selectedSubUser?.key]); + dispatch(slaughterGetActiveRequests({ selectedDate1, selectedDate2 })); + }, [selectedDate1, selectedDate2]); useEffect(() => { const filteredData = slaughterActiveRequests?.filter( diff --git a/src/features/slaughter-house/components/slaughter-balance-status-button/SlaughterBalanceStatusButton.js b/src/features/slaughter-house/components/slaughter-balance-status-button/SlaughterBalanceStatusButton.js index f49e622..10f6e2a 100644 --- a/src/features/slaughter-house/components/slaughter-balance-status-button/SlaughterBalanceStatusButton.js +++ b/src/features/slaughter-house/components/slaughter-balance-status-button/SlaughterBalanceStatusButton.js @@ -56,7 +56,7 @@ export const SlaughterBalanceStatusButton = () => { sx={{ width: { xs: "22px", md: "30px" }, height: { xs: "22px", md: "30px" }, - marginLeft: { xs: "8px", md: "8px" }, + marginLeft: { xs: "8px", md: "12px" }, }} title="به علت بدهی" /> @@ -69,8 +69,7 @@ export const SlaughterBalanceStatusButton = () => { sx={{ width: { xs: "22px", md: "30px" }, height: { xs: "22px", md: "30px" }, - marginLeft: { xs: "12px", md: "12px" }, - marginRight: { xs: "12px", md: "16px" }, + marginLeft: { xs: "12px", md: "20px" }, }} title="به علت پر بودن انبار" /> diff --git a/src/features/slaughter-house/components/slaughter-bars/SlaughterBars.js b/src/features/slaughter-house/components/slaughter-bars/SlaughterBars.js index 62f2d5a..1d312e8 100644 --- a/src/features/slaughter-house/components/slaughter-bars/SlaughterBars.js +++ b/src/features/slaughter-house/components/slaughter-bars/SlaughterBars.js @@ -38,7 +38,6 @@ import { CheckCleanceCode } from "../../../../components/check-clearance-code/Ch import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable"; import { SlaughterBarDashboardService } from "../../services/slaughter-bar-dashbored"; import { SlaughterEnterNoneReciept } from "../slaughter-enter-none-receipt/SlaughterEnterNoneReciept"; -import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; export const SlaughterBars = () => { const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] = @@ -66,18 +65,11 @@ export const SlaughterBars = () => { const [totalRows, setTotalRows] = useState(0); const [perPage, setPerPage] = useState(10); const [dashboardData, setDashboardData] = useState([]); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); const fetchApiData = async (page) => { setLoading(true); const response = await axios.get( - `kill_house_request_bar_management/?check&search=filter&value=${textValue}&role=${getRoleFromUrl()}${ - checkPathStartsWith("slaughter") - ? `&role_key=${selectedSubUser?.key}` - : "" - }&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${perPage}` + `kill_house_request_bar_management/?check&search=filter&value=${textValue}&role=${getRoleFromUrl()}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${perPage}` ); setData(response.data.results); @@ -100,11 +92,7 @@ export const SlaughterBars = () => { const handlePerRowsChange = async (newPerPage, page) => { setLoading(true); const response = await axios.get( - `kill_house_request_bar_management/?check&search=filter&value=${textValue}&role=${getRoleFromUrl()}${ - checkPathStartsWith("slaughter") - ? `&role_key=${selectedSubUser?.key}` - : "" - }&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${newPerPage}` + `kill_house_request_bar_management/?check&search=filter&value=${textValue}&role=${getRoleFromUrl()}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${newPerPage}` ); setData(response.data.results); @@ -472,7 +460,7 @@ export const SlaughterBars = () => { useEffect(() => { fetchApiData(1); - }, [selectedDate1, selectedDate2, perPage, selectedSubUser?.key]); + }, [selectedDate1, selectedDate2, perPage]); const [textValue, setTextValue] = useState(""); @@ -487,14 +475,11 @@ export const SlaughterBars = () => { selectedDate1, selectedDate2, textValue, - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", }) ).then((r) => { setDashboardData(r.payload.data); }); - }, [dispatch, selectedDate1, selectedDate2, selectedSubUser?.key]); + }, [dispatch, selectedDate1, selectedDate2]); const handleSubmit = async (event) => { event.preventDefault(); @@ -502,11 +487,7 @@ export const SlaughterBars = () => { try { const response = await axios.get( - `kill_house_request_bar_management/?check&role=${getRoleFromUrl()}${ - checkPathStartsWith("slaughter") - ? `&role_key=${selectedSubUser?.key}` - : "" - }&search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${1}&page_size=${perPage}` + `kill_house_request_bar_management/?check&role=${getRoleFromUrl()}&search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${1}&page_size=${perPage}` ); setData(response.data.results); setTotalRows(response.data.count); @@ -515,9 +496,6 @@ export const SlaughterBars = () => { selectedDate1, selectedDate2, textValue, - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", }) ).then((r) => { setDashboardData(r.payload.data); @@ -588,11 +566,7 @@ export const SlaughterBars = () => { -
    + {/* + + */} { const dispatch = useDispatch(); const [exportData, setExportData] = useState(); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); useEffect(() => { - dispatch( - slaughterGetExportAllowState({ - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) - ).then((r) => { + dispatch(slaughterGetExportAllowState()).then((r) => { setExportData(r.payload.data); }); - }, [selectedSubUser?.key]); + }, []); const [activeTab, setActiveTab] = useState(0); @@ -70,15 +60,12 @@ export const SlaughterExport = () => { const [tableDataArchive, setTableDataArchive] = useState([]); const fetchApiData = async (page) => { + let response; dispatch(LOADING_START()); - const response = await axios.get( + response = await axios.get( `kill_request/?export=true&type=${ activeTab === 0 ? "pending" : "archive" - }&search=filter&value=${textValue}&role=${getRoleFromUrl()}${ - checkPathStartsWith("slaughter") - ? `&role_key=${selectedSubUser?.key}` - : "" - }&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${perPage}` + }&search=filter&value=${textValue}&role=${getRoleFromUrl()}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${perPage}` ); dispatch(LOADING_END()); setData(response.data.results); @@ -101,7 +88,7 @@ export const SlaughterExport = () => { useEffect(() => { fetchApiData(1); - }, [selectedSubUser?.key, selectedDate1, selectedDate2, perPage, activeTab]); + }, []); const getItemState = (item) => { let state = ""; @@ -194,6 +181,10 @@ export const SlaughterExport = () => { setTableDataArchive(a); }, [data]); + useEffect(() => { + fetchApiData(1); + }, [selectedDate1, selectedDate2, perPage, activeTab]); + const handleSubmit = async (event) => { event.preventDefault(); dispatch(LOADING_START()); @@ -202,11 +193,7 @@ export const SlaughterExport = () => { const response = await axios.get( `kill_request/?export=true&type=${ activeTab === 0 ? "pending" : "archive" - }&role=${getRoleFromUrl()}${ - checkPathStartsWith("slaughter") - ? `&role_key=${selectedSubUser?.key}` - : "" - }&search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${1}&page_size=${perPage}` + }&role=${getRoleFromUrl()}&search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${1}&page_size=${perPage}` ); setData(response.data.results); setTotalRows(response.data.count); @@ -309,11 +296,7 @@ export const SlaughterExport = () => { -
    -
    - - ); -}; diff --git a/src/features/slaughter-house/components/slaughter-house-delegates/DelegatesOperations.js b/src/features/slaughter-house/components/slaughter-house-delegates/DelegatesOperations.js deleted file mode 100644 index fb538c3..0000000 --- a/src/features/slaughter-house/components/slaughter-house-delegates/DelegatesOperations.js +++ /dev/null @@ -1,139 +0,0 @@ -import { IconButton, Popover, Typography, Button } from "@mui/material"; -import React, { useState, useContext } from "react"; -import TuneIcon from "@mui/icons-material/Tune"; -import ToggleOnIcon from "@mui/icons-material/ToggleOn"; -import ToggleOffIcon from "@mui/icons-material/ToggleOff"; -import BlockIcon from "@mui/icons-material/Block"; -import { useDispatch } from "react-redux"; -import { AppContext } from "../../../../contexts/AppContext"; -import { OPEN_MODAL } from "../../../../lib/redux/slices/appSlice"; -import { slaughterEditDelegatesService } from "../../services/slaughter-get-delegates-service"; -import { DelegatesLimitationForm } from "./DelegatesLimitationForm"; - -export const DelegatesOperations = ({ item, updateTable }) => { - const [anchorEl, setAnchorEl] = useState(null); - const dispatch = useDispatch(); - const [openNotif] = useContext(AppContext); - - const handleClick = (event) => { - setAnchorEl(event.currentTarget); - }; - - const handleClose = () => { - setAnchorEl(null); - }; - - const open = Boolean(anchorEl); - const id = open ? "popover" : undefined; - - const isActive = item?.active !== undefined ? item.active : !item?.trash; - - const handleToggleActive = () => { - handleClose(); - dispatch( - slaughterEditDelegatesService({ - key: item?.key, - active: !isActive, - }) - ).then((r) => { - if (r.payload?.error) { - openNotif({ - vertical: "top", - horizontal: "center", - msg: r.payload.error, - severity: "error", - }); - } else { - openNotif({ - vertical: "top", - horizontal: "center", - msg: "عملیات با موفقیت انجام شد.", - severity: "success", - }); - if (updateTable) { - updateTable(); - } - } - }); - }; - - return ( -
    - - - - -
    - - -
    -
    -
    - ); -}; diff --git a/src/features/slaughter-house/components/slaughter-house-delegates/KillHouseDelegatesTab.js b/src/features/slaughter-house/components/slaughter-house-delegates/KillHouseDelegatesTab.js deleted file mode 100644 index 1f407db..0000000 --- a/src/features/slaughter-house/components/slaughter-house-delegates/KillHouseDelegatesTab.js +++ /dev/null @@ -1,199 +0,0 @@ -import React, { useEffect, useState, useRef } from "react"; -import { Box, Button, Grid, TextField, Chip } from "@mui/material"; -import { useDispatch } from "react-redux"; -import { slaughterGetDelegatesService } from "../../services/slaughter-get-delegates-service"; -import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable"; -import { SPACING } from "../../../../data/spacing"; -import { RiSearchLine } from "react-icons/ri"; -import { DelegatesOperations } from "./DelegatesOperations"; - -export const KillHouseDelegatesTab = () => { - const dispatch = useDispatch(); - const [data, setData] = useState([]); - const [totalRows, setTotalRows] = useState(0); - const [perPage, setPerPage] = useState(10); - const [textValue, setTextValue] = useState(""); - const [page, setPage] = useState(1); - const [tableData, setTableData] = useState([]); - const isFirstMount = useRef(true); - - const handleTextChange = (e) => setTextValue(e.target.value); - - const fetchApiData = async (pageNum) => { - const response = await dispatch( - slaughterGetDelegatesService({ - type: "KillHouse", - search: "filter", - value: textValue, - page: pageNum, - page_size: perPage, - }) - ); - - if (response.payload.error) { - console.error("Error fetching data:", response.payload.error); - setData([]); - setTotalRows(0); - } else { - setData(response.payload.data?.results || []); - const count = Number(response.payload.data?.count) || 0; - setTotalRows(count); - } - }; - - const handlePageChange = (pageNum) => { - fetchApiData(pageNum); - setPage(pageNum); - }; - - const handlePerRowsChange = (perRows) => { - setPerPage(Number(perRows)); - setPage(1); - }; - - const updateTableData = () => { - fetchApiData(page); - }; - - useEffect(() => { - if (!data || !Array.isArray(data)) { - setTableData([]); - return; - } - const d = data.map((item, i) => { - const isActive = item?.active !== undefined ? item.active : !item?.trash; - const hasLimitation = item?.limitation; - const limitationBadge = ( - - ); - - const killhouseDisplay = - item?.killHouse?.name && item?.killHouse?.mobile - ? `${item.killHouse.name} (${item.killHouse.mobile})` - : item?.killHouse?.name - ? item.killHouse.name - : "-"; - - return [ - page === 1 ? i + 1 : i + perPage * (page - 1) + 1, - item?.firstName || item?.first_name || "-", - item?.lastName || item?.last_name || "-", - item?.mobile || "-", - item?.city || "-", - killhouseDisplay, - limitationBadge, - item?.governmentalLimitationWeight || 0, - item?.freeLimitationWeight || 0, - , - , - ]; - }); - setTableData(d); - }, [data, page, perPage]); - - useEffect(() => { - fetchApiData(1); - }, []); - - useEffect(() => { - if (isFirstMount.current) { - isFirstMount.current = false; - return; - } - fetchApiData(1); - setPage(1); - }, [perPage]); - - const handleSubmit = async (e) => { - e.preventDefault(); - setPage(1); - const response = await dispatch( - slaughterGetDelegatesService({ - type: "KillHouse", - search: "filter", - value: textValue, - page: 1, - page_size: perPage, - }) - ); - - if (response.payload.error) { - console.error("Error fetching data:", response.payload.error); - setData([]); - setTotalRows(0); - } else { - setData(response.payload.data?.results || []); - const count = Number(response.payload.data?.count) || 0; - setTotalRows(count); - } - }; - - return ( - - -
    - - - - -
    -
    - - - - -
    - ); -}; diff --git a/src/features/slaughter-house/components/slaughter-house-delegates/SlaughterHouseDelegates.js b/src/features/slaughter-house/components/slaughter-house-delegates/SlaughterHouseDelegates.js deleted file mode 100644 index df4c2a3..0000000 --- a/src/features/slaughter-house/components/slaughter-house-delegates/SlaughterHouseDelegates.js +++ /dev/null @@ -1,27 +0,0 @@ -import React, { useState } from "react"; -import { Grid } from "../../../../components/grid/Grid"; -import { Tab, Tabs, Box } from "@mui/material"; -import { StewardDelegatesTab } from "./StewardDelegatesTab"; -import { KillHouseDelegatesTab } from "./KillHouseDelegatesTab"; - -export const SlaughterHouseDelegates = () => { - const [value, setValue] = useState(0); - - const handleChange = (event, newValue) => { - setValue(newValue); - }; - - return ( - - - - - - - - {value === 0 && } - {value === 1 && } - - - ); -}; diff --git a/src/features/slaughter-house/components/slaughter-house-delegates/StewardDelegatesTab.js b/src/features/slaughter-house/components/slaughter-house-delegates/StewardDelegatesTab.js deleted file mode 100644 index 69d316d..0000000 --- a/src/features/slaughter-house/components/slaughter-house-delegates/StewardDelegatesTab.js +++ /dev/null @@ -1,199 +0,0 @@ -import React, { useEffect, useState, useRef } from "react"; -import { Box, Button, Grid, TextField, Chip } from "@mui/material"; -import { useDispatch } from "react-redux"; -import { slaughterGetDelegatesService } from "../../services/slaughter-get-delegates-service"; -import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable"; -import { SPACING } from "../../../../data/spacing"; -import { RiSearchLine } from "react-icons/ri"; -import { DelegatesOperations } from "./DelegatesOperations"; - -export const StewardDelegatesTab = () => { - const dispatch = useDispatch(); - const [data, setData] = useState([]); - const [totalRows, setTotalRows] = useState(0); - const [perPage, setPerPage] = useState(10); - const [textValue, setTextValue] = useState(""); - const [page, setPage] = useState(1); - const [tableData, setTableData] = useState([]); - const isFirstMount = useRef(true); - - const handleTextChange = (e) => setTextValue(e.target.value); - - const fetchApiData = async (pageNum) => { - const response = await dispatch( - slaughterGetDelegatesService({ - type: "Steward", - search: "filter", - value: textValue, - page: pageNum, - page_size: perPage, - }) - ); - - if (response.payload.error) { - console.error("Error fetching data:", response.payload.error); - setData([]); - setTotalRows(0); - } else { - setData(response.payload.data?.results || []); - const count = Number(response.payload.data?.count) || 0; - setTotalRows(count); - } - }; - - const handlePageChange = (pageNum) => { - fetchApiData(pageNum); - setPage(pageNum); - }; - - const handlePerRowsChange = (perRows) => { - setPerPage(Number(perRows)); - setPage(1); - }; - - const updateTableData = () => { - fetchApiData(page); - }; - - useEffect(() => { - if (!data || !Array.isArray(data)) { - setTableData([]); - return; - } - const d = data.map((item, i) => { - const isActive = item?.active !== undefined ? item.active : !item?.trash; - const hasLimitation = item?.limitation; - const limitationBadge = ( - - ); - - const stewardDisplay = - item?.steward?.name && item?.steward?.user?.mobile - ? `${item.steward.name} (${item.steward.user.mobile})` - : item?.steward?.name - ? item.steward.name - : "-"; - - return [ - page === 1 ? i + 1 : i + perPage * (page - 1) + 1, - item?.firstName || item?.first_name || "-", - item?.lastName || item?.last_name || "-", - item?.mobile || "-", - item?.city || "-", - stewardDisplay, - limitationBadge, - item?.governmentalLimitationWeight || 0, - item?.freeLimitationWeight || 0, - , - , - ]; - }); - setTableData(d); - }, [data, page, perPage]); - - useEffect(() => { - fetchApiData(1); - }, []); - - useEffect(() => { - if (isFirstMount.current) { - isFirstMount.current = false; - return; - } - fetchApiData(1); - setPage(1); - }, [perPage]); - - const handleSubmit = async (e) => { - e.preventDefault(); - setPage(1); - const response = await dispatch( - slaughterGetDelegatesService({ - type: "Steward", - search: "filter", - value: textValue, - page: 1, - page_size: perPage, - }) - ); - - if (response.payload.error) { - console.error("Error fetching data:", response.payload.error); - setData([]); - setTotalRows(0); - } else { - setData(response.payload.data?.results || []); - const count = Number(response.payload.data?.count) || 0; - setTotalRows(count); - } - }; - - return ( - - -
    - - - - -
    -
    - - - - -
    - ); -}; diff --git a/src/features/slaughter-house/components/slaughter-house-dispensers-operations/SlaughterHouseDispensersOperations.js b/src/features/slaughter-house/components/slaughter-house-dispensers-operations/SlaughterHouseDispensersOperations.js index d9fcbe7..d8cbb9f 100644 --- a/src/features/slaughter-house/components/slaughter-house-dispensers-operations/SlaughterHouseDispensersOperations.js +++ b/src/features/slaughter-house/components/slaughter-house-dispensers-operations/SlaughterHouseDispensersOperations.js @@ -5,11 +5,9 @@ import { NavLink } from "../../../../components/nav-link/NavLink"; import LinkItem from "../../../../components/link-item/LinkItem"; import { VscBroadcast, VscPerson } from "react-icons/vsc"; import { - ROUTE_ADMINX_DELEGATES_MANAGEMENT, ROUTE_ADMINX_DISPENSERS_INVENTORY, ROUTE_ADMINX_DISPENSERS_KILLHOUSES, ROUTE_ADMINX_DISPENSERS_MANAGEMENT, - ROUTE_ADMINX_DISPENSERS_MANAGEMENT_V2, ROUTE_ADMINX_DISPENSERS_STEWARDS, ROUTE_ADMINX_DISPENSERS_STOCK, ROUTE_ADMINX_SALE_DESTRIBUTION_DETAILS, @@ -42,15 +40,12 @@ import { import { useLocation } from "react-router-dom"; import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl"; import { FaMoneyBill, FaStore, FaWarehouse } from "react-icons/fa"; -import BadgeIcon from "@mui/icons-material/Badge"; const ROUTE_MAP = { management: { KillHouse: ROUTE_SLAUGHTER_DISPENSERS_MANAGEMENT, AdminX: ROUTE_ADMINX_DISPENSERS_MANAGEMENT, SuperAdmin: ROUTE_SUPER_ADMIN_DISPENSERS_MANAGEMENT, - AdminXX: ROUTE_ADMINX_DISPENSERS_MANAGEMENT_V2, - AdminXXX: ROUTE_ADMINX_DELEGATES_MANAGEMENT, default: ROUTE_PROVINCE_DISPENSERS_MANAGEMENT, }, killhouses: { @@ -114,8 +109,6 @@ export const SlaughterHouseDispensersOperations = () => { ].includes(role); const managementRoute = getRoute("management", role); - const managementRouteV2 = getRoute("management", "AdminXX"); - const managementRouteDelegates = getRoute("management", "AdminXXX"); const killhousesRoute = getRoute("killhouses", role); const stewardsRoute = getRoute("stewards", role); const inventoryRoute = getRoute("inventory", role); @@ -135,26 +128,6 @@ export const SlaughterHouseDispensersOperations = () => { {isAdminX && ( - - } - title="مدیریت نمایندگان" - description="مدیریت نمایندگان" - /> - - - } - title="مدیریت توزیع کنندگان دوم" - description="مدیریت توزیع کنندگان دوم" - /> - ( - - - - - {label} - - {value || "-"} - - -); - -const getValidationSchema = () => - yup.object({ - mobile: yup - .string() - .required("شماره همراه الزامی است") - .matches(/^09\d{9}$/, "شماره تلفن باید با 09 شروع شود و 11 رقم باشد"), - }); - -const DispenserForm = ({ formik, userInfo }) => { - return ( -
    - - {userInfo && ( - - - - اطلاعات شخصی - - - - - - - - - - - - - - - - - - - - - )} - - - - - - - - - - - - - - - - - - - {formik.values.dispenser_type === "driver" && ( - <> - - - - {formik.values.pelak && ( - - - - )} - - )} - - - - - - - - - - - - - -
    - ); -}; - -export const AllDispensersEditForm = ({ item, updateTable }) => { - const dispatch = useDispatch(); - const [openNotif] = useContext(AppContext); - - const nationalId = item?.user?.nationalId || item?.user?.nationalCode; - - // Extract userInfo from item.user object - const userInfo = item?.user - ? { - nationalCode: item.user.nationalId || item.user.nationalCode || null, - fatherName: item.user.fatherName || null, - birthday: item.user.birthday || null, - gender: item.user.gender, - identityNo: item.user.identityNo || null, - identitySeries: item.user.identitySeries || null, - identitySerial: item.user.identitySerial || null, - } - : null; - - const formik = useFormik({ - initialValues: { - first_name: item?.user?.firstName || "", - last_name: item?.user?.lastName || "", - mobile: item?.user?.mobile || "", - city: item?.user?.cityName || "", - national_id: nationalId || "", - dispenser_type: item?.dispenserType || "inductor", - limitation_amount: item?.limitationAmount || 0, - driver_car_type: item?.car || "", - pelak: item?.pelak || "", - }, - enableReinitialize: true, - validationSchema: getValidationSchema(), - onSubmit: (values) => { - const submitData = { - key: item?.key, - mobile: values.mobile, - }; - - dispatch(slaughterHouseEditDispenserService(submitData)).then((r) => { - if (r.payload?.error) { - openNotif({ - vertical: "top", - horizontal: "center", - msg: r.payload.error, - severity: "error", - }); - } else { - openNotif({ - vertical: "top", - horizontal: "center", - msg: "عملیات با موفقیت انجام شد.", - severity: "success", - }); - if (updateTable) { - updateTable(); - } - dispatch(CLOSE_MODAL()); - } - }); - }, - }); - - return ; -}; diff --git a/src/features/slaughter-house/components/slaughter-house-dispensers-v2/AllDispensersOperations.js b/src/features/slaughter-house/components/slaughter-house-dispensers-v2/AllDispensersOperations.js deleted file mode 100644 index 34a4bf4..0000000 --- a/src/features/slaughter-house/components/slaughter-house-dispensers-v2/AllDispensersOperations.js +++ /dev/null @@ -1,79 +0,0 @@ -import { IconButton, Popover, Typography, Button } from "@mui/material"; -import React, { useState } from "react"; -import EditIcon from "@mui/icons-material/Edit"; -import TuneIcon from "@mui/icons-material/Tune"; -import { useDispatch } from "react-redux"; -import { OPEN_MODAL } from "../../../../lib/redux/slices/appSlice"; -import { AllDispensersEditForm } from "./AllDispensersEditForm"; - -export const AllDispensersOperations = ({ item, updateTable }) => { - const [anchorEl, setAnchorEl] = useState(null); - const dispatch = useDispatch(); - - const handleClick = (event) => { - setAnchorEl(event.currentTarget); - }; - - const handleClose = () => { - setAnchorEl(null); - }; - - const open = Boolean(anchorEl); - const id = open ? "popover" : undefined; - - return ( -
    - - - - -
    - -
    -
    -
    - ); -}; diff --git a/src/features/slaughter-house/components/slaughter-house-dispensers-v2/AllDispensersTab.js b/src/features/slaughter-house/components/slaughter-house-dispensers-v2/AllDispensersTab.js deleted file mode 100644 index 8ef8617..0000000 --- a/src/features/slaughter-house/components/slaughter-house-dispensers-v2/AllDispensersTab.js +++ /dev/null @@ -1,162 +0,0 @@ -import React, { useEffect, useState, useRef } from "react"; -import { Box, Button, Grid, TextField } from "@mui/material"; -import { useDispatch } from "react-redux"; -import { slaughterGetDispenserService } from "../../services/slaughter-get-dispenser-service"; -import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable"; -import { SPACING } from "../../../../data/spacing"; -import { RiSearchLine } from "react-icons/ri"; -import { AllDispensersOperations } from "./AllDispensersOperations"; - -export const AllDispensersTab = () => { - const dispatch = useDispatch(); - const [data, setData] = useState([]); - const [totalRows, setTotalRows] = useState(0); - const [perPage, setPerPage] = useState(10); - const [textValue, setTextValue] = useState(""); - const [page, setPage] = useState(1); - const [tableData, setTableData] = useState([]); - const isFirstMount = useRef(true); - - const handleTextChange = (e) => setTextValue(e.target.value); - - const fetchApiData = async (pageNum) => { - const response = await dispatch( - slaughterGetDispenserService({ - search: "filter", - value: textValue, - page: pageNum, - page_size: perPage, - }) - ); - - if (response.payload.error) { - console.error("Error fetching data:", response.payload.error); - setData([]); - setTotalRows(0); - } else { - setData(response.payload.data?.results || []); - const count = Number(response.payload.data?.count) || 0; - setTotalRows(count); - } - }; - - const handlePageChange = (pageNum) => { - fetchApiData(pageNum); - setPage(pageNum); - }; - - const handlePerRowsChange = (perRows) => { - setPerPage(Number(perRows)); - setPage(1); - }; - - const updateTableData = () => { - fetchApiData(page !== 0 ? page : 1); - }; - - useEffect(() => { - if (!data || !Array.isArray(data)) { - setTableData([]); - return; - } - const d = data.map((item, i) => { - return [ - page === 1 ? i + 1 : i + perPage * (page - 1) + 1, - item?.user?.firstName || "-", - item?.user?.lastName || "-", - item?.user?.mobile || "-", - item?.user?.cityName || "-", - , - ]; - }); - setTableData(d); - }, [data, page, perPage]); - - useEffect(() => { - fetchApiData(1); - }, []); - - useEffect(() => { - if (isFirstMount.current) { - isFirstMount.current = false; - return; - } - fetchApiData(1); - setPage(1); - }, [perPage]); - - const handleSubmit = async (e) => { - e.preventDefault(); - setPage(1); - const response = await dispatch( - slaughterGetDispenserService({ - search: "filter", - value: textValue, - page: 1, - page_size: perPage, - }) - ); - - if (response.payload.error) { - console.error("Error fetching data:", response.payload.error); - setData([]); - setTotalRows(0); - } else { - setData(response.payload.data?.results || []); - const count = Number(response.payload.data?.count) || 0; - setTotalRows(count); - } - }; - - return ( - - -
    - - - - -
    -
    - - - - -
    - ); -}; diff --git a/src/features/slaughter-house/components/slaughter-house-dispensers-v2/DispenserInfoLimitationForm.js b/src/features/slaughter-house/components/slaughter-house-dispensers-v2/DispenserInfoLimitationForm.js deleted file mode 100644 index a1ef205..0000000 --- a/src/features/slaughter-house/components/slaughter-house-dispensers-v2/DispenserInfoLimitationForm.js +++ /dev/null @@ -1,135 +0,0 @@ -import React, { useContext, useState } from "react"; -import { - Button, - TextField, - Typography, - Checkbox, - FormControlLabel, -} from "@mui/material"; -import { useDispatch } from "react-redux"; -import { Grid } from "../../../../components/grid/Grid"; -import { SPACING } from "../../../../data/spacing"; -import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice"; -import { AppContext } from "../../../../contexts/AppContext"; -import { slaughterEditDispenserInfoService } from "../../services/slaughter-edit-dispenser-info"; - -export const DispenserInfoLimitationForm = ({ item, updateTable }) => { - const dispatch = useDispatch(); - const [openNotif] = useContext(AppContext); - - const [hasLimitation, setHasLimitation] = useState(item?.limitation || false); - const [governmentalValue, setGovernmentalValue] = useState( - - item?.governmentalLimitationWeight || - 0 - ); - const [freeValue, setFreeValue] = useState( - item?.freeLimitationWeight || 0 - ); - - const handleSubmit = (e) => { - e.preventDefault(); - - const submitData = { - key: item?.key, - limitation: hasLimitation, - governmental_limitation_weight: hasLimitation - ? Number(governmentalValue) - : 0, - free_limitation_weight: hasLimitation ? Number(freeValue) : 0, - }; - - dispatch(slaughterEditDispenserInfoService(submitData)).then((r) => { - if (r.payload?.error) { - openNotif({ - vertical: "top", - horizontal: "center", - msg: r.payload.error, - severity: "error", - }); - } else { - openNotif({ - vertical: "top", - horizontal: "center", - msg: "عملیات با موفقیت انجام شد.", - severity: "success", - }); - if (updateTable) { - updateTable(); - } - dispatch(CLOSE_MODAL()); - } - }); - }; - - return ( -
    - - - - اطلاعات توزیع کننده: - - - {item?.firstName} {item?.lastName} - - - - - setHasLimitation(e.target.checked)} - color="primary" - /> - } - label="محدودیت فروش روزانه" - /> - - - {hasLimitation && ( - <> - - setGovernmentalValue(e.target.value)} - inputProps={{ min: 0 }} - /> - - - - setFreeValue(e.target.value)} - inputProps={{ min: 0 }} - /> - - - )} - - - - - -
    - ); -}; - diff --git a/src/features/slaughter-house/components/slaughter-house-dispensers-v2/DispenserInfoOperations.js b/src/features/slaughter-house/components/slaughter-house-dispensers-v2/DispenserInfoOperations.js deleted file mode 100644 index 7ca2d2d..0000000 --- a/src/features/slaughter-house/components/slaughter-house-dispensers-v2/DispenserInfoOperations.js +++ /dev/null @@ -1,140 +0,0 @@ -import { IconButton, Popover, Typography, Button } from "@mui/material"; -import React, { useState, useContext } from "react"; -import TuneIcon from "@mui/icons-material/Tune"; -import ToggleOnIcon from "@mui/icons-material/ToggleOn"; -import ToggleOffIcon from "@mui/icons-material/ToggleOff"; -import BlockIcon from "@mui/icons-material/Block"; -import { useDispatch } from "react-redux"; -import { AppContext } from "../../../../contexts/AppContext"; -import { OPEN_MODAL } from "../../../../lib/redux/slices/appSlice"; -import { slaughterEditDispenserInfoService } from "../../services/slaughter-edit-dispenser-info"; -import { DispenserInfoLimitationForm } from "./DispenserInfoLimitationForm"; - -export const DispenserInfoOperations = ({ item, updateTable }) => { - const [anchorEl, setAnchorEl] = useState(null); - const dispatch = useDispatch(); - const [openNotif] = useContext(AppContext); - - const handleClick = (event) => { - setAnchorEl(event.currentTarget); - }; - - const handleClose = () => { - setAnchorEl(null); - }; - - const open = Boolean(anchorEl); - const id = open ? "popover" : undefined; - - const isActive = item?.active; - - const handleToggleActive = () => { - handleClose(); - dispatch( - slaughterEditDispenserInfoService({ - key: item?.key, - active: !isActive, - }) - ).then((r) => { - if (r.payload?.error) { - openNotif({ - vertical: "top", - horizontal: "center", - msg: r.payload.error, - severity: "error", - }); - } else { - openNotif({ - vertical: "top", - horizontal: "center", - msg: "عملیات با موفقیت انجام شد.", - severity: "success", - }); - if (updateTable) { - updateTable(); - } - } - }); - }; - - return ( -
    - - - - -
    - - -
    -
    -
    - ); -}; - diff --git a/src/features/slaughter-house/components/slaughter-house-dispensers-v2/KillHouseDispensersTab.js b/src/features/slaughter-house/components/slaughter-house-dispensers-v2/KillHouseDispensersTab.js deleted file mode 100644 index b95c8d1..0000000 --- a/src/features/slaughter-house/components/slaughter-house-dispensers-v2/KillHouseDispensersTab.js +++ /dev/null @@ -1,199 +0,0 @@ -import React, { useEffect, useState, useRef } from "react"; -import { Box, Button, Grid, TextField, Chip } from "@mui/material"; -import { useDispatch } from "react-redux"; -import { slaughterGetDispenserInfoService } from "../../services/slaughter-get-dispenser-info"; -import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable"; -import { SPACING } from "../../../../data/spacing"; -import { RiSearchLine } from "react-icons/ri"; -import { DispenserInfoOperations } from "./DispenserInfoOperations"; - -export const KillHouseDispensersTab = () => { - const dispatch = useDispatch(); - const [data, setData] = useState([]); - const [totalRows, setTotalRows] = useState(0); - const [perPage, setPerPage] = useState(10); - const [textValue, setTextValue] = useState(""); - const [page, setPage] = useState(1); - const [tableData, setTableData] = useState([]); - const isFirstMount = useRef(true); - - const handleTextChange = (e) => setTextValue(e.target.value); - - const fetchApiData = async (pageNum) => { - const response = await dispatch( - slaughterGetDispenserInfoService({ - type: "KillHouse", - search: "filter", - value: textValue, - page: pageNum, - page_size: perPage, - }) - ); - - if (response.payload.error) { - console.error("Error fetching data:", response.payload.error); - setData([]); - setTotalRows(0); - } else { - setData(response.payload.data?.results || []); - const count = Number(response.payload.data?.count) || 0; - setTotalRows(count); - } - }; - - const handlePageChange = (pageNum) => { - fetchApiData(pageNum); - setPage(pageNum); - }; - - const handlePerRowsChange = (perRows) => { - setPerPage(Number(perRows)); - setPage(1); - }; - - useEffect(() => { - if (!data || !Array.isArray(data)) { - setTableData([]); - return; - } - const d = data.map((item, i) => { - const isActive = item?.active; - const hasLimitation = item?.limitation; - const limitationBadge = ( - - ); - - const killhouseDisplay = - item?.killHouse?.name && item?.killHouse?.mobile - ? `${item.killHouse.name} (${item.killHouse.mobile})` - : item?.killHouse?.name - ? item.killHouse.name - : "-"; - - return [ - page === 1 ? i + 1 : i + perPage * (page - 1) + 1, - item?.firstName || "-", - item?.lastName || "-", - item?.mobile || "-", - item?.city || "-", - killhouseDisplay, - limitationBadge, - item?.governmentalLimitationWeight || 0, - item?.freeLimitationWeight || 0, - , - , - ]; - }); - setTableData(d); - }, [data, page, perPage]); - - const updateTableData = () => { - fetchApiData(page); - }; - - useEffect(() => { - fetchApiData(1); - }, []); - - useEffect(() => { - if (isFirstMount.current) { - isFirstMount.current = false; - return; - } - fetchApiData(1); - setPage(1); - }, [perPage]); - - const handleSubmit = async (e) => { - e.preventDefault(); - setPage(1); - const response = await dispatch( - slaughterGetDispenserInfoService({ - type: "KillHouse", - search: "filter", - value: textValue, - page: 1, - page_size: perPage, - }) - ); - - if (response.payload.error) { - console.error("Error fetching data:", response.payload.error); - setData([]); - setTotalRows(0); - } else { - setData(response.payload.data?.results || []); - const count = Number(response.payload.data?.count) || 0; - setTotalRows(count); - } - }; - - return ( - - -
    - - - - -
    -
    - - - - -
    - ); -}; diff --git a/src/features/slaughter-house/components/slaughter-house-dispensers-v2/SlaughterHouseDispensers.js b/src/features/slaughter-house/components/slaughter-house-dispensers-v2/SlaughterHouseDispensers.js deleted file mode 100644 index 47115c8..0000000 --- a/src/features/slaughter-house/components/slaughter-house-dispensers-v2/SlaughterHouseDispensers.js +++ /dev/null @@ -1,30 +0,0 @@ -import React, { useState } from "react"; -import { Grid } from "../../../../components/grid/Grid"; -import { Tab, Tabs, Box } from "@mui/material"; -import { AllDispensersTab } from "./AllDispensersTab"; -import { KillHouseDispensersTab } from "./KillHouseDispensersTab"; -import { StewardDispensersTab } from "./StewardDispensersTab"; - -export const SlaughterHouseDispensersV2 = () => { - const [value, setValue] = useState(0); - - const handleChange = (event, newValue) => { - setValue(newValue); - }; - - return ( - - - - - - - - - {value === 0 && } - {value === 1 && } - {value === 2 && } - - - ); -}; diff --git a/src/features/slaughter-house/components/slaughter-house-dispensers-v2/StewardDispensersTab.js b/src/features/slaughter-house/components/slaughter-house-dispensers-v2/StewardDispensersTab.js deleted file mode 100644 index b7c1070..0000000 --- a/src/features/slaughter-house/components/slaughter-house-dispensers-v2/StewardDispensersTab.js +++ /dev/null @@ -1,199 +0,0 @@ -import React, { useEffect, useState, useRef } from "react"; -import { Box, Button, Grid, TextField, Chip } from "@mui/material"; -import { useDispatch } from "react-redux"; -import { slaughterGetDispenserInfoService } from "../../services/slaughter-get-dispenser-info"; -import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable"; -import { SPACING } from "../../../../data/spacing"; -import { RiSearchLine } from "react-icons/ri"; -import { DispenserInfoOperations } from "./DispenserInfoOperations"; - -export const StewardDispensersTab = () => { - const dispatch = useDispatch(); - const [data, setData] = useState([]); - const [totalRows, setTotalRows] = useState(0); - const [perPage, setPerPage] = useState(10); - const [textValue, setTextValue] = useState(""); - const [page, setPage] = useState(1); - const [tableData, setTableData] = useState([]); - const isFirstMount = useRef(true); - - const handleTextChange = (e) => setTextValue(e.target.value); - - const fetchApiData = async (pageNum) => { - const response = await dispatch( - slaughterGetDispenserInfoService({ - type: "Steward", - search: "filter", - value: textValue, - page: pageNum, - page_size: perPage, - }) - ); - - if (response.payload.error) { - console.error("Error fetching data:", response.payload.error); - setData([]); - setTotalRows(0); - } else { - setData(response.payload.data?.results || []); - const count = Number(response.payload.data?.count) || 0; - setTotalRows(count); - } - }; - - const handlePageChange = (pageNum) => { - fetchApiData(pageNum); - setPage(pageNum); - }; - - const handlePerRowsChange = (perRows) => { - setPerPage(Number(perRows)); - setPage(1); - }; - - useEffect(() => { - if (!data || !Array.isArray(data)) { - setTableData([]); - return; - } - const d = data.map((item, i) => { - const isActive = item?.active; - const hasLimitation = item?.limitation; - const limitationBadge = ( - - ); - - const stewardDisplay = - item?.steward?.name && item?.steward?.user?.mobile - ? `${item.steward.name} (${item.steward.user.mobile})` - : item?.steward?.name - ? item.steward.name - : "-"; - - return [ - page === 1 ? i + 1 : i + perPage * (page - 1) + 1, - item?.firstName || "-", - item?.lastName || "-", - item?.mobile || "-", - item?.city || "-", - stewardDisplay, - limitationBadge, - item?.governmentalLimitationWeight || 0, - item?.freeLimitationWeight || 0, - , - , - ]; - }); - setTableData(d); - }, [data, page, perPage]); - - const updateTableData = () => { - fetchApiData(page); - }; - - useEffect(() => { - fetchApiData(1); - }, []); - - useEffect(() => { - if (isFirstMount.current) { - isFirstMount.current = false; - return; - } - fetchApiData(1); - setPage(1); - }, [perPage]); - - const handleSubmit = async (e) => { - e.preventDefault(); - setPage(1); - const response = await dispatch( - slaughterGetDispenserInfoService({ - type: "Steward", - search: "filter", - value: textValue, - page: 1, - page_size: perPage, - }) - ); - - if (response.payload.error) { - console.error("Error fetching data:", response.payload.error); - setData([]); - setTotalRows(0); - } else { - setData(response.payload.data?.results || []); - const count = Number(response.payload.data?.count) || 0; - setTotalRows(count); - } - }; - - return ( - - -
    - - - - -
    -
    - - - - -
    - ); -}; diff --git a/src/features/slaughter-house/components/slaughter-inventory-free-buy-bars-alives/SlaughterInventoryFreeBuyBarsAlives.js b/src/features/slaughter-house/components/slaughter-inventory-free-buy-bars-alives/SlaughterInventoryFreeBuyBarsAlives.js index 2dd29bb..9537cf0 100644 --- a/src/features/slaughter-house/components/slaughter-inventory-free-buy-bars-alives/SlaughterInventoryFreeBuyBarsAlives.js +++ b/src/features/slaughter-house/components/slaughter-inventory-free-buy-bars-alives/SlaughterInventoryFreeBuyBarsAlives.js @@ -19,7 +19,6 @@ import { slaughterGetProfile } from "../../services/slaughter-get-profile"; import { CheckCleanceCode } from "../../../../components/check-clearance-code/ChechClearanceCode"; import { SlaughterFreeBarsAlivesOperations } from "../slaughter-free-bars-alives-operations/SlaughterFreeBarsAlivesOperations"; import { AppContext } from "../../../../contexts/AppContext"; -import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; export const SlaughterInventoryFreeBuyBarsAlives = ({ title, @@ -32,19 +31,9 @@ export const SlaughterInventoryFreeBuyBarsAlives = ({ }) => { const dispatch = useDispatch(); const [openNotif] = useContext(AppContext); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); - useEffect(() => { - dispatch( - slaughterGetProfile({ - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) - ); - }, [selectedSubUser?.key]); + dispatch(slaughterGetProfile()); + }, []); const [data, setData] = useState([]); const [totalRows, setTotalRows] = useState(0); @@ -57,11 +46,7 @@ export const SlaughterInventoryFreeBuyBarsAlives = ({ dispatch(LOADING_START()); try { response = await axios.get( - `kill_house_free_bar/?type=live&role=${getRoleFromUrl()}${ - checkPathStartsWith("slaughter") - ? `&role_key=${selectedSubUser?.key}` - : "" - }&page=${page}&page_size=${perPage}&bar_state=${barState}&date_type=input${ + `kill_house_free_bar/?type=live&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}&bar_state=${barState}&date_type=input${ withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : "" }${searchValue ? `&search=filter&value=${searchValue}` : ""}` ); @@ -91,14 +76,7 @@ export const SlaughterInventoryFreeBuyBarsAlives = ({ useEffect(() => { fetchApiData(1); - }, [ - perPage, - withDate, - selectedDate1, - selectedDate2, - searchValue, - selectedSubUser?.key, - ]); + }, [perPage, withDate, selectedDate1, selectedDate2, searchValue]); useEffect(() => { const d = data?.map((item, i) => { @@ -186,11 +164,7 @@ export const SlaughterInventoryFreeBuyBarsAlives = ({ }); const link = `${ axios.defaults.baseURL - }kill_house_free_bar_excel/?role=${getRoleFromUrl()}${ - checkPathStartsWith("slaughter") - ? `&role_key=${selectedSubUser?.key}` - : "" - }&key=${userKey}&type=live&bar_state=${barState}${ + }kill_house_free_bar_excel/?role=${getRoleFromUrl()}&key=${userKey}&type=live&bar_state=${barState}${ withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : "" diff --git a/src/features/slaughter-house/components/slaughter-inventory-free-buy-bars/SlaughterInventoryFreeBuyBars.js b/src/features/slaughter-house/components/slaughter-inventory-free-buy-bars/SlaughterInventoryFreeBuyBars.js index 23584f4..cf211d2 100644 --- a/src/features/slaughter-house/components/slaughter-inventory-free-buy-bars/SlaughterInventoryFreeBuyBars.js +++ b/src/features/slaughter-house/components/slaughter-inventory-free-buy-bars/SlaughterInventoryFreeBuyBars.js @@ -26,7 +26,6 @@ import { vetFarmGetOutProvinceDashboard } from "../../../vet-farm/services/vet-f import ToggleOffOutlinedIcon from "@mui/icons-material/ToggleOffOutlined"; import ToggleOnIcon from "@mui/icons-material/ToggleOn"; import { SlaughterInventoryFreeBuyBarsAlives } from "../slaughter-inventory-free-buy-bars-alives/SlaughterInventoryFreeBuyBarsAlives"; -import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; export const SlaughterInventoryFreeBuyBars = () => { const dispatch = useDispatch(); @@ -34,9 +33,6 @@ export const SlaughterInventoryFreeBuyBars = () => { const handleTabChange = (event, newValue) => { setActiveTab(newValue); }; - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] = useContext(AppContext); @@ -52,14 +48,8 @@ export const SlaughterInventoryFreeBuyBars = () => { }; useEffect(() => { - dispatch( - slaughterGetProfile({ - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) - ); - }, [selectedSubUser?.key, dispatch]); + dispatch(slaughterGetProfile()); + }, []); const [data, setData] = useState([]); const [totalRows, setTotalRows] = useState(0); @@ -71,15 +61,12 @@ export const SlaughterInventoryFreeBuyBars = () => { const [searchValue, setSearchValue] = useState(""); const fetchApiData = async (page) => { + let response; dispatch(LOADING_START()); - const response = await axios.get( + response = await axios.get( `kill_house_free_bar/?type=${ activeTab === 0 ? "live" : "carcass" }&dashboard=true&search=filter&value=${searchValue}&role=${getRoleFromUrl()}${ - checkPathStartsWith("slaughter") - ? `&role_key=${selectedSubUser?.key}` - : "" - }${ withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : "" }&page=${page}&page_size=${perPage}&date_type=input` ); @@ -99,8 +86,7 @@ export const SlaughterInventoryFreeBuyBars = () => { }; const updateTable = () => { - setPage(1); - fetchApiData(1); + fetchApiData(page !== 0 ? page : 1); fetchDashboardData(); }; @@ -109,9 +95,6 @@ export const SlaughterInventoryFreeBuyBars = () => { vetFarmGetOutProvinceDashboard({ search: "filter", role: getRoleFromUrl(), - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", value: searchValue, type: activeTab === 0 ? "live" : "carcass", ...(withDate && { @@ -127,15 +110,7 @@ export const SlaughterInventoryFreeBuyBars = () => { useEffect(() => { fetchApiData(page !== 0 ? page : 1); fetchDashboardData(); - }, [ - withDate, - selectedDate1, - selectedDate2, - perPage, - activeTab, - searchValue, - selectedSubUser?.key, - ]); + }, [withDate, selectedDate1, selectedDate2, perPage, activeTab, searchValue]); useEffect(() => { const d = data?.map((item, i) => { @@ -343,7 +318,7 @@ export const SlaughterInventoryFreeBuyBars = () => {
    - + {activeTab === 0 ? ( { onClick={() => { const link = `${ axios.defaults.baseURL - }kill_house_free_bar_excel/?role=${getRoleFromUrl()}${ - checkPathStartsWith("slaughter") - ? `&role_key=${selectedSubUser?.key}` - : "" - }&key=${userKey}${ + }kill_house_free_bar_excel/?role=${getRoleFromUrl()}&key=${userKey}${ withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : "" diff --git a/src/features/slaughter-house/components/slaughter-inventory-in-province-bars/SlaughterInventoryInProvinceBars.js b/src/features/slaughter-house/components/slaughter-inventory-in-province-bars/SlaughterInventoryInProvinceBars.js index 0dce5b9..13ec4cb 100644 --- a/src/features/slaughter-house/components/slaughter-inventory-in-province-bars/SlaughterInventoryInProvinceBars.js +++ b/src/features/slaughter-house/components/slaughter-inventory-in-province-bars/SlaughterInventoryInProvinceBars.js @@ -13,7 +13,7 @@ import { } from "@mui/material"; import { DatePicker } from "@mui/x-date-pickers"; import moment from "moment"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; import axios from "axios"; import { LOADING_END, @@ -27,15 +27,11 @@ import { SlaughterSubmitRealInventory } from "../slaughter-submit-real-inventory import SettingsIcon from "@mui/icons-material/Settings"; import { formatJustDate } from "../../../../utils/formatTime"; import { RiSearchLine } from "react-icons/ri"; -import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; export const SlaughterInventoryInProvinceBars = ({ type }) => { const [selectedDate1, setSelectedDate1] = useState( moment(new Date()).format("YYYY-MM-DD") ); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); const [selectedDate2, setSelectedDate2] = useState( moment(new Date()).format("YYYY-MM-DD") ); @@ -58,13 +54,7 @@ export const SlaughterInventoryInProvinceBars = ({ type }) => { dispatch(LOADING_START()); const response = await axios.get( `bars_for_kill_house/?search=filter&value=${textValue}&role=${getRoleFromUrl()}${ - withDate - ? `&date1=${selectedDate1}${ - checkPathStartsWith("slaughter") - ? `&role_key=${selectedSubUser?.key}` - : "" - }&date2=${selectedDate2}` - : `` + withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : `` }&page=${page}&page_size=${perPage}&type=${type}"a=${quota}` ); dispatch(LOADING_END()); @@ -81,7 +71,6 @@ export const SlaughterInventoryInProvinceBars = ({ type }) => { quota, dispatch, setData, - selectedSubUser?.key, setTotalRows, ] ); @@ -172,11 +161,7 @@ export const SlaughterInventoryInProvinceBars = ({ type }) => { try { const response = await axios.get( - `bars_for_kill_house/?role=${getRoleFromUrl()}${ - checkPathStartsWith("slaughter") - ? `&role_key=${selectedSubUser?.key}` - : "" - }&search=filter&value=${textValue}${ + `bars_for_kill_house/?role=${getRoleFromUrl()}&search=filter&value=${textValue}${ withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : `` }&page=${1}&page_size=${perPage}&type=${type}"a=${quota}` ); diff --git a/src/features/slaughter-house/components/slaughter-inventory-summary/SlaughterInventorySummary.js b/src/features/slaughter-house/components/slaughter-inventory-summary/SlaughterInventorySummary.js index ad18a72..868aba4 100644 --- a/src/features/slaughter-house/components/slaughter-inventory-summary/SlaughterInventorySummary.js +++ b/src/features/slaughter-house/components/slaughter-inventory-summary/SlaughterInventorySummary.js @@ -1,4 +1,4 @@ -import React, { useEffect } from "react"; +import React from "react"; import { Grid } from "../../../../components/grid/Grid"; import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable"; import { SlaughterShowProducts } from "../slaughter-show-products/SlaughterShowProducts"; @@ -8,31 +8,17 @@ import { Button } from "@mui/material"; import { DRAWER } from "../../../../lib/redux/slices/appSlice"; import { SlaughterSubmitOperations } from "../slaughter-submit-operations/SlaughterSubmitOperations"; import { fetchSlaughterBroadcastAndProducts } from "../../services/handle-fetch-slaughter-products"; -import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; export const SlaughterInventorySummary = ({ priceInfo }) => { const { distributionInfo, slaughterProducts } = useSelector( (state) => state.slaughterSlice ); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); const dispatch = useDispatch(); const updateTable = () => { - dispatch( - fetchSlaughterBroadcastAndProducts({ - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) - ); + dispatch(fetchSlaughterBroadcastAndProducts()); }; - useEffect(() => { - updateTable(); - }, [selectedSubUser?.key]); - return ( {!!data?.length && ( -
    + @@ -617,31 +329,205 @@ export const SlaughterManageBars = () => {
    )} - {showDocumentCheckbox && ( + {(getRoleFromUrl() === "SuperAdmin" || + getRoleFromUrl() === "Supporter" || + getRoleFromUrl() === "AdminX") && ( } label="بدون وضعیت سند" /> )}
    - + + {dashboardData?.lenKillRequest?.toLocaleString()} + , + + {dashboardData?.killRequestQuantity?.toLocaleString()} + , + + {dashboardData?.killRequestWeight?.toLocaleString()} + , + + {dashboardData?.avgWeight} + , + + {dashboardData?.minAge} + , + + {dashboardData?.maxAge} + , + + {dashboardData?.avgAge} + , + + {dashboardData?.lenKillRequestHasCode?.toLocaleString()} + , + + {dashboardData?.quantityOfKillRequestHasCode?.toLocaleString()} + , + + {dashboardData?.lenKillRequestHasQuarantine?.toLocaleString()} + , + + {dashboardData?.quantityOfKillRequestHasQuarantine?.toLocaleString()} + , + + {dashboardData?.lenKillRequestHasNotCode?.toLocaleString()} + , + + {dashboardData?.quantityOfKillRequestHasNotCode?.toLocaleString()} + , + + {dashboardData?.differenceBar?.toLocaleString()} + , + + {dashboardData?.lenCompleteWithKillHouse?.toLocaleString()} + , + + {dashboardData?.quantityFinalKillHouse?.toLocaleString()} + , + + {dashboardData?.weightFinalKillHouse?.toLocaleString()} + , + + {dashboardData?.wareHouseBars?.toLocaleString()} + , + + {dashboardData?.wareHouseBarsQuantity?.toLocaleString()} + , + + {dashboardData?.wareHouseBarsWeight?.toLocaleString()} + , + + {dashboardData?.wareHouseBarsWeightLose + ?.toFixed(2) + ?.toLocaleString()} + , + ], + ]} /> { - const dispatch = useDispatch(); - const [data, setData] = useState([]); - const [totalRows, setTotalRows] = useState(0); - const [perPage, setPerPage] = useState(10); - const [textValue, setTextValue] = useState(""); - const [page, setPage] = useState(1); - const [tableData, setTableData] = useState([]); - const isFirstMount = useRef(true); - const isSteward = getRoleFromUrl() === "Steward"; - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); - const handleTextChange = (e) => setTextValue(e.target.value); - - const fetchApiData = async (pageNum) => { - const response = await dispatch( - slaughterGetDelegatesInfoService({ - search: "filter", - value: textValue, - page: pageNum, - page_size: perPage, - role_key: - checkPathStartsWith("slaughter") || checkPathStartsWith("steward") - ? selectedSubUser?.key || "" - : "", - }) - ); - - if (response.payload.error) { - console.error("Error fetching data:", response.payload.error); - setData([]); - setTotalRows(0); - } else { - setData(response.payload.data?.results || []); - const count = Number(response.payload.data?.count) || 0; - setTotalRows(count); - } - }; - - const handlePageChange = (pageNum) => { - fetchApiData(pageNum); - setPage(pageNum); - }; - - const handlePerRowsChange = (perRows) => { - setPerPage(Number(perRows)); - setPage(1); - }; - - const updateTableData = () => { - fetchApiData(page !== 0 ? page : 1); - }; - - useEffect(() => { - if (!data || !Array.isArray(data)) { - setTableData([]); - return; - } - const d = data.map((item, i) => { - const isActive = item?.trash !== undefined ? !item.trash : null; - const statusBadge = - isActive === null ? ( - "-" - ) : ( - - ); - const hasLimitation = item?.limitation; - const limitationBadge = ( - - ); - const killhouseDisplay = - item?.killHouse?.name && item?.killHouse?.mobile - ? `${item.killHouse.name} (${item.killHouse.mobile})` - : item?.killHouse?.name - ? item.killHouse.name - : "-"; - - const stewardDisplay = - item?.steward?.name && item?.steward?.user?.mobile - ? `${item.steward.name} (${item.steward.user.mobile})` - : item?.steward?.name - ? item.steward.name - : "-"; - - const displayValue = isSteward ? stewardDisplay : killhouseDisplay; - - return [ - page === 1 ? i + 1 : i + perPage * (page - 1) + 1, - item?.createDate ? formatJustDate(item.createDate) : "-", - item?.firstName || "-", - item?.lastName || "-", - item?.mobile || "-", - item?.city || "-", - displayValue, - limitationBadge, - item?.governmentalLimitationWeight || 0, - item?.freeLimitationWeight || 0, - statusBadge, - , - ]; - }); - setTableData(d); - }, [data, page, perPage]); - - useEffect(() => { - fetchApiData(1); - }, [selectedSubUser?.key]); - - useEffect(() => { - if (isFirstMount.current) { - isFirstMount.current = false; - return; - } - fetchApiData(1); - setPage(1); - }, [perPage]); - - const handleSubmit = async (e) => { - e.preventDefault(); - setPage(1); - const response = await dispatch( - slaughterGetDelegatesInfoService({ - search: "filter", - value: textValue, - page: 1, - page_size: perPage, - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) - ); - - if (response.payload.error) { - console.error("Error fetching data:", response.payload.error); - setData([]); - setTotalRows(0); - } else { - setData(response.payload.data?.results || []); - const count = Number(response.payload.data?.count) || 0; - setTotalRows(count); - } - }; - - const handleOpenModal = () => { - dispatch( - OPEN_MODAL({ - title: "ثبت نماینده جدید", - content: , - size: 300, - }) - ); - }; - - return ( - - - - - - - -
    - - - - - -
    -
    - - - - -
    -
    - ); -}; - -export default SlaughterManageDelegates; diff --git a/src/features/slaughter-house/components/slaughter-manage-delegates/SlaughterManageDelegatesForm.js b/src/features/slaughter-house/components/slaughter-manage-delegates/SlaughterManageDelegatesForm.js deleted file mode 100644 index 5467f48..0000000 --- a/src/features/slaughter-house/components/slaughter-manage-delegates/SlaughterManageDelegatesForm.js +++ /dev/null @@ -1,165 +0,0 @@ -import React, { useContext } from "react"; -import { useFormik } from "formik"; -import * as yup from "yup"; -import { useDispatch } from "react-redux"; -import { Button, TextField } from "@mui/material"; -import { Grid } from "../../../../components/grid/Grid"; -import { SPACING } from "../../../../data/spacing"; -import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice"; -import { AppContext } from "../../../../contexts/AppContext"; -import { - slaughterSubmitRepresentativeService, - slaughterEditRepresentativeService, -} from "../../services/slaughter-submit-delegate"; -import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl"; - -const getValidationSchema = () => - yup.object({ - first_name: yup.string().required("نام الزامی است"), - last_name: yup.string().required("نام خانوادگی الزامی است"), - mobile: yup - .string() - .required("شماره همراه الزامی است") - .matches(/^09\d{9}$/, "شماره تلفن باید با 09 شروع شود و 11 رقم باشد"), - city: yup.string().required("شهر الزامی است"), - }); - -export const SlaughterManageDelegatesForm = ({ updateTable, item, isEdit }) => { - const dispatch = useDispatch(); - const [openNotif] = useContext(AppContext); - - const formik = useFormik({ - initialValues: { - first_name: item?.first_name || item?.firstName || "", - last_name: item?.last_name || item?.lastName || "", - mobile: item?.mobile || "", - city: item?.city || "", - }, - enableReinitialize: true, - validationSchema: getValidationSchema(), - onSubmit: (values) => { - const submitData = isEdit - ? { - key: item?.key, - first_name: values.first_name, - last_name: values.last_name, - mobile: values.mobile, - city: values.city, - } - : { - first_name: values.first_name, - last_name: values.last_name, - mobile: values.mobile, - city: values.city, - role: getRoleFromUrl(), - }; - - const service = isEdit - ? slaughterEditRepresentativeService - : slaughterSubmitRepresentativeService; - - dispatch(service(submitData)).then((r) => { - if (r.payload.error) { - openNotif({ - vertical: "top", - horizontal: "center", - msg: r.payload.error, - severity: "error", - }); - } else { - openNotif({ - vertical: "top", - horizontal: "center", - msg: "عملیات با موفقیت انجام شد.", - severity: "success", - }); - if (updateTable) { - updateTable(); - } - dispatch(CLOSE_MODAL()); - } - }); - }, - }); - - return ( -
    - - - - - - - - - - - - - - - - - - - - - -
    - ); -}; diff --git a/src/features/slaughter-house/components/slaughter-manage-delegates/SlaughterManageDelegatesLimitationForm.js b/src/features/slaughter-house/components/slaughter-manage-delegates/SlaughterManageDelegatesLimitationForm.js deleted file mode 100644 index 03363df..0000000 --- a/src/features/slaughter-house/components/slaughter-manage-delegates/SlaughterManageDelegatesLimitationForm.js +++ /dev/null @@ -1,133 +0,0 @@ -import React, { useContext, useState } from "react"; -import { - Button, - TextField, - Typography, - Checkbox, - FormControlLabel, -} from "@mui/material"; -import { useDispatch } from "react-redux"; -import { Grid } from "../../../../components/grid/Grid"; -import { SPACING } from "../../../../data/spacing"; -import { CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice"; -import { AppContext } from "../../../../contexts/AppContext"; -import { slaughterEditRepresentativeService } from "../../services/slaughter-submit-delegate"; - -export const SlaughterManageDelegatesLimitationForm = ({ - item, - updateTable, -}) => { - const dispatch = useDispatch(); - const [openNotif] = useContext(AppContext); - - const [hasLimitation, setHasLimitation] = useState(item?.limitation || false); - const [governmentalValue, setGovernmentalValue] = useState( - item?.governmentalLimitationWeight || 0 - ); - const [freeValue, setFreeValue] = useState(item?.freeLimitationWeight || 0); - - const handleSubmit = (e) => { - e.preventDefault(); - - const submitData = { - key: item?.key, - limitation: hasLimitation, - governmental_limitation_weight: hasLimitation - ? Number(governmentalValue) - : 0, - free_limitation_weight: hasLimitation ? Number(freeValue) : 0, - }; - - dispatch(slaughterEditRepresentativeService(submitData)).then((r) => { - if (r.payload?.error) { - openNotif({ - vertical: "top", - horizontal: "center", - msg: r.payload.error, - severity: "error", - }); - } else { - openNotif({ - vertical: "top", - horizontal: "center", - msg: "عملیات با موفقیت انجام شد.", - severity: "success", - }); - if (updateTable) { - updateTable(); - } - dispatch(CLOSE_MODAL()); - } - }); - }; - - return ( -
    - - - - اطلاعات نماینده: - - - {item?.firstName} {item?.lastName} - - - - - setHasLimitation(e.target.checked)} - color="primary" - /> - } - label="محدودیت فروش روزانه" - /> - - - {hasLimitation && ( - <> - - setGovernmentalValue(e.target.value)} - inputProps={{ min: 0 }} - /> - - - - setFreeValue(e.target.value)} - inputProps={{ min: 0 }} - /> - - - )} - - - - - -
    - ); -}; diff --git a/src/features/slaughter-house/components/slaughter-manage-delegates/SlaughterManageDelegatesOperations.js b/src/features/slaughter-house/components/slaughter-manage-delegates/SlaughterManageDelegatesOperations.js deleted file mode 100644 index 0ba758f..0000000 --- a/src/features/slaughter-house/components/slaughter-manage-delegates/SlaughterManageDelegatesOperations.js +++ /dev/null @@ -1,114 +0,0 @@ -import { IconButton, Popover, Typography, Button, Box } from "@mui/material"; -import React, { useState } from "react"; -import EditIcon from "@mui/icons-material/Edit"; -import BlockIcon from "@mui/icons-material/Block"; -import TuneIcon from "@mui/icons-material/Tune"; -import { useDispatch } from "react-redux"; -import { OPEN_MODAL } from "../../../../lib/redux/slices/appSlice"; -import { SlaughterManageDelegatesForm } from "./SlaughterManageDelegatesForm"; -import { SlaughterManageDelegatesLimitationForm } from "./SlaughterManageDelegatesLimitationForm"; - -export const SlaughterManageDelegatesOperations = ({ item, updateTable }) => { - const [anchorEl, setAnchorEl] = useState(null); - const dispatch = useDispatch(); - - const handleClick = (event) => { - setAnchorEl(event.currentTarget); - }; - - const handleClose = () => { - setAnchorEl(null); - }; - - const open = Boolean(anchorEl); - const id = open ? "popover" : undefined; - - return ( -
    - - - - - - - - - -
    - ); -}; diff --git a/src/features/slaughter-house/components/slaughter-manage-dispensers/SlaughterManageDispensers.js b/src/features/slaughter-house/components/slaughter-manage-dispensers/SlaughterManageDispensers.js index 2426ad2..84d4bb3 100644 --- a/src/features/slaughter-house/components/slaughter-manage-dispensers/SlaughterManageDispensers.js +++ b/src/features/slaughter-house/components/slaughter-manage-dispensers/SlaughterManageDispensers.js @@ -1,6 +1,8 @@ import React, { useEffect, useState } from "react"; -import { Box, Button, Grid, TextField, Chip } from "@mui/material"; -import { useDispatch, useSelector } from "react-redux"; +import { Box, Button, Grid, TextField } from "@mui/material"; +import { DatePicker } from "@mui/x-date-pickers"; +import moment from "moment"; +import { useDispatch } from "react-redux"; import { BackButton } from "../../../../components/back-button/BackButton"; import { OPEN_MODAL, CLOSE_MODAL } from "../../../../lib/redux/slices/appSlice"; @@ -10,9 +12,6 @@ import ResponsiveTable from "../../../../components/responsive-table/ResponsiveT import { SPACING } from "../../../../data/spacing"; import { RiSearchLine } from "react-icons/ri"; import { formatJustDate } from "../../../../utils/formatTime"; -import { SlaughterManageDispensersOperations } from "./SlaughterManageDispensersOperations"; -import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl"; -import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; const SlaughterManageDispensers = () => { const dispatch = useDispatch(); @@ -22,10 +21,9 @@ const SlaughterManageDispensers = () => { const [textValue, setTextValue] = useState(""); const [page, setPage] = useState(1); const [tableData, setTableData] = useState([]); - const isSteward = getRoleFromUrl() === "Steward"; - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); + const [selectedDate1, setSelectedDate1] = useState(null); + const [selectedDate2, setSelectedDate2] = useState(null); + const handleTextChange = (e) => setTextValue(e.target.value); const fetchApiData = async (pageNum) => { @@ -35,9 +33,12 @@ const SlaughterManageDispensers = () => { value: textValue, page: pageNum, page_size: perPage, - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", + ...(selectedDate1 && { + date_from: moment(selectedDate1).format("YYYY-MM-DD"), + }), + ...(selectedDate2 && { + date_to: moment(selectedDate2).format("YYYY-MM-DD"), + }), }) ); @@ -72,62 +73,16 @@ const SlaughterManageDispensers = () => { return; } const d = data.map((item, i) => { - const isActive = item?.active !== undefined ? item.active : null; - const statusBadge = - isActive === null ? ( - "-" - ) : ( - - ); - const hasLimitation = item?.limitation; - const limitationBadge = ( - - ); - const killhouseDisplay = - item?.killHouse?.name && item?.killHouse?.mobile - ? `${item.killHouse.name} (${item.killHouse.mobile})` - : item?.killHouse?.name - ? item.killHouse.name - : "-"; - - const stewardDisplay = - item?.steward?.name && item?.steward?.user?.mobile - ? `${item.steward.name} (${item.steward.user.mobile})` - : item?.steward?.name - ? item.steward.name - : "-"; - - const displayValue = isSteward ? stewardDisplay : killhouseDisplay; - return [ page === 1 ? i + 1 : i + perPage * (page - 1) + 1, - item?.createDate ? formatJustDate(item.createDate) : "-", item?.nationalId || "-", item?.firstName || "-", item?.lastName || "-", item?.mobile || "-", item?.city || "-", item?.province || "-", - displayValue, - limitationBadge, - item?.governmentalLimitationWeight || 0, - item?.freeLimitationWeight || 0, - statusBadge, - , + item?.active !== undefined ? (item.active ? "فعال" : "غیرفعال") : "-", + item?.createDate ? formatJustDate(item.createDate) : "-", ]; }); setTableData(d); @@ -136,11 +91,11 @@ const SlaughterManageDispensers = () => { useEffect(() => { fetchApiData(1); setPage(1); - }, [perPage, selectedSubUser?.key]); + }, [perPage]); useEffect(() => { fetchApiData(1); - }, [selectedSubUser?.key]); + }, []); const handleSubmit = async (e) => { e.preventDefault(); @@ -151,10 +106,12 @@ const SlaughterManageDispensers = () => { value: textValue, page: 1, page_size: perPage, - role_key: - checkPathStartsWith("slaughter") || checkPathStartsWith("steward") - ? selectedSubUser?.key || "" - : "", + ...(selectedDate1 && { + date_from: moment(selectedDate1).format("YYYY-MM-DD"), + }), + ...(selectedDate2 && { + date_to: moment(selectedDate2).format("YYYY-MM-DD"), + }), }) ); @@ -206,6 +163,28 @@ const SlaughterManageDispensers = () => { onChange={handleTextChange} /> + { + setSelectedDate1(newValue); + }} + renderInput={(params) => ( + + )} + /> + + { + setSelectedDate2(newValue); + }} + renderInput={(params) => ( + + )} + /> + -
    -
    - - ); -}; diff --git a/src/features/slaughter-house/components/slaughter-manage-dispensers/SlaughterManageDispensersOperations.js b/src/features/slaughter-house/components/slaughter-manage-dispensers/SlaughterManageDispensersOperations.js deleted file mode 100644 index deeeb24..0000000 --- a/src/features/slaughter-house/components/slaughter-manage-dispensers/SlaughterManageDispensersOperations.js +++ /dev/null @@ -1,82 +0,0 @@ -import { IconButton, Popover, Typography, Button } from "@mui/material"; -import React, { useState } from "react"; -import TuneIcon from "@mui/icons-material/Tune"; -import BlockIcon from "@mui/icons-material/Block"; -import { useDispatch } from "react-redux"; -import { OPEN_MODAL } from "../../../../lib/redux/slices/appSlice"; -import { SlaughterManageDispensersLimitationForm } from "./SlaughterManageDispensersLimitationForm"; - -export const SlaughterManageDispensersOperations = ({ item, updateTable }) => { - const [anchorEl, setAnchorEl] = useState(null); - const dispatch = useDispatch(); - - const handleClick = (event) => { - setAnchorEl(event.currentTarget); - }; - - const handleClose = () => { - setAnchorEl(null); - }; - - const open = Boolean(anchorEl); - const id = open ? "popover" : undefined; - - const handleOpenLimitationModal = () => { - handleClose(); - dispatch( - OPEN_MODAL({ - title: "تنظیم محدودیت فروش", - content: ( - - ), - size: 400, - }) - ); - }; - - return ( -
    - - - - -
    - -
    -
    -
    - ); -}; - diff --git a/src/features/slaughter-house/components/slaughter-morgue-view/SlaughterMorgueView.js b/src/features/slaughter-house/components/slaughter-morgue-view/SlaughterMorgueView.js index 9ff7c09..3b9bc4f 100644 --- a/src/features/slaughter-house/components/slaughter-morgue-view/SlaughterMorgueView.js +++ b/src/features/slaughter-house/components/slaughter-morgue-view/SlaughterMorgueView.js @@ -6,7 +6,7 @@ import { Tabs, TextField, } from "@mui/material"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; import moment from "moment"; import { DatePicker } from "@mui/x-date-pickers"; import { @@ -18,15 +18,12 @@ import ResponsiveTable from "../../../../components/responsive-table/ResponsiveT import { SPACING } from "../../../../data/spacing"; import { SlaughterColdHouseBars } from "../slaughter-cold-house-bars/SlaughterColdHouseBars"; import { useParams } from "react-router-dom"; -import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; export const SlaughterMorgueView = () => { const dispatch = useDispatch(); const [tableData, setTableData] = useState([]); const [tableDataDashboard, setTableDataDashboard] = useState([]); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); + const { key } = useParams(); const [withDate, setWithDate] = useState(false); @@ -40,13 +37,7 @@ export const SlaughterMorgueView = () => { const getDashboardsData = () => { dispatch( - liveStockGetInventoryData({ - dashboard: true, - cold_house_key: key, - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) + liveStockGetInventoryData({ dashboard: true, cold_house_key: key }) ).then((r) => { setTableData(r.payload.data); }); @@ -55,9 +46,6 @@ export const SlaughterMorgueView = () => { date1: withDate ? selectedDate1 : null, date2: withDate ? selectedDate2 : null, cold_house_key: key, - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", }) ).then((r) => { setTableDataDashboard(r.payload.data); @@ -65,7 +53,7 @@ export const SlaughterMorgueView = () => { }; useEffect(() => { getDashboardsData(); - }, [dispatch, withDate, selectedDate1, selectedDate2, selectedSubUser?.key]); + }, [dispatch, withDate, selectedDate1, selectedDate2]); const [value, setValue] = useState(0); diff --git a/src/features/slaughter-house/components/slaughter-new-request/SlaughterNewRequestForm.js b/src/features/slaughter-house/components/slaughter-new-request/SlaughterNewRequestForm.js index 72b3413..7aa523a 100644 --- a/src/features/slaughter-house/components/slaughter-new-request/SlaughterNewRequestForm.js +++ b/src/features/slaughter-house/components/slaughter-new-request/SlaughterNewRequestForm.js @@ -1,9 +1,13 @@ import { Button, Checkbox, + // Checkbox, FormControl, FormControlLabel, FormHelperText, + // FormControlLabel, + // FormGroup, + // FormHelperText, Grid, InputLabel, ListItem, @@ -16,14 +20,11 @@ import { Typography, } from "@mui/material"; import { DatePicker } from "@mui/x-date-pickers"; -import DoneIcon from "@mui/icons-material/Done"; -import { useEffect, useState, useContext } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { SPACING } from "../../../../data/spacing"; import { useFormik } from "formik"; import moment from "moment"; - -import { SPACING } from "../../../../data/spacing"; import { Yup } from "../../../../lib/yup/yup"; + import { CLOSE_MODAL, DRAWER, @@ -31,108 +32,88 @@ import { LOADING_START, OPEN_MODAL, } from "../../../../lib/redux/slices/appSlice"; -import { AppContext } from "../../../../contexts/AppContext"; -import { DialogAlert } from "../../../../components/dialog-alert/DialogAlert"; -import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom"; -import useUserProfile from "../../../authentication/hooks/useUserProfile"; -import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl"; import { slaughterNewRequest } from "../../services/slaughter-new-request"; import { slaughterGetRequests } from "../../services/salughter-get-requests"; +import { useEffect, useState } from "react"; +import { useDispatch, useSelector } from "react-redux"; +import { useContext } from "react"; +import { AppContext } from "../../../../contexts/AppContext"; +import { DialogAlert } from "../../../../components/dialog-alert/DialogAlert"; +import useUserProfile from "../../../authentication/hooks/useUserProfile"; +import DoneIcon from "@mui/icons-material/Done"; +import { NumberInput } from "../../../../components/number-format-custom/NumberFormatCustom"; import { slaughterGetProfile } from "../../services/slaughter-get-profile"; import { slaughterGetKillerKillhousesService } from "../../services/slaughter-get-killers-killhouses"; +import CustomCard from "../../../../components/custom-card/CustomCard"; +import { format } from "date-fns-jalali"; import { provinceGetPricing } from "../../../province/services/province-get-pricing"; -import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; - -const TIME_RANGES = [ - "12 - 14", - "14 - 16", - "16 - 18", - "18 - 20", - "20 - 22", - "22 - 24", -]; - -const CHICKEN_BREEDS = [ - "آرین", - "راس", - "آربراکرز (آپلاس)", - "کاب", - "هوبارد", - "ترکیبی", - "وارداتی", -]; - -const DEFAULT_INDEX_WEIGHT = 2.7; -const PENALTY_MULTIPLIER = 1000; -const SMS_COST = "5000 تومان"; - -const getInitialValues = (selectedSubUser) => ({ - capacity: "", - recieveTime: "", - selectedKillhouse: selectedSubUser?.key || "", - selectedKillerKillhouse: "", - race: CHICKEN_BREEDS[0], - sellType: { - cash: true, - haveTime: false, - }, - weightType: { - under2AndHalf: false, - over2AndHalf: false, - }, - recieveDate: moment().format("YYYY-MM-DD hh:mm:ss"), - isAccepted: getRoleFromUrl() === "ProvinceOperator", - indexWeight: DEFAULT_INDEX_WEIGHT, -}); - -const getValidationSchema = (selectedSubUser) => - Yup.object({ - capacity: Yup.number() - .required("این فیلد اجباری است!") - .typeError("لطفا عدد وارد کنید!"), - selectedKillhouse: Yup.string().required("این فیلد اجباری است!"), - selectedKillerKillhouse: selectedSubUser?.killer - ? Yup.string().required("این فیلد اجباری است!") - : Yup.string(), - recieveTime: Yup.string() - .required("این فیلد اجباری است!") - .typeError("لطفا وزن را وارد کنید!"), - sellType: Yup.object() - .test("sellType", "نحوه فروش را انتخاب کنید!", (val, context) => { - return ( - context.originalValue && - Object.values(context.originalValue).some((item) => item === true) - ); - }) - .required("این فیلد اجباری است!"), - isAccepted: Yup.boolean() - .test("req", "باید تعهد نامه را بپذیرید!", (val, context) => { - return context.originalValue && context.originalValue === true; - }) - .required("این فیلد اجباری است!"), - }); +import { getRoleFromUrl } from "../../../../utils/getRoleFromUrl"; export const SlaughterNewRequestForm = () => { - const [openNotif, , selectedDate1, , selectedDate2] = useContext(AppContext); + const [openNotif] = useContext(AppContext); const dispatch = useDispatch(); const [, userProfile] = useUserProfile(); const { profile, slaughterGetKillerKillhouses } = useSelector( (state) => state.slaughterSlice ); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); - const [checkedSms, setCheckedSms] = useState(true); - const [checkedBreedAndWeight, setCheckedBreedAndWeight] = useState(false); + const [, , selectedDate1, , selectedDate2] = useContext(AppContext); const formik = useFormik({ - initialValues: getInitialValues(selectedSubUser), - validationSchema: getValidationSchema(selectedSubUser), + initialValues: { + capacity: "", + recieveTime: "", + selectedKillhouse: "", + selectedKillerKillhouse: "", + race: "آرین", + sellType: { + cash: true, + haveTime: false, + }, + weightType: { + under2AndHalf: false, + over2AndHalf: false, + }, + recieveDate: moment(Date()).format("YYYY-MM-DD hh:mm:ss"), + isAccepted: getRoleFromUrl() === "ProvinceOperator" ? true : false, + indexWeight: 2.7, + }, + validationSchema: Yup.object({ + capacity: Yup.number() + .required("این فیلد اجباری است!") + .typeError("لطفا عدد وارد کنید!"), + selectedKillhouse: Yup.string().required("این فیلد اجباری است!"), + selectedKillerKillhouse: profile?.killHouseOperator?.killer + ? Yup.string().required("این فیلد اجباری است!") + : Yup.string(), + recieveTime: Yup.string() + .required("این فیلد اجباری است!") + .typeError("لطفا وزن را وارد کنید!"), + sellType: Yup.object() + .test("sellType", "نحوه فروش را انتخاب کنید!", (val, context) => { + return ( + context.originalValue && + Object.values(context.originalValue).some((item) => item === true) + ); + }) + .required("این فیلد اجباری است!"), + isAccepted: Yup.boolean() + .test("req", "باید تعهد نامه را بپذیرید!", (val, context) => { + return context.originalValue && context.originalValue === true; + }) + .required("این فیلد اجباری است!"), + // weightType: Yup.object() + // .test("weightType", "وزن را انتخاب کنید!", (val, context) => { + // return ( + // context.originalValue && + // Object.values(context.originalValue).some((item) => item === true) + // ); + // }) + // .required("این فیلد اجباری است!"), + }), }); - const penaltyPrice = formik.values.capacity * PENALTY_MULTIPLIER; - + const penaltyPrice = formik.values.capacity * 1000; const dialogContent = ( <> @@ -152,117 +133,80 @@ export const SlaughterNewRequestForm = () => { ); useEffect(() => { - dispatch( - slaughterGetKillerKillhousesService({ - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) - ); + dispatch(slaughterGetKillerKillhousesService()); dispatch(LOADING_START()); - dispatch( - slaughterGetProfile({ - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) - ).then(() => { + dispatch(slaughterGetProfile()).then((r) => { dispatch(LOADING_END()); }); - dispatch(provinceGetPricing()); formik.validateForm(); - }, [selectedSubUser?.key]); + }, []); - const handleSubmit = async () => { - dispatch(LOADING_START()); - const result = await dispatch( - slaughterNewRequest({ - kill_capacity: formik.values.capacity, - recive_time: formik.values.recieveTime, - recive_date: formik.values.recieveDate, - low_weight: formik.values.weightType.under2AndHalf, - high_weight: formik.values.weightType.over2AndHalf, - Index_weight: checkedBreedAndWeight - ? formik.values.indexWeight - : DEFAULT_INDEX_WEIGHT, - chicken_breed: checkedBreedAndWeight - ? formik.values.race - : "تعیین نشده", - cash: formik.values.sellType.cash, - credit: formik.values.sellType.haveTime, - sms_payment: checkedSms, - kill_house_key: formik.values.selectedKillhouse, - killer_kill_house_key: formik.values.selectedKillerKillhouse || null, - role: getRoleFromUrl(), - }) - ); + // const handleSellTypeChange = (event) => { + // formik.setFieldValue("sellType", { + // ...formik.values.sellType, + // [event.target.name]: event.target.checked, + // }); + // }; + // const handleWeightTypeChange = (event) => { + // formik.setFieldValue("weightType", { + // ...formik.values.weightType, + // [event.target.name]: event.target.checked, + // }); + // }; - dispatch(LOADING_END()); + const [checkedSms, setCheckedSms] = useState(true); - if (result.payload.error) { - openNotif({ - vertical: "top", - horizontal: "center", - msg: result.payload.error, - severity: "error", - }); - return; - } - - dispatch( - slaughterGetRequests({ - selectedDate1, - selectedDate2, - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) - ); - dispatch( - OPEN_MODAL({ - title: result.payload.data.result, - content: ( - - ), - }) - ); - openNotif({ - vertical: "top", - horizontal: "center", - msg: "عملیات با موفقیت انجام شد.", - severity: "success", - }); - dispatch(DRAWER({ right: false, bottom: false, content: null })); + const handleChangeCheckedSms = (event) => { + setCheckedSms(event.target.checked); }; - const isProvinceOperator = getRoleFromUrl() === "ProvinceOperator"; + const [checkedBreedAndWeight, setCheckedBreedAndWeight] = useState(false); + + const handleChangeBreedAndWeight = (event) => { + setCheckedBreedAndWeight(event.target.checked); + }; + + const { provincePrices } = useSelector((state) => state.provinceSlice); + + const chickenPrice = provincePrices?.length + ? provincePrices[0]?.liveChickenPrice?.toLocaleString() + " ﷼" + : "نامشخص"; + const chickenPriceDate = provincePrices?.length + ? provincePrices[0]?.createDate + : Date(); + + useEffect(() => { + dispatch(provinceGetPricing()); + }, []); return ( - - - {!selectedSubUser?.key && ( + <> + + + - {selectedSubUser?.killer ? "کشتارکن" : "محل کشتار"} را انتخاب کنید + {profile?.killHouseOperator?.killer ? "کشتارکن" : "محل کشتار"} را + انتخاب کنید - {formik.errors.selectedKillhouse && - formik.touched.selectedKillhouse && ( - - {formik.errors.selectedKillhouse} - - )} + {formik.errors.selectedOption && formik.touched.selectedOption && ( +
    {formik.errors.selectedOption}
    + )}
    - )} - {selectedSubUser?.killer && ( - - محل کشتار را انتخاب کنید - - {formik.errors.selectedKillerKillhouse && - formik.touched.selectedKillerKillhouse && ( - - {formik.errors.selectedKillerKillhouse} - - )} - - )} - - - - - - - - بازه زمانی دریافت مرغ مرغدار - - - - - - } - value={formik.values.recieveDate} - error={ - formik.touched.recieveDate - ? Boolean(formik.errors.recieveDate) - : null - } - onChange={(e) => { - formik.setFieldValue( - "recieveDate", - moment(e).format("YYYY-MM-DD hh:mm:ss") - ); - }} - onBlur={formik.handleBlur} - helperText={ - formik.touched.recieveDate && Boolean(formik.errors.recieveDate) - ? formik.errors.recieveDate - : null - } - /> - -
    - - setCheckedBreedAndWeight(e.target.checked)} - color="primary" - /> - } - label="تعیین نژاد/وزن مرغ" - /> - - {checkedBreedAndWeight && ( - - - نژاد مرغ - - - {formik.touched.race && Boolean(formik.errors.race) - ? formik.errors.race - : null} - - + کشتارگاه را انتخاب کنید + + {formik.errors.selectedKillerKillhouse && + formik.touched.selectedKillerKillhouse && ( +
    {formik.errors.selectedKillerKillhouse}
    + )} + + )} + + + + بازه زمانی دریافت مرغ مرغدار + + + + + + } + value={formik.values.recieveDate} + error={ + formik.touched.recieveDate + ? Boolean(formik.errors.recieveDate) + : null + } + onChange={(e) => { + formik.setFieldValue( + "recieveDate", + moment(e).format("YYYY-MM-DD hh:mm:ss") + ); + }} + onBlur={formik.handleBlur} + helperText={ + formik.touched.recieveDate && Boolean(formik.errors.recieveDate) + ? formik.errors.recieveDate : null } />
    - )} - - - {!isProvinceOperator && ( - - - - - } - btnTitle="با تعهد نامه موافق هستم!" - isAccepted={formik.values.isAccepted} - /> - )} - - - setCheckedSms(e.target.checked)} + + } + label="تعیین نژاد/وزن مرغ" + /> + {checkedBreedAndWeight && ( + + + نژاد مرغ + + + {formik.touched.race && Boolean(formik.errors.race) + ? formik.errors.race + : null} + + + + - } - label={ - - - مایل به دریافت پیامک اطلاع رسانی هستم! - - - } - /> + + + )} + {/* + + نحوه خرید + + + + } + label="نقدی" + /> + + } + label="زمان دار (تا یک ماه)" + /> + + + {formik.touched.sellType && Boolean(formik.errors.sellType) + ? formik.errors.sellType + : null} + + */} + {/* + + وزن پیشنهادی + + + + } + label="2 تا 2.5 کیلوگرم" + /> + + } + label="2.5 کیلوگرم به بالا" + /> + + */} + + {getRoleFromUrl() !== "ProvinceOperator" && ( + + + + + } + btnTitle={"با تعهد نامه موافق هستم!"} + isAccepted={formik.values.isAccepted} + /> + )} + + + + } + label={ + + + مایل به دریافت پیامک اطلاع رسانی هستم! + + + } + /> + + + + + ), + }) + ); + openNotif({ + vertical: "top", + horizontal: "center", + msg: "عملیات با موفقیت انجام شد.", + severity: "success", + }); + dispatch( + DRAWER({ right: false, bottom: false, content: null }) + ); + } + }); + }} + > + ثبت درخواست +
    - - - - -
    + ); }; diff --git a/src/features/slaughter-house/components/slaughter-orders/SlaughterOrders.js b/src/features/slaughter-house/components/slaughter-orders/SlaughterOrders.js index a4b0030..aaa0bb0 100644 --- a/src/features/slaughter-house/components/slaughter-orders/SlaughterOrders.js +++ b/src/features/slaughter-house/components/slaughter-orders/SlaughterOrders.js @@ -9,7 +9,7 @@ import { } from "@mui/material"; import { DatePicker } from "@mui/x-date-pickers"; import moment from "moment"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; import axios from "axios"; import { LOADING_END, @@ -22,7 +22,6 @@ import { Grid } from "../../../../components/grid/Grid"; import VisibilityIcon from "@mui/icons-material/Visibility"; import { formatJustDate } from "../../../../utils/formatTime"; import { RiSearchLine } from "react-icons/ri"; -import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; export const SlaughterOrders = () => { const [selectedDate1, setSelectedDate1] = useState( @@ -32,9 +31,7 @@ export const SlaughterOrders = () => { moment(new Date()).format("YYYY-MM-DD") ); const dispatch = useDispatch(); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); + const handleTextChange = (event) => { setTextValue(event.target.value); }; @@ -48,13 +45,10 @@ export const SlaughterOrders = () => { const fetchApiData = useCallback( async (page) => { + let response; dispatch(LOADING_START()); - const response = await axios.get( + response = await axios.get( `orders_for_kill_house/?search=filter&value=${textValue}&role=${getRoleFromUrl()}${ - checkPathStartsWith("slaughter") - ? `&role_key=${selectedSubUser?.key}` - : "" - }${ withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : `` }&page=${page}&page_size=${perPage}` ); @@ -62,18 +56,7 @@ export const SlaughterOrders = () => { setData(response.data.results); setTotalRows(response.data.count); }, - [ - textValue, - withDate, - selectedDate1, - selectedDate2, - perPage, - setData, - setTotalRows, - page, - dispatch, - selectedSubUser?.key, - ] + [textValue, withDate, selectedDate1, selectedDate2, perPage, dispatch] ); const handlePageChange = (page) => { @@ -162,7 +145,7 @@ export const SlaughterOrders = () => { useEffect(() => { fetchApiData(1); - }, [selectedSubUser?.key]); + }, [fetchApiData]); const handleSubmit = async (event) => { event.preventDefault(); @@ -170,11 +153,7 @@ export const SlaughterOrders = () => { try { const response = await axios.get( - `orders_for_kill_house/?role=${getRoleFromUrl()}${ - checkPathStartsWith("slaughter") - ? `&role_key=${selectedSubUser?.key}` - : "" - }&search=filter&value=${textValue}${ + `orders_for_kill_house/?role=${getRoleFromUrl()}&search=filter&value=${textValue}${ withDate ? `&date1=${selectedDate1}&date2=${selectedDate2}` : `` }&page=${1}&page_size=${perPage}` ); diff --git a/src/features/slaughter-house/components/slaughter-psp-devices/SlaughterPspDevices.js b/src/features/slaughter-house/components/slaughter-psp-devices/SlaughterPspDevices.js deleted file mode 100644 index 3907673..0000000 --- a/src/features/slaughter-house/components/slaughter-psp-devices/SlaughterPspDevices.js +++ /dev/null @@ -1,5 +0,0 @@ -const SlaughterPspDevices = () => { - return
    SlaughterPspDevices
    ; -}; - -export default SlaughterPspDevices; diff --git a/src/features/slaughter-house/components/slaughter-requests/SlaughterRequests.js b/src/features/slaughter-house/components/slaughter-requests/SlaughterRequests.js index 1c8cbc1..3349611 100644 --- a/src/features/slaughter-house/components/slaughter-requests/SlaughterRequests.js +++ b/src/features/slaughter-house/components/slaughter-requests/SlaughterRequests.js @@ -18,7 +18,6 @@ import { formatJustDate } from "../../../../utils/formatTime"; import { DatePicker } from "@mui/x-date-pickers"; import moment from "moment/moment"; import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable"; -import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; // import { slaughterPayService } from "../../services/salughter-pay"; export const SlaughterRequests = () => { @@ -29,9 +28,6 @@ export const SlaughterRequests = () => { const [openNotif] = useContext(AppContext); const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] = useContext(AppContext); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); useEffect(() => { const currentDate = moment(new Date()).format("YYYY-MM-DD"); @@ -40,16 +36,8 @@ export const SlaughterRequests = () => { }, []); useEffect(() => { - dispatch( - slaughterGetRequests({ - selectedDate1, - selectedDate2, - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) - ); - }, [selectedDate1, selectedDate2, selectedSubUser?.key]); + dispatch(slaughterGetRequests({ selectedDate1, selectedDate2 })); + }, [selectedDate1, selectedDate2]); useEffect(() => { const d = slaughterRequests?.map((item, i) => { @@ -116,11 +104,8 @@ export const SlaughterRequests = () => { slaughterGetRequests({ selectedDate1, selectedDate2, - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", }) - ).then(() => { + ).then((r) => { openNotif({ vertical: "top", horizontal: "center", diff --git a/src/features/slaughter-house/components/slaughter-segmentation/SlaughterSegmentation.js b/src/features/slaughter-house/components/slaughter-segmentation/SlaughterSegmentation.js index 4d86c11..70a9855 100644 --- a/src/features/slaughter-house/components/slaughter-segmentation/SlaughterSegmentation.js +++ b/src/features/slaughter-house/components/slaughter-segmentation/SlaughterSegmentation.js @@ -1,5 +1,5 @@ import { useContext, useEffect, useState } from "react"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; import moment from "moment"; import { Button, TextField } from "@mui/material"; import { DatePicker } from "@mui/x-date-pickers"; @@ -20,7 +20,6 @@ import { Grid } from "../../../../components/grid/Grid"; import { SPACING } from "../../../../data/spacing"; import ResponsiveTable from "../../../../components/responsive-table/ResponsiveTable"; import { StewardSegmentSubmitOperation } from "../../../guild/components/StewardSegmentSubmitOperation"; -import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; export const SlaughterSegmentation = () => { const [data, setData] = useState([]); @@ -31,9 +30,6 @@ export const SlaughterSegmentation = () => { const [textValue, setTextValue] = useState(""); const [page, setPage] = useState(1); const [dashboardData, setDashboardData] = useState([]); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] = useContext(AppContext); const dispatch = useDispatch(); @@ -47,7 +43,6 @@ export const SlaughterSegmentation = () => { date1: selectedDate1, date2: selectedDate2, role: getRoleFromUrl(), - role_key: checkPathStartsWith("slaughter") ? selectedSubUser?.key : "", }) ).then((r) => { setDashboardData(r.payload.data); @@ -63,11 +58,7 @@ export const SlaughterSegmentation = () => { const fetchApiData = async (page) => { dispatch(LOADING_START()); const response = await axios.get( - `app-segmentation/?search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${perPage}&role=${getRoleFromUrl()}${ - checkPathStartsWith("slaughter") - ? `&role_key=${selectedSubUser?.key}` - : "" - }` + `app-segmentation/?search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${perPage}&role=${getRoleFromUrl()}` ); getDashboardData(); @@ -95,13 +86,7 @@ export const SlaughterSegmentation = () => { useEffect(() => { fetchApiData(1); - dispatch( - stewardGetOutSellService({ - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) - ).then((r) => { + dispatch(stewardGetOutSellService()).then((r) => { setProducts(r.payload.data); }); }, []); @@ -148,18 +133,14 @@ export const SlaughterSegmentation = () => { useEffect(() => { fetchApiData(1); - }, [selectedDate1, selectedDate2, perPage, selectedSubUser?.key]); + }, [selectedDate1, selectedDate2, perPage]); const handleSubmit = async (event) => { event.preventDefault(); dispatch(LOADING_START()); try { const response = await axios.get( - `app-segmentation/?search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&role=${getRoleFromUrl()}${ - checkPathStartsWith("slaughter") - ? `&role_key=${selectedSubUser?.key}` - : "" - }` + `app-segmentation/?search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&role=${getRoleFromUrl()}` ); setData(response.data.results); setTotalRows(response.data.count); @@ -179,7 +160,7 @@ export const SlaughterSegmentation = () => { gap={SPACING.SMALL} justifyContent="flex-start" > - + { const province = useProvinceName(); - const userKey = useSelector((state) => state.userSlice.userProfile.key); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); + // const [killHouseTable, setKillHouseTable] = useState(); const { slaughterProducts } = useSelector((state) => state.slaughterSlice); @@ -86,11 +81,7 @@ export const ProvinceSellCarcassInProvince = ({ updateTable, priceInfo }) => { const fetchApiData = async (page) => { dispatch(LOADING_START()); const response = await axios.get( - `steward-allocation/?search=filter&value=${textValue}&role=${getRoleFromUrl()}${ - checkPathStartsWith("slaughter") - ? `&role_key=${selectedSubUser?.key}` - : "" - }&date1=${selectedDate1}&date2=${selectedDate2}&page=${ + `steward-allocation/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&date1=${selectedDate1}&date2=${selectedDate2}&page=${ page ? page : 1 }&page_size=${perPage}` ); @@ -111,7 +102,7 @@ export const ProvinceSellCarcassInProvince = ({ updateTable, priceInfo }) => { type = `${item?.toKillHouse?.name} - ${item?.toKillHouse?.killHouseOperator?.user?.fullname} (${item?.toKillHouse?.killHouseOperator?.user?.mobile})`; break; case "killhouse_steward": - type = `${item?.toStewards?.name} - ${item?.toStewards?.user?.fullname} (${item?.toStewards?.user?.mobile})`; + type = `${item?.toSteward?.guildsName} - ${item?.toSteward?.user?.fullname} (${item?.toSteward?.user?.mobile})`; break; case "killhouse_guild": type = `${item?.toGuilds?.guildsName} - ${item?.toGuilds?.user?.fullname} (${item?.toGuilds?.user?.mobile})`; @@ -212,7 +203,7 @@ export const ProvinceSellCarcassInProvince = ({ updateTable, priceInfo }) => { useEffect(() => { fetchApiData(1); - }, [dispatch, selectedDate1, selectedDate2, perPage, selectedSubUser?.key]); + }, [dispatch, selectedDate1, selectedDate2, perPage]); const PendingOperationsPopover = ({ item, fetchApiData, updateTable }) => { const [anchorEl, setAnchorEl] = useState(null); @@ -244,13 +235,7 @@ export const ProvinceSellCarcassInProvince = ({ updateTable, priceInfo }) => { }) ).then(() => { dispatch(CLOSE_MODAL()); - dispatch( - fetchSlaughterBroadcastAndProducts({ - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key - : "", - }) - ); + dispatch(fetchSlaughterBroadcastAndProducts()); fetchApiData(1); }); }} @@ -384,11 +369,7 @@ export const ProvinceSellCarcassInProvince = ({ updateTable, priceInfo }) => { try { const response = await axios.get( - `steward-allocation/?role=${getRoleFromUrl()}${ - checkPathStartsWith("slaughter") - ? `&role_key=${selectedSubUser?.key}` - : "" - }&search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${1}&page_size=${perPage}` + `steward-allocation/?role=${getRoleFromUrl()}&search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${1}&page_size=${perPage}` ); setData(response.data.results); setTotalRows(response.data.count); @@ -627,30 +608,6 @@ export const ProvinceSellCarcassInProvince = ({ updateTable, priceInfo }) => { > تایید نهایی (یکجا) - - - { const handleTextChange = (event) => { @@ -37,18 +36,11 @@ export const SlaughterSellCarcassOutProvinceBuyers = () => { const [page, setPage] = useState(1); const [tableData, setTableData] = useState([]); const [personType, setPersonType] = useState("real"); // real | legal - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); const fetchApiData = async (page) => { dispatch(LOADING_START()); const response = await axios.get( - `out-province-carcasses-buyer/?search=filter&value=${textValue}&role=${getRoleFromUrl()}${ - checkPathStartsWith("slaughter") - ? `&role_key=${selectedSubUser?.key}` - : "" - }&page=${page}&page_size=${perPage}&state=buyer-list&type=${personType}` + `out-province-carcasses-buyer/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&page=${page}&page_size=${perPage}&state=buyer-list&type=${personType}` ); dispatch(LOADING_END()); setData(response.data.results); @@ -136,7 +128,7 @@ export const SlaughterSellCarcassOutProvinceBuyers = () => { useEffect(() => { fetchApiData(1); - }, [dispatch, perPage, personType, selectedSubUser?.key]); + }, [dispatch, perPage, personType]); const handleSubmit = async (event) => { event.preventDefault(); @@ -144,11 +136,7 @@ export const SlaughterSellCarcassOutProvinceBuyers = () => { try { const response = await axios.get( - `out-province-carcasses-buyer/?role=${getRoleFromUrl()}${ - checkPathStartsWith("slaughter") - ? `&role_key=${selectedSubUser?.key}` - : "" - }&search=filter&value=${textValue}&page=${1}&page_size=${perPage}&state=buyer-list&type=${personType}` + `out-province-carcasses-buyer/?role=${getRoleFromUrl()}&search=filter&value=${textValue}&page=${1}&page_size=${perPage}&state=buyer-list&type=${personType}` ); setData(response.data.results); setTotalRows(response.data.count); diff --git a/src/features/slaughter-house/components/slaughter-sell-carcass-out-province-sell/SlaughterSellCarcassOutProvinceSell.js b/src/features/slaughter-house/components/slaughter-sell-carcass-out-province-sell/SlaughterSellCarcassOutProvinceSell.js index 6db53b5..9be85a8 100644 --- a/src/features/slaughter-house/components/slaughter-sell-carcass-out-province-sell/SlaughterSellCarcassOutProvinceSell.js +++ b/src/features/slaughter-house/components/slaughter-sell-carcass-out-province-sell/SlaughterSellCarcassOutProvinceSell.js @@ -21,7 +21,6 @@ import { CheckCleanceCode } from "../../../../components/check-clearance-code/Ch import { formatJustDate, formatTime } from "../../../../utils/formatTime"; import { SlaughterOutProvinceRegistrationCodeInput } from "../slaughter-out-province-registration-code-input/SlaughterOutProvinceRegistrationCodeInput"; import { SlaughterOutProvinceSalesOperations } from "../slaughter-out-province-sales-operations/SlaughterOutProvinceSalesOperations"; -import { checkPathStartsWith } from "../../../../utils/checkPathStartsWith"; export const SlaughterSellCarcassOutProvinceSell = () => { const [, , selectedDate1, setSelectedDate1, selectedDate2, setSelectedDate2] = @@ -32,9 +31,6 @@ export const SlaughterSellCarcassOutProvinceSell = () => { setSelectedDate1(currentDate); setSelectedDate2(currentDate); }, []); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); const handleTextChange = (event) => { setTextValue(event.target.value); @@ -50,11 +46,7 @@ export const SlaughterSellCarcassOutProvinceSell = () => { const fetchApiData = async (page) => { dispatch(LOADING_START()); const response = await axios.get( - `kill_house_free_sale_bar/?search=filter&value=${textValue}&role=${getRoleFromUrl()}${ - checkPathStartsWith("slaughter") - ? `&role_key=${selectedSubUser?.key}` - : "" - }&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${perPage}&type=dashboard` + `kill_house_free_sale_bar/?search=filter&value=${textValue}&role=${getRoleFromUrl()}&date1=${selectedDate1}&date2=${selectedDate2}&page=${page}&page_size=${perPage}&type=dashboard` ); dispatch(LOADING_END()); setData(response.data.results); @@ -142,7 +134,7 @@ export const SlaughterSellCarcassOutProvinceSell = () => { useEffect(() => { fetchApiData(1); - }, [dispatch, selectedDate1, selectedDate2, perPage, selectedSubUser?.key]); + }, [dispatch, selectedDate1, selectedDate2, perPage]); const handleSubmit = async (event) => { event.preventDefault(); @@ -150,11 +142,7 @@ export const SlaughterSellCarcassOutProvinceSell = () => { try { const response = await axios.get( - `kill_house_free_sale_bar/?role=${getRoleFromUrl()}${ - checkPathStartsWith("slaughter") - ? `&role_key=${selectedSubUser?.key}` - : "" - }&search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${1}&page_size=${perPage}&type=dashboard` + `kill_house_free_sale_bar/?role=${getRoleFromUrl()}&search=filter&value=${textValue}&date1=${selectedDate1}&date2=${selectedDate2}&page=${1}&page_size=${perPage}&type=dashboard` ); setData(response.data.results); setTotalRows(response.data.count); @@ -166,9 +154,6 @@ export const SlaughterSellCarcassOutProvinceSell = () => { slaughterSellCarcassOutProvinceGetDashboard({ selectedDate1, selectedDate2, - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", }) ).then((r) => { setDashboardData(r.payload.data); @@ -182,14 +167,11 @@ export const SlaughterSellCarcassOutProvinceSell = () => { slaughterSellCarcassOutProvinceGetDashboard({ selectedDate1, selectedDate2, - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", }) ).then((r) => { setDashboardData(r.payload.data); }); - }, [selectedDate1, selectedDate2, selectedSubUser?.key]); + }, [selectedDate1, selectedDate2]); return ( @@ -251,11 +233,7 @@ export const SlaughterSellCarcassOutProvinceSell = () => {
    - -
    - ), - }) - ); - }; - - const content = ( - - - - - - - ); - - if (!open) { - return ( - - {content} - - ); - } - - return content; -}); - -LogoutButton.displayName = "LogoutButton"; diff --git a/src/layouts/sidebar/components/MenuItem.js b/src/layouts/sidebar/components/MenuItem.js deleted file mode 100644 index 15fa74d..0000000 --- a/src/layouts/sidebar/components/MenuItem.js +++ /dev/null @@ -1,67 +0,0 @@ -import React from "react"; -import { - ListItemButton, - ListItemIcon, - ListItemText, - Tooltip, -} from "@mui/material"; -import { useLocation, useNavigate } from "react-router-dom"; -import { useDispatch } from "react-redux"; -import { DRAWER } from "../../../lib/redux/slices/appSlice"; - -export const MenuItem = React.memo( - ({ - icon, - text, - route, - tooltip, - open, - disabled = false, - onClick, - onClose, - }) => { - const navigate = useNavigate(); - const { pathname } = useLocation(); - const dispatch = useDispatch(); - const isSelected = pathname.includes(route); - - const handleClick = () => { - if (disabled) return; - - dispatch(DRAWER({ right: false, bottom: false, content: null })); - - if (onClick) { - onClick(); - } else if (route) { - navigate(route); - } - - if (onClose) { - onClose(); - } - }; - - const content = ( - - {icon || null} - - - ); - - if (tooltip && !open) { - return ( - - {content} - - ); - } - - return content; - } -); - -MenuItem.displayName = "MenuItem"; diff --git a/src/layouts/sidebar/components/RoleAccordion.js b/src/layouts/sidebar/components/RoleAccordion.js deleted file mode 100644 index 24e596b..0000000 --- a/src/layouts/sidebar/components/RoleAccordion.js +++ /dev/null @@ -1,103 +0,0 @@ -import React from "react"; -import { Accordion, AccordionSummary, Typography, Grid } from "@mui/material"; -import ExpandMoreIcon from "@mui/icons-material/ExpandMore"; -import { motion } from "framer-motion"; -import { getFaUserRole } from "../../../utils/getFaUserRole"; -import { getIconUserRole } from "../../../utils/getRoleIcon"; - -export const RoleAccordion = React.memo( - ({ role, open, isExpanded, onToggle, children }) => { - return ( - - - } - style={{ - backgroundColor: isExpanded ? "#0fb9b1" : "#dfe6e9", - boxShadow: isExpanded ? "inset 0 0 2px rgba(0,0,0,0.75)" : "none", - }} - > - {open ? ( - - - - - {getIconUserRole(role)} - - - - - {getFaUserRole(role)} - - - - - ) : ( - - {getIconUserRole(role)} - - )} - - - {children} - - - ); - } -); - -RoleAccordion.displayName = "RoleAccordion"; diff --git a/src/layouts/sidebar/components/RoleMenuRenderer.js b/src/layouts/sidebar/components/RoleMenuRenderer.js deleted file mode 100644 index 77634bf..0000000 --- a/src/layouts/sidebar/components/RoleMenuRenderer.js +++ /dev/null @@ -1,64 +0,0 @@ -import React from "react"; -import { CollapsibleMenuSection } from "./CollapsibleMenuSection"; -import { MenuItem } from "./MenuItem"; -import { useDispatch } from "react-redux"; -import { OPEN_MODAL } from "../../../lib/redux/slices/appSlice"; - -export const RoleMenuRenderer = React.memo( - ({ menuConfig, open, openSub, onToggleSub, onClose }) => { - const dispatch = useDispatch(); - - const handleModalItem = (item) => { - if (item.isModal && item.modalContent) { - const ModalContent = item.modalContent; - dispatch( - OPEN_MODAL({ - title: item.modalTitle || "اطلاعات", - content: React.isValidElement(ModalContent) ? ( - ModalContent - ) : ( - - ), - }) - ); - } - }; - - return ( - <> - {menuConfig.collapsibleSections?.map((section) => ( - onToggleSub(section.key)} - items={section.items} - onClose={onClose} - /> - ))} - - {menuConfig.regularItems?.map((item, index) => { - if (item.isModal) { - return ( - handleModalItem(item)} - onClose={onClose} - /> - ); - } - return ( - - ); - })} - - ); - } -); - -RoleMenuRenderer.displayName = "RoleMenuRenderer"; diff --git a/src/layouts/sidebar/components/SidebarHeader.js b/src/layouts/sidebar/components/SidebarHeader.js deleted file mode 100644 index ad19acd..0000000 --- a/src/layouts/sidebar/components/SidebarHeader.js +++ /dev/null @@ -1,137 +0,0 @@ -import React from "react"; -import { Avatar, IconButton, Tooltip, Typography, Grid } from "@mui/material"; -import AccountBoxIcon from "@mui/icons-material/AccountBox"; -import EmailIcon from "@mui/icons-material/Email"; -import LightbulbIcon from "@mui/icons-material/Lightbulb"; -import PermPhoneMsgIcon from "@mui/icons-material/PermPhoneMsg"; -import { useNavigate } from "react-router-dom"; -import { useDispatch } from "react-redux"; -import { DRAWER } from "../../../lib/redux/slices/appSlice"; -import { - ROUTE_GENERAL_USER_PROFILE, - ROUTE_GENERAL_MESSAGES, - ROUTE_GENERAL_TRAINING, - ROUTE_GENERAL_SUPPORT, -} from "../../../routes/routes"; -import PersianDate from "persian-date"; -import { SPACING } from "../../../data/spacing"; - -const stringAvatar = (name) => { - if (name) { - const nameArr = name - ?.split(" ") - ?.filter((item) => item) - ?.map((item) => item[0]); - return { - sx: { - bgcolor: "#353b48", - }, - children: nameArr[0], - }; - } - return {}; -}; - -export const SidebarHeader = React.memo(({ userProfile, open, onClose }) => { - const navigate = useNavigate(); - const dispatch = useDispatch(); - - const handleNavigation = (route) => { - dispatch(DRAWER({ right: false, bottom: false, content: null })); - navigate(route); - if (onClose) onClose(); - }; - - return ( - <> - - - {userProfile?.image && - userProfile?.image !== "empty" && - userProfile?.fullname ? ( - - ) : ( - - )} - {open && ( - - {userProfile?.fullname} - - موبایل: {userProfile?.mobile} - - - )} - - - - - - handleNavigation(ROUTE_GENERAL_USER_PROFILE)} - > - - - - - handleNavigation(ROUTE_GENERAL_MESSAGES)} - > - - - - - handleNavigation(ROUTE_GENERAL_TRAINING)} - > - - - - - handleNavigation(ROUTE_GENERAL_SUPPORT)} - > - - - - - - {open && ( - - - {new PersianDate().toLocale("fa").format("dddd DD MMMM")} - - - )} - - ); -}); - -SidebarHeader.displayName = "SidebarHeader"; diff --git a/src/layouts/sidebar/constants/menuItemHelpers.js b/src/layouts/sidebar/constants/menuItemHelpers.js deleted file mode 100644 index 00706d5..0000000 --- a/src/layouts/sidebar/constants/menuItemHelpers.js +++ /dev/null @@ -1,140 +0,0 @@ -import React from "react"; -import { - FeaturedPlayListIcon, - AddShoppingCartIcon, - AssignmentIcon, - LocalOfferIcon, - ShoppingCartIcon, - FlightIcon, - BusinessIcon, - LanIcon, - AssignmentTurnedInIcon, - AutoFixHighIcon, - DraftsIcon, - CompareArrowsIcon, - EggIcon, - AttachMoneyIcon, - PieChart, - NoteAltIcon, - SupportIcon, - SettingsSuggestIcon, - SettingsInputCompositeIcon, - AccountTreeIcon, - LocalShippingIcon, - CorporateFareIcon, - PersonAddAltIcon, - DirectionsCarIcon, - FactoryIcon, - InventoryIcon, - MailOutlineIcon, - CoPresentIcon, - WarehouseIcon, - SummarizeIcon, - EqualizerIcon, - ReportIcon, - PaymentIcon, - TaskAltIcon, - NewReleasesIcon, - ArchiveIcon, - WarningIcon, - FolderOpenIcon, - MeetingRoomIcon, - AttachFileIcon, - AssignmentLateIcon, - PendingActionsIcon, - MonetizationOnIcon, - AccountBalanceWalletIcon, - SwapHorizontalCircleIcon, - ReceiptIcon, - PaidIcon, - FactCheckIcon, - LoopIcon, - CreditScoreIcon, - ToggleOnIcon, - DocumentScanner, - AcUnitIcon, - KitchenIcon, - ReceiptLongIcon, -} from "@mui/icons-material"; -import { - Folder, - AttachMoney, - FileCopy, - Archive, - Warning, - AddBox, -} from "@mui/icons-material"; -import { FaFile } from "react-icons/fa"; - -// Helper to create menu items with consistent structure -export const createMenuItem = (route, icon, text) => ({ - route, - icon: React.createElement(icon), - text, -}); - -// Common icons as components -export const Icons = { - FeaturedPlayList: FeaturedPlayListIcon, - AddShoppingCart: AddShoppingCartIcon, - Assignment: AssignmentIcon, - LocalOffer: LocalOfferIcon, - ShoppingCart: ShoppingCartIcon, - Flight: FlightIcon, - Business: BusinessIcon, - Lan: LanIcon, - AssignmentTurnedIn: AssignmentTurnedInIcon, - AutoFixHigh: AutoFixHighIcon, - Drafts: DraftsIcon, - CompareArrows: CompareArrowsIcon, - Egg: EggIcon, - AttachMoney: AttachMoneyIcon, - PieChart, - NoteAlt: NoteAltIcon, - Support: SupportIcon, - SettingsSuggest: SettingsSuggestIcon, - SettingsInputComposite: SettingsInputCompositeIcon, - AccountTree: AccountTreeIcon, - LocalShipping: LocalShippingIcon, - CorporateFare: CorporateFareIcon, - PersonAddAlt: PersonAddAltIcon, - DirectionsCar: DirectionsCarIcon, - Factory: FactoryIcon, - Inventory: InventoryIcon, - MailOutline: MailOutlineIcon, - CoPresent: CoPresentIcon, - Warehouse: WarehouseIcon, - Summarize: SummarizeIcon, - Equalizer: EqualizerIcon, - Report: ReportIcon, - Payment: PaymentIcon, - TaskAlt: TaskAltIcon, - NewReleases: NewReleasesIcon, - Archive: ArchiveIcon, - Warning: WarningIcon, - FolderOpen: FolderOpenIcon, - MeetingRoom: MeetingRoomIcon, - AttachFile: AttachFileIcon, - AssignmentLate: AssignmentLateIcon, - PendingActions: PendingActionsIcon, - MonetizationOn: MonetizationOnIcon, - AccountBalanceWallet: AccountBalanceWalletIcon, - SwapHorizontalCircle: SwapHorizontalCircleIcon, - Receipt: ReceiptIcon, - Paid: PaidIcon, - FactCheck: FactCheckIcon, - Loop: LoopIcon, - CreditScore: CreditScoreIcon, - ToggleOn: ToggleOnIcon, - DocumentScanner, - AcUnit: AcUnitIcon, - Kitchen: KitchenIcon, - ReceiptLong: ReceiptLongIcon, - Folder, - AttachMoneyIcon: AttachMoney, - FileCopy, - ArchiveIcon: Archive, - WarningIcon: Warning, - AddBox, - FaFile, -}; diff --git a/src/layouts/sidebar/constants/roleMenuConfigs.js b/src/layouts/sidebar/constants/roleMenuConfigs.js deleted file mode 100644 index dc330e6..0000000 --- a/src/layouts/sidebar/constants/roleMenuConfigs.js +++ /dev/null @@ -1,620 +0,0 @@ -import React from "react"; -import { Icons, createMenuItem } from "./menuItemHelpers"; -import * as ROUTES from "../../../routes/routes"; -import PorvinceGetReportOperations from "../../../features/province/components/province-get-report-operations/PorvinceGetReportOperations"; - -// Province Menu Items -export const getProvinceMenuItems = () => ({ - collapsibleSections: [ - { - key: "province", - icon: Icons.SettingsSuggest, - text: "پنل مدیریت", - items: [ - createMenuItem( - ROUTES.ROUTE_PROVINCE_CITY_NEW_REQUESTS, - Icons.FeaturedPlayList, - "مدیریت درخواست ها" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_STATEMENTـOFـNEED_REQUESTS, - Icons.AddShoppingCart, - "اعلام نیاز خریداران" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_ALLOCATION_REQUESTS, - Icons.Assignment, - "تخصیصات" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_PAYING_FEES_REQUESTS, - Icons.LocalOffer, - "تعرفه ها" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCEـFREE_BUY, - Icons.ShoppingCart, - "خرید مستقیم" - ), - createMenuItem(ROUTES.ROUTE_PROVINCEـEXPORT, Icons.Flight, "صادرات"), - createMenuItem( - ROUTES.ROUTE_PROVINCE_FREE_SALES_REQUESTS, - Icons.Business, - "فروش به خارج استان" - ), - createMenuItem(ROUTES.ROUTE_PROVINCE_CHAINS, Icons.Lan, "زنجیره ها"), - createMenuItem( - ROUTES.ROUTE_PROVINCE_ALLOCATED_REQUESTS, - Icons.AssignmentTurnedIn, - "مدیریت تخصیصات" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_AUTO_ALLOCATION_REQUESTS, - Icons.AutoFixHigh, - "تخصیصات خودکار" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_ISSUANCE_OF_LETTER, - Icons.Drafts, - "صدور نامه" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_TRANSACTIONS, - Icons.CompareArrows, - "تراکنش ها" - ), - ], - }, - ], - regularItems: [ - { - icon: React.createElement(Icons.Summarize), - text: "گزارش روزانه", - isModal: true, - modalContent: PorvinceGetReportOperations, - modalTitle: "اطلاعات گزارش", - }, - createMenuItem( - ROUTES.ROUTE_PROVINCEـVISOR_STATICS, - Icons.Equalizer, - "تحلیل داده" - ), - createMenuItem(ROUTES.ROUTE_PROVINCE_HATCHING, Icons.Egg, "مدیریت کشتار"), - createMenuItem( - ROUTES.ROUTE_PROVINCEـHATCHINGS, - Icons.SettingsInputComposite, - "مدیریت جوجه ریزی" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_PRICING3, - Icons.AttachMoney, - "قیمت روز" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_STATICS, - Icons.PieChart, - "آمار و اطلاعات" - ), - createMenuItem(ROUTES.ROUTE_PROVINCE_REPORT, Icons.FaFile, "گزارشات"), - createMenuItem( - ROUTES.ROUTE_PROVINCE_ROUTE_FILES_STATE, - Icons.AccountTree, - "پرونده های کشتار" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_ROUTE_ALLOCATIONS, - Icons.LocalShipping, - "مدیریت بارها" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_DISPENSERS, - Icons.CoPresent, - "مدیریت توزیع" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_ROUTE_MANAGE_GUILDS, - Icons.CorporateFare, - "مدیریت اصناف" - ), - createMenuItem(ROUTES.ROUTE_PROVINCE_CARS, Icons.DirectionsCar, "خودروها"), - createMenuItem(ROUTES.ROUTE_PROVINCE_USERS, Icons.PersonAddAlt, "کاربران"), - createMenuItem( - ROUTES.ROUTE_PROVINCE_GUILD_TRANSACTIONS, - Icons.ReceiptLong, - "مدیریت تراکنش ها" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_POULTRIES, - Icons.PersonAddAlt, - "مدیریت فارم ها" - ), - createMenuItem(ROUTES.ROUTE_PROVINCE_SLAUGHTERS, Icons.Factory, "خریداران"), - createMenuItem(ROUTES.ROUTE_PROVINCE_PRODUCTS, Icons.Inventory, "محصولات"), - createMenuItem( - ROUTES.ROUTE_PROVINCEـBROADCAST_MANAGEMENT, - Icons.PersonAddAlt, - "مدیریت پخش" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_ASSIGN_VET_FARM, - Icons.PersonAddAlt, - "دامپزشکان" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_ROUTE_SMS, - Icons.MailOutline, - "پنل اطلاع رسانی" - ), - createMenuItem(ROUTES.ROUTE_PROVINCE_TICKET, Icons.Support, "تیکت ها"), - ], -}); - -// City Menu Items -export const getCityMenuItems = () => ({ - collapsibleSections: [ - { - key: "city", - icon: Icons.SettingsSuggest, - text: "پنل مدیریت", - items: [ - createMenuItem( - ROUTES.ROUTE_CITY_NEW_REQUESTS, - Icons.NewReleases, - "درخواست های جدید" - ), - createMenuItem( - ROUTES.ROUTE_CITY_ACTIVE_REQUESTS, - Icons.TaskAlt, - "درخواست های فعال" - ), - createMenuItem( - ROUTES.ROUTE_CITY_AWAITING_PAYMENT_REQUESTS, - Icons.Payment, - "در انتظار پرداخت" - ), - createMenuItem( - ROUTES.ROUTE_CITY_AWAITING_INSPECTION_REQUESTS, - Icons.Report, - "در انتظار بازرسی" - ), - createMenuItem( - ROUTES.ROUTE_CITY_REJECTED_REQUESTS, - Icons.Report, - "درخواست های رد شده" - ), - createMenuItem( - ROUTES.ROUTE_CITY_FREE_SALES_REQUESTS, - Icons.FolderOpen, - "فروش خارج از استان" - ), - createMenuItem( - ROUTES.ROUTE_CITY_ARCHIVED_REQUESTS, - Icons.Archive, - "بایگانی" - ), - ], - }, - ], - regularItems: [ - createMenuItem( - ROUTES.ROUTE_CITY_VISOR_STATICS, - Icons.Equalizer, - "تحلیل داده" - ), - createMenuItem(ROUTES.ROUTE_CITY_HATCHING, Icons.Egg, "مدیریت کشتار"), - createMenuItem( - ROUTES.ROUTE_CITY_ROUTE_FILES_STATE, - Icons.AccountTree, - "پرونده های کشتار" - ), - createMenuItem( - ROUTES.ROUTE_CITYـHATCHINGS, - Icons.SettingsInputComposite, - "مدیریت جوجه ریزی" - ), - createMenuItem( - ROUTES.ROUTE_CITY_ROUTE_ALLOCATIONS, - Icons.LocalShipping, - "مدیریت بارها" - ), - createMenuItem(ROUTES.ROUTE_CITY_PRICING, Icons.AttachMoney, "قیمت روز"), - createMenuItem( - ROUTES.ROUTE_CITY_POULTRIES, - Icons.PersonAddAlt, - "مدیریت فارم ها" - ), - createMenuItem( - ROUTES.ROUTE_CITY_POULTRY_FARMS, - Icons.Warehouse, - "مرغداران" - ), - createMenuItem(ROUTES.ROUTE_CITY_STATICS, Icons.PieChart, "آمار و اطلاعات"), - createMenuItem( - ROUTES.ROUTE_CITY_USER_MANAGEMENT, - Icons.PersonAddAlt, - "کاربران" - ), - createMenuItem(ROUTES.ROUTE_CITY_TICKET, Icons.Support, "تیکت ها"), - ], -}); - -// Inspector Menu Items -export const getInspectorMenuItems = () => ({ - collapsibleSections: [ - { - key: "inspector", - icon: Icons.SettingsSuggest, - text: "پنل مدیریت", - items: [ - createMenuItem( - ROUTES.ROUTE_INSPECTOR_REQUESTS_NEW_REQUESTS, - Icons.Folder, - "درخواست های جدید" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_INSPECTOR_AWAITING_PAYMENT_REQUESTS, - Icons.AttachMoneyIcon, - "در انتظار پرداخت" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_INSPECTOR_AWAITING_INSPECTION_REQUESTS, - Icons.FileCopy, - "در انتظار بازرسی" - ), - createMenuItem( - ROUTES.ROUTE_INSPECTOR_REJECTED_REQUESTS, - Icons.WarningIcon, - "درخواست های رد شده" - ), - createMenuItem( - ROUTES.ROUTE_INSPECTOR_ARCHIVED_REQUESTS, - Icons.ArchiveIcon, - "بایگانی" - ), - ], - }, - ], - regularItems: [ - createMenuItem( - ROUTES.ROUTE_INSPECTOR_STATICS, - Icons.PieChart, - "آمار و اطلاعات" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_INSPECTOR_REPORTING, - Icons.NoteAlt, - "گزارشات" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_INSPECTOR_TICKET, - Icons.Support, - "تیکت ها" - ), - ], -}); - -// Aviculture Menu Items -export const getAvicultureMenuItems = () => ({ - collapsibleSections: [ - { - key: "avicuture", - icon: Icons.SettingsSuggest, - text: "پنل مدیریت", - items: [ - createMenuItem( - ROUTES.ROUTE_AVICULTURE_HATCHING, - Icons.Egg, - "جوجه ریزی" - ), - createMenuItem( - ROUTES.ROUTE_AVICULTURE_SUBMIT_REQUEST, - Icons.AttachFile, - "درخواست های کشتار" - ), - createMenuItem( - ROUTES.ROUTE_AVICULTURE_AWAITING_PAYMENT_REQUESTS, - Icons.Payment, - "در انتظار پرداخت" - ), - createMenuItem( - ROUTES.ROUTE_AVICULTURE_AWAITING_INSPECTION_REQUESTS, - Icons.AssignmentLate, - "در انتظار بازرسی" - ), - createMenuItem( - ROUTES.ROUTE_AVICULTURE_REJECTED_REQUESTS, - Icons.Warning, - "درخواست های رد شده" - ), - createMenuItem( - ROUTES.ROUTE_AVICULTURE_ARCHIVED_REQUESTS, - Icons.Archive, - "بایگانی" - ), - createMenuItem( - ROUTES.ROUTE_AVICULTURE_GIVE_PERMISSION, - Icons.Archive, - "وکالت" - ), - ], - }, - ], - regularItems: [ - createMenuItem( - ROUTES.ROUTE_AVICULTURE_PRICING, - Icons.AttachMoney, - "قیمت روز" - ), - createMenuItem( - ROUTES.ROUTE_AVICULTURE_ROUTE_HALLS, - Icons.MeetingRoom, - "سالن ها" - ), - createMenuItem(ROUTES.ROUTE_AVICULTURE_TICKET, Icons.Support, "تیکت ها"), - ], -}); - -// Slaughter House Menu Items -export const getSlaughterHouseMenuItems = (slaughterPermissionState) => ({ - collapsibleSections: [ - { - key: "slaughter", - icon: Icons.SettingsSuggest, - text: "پنل مدیریت", - items: [ - createMenuItem( - ROUTES.ROUTE_SLAUGHTER_NEW_REQUESTS, - Icons.FeaturedPlayList, - "ثبت درخواست" - ), - createMenuItem( - ROUTES.ROUTE_SLAUGHTERـFREE_BUY, - Icons.ShoppingCart, - "خرید مستقیم" - ), - createMenuItem(ROUTES.ROUTE_SLAUGHTERـEXPORT, Icons.Flight, "صادرات"), - createMenuItem( - ROUTES.ROUTE_SLAUGHTER_PENDING_REQUESTS, - Icons.PendingActions, - "سفارش های دریافت شده" - ), - createMenuItem( - ROUTES.ROUTE_SLAUGHTER_ALLOCATION_REQUESTS, - Icons.AssignmentTurnedIn, - "تخصیصات" - ), - createMenuItem( - ROUTES.ROUTE_SLAUGHTER_ALLOCATE_CAR_REQUESTS, - Icons.LocalShipping, - "تخصیص خودرو" - ), - createMenuItem( - ROUTES.ROUTE_SLAUGHTER_ENTER_BAR_INFO, - Icons.LocalShipping, - "وارد کردن اطلاعات بار" - ), - createMenuItem( - ROUTES.ROUTE_SLAUGHTER_PAYING_FEES_REQUESTS, - Icons.MonetizationOn, - "مدیریت تعرفه ها" - ), - createMenuItem( - ROUTES.ROUTE_SLAUGHTER_WALLET, - Icons.AccountBalanceWallet, - "کیف پول" - ), - createMenuItem( - ROUTES.ROUTE_SLAUGHTER_FINANCIAL_TRANSACTIONS, - Icons.SwapHorizontalCircle, - "مدیریت تراکنش ها" - ), - createMenuItem( - ROUTES.ROUTE_SLAUGHTER_PAY_FACTORS_REQUESTS, - Icons.Receipt, - "مدیریت فاکتورها" - ), - ], - }, - ], - regularItems: [ - { - ...createMenuItem( - ROUTES.ROUTE_SLAUGHTER_ROUTE_MANAGE_BARS, - Icons.CorporateFare, - "مدیریت بارها" - ), - disabled: !slaughterPermissionState, - }, - { - ...createMenuItem( - ROUTES.ROUTE_SLAUGHTER_ROUTE_MANAGE_GUILDS, - Icons.CorporateFare, - "مدیریت اصناف" - ), - disabled: !slaughterPermissionState, - }, - { - ...createMenuItem( - ROUTES.ROUTE_SLAUGHTER_PRICING, - Icons.AttachMoney, - "قیمت روز" - ), - disabled: !slaughterPermissionState, - }, - { - ...createMenuItem( - ROUTES.ROUTE_SLAUGHTER_CAR_MANAGEMENT, - Icons.DirectionsCar, - "خودروها" - ), - disabled: !slaughterPermissionState, - }, - { - ...createMenuItem( - ROUTES.ROUTE_SLAUGHTER_DISPENSERS, - Icons.CoPresent, - "مدیریت توزیع" - ), - disabled: true, - }, - { - ...createMenuItem( - ROUTES.ROUTE_SLAUGHTER_INVENTORY, - Icons.Warehouse, - "انبار و توزیع" - ), - disabled: !slaughterPermissionState, - }, - { - ...createMenuItem(ROUTES.ROUTE_SLAUGHTER_MORGUE, Icons.AcUnit, "سردخانه"), - disabled: !slaughterPermissionState, - }, - ], -}); - -// Province Financial Menu Items -export const getProvinceFinancialMenuItems = () => ({ - collapsibleSections: [ - { - key: "provinceFinancial", - icon: Icons.SettingsSuggest, - text: "پنل مدیریت", - items: [ - createMenuItem( - ROUTES.ROUTE_PROVINCE_FINANCIAL_PENDING_REQUESTS, - Icons.PendingActions, - "صدور فاکتور" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_FINANCIAL_AWAITING_PAYMENT_REQUESTS, - Icons.AttachMoney, - "در انتظار پرداخت" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_FINANCIAL_CHECK_PAYED_FACTOR_REQUESTS, - Icons.Paid, - "فاکتورهای پرداخت شده" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_FINANCIAL_TRANSACTIONS, - Icons.Loop, - "تراکنش ها" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_FINANCIAL_FINAL_FACTORS_REQUESTS, - Icons.FactCheck, - "اسناد مالی" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_FINANCIAL_ACTIVE_REQUESTS, - Icons.FolderOpen, - "درخواست های فعال" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_FINANCIAL_AWAITING_INSPECTION_REQUESTS, - Icons.PendingActions, - "در انتظار بازرسی" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_FINANCIAL_ARCHIVED_REQUESTS, - Icons.Archive, - "بایگانی" - ), - ], - }, - ], - regularItems: [ - createMenuItem( - ROUTES.ROUTE_PROVINCE_FINANCIAL_SETTLEMENT, - Icons.CreditScore, - "تسویه حساب" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_PRICING, - Icons.AttachMoney, - "قیمت گذاری" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_FINANCIAL_STATICS, - Icons.PieChart, - "آمار و اطلاعات" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_FINANCIAL_TICKET, - Icons.Support, - "تیکت ها" - ), - createMenuItem( - ROUTES.ROUTE_PROVINCE_FINANCIAL_DOCUMENT_REGISTRATION, - Icons.AttachMoney, - "ثبت سند مالی" - ), - ], -}); - -// Vet Farm Menu Items -export const getVetFarmMenuItems = () => ({ - regularItems: [ - createMenuItem( - ROUTES.ROUTE_VETFARM_ROUTE_ALLOCATIONS, - Icons.SettingsSuggest, - "کدرهگیری قرنطینه" - ), - createMenuItem( - ROUTES.ROUTE_VETFARM_REGISTER_INFO, - Icons.Vaccines, - "مدیریت فارم" - ), - ], -}); - -// Driver Menu Items -export const getDriverMenuItems = () => ({ - regularItems: [ - createMenuItem( - ROUTES.ROUTE_DRIVER_REQUESTS, - Icons.SettingsSuggest, - "پنل مدیریت" - ), - ], -}); - -// Dispenser Menu Items -export const getDispenserMenuItems = () => ({ - regularItems: [ - createMenuItem( - ROUTES.ROUTE_DISPENSER_DASHBOARD, - Icons.SettingsSuggest, - "پنل مدیریت" - ), - ], -}); - -// Factory function to get menu items by role -export const getMenuItemsByRole = (role, additionalProps = {}) => { - switch (role) { - case "ProvinceOperator": - return getProvinceMenuItems(); - case "CityOperator": - return getCityMenuItems(); - case "ProvinceInspector": - case "Admin": - return getInspectorMenuItems(); - case "Poultry": - return getAvicultureMenuItems(); - case "KillHouse": - return getSlaughterHouseMenuItems( - additionalProps.slaughterPermissionState - ); - case "ProvinceFinancial": - return getProvinceFinancialMenuItems(); - case "VetFarm": - return getVetFarmMenuItems(); - case "Driver": - return getDriverMenuItems(); - case "Dispenser": - return getDispenserMenuItems(); - default: - return { collapsibleSections: [], regularItems: [] }; - } -}; diff --git a/src/layouts/sidebar/hooks/useResponsiveSidebar.js b/src/layouts/sidebar/hooks/useResponsiveSidebar.js deleted file mode 100644 index f07c6c8..0000000 --- a/src/layouts/sidebar/hooks/useResponsiveSidebar.js +++ /dev/null @@ -1,22 +0,0 @@ -import { useState, useEffect } from "react"; - -export const useResponsiveSidebar = () => { - const [width, setWidth] = useState( - typeof window !== "undefined" ? window.innerWidth : 768 - ); - - useEffect(() => { - const handleWindowSizeChange = () => { - setWidth(window.innerWidth); - }; - - window.addEventListener("resize", handleWindowSizeChange); - return () => { - window.removeEventListener("resize", handleWindowSizeChange); - }; - }, []); - - const isMobile = width <= 768; - - return { isMobile, width }; -}; diff --git a/src/layouts/sidebar/hooks/useSidebarState.js b/src/layouts/sidebar/hooks/useSidebarState.js deleted file mode 100644 index 43373df..0000000 --- a/src/layouts/sidebar/hooks/useSidebarState.js +++ /dev/null @@ -1,86 +0,0 @@ -import { useState, useEffect, useContext } from "react"; -import { useDispatch } from "react-redux"; -import { SidebarContext } from "../../../contexts/SidebarContext"; -import { - BACKDROP_HIDE, - BACKDROP_SHOW, -} from "../../../lib/redux/slices/appSlice"; - -export const useSidebarState = () => { - const [open, setOpen] = useState(false); - const [expandedItems, setExpandedItems] = useState([]); - const [openSub, setOpenSub] = useState({ - province: false, - adminx: false, - slaughter: false, - avicuture: false, - city: false, - provinceFinancial: false, - inspector: false, - slaughterVet: false, - superAdmin: false, - }); - const [sidebarMobileState, setSidebarMobileState] = - useContext(SidebarContext); - const dispatch = useDispatch(); - - const closeSidebar = () => { - setSidebarMobileState(false); - setOpen(false); - }; - - const handleAccordionChange = (index) => { - setExpandedItems((prev) => { - const newExpandedItems = [...prev]; - const currentIndex = newExpandedItems.indexOf(index); - if (currentIndex === -1) { - newExpandedItems.push(index); - } else { - newExpandedItems.splice(currentIndex, 1); - } - return newExpandedItems; - }); - }; - - const toggleSubMenu = (key) => { - setOpenSub((prev) => ({ - ...prev, - [key]: !prev[key], - })); - }; - - useEffect(() => { - setOpen(sidebarMobileState); - }, [sidebarMobileState]); - - useEffect(() => { - if (open) { - dispatch(BACKDROP_SHOW()); - } else { - dispatch(BACKDROP_HIDE()); - } - }, [open, dispatch]); - - useEffect(() => { - const handleDocumentClick = (e) => { - if (open && !e.target.closest("#sidebar")) { - closeSidebar(); - } - }; - - document.addEventListener("click", handleDocumentClick); - return () => { - document.removeEventListener("click", handleDocumentClick); - }; - }, [open]); - - return { - open, - setOpen, - expandedItems, - openSub, - closeSidebar, - handleAccordionChange, - toggleSubMenu, - }; -}; diff --git a/src/layouts/sidebar/sidebar.js b/src/layouts/sidebar/sidebar.js index 4211b3d..22564ce 100644 --- a/src/layouts/sidebar/sidebar.js +++ b/src/layouts/sidebar/sidebar.js @@ -2,16 +2,357 @@ import * as React from "react"; import { styled } from "@mui/material/styles"; import MuiDrawer from "@mui/material/Drawer"; import List from "@mui/material/List"; +import InventoryIcon from "@mui/icons-material/Inventory"; +// import Toolbar from "@mui/material/Toolbar"; +// import IconButton from "@mui/material/IconButton"; +// import ChevronLeftIcon from "@mui/icons-material/ChevronLeft"; +// import ChevronRightIcon from "@mui/icons-material/ChevronRight"; +import FactoryIcon from "@mui/icons-material/Factory"; +import WarehouseIcon from "@mui/icons-material/Warehouse"; +import EggIcon from "@mui/icons-material/Egg"; +import LocalShippingIcon from "@mui/icons-material/LocalShipping"; +// import ThumbDownIcon from "@mui/icons-material/ThumbDown"; +// import GavelIcon from "@mui/icons-material/Gavel"; +import AttachMoneyIcon from "@mui/icons-material/AttachMoney"; +import MeetingRoomIcon from "@mui/icons-material/MeetingRoom"; +import NoteAltIcon from "@mui/icons-material/NoteAlt"; +import PieChart from "@mui/icons-material/PieChart"; +import MailOutlineIcon from "@mui/icons-material/MailOutline"; +// import EggIcon from '@mui/icons-material/Egg'; +import CorporateFareIcon from "@mui/icons-material/CorporateFare"; +import { motion } from "framer-motion"; +import AccountBoxIcon from "@mui/icons-material/AccountBox"; +import ExpandMoreIcon from "@mui/icons-material/ExpandMore"; +import SettingsSuggestIcon from "@mui/icons-material/SettingsSuggest"; +import SettingsInputCompositeIcon from "@mui/icons-material/SettingsInputComposite"; +import FeaturedPlayListIcon from "@mui/icons-material/FeaturedPlayList"; +import ExpandLess from "@mui/icons-material/ExpandLess"; +import ExpandMore from "@mui/icons-material/ExpandMore"; +import ArrowBackIosNewIcon from "@mui/icons-material/ArrowBackIosNew"; +import SummarizeIcon from "@mui/icons-material/Summarize"; +import AddShoppingCartIcon from "@mui/icons-material/AddShoppingCart"; +import AssignmentIcon from "@mui/icons-material/Assignment"; +import LocalOfferIcon from "@mui/icons-material/LocalOffer"; +import ShoppingCartIcon from "@mui/icons-material/ShoppingCart"; +import FlightIcon from "@mui/icons-material/Flight"; +import BusinessIcon from "@mui/icons-material/Business"; +import LanIcon from "@mui/icons-material/Lan"; +import AssignmentTurnedInIcon from "@mui/icons-material/AssignmentTurnedIn"; +import AutoFixHighIcon from "@mui/icons-material/AutoFixHigh"; +import DraftsIcon from "@mui/icons-material/Drafts"; +import CompareArrowsIcon from "@mui/icons-material/CompareArrows"; +import AttachFileIcon from "@mui/icons-material/AttachFile"; +import PaymentIcon from "@mui/icons-material/Payment"; +import AssignmentLateIcon from "@mui/icons-material/AssignmentLate"; +import ArchiveIcon from "@mui/icons-material/Archive"; +import WarningIcon from "@mui/icons-material/Warning"; +import FolderOpenIcon from "@mui/icons-material/FolderOpen"; +import ReportIcon from "@mui/icons-material/Report"; +import NewReleasesIcon from "@mui/icons-material/NewReleases"; +import TaskAltIcon from "@mui/icons-material/TaskAlt"; +// import PaymentIcon from "@mui/icons-material/Payment"; +import { + Avatar, + Button, + Collapse, + IconButton, + ListItemButton, + ListItemIcon, + ListItemText, + Tooltip, + Typography, + // ListSubheader, +} from "@mui/material"; +// import DashboardIcon from "@mui/icons-material/Dashboard"; +// import SupportAgentIcon from "@mui/icons-material/SupportAgent"; +import PermPhoneMsgIcon from "@mui/icons-material/PermPhoneMsg"; +import EmailIcon from "@mui/icons-material/Email"; +import { Grid } from "../../components/grid/Grid"; +import LogoutIcon from "@mui/icons-material/Logout"; +import DirectionsCarIcon from "@mui/icons-material/DirectionsCar"; +import { useLocation, useNavigate } from "react-router-dom"; +import { + ROUTE_CITY_POULTRY_FARMS, + ROUTE_DRIVER_REQUESTS, + ROUTE_GENERAL_MESSAGES, + ROUTE_GENERAL_SUPPORT, + ROUTE_PROVINCE_PRICING, + ROUTE_SLAUGHTER_CAR_MANAGEMENT, + ROUTE_VETFARM_REGISTER_INFO, + ROUTE_AVICULTURE_ROUTE_HALLS, + ROUTE_AVICULTURE_TICKET, + ROUTE_PROVINCE_FINANCIAL_TICKET, + ROUTE_CITY_TICKET, + ROUTE_PROVINCE_TICKET, + ROUTE_PROVINCE_INSPECTOR_TICKET, + ROUTE_CITY_USER_MANAGEMENT, + ROUTE_PROVINCE_INSPECTOR_REPORTING, + ROUTE_ADMIN_STATICS, + ROUTE_INSPECTOR_STATICS, + ROUTE_PROVINCE_STATICS, + ROUTE_CITY_STATICS, + ROUTE_PROVINCE_FINANCIAL_STATICS, + ROUTE_PROVINCE_FINANCIAL_DOCUMENT_REGISTRATION, + ROUTE_CITY_HATCHING, + ROUTE_PROVINCE_HATCHING, + ROUTE_JAHAD_KILLS_STATS, + ROUTE_VETFARM_ROUTE_ALLOCATIONS, + ROUTE_VETـSUPERVISOR_ALLOCATIONS, + ROUTE_JAHAD_ILLEGALـKILLING, + ROUTE_VETـSUPERVISOR_ILLEGALـKILLING, + ROUTE_PROVINCE_ROUTE_ALLOCATIONS, + ROUTE_VETـSUPERVISOR_KILLS_STATS, + ROUTE_PROVINCE_ROUTE_SMS, + ROUTE_PROVINCE_PRICING3, + ROUTE_CITY_PRICING, + ROUTE_AVICULTURE_PRICING, + ROUTE_SLAUGHTER_PRICING, + ROUTE_PROVINCE_FINANCIAL_SETTLEMENT, + ROUTE_PROVINCE_CARS, + ROUTE_PROVINCE_USERS, + ROUTE_PROVINCE_ASSIGN_VET_FARM, + ROUTE_GENERAL_TRAINING, + ROUTE_PROVINCE_ROUTE_FILES_STATE, + ROUTE_JAHAD_PRICING, + ROUTE_JAHAD_FILES_STATE, + ROUTE_PROVINCE_ROUTE_MANAGE_GUILDS, + ROUTE_CITY_ROUTE_ALLOCATIONS, + ROUTE_CITY_ROUTE_FILES_STATE, + ROUTE_STEWARD_INVENTORY, + ROUTE_PROVINCE_POULTRIES, + ROUTE_COMMERCE_ROUTE_MANAGE_GUILDS, + ROUTE_COMMERCE_ROUTE_FILES_STATE, + ROUTE_COMMERCE_ROUTE_ALLOCATIONS, + ROUTE_CITY_COMMERCE_ROUTE_MANAGE_GUILDS, + ROUTE_CITY_COMMERCE_ROUTE_FILES_STATE, + ROUTE_CITY_COMMERCE_ROUTE_ALLOCATIONS, + ROUTE_COMMERCE_STATICS, + ROUTE_CITY_POULTRIES, + ROUTE_SLAUGHTER_ROUTE_MANAGE_GUILDS, + ROUTE_CITYVET_ROUTE_ALLOCATIONS, + ROUTE_CITY_JIHAD_STATICS, + ROUTE_CITY_JIHAD_ROUTE_FILES_STATE, + ROUTE_CITY_JIHAD_ROUTE_ALLOCATIONS, + ROUTE_CITY_JIHAD_ROUTE_MANAGE_GUILDS, + ROUTE_PROVINCEـBROADCAST_MANAGEMENT, + ROUTE_SLAUGHTER_MORGUE, + ROUTE_OBSERVATORY_STATICS, + ROUTE_PROVINCE_SUPERVISOR_STATICS, + ROUTE_PROVINCE_SUPERVISOR_ROUTE_MANAGE_GUILDS, + ROUTE_PROVINCE_SUPERVISOR_ROUTE_FILES_STATE, + ROUTE_PROVINCE_SUPERVISOR_ROUTE_ALLOCATIONS, + ROUTE_STEWARD_MANAGE_GUILDS, + ROUTE_SENF_INVENTORY, + ROUTE_COMMERCE_HATCHING, + ROUTE_PROVINCE_SUPERVISOR_HATCHING, + ROUTE_SLAUGHTER_ROUTE_MANAGE_BARS, + ROUTE_PROVINCE_REPORT, + ROUTE_VETـSUPERVISOR_STATICS, + ROUTE_VETـSUPERVISOR_ROUTE_FILES_STATE, + ROUTE_VETـSUPERVISOR_HATCHING, + ROUTE_VETـSUPERVISOR_REPORTING, + ROUTE_GUILD_ROOM_ROUTE_MANAGE_GUILDS, + ROUTE_PSP_COMPANY_ROUTE_MANAGE_STEWARDS, + ROUTE_PROVINCE_PRODUCTS, + ROUTE_PROVINCE_GUILD_TRANSACTIONS, + ROUTE_LIVE_STOCK_SUPPORT_MANAGE_BARS, + ROUTE_LIVE_STOCK_SUPPORT_ROUTE_FILES_STATE, + ROUTE_LIVE_STOCK_FREEZING_REQUESTS, + ROUTE_LIVE_STOCK_COLD_HOUSE, + ROUTE_SUPER_ADMIN_TICKET, + ROUTE_SUPER_ADMIN_ROUTE_MANAGE_PROCESS, + ROUTE_SUPER_ADMIN_ROUTE_SMS, + ROUTE_SUPER_ADMIN_ASSIGN_VET_FARM, + ROUTE_SUPER_ADMIN_BROADCAST_MANAGEMENT, + ROUTE_SUPER_ADMIN_PRODUCTS, + ROUTE_SUPER_ADMIN_SLAUGHTERS, + ROUTE_SUPER_ADMIN_POULTRIES, + ROUTE_SUPER_ADMIN_GUILD_TRANSACTIONS, + ROUTE_SUPER_ADMIN_USERS, + ROUTE_SUPER_ADMIN_CARS, + ROUTE_SUPER_ADMIN_ROUTE_MANAGE_GUILDS, + ROUTE_SUPER_ADMIN_ROUTE_ALLOCATIONS, + ROUTE_SUPER_ADMIN_ROUTE_FILES_STATE, + ROUTE_SUPER_ADMIN_REPORT, + ROUTE_SUPER_ADMIN_STATICS, + ROUTE_SUPER_ADMIN_PRICING3, + ROUTE_SUPER_ADMIN_HATCHING, + ROUTE_PROVINCE_SUPERVISOR_REPORTING, + ROUTE_CHAIN_COMPANY_POULTRIES, + ROUTE_CHAIN_COMPANY_MANAGE_BARS, + ROUTE_CHAIN_COMPANY_MANAGE_FEES, + ROUTE_PROVINCE_SLAUGHTERS, + ROUTE_ADMINX_PROVINCE_SWITCH, + ROUTE_ADMINX_ROUTE_MANAGE_PROCESS, + ROUTE_SUPPORTER_ROUTE_ALLOCATIONS, + ROUTE_ADMINX_ROUTE_ALLOCATIONS, + ROUTE_ADMINX_TICKET, + ROUTE_ADMINX_ROUTE_SMS, + ROUTE_ADMINX_ASSIGN_VET_FARM, + ROUTE_ADMINX_BROADCAST_MANAGEMENT, + ROUTE_ADMINX_PRODUCTS, + ROUTE_ADMINX_SLAUGHTERS, + ROUTE_ADMINX_POULTRIES, + ROUTE_ADMINX_GUILD_TRANSACTIONS, + ROUTE_ADMINX_USERS, + ROUTE_ADMINX_CARS, + ROUTE_ADMINX_ROUTE_MANAGE_GUILDS, + ROUTE_ADMINX_ROUTE_FILES_STATE, + ROUTE_ADMINX_REPORT, + ROUTE_ADMINX_STATICS, + ROUTE_ADMINX_PRICING3, + ROUTE_ADMINX_HATCHING, + ROUTE_ADMIN_VISOR_STATICS, + ROUTE_ADMINX_VISOR_STATICS, + ROUTE_CITY_VISOR_STATICS, + ROUTE_OBSERVATORY_VISOR_STATICS, + ROUTE_PROVINCEـVISOR_STATICS, + ROUTE_SUPER_ADMIN_VISOR_STATICS, + ROUTE_DISPENSER_DASHBOARD, + ROUTE_ADMINX_EXCEL_CHECK, + ROUTE_SLAUGHTER_DISPENSERS, + ROUTE_ADMINX_DISPENSERS, + ROUTE_CITY_POULTRY_STATICS, + ROUTE_CITY_POULTRY_ROUTE_FILES_STATE, + ROUTE_CITY_POULTRY_ROUTE_ALLOCATIONS, + ROUTE_CITY_POULTRY_ROUTE_MANAGE_GUILDS, + ROUTE_CITY_POULTRY_HATCHING, + ROUTE_GENERAL_USER_PROFILE, + ROUTE_PROVINCEـHATCHINGS, + ROUTE_PROVINCE_SUPERVISORـHATCHINGS, + ROUTE_CITY_POULTRYـHATCHINGS, + ROUTE_SUPER_ADMINـHATCHINGS, + ROUTE_ADMINXـHATCHINGS, + ROUTE_SUPPORTERـHATCHINGS, + ROUTE_CITYـHATCHINGS, + ROUTE_PROVINCE_DISPENSERS, + ROUTE_SUPER_ADMIN_DISPENSERS, + ROUTE_SLAUGHTER_INVENTORY, + ROUTE_PROVINCE_CITY_NEW_REQUESTS, + ROUTE_PROVINCE_STATEMENTـOFـNEED_REQUESTS, + ROUTE_PROVINCE_ALLOCATION_REQUESTS, + ROUTE_PROVINCE_PAYING_FEES_REQUESTS, + ROUTE_PROVINCEـFREE_BUY, + ROUTE_PROVINCEـEXPORT, + ROUTE_PROVINCE_FREE_SALES_REQUESTS, + ROUTE_PROVINCE_CHAINS, + ROUTE_PROVINCE_ALLOCATED_REQUESTS, + ROUTE_PROVINCE_AUTO_ALLOCATION_REQUESTS, + ROUTE_PROVINCE_ISSUANCE_OF_LETTER, + ROUTE_PROVINCE_TRANSACTIONS, + ROUTE_ADMINX_TRANSACTIONS, + ROUTE_ADMINX_ISSUANCE_OF_LETTER, + ROUTE_ADMINX_AUTO_ALLOCATION_REQUESTS, + ROUTE_ADMINX_ALLOCATED_REQUESTS, + ROUTE_ADMINX_CHAINS, + ROUTE_ADMINX_FREE_SALES_REQUESTS, + ROUTE_ADMINX_EXPORT, + ROUTE_ADMINX_PAYING_FEES_REQUESTS, + ROUTE_ADMINX_ALLOCATION_REQUESTS, + ROUTE_ADMINX_STATEMENTـOFـNEED_REQUESTS, + ROUTE_ADMINX_CITY_NEW_REQUESTS, + ROUTE_SLAUGHTER_NEW_REQUESTS, + ROUTE_SLAUGHTERـFREE_BUY, + ROUTE_SLAUGHTERـEXPORT, + ROUTE_SLAUGHTER_PENDING_REQUESTS, + ROUTE_SLAUGHTER_ALLOCATION_REQUESTS, + ROUTE_SLAUGHTER_ALLOCATE_CAR_REQUESTS, + ROUTE_SLAUGHTER_ENTER_BAR_INFO, + ROUTE_SLAUGHTER_PAYING_FEES_REQUESTS, + ROUTE_SLAUGHTER_WALLET, + ROUTE_SLAUGHTER_FINANCIAL_TRANSACTIONS, + ROUTE_SLAUGHTER_PAY_FACTORS_REQUESTS, + ROUTE_AVICULTURE_HATCHING, + ROUTE_AVICULTURE_SUBMIT_REQUEST, + ROUTE_AVICULTURE_AWAITING_PAYMENT_REQUESTS, + ROUTE_AVICULTURE_AWAITING_INSPECTION_REQUESTS, + ROUTE_AVICULTURE_REJECTED_REQUESTS, + ROUTE_AVICULTURE_ARCHIVED_REQUESTS, + ROUTE_AVICULTURE_GIVE_PERMISSION, + ROUTE_CITY_ARCHIVED_REQUESTS, + ROUTE_CITY_FREE_SALES_REQUESTS, + ROUTE_CITY_REJECTED_REQUESTS, + ROUTE_CITY_AWAITING_INSPECTION_REQUESTS, + ROUTE_CITY_AWAITING_PAYMENT_REQUESTS, + ROUTE_CITY_ACTIVE_REQUESTS, + ROUTE_CITY_NEW_REQUESTS, + ROUTE_PROVINCE_FINANCIAL_ARCHIVED_REQUESTS, + ROUTE_PROVINCE_FINANCIAL_AWAITING_INSPECTION_REQUESTS, + ROUTE_PROVINCE_FINANCIAL_ACTIVE_REQUESTS, + ROUTE_PROVINCE_FINANCIAL_FINAL_FACTORS_REQUESTS, + ROUTE_PROVINCE_FINANCIAL_TRANSACTIONS, + ROUTE_PROVINCE_FINANCIAL_CHECK_PAYED_FACTOR_REQUESTS, + ROUTE_PROVINCE_FINANCIAL_AWAITING_PAYMENT_REQUESTS, + ROUTE_PROVINCE_FINANCIAL_PENDING_REQUESTS, + ROUTE_INSPECTOR_REQUESTS_NEW_REQUESTS, + ROUTE_PROVINCE_INSPECTOR_AWAITING_PAYMENT_REQUESTS, + ROUTE_PROVINCE_INSPECTOR_AWAITING_INSPECTION_REQUESTS, + ROUTE_INSPECTOR_REJECTED_REQUESTS, + ROUTE_INSPECTOR_ARCHIVED_REQUESTS, + ROUTE_SLAUGHTER_HOUSE_VET_FREE_BUY_ROUTE, + ROUTE_SLAUGHTER_HOUSE_VET_NEW_REQUESTS, + ROUTE_SLAUGHTER_HOUSE_VET_ENTER_BAR_INFO, + ROUTE_SUPER_ADMIN_TRANSACTIONS, + ROUTE_SUPER_ADMIN_ISSUANCE_OF_LETTER, + ROUTE_SUPER_ADMIN_AUTO_ALLOCATION_REQUESTS, + ROUTE_SUPER_ADMIN_ALLOCATED_REQUESTS, + ROUTE_SUPER_ADMIN_CHAINS, + ROUTE_SUPER_ADMIN_FREE_SALES_REQUESTS, + ROUTE_SUPER_ADMIN_EXPORT, + ROUTE_SUPER_ADMIN_PAYING_FEES_REQUESTS, + ROUTE_SUPER_ADMIN_ALLOCATION_REQUESTS, + ROUTE_SUPER_ADMIN_STATEMENTـOFـNEED_REQUESTS, + ROUTE_SUPER_ADMIN_CITY_NEW_REQUESTS, +} from "../../routes/routes"; import { useDispatch, useSelector } from "react-redux"; +import { LOG_OUT } from "../../lib/redux/slices/userSlice"; +import { getFaUserRole } from "../../utils/getFaUserRole"; +import { Box } from "@mui/system"; +import VaccinesIcon from "@mui/icons-material/Vaccines"; +import PersonAddAltIcon from "@mui/icons-material/PersonAddAlt"; +import ErrorIcon from "@mui/icons-material/Error"; +import CreditScoreIcon from "@mui/icons-material/CreditScore"; +import { SPACING } from "../../data/spacing"; +import useUserProfile from "../../features/authentication/hooks/useUserProfile"; +import { SidebarContext } from "../../contexts/SidebarContext"; +import ReceiptLongIcon from "@mui/icons-material/ReceiptLong"; +import CoPresentIcon from "@mui/icons-material/CoPresent"; +import { + BACKDROP_HIDE, + BACKDROP_SHOW, + CLOSE_MODAL, + DRAWER, + OPEN_MODAL, +} from "../../lib/redux/slices/appSlice"; +import SupportIcon from "@mui/icons-material/Support"; import { getUserProfile } from "../../features/authentication/services/getUserProfile"; -import { useUserProfile } from "../../features/authentication/hooks/useUserProfile"; -import { SidebarHeader } from "./components/SidebarHeader"; -import { LogoutButton } from "./components/LogoutButton"; -import { RoleAccordion } from "./components/RoleAccordion"; -import { RoleMenuRenderer } from "./components/RoleMenuRenderer"; -import { useSidebarState } from "./hooks/useSidebarState"; -import { useResponsiveSidebar } from "./hooks/useResponsiveSidebar"; -import { getMenuItemsByRole } from "./constants/roleMenuConfigs"; +import AccountTreeIcon from "@mui/icons-material/AccountTree"; +import LightbulbIcon from "@mui/icons-material/Lightbulb"; +import AcUnitIcon from "@mui/icons-material/AcUnit"; +import { FaFile } from "react-icons/fa"; +import KitchenIcon from "@mui/icons-material/Kitchen"; +import { Accordion, AccordionSummary } from "@mui/material"; +import { getIconUserRole } from "../../utils/getRoleIcon"; +import ToggleOnIcon from "@mui/icons-material/ToggleOn"; +import EqualizerIcon from "@mui/icons-material/Equalizer"; +import { DocumentScanner } from "@mui/icons-material"; +import PorvinceGetReportOperations from "../../features/province/components/province-get-report-operations/PorvinceGetReportOperations"; +import FlightTakeoffIcon from "@mui/icons-material/FlightTakeoff"; +import PendingActionsIcon from "@mui/icons-material/PendingActions"; +import MonetizationOnIcon from "@mui/icons-material/MonetizationOn"; +import AccountBalanceWalletIcon from "@mui/icons-material/AccountBalanceWallet"; +import SwapHorizontalCircleIcon from "@mui/icons-material/SwapHorizontalCircle"; +import ReceiptIcon from "@mui/icons-material/Receipt"; +import PaidIcon from "@mui/icons-material/Paid"; +import FactCheckIcon from "@mui/icons-material/FactCheck"; +import LoopIcon from "@mui/icons-material/Loop"; +import { Folder } from "@mui/icons-material"; +import { AttachMoney } from "@mui/icons-material"; +import { FileCopy } from "@mui/icons-material"; +import { Archive } from "@mui/icons-material"; +import { Warning } from "@mui/icons-material"; +import { AddBox } from "@mui/icons-material"; +import PersianDate from "persian-date"; const drawerWidth = 280; @@ -36,6 +377,32 @@ const closedMixin = (theme) => ({ }, }); +// export const secondaryListItems = ( +// +// +// Saved reports +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// +// ); + const Drawer = styled(MuiDrawer, { shouldForwardProp: (prop) => prop !== "open", })(({ theme, open }) => ({ @@ -55,6 +422,8 @@ const Drawer = styled(MuiDrawer, { })); export const Sidebar = () => { + const { pathname } = useLocation(); + const navigate = useNavigate(); const dispatch = useDispatch(); const [role, userProfile] = useUserProfile(); const roles = [...role]; @@ -62,24 +431,4168 @@ export const Sidebar = () => { (item) => item.slaughterSlice ); - const { - open, - setOpen, - expandedItems, - openSub, - closeSidebar, - handleAccordionChange, - toggleSubMenu, - } = useSidebarState(); - - const { isMobile } = useResponsiveSidebar(); - React.useEffect(() => { if (Array.isArray(role)) { roles.sort(); } dispatch(getUserProfile()); - }, [dispatch, role, roles]); + }, []); + + function stringAvatar(name) { + if (name) { + const nameArr = name + ?.split(" ") + ?.filter((item) => item) + ?.map((item) => item[0]); + return { + sx: { + bgcolor: "#353b48", + }, + children: nameArr[0], + }; + } + return {}; + } + + const [open, setOpen] = React.useState(false); + // const toggleDrawer = () => { + // setOpen(!open); + // }; + + const [expandedItems, setExpandedItems] = React.useState([]); + + const handleAccordionChange = (index) => { + const newExpandedItems = [...expandedItems]; + const currentIndex = newExpandedItems.indexOf(index); + if (currentIndex === -1) { + newExpandedItems.push(index); + } else { + newExpandedItems.splice(currentIndex, 1); + } + setExpandedItems(newExpandedItems); + }; + + React.useEffect(() => { + const handleDocumentClick = (e) => { + if (open && !e.target.closest("#sidebar")) { + closeSidebar(); + } + }; + + document.addEventListener("click", handleDocumentClick); + + return () => { + document.removeEventListener("click", handleDocumentClick); + }; + }, [open]); + + const [sidebarMobileState, setSidebarMobileState] = + React.useContext(SidebarContext); + + const closeSidebar = () => { + setSidebarMobileState(false); + setOpen(false); + }; + + React.useEffect(() => { + setOpen(sidebarMobileState); + }, [sidebarMobileState]); + + React.useEffect(() => { + if (open) { + dispatch(BACKDROP_SHOW()); + } else { + dispatch(BACKDROP_HIDE()); + } + }, [open]); + + const [openSub, setOpenSub] = React.useState({ + province: false, + adminx: false, + slaughter: false, + avicuture: false, + city: false, + provinceFinancial: false, + inspector: false, + slaughterVet: false, + superAdmin: false, + }); + + const handleRenderDashboardItems = (items) => { + return ( + <> + {items.map((item, i) => { + return ( + { + dispatch( + DRAWER({ right: false, bottom: false, content: null }) + ); + navigate(item?.route); + closeSidebar(); + }} + selected={pathname.includes(item?.route)} + > + + {item?.icon ? item.icon : } + + + + ); + })} + + ); + }; + + // const [currentTime, setCurrentTime] = React.useState(new Date()); + + // useEffect(() => { + // const intervalId = setInterval(() => { + // setCurrentTime(new Date()); + // }, 1000); + + // return () => clearInterval(intervalId); + // }, []); + const generalItems = ( + <> + {/* + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_GENERAL_MESSAGES); + closeSidebar(); + }} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_GENERAL_TRAINING); + closeSidebar(); + }} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_GENERAL_SUPPORT); + closeSidebar(); + }} + > + + + + + + */} + + + { + closeSidebar(); + dispatch(DRAWER({ right: false, bottom: false, content: null })); + dispatch( + OPEN_MODAL({ + title: "از سامانه خارج میشوید؟", + content: ( + + + + + ), + }) + ); + }} + > + + + + + + + + ); + + const dispenserItems = ( + <> + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_DISPENSER_DASHBOARD); + closeSidebar(); + }} + > + + + + + + + + ); + + const vetFarmItems = ( + <> + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_VETFARM_ROUTE_ALLOCATIONS); + closeSidebar(); + }} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_VETFARM_REGISTER_INFO); + closeSidebar(); + }} + > + + + + + + + {/* + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_VETFARM_ROUTE_HATCHING); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_VETFARM_ROUTE_HATCHING)} + > + + + + + + */} + + ); + + const inspectorItems = ( + <> + { + setOpenSub((prevState) => ({ + ...prevState, + inspector: !prevState.inspector, + })); + }} + > + + + + + {openSub.inspector ? : } + + + + {handleRenderDashboardItems([ + { + route: ROUTE_INSPECTOR_REQUESTS_NEW_REQUESTS, + icon: , + text: "درخواست های جدید", + }, + { + route: ROUTE_PROVINCE_INSPECTOR_AWAITING_PAYMENT_REQUESTS, + icon: , + text: "در انتظار پرداخت", + }, + { + route: ROUTE_PROVINCE_INSPECTOR_AWAITING_INSPECTION_REQUESTS, + icon: , + text: "در انتظار بازرسی", + }, + { + route: ROUTE_INSPECTOR_REJECTED_REQUESTS, + icon: , + text: "درخواست های رد شده", + }, + { + route: ROUTE_INSPECTOR_ARCHIVED_REQUESTS, + icon: , + text: "بایگانی", + }, + ])} + + + + {/* + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_INSPECTOR_PRICING); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_INSPECTOR_PRICING)} + > + + + + + + */} + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_INSPECTOR_STATICS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_INSPECTOR_STATICS)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_INSPECTOR_REPORTING); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_INSPECTOR_REPORTING)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_INSPECTOR_TICKET); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_INSPECTOR_TICKET)} + > + + + + + + + {/* + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + window.open( + `https://seeyo.ir/autologin/${userInfo.authToken}/${userInfo.userProfile.province}`, + "_blank" + ); + closeSidebar(); + }} + > + + + + + + */} + + ); + + const cityItems = ( + + { + setOpenSub((prevState) => ({ + ...prevState, + city: !prevState.city, + })); + }} + > + + + + + {openSub.city ? : } + + + + {handleRenderDashboardItems([ + { + route: ROUTE_CITY_NEW_REQUESTS, + icon: , + text: "درخواست های جدید", + }, + { + route: ROUTE_CITY_ACTIVE_REQUESTS, + icon: , + text: "درخواست های فعال", + }, + { + route: ROUTE_CITY_AWAITING_PAYMENT_REQUESTS, + icon: , + text: "در انتظار پرداخت", + }, + { + route: ROUTE_CITY_AWAITING_INSPECTION_REQUESTS, + icon: , + text: "در انتظار بازرسی", + }, + { + route: ROUTE_CITY_REJECTED_REQUESTS, + icon: , + text: "درخواست های رد شده", + }, + { + route: ROUTE_CITY_FREE_SALES_REQUESTS, + icon: , + text: "فروش خارج از استان", + }, + { + route: ROUTE_CITY_ARCHIVED_REQUESTS, + icon: , + text: "بایگانی", + }, + ])} + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CITY_VISOR_STATICS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_CITY_VISOR_STATICS)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CITY_HATCHING); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_CITY_HATCHING)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CITY_ROUTE_FILES_STATE); + closeSidebar(); + }} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CITYـHATCHINGS); + closeSidebar(); + }} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CITY_ROUTE_ALLOCATIONS); + closeSidebar(); + }} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CITY_PRICING); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_CITY_PRICING)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CITY_POULTRIES); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_CITY_POULTRIES)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CITY_POULTRY_FARMS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_CITY_POULTRY_FARMS)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CITY_STATICS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_CITY_STATICS)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CITY_USER_MANAGEMENT); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_CITY_USER_MANAGEMENT)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CITY_TICKET); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_CITY_TICKET)} + > + + + + + + + + ); + + const avicultureItems = ( + + { + setOpenSub((prevState) => ({ + ...prevState, + avicuture: !prevState.avicuture, + })); + }} + > + + + + + {openSub.avicuture ? : } + + + + {handleRenderDashboardItems([ + { + route: ROUTE_AVICULTURE_HATCHING, + icon: , + text: "جوجه ریزی", + }, + { + route: ROUTE_AVICULTURE_SUBMIT_REQUEST, + icon: , + text: "درخواست های کشتار", + }, + { + route: ROUTE_AVICULTURE_AWAITING_PAYMENT_REQUESTS, + icon: , + text: "در انتظار پرداخت", + }, + { + route: ROUTE_AVICULTURE_AWAITING_INSPECTION_REQUESTS, + icon: , + text: "در انتظار بازرسی", + }, + { + route: ROUTE_AVICULTURE_REJECTED_REQUESTS, + icon: , + text: "درخواست های رد شده", + }, + { + route: ROUTE_AVICULTURE_ARCHIVED_REQUESTS, + icon: , + text: "بایگانی", + }, + { + route: ROUTE_AVICULTURE_GIVE_PERMISSION, + icon: , + text: "وکالت", + }, + ])} + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_AVICULTURE_PRICING); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_AVICULTURE_PRICING)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_AVICULTURE_ROUTE_HALLS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_AVICULTURE_ROUTE_HALLS)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_AVICULTURE_TICKET); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_AVICULTURE_TICKET)} + > + + + + + + + + {/* + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_AVICULTURE_REPORTS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_AVICULTURE_REPORTS)} + > + + + + + + */} + + {/* + { + navigate(ROUTE_AVICULTURE_AUCTION); + dispatch(DRAWER({ right: false, bottom: false, content: null })); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_AVICULTURE_AUCTION)} + > + + + + + + */} + + ); + + const provinceItems = ( + + { + setOpenSub((prevState) => ({ + ...prevState, + province: !prevState.province, + })); + }} + > + + + + + {openSub.province ? : } + + + + {handleRenderDashboardItems([ + { + text: "مدیریت درخواست ها", + route: ROUTE_PROVINCE_CITY_NEW_REQUESTS, + icon: , + }, + { + text: "اعلام نیاز خریداران", + route: ROUTE_PROVINCE_STATEMENTـOFـNEED_REQUESTS, + icon: , + }, + { + text: "تخصیصات", + route: ROUTE_PROVINCE_ALLOCATION_REQUESTS, + icon: , + }, + { + text: "تعرفه ها", + route: ROUTE_PROVINCE_PAYING_FEES_REQUESTS, + icon: , + }, + { + text: "خرید مستقیم", + route: ROUTE_PROVINCEـFREE_BUY, + icon: , + }, + { + text: "صادرات", + route: ROUTE_PROVINCEـEXPORT, + icon: , + }, + { + text: "فروش به خارج استان", + route: ROUTE_PROVINCE_FREE_SALES_REQUESTS, + icon: , + }, + { + text: "زنجیره ها", + route: ROUTE_PROVINCE_CHAINS, + icon: , + }, + { + text: "مدیریت تخصیصات", + route: ROUTE_PROVINCE_ALLOCATED_REQUESTS, + icon: , + }, + { + text: "تخصیصات خودکار", + route: ROUTE_PROVINCE_AUTO_ALLOCATION_REQUESTS, + icon: , + }, + { + text: "صدور نامه", + route: ROUTE_PROVINCE_ISSUANCE_OF_LETTER, + icon: , + }, + { + text: "تراکنش ها", + route: ROUTE_PROVINCE_TRANSACTIONS, + icon: , + }, + ])} + + + + + dispatch( + OPEN_MODAL({ + title: "اطلاعات گزارش", + content: , + }) + ) + } + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCEـVISOR_STATICS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCEـVISOR_STATICS)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_HATCHING); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_HATCHING)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCEـHATCHINGS); + closeSidebar(); + }} + > + + + + + + + + {/* */} + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_PRICING3); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_PRICING3)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_STATICS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_STATICS)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_REPORT); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_REPORT)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_ROUTE_FILES_STATE); + closeSidebar(); + }} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_ROUTE_ALLOCATIONS); + closeSidebar(); + }} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_DISPENSERS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_DISPENSERS)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_ROUTE_MANAGE_GUILDS); + closeSidebar(); + }} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_CARS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_CARS)} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_USERS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_USERS)} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_GUILD_TRANSACTIONS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_GUILD_TRANSACTIONS)} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_POULTRIES); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_POULTRIES)} + > + + + + + + + {/* + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_MANAGE_USERS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_MANAGE_USERS)} + > + + + + + + */} + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_SLAUGHTERS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_SLAUGHTERS)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_PRODUCTS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_PRODUCTS)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCEـBROADCAST_MANAGEMENT); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCEـBROADCAST_MANAGEMENT)} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_ASSIGN_VET_FARM); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_ASSIGN_VET_FARM)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_ROUTE_SMS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_ROUTE_SMS)} + > + + + + + + + {/* + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_SEND_MESSAGE); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_SEND_MESSAGE)} + > + + + + + + */} + {/* + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_KILLER_MANAGMENT); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_KILLER_MANAGMENT)} + > + + + + + + */} + + {/* + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_ROUTE_MANAGE_PROCESS); + closeSidebar(); + }} + > + + + + + + */} + + {/* + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_ROUTE_CASE_STATUS); + closeSidebar(); + }} + > + + + + + + */} + {/* + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_STATICS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_STATICS)} + > + + + + + + */} + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_TICKET); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_TICKET)} + > + + + + + + + + {/* + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + window.open( + `https://seeyo.ir/autologin/${userInfo.authToken}/${userInfo.userProfile.province}`, + "_blank" + ); + closeSidebar(); + }} + > + + + + + + */} + + ); + + const superAdminItems = ( + + { + setOpenSub((prevState) => ({ + ...prevState, + superAdmin: !prevState.superAdmin, + })); + }} + > + + + + + {openSub.superAdmin ? : } + + + + {handleRenderDashboardItems([ + { + text: "مدیریت درخواست ها", + route: ROUTE_SUPER_ADMIN_CITY_NEW_REQUESTS, + icon: , + }, + { + text: "اعلام نیاز خریداران", + route: ROUTE_SUPER_ADMIN_STATEMENTـOFـNEED_REQUESTS, + icon: , + }, + { + text: "تخصیصات", + route: ROUTE_SUPER_ADMIN_ALLOCATION_REQUESTS, + icon: , + }, + { + text: "تعرفه ها", + route: ROUTE_SUPER_ADMIN_PAYING_FEES_REQUESTS, + icon: , + }, + { + text: "خرید مستقیم", + route: ROUTE_PROVINCEـFREE_BUY, + icon: , + }, + { + text: "صادرات", + route: ROUTE_SUPER_ADMIN_EXPORT, + icon: , + }, + { + text: "فروش به خارج استان", + route: ROUTE_SUPER_ADMIN_FREE_SALES_REQUESTS, + icon: , + }, + { + text: "زنجیره ها", + route: ROUTE_SUPER_ADMIN_CHAINS, + icon: , + }, + { + text: "مدیریت تخصیصات", + route: ROUTE_SUPER_ADMIN_ALLOCATED_REQUESTS, + icon: , + }, + { + text: "تخصیصات خودکار", + route: ROUTE_SUPER_ADMIN_AUTO_ALLOCATION_REQUESTS, + icon: , + }, + { + text: "صدور نامه", + route: ROUTE_SUPER_ADMIN_ISSUANCE_OF_LETTER, + icon: , + }, + { + text: "تراکنش ها", + route: ROUTE_SUPER_ADMIN_TRANSACTIONS, + icon: , + }, + ])} + + + + + dispatch( + OPEN_MODAL({ + title: "اطلاعات گزارش", + content: , + }) + ) + } + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPER_ADMIN_VISOR_STATICS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SUPER_ADMIN_VISOR_STATICS)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPER_ADMIN_HATCHING); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SUPER_ADMIN_HATCHING)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPER_ADMINـHATCHINGS); + closeSidebar(); + }} + > + + + + + + + + {/* */} + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPER_ADMIN_PRICING3); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SUPER_ADMIN_PRICING3)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPER_ADMIN_STATICS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SUPER_ADMIN_STATICS)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPER_ADMIN_REPORT); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SUPER_ADMIN_REPORT)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPER_ADMIN_ROUTE_FILES_STATE); + closeSidebar(); + }} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPER_ADMIN_ROUTE_ALLOCATIONS); + closeSidebar(); + }} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPER_ADMIN_DISPENSERS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SUPER_ADMIN_DISPENSERS)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPER_ADMIN_ROUTE_MANAGE_GUILDS); + closeSidebar(); + }} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPER_ADMIN_CARS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SUPER_ADMIN_CARS)} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPER_ADMIN_USERS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SUPER_ADMIN_USERS)} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPER_ADMIN_GUILD_TRANSACTIONS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SUPER_ADMIN_GUILD_TRANSACTIONS)} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPER_ADMIN_POULTRIES); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SUPER_ADMIN_POULTRIES)} + > + + + + + + + {/* + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPER_ADMIN_MANAGE_USERS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SUPER_ADMIN_MANAGE_USERS)} + > + + + + + + */} + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPER_ADMIN_SLAUGHTERS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SUPER_ADMIN_SLAUGHTERS)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPER_ADMIN_PRODUCTS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SUPER_ADMIN_PRODUCTS)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPER_ADMIN_BROADCAST_MANAGEMENT); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SUPER_ADMIN_BROADCAST_MANAGEMENT)} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPER_ADMIN_ASSIGN_VET_FARM); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SUPER_ADMIN_ASSIGN_VET_FARM)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPER_ADMIN_ROUTE_SMS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SUPER_ADMIN_ROUTE_SMS)} + > + + + + + + + {/* + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPER_ADMIN_SEND_MESSAGE); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SUPER_ADMIN_SEND_MESSAGE)} + > + + + + + + */} + {/* + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPER_ADMIN_KILLER_MANAGMENT); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SUPER_ADMIN_KILLER_MANAGMENT)} + > + + + + + + */} + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPER_ADMIN_ROUTE_MANAGE_PROCESS); + closeSidebar(); + }} + > + + + + + + + + {/* + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPER_ADMIN_ROUTE_CASE_STATUS); + closeSidebar(); + }} + > + + + + + + */} + {/* + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPER_ADMIN_STATICS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SUPER_ADMIN_STATICS)} + > + + + + + + */} + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPER_ADMIN_TICKET); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SUPER_ADMIN_TICKET)} + > + + + + + + + + {/* + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + window.open( + `https://seeyo.ir/autologin/${userInfo.authToken}/${userInfo.userProfile.province}`, + "_blank" + ); + closeSidebar(); + }} + > + + + + + + */} + + ); + + const vetSupervisorItems = ( + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_VETـSUPERVISOR_HATCHING); + closeSidebar(); + }} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_VETـSUPERVISOR_ROUTE_FILES_STATE); + closeSidebar(); + }} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_VETـSUPERVISOR_STATICS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_VETـSUPERVISOR_STATICS)} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_VETـSUPERVISOR_ALLOCATIONS); + closeSidebar(); + }} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_VETـSUPERVISOR_ILLEGALـKILLING); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_VETـSUPERVISOR_ILLEGALـKILLING)} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_VETـSUPERVISOR_KILLS_STATS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_VETـSUPERVISOR_KILLS_STATS)} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_VETـSUPERVISOR_REPORTING); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_VETـSUPERVISOR_REPORTING)} + > + + + + + + + + ); + + const slaughterHouseItems = ( + + { + setOpenSub((prevState) => ({ + ...prevState, + slaughter: !prevState.slaughter, + })); + }} + > + + + + + {openSub.slaughter ? : } + + + + {handleRenderDashboardItems([ + { + text: "ثبت درخواست", + route: ROUTE_SLAUGHTER_NEW_REQUESTS, + icon: , + }, + { + text: "خرید مستقیم", + route: ROUTE_SLAUGHTERـFREE_BUY, + icon: , + }, + { + text: "صادرات", + route: ROUTE_SLAUGHTERـEXPORT, + icon: , + }, + { + text: "سفارش های دریافت شده", + route: ROUTE_SLAUGHTER_PENDING_REQUESTS, + icon: , + }, + { + text: "تخصیصات", + route: ROUTE_SLAUGHTER_ALLOCATION_REQUESTS, + icon: , + }, + { + text: "تخصیص خودرو", + route: ROUTE_SLAUGHTER_ALLOCATE_CAR_REQUESTS, + icon: , + }, + { + text: "وارد کردن اطلاعات بار", + route: ROUTE_SLAUGHTER_ENTER_BAR_INFO, + icon: , + }, + // { + // text: "انبار و توزیع", + // route: ROUTE_SLAUGHTER_INVENTORY, + // icon: , + // }, + { + text: "مدیریت تعرفه ها", + route: ROUTE_SLAUGHTER_PAYING_FEES_REQUESTS, + icon: , + }, + { + text: "کیف پول", + route: ROUTE_SLAUGHTER_WALLET, + icon: , + }, + { + text: "مدیریت تراکنش ها", + route: ROUTE_SLAUGHTER_FINANCIAL_TRANSACTIONS, + icon: , + }, + { + text: "مدیریت فاکتورها", + route: ROUTE_SLAUGHTER_PAY_FACTORS_REQUESTS, + icon: , + }, + ])} + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SLAUGHTER_ROUTE_MANAGE_BARS); + closeSidebar(); + }} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SLAUGHTER_ROUTE_MANAGE_GUILDS); + closeSidebar(); + }} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SLAUGHTER_PRICING); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SLAUGHTER_PRICING)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SLAUGHTER_CAR_MANAGEMENT); + closeSidebar(); + }} + selected={pathname.includes("cars")} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SLAUGHTER_DISPENSERS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SLAUGHTER_DISPENSERS)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SLAUGHTER_INVENTORY); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SLAUGHTER_INVENTORY)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SLAUGHTER_MORGUE); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SLAUGHTER_MORGUE)} + > + + + + + + + + {/* + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SLAUGHTER_TICKET); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SLAUGHTER_TICKET)} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SLAUGHTER_COMPLAINTS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SLAUGHTER_COMPLAINTS)} + > + + + + + + */} + + {/* + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SLAUGHTER_AGENT_SHARE); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SLAUGHTER_AGENT_SHARE)} + > + + + + + + */} + + {/* + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SLAUGHTER_AUCTION); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SLAUGHTER_AUCTION)} + > + + + + + + */} + + ); + + const cityJihadItems = ( + <> + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CITY_JIHAD_STATICS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_CITY_JIHAD_STATICS)} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CITY_JIHAD_ROUTE_FILES_STATE); + closeSidebar(); + }} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CITY_JIHAD_ROUTE_ALLOCATIONS); + closeSidebar(); + }} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CITY_JIHAD_ROUTE_MANAGE_GUILDS); + closeSidebar(); + }} + > + + + + + + + + ); + + const cityPoultryItems = ( + <> + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CITY_POULTRY_HATCHING); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_CITY_POULTRY_HATCHING)} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CITY_POULTRY_STATICS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_CITY_POULTRY_STATICS)} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CITY_POULTRY_ROUTE_FILES_STATE); + closeSidebar(); + }} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CITY_POULTRYـHATCHINGS); + closeSidebar(); + }} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CITY_POULTRY_ROUTE_ALLOCATIONS); + closeSidebar(); + }} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CITY_POULTRY_ROUTE_MANAGE_GUILDS); + closeSidebar(); + }} + > + + + + + + + + ); + + const slaughterHouseVetItems = ( + <> + { + setOpenSub((prevState) => ({ + ...prevState, + slaughterVet: !prevState.slaughterVet, + })); + }} + > + + + + + {openSub.slaughterVet ? : } + + + + {handleRenderDashboardItems([ + { + route: ROUTE_SLAUGHTER_HOUSE_VET_FREE_BUY_ROUTE, + icon: , + text: "بارهای خارج استان", + }, + { + route: ROUTE_SLAUGHTER_HOUSE_VET_NEW_REQUESTS, + icon: , + text: "بارهای جدید", + }, + { + route: ROUTE_SLAUGHTER_HOUSE_VET_ENTER_BAR_INFO, + icon: , + text: "وارد کردن اطلاعات بار", + }, + ])} + + + + ); + + const driverItems = ( + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_DRIVER_REQUESTS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_DRIVER_REQUESTS)} + > + + + + + + + + ); + + const provinceFinancialItems = ( + + { + setOpenSub((prevState) => ({ + ...prevState, + provinceFinancial: !prevState.provinceFinancial, + })); + }} + > + + + + + {openSub.provinceFinancial ? : } + + + + {handleRenderDashboardItems([ + { + route: ROUTE_PROVINCE_FINANCIAL_PENDING_REQUESTS, + icon: , + text: "صدور فاکتور", + }, + { + route: ROUTE_PROVINCE_FINANCIAL_AWAITING_PAYMENT_REQUESTS, + icon: , + text: "در انتظار پرداخت", + }, + { + route: ROUTE_PROVINCE_FINANCIAL_CHECK_PAYED_FACTOR_REQUESTS, + icon: , + text: "فاکتورهای پرداخت شده", + }, + { + route: ROUTE_PROVINCE_FINANCIAL_TRANSACTIONS, + icon: , + text: "تراکنش ها", + }, + { + route: ROUTE_PROVINCE_FINANCIAL_FINAL_FACTORS_REQUESTS, + icon: , + text: "اسناد مالی", + }, + { + route: ROUTE_PROVINCE_FINANCIAL_ACTIVE_REQUESTS, + icon: , + text: "درخواست های فعال", + }, + { + route: ROUTE_PROVINCE_FINANCIAL_AWAITING_INSPECTION_REQUESTS, + icon: , + text: "در انتظار بازرسی", + }, + { + route: ROUTE_PROVINCE_FINANCIAL_ARCHIVED_REQUESTS, + icon: , + text: "بایگانی", + }, + ])} + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_FINANCIAL_SETTLEMENT); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_FINANCIAL_SETTLEMENT)} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_PRICING); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_PRICING)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_FINANCIAL_STATICS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_FINANCIAL_STATICS)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_FINANCIAL_TICKET); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_FINANCIAL_TICKET)} + > + + + + + + + + {/* + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_FINANCIAL_COMPLAINTS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_FINANCIAL_COMPLAINTS)} + > + + + + + + */} + + {/* + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_FINANCIAL_ROUTE_DEBT); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_FINANCIAL_ROUTE_DEBT)} + > + + + + + + */} + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_FINANCIAL_DOCUMENT_REGISTRATION); + closeSidebar(); + }} + selected={pathname.includes( + ROUTE_PROVINCE_FINANCIAL_DOCUMENT_REGISTRATION + )} + > + + + + + + + + ); + + const adminItems = ( + + {/* + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMIN_REQUESTS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_ADMIN_REQUESTS)} + > + + + + + + */} + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMIN_VISOR_STATICS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_ADMIN_VISOR_STATICS)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMIN_STATICS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_ADMIN_STATICS)} + > + + + + + + + + ); + + const jahadItems = ( + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_JAHAD_KILLS_STATS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_JAHAD_KILLS_STATS)} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_JAHAD_ILLEGALـKILLING); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_JAHAD_ILLEGALـKILLING)} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_JAHAD_PRICING); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_JAHAD_PRICING)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_JAHAD_FILES_STATE); + closeSidebar(); + }} + > + + + + + + + + ); + + const guildItems = ( + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_STEWARD_INVENTORY); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_STEWARD_INVENTORY)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_STEWARD_MANAGE_GUILDS); + closeSidebar(); + }} + > + + + + + + + + ); + + const senfItems = ( + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SENF_INVENTORY); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_SENF_INVENTORY)} + > + + + + + + + + ); + + const commerceItems = ( + + + dispatch( + OPEN_MODAL({ + title: "اطلاعات گزارش", + content: , + }) + ) + } + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_COMMERCE_STATICS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_COMMERCE_STATICS)} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_COMMERCE_ROUTE_MANAGE_GUILDS); + closeSidebar(); + }} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_COMMERCE_ROUTE_FILES_STATE); + closeSidebar(); + }} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_COMMERCE_ROUTE_ALLOCATIONS); + closeSidebar(); + }} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_COMMERCE_HATCHING); + closeSidebar(); + }} + > + + + + + + + + ); + const ProvinceSupervisorItems = ( + + + dispatch( + OPEN_MODAL({ + title: "اطلاعات گزارش", + content: , + }) + ) + } + > + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_SUPERVISOR_STATICS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_SUPERVISOR_STATICS)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_SUPERVISOR_ROUTE_FILES_STATE); + closeSidebar(); + }} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_SUPERVISORـHATCHINGS); + closeSidebar(); + }} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_SUPERVISOR_ROUTE_ALLOCATIONS); + closeSidebar(); + }} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_SUPERVISOR_HATCHING); + closeSidebar(); + }} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_SUPERVISOR_ROUTE_MANAGE_GUILDS); + closeSidebar(); + }} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PROVINCE_SUPERVISOR_REPORTING); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PROVINCE_SUPERVISOR_REPORTING)} + > + + + + + + + + {/* + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + window.open( + `https://seeyo.ir/autologin/${userInfo.authToken}/${userInfo.userProfile.province}`, + "_blank" + ); + closeSidebar(); + }} + > + + + + + + */} + {/* + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_VETـSUPERVISOR_REPORTING); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_VETـSUPERVISOR_REPORTING)} + > + + + + + + */} + + ); + + const cityCommerceItems = ( + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CITY_COMMERCE_ROUTE_MANAGE_GUILDS); + closeSidebar(); + }} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CITY_COMMERCE_ROUTE_FILES_STATE); + closeSidebar(); + }} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CITY_COMMERCE_ROUTE_ALLOCATIONS); + closeSidebar(); + }} + > + + + + + + + + ); + + const liveStockItems = ( + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_LIVE_STOCK_SUPPORT_MANAGE_BARS); + closeSidebar(); + }} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_LIVE_STOCK_SUPPORT_ROUTE_FILES_STATE); + closeSidebar(); + }} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_LIVE_STOCK_FREEZING_REQUESTS); + closeSidebar(); + }} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_LIVE_STOCK_COLD_HOUSE); + closeSidebar(); + }} + > + + + + + + + + ); + + const cityVetItems = ( + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CITYVET_ROUTE_ALLOCATIONS); + closeSidebar(); + }} + > + + + + + + + + ); + + const observatoryItems = ( + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_OBSERVATORY_STATICS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_OBSERVATORY_STATICS)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_OBSERVATORY_VISOR_STATICS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_OBSERVATORY_VISOR_STATICS)} + > + + + + + + + + ); + + const guildRoomItems = ( + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_GUILD_ROOM_ROUTE_MANAGE_GUILDS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_GUILD_ROOM_ROUTE_MANAGE_GUILDS)} + > + + + + + + + + ); + + const pspCompanyItems = ( + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_PSP_COMPANY_ROUTE_MANAGE_STEWARDS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_PSP_COMPANY_ROUTE_MANAGE_STEWARDS)} + > + + + + + + + + ); + + const chainCompanyItems = ( + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CHAIN_COMPANY_POULTRIES); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_CHAIN_COMPANY_POULTRIES)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CHAIN_COMPANY_MANAGE_BARS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_CHAIN_COMPANY_MANAGE_BARS)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_CHAIN_COMPANY_MANAGE_FEES); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_CHAIN_COMPANY_MANAGE_FEES)} + > + + + + + + + + ); + + const adminXItems = ( + + { + setOpenSub((prevState) => ({ + ...prevState, + adminx: !prevState.adminx, + })); + }} + > + + + + + {openSub.adminx ? : } + + + + {handleRenderDashboardItems([ + { + text: "مدیریت درخواست ها", + route: ROUTE_ADMINX_CITY_NEW_REQUESTS, + icon: , + }, + { + text: "اعلام نیاز خریداران", + route: ROUTE_ADMINX_STATEMENTـOFـNEED_REQUESTS, + icon: , + }, + { + text: "تخصیصات", + route: ROUTE_ADMINX_ALLOCATION_REQUESTS, + icon: , + }, + { + text: "تعرفه ها", + route: ROUTE_ADMINX_PAYING_FEES_REQUESTS, + icon: , + }, + { + text: "خرید مستقیم", + route: ROUTE_PROVINCEـFREE_BUY, + icon: , + }, + { + text: "صادرات", + route: ROUTE_ADMINX_EXPORT, + icon: , + }, + { + text: "فروش به خارج استان", + route: ROUTE_ADMINX_FREE_SALES_REQUESTS, + icon: , + }, + { + text: "زنجیره ها", + route: ROUTE_ADMINX_CHAINS, + icon: , + }, + { + text: "مدیریت تخصیصات", + route: ROUTE_ADMINX_ALLOCATED_REQUESTS, + icon: , + }, + { + text: "تخصیصات خودکار", + route: ROUTE_ADMINX_AUTO_ALLOCATION_REQUESTS, + icon: , + }, + { + text: "صدور نامه", + route: ROUTE_ADMINX_ISSUANCE_OF_LETTER, + icon: , + }, + { + text: "تراکنش ها", + route: ROUTE_ADMINX_TRANSACTIONS, + icon: , + }, + ])} + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINX_PROVINCE_SWITCH); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_ADMINX_PROVINCE_SWITCH)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINX_VISOR_STATICS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_ADMINX_VISOR_STATICS)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINX_HATCHING); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_ADMINX_HATCHING)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINXـHATCHINGS); + closeSidebar(); + }} + > + + + + + + + + {/* */} + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINX_PRICING3); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_ADMINX_PRICING3)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINX_STATICS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_ADMINX_STATICS)} + > + + + + + + + + + dispatch( + OPEN_MODAL({ + title: "اطلاعات گزارش", + content: , + }) + ) + } + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINX_REPORT); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_ADMINX_REPORT)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINX_ROUTE_FILES_STATE); + closeSidebar(); + }} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINX_ROUTE_ALLOCATIONS); + closeSidebar(); + }} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINX_DISPENSERS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_ADMINX_DISPENSERS)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINX_ROUTE_MANAGE_GUILDS); + closeSidebar(); + }} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINX_CARS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_ADMINX_CARS)} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINX_USERS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_ADMINX_USERS)} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINX_GUILD_TRANSACTIONS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_ADMINX_GUILD_TRANSACTIONS)} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINX_POULTRIES); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_ADMINX_POULTRIES)} + > + + + + + + + {/* + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINX_MANAGE_USERS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_ADMINX_MANAGE_USERS)} + > + + + + + + */} + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINX_SLAUGHTERS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_ADMINX_SLAUGHTERS)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINX_PRODUCTS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_ADMINX_PRODUCTS)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINX_BROADCAST_MANAGEMENT); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_ADMINX_BROADCAST_MANAGEMENT)} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINX_ASSIGN_VET_FARM); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_ADMINX_ASSIGN_VET_FARM)} + > + + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINX_ROUTE_SMS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_ADMINX_ROUTE_SMS)} + > + + + + + + + {/* + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINX_SEND_MESSAGE); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_ADMINX_SEND_MESSAGE)} + > + + + + + + */} + {/* + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINX_KILLER_MANAGMENT); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_ADMINX_KILLER_MANAGMENT)} + > + + + + + + */} + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINX_ROUTE_MANAGE_PROCESS); + closeSidebar(); + }} + > + + + + + + + + {/* + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINX_ROUTE_CASE_STATUS); + closeSidebar(); + }} + > + + + + + + */} + {/* + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINX_STATICS); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_ADMINX_STATICS)} + > + + + + + + */} + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINX_TICKET); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_ADMINX_TICKET)} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_ADMINX_EXCEL_CHECK); + closeSidebar(); + }} + selected={pathname.includes(ROUTE_ADMINX_EXCEL_CHECK)} + > + + + + + + + + {/* + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + window.open( + `https://seeyo.ir/autologin/${userInfo.authToken}/${userInfo.userProfile.province}`, + "_blank" + ); + closeSidebar(); + }} + > + + + + + + */} + + ); + + const supporterItems = ( + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPPORTER_ROUTE_ALLOCATIONS); + closeSidebar(); + }} + > + + + + + + + + { + dispatch(DRAWER({ right: false, bottom: false, content: null })); + navigate(ROUTE_SUPPORTERـHATCHINGS); + closeSidebar(); + }} + > + + + + + + + + ); + + const getSidebarItemsByRole = (role) => { + switch (role) { + case "AdminX": + return adminXItems; + case "Admin": + return { ...adminItems, ...inspectorItems }; + case "CityOperator": + return cityItems; + case "Poultry": + return avicultureItems; + case "ProvinceOperator": + return provinceItems; + case "ProvinceFinancial": + return provinceFinancialItems; + case "KillHouse": + return slaughterHouseItems; + case "KillHouseVet": + return slaughterHouseVetItems; + case "VetFarm": + return vetFarmItems; + case "Driver": + return driverItems; + case "VetSupervisor": + return vetSupervisorItems; + case "ProvinceInspector": + return inspectorItems; + case "Jahad": + return jahadItems; + case "ProvincialGovernment": + return jahadItems; + case "Guilds": + return senfItems; + case "Steward": + return guildItems; + case "Commerce": + return commerceItems; + case "ProvinceSupervisor": + return ProvinceSupervisorItems; + case "CityCommerce": + return cityCommerceItems; + case "CityVet": + return cityVetItems; + case "CityJahad": + return cityJihadItems; + case "Observatory": + return observatoryItems; + case "GuildRoom": + return guildRoomItems; + case "PosCompany": + return pspCompanyItems; + case "LiveStockSupport": + return liveStockItems; + case "SuperAdmin": + return superAdminItems; + case "ChainCompany": + return chainCompanyItems; + case "Supporter": + return supporterItems; + case "Dispenser": + return dispenserItems; + case "CityPoultry": + return cityPoultryItems; + default: + return null; + } + }; + + // const topItems = ( + // <> + // + // { + // dispatch(DRAWER({ right: false, bottom: false, content: null })); + // navigate("/"); + // closeSidebar(); + // }} + // selected={pathname === "/"} + // > + // + // + // + // + // + // + // + // ); + + const [width, setWidth] = React.useState(window.innerWidth); + + function handleWindowSizeChange() { + setWidth(window.innerWidth); + } + React.useEffect(() => { + window.addEventListener("resize", handleWindowSizeChange); + return () => { + window.removeEventListener("resize", handleWindowSizeChange); + }; + }, []); + + const isMobile = width <= 768; + + // const [sidebarSelectRolesOptions, setSidebarSelectRolesOptions] = + // React.useState([]); + + React.useEffect(() => { + // const sidebarSelectRoles = roles.map((userRole, i) => { + // return { + // label: getFaUserRole(userRole), + // value: userRole, + // }; + // }); + // setSidebarSelectRolesOptions(sidebarSelectRoles); + }, []); + + // React.useEffect(() => { + // if (!selectedRoles.length) { + // if (sidebarSelectRolesOptions?.length) { + // dispatch(CHANGE_SELECTED_ROLES(roles)); + // } + // } + // }, [sidebarSelectRolesOptions]); return ( { zIndex: (theme) => theme.zIndex.drawer + 11, }} > + {/* + + + {open ? : } + + + + */} - + + + {userProfile?.image && + userProfile?.image !== "empty" && + userProfile?.fullname ? ( + + ) : ( + + )} + {open && ( + + {userProfile?.fullname} + + موبایل: {userProfile?.mobile} + + + )} + + + + + + { + dispatch( + DRAWER({ right: false, bottom: false, content: null }) + ); + navigate(ROUTE_GENERAL_USER_PROFILE); + closeSidebar(); + }} + > + + + + + { + dispatch( + DRAWER({ right: false, bottom: false, content: null }) + ); + navigate(ROUTE_GENERAL_MESSAGES); + closeSidebar(); + }} + > + + + + + { + dispatch( + DRAWER({ right: false, bottom: false, content: null }) + ); + navigate(ROUTE_GENERAL_TRAINING); + closeSidebar(); + }} + > + + + + + { + dispatch( + DRAWER({ right: false, bottom: false, content: null }) + ); + navigate(ROUTE_GENERAL_SUPPORT); + closeSidebar(); + }} + > + + + + + + {open && ( + + {/* + ( + */} + + {new PersianDate().toLocale("fa").format("dddd DD MMMM")} + + {/* + - + + + {currentTime.toLocaleTimeString([], { + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + hour12: false, + })} + + + ) + */} + + )} + {/* */} + {/* {topItems} */} {roles.map((userRole, i) => { - const menuConfig = getMenuItemsByRole(userRole, { - slaughterPermissionState, - }); - const isExpanded = expandedItems.includes(i); - - // Skip rendering if no menu items - if ( - (!menuConfig.collapsibleSections || - menuConfig.collapsibleSections.length === 0) && - (!menuConfig.regularItems || menuConfig.regularItems.length === 0) - ) { - return null; - } - + const jsx = getSidebarItemsByRole(userRole); return ( - handleAccordionChange(i)} + style={{ + borderRadius: "8px", + }} > - - + handleAccordionChange(i)} + expandIcon={ + + } + style={{ + backgroundColor: expandedItems.includes(i) + ? "#0fb9b1" + : "#dfe6e9", + boxShadow: expandedItems.includes(i) + ? "inset 0 0 2px rgba(0,0,0,0.75)" + : "none", + }} + > + {open ? ( + + + + + {getIconUserRole(userRole)} + + + + + {getFaUserRole(userRole)} + + + + + ) : ( + + {getIconUserRole(userRole)} + + )} + + + {jsx} + +
    ); })} - + {generalItems} + {/* {secondaryListItems} */} ); diff --git a/src/layouts/site-map/SiteMap.js b/src/layouts/site-map/SiteMap.js index 5786c21..b315644 100644 --- a/src/layouts/site-map/SiteMap.js +++ b/src/layouts/site-map/SiteMap.js @@ -1,179 +1,19 @@ -import React, { useState, useEffect } from "react"; +import React from "react"; import { Grid } from "../../components/grid/Grid"; -import { - Typography, - Select, - MenuItem, - FormControl, - Box, - IconButton, - Button, - InputLabel, - CircularProgress, -} from "@mui/material"; -import EditIcon from "@mui/icons-material/Edit"; +import { Typography } from "@mui/material"; import { getFaUserRole } from "../../utils/getFaUserRole"; import { getRoleFromUrl } from "../../utils/getRoleFromUrl"; import { getRoleItems } from "../../utils/getRolesItems"; import { useLocation, useNavigate } from "react-router-dom"; -import { useSelector, useDispatch } from "react-redux"; +import { useSelector } from "react-redux"; import { getLiveStockItems } from "../../utils/getLivestock"; import arrow from "../../assets/images/arrow.png"; -import { SET_SELECTED_SUB_USER } from "../../lib/redux/slices/userSlice"; -import { OPEN_MODAL, CLOSE_MODAL } from "../../lib/redux/slices/appSlice"; -import { getUserRoleInfo } from "../../features/authentication/services/getUserRoleInfo"; - -// Edit Modal Content Component -const EditModalContent = ({ - initialRole, - initialSubUser, - subUsers: initialSubUsers, - onSubmit, - onCancel, - userKey, -}) => { - const dispatch = useDispatch(); - const [selectedSubUserInModal, setSelectedSubUserInModal] = - useState(initialSubUser); - const [subUsers, setSubUsers] = useState(initialSubUsers || []); - const [loadingSubUsers, setLoadingSubUsers] = useState(false); - - const rolesNeedingSubUsers = [ - "Steward", - "ColdHouseSteward", - "KillHouse", - "Guilds", - ]; - - const getRoleLabel = (role) => { - switch (role) { - case "KillHouse": - return "نام کشتارگاه"; - case "ColdHouseSteward": - case "Steward": - return "نام مباشر"; - case "Guilds": - return "نام صنف"; - default: - return "انتخاب واحد"; - } - }; - - const fetchSubUsers = React.useCallback( - (role) => { - if (role && rolesNeedingSubUsers.includes(role) && userKey) { - setLoadingSubUsers(true); - dispatch(getUserRoleInfo({ userKey, role })) - .unwrap() - .then((result) => { - if (result?.data && Array.isArray(result.data)) { - setSubUsers(result.data); - } else { - setSubUsers([]); - } - setLoadingSubUsers(false); - }) - .catch((error) => { - console.error("Error fetching subUsers:", error); - setSubUsers([]); - setLoadingSubUsers(false); - }); - } else { - setSubUsers([]); - setLoadingSubUsers(false); - } - }, - [userKey, dispatch, rolesNeedingSubUsers] - ); - - useEffect(() => { - if (initialRole) { - if (initialSubUsers && initialSubUsers.length > 0) { - return; - } - fetchSubUsers(initialRole); - } - }, [initialRole]); - - return ( - - {rolesNeedingSubUsers.includes(initialRole) && ( - - - - {getRoleLabel(initialRole)} - - {loadingSubUsers ? ( - - - - ) : ( - - )} - - - )} - - - - - - - - - - ); -}; export const SiteMap = () => { const { pathname } = useLocation(); const navigate = useNavigate(); - const dispatch = useDispatch(); const { subMenuText, mediatorText } = useSelector((state) => state.userSlice); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); - const subUsers = useSelector((state) => state.userSlice.subUsers); - const userProfile = useSelector((state) => state.userSlice.userProfile); - const loginUserProfile = useSelector( - (state) => state.userSlice.loginUserProfile - ); - const userKey = userProfile?.key || loginUserProfile?.key; - - // Check if current route is slaughter, senf, or steward - const isAllowedRoute = - pathname.startsWith("/slaughter") || - pathname.startsWith("/senf") || - pathname.startsWith("/steward"); const showSecondPath = !getRoleItems(getRoleFromUrl())?.find( @@ -191,94 +31,6 @@ export const SiteMap = () => { (element) => element.route === mediatorText )?.text; - const getRoleLabel = (role) => { - switch (role) { - case "KillHouse": - return "کشتارگاه"; - case "Steward": - return "مباشر"; - case "Guilds": - return "صنف"; - default: - return "کشتارگاه"; // Default fallback - } - }; - - const currentRole = getRoleFromUrl(); - const roleLabel = getRoleLabel(currentRole); - const subUserName = selectedSubUser?.unit; - - const handleOpenEditModal = () => { - const initialRole = getRoleFromUrl() || ""; - const initialSubUser = selectedSubUser?.key || ""; - - dispatch( - OPEN_MODAL({ - title: "تغییر واحد", - content: ( - dispatch(CLOSE_MODAL())} - userKey={userKey} - /> - ), - size: 400, - }) - ); - }; - - const handleSubmit = (selectedSubUserInModal) => { - dispatch(CLOSE_MODAL()); - dispatch( - OPEN_MODAL({ - title: "تأیید تغییرات", - content: ( - - - - آیا از تغییر واحد مطمئن هستید؟ - - - - - - - - - - - - ), - size: 300, - }) - ); - }; - - const handleConfirmSubmit = (selectedSubUserInModal) => { - if (selectedSubUserInModal) { - const subUser = subUsers.find((u) => u.key === selectedSubUserInModal); - if (subUser) { - dispatch(SET_SELECTED_SUB_USER(subUser)); - } - } - dispatch(CLOSE_MODAL()); - }; - return ( { px={2} mt={1} > - { : "نمایش"} - - {isAllowedRoute && subUsers && subUsers.length > 1 && ( - - - نام {roleLabel} :{" "} - - {subUserName} - - - - - - - )} - +
    ); }; diff --git a/src/lib/redux/slices/generalExtraReducers.js b/src/lib/redux/slices/generalExtraReducers.js index b37107c..9116428 100644 --- a/src/lib/redux/slices/generalExtraReducers.js +++ b/src/lib/redux/slices/generalExtraReducers.js @@ -11,8 +11,6 @@ import { guildGetStewards } from "../../../features/guild/services/guild-get-ste import { guildGetAllocationData } from "../../../features/guild/services/guildGetAllocationData"; import { senfGetInventoryAllocatedService } from "../../../features/guild/services/senf-get-inventory-allocated"; import { senfGetInventoryStockService } from "../../../features/guild/services/senf-get-inventory-stock"; -import { senfGetAllocationDashboardService } from "../../../features/guild/services/senf-get-allocation-dashboard"; -import { guildSalesInfoDashboardService } from "../../../features/guild/services/guild-sales-info-dashboard"; export const generalExtraReducers = { [guildGetProfile.fulfilled]: (state, { payload }) => { @@ -44,9 +42,6 @@ export const generalExtraReducers = { [senfGetInventoryStockService.fulfilled]: (state, { payload }) => { state.senfGetInventoryStock = payload.data; }, - [senfGetAllocationDashboardService.fulfilled]: (state, { payload }) => { - state.senfGetInventoryStock = payload.data; - }, [guildGetStewards.fulfilled]: (state, { payload }) => { state.guildStewards = payload.data; }, @@ -69,7 +64,4 @@ export const generalExtraReducers = { state.guildGetGuildData = payload.data; state.pending = false; }, - [guildSalesInfoDashboardService.fulfilled]: (state, { payload }) => { - state.guildSalesInfoDashboard = payload.data; - }, }; diff --git a/src/lib/redux/slices/userExtraReducers.js b/src/lib/redux/slices/userExtraReducers.js index 5f46ff3..badd390 100644 --- a/src/lib/redux/slices/userExtraReducers.js +++ b/src/lib/redux/slices/userExtraReducers.js @@ -1,6 +1,5 @@ import { getUserMovingTextsService } from "../../../features/authentication/services/getUserMovingTexts"; import { getUserProfile } from "../../../features/authentication/services/getUserProfile"; -import { getUserRoleInfo } from "../../../features/authentication/services/getUserRoleInfo"; import { changePassword, checkUserPath, @@ -68,24 +67,4 @@ export const userExtraReducers = { state.pending = false; state.userMovingTexts = fulltext; }, - [getUserRoleInfo.fulfilled]: (state, { payload }) => { - state.pending = false; - if (payload.data && Array.isArray(payload.data)) { - state.subUsers = payload.data; - if (payload.data.length > 0) { - state.selectedSubUser = payload.data[0]; - } - } else { - state.subUsers = []; - state.selectedSubUser = null; - } - }, - [getUserRoleInfo.pending]: (state) => { - state.pending = true; - }, - [getUserRoleInfo.rejected]: (state) => { - state.pending = false; - state.subUsers = []; - state.selectedSubUser = null; - }, }; diff --git a/src/lib/redux/slices/userReducers.js b/src/lib/redux/slices/userReducers.js index 296ace5..177af2d 100644 --- a/src/lib/redux/slices/userReducers.js +++ b/src/lib/redux/slices/userReducers.js @@ -45,13 +45,4 @@ export const userReducers = { SET_TYPE_ACTIVITY_SELECTED: (state, action) => { state.typeActivitySelected = action.payload; }, - SET_SELECTED_ROLE: (state, action) => { - state.selectedRole = action.payload; - }, - SET_SELECTED_SUB_USER: (state, action) => { - state.selectedSubUser = action.payload; - }, - SET_SUB_USERS: (state, action) => { - state.subUsers = action.payload; - }, }; diff --git a/src/lib/redux/slices/userSlice.js b/src/lib/redux/slices/userSlice.js index c0b90d6..672ce45 100644 --- a/src/lib/redux/slices/userSlice.js +++ b/src/lib/redux/slices/userSlice.js @@ -11,9 +11,6 @@ const initialState = { userProfile: {}, loginUserProfile: {}, role: null, - selectedRole: null, - selectedSubUser: null, - subUsers: [], isFirstLogin: true, userPath: "https://habackend.rasadyar.com/", }; @@ -33,9 +30,6 @@ export const { SET_USER_PATH, SET_ADMIN_TOKEN, SET_TYPE_ACTIVITY_SELECTED, - SET_SELECTED_ROLE, - SET_SELECTED_SUB_USER, - SET_SUB_USERS, } = slice.actions; // export default slice.reducer; export const { reducer: userSlice } = slice; diff --git a/src/pages/AcessDashboardV2.js b/src/pages/AcessDashboardV2.js deleted file mode 100644 index 2a62914..0000000 --- a/src/pages/AcessDashboardV2.js +++ /dev/null @@ -1,1434 +0,0 @@ -import React, { useContext, useEffect, useState } from "react"; -import { - Grid, - Card, - Chip, - Divider, - Box, - Typography, - IconButton, - Tooltip, - Dialog, - DialogTitle, - DialogContent, - Button, - Select, - MenuItem, - FormControl, - InputLabel, - Skeleton, -} from "@mui/material"; -import { useNavigate } from "react-router-dom"; -import { useDispatch, useSelector } from "react-redux"; -import { getRoleItems } from "../utils/getRolesItems"; -import { getFaUserRole } from "../utils/getFaUserRole"; -import { sortRoles } from "../utils/sortRoles"; -import { getUserProfile } from "../features/authentication/services/getUserProfile"; -import { getUserRoleInfo } from "../features/authentication/services/getUserRoleInfo"; -import { AppContext } from "../contexts/AppContext"; -import { getLiveStockItems } from "../utils/getLivestock"; -import { - getBarSquareRoles, - getLiveStockRoles, - getPoultryRoles, - getUserTypeOfActivity, -} from "../utils/getUserTypeOfActivity"; - -import { - SET_SELECTED_ROLE, - SET_SELECTED_SUB_USER, - SET_SUB_USERS, -} from "../lib/redux/slices/userSlice"; -import { getBarSquareItems } from "../utils/getBarSquareItems"; -import { trackItemClick } from "../utils/usageTracker"; -import { - applyCustomOrder, - saveRoleCustomOrder, - reorderArray, -} from "../utils/dashboardCustomization"; -import EditIcon from "@mui/icons-material/Edit"; -import SaveIcon from "@mui/icons-material/Save"; -import { Check, OpenWith } from "@mui/icons-material"; -import FolderOffIcon from "@mui/icons-material/FolderOff"; -import { SlaughterBalanceStatusButton } from "../features/slaughter-house/components/slaughter-balance-status-button/SlaughterBalanceStatusButton"; - -const AccessDashboardV2 = () => { - const [openNotif] = useContext(AppContext); - const navigate = useNavigate(); - const userRoles = useSelector((state) => state.userSlice.role); - const { - typeActivitySelected, - selectedRole, - userProfile, - loginUserProfile, - subUsers: reduxSubUsers, - selectedSubUser: reduxSelectedSubUser, - } = useSelector((state) => state.userSlice); - const dispatch = useDispatch(); - - const [editModes, setEditModes] = useState({}); - - const [draggedItems, setDraggedItems] = useState({}); - - const [draggingCardIndex, setDraggingCardIndex] = useState(null); - - const [roleSelectionModalOpen, setRoleSelectionModalOpen] = useState(false); - const [selectedRoleLocal, setSelectedRoleLocal] = useState(selectedRole); - const [subUsers, setSubUsers] = useState([]); - const [selectedSubUser, setSelectedSubUser] = useState(null); - const [isLoading, setIsLoading] = useState(false); - - useEffect(() => { - dispatch(getUserProfile()); - }, []); - - useEffect(() => { - if (userRoles && userRoles.length > 0 && !selectedRole) { - if (userRoles.length === 1) { - const role = userRoles[0]; - dispatch(SET_SELECTED_ROLE(role)); - setSelectedRoleLocal(role); - setRoleSelectionModalOpen(false); - - const rolesNeedingSubUsers = ["Steward", "KillHouse", "Guilds"]; - if (rolesNeedingSubUsers.includes(role)) { - const userKey = userProfile?.key || loginUserProfile?.key; - if (userKey && role) { - dispatch(getUserRoleInfo({ userKey, role })).catch((error) => { - console.error("Error fetching user role info:", error); - }); - } - } - } else { - setRoleSelectionModalOpen(true); - } - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [userRoles, selectedRole]); - - useEffect(() => { - if (selectedRole) { - const rolesNeedingSubUsers = ["Steward", "KillHouse", "Guilds"]; - if (rolesNeedingSubUsers.includes(selectedRole)) { - if (reduxSubUsers && reduxSubUsers.length > 0) { - const subUsersKeys = subUsers.map((u) => u?.key).join(","); - const reduxSubUsersKeys = reduxSubUsers.map((u) => u?.key).join(","); - if (subUsersKeys !== reduxSubUsersKeys) { - setSubUsers(reduxSubUsers); - } - - if (reduxSelectedSubUser) { - if (selectedSubUser?.key !== reduxSelectedSubUser?.key) { - setSelectedSubUser(reduxSelectedSubUser); - } - } else if (reduxSubUsers.length > 0) { - const firstSubUser = reduxSubUsers[0]; - if (selectedSubUser?.key !== firstSubUser?.key) { - setSelectedSubUser(firstSubUser); - dispatch(SET_SELECTED_SUB_USER(firstSubUser)); - } - } - setIsLoading(false); - } else { - if (subUsers.length > 0 || selectedSubUser) { - setSubUsers([]); - setSelectedSubUser(null); - } - setIsLoading(true); - } - } else { - if (subUsers.length > 0 || selectedSubUser) { - setSubUsers([]); - setSelectedSubUser(null); - dispatch(SET_SUB_USERS([])); - } - setIsLoading(false); - } - } else { - if (subUsers.length > 0 || selectedSubUser) { - setSubUsers([]); - setSelectedSubUser(null); - dispatch(SET_SUB_USERS([])); - } - setIsLoading(false); - } - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [selectedRole, reduxSubUsers, reduxSelectedSubUser]); - - const getInitialSelection = () => { - if (typeActivitySelected) { - return typeActivitySelected; - } - if (getUserTypeOfActivity(userRoles) === "LiveStock") { - return "Livestock"; - } - return "Poultry"; - }; - - const [selected] = useState(getInitialSelection()); - - const handleRoleSelection = async (role) => { - setSelectedRoleLocal(role); - dispatch(SET_SELECTED_ROLE(role)); - setRoleSelectionModalOpen(false); - - setSubUsers([]); - setSelectedSubUser(null); - dispatch(SET_SUB_USERS([])); - - const rolesNeedingSubUsers = ["Steward", "KillHouse", "Guilds"]; - if (rolesNeedingSubUsers.includes(role)) { - setIsLoading(true); - const userKey = userProfile?.key || loginUserProfile?.key; - if (userKey && role) { - try { - await dispatch(getUserRoleInfo({ userKey, role })).unwrap(); - } catch (error) { - console.error("Error fetching user role info:", error); - setIsLoading(false); - openNotif({ - vertical: "top", - horizontal: "center", - msg: "خطا در دریافت اطلاعات نقش کاربر", - severity: "error", - }); - } - } else { - setIsLoading(false); - } - } - }; - - const handleSubUserChange = (event) => { - const subUserKey = event.target.value; - const subUser = subUsers.find((u) => u.key === subUserKey); - setSelectedSubUser(subUser); - dispatch(SET_SELECTED_SUB_USER(subUser)); - - setIsLoading(true); - setTimeout(() => { - setIsLoading(false); - }, 1000); - }; - - const handleCardClick = (roleItem, role) => { - if (editModes[role]) return; - - if (roleItem?.disabled) { - openNotif({ - vertical: "top", - horizontal: "center", - msg: roleItem.disabledText || "این بخش در دست توسعه است !", - severity: "error", - }); - } else { - trackItemClick(role, roleItem.route); - navigate(roleItem.route); - } - }; - - const toggleEditMode = (role, items) => { - const isEnteringEditMode = !editModes[role]; - - if (isEnteringEditMode) { - setEditModes({ ...editModes, [role]: true }); - setDraggedItems({ ...draggedItems, [role]: items }); - } else { - saveRoleCustomOrder(role, draggedItems[role]); - setEditModes({ ...editModes, [role]: false }); - openNotif({ - vertical: "top", - horizontal: "center", - msg: "ترتیب کارت‌ها ذخیره شد", - severity: "success", - }); - } - }; - - const handleCardMouseDown = (index) => { - setDraggingCardIndex(index); - }; - - const handleCardMouseUp = () => { - setDraggingCardIndex(null); - }; - - const handleDragStart = (e, index) => { - e.dataTransfer.effectAllowed = "move"; - e.dataTransfer.setData("text/html", index); - setDraggingCardIndex(index); - }; - - const handleDragOver = (e) => { - e.preventDefault(); - e.dataTransfer.dropEffect = "move"; - }; - - const handleDrop = (e, role, dropIndex) => { - e.preventDefault(); - const dragIndex = parseInt(e.dataTransfer.getData("text/html")); - - if (dragIndex === dropIndex) return; - - const currentItems = draggedItems[role] || []; - const reorderedItems = reorderArray(currentItems, dragIndex, dropIndex); - - setDraggedItems({ ...draggedItems, [role]: reorderedItems }); - }; - - const handleDragEnd = () => { - setDraggingCardIndex(null); - }; - - const getItemsForRole = (items, role) => { - if (editModes[role] && draggedItems[role]) { - return draggedItems[role]; - } - - return applyCustomOrder(items, role); - }; - - function renderSkeletonCards(count = 6) { - return ( - - {Array.from({ length: count }).map((_, i) => ( - - - - - {Array.from({ length: 6 }).map((_, idx) => ( - - - - ))} - - - - ))} - - ); - } - - const renderContent = () => { - if (!selectedRole) { - return null; - } - - const filteredRoles = - userRoles?.filter((role) => role === selectedRole) || []; - - if (selected === "Poultry") { - return renderPoultrySection(filteredRoles); - } - if (selected === "Livestock") { - return renderLivestockSection(filteredRoles); - } - return renderBarSquareSection(filteredRoles); - }; - - const sortRolesByPriority = (roles) => { - const priorityOrder = [ - "SuperAdmin", - "AdminX", - "Admin", - "ProvinceOperator", - "ProvincialGovernment", - "Jahad", - "LiveStockProvinceJahad", - "CityJahad", - "ProvinceFinancial", - "Commerce", - "CityCommerce", - "KillHouse", - "Guilds", - "Steward", - "ColdHouseSteward", - "GuildRoom", - "CityGuild", - "VetSupervisor", - "KillHouseVet", - "VetFarm", - "CityVet", - "ParentCompany", - "ChainCompany", - "PosCompany", - "ProvinceSupervisor", - "ProvinceInspector", - "Observatory", - "CityOperator", - "CityPoultry", - "UnitWindow", - "Union", - "Cooperative", - "Rancher", - "LiveStockSupport", - "Poultry", - "PoultryScience", - "Dispenser", - "Supporter", - "Driver", - ]; - - return [...roles].sort((a, b) => { - const aIndex = priorityOrder.indexOf(a); - const bIndex = priorityOrder.indexOf(b); - if (aIndex !== -1 && bIndex !== -1) { - return aIndex - bIndex; - } - if (aIndex !== -1) return -1; - if (bIndex !== -1) return 1; - return a.localeCompare(b); - }); - }; - - const getRolePageCount = (role) => { - const roleItems = getRoleItems(role) || []; - const liveStockItems = getLiveStockItems(role) || []; - return roleItems.length + liveStockItems.length; - }; - - const availableRoles = userRoles ? sortRolesByPriority(userRoles) : []; - - return ( - <> - {availableRoles.length > 1 && ( - {}} - disableEscapeKeyDown - PaperProps={{ - sx: { - width: "670px", - maxWidth: "90vw", - }, - }} - > - انتخاب نقش کاربر - - - لطفاً نقش خود را انتخاب کنید: - - - {availableRoles.map((role) => ( - - - - - - ))} - - - - )} - - - - - - - {availableRoles.length > 1 && ( - - نقش - - - )} - - {subUsers.length > 1 && ( - - - {selectedRole === "Steward" - ? "مباشر" - : selectedRole === "Guilds" - ? "صنف" - : "کشتارگاه"} - - - - )} - - {userRoles && userRoles.includes("KillHouse") && ( - - )} - - - {renderContent()} - - - - ); - - function renderPoultrySection(filteredRoles = userRoles) { - const poultryRoles = getPoultryRoles(filteredRoles); - if (isLoading) { - return renderSkeletonCards(poultryRoles?.length || 1); - } - - if (!poultryRoles || poultryRoles.length === 0) { - return ( - - - - - هیچ دسترسی برای این نقش وجود ندارد - - - - ); - } - - return ( - - {sortRoles(poultryRoles)?.map((item, i) => ( - - - - - - toggleEditMode( - item, - getItemsForRole(getRoleItems(item), item) - ) - } - sx={{ - position: "absolute", - top: 2, - right: 0, - zIndex: 10, - backgroundColor: editModes[item] - ? "success.main" - : "primary.main", - color: "white", - "&:hover": { - backgroundColor: editModes[item] - ? "success.dark" - : "primary.dark", - }, - width: 24, - height: 24, - }} - size="small" - > - {editModes[item] ? ( - - ) : ( - - )} - - - - - - - - - - {getItemsForRole(getRoleItems(item), item)?.map( - (roleItem, index) => ( - - - editModes[item] && handleDragStart(e, index) - } - onDragEnd={handleDragEnd} - onDragOver={(e) => editModes[item] && handleDragOver(e)} - onDrop={(e) => - editModes[item] && handleDrop(e, item, index) - } - onMouseDown={() => - editModes[item] && handleCardMouseDown(index) - } - onMouseUp={handleCardMouseUp} - onTouchStart={() => - editModes[item] && handleCardMouseDown(index) - } - onTouchEnd={handleCardMouseUp} - sx={{ - width: "100%", - aspectRatio: "1/1", - borderRadius: "8px", - display: "flex", - alignItems: "center", - justifyContent: "center", - textAlign: "center", - cursor: editModes[item] ? "move" : "pointer", - transition: - "transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out", - position: "relative", - backgroundSize: "cover", - backgroundPosition: "center", - color: (theme) => theme.palette.primary.main, - borderStyle: "solid", - borderWidth: "1px", - borderColor: (theme) => theme.palette.primary.main, - opacity: editModes[item] ? 0.9 : 1, - "&:hover": { - transform: editModes[item] - ? "scale(1.02)" - : "scale(1.05)", - boxShadow: "0 4px 12px rgba(0,0,0,0.15)", - backgroundColor: (theme) => - theme.palette.primary.light, - }, - }} - onClick={() => handleCardClick(roleItem, item)} - > - {editModes[item] && ( - - - - )} - - {roleItem.icon && ( - - {React.cloneElement(roleItem.icon, { - sx: { - fontSize: { - xs: "2rem", - sm: "2.5rem", - xxl: "2.8rem", - xxxl: "3.2rem", - }, - }, - })} - - )} - theme.palette.primary.dark, - }} - > - {roleItem.text} - - - - - ) - )} - - - - ))} - - ); - } - - function renderLivestockSection(filteredRoles = userRoles) { - const livestockRoles = getLiveStockRoles(filteredRoles); - if (isLoading) { - return renderSkeletonCards(livestockRoles?.length || 1); - } - - if (!livestockRoles || livestockRoles.length === 0) { - return ( - - - - - هیچ صفحه‌ای برای این نقش وجود ندارد - - - - ); - } - - return ( - - {sortRoles(livestockRoles)?.map((item, i) => ( - - - - - - toggleEditMode( - item, - getItemsForRole(getLiveStockItems(item), item) - ) - } - sx={{ - position: "absolute", - top: -8, - right: 8, - zIndex: 10, - backgroundColor: editModes[item] - ? "success.main" - : "primary.main", - color: "white", - "&:hover": { - backgroundColor: editModes[item] - ? "success.dark" - : "primary.dark", - }, - width: 32, - height: 32, - }} - size="small" - > - {editModes[item] ? ( - - ) : ( - - )} - - - - - - - - - - {getItemsForRole(getLiveStockItems(item), item)?.map( - (roleItem, index) => ( - - - editModes[item] && handleDragStart(e, index) - } - onDragEnd={handleDragEnd} - onDragOver={(e) => editModes[item] && handleDragOver(e)} - onDrop={(e) => - editModes[item] && handleDrop(e, item, index) - } - onMouseDown={() => - editModes[item] && handleCardMouseDown(index) - } - onMouseUp={handleCardMouseUp} - onTouchStart={() => - editModes[item] && handleCardMouseDown(index) - } - onTouchEnd={handleCardMouseUp} - sx={{ - width: "100%", - aspectRatio: "1/1", - borderRadius: "8px", - display: "flex", - alignItems: "center", - justifyContent: "center", - textAlign: "center", - cursor: editModes[item] ? "move" : "pointer", - transition: - "transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out", - position: "relative", - backgroundSize: "cover", - backgroundPosition: "center", - color: (theme) => theme.palette.info.main, - borderStyle: "solid", - borderWidth: "1px", - borderColor: (theme) => theme.palette.primary.main, - opacity: editModes[item] ? 0.9 : 1, - "&:hover": { - transform: editModes[item] - ? "scale(1.02)" - : "scale(1.05)", - boxShadow: "0 4px 12px rgba(0,0,0,0.15)", - backgroundColor: (theme) => - theme.palette.primary.light, - }, - }} - onClick={() => handleCardClick(roleItem, item)} - > - {editModes[item] && ( - - - - )} - - {roleItem.icon && ( - - {React.cloneElement(roleItem.icon, { - sx: { - fontSize: { - xs: "2rem", - sm: "2.5rem", - }, - }, - })} - - )} - theme.palette.primary.dark, - }} - > - {roleItem.text} - - - - - ) - )} - - - - ))} - - ); - } - - function renderBarSquareSection(filteredRoles = userRoles) { - const barSquareRoles = getBarSquareRoles(filteredRoles); - if (isLoading) { - return renderSkeletonCards(barSquareRoles?.length || 1); - } - - if (!barSquareRoles || barSquareRoles.length === 0) { - return ( - - - - - هیچ صفحه‌ای برای این نقش وجود ندارد - - - - ); - } - - return ( - - {sortRoles(barSquareRoles)?.map((item, i) => ( - - - - - - toggleEditMode( - item, - getItemsForRole(getBarSquareItems(item), item) - ) - } - sx={{ - position: "absolute", - top: -8, - right: 8, - zIndex: 10, - backgroundColor: editModes[item] - ? "success.main" - : "primary.main", - color: "white", - "&:hover": { - backgroundColor: editModes[item] - ? "success.dark" - : "primary.dark", - }, - width: 32, - height: 32, - }} - size="small" - > - {editModes[item] ? ( - - ) : ( - - )} - - - - - - - - - - {getItemsForRole(getBarSquareItems(item), item)?.map( - (roleItem, index) => ( - - - editModes[item] && handleDragStart(e, index) - } - onDragEnd={handleDragEnd} - onDragOver={(e) => editModes[item] && handleDragOver(e)} - onDrop={(e) => - editModes[item] && handleDrop(e, item, index) - } - onMouseDown={() => - editModes[item] && handleCardMouseDown(index) - } - onMouseUp={handleCardMouseUp} - onTouchStart={() => - editModes[item] && handleCardMouseDown(index) - } - onTouchEnd={handleCardMouseUp} - onClick={() => handleCardClick(roleItem, item)} - sx={{ - width: "100%", - aspectRatio: "1/1", - borderRadius: "8px", - display: "flex", - alignItems: "center", - justifyContent: "center", - textAlign: "center", - cursor: editModes[item] ? "move" : "pointer", - transition: - "transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out", - position: "relative", - backgroundSize: "cover", - backgroundPosition: "center", - color: "orange", - borderStyle: "solid", - borderWidth: "1px", - borderColor: (theme) => theme.palette.primary.main, - opacity: editModes[item] ? 0.9 : 1, - "&:hover": { - transform: editModes[item] - ? "scale(1.02)" - : "scale(1.05)", - boxShadow: "0 4px 12px rgba(0,0,0,0.15)", - backgroundColor: (theme) => - theme.palette.primary.light, - }, - }} - > - - {roleItem.icon && ( - - {React.cloneElement(roleItem.icon, { - sx: { - fontSize: { - xs: "2rem", - sm: "2.5rem", - lg: "3rem", - }, - }, - })} - - )} - theme.palette.primary.dark, - }} - > - {roleItem.text} - - - - - ) - )} - - - - ))} - - ); - } -}; - -export default AccessDashboardV2; diff --git a/src/pages/DashboardPage.js b/src/pages/DashboardPage.js index 063290a..248f0da 100644 --- a/src/pages/DashboardPage.js +++ b/src/pages/DashboardPage.js @@ -8,23 +8,27 @@ import { ROUTE_SUPER_ADMIN_DASHBOARD, } from "../routes/routes"; import { DashboardTab } from "../features/dashboard/components/dashboard-tab/DashboardTab"; -import { BackButton } from "../components/back-button/BackButton"; const DashboardPage = () => { const { pathname } = useLocation(); return ( - - - - {(pathname.includes(ROUTE_ADMINX_DASHBOARD) || - pathname.includes(ROUTE_SUPER_ADMIN_DASHBOARD) || - pathname.includes(ROUTE_PROVINCE_DASHBOARD) || - pathname.includes(ROUTE_PROVINCE_SUPERVISOR_DASHBOARD)) && ( - - )} - - + <> + + + {(pathname.includes(ROUTE_ADMINX_DASHBOARD) || + pathname.includes(ROUTE_SUPER_ADMIN_DASHBOARD) || + pathname.includes(ROUTE_PROVINCE_DASHBOARD) || + pathname.includes(ROUTE_PROVINCE_SUPERVISOR_DASHBOARD)) && ( + + )} + + {/* + + */} + + + ); }; diff --git a/src/pages/DiffrenceKillerPage.js b/src/pages/DiffrenceKillerPage.js index 5454b21..e69f8ad 100644 --- a/src/pages/DiffrenceKillerPage.js +++ b/src/pages/DiffrenceKillerPage.js @@ -1,4 +1,4 @@ -import { Box } from "@mui/material"; +import { Box, Typography } from "@mui/material"; import { useLocation } from "react-router-dom"; import { Grid } from "../components/grid/Grid"; import { SPACING } from "../data/spacing"; @@ -26,18 +26,24 @@ const DiffrenceKillerPage = () => { return ( <> - - - - + + + + {pathname === ROUTE_ADMINX_DIFFRENCE_KILLER || pathname === ROUTE_SUPER_ADMIN_DIFFRENCE_KILLER || pathname === ROUTE_CITY_DIFFRENCE_KILLER || pathname === ROUTE_PROVINCE_DIFFRENCE_KILLER ? ( <> {" "} - - + + + اختلاف کشتار + @@ -46,7 +52,7 @@ const DiffrenceKillerPage = () => { )} - + {(pathname.includes(ROUTE_ADMINX_DIFFRENCE_KILLER_SLAUGHTER) || pathname.includes(ROUTE_SUPER_ADMIN_DIFFRENCE_KILLER_SLAUGHTER) || pathname.includes(ROUTE_PROVINCE_DIFFRENCE_KILLER_SLAUGHTER) || diff --git a/src/pages/GeneralDashboard.js b/src/pages/GeneralDashboard.js index e89c5a5..470363f 100644 --- a/src/pages/GeneralDashboard.js +++ b/src/pages/GeneralDashboard.js @@ -36,7 +36,7 @@ import { CityVetProfile } from "../features/city-vet/components/CityVetProfile"; import LiveStockProfile from "../features/live-stock-support/components/live-stock-profile/LiveStockProfile"; import { ChainCompanyProfile } from "../features/chain-company/components/chain-company-profile/ChainCompanyProfile"; import { BackButton } from "../components/back-button/BackButton"; -import AccessDashboardV2 from "./AcessDashboardV2"; +import AccessDashboard from "./AccessDashboard"; const GeneralDashboard = () => { const { pathname } = useLocation(); @@ -77,8 +77,8 @@ const GeneralDashboard = () => { )} {pathname === "/" ? ( - - + + ) : ( diff --git a/src/pages/ProvinceManageStewards.js b/src/pages/ProvinceManageStewards.js deleted file mode 100644 index ce75e00..0000000 --- a/src/pages/ProvinceManageStewards.js +++ /dev/null @@ -1,92 +0,0 @@ -import { SPACING } from "../data/spacing"; -import { NavLink } from "../components/nav-link/NavLink"; -import { useLocation } from "react-router-dom"; - -import LinkItem from "../components/link-item/LinkItem"; -import { MdCorporateFare } from "react-icons/md"; -import { BackButton } from "../components/back-button/BackButton"; -import { Grid } from "../components/grid/Grid"; -import { - ROUTE_ADMINX_ROUTE_MANAGE_STEWARDS, - ROUTE_PROVINCE_SUPERVISOR_ROUTE_MANAGE_STEWARDS, - ROUTE_SUPER_ADMIN_ROUTE_MANAGE_STEWARDS, -} from "../routes/routes"; - -const ProvinceManageStewards = () => { - const { pathname } = useLocation(); - - return ( - <> - {["reza"].includes(pathname) && } - - - {(ROUTE_ADMINX_ROUTE_MANAGE_STEWARDS === pathname || - ROUTE_SUPER_ADMIN_ROUTE_MANAGE_STEWARDS === pathname || - ROUTE_PROVINCE_SUPERVISOR_ROUTE_MANAGE_STEWARDS === pathname) && ( - <> - - } - title="مباشرین داخل استان" - /> - - - } - title="مباشرین خارج استان" - /> - - - )} - {["reza"].includes(pathname) && ( - <> - - } - title="درخواست های ثبت صنف" - /> - - - } - title="اصناف حقیقی" - /> - - - } - title="اصناف حقوقی" - /> - - - )} - - {["reza"].includes(pathname) && ( - <> - - } - title="اصناف حقیقی" - /> - - - } - title="اصناف حقوقی" - /> - - - )} - - - ); -}; - -export default ProvinceManageStewards; diff --git a/src/pages/ProvinceRequests.js b/src/pages/ProvinceRequests.js index 5b398ec..2fedbc5 100644 --- a/src/pages/ProvinceRequests.js +++ b/src/pages/ProvinceRequests.js @@ -78,7 +78,15 @@ const ProvinceRequests = () => { return ( - + {pathname === ROUTE_PROVINCE_REQUESTS || pathname === ROUTE_SUPER_ADMIN_REQUESTS || pathname === ROUTE_ADMINX_REQUESTS ? ( diff --git a/src/pages/PspCompany.js b/src/pages/PspCompany.js index 8c6a87b..0492276 100644 --- a/src/pages/PspCompany.js +++ b/src/pages/PspCompany.js @@ -6,15 +6,15 @@ import { ROUTE_PSP_COMPANY_ROUTE_ACTIVE_SESSION, ROUTE_PSP_COMPANY_ROUTE_GUILDS, ROUTE_PSP_COMPANY_ROUTE_DEVICES, + ROUTE_PSP_ROUTE_COMPANY_MANAGE_STEWARDS, + ROUTE_SUPER_ADMIN_ROUTE_COMPANY_MANAGE_STEWARDS, + ROUTE_ADMINX_ROUTE_COMPANY_MANAGE_STEWARDS, ROUTE_SUPER_ADMIN_COMPANY_ROUTE_GUILDS, ROUTE_ADMINX_COMPANY_ROUTE_GUILDS, ROUTE_SUPER_ADMIN_COMPANY_ROUTE_ACTIVE_SESSION, ROUTE_ADMINX_COMPANY_ROUTE_ACTIVE_SESSION, ROUTE_SUPER_ADMIN_COMPANY_ROUTE_DEVICES, ROUTE_ADMINX_COMPANY_ROUTE_DEVICES, - ROUTE_ADMINX_ROUTE_PSP_COMPANIES, - ROUTE_SUPER_ADMIN_ROUTE_PSP_COMPANIES, - ROUTE_PSP_ROUTE_COMPANY_PSP_COMPANIES, } from "../routes/routes"; import { BackButton } from "../components/back-button/BackButton"; import { PspOperations } from "../features/psp-company/components/psp-operations/PspOperations"; @@ -37,9 +37,9 @@ const PspCompanyManagement = () => { lg={10} > {[ - ROUTE_PSP_ROUTE_COMPANY_PSP_COMPANIES, - ROUTE_SUPER_ADMIN_ROUTE_PSP_COMPANIES, - ROUTE_ADMINX_ROUTE_PSP_COMPANIES, + ROUTE_PSP_ROUTE_COMPANY_MANAGE_STEWARDS, + ROUTE_SUPER_ADMIN_ROUTE_COMPANY_MANAGE_STEWARDS, + ROUTE_ADMINX_ROUTE_COMPANY_MANAGE_STEWARDS, ].includes(pathname) ? ( diff --git a/src/pages/SenfInventoryPage.js b/src/pages/SenfInventoryPage.js index e946b90..b0e4ff2 100644 --- a/src/pages/SenfInventoryPage.js +++ b/src/pages/SenfInventoryPage.js @@ -1,4 +1,4 @@ -import { Box } from "@mui/material"; +import { Box, Typography } from "@mui/material"; import { Grid } from "../components/grid/Grid"; import { SPACING } from "../data/spacing"; import { useLocation } from "react-router-dom"; @@ -6,49 +6,47 @@ import { BackButton } from "../components/back-button/BackButton"; import { SenfInventoryOperation } from "../features/senf/components/SenfInventoryOperation"; import { ROUTE_SENF_INVENTORY, - ROUTE_SENF_INVENTORY_ENTER, - ROUTE_SENF_INVENTORY_SEGMENTATION, ROUTE_SENF_INVENTORY_STOCK, } from "../routes/routes"; import { SenfStock } from "../features/senf/components/SenfStock"; -import { SenfSegmentaion } from "../features/senf/components/SenfSegmentaion"; -import { SenfEnterToWarehouse } from "../features/senf/components/SenfEnterToWarehouse"; const SenfInventoryPage = () => { const { pathname } = useLocation(); return ( - - - - {pathname === ROUTE_SENF_INVENTORY && ( - - - - )} - {pathname.includes(ROUTE_SENF_INVENTORY_STOCK) && } - {pathname.includes(ROUTE_SENF_INVENTORY_SEGMENTATION) && ( - - )} - {pathname.includes(ROUTE_SENF_INVENTORY_ENTER) && ( - - )} - - + <> + + + {pathname === ROUTE_SENF_INVENTORY ? ( + + + + مدیریت انبار + + + + + ) : ( + + )} + {pathname.includes(ROUTE_SENF_INVENTORY_STOCK) && } + + + ); }; diff --git a/src/pages/SlaughterHouseDispenserDashboard.js b/src/pages/SlaughterHouseDispenserDashboard.js index 892d969..2933d87 100644 --- a/src/pages/SlaughterHouseDispenserDashboard.js +++ b/src/pages/SlaughterHouseDispenserDashboard.js @@ -3,12 +3,10 @@ import React from "react"; import { Grid } from "../components/grid/Grid"; import { useLocation, useParams } from "react-router-dom"; import { - ROUTE_ADMINX_DELEGATES_MANAGEMENT, ROUTE_ADMINX_DISPENSERS, ROUTE_ADMINX_DISPENSERS_INVENTORY, ROUTE_ADMINX_DISPENSERS_KILLHOUSES, ROUTE_ADMINX_DISPENSERS_MANAGEMENT, - ROUTE_ADMINX_DISPENSERS_MANAGEMENT_V2, ROUTE_ADMINX_DISPENSERS_SELL_CARCASS, ROUTE_ADMINX_DISPENSERS_STEWARDS, ROUTE_ADMINX_DISPENSER_DETAILS, @@ -69,8 +67,6 @@ import { ProvinceDispensersSellCarcass } from "../features/province/components/p import { ProvinceDispensersKillhouses } from "../features/province/components/province-dispensers-killhouses/ProvinceDispensersKillhouses"; import { ProvinceDispensersViewKillHouse } from "../features/province/components/province-dispensers-view-killhouse/ProvinceDispensersViewKillHouse"; import { ProvinceDispencerSaleDistribution } from "../features/province/components/province-dispencer-sale-distribution/ProvinceDispencerSaleDistribution"; -import { SlaughterHouseDispensersV2 } from "../features/slaughter-house/components/slaughter-house-dispensers-v2/SlaughterHouseDispensers"; -import { SlaughterHouseDelegates } from "../features/slaughter-house/components/slaughter-house-delegates/SlaughterHouseDelegates"; // import { ProvinceDispencerSaleDistribution } from "../features/province/components/province-dispencer-sale-distribution/ProvinceDispencerSaleDistribution"; const DashboardTitle = () => ( @@ -145,15 +141,7 @@ const renderComponentBasedOnPath = (pathname) => { ROUTE_PROVINCE_SUPERVISOR_REQUEST_DISTRIBUTION, ]; - const managementRoutesV2 = [ROUTE_ADMINX_DISPENSERS_MANAGEMENT_V2]; - - const managementRoutesDelegates = [ROUTE_ADMINX_DELEGATES_MANAGEMENT]; - if (managementRoutes.includes(pathname)) return ; - if (managementRoutesV2.includes(pathname)) - return ; - if (managementRoutesDelegates.includes(pathname)) - return ; if (distribution.includes(pathname)) return ; if (detailsRoutes.some((route) => pathname.includes(route))) diff --git a/src/pages/SlaughterInventoryPage.js b/src/pages/SlaughterInventoryPage.js index 66b436a..be7a2f4 100644 --- a/src/pages/SlaughterInventoryPage.js +++ b/src/pages/SlaughterInventoryPage.js @@ -31,8 +31,8 @@ import WarehouseIcon from "@mui/icons-material/Warehouse"; import StoreIcon from "@mui/icons-material/Store"; import PublicIcon from "@mui/icons-material/Public"; import ContentCutIcon from "@mui/icons-material/ContentCut"; +import ListAltIcon from "@mui/icons-material/ListAlt"; import { SlaughterFreeBuyBars } from "../features/slaughter-house/components/slaughter-free-buy-bars/SlaughterFreeBuyBars"; -import { checkPathStartsWith } from "../utils/checkPathStartsWith"; // import { Grading } from "@mui/icons-material"; const SlaughterInventoryPage = () => { @@ -41,33 +41,13 @@ const SlaughterInventoryPage = () => { const { distributionInfo, priceInfo } = useSelector( (state) => state.slaughterSlice ); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); useEffect(() => { - if ( - [ - ROUTE_SLAUGHTER_INVENTORY, - ROUTE_SLAUGHTER_INVENTORY_SELL_CARCASS_OUT_PROVINCE, - ].includes(pathname) - ) { - dispatch( - fetchSlaughterBroadcastAndProducts({ - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) - ); - dispatch( - getKillhouseApprovedPriceState({ - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) - ); + if (pathname === ROUTE_SLAUGHTER_INVENTORY) { + dispatch(fetchSlaughterBroadcastAndProducts()); + dispatch(getKillhouseApprovedPriceState()); } - }, [pathname, selectedSubUser?.key]); + }, [pathname]); return ( <> @@ -98,7 +78,7 @@ const SlaughterInventoryPage = () => { mt={SPACING.MEDIUM} xs={12} alignItems="center" - width="1040px" + width="900px" mx="auto" > {/* diff --git a/src/pages/SlaughterMorgue.js b/src/pages/SlaughterMorgue.js index 8929c93..b0a4e68 100644 --- a/src/pages/SlaughterMorgue.js +++ b/src/pages/SlaughterMorgue.js @@ -2,7 +2,7 @@ import React, { useEffect, useState } from "react"; import { Grid } from "../components/grid/Grid"; import { Box, IconButton } from "@mui/material"; import ResponsiveTable from "../components/responsive-table/ResponsiveTable"; -import { useDispatch, useSelector } from "react-redux"; +import { useDispatch } from "react-redux"; import { slaughterGetMorgueDashboardService, slaughterGetMorguesService, @@ -12,28 +12,19 @@ import { SlaughterMorgueView } from "../features/slaughter-house/components/slau import { ROUTE_SLAUGHTER_MORGUE } from "../routes/routes"; import { BackButton } from "../components/back-button/BackButton"; import VisibilityIcon from "@mui/icons-material/Visibility"; -import { checkPathStartsWith } from "../utils/checkPathStartsWith"; const SlaughterMorgue = () => { const dispatch = useDispatch(); const [dashboardData, setDashboardData] = useState([]); const [tableData, setTableData] = useState([]); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); + const navigate = useNavigate(); const { key } = useParams(); useEffect(() => { if (!key) { - dispatch( - slaughterGetMorgueDashboardService({ - role_key: checkPathStartsWith("slaughter") - ? selectedSubUser?.key || "" - : "", - }) - ).then((r) => { + dispatch(slaughterGetMorgueDashboardService()).then((r) => { setDashboardData(r.payload.data); }); dispatch(slaughterGetMorguesService()).then((r) => { @@ -58,7 +49,7 @@ const SlaughterMorgue = () => { setTableData(d); }); } - }, [dispatch, key, selectedSubUser?.key]); + }, [dispatch, key]); return ( <> @@ -72,10 +63,9 @@ const SlaughterMorgue = () => { md={10} lg={10} > - {!key ? ( - + { ) : ( + )} diff --git a/src/pages/SlaughterSubUnits.js b/src/pages/SlaughterSubUnits.js deleted file mode 100644 index 38402b8..0000000 --- a/src/pages/SlaughterSubUnits.js +++ /dev/null @@ -1,66 +0,0 @@ -import { Box, Grid } from "@mui/material"; -import { BackButton } from "../components/back-button/BackButton"; -import { NavLink } from "../components/nav-link/NavLink"; -import LinkItem from "../components/link-item/LinkItem"; -import { SPACING } from "../data/spacing"; -import { - ROUTE_SLAUGHTER_ROUTE_MANAGE_DISPENSERS, - ROUTE_SLAUGHTER_ROUTE_MANAGE_DELEGATES, - ROUTE_STEWARD_ROUTE_MANAGE_DELEGATES, - ROUTE_STEWARD_ROUTE_MANAGE_DISPENSERS, -} from "../routes/routes"; -import { VscPerson } from "react-icons/vsc"; -import BadgeIcon from "@mui/icons-material/Badge"; -import { getRoleFromUrl } from "../utils/getRoleFromUrl"; - -const SlaughterSubUnits = () => { - return ( - <> - - - - - - } - title="نمایندگان" - description="مدیریت نمایندگان" - /> - - - } - title="توزیع کنندگان" - description="مدیریت توزیع کنندگان" - /> - - - - - - ); -}; - -export default SlaughterSubUnits; diff --git a/src/pages/StewardInventoryPage.js b/src/pages/StewardInventoryPage.js index 27c120d..b4664f5 100644 --- a/src/pages/StewardInventoryPage.js +++ b/src/pages/StewardInventoryPage.js @@ -1,4 +1,4 @@ -import { Box } from "@mui/material"; +import { Box, Typography } from "@mui/material"; import { Grid } from "../components/grid/Grid"; import { SPACING } from "../data/spacing"; import { useLocation } from "react-router-dom"; @@ -24,37 +24,31 @@ import { StewardStock } from "../features/steward/components/steward-stock/Stewa import { StewardPurchaseOutProvince } from "../features/steward/components/steward-purchase-out-province/StewardPurchaseOutProvince"; import { StewardSellOutOfProvince } from "../features/steward/components/steward-sell-out-of-province/StewardSellOutOfProvince"; import { StewardSellInProvince } from "../features/steward/components/steward-sell-in-province/StewardSellInProvince"; -import { checkPathStartsWith } from "../utils/checkPathStartsWith"; const StewardInventoryPage = () => { const { pathname } = useLocation(); const dispatch = useDispatch(); - const selectedSubUser = useSelector( - (state) => state.userSlice.selectedSubUser - ); + const { distributionInfo } = useSelector((state) => state.stewardSlice); useEffect(() => { - if ( - [ - ROUTE_STEWARD_PURCHASE_OUT_PROVINCE, - ROUTE_STEWARD_INVENTORY, - ROUTE_STEWARD_SALE_OUT_PROVINCE, - ].includes(pathname) - ) { - dispatch( - fetchStewardBroadcastAndProducts({ - role_key: checkPathStartsWith("steward") ? selectedSubUser?.key : "", - }) - ); + if (pathname === ROUTE_STEWARD_INVENTORY) { + dispatch(fetchStewardBroadcastAndProducts()); } - }, [dispatch, pathname, selectedSubUser?.key]); + }, [dispatch, pathname]); return ( <> - - - + + {pathname === ROUTE_STEWARD_INVENTORY ? ( { justifyContent="center" alignItems="center" > + + + مدیریت انبار + + + { - ) : null} + ) : ( + + )} {pathname.includes(ROUTE_STEWARD_INVENTORY_STOCK) && } {pathname.includes(ROUTE_STEWARD_SALE_IN_PROVINCE) && ( @@ -172,6 +174,7 @@ const StewardInventoryPage = () => { {pathname.includes(ROUTE_STEWARD_PURCHASE_OUT_PROVINCE) && ( )} + {pathname.includes(ROUTE_STEWARD_DAILY_LIST) && } {pathname.includes(ROUTE_STEWARD_SALE_OUT_PROVINCE) && ( diff --git a/src/routes/managerRouting.js b/src/routes/managerRouting.js index d771085..e560703 100644 --- a/src/routes/managerRouting.js +++ b/src/routes/managerRouting.js @@ -176,25 +176,11 @@ const PoultriesDetails = lazy(() => lazyRetry(() => import("../pages/PoultriesDetailsPage")) ); -const AccessDashboardV2 = lazy(() => - lazyRetry(() => import("../pages/AcessDashboardV2")) -); - const Inspection = lazy(() => lazyRetry(() => import("../pages/Inspection"))); const PspCompany = lazy(() => lazyRetry(() => import("../pages/PspCompany"))); -const ManageStewards = lazy(() => - lazyRetry(() => import("../pages/ProvinceManageStewards")) -); - const consolidatedRouting = [ - { - path: [ROUTES.ROUTE_ADMINX_BASE_NEW_HOME], - Page: AccessDashboardV2, - exact: false, - props: {}, - }, { path: [ROUTES.ROUTE_ADMINX_PROVINCE_SWITCH], Page: AdminXDashboard, @@ -677,8 +663,6 @@ const consolidatedRouting = [ path: [ ROUTES.ROUTE_ADMINX_DISPENSERS, ROUTES.ROUTE_ADMINX_DISPENSERS_MANAGEMENT, - ROUTES.ROUTE_ADMINX_DISPENSERS_MANAGEMENT_V2, - ROUTES.ROUTE_ADMINX_DELEGATES_MANAGEMENT, ROUTES.ROUTE_ADMINX_DISPENSER_DETAILS, ROUTES.ROUTE_ADMINX_DISPENSER_DETAILS_VIEW, ROUTES.ROUTE_ADMINX_DISPENSERS_STEWARDS, @@ -967,11 +951,11 @@ const consolidatedRouting = [ // ROUTE_SUPER_ADMIN_BASE + "/devices"; { path: [ - ROUTES.ROUTE_SUPER_ADMIN_ROUTE_PSP_COMPANIES, + ROUTES.ROUTE_SUPER_ADMIN_ROUTE_COMPANY_MANAGE_STEWARDS, ROUTES.ROUTE_SUPER_ADMIN_COMPANY_ROUTE_GUILDS, ROUTES.ROUTE_SUPER_ADMIN_COMPANY_ROUTE_ACTIVE_SESSION, ROUTES.ROUTE_SUPER_ADMIN_COMPANY_ROUTE_DEVICES, - ROUTES.ROUTE_ADMINX_ROUTE_PSP_COMPANIES, + ROUTES.ROUTE_ADMINX_ROUTE_COMPANY_MANAGE_STEWARDS, ROUTES.ROUTE_ADMINX_COMPANY_ROUTE_GUILDS, ROUTES.ROUTE_ADMINX_COMPANY_ROUTE_ACTIVE_SESSION, ROUTES.ROUTE_ADMINX_COMPANY_ROUTE_DEVICES, @@ -999,16 +983,6 @@ const consolidatedRouting = [ exact: false, props: {}, }, - { - path: [ - ROUTES.ROUTE_ADMINX_ROUTE_MANAGE_STEWARDS, - ROUTES.ROUTE_SUPER_ADMIN_ROUTE_MANAGE_STEWARDS, - ROUTES.ROUTE_PROVINCE_SUPERVISOR_ROUTE_MANAGE_STEWARDS, - ], - Page: ManageStewards, - exact: false, - props: {}, - }, ]; export const getManagerRouting = (role) => { diff --git a/src/routes/posCompanyRouting.js b/src/routes/posCompanyRouting.js index 404d346..bb93a2d 100644 --- a/src/routes/posCompanyRouting.js +++ b/src/routes/posCompanyRouting.js @@ -3,19 +3,12 @@ import { lazyRetry } from "../utils/lazyRetry"; import { ROUTE_PSP_COMPANY_ROUTE_ACTIVE_SESSION, ROUTE_PSP_COMPANY_ROUTE_DEVICES, - ROUTE_PSP_COMPANY_ROUTE_DEVICES_V2, ROUTE_PSP_COMPANY_ROUTE_GUILDS, - ROUTE_PSP_ROUTE_COMPANY_PSP_COMPANIES, + ROUTE_PSP_ROUTE_COMPANY_MANAGE_STEWARDS, } from "./routes"; const Stewards = lazy(() => lazyRetry(() => import("../pages/PspCompany"))); -const PspDevicesV2 = lazy(() => - lazyRetry(() => - import("../features/psp-company/components/psp-devices-v2/PspDevicesV2") - ) -); - // export const ROUTE_PSP_ROUTE_COMPANY_MANAGE_STEWARDS = // ROUTE_PSP_COMPANY_BASE + "/manage-stewards"; @@ -30,7 +23,7 @@ const PspDevicesV2 = lazy(() => export const posCompanyRouting = [ { path: [ - ROUTE_PSP_ROUTE_COMPANY_PSP_COMPANIES, + ROUTE_PSP_ROUTE_COMPANY_MANAGE_STEWARDS, ROUTE_PSP_COMPANY_ROUTE_GUILDS, ROUTE_PSP_COMPANY_ROUTE_ACTIVE_SESSION, ROUTE_PSP_COMPANY_ROUTE_DEVICES, @@ -39,10 +32,4 @@ export const posCompanyRouting = [ exact: false, props: {}, }, - { - path: [ROUTE_PSP_COMPANY_ROUTE_DEVICES_V2], - Page: PspDevicesV2, - exact: false, - props: {}, - }, ]; diff --git a/src/routes/routes.js b/src/routes/routes.js index 91d364a..7b089de 100644 --- a/src/routes/routes.js +++ b/src/routes/routes.js @@ -219,8 +219,6 @@ export const ROUTE_SLAUGHTER_FINAL_FACTORS = ROUTE_SLAUGHTER_BASE + "/requests/final-factors"; export const ROUTE_SLAUGHTER_ROUTE_MANAGE_GUILDS = ROUTE_SLAUGHTER_BASE + "/manage-guilds/"; -export const ROUTE_SLAUGHTER_ROUTE_MANAGE_STEWARDS = - ROUTE_SLAUGHTER_BASE + "/manage-stewards/"; export const ROUTE_SLAUGHTER_ROUTE_MANAGE_BARS = ROUTE_SLAUGHTER_BASE + "/manage-bars/"; export const ROUTE_SLAUGHTER_FINANCIAL_TRANSACTIONS = @@ -251,14 +249,9 @@ export const ROUTE_SLAUGHTER_RETURN_PURCHASES = ROUTE_SLAUGHTER_BASE + "/return-purchases"; export const ROUTE_SLAUGHTER_TRADING_PANEL = ROUTE_SLAUGHTER_BASE + "/requests/trade-panel"; -export const ROUTE_SLAUGHTER_ROUTE_SUB_UNITS = - ROUTE_SLAUGHTER_BASE + "/sub-unit"; export const ROUTE_SLAUGHTER_ROUTE_MANAGE_DISPENSERS = ROUTE_SLAUGHTER_BASE + "/manage-dispensers"; -export const ROUTE_SLAUGHTER_ROUTE_MANAGE_DELEGATES = - ROUTE_SLAUGHTER_BASE + "/manage-delegates"; -export const ROUTE_SLAUGHTER_ROUTE_DEVICES = ROUTE_SLAUGHTER_BASE + "/devices"; // PROVINCE export const ROUTE_PROVINCE_TRADING_PANEL = @@ -316,8 +309,6 @@ export const ROUTE_PROVINCE_ROUTE_ALLOCATIONS = ROUTE_PROVINCE_BASE + "/allocations/"; export const ROUTE_PROVINCE_ROUTE_MANAGE_GUILDS = ROUTE_PROVINCE_BASE + "/manage-guilds/"; -export const ROUTE_PROVINCE_ROUTE_MANAGE_STEWARDS = - ROUTE_PROVINCE_BASE + "/manage-stewards/"; export const ROUTE_PROVINCE_ROUTE_IN_PROVINCE_GUILDS = ROUTE_PROVINCE_BASE + "/manage-guilds/in-province"; export const ROUTE_PROVINCE_ROUTE_OUT_PROVINCE_GUILDS = @@ -714,19 +705,13 @@ export const ROUTE_STEWARD_MANAGE_GUILDS = ROUTE_STEWARD_BASE + "/manage-guilds"; export const ROUTE_STEWARD_DAILY_LIST = ROUTE_STEWARD_BASE + "/dailylist"; export const ROUTE_STEWARD_SEGMENT = ROUTE_STEWARD_BASE + "/segment"; -export const ROUTE_STEWARD_ROUTE_SUB_UNITS = ROUTE_STEWARD_BASE + "/sub-units"; export const ROUTE_STEWARD_ROUTE_MANAGE_DISPENSERS = ROUTE_STEWARD_BASE + "/manage-dispensers"; -export const ROUTE_STEWARD_ROUTE_MANAGE_DELEGATES = - ROUTE_STEWARD_BASE + "/manage-delegates"; -export const ROUTE_STEWARD_ROUTE_DEVICES = ROUTE_STEWARD_BASE + "/devices"; // Commerce export const ROUTE_COMMERCE_REQUESTS = ROUTE_COMMERCE_BASE + "/requests"; export const ROUTE_COMMERCE_ROUTE_MANAGE_GUILDS = ROUTE_COMMERCE_BASE + "/manage-guilds/"; -export const ROUTE_COMMERCE_ROUTE_MANAGE_STEWARDS = - ROUTE_COMMERCE_BASE + "/manage-stewards/"; export const ROUTE_COMMERCE_ROUTE_GUILDS = ROUTE_COMMERCE_BASE + "/manage-guilds/guilds"; export const ROUTE_COMMERCE_ROUTE_STEWARDS = @@ -759,8 +744,6 @@ export const ROUTE_PROVINCE_SUPERVISOR_REQUESTS = ROUTE_PROVINCE_SUPERVISOR_BASE + "/requests"; export const ROUTE_PROVINCE_SUPERVISOR_ROUTE_MANAGE_GUILDS = ROUTE_PROVINCE_SUPERVISOR_BASE + "/manage-guilds/"; -export const ROUTE_PROVINCE_SUPERVISOR_ROUTE_MANAGE_STEWARDS = - ROUTE_PROVINCE_SUPERVISOR_BASE + "/manage-stewards/"; export const ROUTE_PROVINCE_SUPERVISOR_ROUTE_GUILDS = ROUTE_PROVINCE_SUPERVISOR_BASE + "/manage-guilds/guilds"; export const ROUTE_PROVINCE_SUPERVISOR_ROUTE_STEWARDS = @@ -847,8 +830,6 @@ export const ROUTE_PROVINCE_SUPERVISOR_ROUTE_INSPECTION = // CityCommerce export const ROUTE_CITY_COMMERCE_ROUTE_MANAGE_GUILDS = ROUTE_CITY_COMMERCE_BASE + "/manage-guilds/"; -export const ROUTE_CITY_COMMERCE_ROUTE_MANAGE_STEWARDS = - ROUTE_CITY_COMMERCE_BASE + "/manage-stewards/"; export const ROUTE_CITY_COMMERCE_ROUTE_GUILDS = ROUTE_CITY_COMMERCE_BASE + "/manage-guilds/guilds"; export const ROUTE_CITY_COMMERCE_ROUTE_STEWARDS = @@ -876,8 +857,6 @@ export const ROUTE_CITY_JIHAD_ROUTE_ALLOCATIONS = ROUTE_CITY_JAHAD_BASE + "/allocations/"; export const ROUTE_CITY_JIHAD_ROUTE_MANAGE_GUILDS = ROUTE_CITY_JAHAD_BASE + "/manage-guilds/"; -export const ROUTE_CITY_JIHAD_ROUTE_MANAGE_STEWARDS = - ROUTE_CITY_JAHAD_BASE + "/manage-stewards/"; export const ROUTE_CITY_JIHAD_ROUTE_GUILDS = ROUTE_CITY_JAHAD_BASE + "/manage-guilds/guilds"; export const ROUTE_CITY_JIHAD_ROUTE_STEWARDS = @@ -913,8 +892,6 @@ export const ROUTE_CITY_POULTRY_ROUTE_ALLOCATIONS = ROUTE_CITY_POULTRY_BASE + "/allocations/"; export const ROUTE_CITY_POULTRY_ROUTE_MANAGE_GUILDS = ROUTE_CITY_POULTRY_BASE + "/manage-guilds/"; -export const ROUTE_CITY_POULTRY_ROUTE_MANAGE_STEWARDS = - ROUTE_CITY_POULTRY_BASE + "/manage-stewards/"; export const ROUTE_CITY_POULTRY_ROUTE_GUILDS = ROUTE_CITY_POULTRY_BASE + "/manage-guilds/guilds"; export const ROUTE_CITY_POULTRY_ROUTE_STEWARDS = @@ -955,10 +932,6 @@ export const ROUTE_OBSERVATORYـHATCHINGS_DETAILS = // Senf export const ROUTE_SENF_INVENTORY = ROUTE_SENF_BASE + "/inventory"; export const ROUTE_SENF_INVENTORY_STOCK = ROUTE_SENF_BASE + "/inventory/stock"; -export const ROUTE_SENF_INVENTORY_SEGMENTATION = - ROUTE_SENF_BASE + "/inventory/segmentaion"; -export const ROUTE_SENF_INVENTORY_ENTER = ROUTE_SENF_BASE + "/inventory/enter"; -export const ROUTE_GUILD_ROUTE_DEVICES = ROUTE_SENF_BASE + "/devices"; //Guild Room @@ -981,8 +954,7 @@ export const ROUTE_GUILD_ROOM_ROUTE_STEWARDS = export const ROUTE_PSP_ROUTE_COMPANY_MANAGE_STEWARDS = ROUTE_PSP_COMPANY_BASE + "/manage-stewards"; -export const ROUTE_PSP_ROUTE_COMPANY_PSP_COMPANIES = - ROUTE_PSP_COMPANY_BASE + "/psp-companies"; + export const ROUTE_PSP_COMPANY_ROUTE_GUILDS = ROUTE_PSP_COMPANY_BASE + "/manage-guilds/guilds"; @@ -991,8 +963,6 @@ export const ROUTE_PSP_COMPANY_ROUTE_ACTIVE_SESSION = export const ROUTE_PSP_COMPANY_ROUTE_DEVICES = ROUTE_PSP_COMPANY_BASE + "/devices"; -export const ROUTE_PSP_COMPANY_ROUTE_DEVICES_V2 = - ROUTE_PSP_COMPANY_BASE + "/devices-v2"; //LIVE STOCK SUPPORT @@ -1076,8 +1046,6 @@ export const ROUTE_SUPER_ADMIN_ROUTE_ALLOCATIONS = ROUTE_SUPER_ADMIN_BASE + "/allocations/"; export const ROUTE_SUPER_ADMIN_ROUTE_MANAGE_GUILDS = ROUTE_SUPER_ADMIN_BASE + "/manage-guilds/"; -export const ROUTE_SUPER_ADMIN_ROUTE_MANAGE_STEWARDS = - ROUTE_SUPER_ADMIN_BASE + "/manage-stewards/"; export const ROUTE_SUPER_ADMIN_ROUTE_IN_PROVINCE_GUILDS = ROUTE_SUPER_ADMIN_BASE + "/manage-guilds/in-province"; export const ROUTE_SUPER_ADMIN_ROUTE_OUT_PROVINCE_GUILDS = @@ -1299,8 +1267,6 @@ export const ROUTE_SUPER_ADMIN_ROUTE_MANAGE_DEVICES = export const ROUTE_SUPER_ADMIN_ROUTE_COMPANY_MANAGE_STEWARDS = ROUTE_SUPER_ADMIN_BASE + "/manage-stewards"; -export const ROUTE_SUPER_ADMIN_ROUTE_PSP_COMPANIES = - ROUTE_SUPER_ADMIN_BASE + "/psp-companies"; export const ROUTE_SUPER_ADMIN_COMPANY_ROUTE_GUILDS = ROUTE_SUPER_ADMIN_BASE + "/manage-guilds/guilds"; export const ROUTE_SUPER_ADMIN_COMPANY_ROUTE_ACTIVE_SESSION = @@ -1334,7 +1300,6 @@ export const ROUTE_CHAIN_COMPANY_MANAGE_FEES = ROUTE_CHAIN_COMPANY_BASE + "/manage-fee/"; // ADMIN X -export const ROUTE_ADMINX_BASE_NEW_HOME = ROUTE_ADMINX_BASE + "/home"; export const ROUTE_ADMINX_USER_PROFILE = "/dashboard/profile" + ROUTE_ADMINX_BASE; export const ROUTE_ADMINX_REQUESTS = ROUTE_ADMINX_BASE + "/requests"; @@ -1389,8 +1354,6 @@ export const ROUTE_ADMINX_ROUTE_ALLOCATIONS = ROUTE_ADMINX_BASE + "/allocations/"; export const ROUTE_ADMINX_ROUTE_MANAGE_GUILDS = ROUTE_ADMINX_BASE + "/manage-guilds/"; -export const ROUTE_ADMINX_ROUTE_MANAGE_STEWARDS = - ROUTE_ADMINX_BASE + "/manage-stewards/"; export const ROUTE_ADMINX_ROUTE_IN_PROVINCE_GUILDS = ROUTE_ADMINX_BASE + "/manage-guilds/in-province"; export const ROUTE_ADMINX_ROUTE_OUT_PROVINCE_GUILDS = @@ -1522,10 +1485,6 @@ export const ROUTE_ADMINX_EXCEL_CHECK = ROUTE_ADMINX_BASE + "/excel-check"; export const ROUTE_ADMINX_DISPENSERS = ROUTE_ADMINX_BASE + "/dispensers"; export const ROUTE_ADMINX_DISPENSERS_MANAGEMENT = ROUTE_ADMINX_BASE + "/dispensers-management"; -export const ROUTE_ADMINX_DISPENSERS_MANAGEMENT_V2 = - ROUTE_ADMINX_BASE + "/dispensers-management-v2"; -export const ROUTE_ADMINX_DELEGATES_MANAGEMENT = - ROUTE_ADMINX_BASE + "/delegates-management"; export const ROUTE_ADMINX_DISPENSER_DETAILS = ROUTE_ADMINX_BASE + "/dispenser-data"; export const ROUTE_ADMINX_DISPENSER_DETAILS_VIEW = @@ -1607,8 +1566,6 @@ export const ROUTE_ADMINX_RETURN_PURCHASES = export const ROUTE_ADMINX_ROUTE_COMPANY_MANAGE_STEWARDS = ROUTE_ADMINX_BASE + "/manage-stewards"; -export const ROUTE_ADMINX_ROUTE_PSP_COMPANIES = - ROUTE_ADMINX_BASE + "/psp-companies"; export const ROUTE_ADMINX_COMPANY_ROUTE_GUILDS = ROUTE_ADMINX_BASE + "/manage-guilds/guilds"; export const ROUTE_ADMINX_COMPANY_ROUTE_ACTIVE_SESSION = diff --git a/src/routes/senfRouting.js b/src/routes/senfRouting.js index 93e6d6c..efa3cee 100644 --- a/src/routes/senfRouting.js +++ b/src/routes/senfRouting.js @@ -1,39 +1,16 @@ import { lazy } from "react"; import { lazyRetry } from "../utils/lazyRetry"; -import { - ROUTE_GUILD_ROUTE_DEVICES, - ROUTE_SENF_INVENTORY, - ROUTE_SENF_INVENTORY_ENTER, - ROUTE_SENF_INVENTORY_SEGMENTATION, - ROUTE_SENF_INVENTORY_STOCK, -} from "./routes"; +import { ROUTE_SENF_INVENTORY, ROUTE_SENF_INVENTORY_STOCK } from "./routes"; const SenfInventoryPage = lazy(() => lazyRetry(() => import("../pages/SenfInventoryPage")) ); -const GuildPspDevices = lazy(() => - lazyRetry(() => - import("../features/guild/components/guild-psp-devices/GuildPspDevices") - ) -); - export const senfRouting = [ { - path: [ - ROUTE_SENF_INVENTORY, - ROUTE_SENF_INVENTORY_STOCK, - ROUTE_SENF_INVENTORY_SEGMENTATION, - ROUTE_SENF_INVENTORY_ENTER, - ], + path: [ROUTE_SENF_INVENTORY, ROUTE_SENF_INVENTORY_STOCK], Page: SenfInventoryPage, exact: false, props: {}, }, - { - path: [ROUTE_GUILD_ROUTE_DEVICES], - Page: GuildPspDevices, - exact: false, - props: {}, - }, ]; diff --git a/src/routes/slaughterRouting.js b/src/routes/slaughterRouting.js index cfd4ad8..5cc3271 100644 --- a/src/routes/slaughterRouting.js +++ b/src/routes/slaughterRouting.js @@ -54,9 +54,6 @@ import { ROUTE_SLAUGHTER_INVENTORY_SUMMARY, ROUTE_SLAUGHTER_ORDERS, ROUTE_SLAUGHTER_ROUTE_MANAGE_DISPENSERS, - ROUTE_SLAUGHTER_ROUTE_MANAGE_DELEGATES, - ROUTE_SLAUGHTER_ROUTE_DEVICES, - ROUTE_SLAUGHTER_ROUTE_SUB_UNITS, } from "./routes"; const TradePanel = lazy(() => lazyRetry(() => import("../pages/TradePanel"))); @@ -124,24 +121,6 @@ const ManageDispensers = lazy(() => ) ); -const ManageDelegates = lazy(() => - lazyRetry(() => - import( - "../features/slaughter-house/components/slaughter-manage-delegates/SlaughterManageDelegates" - ) - ) -); - -const PspDevices = lazy(() => - lazyRetry(() => - import("../features/guild/components/guild-psp-devices/GuildPspDevices") - ) -); - -const SlaughterSubUnits = lazy(() => - lazyRetry(() => import("../pages/SlaughterSubUnits")) -); - export const slaughterRouting = [ //cars section slaughter { @@ -312,28 +291,10 @@ export const slaughterRouting = [ exact: false, props: {}, }, - { - path: [ROUTE_SLAUGHTER_ROUTE_SUB_UNITS], - Page: SlaughterSubUnits, - exact: false, - props: {}, - }, { path: [ROUTE_SLAUGHTER_ROUTE_MANAGE_DISPENSERS], Page: ManageDispensers, exact: false, props: {}, }, - { - path: [ROUTE_SLAUGHTER_ROUTE_MANAGE_DELEGATES], - Page: ManageDelegates, - exact: false, - props: {}, - }, - { - path: [ROUTE_SLAUGHTER_ROUTE_DEVICES], - Page: PspDevices, - exact: false, - props: {}, - }, ]; diff --git a/src/routes/stewardRouting.js b/src/routes/stewardRouting.js index 3035d86..ae79696 100644 --- a/src/routes/stewardRouting.js +++ b/src/routes/stewardRouting.js @@ -11,9 +11,6 @@ import { ROUTE_STEWARD_SALE_OUT_PROVINCE, ROUTE_STEWARD_SEGMENT, ROUTE_STEWARD_ROUTE_MANAGE_DISPENSERS, - ROUTE_STEWARD_ROUTE_MANAGE_DELEGATES, - ROUTE_STEWARD_ROUTE_DEVICES, - ROUTE_STEWARD_ROUTE_SUB_UNITS, } from "./routes"; const FilesState = lazy(() => lazyRetry(() => import("../pages/FilesState"))); @@ -33,24 +30,6 @@ const ManageDispensers = lazy(() => ) ); -const ManageDelegates = lazy(() => - lazyRetry(() => - import( - "../features/slaughter-house/components/slaughter-manage-delegates/SlaughterManageDelegates" - ) - ) -); - -const PspDevices = lazy(() => - lazyRetry(() => - import("../features/guild/components/guild-psp-devices/GuildPspDevices") - ) -); - -const SubUnits = lazy(() => - lazyRetry(() => import("../pages/SlaughterSubUnits")) -); - export const stewardRouting = [ { path: [ROUTE_JAHAD_FILES_STATE], @@ -78,28 +57,10 @@ export const stewardRouting = [ exact: false, props: {}, }, - { - path: [ROUTE_STEWARD_ROUTE_SUB_UNITS], - Page: SubUnits, - exact: false, - props: {}, - }, { path: [ROUTE_STEWARD_ROUTE_MANAGE_DISPENSERS], Page: ManageDispensers, exact: false, props: {}, }, - { - path: [ROUTE_STEWARD_ROUTE_MANAGE_DELEGATES], - Page: ManageDelegates, - exact: false, - props: {}, - }, - { - path: [ROUTE_STEWARD_ROUTE_DEVICES], - Page: PspDevices, - exact: false, - props: {}, - }, ]; diff --git a/src/utils/checkPathStartsWith.js b/src/utils/checkPathStartsWith.js deleted file mode 100644 index 009e815..0000000 --- a/src/utils/checkPathStartsWith.js +++ /dev/null @@ -1,7 +0,0 @@ -export const checkPathStartsWith = (str) => { - const path = window.location.pathname; - if (path.startsWith("/" + str)) { - return true; - } - return false; -}; diff --git a/src/utils/getFaUserRole.js b/src/utils/getFaUserRole.js index 3da9150..dd0f373 100644 --- a/src/utils/getFaUserRole.js +++ b/src/utils/getFaUserRole.js @@ -80,8 +80,6 @@ export function getFaUserRole(role) { return "جهاد میدان بار"; case "PoultryScience": return "کارشناس علوم دامی"; - case "ProteinGuild": - return "گویهای پروتئین"; default: return ""; } diff --git a/src/utils/getRoleFromUrl.js b/src/utils/getRoleFromUrl.js index bd70927..01fe0cc 100644 --- a/src/utils/getRoleFromUrl.js +++ b/src/utils/getRoleFromUrl.js @@ -32,8 +32,6 @@ export const getRoleFromUrl = () => { return "ProvinceSupervisor"; case "guild": return "Guilds"; - case "senf": - return "Guilds"; case "steward": return "Steward"; case "guild-room": diff --git a/src/utils/getRolesItems.js b/src/utils/getRolesItems.js index 13d2f30..5ee5115 100644 --- a/src/utils/getRolesItems.js +++ b/src/utils/getRolesItems.js @@ -23,8 +23,6 @@ import { DirectionsCarFilled, DriveEta, Engineering, - Home, - Lan, Payment, PriceChange, SettingsApplications, @@ -67,8 +65,6 @@ import CategoryIcon from "@mui/icons-material/Category"; import MedicalServicesIcon from "@mui/icons-material/MedicalServices"; import NotificationsIcon from "@mui/icons-material/Notifications"; import TableChartIcon from "@mui/icons-material/TableChart"; -import { FaFax } from "react-icons/fa"; -import BadgeIcon from "@mui/icons-material/Badge"; export const getRoleItems = (role) => { switch (role) { @@ -237,11 +233,6 @@ export const getRoleItems = (role) => { route: ROUTES.ROUTE_ADMINX_ROUTE_MANAGE_GUILDS, icon: , }, - { - text: "مدیریت مباشرین", - route: ROUTES.ROUTE_ADMINX_ROUTE_MANAGE_STEWARDS, - icon: , - }, { text: "مدیریت سردخانه ها", icon: , @@ -249,7 +240,7 @@ export const getRoleItems = (role) => { }, { text: "شرکت‌های پرداخت الکترونیک", - route: ROUTES.ROUTE_ADMINX_ROUTE_PSP_COMPANIES, + route: ROUTES.ROUTE_ADMINX_ROUTE_COMPANY_MANAGE_STEWARDS, icon: , }, { @@ -313,11 +304,6 @@ export const getRoleItems = (role) => { route: ROUTES.ROUTE_ADMINX_EXCEL_CHECK, icon: , }, - { - text: "خانه", - route: ROUTES.ROUTE_ADMINX_BASE_NEW_HOME, - icon: , - }, ]; case "Admin": return [ @@ -644,11 +630,6 @@ export const getRoleItems = (role) => { icon: , route: ROUTES.ROUTE_PROVINCE_ROUTE_MANAGE_GUILDS, }, - { - text: "مدیریت مباشرین", - route: ROUTES.ROUTE_PROVINCE_ROUTE_MANAGE_STEWARDS, - icon: , - }, { text: "خودروها", icon: , @@ -812,11 +793,11 @@ export const getRoleItems = (role) => { route: ROUTES.ROUTE_SLAUGHTER_INVENTORY, icon: , }, - { - text: "زیر مجموعه ها", - route: ROUTES.ROUTE_SLAUGHTER_ROUTE_SUB_UNITS, - icon: , - }, + // { + // text: "مدیریت توزیع کننده‌ها", + // route: ROUTES.ROUTE_SLAUGHTER_ROUTE_MANAGE_DISPENSERS, + // icon: , + // }, { text: "مدیریت تعرفه ها", route: ROUTES.ROUTE_SLAUGHTER_PAYING_FEES_REQUESTS, @@ -833,11 +814,6 @@ export const getRoleItems = (role) => { route: ROUTES.ROUTE_SLAUGHTER_ROUTE_MANAGE_GUILDS, icon: , }, - { - text: "مدیریت مباشرین", - route: ROUTES.ROUTE_SLAUGHTER_ROUTE_MANAGE_STEWARDS, - icon: , - }, // { // text: "قیمت روز ", // route: ROUTES.ROUTE_SLAUGHTER_PRICING, @@ -896,11 +872,6 @@ export const getRoleItems = (role) => { route: ROUTES.ROUTE_SLAUGHTER_RETURN_PURCHASES, icon: , }, - { - route: ROUTES.ROUTE_SLAUGHTER_ROUTE_DEVICES, - icon: , - text: "مدیریت دستگاه‌ها", - }, ]; case "KillHouseVet": return [ @@ -1090,11 +1061,6 @@ export const getRoleItems = (role) => { icon: , text: "انبار", }, - { - route: ROUTES.ROUTE_GUILD_ROUTE_DEVICES, - icon: , - text: "مدیریت دستگاه‌ها", - }, ]; case "Steward": return [ @@ -1103,16 +1069,11 @@ export const getRoleItems = (role) => { icon: , text: "انبار", }, - { - route: ROUTES.ROUTE_STEWARD_ROUTE_SUB_UNITS, - icon: , - text: "زیر مجموعه ها", - }, - { - route: ROUTES.ROUTE_STEWARD_ROUTE_DEVICES, - icon: , - text: "مدیریت دستگاه‌ها", - }, + // { + // route: ROUTES.ROUTE_STEWARD_ROUTE_MANAGE_DISPENSERS, + // icon: , + // text: "مدیریت توزیع کننده‌ها", + // }, // { // route: ROUTES.ROUTE_STEWARD_MANAGE_GUILDS, // icon: , @@ -1131,11 +1092,6 @@ export const getRoleItems = (role) => { icon: , text: "مدیریت اصناف", }, - { - text: "مدیریت مباشرین", - route: ROUTES.ROUTE_COMMERCE_ROUTE_MANAGE_STEWARDS, - icon: , - }, // { // route: ROUTES.ROUTE_COMMERCE_ROUTE_FILES_STATE, // icon: , @@ -1189,11 +1145,6 @@ export const getRoleItems = (role) => { icon: , text: "مدیریت اصناف", }, - { - text: "مدیریت مباشرین", - route: ROUTES.ROUTE_PROVINCE_SUPERVISOR_ROUTE_MANAGE_STEWARDS, - icon: , - }, { text: "پایش کشوری", route: ROUTES.ROUTE_PROVINCE_SUPERVISOR_ROUTE_NATIONAL_INFO, @@ -1222,11 +1173,6 @@ export const getRoleItems = (role) => { icon: , text: "مدیریت اصناف", }, - { - text: "مدیریت مباشرین", - route: ROUTES.ROUTE_CITY_COMMERCE_ROUTE_MANAGE_STEWARDS, - icon: , - }, // { // route: ROUTES.ROUTE_CITY_COMMERCE_ROUTE_FILES_STATE, // icon: , @@ -1283,11 +1229,6 @@ export const getRoleItems = (role) => { icon: , text: "مدیریت اصناف", }, - { - text: "مدیریت مباشرین", - route: ROUTES.ROUTE_CITY_JIHAD_ROUTE_MANAGE_STEWARDS, - icon: , - }, { route: ROUTES.ROUTE_CITY_JIHADـHATCHINGS, icon: , @@ -1324,7 +1265,7 @@ export const getRoleItems = (role) => { case "PosCompany": return [ { - route: ROUTES.ROUTE_PSP_ROUTE_COMPANY_PSP_COMPANIES, + route: ROUTES.ROUTE_PSP_ROUTE_COMPANY_MANAGE_STEWARDS, icon: , text: "اتاق اصناف", }, @@ -1510,18 +1451,13 @@ export const getRoleItems = (role) => { icon: , route: ROUTES.ROUTE_SUPER_ADMIN_ROUTE_MANAGE_GUILDS, }, - { - text: "مدیریت مباشرین", - route: ROUTES.ROUTE_SUPER_ADMIN_ROUTE_MANAGE_STEWARDS, - icon: , - }, { text: "مدیریت سردخانه ها", icon: , route: ROUTES.ROUTE_SUPER_ADMIN_COLD_HOUSES, }, { - route: ROUTES.ROUTE_SUPER_ADMIN_ROUTE_PSP_COMPANIES, + route: ROUTES.ROUTE_SUPER_ADMIN_ROUTE_COMPANY_MANAGE_STEWARDS, icon: , text: "شرکت‌های پرداخت الکترونیک", }, @@ -1634,11 +1570,6 @@ export const getRoleItems = (role) => { icon: , route: ROUTES.ROUTE_CITY_POULTRY_ROUTE_MANAGE_GUILDS, }, - { - text: "مدیریت مباشرین", - route: ROUTES.ROUTE_CITY_POULTRY_ROUTE_MANAGE_STEWARDS, - icon: , - }, // { // text: "مدیریت توزیع", // icon: , @@ -1666,8 +1597,6 @@ export const getRoleItems = (role) => { icon: , }, ]; - case "ProteinGuild": - return []; default: return []; diff --git a/src/utils/getSelectedSubUserKey.js b/src/utils/getSelectedSubUserKey.js deleted file mode 100644 index 41575b1..0000000 --- a/src/utils/getSelectedSubUserKey.js +++ /dev/null @@ -1,11 +0,0 @@ -/** - * Helper function to get the selected sub user key from Redux state - * @param {Object} state - Redux state - * @returns {string|null} - The sub user key or null if not available - */ -export const getSelectedSubUserKey = (state) => { - const selectedSubUser = state?.userSlice?.selectedSubUser; - return selectedSubUser?.key || null; -}; - -export default getSelectedSubUserKey; diff --git a/src/version.txt b/src/version.txt index 6b4f41a..ac412c6 100644 --- a/src/version.txt +++ b/src/version.txt @@ -1 +1 @@ -6.95 \ No newline at end of file +6.96 \ No newline at end of file diff --git a/vite.config.js b/vite.config.js index 5059958..d98b93a 100644 --- a/vite.config.js +++ b/vite.config.js @@ -73,7 +73,7 @@ export default defineConfig({ ], preview: { - allowedHosts: ["rasadyar.com", "rasadyar.net", "rasadyar.ir", "dev.rasadyar.com"], + allowedHosts: ["rasadyar.com", "rasadyar.net", "rasadyar.ir"], }, // Resolve configuration