From 12d6d08bef66819fa52e6b75e8a1ee34cae7143b Mon Sep 17 00:00:00 2001 From: AmirHossein Mahmoodi Date: Wed, 25 Jun 2025 07:41:03 +0000 Subject: [PATCH] Feature/amiriis missions --- .../dashboard/azmayesh/page.js | 36 +- .../dashboard/azmayesh_type/page.js | 32 +- .../dashboard/damage-items/page.js | 26 +- .../dashboard/damages/operator/page.js | 32 +- .../dashboard/damages/report/page.js | 26 +- .../dashboard/fast-react/operator/page.js | 30 +- .../dashboard/fast-react/supervisor/page.js | 32 +- .../assistant/zamin-gov/page.js | 24 +- .../city-admin/zamin-gov/page.js | 24 +- .../general-manager/zamin-gov/page.js | 24 +- .../province-admin/zamin-gov/page.js | 24 +- .../(dashboardLayout)/dashboard/loading.jsx | 14 +- .../(dashboardLayout)/dashboard/page.js | 18 +- .../dashboard/permissions/page.js | 26 +- .../dashboard/road-items/operator/page.js | 32 +- .../road-items/reports/items-report/page.js | 40 +- .../dashboard/road-items/reports/map/page.js | 18 +- .../reports/sub-items-report/page.js | 40 +- .../dashboard/road-items/supervisor/page.js | 36 +- .../dashboard/road-missions/control/page.js | 17 + .../dashboard/road-missions/operator/page.js | 18 + .../road-missions/transportation/page.js | 17 + .../dashboard/road-patrols/operator/page.js | 34 +- .../dashboard/road-patrols/reports/page.js | 40 +- .../dashboard/road-patrols/supervisor/page.js | 36 +- .../dashboard/road-safety/operator/page.js | 32 +- .../dashboard/road-safety/reports/map/page.js | 18 +- .../dashboard/road-safety/reports/page.js | 38 +- .../dashboard/road-safety/supervisor/page.js | 42 +- .../dashboard/user-activities/page.js | 26 +- .../infrastructure/toll-house/loading.jsx | 14 +- .../infrastructure/toll-house/page.js | 32 +- .../(withAuth)/(dashboardLayout)/layout.js | 34 +- src/app/(withAuth)/layout.js | 62 +- src/app/api/fake-cities/route.js | 36 +- src/app/api/fake-data/route.js | 82 +- src/app/api/fake-prev-state-opinion/route.js | 18 +- src/app/api/fake-provinces/route.js | 36 +- src/app/api/fake-road-items/operator/route.js | 168 +-- .../api/fake-road-items/supervisor/route.js | 168 +-- .../api/fake-road-patrol/operator/route.js | 48 +- .../api/fake-road-patrol/supervisor/route.js | 56 +- src/app/api/fake-submit/[id]/route.js | 6 +- src/app/api/fake-tests-type/route.js | 36 +- src/app/api/fake-tests/route.js | 142 +- src/app/default.js | 6 +- src/app/layout.js | 50 +- src/app/lfwd/page.js | 122 +- src/app/not-found.js | 32 +- src/app/page.js | 16 +- src/app/template.js | 80 +- src/assets/scss/fontiran.scss | 380 +++--- src/assets/scss/global.scss | 23 +- src/assets/scss/map-styles.scss | 38 +- .../azmayesh/Actions/Create/index.jsx | 66 +- .../dashboard/azmayesh/AzmayeshList.jsx | 432 +++--- .../CandUAzmayesh/CandUChooseLocation.jsx | 426 +++--- .../Forms/CandUAzmayesh/CandUGeneralInfo.jsx | 746 +++++----- .../Forms/CandUAzmayesh/CandUMapBox.jsx | 82 +- .../Forms/CandUAzmayesh/CandUTimeLine.jsx | 130 +- .../Forms/CandUAzmayesh/FormAndRequest.jsx | 400 +++--- .../azmayesh/Forms/CandUAzmayesh/index.jsx | 76 +- .../RowActions/AzmayeshUpdate/index.jsx | 104 +- .../RowActions/DeleteAzmayesh/index.jsx | 156 +-- .../Actions/Create/index.jsx | 118 +- .../ShowSampleOfAzmayesh/AzmayeshInfo.jsx | 164 +-- .../CandUSampleOfAzmayesh/FormAndRequest.jsx | 152 +-- .../Forms/CandUSampleOfAzmayesh/index.jsx | 148 +- .../RowActions/DeleteSample.jsx | 156 +-- .../RowActions/UpdateSample.jsx | 120 +- .../ShowSampleOfAzmayesh/RowActions/index.jsx | 36 +- .../ShowSampleOfAzmayesh/ShowSampleList.jsx | 160 +-- .../ShowSampleOfAzmayesh/Toolbar.jsx | 20 +- .../RowActions/ShowSampleOfAzmayesh/index.jsx | 92 +- .../dashboard/azmayesh/RowActions/index.jsx | 28 +- .../dashboard/azmayesh/ShowLocation/index.jsx | 104 +- src/components/dashboard/azmayesh/Toolbar.jsx | 20 +- src/components/dashboard/azmayesh/index.jsx | 30 +- .../azmayeshType/Actions/Create/index.jsx | 66 +- .../azmayeshType/AzmayeshTypeList.jsx | 130 +- .../CandUAzmayeshType/AzmayeshFields.jsx | 362 ++--- .../CandUAzmayeshType/FormAndRequest.jsx | 436 +++--- .../Forms/CandUAzmayeshType/ListItems.jsx | 154 +-- .../Forms/CandUAzmayeshType/SelectItemBox.jsx | 216 +-- .../Forms/CandUAzmayeshType/index.jsx | 74 +- .../RowActions/DeleteAzmayeshType/index.jsx | 156 +-- .../RowActions/UpdateAzmayeshType/index.jsx | 106 +- .../azmayeshType/RowActions/index.jsx | 26 +- .../dashboard/azmayeshType/Toolbar.jsx | 20 +- .../dashboard/azmayeshType/index.jsx | 30 +- .../Actions/Create/Form/CreateFormContent.jsx | 290 ++-- .../damageItems/Actions/Create/Form/index.jsx | 50 +- .../damageItems/Actions/Create/index.jsx | 72 +- .../dashboard/damageItems/DamagesList.jsx | 168 +-- .../damageItems/RowActions/Activity/index.jsx | 62 +- .../RowActions/Edit/Form/index.jsx | 290 ++-- .../damageItems/RowActions/Edit/index.jsx | 88 +- .../damageItems/RowActions/index.jsx | 26 +- .../dashboard/damageItems/Toolbar.jsx | 20 +- .../dashboard/damageItems/index.jsx | 26 +- .../Actions/create/Forms/CityContent.jsx | 66 +- .../Actions/create/Forms/CityController.jsx | 32 +- .../create/Forms/CreateFormContent.jsx | 524 +++---- .../Actions/create/Forms/DamageAmount.jsx | 112 +- .../Actions/create/Forms/DamageInfo.jsx | 506 +++---- .../Actions/create/Forms/DamageItem.jsx | 334 ++--- .../Actions/create/Forms/DamageItemInfo.jsx | 120 +- .../Actions/create/Forms/DamagePrice.jsx | 96 +- .../Actions/create/Forms/DamageReport.jsx | 102 +- .../Actions/create/Forms/ImageUpload.jsx | 154 +-- .../create/Forms/LogesticController.jsx | 128 +- .../Actions/create/Forms/PoliceFileReport.jsx | 134 +- .../operator/Actions/create/Forms/index.jsx | 224 +-- .../damages/operator/Actions/create/index.jsx | 76 +- .../damages/operator/ExcelPrint/index.jsx | 150 +- .../Form/CreateFactor/CreateFactorContent.jsx | 438 +++--- .../operator/Form/CreateFactor/index.jsx | 86 +- .../operator/Form/EditForm/EditController.jsx | 246 ++-- .../damages/operator/Form/EditForm/index.jsx | 118 +- .../Form/RegisterInsurance/DaghiFile.jsx | 96 +- .../Form/RegisterInsurance/DaghiPayment.jsx | 106 +- .../Form/RegisterInsurance/ImageUpload.jsx | 154 +-- .../Form/RegisterInsurance/InsuranceFile.jsx | 96 +- .../RegisterInsurance/InsurancePayment.jsx | 104 +- .../RegisterInsuranceContent.jsx | 406 +++--- .../operator/Form/RegisterInsurance/index.jsx | 106 +- .../damages/operator/OperatorList.jsx | 1008 +++++++------- .../DamageItemDialog/DamageItemContent.jsx | 164 +-- .../RowActions/DamageItemDialog/index.jsx | 86 +- .../DamageReport/DamageReportContent.jsx | 206 +-- .../DamageReport/DamageReportController.jsx | 68 +- .../RowActions/DamageReport/index.jsx | 76 +- .../RowActions/DeleteDialog/DeleteContent.jsx | 78 +- .../RowActions/DeleteDialog/index.jsx | 68 +- .../ImageDialog/ImageFormContent.jsx | 90 +- .../operator/RowActions/ImageDialog/index.jsx | 88 +- .../LocationForm/LocationFormContent.jsx | 70 +- .../RowActions/LocationForm/index.jsx | 80 +- .../PoliceRahLetterContent.jsx | 80 +- .../RowActions/PoliceRahLetter/index.jsx | 76 +- .../SendToInsuranceContent.jsx | 86 +- .../RowActions/SendToInsurance/index.jsx | 76 +- .../operator/RowActions/ShowPlate/index.jsx | 76 +- .../damages/operator/RowActions/index.jsx | 70 +- .../dashboard/damages/operator/Toolbar.jsx | 32 +- .../dashboard/damages/operator/index.jsx | 28 +- .../damages/report/ExcelPrint/index.jsx | 144 +- .../dashboard/damages/report/ReportLists.jsx | 646 ++++----- .../report/Search/FromDateController.jsx | 56 +- .../report/Search/SearchReportField.jsx | 90 +- .../damages/report/Search/SelectProvince.jsx | 94 +- .../report/Search/ToDateController.jsx | 60 +- .../dashboard/damages/report/Search/index.jsx | 26 +- .../dashboard/damages/report/Toolbar.jsx | 22 +- .../dashboard/damages/report/index.jsx | 274 ++-- .../complaintList/ComplaintListTable.jsx | 562 ++++---- .../complaintList/ExcelPrint/index.jsx | 148 +- .../Form/registerAction/ImageUpload.jsx | 154 +-- .../registerAction/RegisterActionContent.jsx | 222 +-- .../registerAction/RegisterActionDone.jsx | 172 +-- .../registerAction/RegisterActionUndone.jsx | 74 +- .../Form/registerAction/index.jsx | 134 +- .../RowActions/DescriptionDialog/index.jsx | 100 +- .../LocationDialog/LocationFormContent.jsx | 60 +- .../RowActions/LocationDialog/index.jsx | 72 +- .../RowActions/Refer/EdarateShahriField.jsx | 140 +- .../RowActions/Refer/ProvinceField.jsx | 66 +- .../RowActions/Refer/ReferContent.jsx | 204 +-- .../complaintList/RowActions/Refer/index.jsx | 64 +- .../RowActions/ReferList/ReferListContent.jsx | 164 +-- .../RowActions/ReferList/index.jsx | 86 +- .../complaintList/RowActions/index.jsx | 48 +- .../fastReact/complaintList/Toolbar.jsx | 22 +- .../fastReact/complaintList/index.jsx | 90 +- .../fastReact/operator/ExcelPrint/index.jsx | 150 +- .../operator/Form/EditForm/EditController.jsx | 144 +- .../operator/Form/EditForm/index.jsx | 116 +- .../fastReact/operator/OperatorList.jsx | 740 +++++----- .../RowActions/DescriptionDialog/index.jsx | 100 +- .../ImageDialog/ImageFormContent.jsx | 90 +- .../operator/RowActions/ImageDialog/index.jsx | 92 +- .../LocationDialog/LocationFormContent.jsx | 60 +- .../RowActions/LocationDialog/index.jsx | 72 +- .../fastReact/operator/RowActions/index.jsx | 26 +- .../dashboard/fastReact/operator/Toolbar.jsx | 26 +- .../dashboard/fastReact/operator/index.jsx | 28 +- .../fastReact/supervisor/ExcelPrint/index.jsx | 150 +- .../ConfirmDialog/ConfirmContent.jsx | 140 +- .../RowActions/ConfirmDialog/index.jsx | 58 +- .../RowActions/DescriptionDialog/index.jsx | 100 +- .../ImageDialog/ImageFormContent.jsx | 90 +- .../RowActions/ImageDialog/index.jsx | 92 +- .../LocationDialog/LocationFormContent.jsx | 60 +- .../RowActions/LocationDialog/index.jsx | 72 +- .../RejectDialog/RejectFormContent.jsx | 168 +-- .../RowActions/RejectDialog/index.jsx | 58 +- .../RowActions/RestoreForm/RestoreContent.jsx | 84 +- .../RowActions/RestoreForm/index.jsx | 64 +- .../fastReact/supervisor/RowActions/index.jsx | 40 +- .../fastReact/supervisor/SupervisorList.jsx | 940 ++++++------- .../fastReact/supervisor/Toolbar.jsx | 26 +- .../dashboard/fastReact/supervisor/index.jsx | 28 +- .../RoadSafetyForm/DescriptionForm.jsx | 58 +- .../ManagerOrAssistantSubmit.jsx | 30 +- .../RoadSafetyForm/PrevCartableOpinion.jsx | 50 +- .../RoadSafetyForm/QuestionSafetyForm.jsx | 66 +- .../RoadSafetyForm/RoadSafetyFormContext.jsx | 164 +-- .../RowActions/RoadSafetyForm/index.jsx | 104 +- .../RowActions/TaskDetail/DetailDialog.jsx | 150 +- .../zaminGov/RowActions/TaskDetail/index.jsx | 52 +- .../assistant/zaminGov/RowActions/index.jsx | 26 +- .../assistant/zaminGov/TaskList.jsx | 290 ++-- .../assistant/zaminGov/index.jsx | 30 +- .../RowActions/Refer/ReferFormContext.jsx | 276 ++-- .../zaminGov/RowActions/Refer/index.jsx | 82 +- .../RowActions/TaskDetail/DetailDialog.jsx | 218 +-- .../zaminGov/RowActions/TaskDetail/index.jsx | 52 +- .../cityAdmin/zaminGov/RowActions/index.jsx | 30 +- .../cityAdmin/zaminGov/TaskList.jsx | 290 ++-- .../cityAdmin/zaminGov/index.jsx | 28 +- .../RoadSafetyForm/DescriptionForm.jsx | 58 +- .../ManagerOrAssistantSubmit.jsx | 30 +- .../RoadSafetyForm/PrevCartableOpinion.jsx | 52 +- .../RoadSafetyForm/QuestionSafetyForm.jsx | 66 +- .../RoadSafetyForm/RoadSafetyFormContext.jsx | 164 +-- .../RowActions/RoadSafetyForm/index.jsx | 104 +- .../RowActions/TaskDetail/DetailDialog.jsx | 150 +- .../zaminGov/RowActions/TaskDetail/index.jsx | 52 +- .../zaminGov/RowActions/index.jsx | 26 +- .../generalManager/zaminGov/TaskList.jsx | 290 ++-- .../generalManager/zaminGov/index.jsx | 30 +- .../RowActions/MapModify/MapActionButtons.jsx | 200 +-- .../RowActions/MapModify/MapModifyDialog.jsx | 192 +-- .../RowActions/MapModify/PolygonForDesign.jsx | 230 ++-- .../zaminGov/RowActions/MapModify/index.jsx | 58 +- .../RowActions/Refer/ReferFormContext.jsx | 278 ++-- .../zaminGov/RowActions/Refer/index.jsx | 82 +- .../RoadSafetyForm/DescriptionForm.jsx | 58 +- .../RoadSafetyForm/PrevCartableOpinion.jsx | 54 +- .../RoadSafetyForm/QuestionSafetyForm.jsx | 114 +- .../RoadSafetyForm/RoadSaftyFormContext.jsx | 160 +-- .../RoadSafetyForm/SubmitButtonsAdmin.jsx | 42 +- .../RowActions/RoadSafetyForm/index.jsx | 104 +- .../RowActions/TaskDetail/DetailDialog.jsx | 150 +- .../zaminGov/RowActions/TaskDetail/index.jsx | 52 +- .../zaminGov/RowActions/index.jsx | 34 +- .../provinceAdmin/zaminGov/TaskList.jsx | 290 ++-- .../provinceAdmin/zaminGov/index.jsx | 30 +- .../Actions/Create/Form/CreateFormContent.jsx | 436 +++--- .../Actions/Create/Form/index.jsx | 132 +- .../permissionTable/Actions/Create/index.jsx | 72 +- .../Actions/Edit/EditController.jsx | 92 +- .../permissionTable/Actions/Edit/index.jsx | 102 +- .../permissionTable/PermissionList.jsx | 314 ++--- .../RowActions/DeleteDialog/DeleteContent.jsx | 78 +- .../RowActions/DeleteDialog/index.jsx | 68 +- .../permissionTable/RowActions/index.jsx | 24 +- .../dashboard/permissionTable/Toolbar.jsx | 18 +- .../dashboard/permissionTable/index.jsx | 26 +- .../Create/Forms/CreateFormContent.jsx | 612 ++++----- .../Actions/Create/Forms/GetItemInfo.jsx | 248 ++-- .../Actions/Create/Forms/GetItemsForm.jsx | 128 +- .../Actions/Create/Forms/GetSubItemsForm.jsx | 106 +- .../Actions/Create/Forms/ImageUpload.jsx | 346 ++--- .../Create/Forms/PreviousStatesInfo.jsx | 86 +- .../operator/Actions/Create/Forms/index.jsx | 88 +- .../operator/Actions/Create/index.jsx | 76 +- .../ObservedGashtCreate/GashtCreate.jsx | 58 +- .../GashtCreateContent.jsx | 324 ++--- .../LocationForm/LocationFormContent.jsx | 62 +- .../LocationForm/index.jsx | 72 +- .../RowActions/CompleteItem.jsx | 470 +++---- .../RowActions/GetItemInfo.jsx | 56 +- .../RowActions/ImageUpload.jsx | 314 ++--- .../RowActions/PreviousStatesInfo.jsx | 86 +- .../RowActions/SubItemForm/index.jsx | 42 +- .../ObservedGashtCreate/RowActions/index.jsx | 22 +- .../ObservedGashtCreate/SearchItemInfo.jsx | 84 +- .../ObservedGashtCreate/SearchItems.jsx | 184 +-- .../Actions/ObservedGashtCreate/TableInfo.jsx | 230 ++-- .../Actions/ObservedGashtCreate/index.jsx | 84 +- .../roadItems/operator/ExcelPrint/index.jsx | 152 +-- .../roadItems/operator/OperatorList.jsx | 746 +++++----- .../RowActions/DescriptionForm/index.jsx | 102 +- .../RowActions/EditForm/EditController.jsx | 216 +-- .../RowActions/EditForm/EditFormContent.jsx | 194 +-- .../RowActions/EditForm/EditFormCreate.jsx | 396 +++--- .../operator/RowActions/EditForm/index.jsx | 120 +- .../RowActions/ImageForm/ImageFormContent.jsx | 90 +- .../RowActions/ImageForm/ImagesContent.jsx | 86 +- .../operator/RowActions/ImageForm/index.jsx | 80 +- .../LocationForm/LocationFormContent.jsx | 70 +- .../RowActions/LocationForm/index.jsx | 76 +- .../MachinesCodeForm/MachinesCodeContent.jsx | 158 +-- .../RowActions/MachinesCodeForm/index.jsx | 86 +- .../RahdaranForm/RahdaranContent.jsx | 144 +- .../RowActions/RahdaranForm/index.jsx | 76 +- .../roadItems/operator/RowActions/index.jsx | 22 +- .../dashboard/roadItems/operator/Toolbar.jsx | 30 +- .../dashboard/roadItems/operator/index.jsx | 28 +- .../reports/ItemsReports/ExcelPrint/index.jsx | 156 +-- .../reports/ItemsReports/ReportLists.jsx | 192 +-- .../Search/FromDateController.jsx | 56 +- .../ItemsReports/Search/SearchReportField.jsx | 90 +- .../ItemsReports/Search/SelectProvince.jsx | 94 +- .../ItemsReports/Search/ToDateController.jsx | 60 +- .../reports/ItemsReports/Search/index.jsx | 26 +- .../reports/ItemsReports/TableToolbar.jsx | 20 +- .../roadItems/reports/ItemsReports/index.jsx | 358 ++--- .../reports/Map/ClusterSwitch/index.jsx | 50 +- .../Filter/Drawer/ActivityDateTimeFilter.jsx | 64 +- .../Map/Filter/Drawer/EdarehShahriFilter.jsx | 130 +- .../reports/Map/Filter/Drawer/ItemFilter.jsx | 94 +- .../Map/Filter/Drawer/ProvinceFilter.jsx | 94 +- .../Map/Filter/Drawer/StatusFilter.jsx | 70 +- .../Map/Filter/Drawer/SubItemFilter.jsx | 130 +- .../reports/Map/Filter/Drawer/index.jsx | 282 ++-- .../roadItems/reports/Map/Filter/index.jsx | 88 +- .../roadItems/reports/Map/Legend/index.jsx | 96 +- .../DialogInfoItem/ContentInfoItem.jsx | 208 +-- .../Map/PointsOnMap/DialogInfoItem/index.jsx | 102 +- .../reports/Map/PointsOnMap/index.jsx | 142 +- .../dashboard/roadItems/reports/Map/index.jsx | 254 ++-- .../SubItemsReports/ExcelPrint/index.jsx | 154 +-- .../Search/FromDateController.jsx | 56 +- .../Search/SearchReportField.jsx | 96 +- .../SubItemsReports/Search/SelectItems.jsx | 84 +- .../SubItemsReports/Search/SelectProvince.jsx | 94 +- .../Search/ToDateController.jsx | 60 +- .../reports/SubItemsReports/Search/index.jsx | 24 +- .../reports/SubItemsReports/SubItemsList.jsx | 40 +- .../reports/SubItemsReports/TableToolbar.jsx | 20 +- .../reports/SubItemsReports/index.jsx | 512 +++---- .../roadItems/supervisor/ExcelPrint/index.jsx | 148 +- .../RowActions/ConfirmForm/ConfirmContent.jsx | 144 +- .../RowActions/ConfirmForm/index.jsx | 58 +- .../RowActions/DeleteForm/DeleteContent.jsx | 84 +- .../RowActions/DeleteForm/index.jsx | 64 +- .../RowActions/ImageForm/ImageFormContent.jsx | 90 +- .../RowActions/ImageForm/ImagesContent.jsx | 86 +- .../supervisor/RowActions/ImageForm/index.jsx | 80 +- .../LocationForm/LocationFormContent.jsx | 72 +- .../RowActions/LocationForm/index.jsx | 76 +- .../MachinesCodeForm/MachinesCodeContent.jsx | 158 +-- .../RowActions/MachinesCodeForm/index.jsx | 86 +- .../RahdaranForm/RahdaranContent.jsx | 144 +- .../RowActions/RahdaranForm/index.jsx | 76 +- .../RowActions/RejectForm/RejectContent.jsx | 168 +-- .../RowActions/RejectForm/index.jsx | 58 +- .../RowActions/RestoreForm/RestoreContent.jsx | 88 +- .../RowActions/RestoreForm/index.jsx | 64 +- .../roadItems/supervisor/RowActions/index.jsx | 54 +- .../roadItems/supervisor/SupervisorList.jsx | 876 ++++++------ .../roadItems/supervisor/Toolbar.jsx | 20 +- .../dashboard/roadItems/supervisor/index.jsx | 28 +- .../control/Actions/showArea/index.jsx | 55 + .../control/Actions/showBound/index.jsx | 29 + .../roadMissions/control/ControlList.jsx | 125 ++ .../FinishMission/FinishMissionContent.jsx | 42 + .../RowActions/FinishMission/index.jsx | 36 + .../StartMission/StartMissionContent.jsx | 42 + .../control/RowActions/StartMission/index.jsx | 36 + .../roadMissions/control/RowActions/index.jsx | 13 + .../dashboard/roadMissions/control/index.jsx | 13 + .../Form/Area/MapControl/DrawBound/index.jsx | 116 ++ .../Create/Form/Area/MapControl/index.jsx | 116 ++ .../Actions/Create/Form/Area/index.jsx | 39 + .../Form/GetItemInfo/MissionDates/index.jsx | 93 ++ .../Actions/Create/Form/GetItemInfo/index.jsx | 137 ++ .../Create/Form/Rahdaran/Form/index.jsx | 63 + .../Create/Form/Rahdaran/List/index.jsx | 56 + .../Actions/Create/Form/Rahdaran/index.jsx | 36 + .../Form/RequestMachines/Form/index.jsx | 89 ++ .../Form/RequestMachines/List/index.jsx | 59 + .../Create/Form/RequestMachines/index.jsx | 36 + .../Actions/Create/Form/Verify/index.jsx | 118 ++ .../operator/Actions/Create/Form/index.jsx | 133 ++ .../operator/Actions/Create/index.jsx | 111 ++ .../operator/Actions/showArea/index.jsx | 55 + .../operator/Actions/showBound/index.jsx | 29 + .../roadMissions/operator/OperatorList.jsx | 136 ++ .../RowActions/Delete/DeleteContent.jsx | 39 + .../operator/RowActions/Delete/index.jsx | 34 + .../RowActions/Edit/EditController/index.jsx | 92 ++ .../operator/RowActions/Edit/index.jsx | 48 + .../operator/RowActions/index.jsx | 17 + .../roadMissions/operator/Toolbar.jsx | 11 + .../dashboard/roadMissions/operator/index.jsx | 14 + .../transportation/Actions/showArea/index.jsx | 55 + .../Actions/showBound/index.jsx | 29 + .../MachineList/RowActions/Allocate/index.jsx | 24 + .../MachineList/RowActions/index.jsx | 6 + .../Form/MachinesDialog/MachineList/index.jsx | 61 + .../Allocation/Form/MachinesDialog/index.jsx | 40 + .../Allocation/Form/Reject/Form/index.jsx | 84 ++ .../Allocation/Form/Reject/index.jsx | 40 + .../RowActions/Allocation/Form/index.jsx | 121 ++ .../RowActions/Allocation/index.jsx | 49 + .../transportation/RowActions/index.jsx | 10 + .../transportation/TransportationList.jsx | 125 ++ .../roadMissions/transportation/index.jsx | 14 + .../operator/Actions/Create/index.jsx | 66 +- .../roadPatrols/operator/ExcelPrint/index.jsx | 150 +- .../Forms/CreatePatrol/ActionInfo.jsx | 78 +- .../Forms/CreatePatrol/ActionsDurigPatrol.jsx | 248 ++-- .../Forms/CreatePatrol/CompeleteRequest.jsx | 738 +++++----- .../CreateFormContentObservedItem.jsx | 406 +++--- .../CreatePatrol/DatePickerForEndTime.jsx | 108 +- .../CreatePatrol/DatePickerForStartTime.jsx | 108 +- .../CreatePatrol/EditActionDuringPatrol.jsx | 124 +- .../CreatePatrol/GetObservedItemInfo.jsx | 110 +- .../CreatePatrol/ModalActionsDuringPatrol.jsx | 32 +- .../CreatePatrol/ModalObservedItemPatrol.jsx | 32 +- .../Forms/CreatePatrol/ObservedInfo.jsx | 74 +- .../Forms/CreatePatrol/PatrolDetail.jsx | 360 ++--- .../Forms/CreatePatrol/PatrolDetailInfo.jsx | 332 ++--- .../Forms/CreatePatrol/PatrolForms.jsx | 264 ++-- .../Forms/CreatePatrol/PatrolMapFeatures.jsx | 78 +- .../CreatePatrol/PatrolResultCodeErrors.jsx | 58 +- .../Forms/CreatePatrol/PatrolTimeLine.jsx | 238 ++-- .../PreviousStatesInfoInObservedItem.jsx | 86 +- .../Forms/CreatePatrol/SuperVisorInfo.jsx | 80 +- .../Forms/CreatePatrol/SuperVisorsDetail.jsx | 290 ++-- .../operator/Forms/CreatePatrol/index.jsx | 54 +- .../roadPatrols/operator/OperatorList.jsx | 316 ++--- .../MachinePerformanceContent.jsx | 310 ++--- .../MachinesCodeFetch.jsx | 100 +- .../MachinePerformanceForm/StopsInfo.jsx | 240 ++-- .../MachinePerformanceForm/index.jsx | 86 +- .../MachinesCodeForm/MachinesCodeContent.jsx | 110 +- .../RowActions/MachinesCodeForm/index.jsx | 86 +- .../RahdaranForm/RahdaranContent.jsx | 144 +- .../RowActions/RahdaranForm/index.jsx | 76 +- .../operator/RowActions/ReportForm/index.jsx | 44 +- .../roadPatrols/operator/RowActions/index.jsx | 12 +- .../roadPatrols/operator/Toolbar.jsx | 26 +- .../dashboard/roadPatrols/operator/index.jsx | 28 +- .../roadPatrols/reports/ExcelPrint/index.jsx | 144 +- .../roadPatrols/reports/ReportLists.jsx | 420 +++--- .../reports/Search/FromDateController.jsx | 56 +- .../reports/Search/SearchReportField.jsx | 90 +- .../reports/Search/SelectProvince.jsx | 94 +- .../reports/Search/ToDateController.jsx | 60 +- .../roadPatrols/reports/Search/index.jsx | 26 +- .../dashboard/roadPatrols/reports/Toolbar.jsx | 22 +- .../dashboard/roadPatrols/reports/index.jsx | 268 ++-- .../supervisor/ExcelPrint/index.jsx | 150 +- .../RowActions/DeleteForm/DeleteContent.jsx | 232 ++-- .../RowActions/DeleteForm/index.jsx | 76 +- .../MachinePerformanceContent.jsx | 310 ++--- .../MachinesCodeFetch.jsx | 100 +- .../MachinePerformanceForm/StopsInfo.jsx | 240 ++-- .../MachinePerformanceForm/index.jsx | 86 +- .../RowActions/OfficerDescription/index.jsx | 100 +- .../RahdaranForm/RahdaranContent.jsx | 96 +- .../RowActions/RahdaranForm/index.jsx | 76 +- .../RowActions/ReportForm/index.jsx | 44 +- .../supervisor/RowActions/index.jsx | 44 +- .../roadPatrols/supervisor/SupervisorList.jsx | 562 ++++---- .../roadPatrols/supervisor/Toolbar.jsx | 20 +- .../roadPatrols/supervisor/index.jsx | 28 +- .../roadSafety/operator/ExcelPrint/index.jsx | 148 +- .../Form/EditAxisType/EditFormContent.jsx | 204 +-- .../Form/EditAxisType/OperatorEditForm.jsx | 52 +- .../operator/Form/EditAxisType/index.jsx | 38 +- .../Form/StepOne/CreateFormContent.jsx | 310 ++--- .../operator/Form/StepOne/GetItemInfo.jsx | 124 +- .../operator/Form/StepOne/GetSubItemInfo.jsx | 252 ++-- .../operator/Form/StepOne/ImageUpload.jsx | 154 +-- .../Form/StepOne/OperatorCreateForm.jsx | 52 +- .../operator/Form/StepOne/index.jsx | 72 +- .../operator/Form/StepThree/ImageUpload.jsx | 154 +-- .../Form/StepThree/StepThreeContent.jsx | 228 ++-- .../operator/Form/StepThree/index.jsx | 64 +- .../operator/Form/StepTwo/ShowDocuments.jsx | 74 +- .../operator/Form/StepTwo/StepTwoContent.jsx | 416 +++--- .../operator/Form/StepTwo/index.jsx | 66 +- .../roadSafety/operator/Learn/index.jsx | 78 +- .../roadSafety/operator/OperatorList.jsx | 1000 +++++++------- .../ActionPictureContent.jsx | 88 +- .../RowActions/ActionPictureDialog/index.jsx | 80 +- .../RowActions/DeleteDialog/DeleteContent.jsx | 84 +- .../RowActions/DeleteDialog/index.jsx | 64 +- .../RowActions/DescriptionForm/index.jsx | 102 +- .../FinishDescriptionForm/index.jsx | 102 +- .../RowActions/FinishForm/FinishContent.jsx | 160 +-- .../operator/RowActions/FinishForm/index.jsx | 58 +- .../JudiciaryDocumentContent.jsx | 86 +- .../JudiciaryDocumentController.jsx | 70 +- .../JudiciaryDocumentDialog/index.jsx | 80 +- .../LocationForm/LocationFormContent.jsx | 70 +- .../RowActions/LocationForm/index.jsx | 80 +- .../OperatorDescriptionForm/index.jsx | 102 +- .../RecognizePictureContent.jsx | 88 +- .../RecognizePictureDialog/index.jsx | 80 +- .../roadSafety/operator/RowActions/index.jsx | 54 +- .../dashboard/roadSafety/operator/Toolbar.jsx | 36 +- .../dashboard/roadSafety/operator/index.jsx | 28 +- .../reports/map/ClusterSwitch/index.jsx | 50 +- .../roadSafety/reports/map/Filter/index.jsx | 88 +- .../roadSafety/reports/map/Legend/index.jsx | 96 +- .../DialogInfoItem/ContentInfoItem.jsx | 208 +-- .../map/PointsOnMap/DialogInfoItem/index.jsx | 102 +- .../reports/map/PointsOnMap/index.jsx | 142 +- .../roadSafety/reports/map/index.jsx | 644 ++++----- .../reports/reportPage/ExcelPrint/index.jsx | 134 +- .../reports/reportPage/ReportLists.jsx | 608 ++++----- .../reportPage/Search/FromDateController.jsx | 56 +- .../reportPage/Search/SearchReportField.jsx | 98 +- .../reportPage/Search/SelectAxisType.jsx | 90 +- .../reportPage/Search/SelectProvince.jsx | 90 +- .../reportPage/Search/ToDateController.jsx | 60 +- .../reports/reportPage/Search/index.jsx | 26 +- .../roadSafety/reports/reportPage/Toolbar.jsx | 22 +- .../roadSafety/reports/reportPage/index.jsx | 528 +++---- .../supervisor/ExcelPrint/index.jsx | 148 +- .../roadSafety/supervisor/Learn/index.jsx | 78 +- .../ActionPictureContent.jsx | 88 +- .../RowActions/ActionPictureDialog/index.jsx | 80 +- .../RowActions/ConfirmForm/ConfirmContent.jsx | 140 +- .../RowActions/ConfirmForm/index.jsx | 58 +- .../RowActions/DeleteDialog/DeleteContent.jsx | 84 +- .../RowActions/DeleteDialog/index.jsx | 64 +- .../RowActions/DescriptionForm/index.jsx | 102 +- .../FinishDescriptionForm/index.jsx | 102 +- .../JudiciaryDocumentContent.jsx | 86 +- .../JudiciaryDocumentController.jsx | 70 +- .../JudiciaryDocumentDialog/index.jsx | 80 +- .../LocationForm/LocationFormContent.jsx | 70 +- .../RowActions/LocationForm/index.jsx | 80 +- .../OperatorDescriptionForm/index.jsx | 102 +- .../RecognizePictureContent.jsx | 88 +- .../RecognizePictureDialog/index.jsx | 80 +- .../RowActions/RejectForm/RejectContent.jsx | 166 +-- .../RowActions/RejectForm/index.jsx | 58 +- .../supervisor/RowActions/index.jsx | 44 +- .../roadSafety/supervisor/SupervisorList.jsx | 1212 ++++++++--------- .../roadSafety/supervisor/Toolbar.jsx | 26 +- .../dashboard/roadSafety/supervisor/index.jsx | 28 +- .../Actions/Create/Form/ActionTypeList.jsx | 76 +- .../Actions/Create/Form/CreateFormContent.jsx | 196 +-- .../Actions/Create/Form/index.jsx | 116 +- .../userActivities/Actions/Create/index.jsx | 72 +- .../Actions/Edit/EditController.jsx | 76 +- .../userActivities/Actions/Edit/index.jsx | 102 +- .../RowActions/DeleteDialog/DeleteContent.jsx | 78 +- .../RowActions/DeleteDialog/index.jsx | 68 +- .../userActivities/RowActions/index.jsx | 24 +- .../dashboard/userActivities/Toolbar.jsx | 18 +- .../userActivities/UserActivitiesList.jsx | 166 +-- .../dashboard/userActivities/index.jsx | 26 +- .../Form/CreateTollHouse/CityContent.jsx | 66 +- .../Form/CreateTollHouse/CityController.jsx | 28 +- .../CreateTollHouseContent.jsx | 384 +++--- .../Form/CreateTollHouse/ImageUpload.jsx | 154 +-- .../CreateTollHouse/LogesticController.jsx | 84 +- .../Form/CreateTollHouse/MachineInfo.jsx | 398 +++--- .../Form/CreateTollHouse/TollHouseInfo.jsx | 622 ++++----- .../CreateTollHouse/TollHouseLocation.jsx | 40 +- .../tollHouse/Form/CreateTollHouse/index.jsx | 280 ++-- .../tollHouse/Form/Edit/EditController.jsx | 214 +-- .../tollHouse/Form/Edit/index.jsx | 118 +- .../RowActions/DeleteDialog/DeleteContent.jsx | 78 +- .../RowActions/DeleteDialog/index.jsx | 68 +- .../RowActions/ImageForm/ImageFormContent.jsx | 90 +- .../RowActions/ImageForm/ImagesContent.jsx | 78 +- .../tollHouse/RowActions/ImageForm/index.jsx | 86 +- .../LocationForm/LocationFormContent.jsx | 70 +- .../RowActions/LocationForm/index.jsx | 76 +- .../tollHouse/RowActions/index.jsx | 42 +- .../tollHouse/TollHouseList.jsx | 824 +++++------ .../infrastructure/tollHouse/Toolbar.jsx | 20 +- .../infrastructure/tollHouse/index.jsx | 28 +- .../headerWithLogo/HaederBottom/index.jsx | 90 +- .../dashboard/headerWithLogo/index.jsx | 22 +- .../headerWithSidebar/HeaderMenu/index.jsx | 90 +- .../Sidebar/SidebarBadge.jsx | 38 +- .../Sidebar/SidebarListItems.jsx | 180 +-- .../headerWithSidebar/Sidebar/SidebarMenu.jsx | 244 ++-- .../Sidebar/SidebarSubitems.jsx | 200 +-- .../dashboard/headerWithSidebar/index.jsx | 310 ++--- src/core/components/ActivityCodeLog.jsx | 78 +- .../ApplicantRequestDetail/DetailItem.jsx | 104 +- .../ApplicantRequestDetail/DetailMap.jsx | 78 +- .../ApplicantRequestDetail/FlyToPolygon.jsx | 44 +- .../ApplicantRequestDetail/FlyToPolyline.jsx | 42 +- .../ApplicantRequestDetail/index.jsx | 114 +- src/core/components/BlinkingCell.jsx | 24 +- src/core/components/BlinkingCircle.jsx | 48 +- src/core/components/CarCode.jsx | 206 +-- src/core/components/CustomDatePicker.jsx | 106 +- src/core/components/DataTable/Main.js | 358 ++--- .../components/DataTable/body/TableBody.js | 382 +++--- .../DataTable/body/TableBodyCell.js | 510 +++---- .../DataTable/body/TableBodyCellValue.js | 206 +-- .../components/DataTable/body/TableBodyRow.js | 432 +++--- .../DataTable/body/TableDetailPanel.js | 174 +-- .../DataTable/buttons/CopyButton.js | 136 +- .../DataTable/buttons/GrabHandleButton.js | 92 +- .../DataTable/buttons/ToggleFiltersButton.js | 8 +- .../DataTable/filter/FilterBody.jsx | 260 ++-- .../DataTable/filter/FilterBodyController.jsx | 50 +- .../FilterBodyControllerWithDependency.jsx | 54 +- .../DataTable/filter/FilterBodyField.jsx | 208 +-- .../DataTable/filter/FilterButton.jsx | 74 +- .../DataTable/filter/FilterCustom.jsx | 64 +- .../DataTable/filter/FilterHeader.jsx | 68 +- .../DataTable/filter/FilterOptionList.jsx | 94 +- .../CustomDate/CustomDatePicker.jsx | 46 +- .../CustomDate/CustomDatePickerRange.jsx | 82 +- .../fieldsType/CustomDate/MuiDatePicker.jsx | 144 +- .../filter/fieldsType/CustomSelect.jsx | 60 +- .../fieldsType/CustomSelectByDependency.jsx | 88 +- .../fieldsType/CustomSelectMultiple.jsx | 120 +- .../filter/fieldsType/CustomTextField.jsx | 82 +- .../fieldsType/CustomTextFieldRange.jsx | 124 +- .../components/DataTable/filter/index.jsx | 70 +- .../components/DataTable/head/TableHead.js | 102 +- .../DataTable/head/TableHeadCell.js | 488 +++---- .../components/DataTable/head/TableHeadRow.js | 116 +- .../components/DataTable/hide/HideBody.jsx | 96 +- .../DataTable/hide/HideBodyField.jsx | 152 +-- .../components/DataTable/hide/HideButton.jsx | 70 +- .../components/DataTable/hide/HideHeader.jsx | 68 +- .../DataTable/hide/HideOrShowAll.jsx | 140 +- src/core/components/DataTable/hide/index.jsx | 48 +- src/core/components/DataTable/index.js | 36 +- .../DataTable/localization/fa/datatable.js | 182 +-- .../DataTable/menus/ActionMenuItem.js | 76 +- .../DataTable/menus/CellActionMenu.js | 188 +-- .../DataTable/reset/ResetStorage.jsx | 72 +- src/core/components/DataTable/table/Paper.js | 200 +-- src/core/components/DataTable/table/Table.js | 146 +- .../DataTable/table/TableContainer.js | 144 +- .../DataTable/table/TableLoadingOverlay.js | 88 +- .../DataTable/toolbar/BottomToolbar.js | 144 +- .../DataTable/toolbar/LinearProgressBar.js | 80 +- .../DataTable/toolbar/TablePagination.js | 436 +++--- .../DataTable/toolbar/TopToolbar.js | 276 ++-- .../DataTable/update/UpdateTable.jsx | 38 +- src/core/components/DataTableWithAuth.jsx | 16 +- src/core/components/DialogLoading.jsx | 72 +- src/core/components/DialogTransition.jsx | 16 +- .../FilterDrawer/FilterController.jsx | 50 +- .../FilterControllerWithDependency.jsx | 54 +- .../components/FilterDrawer/FilterField.jsx | 206 +-- .../FilterDrawer/FilterOptionList.jsx | 94 +- .../CustomDate/CustomDatePicker.jsx | 46 +- .../CustomDate/CustomDatePickerRange.jsx | 82 +- .../fieldsType/CustomDate/MuiDatePicker.jsx | 144 +- .../FilterDrawer/fieldsType/CustomSelect.jsx | 60 +- .../fieldsType/CustomSelectByDependency.jsx | 60 +- .../fieldsType/CustomSelectMultiple.jsx | 110 +- .../fieldsType/CustomTextField.jsx | 58 +- .../fieldsType/CustomTextFieldRange.jsx | 124 +- src/core/components/FilterDrawer/index.jsx | 306 ++--- src/core/components/FlyToLocation.jsx | 64 +- src/core/components/FormMaker/DateType.jsx | 70 +- src/core/components/FormMaker/InputType.jsx | 62 +- src/core/components/FormMaker/SelectType.jsx | 68 +- src/core/components/FormMaker/index.jsx | 66 +- src/core/components/HourSelect.jsx | 52 +- src/core/components/LoadingHardPage.jsx | 122 +- src/core/components/LtrTextField.jsx | 20 +- src/core/components/MapInfoOneMarker.jsx | 362 ++--- src/core/components/MapInfoTwoMarker.jsx | 534 ++++---- .../components/MapLayer/Loading/index.jsx | 26 +- src/core/components/MapLayer/index.jsx | 86 +- src/core/components/MuiDatePicker.jsx | 154 +-- src/core/components/MuiTimePicker.jsx | 165 +-- .../NotificationDesign/AskForKeepData.jsx | 130 +- src/core/components/NumberField.jsx | 58 +- src/core/components/PageLoading.jsx | 24 +- src/core/components/PageTitle.jsx | 36 +- src/core/components/PersianTextField.jsx | 36 +- src/core/components/PlateNumber.jsx | 394 +++--- .../components/Profile/ChangePass/Form.jsx | 304 ++--- .../components/Profile/ChangePass/index.jsx | 94 +- .../components/Profile/ProfileActions.jsx | 122 +- src/core/components/Profile/ProfileInfo.jsx | 76 +- src/core/components/Profile/Update/Form.jsx | 514 +++---- src/core/components/Profile/Update/index.jsx | 88 +- src/core/components/Profile/index.jsx | 44 +- src/core/components/RahdarCode.jsx | 194 +-- src/core/components/ScrollBox.jsx | 38 +- src/core/components/SelectBox.jsx | 118 +- src/core/components/ShowLocationMarker.jsx | 362 ++--- src/core/components/ShowPlak.jsx | 124 +- src/core/components/StyledForm.jsx | 10 +- src/core/components/Toasts/error.jsx | 432 +++--- src/core/components/Toasts/success.jsx | 66 +- src/core/components/UploadSystem.jsx | 190 +-- src/core/components/svgs/SvgError.jsx | 188 +-- src/core/components/svgs/SvgLoading.jsx | 584 ++++---- src/core/components/svgs/SvgNotFound.jsx | 324 ++--- src/core/middlewares/withAuth.js | 44 +- src/core/middlewares/withPermission.js | 74 +- .../utils/DataTableFilterDataStructure.js | 20 +- src/core/utils/cacheRtl.js | 56 +- src/core/utils/errorResponse.js | 130 +- src/core/utils/filterMenuItems.js | 34 +- src/core/utils/flattenArrayOfObjects.js | 18 +- src/core/utils/flattenObjectOfObjects.js | 24 +- src/core/utils/formatCounter.js | 14 +- src/core/utils/formatSecondsToHHMMSS.js | 20 +- src/core/utils/getValueByPath.js | 28 +- src/core/utils/headerMenu.js | 164 +-- src/core/utils/isArrayEmpty.js | 12 +- src/core/utils/machineTypes.js | 4 + src/core/utils/nationalCodeValidation.js | 60 +- src/core/utils/pageMenu.js | 1088 +++++++-------- src/core/utils/pageMenuDev.js | 1127 +++++++-------- src/core/utils/routes.js | 371 ++--- src/core/utils/successRequest.js | 20 +- src/core/utils/theme.js | 72 +- src/core/utils/utils.js | 270 ++-- src/lib/contexts/DataTable.js | 358 ++--- src/lib/contexts/auth.js | 188 +-- src/lib/contexts/tableSetting.js | 268 ++-- src/lib/hooks/useAzmayesh.js | 60 +- src/lib/hooks/useCities.js | 118 +- src/lib/hooks/useDamageItemList.js | 58 +- src/lib/hooks/useDataTable.js | 20 +- src/lib/hooks/useEdaratLists.js | 124 +- src/lib/hooks/usePermissions.js | 36 +- src/lib/hooks/usePersianInput.js | 98 +- src/lib/hooks/usePrevStateopinion.js | 62 +- src/lib/hooks/useProvince.js | 58 +- src/lib/hooks/useRequest.js | 120 +- src/lib/hooks/useRoadItemGetISubtems.js | 124 +- src/lib/hooks/useRoadItemGetItems.js | 60 +- src/lib/hooks/useSafetyAndPrivacyGetItems.js | 60 +- src/lib/hooks/useSidebarBadge.js | 32 +- src/lib/hooks/useTableSetting.js | 18 +- 734 files changed, 48930 insertions(+), 46048 deletions(-) create mode 100644 src/app/(withAuth)/(dashboardLayout)/dashboard/road-missions/control/page.js create mode 100644 src/app/(withAuth)/(dashboardLayout)/dashboard/road-missions/operator/page.js create mode 100644 src/app/(withAuth)/(dashboardLayout)/dashboard/road-missions/transportation/page.js create mode 100644 src/components/dashboard/roadMissions/control/Actions/showArea/index.jsx create mode 100644 src/components/dashboard/roadMissions/control/Actions/showBound/index.jsx create mode 100644 src/components/dashboard/roadMissions/control/ControlList.jsx create mode 100644 src/components/dashboard/roadMissions/control/RowActions/FinishMission/FinishMissionContent.jsx create mode 100644 src/components/dashboard/roadMissions/control/RowActions/FinishMission/index.jsx create mode 100644 src/components/dashboard/roadMissions/control/RowActions/StartMission/StartMissionContent.jsx create mode 100644 src/components/dashboard/roadMissions/control/RowActions/StartMission/index.jsx create mode 100644 src/components/dashboard/roadMissions/control/RowActions/index.jsx create mode 100644 src/components/dashboard/roadMissions/control/index.jsx create mode 100644 src/components/dashboard/roadMissions/operator/Actions/Create/Form/Area/MapControl/DrawBound/index.jsx create mode 100644 src/components/dashboard/roadMissions/operator/Actions/Create/Form/Area/MapControl/index.jsx create mode 100644 src/components/dashboard/roadMissions/operator/Actions/Create/Form/Area/index.jsx create mode 100644 src/components/dashboard/roadMissions/operator/Actions/Create/Form/GetItemInfo/MissionDates/index.jsx create mode 100644 src/components/dashboard/roadMissions/operator/Actions/Create/Form/GetItemInfo/index.jsx create mode 100644 src/components/dashboard/roadMissions/operator/Actions/Create/Form/Rahdaran/Form/index.jsx create mode 100644 src/components/dashboard/roadMissions/operator/Actions/Create/Form/Rahdaran/List/index.jsx create mode 100644 src/components/dashboard/roadMissions/operator/Actions/Create/Form/Rahdaran/index.jsx create mode 100644 src/components/dashboard/roadMissions/operator/Actions/Create/Form/RequestMachines/Form/index.jsx create mode 100644 src/components/dashboard/roadMissions/operator/Actions/Create/Form/RequestMachines/List/index.jsx create mode 100644 src/components/dashboard/roadMissions/operator/Actions/Create/Form/RequestMachines/index.jsx create mode 100644 src/components/dashboard/roadMissions/operator/Actions/Create/Form/Verify/index.jsx create mode 100644 src/components/dashboard/roadMissions/operator/Actions/Create/Form/index.jsx create mode 100644 src/components/dashboard/roadMissions/operator/Actions/Create/index.jsx create mode 100644 src/components/dashboard/roadMissions/operator/Actions/showArea/index.jsx create mode 100644 src/components/dashboard/roadMissions/operator/Actions/showBound/index.jsx create mode 100644 src/components/dashboard/roadMissions/operator/OperatorList.jsx create mode 100644 src/components/dashboard/roadMissions/operator/RowActions/Delete/DeleteContent.jsx create mode 100644 src/components/dashboard/roadMissions/operator/RowActions/Delete/index.jsx create mode 100644 src/components/dashboard/roadMissions/operator/RowActions/Edit/EditController/index.jsx create mode 100644 src/components/dashboard/roadMissions/operator/RowActions/Edit/index.jsx create mode 100644 src/components/dashboard/roadMissions/operator/RowActions/index.jsx create mode 100644 src/components/dashboard/roadMissions/operator/Toolbar.jsx create mode 100644 src/components/dashboard/roadMissions/operator/index.jsx create mode 100644 src/components/dashboard/roadMissions/transportation/Actions/showArea/index.jsx create mode 100644 src/components/dashboard/roadMissions/transportation/Actions/showBound/index.jsx create mode 100644 src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/MachinesDialog/MachineList/RowActions/Allocate/index.jsx create mode 100644 src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/MachinesDialog/MachineList/RowActions/index.jsx create mode 100644 src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/MachinesDialog/MachineList/index.jsx create mode 100644 src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/MachinesDialog/index.jsx create mode 100644 src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/Reject/Form/index.jsx create mode 100644 src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/Reject/index.jsx create mode 100644 src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/index.jsx create mode 100644 src/components/dashboard/roadMissions/transportation/RowActions/Allocation/index.jsx create mode 100644 src/components/dashboard/roadMissions/transportation/RowActions/index.jsx create mode 100644 src/components/dashboard/roadMissions/transportation/TransportationList.jsx create mode 100644 src/components/dashboard/roadMissions/transportation/index.jsx create mode 100644 src/core/utils/machineTypes.js diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/azmayesh/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/azmayesh/page.js index 2ef1bbb..5b8177e 100644 --- a/src/app/(withAuth)/(dashboardLayout)/dashboard/azmayesh/page.js +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/azmayesh/page.js @@ -1,18 +1,18 @@ -import AzmayeshPage from "@/components/dashboard/azmayesh"; -import WithPermission from "@/core/middlewares/withPermission"; -import ActivityCodeLog from "@/core/components/ActivityCodeLog"; - -export const metadata = { - title: "کارتابل آزمایشات", -}; - -const Page = () => { - return ( - - - - - ); -}; - -export default Page; +import AzmayeshPage from "@/components/dashboard/azmayesh"; +import WithPermission from "@/core/middlewares/withPermission"; +import ActivityCodeLog from "@/core/components/ActivityCodeLog"; + +export const metadata = { + title: "کارتابل آزمایشات", +}; + +const Page = () => { + return ( + + + + + ); +}; + +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/azmayesh_type/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/azmayesh_type/page.js index 91acd5b..405eb14 100644 --- a/src/app/(withAuth)/(dashboardLayout)/dashboard/azmayesh_type/page.js +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/azmayesh_type/page.js @@ -1,16 +1,16 @@ -import AzmayeshTypePage from "@/components/dashboard/azmayeshType"; -import WithPermission from "@/core/middlewares/withPermission"; -import ActivityCodeLog from "@/core/components/ActivityCodeLog"; -export const metadata = { - title: "کارتابل نوع آزمایشات", -}; -const Page = () => { - return ( - - - - - ); -}; - -export default Page; +import AzmayeshTypePage from "@/components/dashboard/azmayeshType"; +import WithPermission from "@/core/middlewares/withPermission"; +import ActivityCodeLog from "@/core/components/ActivityCodeLog"; +export const metadata = { + title: "کارتابل نوع آزمایشات", +}; +const Page = () => { + return ( + + + + + ); +}; + +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/damage-items/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/damage-items/page.js index 16459f9..90f9c34 100644 --- a/src/app/(withAuth)/(dashboardLayout)/dashboard/damage-items/page.js +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/damage-items/page.js @@ -1,13 +1,13 @@ -import DamagesPage from "@/components/dashboard/damageItems"; -import WithPermission from "@/core/middlewares/withPermission"; -export const metadata = { - title: "آیتم خسارات", -}; -const Page = () => { - return ( - - - - ); -}; -export default Page; +import DamagesPage from "@/components/dashboard/damageItems"; +import WithPermission from "@/core/middlewares/withPermission"; +export const metadata = { + title: "آیتم خسارات", +}; +const Page = () => { + return ( + + + + ); +}; +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/damages/operator/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/damages/operator/page.js index 323d1f2..10b9ad8 100644 --- a/src/app/(withAuth)/(dashboardLayout)/dashboard/damages/operator/page.js +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/damages/operator/page.js @@ -1,16 +1,16 @@ -import OperatorPage from "@/components/dashboard/damages/operator"; -import ActivityCodeLog from "@/core/components/ActivityCodeLog"; -import WithPermission from "@/core/middlewares/withPermission"; -export const metadata = { - title: "کارتابل عملیات خسارات وارد بر ابنیه فنی", -}; -const Page = () => { - return ( - - - - - ); -}; - -export default Page; +import OperatorPage from "@/components/dashboard/damages/operator"; +import ActivityCodeLog from "@/core/components/ActivityCodeLog"; +import WithPermission from "@/core/middlewares/withPermission"; +export const metadata = { + title: "کارتابل عملیات خسارات وارد بر ابنیه فنی", +}; +const Page = () => { + return ( + + + + + ); +}; + +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/damages/report/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/damages/report/page.js index 1ffbf85..d00843a 100644 --- a/src/app/(withAuth)/(dashboardLayout)/dashboard/damages/report/page.js +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/damages/report/page.js @@ -1,13 +1,13 @@ -import DamagesReportPage from "@/components/dashboard/damages/report"; -import WithPermission from "@/core/middlewares/withPermission"; -export const metadata = { - title: "کارتابل گزارش خسارات وارد بر ابنیه فنی", -}; -const Page = () => { - return ( - - - - ); -}; -export default Page; +import DamagesReportPage from "@/components/dashboard/damages/report"; +import WithPermission from "@/core/middlewares/withPermission"; +export const metadata = { + title: "کارتابل گزارش خسارات وارد بر ابنیه فنی", +}; +const Page = () => { + return ( + + + + ); +}; +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/fast-react/operator/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/fast-react/operator/page.js index a3c82ba..8e59581 100644 --- a/src/app/(withAuth)/(dashboardLayout)/dashboard/fast-react/operator/page.js +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/fast-react/operator/page.js @@ -1,15 +1,15 @@ -import OperatorPage from "@/components/dashboard/fastReact/operator"; -import WithPermission from "@/core/middlewares/withPermission"; -export const metadata = { - title: "کارتابل عملیات واکنش سریع", -}; -const Page = () => { - return ( - - - {/* */} - - ); -}; - -export default Page; +import OperatorPage from "@/components/dashboard/fastReact/operator"; +import WithPermission from "@/core/middlewares/withPermission"; +export const metadata = { + title: "کارتابل عملیات واکنش سریع", +}; +const Page = () => { + return ( + + + {/* */} + + ); +}; + +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/fast-react/supervisor/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/fast-react/supervisor/page.js index e5f8ce8..75f6fac 100644 --- a/src/app/(withAuth)/(dashboardLayout)/dashboard/fast-react/supervisor/page.js +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/fast-react/supervisor/page.js @@ -1,16 +1,16 @@ -import WithPermission from "@/core/middlewares/withPermission"; -import SupervisorPage from "@/components/dashboard/fastReact/supervisor"; -import ActivityCodeLog from "@/core/components/ActivityCodeLog"; -export const metadata = { - title: "کارتابل ارزیابی واکنش سریع", -}; -const Page = () => { - return ( - - - - - ); -}; - -export default Page; +import WithPermission from "@/core/middlewares/withPermission"; +import SupervisorPage from "@/components/dashboard/fastReact/supervisor"; +import ActivityCodeLog from "@/core/components/ActivityCodeLog"; +export const metadata = { + title: "کارتابل ارزیابی واکنش سریع", +}; +const Page = () => { + return ( + + + + + ); +}; + +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/inquiry-privacy/assistant/zamin-gov/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/inquiry-privacy/assistant/zamin-gov/page.js index 6679ae5..d82631a 100644 --- a/src/app/(withAuth)/(dashboardLayout)/dashboard/inquiry-privacy/assistant/zamin-gov/page.js +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/inquiry-privacy/assistant/zamin-gov/page.js @@ -1,12 +1,12 @@ -import AssistantZaminGovComponent from "@/components/dashboard/inquiryPrivacy/assistant/zaminGov"; -import WithPermission from "@/core/middlewares/withPermission"; - -const Page = () => { - return ( - - - - ); -}; - -export default Page; +import AssistantZaminGovComponent from "@/components/dashboard/inquiryPrivacy/assistant/zaminGov"; +import WithPermission from "@/core/middlewares/withPermission"; + +const Page = () => { + return ( + + + + ); +}; + +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/inquiry-privacy/city-admin/zamin-gov/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/inquiry-privacy/city-admin/zamin-gov/page.js index 7293246..d7631c9 100644 --- a/src/app/(withAuth)/(dashboardLayout)/dashboard/inquiry-privacy/city-admin/zamin-gov/page.js +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/inquiry-privacy/city-admin/zamin-gov/page.js @@ -1,12 +1,12 @@ -import CityAdminZaminGovComponent from "@/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov"; -import WithPermission from "@/core/middlewares/withPermission"; - -const Page = () => { - return ( - - - - ); -}; - -export default Page; +import CityAdminZaminGovComponent from "@/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov"; +import WithPermission from "@/core/middlewares/withPermission"; + +const Page = () => { + return ( + + + + ); +}; + +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/inquiry-privacy/general-manager/zamin-gov/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/inquiry-privacy/general-manager/zamin-gov/page.js index 9cb8045..9b9d446 100644 --- a/src/app/(withAuth)/(dashboardLayout)/dashboard/inquiry-privacy/general-manager/zamin-gov/page.js +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/inquiry-privacy/general-manager/zamin-gov/page.js @@ -1,12 +1,12 @@ -import GeneralManagerZaminGovComponent from "@/components/dashboard/inquiryPrivacy/generalManager/zaminGov"; -import WithPermission from "@/core/middlewares/withPermission"; - -const Page = () => { - return ( - - - - ); -}; - -export default Page; +import GeneralManagerZaminGovComponent from "@/components/dashboard/inquiryPrivacy/generalManager/zaminGov"; +import WithPermission from "@/core/middlewares/withPermission"; + +const Page = () => { + return ( + + + + ); +}; + +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/inquiry-privacy/province-admin/zamin-gov/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/inquiry-privacy/province-admin/zamin-gov/page.js index e327c74..0c51a47 100644 --- a/src/app/(withAuth)/(dashboardLayout)/dashboard/inquiry-privacy/province-admin/zamin-gov/page.js +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/inquiry-privacy/province-admin/zamin-gov/page.js @@ -1,12 +1,12 @@ -import ProvinceAdminZaminGovComponent from "@/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov"; -import WithPermission from "@/core/middlewares/withPermission"; - -const Page = () => { - return ( - - - - ); -}; - -export default Page; +import ProvinceAdminZaminGovComponent from "@/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov"; +import WithPermission from "@/core/middlewares/withPermission"; + +const Page = () => { + return ( + + + + ); +}; + +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/loading.jsx b/src/app/(withAuth)/(dashboardLayout)/dashboard/loading.jsx index 4535a8d..c3935ed 100644 --- a/src/app/(withAuth)/(dashboardLayout)/dashboard/loading.jsx +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/loading.jsx @@ -1,7 +1,7 @@ -"use client"; -import PageLoading from "@/core/components/PageLoading"; - -const Loading = () => { - return ; -}; -export default Loading; +"use client"; +import PageLoading from "@/core/components/PageLoading"; + +const Loading = () => { + return ; +}; +export default Loading; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/page.js index 13e6158..7198c02 100644 --- a/src/app/(withAuth)/(dashboardLayout)/dashboard/page.js +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/page.js @@ -1,9 +1,9 @@ -export const metadata = { - title: "پیشخوان", -}; - -const Page = () => { - return <>; -}; - -export default Page; +export const metadata = { + title: "پیشخوان", +}; + +const Page = () => { + return <>; +}; + +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/permissions/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/permissions/page.js index 1dcd0b2..79e03dd 100644 --- a/src/app/(withAuth)/(dashboardLayout)/dashboard/permissions/page.js +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/permissions/page.js @@ -1,13 +1,13 @@ -import WithPermission from "@/core/middlewares/withPermission"; -import PermissionTablePage from "@/components/dashboard/permissionTable"; -export const metadata = { - title: "سطح دسترسی ها", -}; -const Page = () => { - return ( - - - - ); -}; -export default Page; +import WithPermission from "@/core/middlewares/withPermission"; +import PermissionTablePage from "@/components/dashboard/permissionTable"; +export const metadata = { + title: "سطح دسترسی ها", +}; +const Page = () => { + return ( + + + + ); +}; +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/road-items/operator/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-items/operator/page.js index daade12..e7c095a 100644 --- a/src/app/(withAuth)/(dashboardLayout)/dashboard/road-items/operator/page.js +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-items/operator/page.js @@ -1,16 +1,16 @@ -import WithPermission from "@/core/middlewares/withPermission"; -import OperatorPage from "@/components/dashboard/roadItems/operator"; -import ActivityCodeLog from "@/core/components/ActivityCodeLog"; -export const metadata = { - title: "کارتابل عملیات فعالیت روزانه", -}; -const Page = () => { - return ( - - - - - ); -}; - -export default Page; +import WithPermission from "@/core/middlewares/withPermission"; +import OperatorPage from "@/components/dashboard/roadItems/operator"; +import ActivityCodeLog from "@/core/components/ActivityCodeLog"; +export const metadata = { + title: "کارتابل عملیات فعالیت روزانه", +}; +const Page = () => { + return ( + + + + + ); +}; + +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/road-items/reports/items-report/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-items/reports/items-report/page.js index ab16926..e1986d3 100644 --- a/src/app/(withAuth)/(dashboardLayout)/dashboard/road-items/reports/items-report/page.js +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-items/reports/items-report/page.js @@ -1,20 +1,20 @@ -import WithPermission from "@/core/middlewares/withPermission"; -import ReportPage from "@/components/dashboard/roadItems/reports/ItemsReports"; -export const metadata = { - title: "کارتابل گزارش تعداد فعالیت ها به تفکیک آیتم", -}; -const Page = () => { - return ( - - - - ); -}; - -export default Page; +import WithPermission from "@/core/middlewares/withPermission"; +import ReportPage from "@/components/dashboard/roadItems/reports/ItemsReports"; +export const metadata = { + title: "کارتابل گزارش تعداد فعالیت ها به تفکیک آیتم", +}; +const Page = () => { + return ( + + + + ); +}; + +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/road-items/reports/map/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-items/reports/map/page.js index 224a577..8f6439b 100644 --- a/src/app/(withAuth)/(dashboardLayout)/dashboard/road-items/reports/map/page.js +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-items/reports/map/page.js @@ -1,9 +1,9 @@ -import RoadItemsReportMap from "@/components/dashboard/roadItems/reports/Map"; -export const metadata = { - title: "پراکندگی بر روی نقشه فعالیت روزانه", -}; - -const Page = () => { - return ; -}; -export default Page; +import RoadItemsReportMap from "@/components/dashboard/roadItems/reports/Map"; +export const metadata = { + title: "پراکندگی بر روی نقشه فعالیت روزانه", +}; + +const Page = () => { + return ; +}; +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/road-items/reports/sub-items-report/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-items/reports/sub-items-report/page.js index a83d75f..26b8ea6 100644 --- a/src/app/(withAuth)/(dashboardLayout)/dashboard/road-items/reports/sub-items-report/page.js +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-items/reports/sub-items-report/page.js @@ -1,20 +1,20 @@ -import WithPermission from "@/core/middlewares/withPermission"; -import SubItemsReports from "@/components/dashboard/roadItems/reports/SubItemsReports"; -export const metadata = { - title: "کارتابل گزارش تعداد فعالیت ها به تفکیک موارد مشاهده شده", -}; -const Page = () => { - return ( - - - - ); -}; - -export default Page; +import WithPermission from "@/core/middlewares/withPermission"; +import SubItemsReports from "@/components/dashboard/roadItems/reports/SubItemsReports"; +export const metadata = { + title: "کارتابل گزارش تعداد فعالیت ها به تفکیک موارد مشاهده شده", +}; +const Page = () => { + return ( + + + + ); +}; + +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/road-items/supervisor/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-items/supervisor/page.js index 2773189..097aad6 100644 --- a/src/app/(withAuth)/(dashboardLayout)/dashboard/road-items/supervisor/page.js +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-items/supervisor/page.js @@ -1,18 +1,18 @@ -import WithPermission from "@/core/middlewares/withPermission"; -import SupervisorPage from "@/components/dashboard/roadItems/supervisor"; -import ActivityCodeLog from "@/core/components/ActivityCodeLog"; -export const metadata = { - title: "کارتابل ارزیابی فعالیت روزانه", -}; -const Page = () => { - return ( - - - - - ); -}; - -export default Page; +import WithPermission from "@/core/middlewares/withPermission"; +import SupervisorPage from "@/components/dashboard/roadItems/supervisor"; +import ActivityCodeLog from "@/core/components/ActivityCodeLog"; +export const metadata = { + title: "کارتابل ارزیابی فعالیت روزانه", +}; +const Page = () => { + return ( + + + + + ); +}; + +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/road-missions/control/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-missions/control/page.js new file mode 100644 index 0000000..1fd96ba --- /dev/null +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-missions/control/page.js @@ -0,0 +1,17 @@ +import ControlPage from "@/components/dashboard/roadMissions/control"; + +export const metadata = { + title: "کارتابل کنترل", +}; +const Page = () => { + return ( + <> + {/* */} + + {/* */} + {/* */} + + ); +}; + +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/road-missions/operator/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-missions/operator/page.js new file mode 100644 index 0000000..55f3975 --- /dev/null +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-missions/operator/page.js @@ -0,0 +1,18 @@ +import WithPermission from "@/core/middlewares/withPermission"; +import ActivityCodeLog from "@/core/components/ActivityCodeLog"; +import OperatorPage from "@/components/dashboard/roadMissions/operator"; +export const metadata = { + title: "کارتابل ماموریت", +}; +const Page = () => { + return ( + <> + {/* */} + + {/* */} + {/* */} + + ); +}; + +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/road-missions/transportation/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-missions/transportation/page.js new file mode 100644 index 0000000..187f888 --- /dev/null +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-missions/transportation/page.js @@ -0,0 +1,17 @@ +import TransportationPage from "@/components/dashboard/roadMissions/transportation"; + +export const metadata = { + title: "کارتابل نقلیه", +}; +const Page = () => { + return ( + <> + {/* */} + + {/* */} + {/* */} + + ); +}; + +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/road-patrols/operator/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-patrols/operator/page.js index 77560bd..2007b89 100644 --- a/src/app/(withAuth)/(dashboardLayout)/dashboard/road-patrols/operator/page.js +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-patrols/operator/page.js @@ -1,17 +1,17 @@ -import WithPermission from "@/core/middlewares/withPermission"; -import OperatorPage from "@/components/dashboard/roadPatrols/operator"; -import ActivityCodeLog from "@/core/components/ActivityCodeLog"; -export const metadata = { - title: "کارتابل عملیات گشت راهداری", -}; - -const Page = () => { - return ( - - - - - ); -}; - -export default Page; +import WithPermission from "@/core/middlewares/withPermission"; +import OperatorPage from "@/components/dashboard/roadPatrols/operator"; +import ActivityCodeLog from "@/core/components/ActivityCodeLog"; +export const metadata = { + title: "کارتابل عملیات گشت راهداری", +}; + +const Page = () => { + return ( + + + + + ); +}; + +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/road-patrols/reports/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-patrols/reports/page.js index 48e1056..cb92e77 100644 --- a/src/app/(withAuth)/(dashboardLayout)/dashboard/road-patrols/reports/page.js +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-patrols/reports/page.js @@ -1,20 +1,20 @@ -import WithPermission from "@/core/middlewares/withPermission"; -import ReportPage from "@/components/dashboard/roadPatrols/reports"; -export const metadata = { - title: "کارتابل گزارش گشت راهداری", -}; -const Page = () => { - return ( - - - - ); -}; - -export default Page; +import WithPermission from "@/core/middlewares/withPermission"; +import ReportPage from "@/components/dashboard/roadPatrols/reports"; +export const metadata = { + title: "کارتابل گزارش گشت راهداری", +}; +const Page = () => { + return ( + + + + ); +}; + +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/road-patrols/supervisor/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-patrols/supervisor/page.js index b7404bc..14a79bc 100644 --- a/src/app/(withAuth)/(dashboardLayout)/dashboard/road-patrols/supervisor/page.js +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-patrols/supervisor/page.js @@ -1,18 +1,18 @@ -import WithPermission from "@/core/middlewares/withPermission"; -import SupervisorPage from "@/components/dashboard/roadPatrols/supervisor"; -import ActivityCodeLog from "@/core/components/ActivityCodeLog"; -export const metadata = { - title: "کارتابل ارزیابی گشت راهداری", -}; -const Page = () => { - return ( - - - - - ); -}; - -export default Page; +import WithPermission from "@/core/middlewares/withPermission"; +import SupervisorPage from "@/components/dashboard/roadPatrols/supervisor"; +import ActivityCodeLog from "@/core/components/ActivityCodeLog"; +export const metadata = { + title: "کارتابل ارزیابی گشت راهداری", +}; +const Page = () => { + return ( + + + + + ); +}; + +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/road-safety/operator/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-safety/operator/page.js index ecf5a33..49ec925 100644 --- a/src/app/(withAuth)/(dashboardLayout)/dashboard/road-safety/operator/page.js +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-safety/operator/page.js @@ -1,16 +1,16 @@ -import WithPermission from "@/core/middlewares/withPermission"; -import OperatorPage from "@/components/dashboard/roadSafety/operator"; -// import ActivityCodeLog from "@/core/components/ActivityCodeLog"; -export const metadata = { - title: "کارتابل عملیات نگهداری حریم", -}; -const Page = () => { - return ( - - - {/**/} - - ); -}; - -export default Page; +import WithPermission from "@/core/middlewares/withPermission"; +import OperatorPage from "@/components/dashboard/roadSafety/operator"; +// import ActivityCodeLog from "@/core/components/ActivityCodeLog"; +export const metadata = { + title: "کارتابل عملیات نگهداری حریم", +}; +const Page = () => { + return ( + + + {/**/} + + ); +}; + +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/road-safety/reports/map/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-safety/reports/map/page.js index b272e5e..b06ad1c 100644 --- a/src/app/(withAuth)/(dashboardLayout)/dashboard/road-safety/reports/map/page.js +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-safety/reports/map/page.js @@ -1,9 +1,9 @@ -import RoadSafetyReportMap from "@/components/dashboard/roadSafety/reports/map"; -export const metadata = { - title: "پراکندگی بر روی نقشه نگهداری حریم", -}; - -const Page = () => { - return ; -}; -export default Page; +import RoadSafetyReportMap from "@/components/dashboard/roadSafety/reports/map"; +export const metadata = { + title: "پراکندگی بر روی نقشه نگهداری حریم", +}; + +const Page = () => { + return ; +}; +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/road-safety/reports/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-safety/reports/page.js index 54df8d0..909de14 100644 --- a/src/app/(withAuth)/(dashboardLayout)/dashboard/road-safety/reports/page.js +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-safety/reports/page.js @@ -1,19 +1,19 @@ -import ReportPage from "@/components/dashboard/roadSafety/reports/reportPage"; -import WithPermission from "@/core/middlewares/withPermission"; -export const metadata = { - title: "کارتابل گزارش نگهداری حریم", -}; -const Page = () => { - return ( - - - - ); -}; -export default Page; +import ReportPage from "@/components/dashboard/roadSafety/reports/reportPage"; +import WithPermission from "@/core/middlewares/withPermission"; +export const metadata = { + title: "کارتابل گزارش نگهداری حریم", +}; +const Page = () => { + return ( + + + + ); +}; +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/road-safety/supervisor/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-safety/supervisor/page.js index 6ef1822..590d405 100644 --- a/src/app/(withAuth)/(dashboardLayout)/dashboard/road-safety/supervisor/page.js +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/road-safety/supervisor/page.js @@ -1,21 +1,21 @@ -import SupervisorPage from "@/components/dashboard/roadSafety/supervisor"; -import WithPermission from "@/core/middlewares/withPermission"; -// import ActivityCodeLog from "@/core/components/ActivityCodeLog"; -export const metadata = { - title: "کارتابل ارزیابی نگهداری حریم", -}; -const Page = () => { - return ( - - - {/**/} - - ); -}; - -export default Page; +import SupervisorPage from "@/components/dashboard/roadSafety/supervisor"; +import WithPermission from "@/core/middlewares/withPermission"; +// import ActivityCodeLog from "@/core/components/ActivityCodeLog"; +export const metadata = { + title: "کارتابل ارزیابی نگهداری حریم", +}; +const Page = () => { + return ( + + + {/**/} + + ); +}; + +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/dashboard/user-activities/page.js b/src/app/(withAuth)/(dashboardLayout)/dashboard/user-activities/page.js index c671c77..b50a6be 100644 --- a/src/app/(withAuth)/(dashboardLayout)/dashboard/user-activities/page.js +++ b/src/app/(withAuth)/(dashboardLayout)/dashboard/user-activities/page.js @@ -1,13 +1,13 @@ -import UserActivitiesPage from "@/components/dashboard/userActivities"; -import WithPermission from "@/core/middlewares/withPermission"; -export const metadata = { - title: "انواع فعالیت کاربران", -}; -const Page = () => { - return ( - - - - ); -}; -export default Page; +import UserActivitiesPage from "@/components/dashboard/userActivities"; +import WithPermission from "@/core/middlewares/withPermission"; +export const metadata = { + title: "انواع فعالیت کاربران", +}; +const Page = () => { + return ( + + + + ); +}; +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/infrastructure/toll-house/loading.jsx b/src/app/(withAuth)/(dashboardLayout)/infrastructure/toll-house/loading.jsx index 4535a8d..c3935ed 100644 --- a/src/app/(withAuth)/(dashboardLayout)/infrastructure/toll-house/loading.jsx +++ b/src/app/(withAuth)/(dashboardLayout)/infrastructure/toll-house/loading.jsx @@ -1,7 +1,7 @@ -"use client"; -import PageLoading from "@/core/components/PageLoading"; - -const Loading = () => { - return ; -}; -export default Loading; +"use client"; +import PageLoading from "@/core/components/PageLoading"; + +const Loading = () => { + return ; +}; +export default Loading; diff --git a/src/app/(withAuth)/(dashboardLayout)/infrastructure/toll-house/page.js b/src/app/(withAuth)/(dashboardLayout)/infrastructure/toll-house/page.js index ca84816..96b18bd 100644 --- a/src/app/(withAuth)/(dashboardLayout)/infrastructure/toll-house/page.js +++ b/src/app/(withAuth)/(dashboardLayout)/infrastructure/toll-house/page.js @@ -1,16 +1,16 @@ -import WithPermission from "@/core/middlewares/withPermission"; -import TollHousePage from "@/components/infrastructure/tollHouse"; - -export const metadata = { - title: "لیست راهدارخانه ها", -}; - -const Page = () => { - return ( - - - - ); -}; - -export default Page; +import WithPermission from "@/core/middlewares/withPermission"; +import TollHousePage from "@/components/infrastructure/tollHouse"; + +export const metadata = { + title: "لیست راهدارخانه ها", +}; + +const Page = () => { + return ( + + + + ); +}; + +export default Page; diff --git a/src/app/(withAuth)/(dashboardLayout)/layout.js b/src/app/(withAuth)/(dashboardLayout)/layout.js index f13663c..a3e4d16 100644 --- a/src/app/(withAuth)/(dashboardLayout)/layout.js +++ b/src/app/(withAuth)/(dashboardLayout)/layout.js @@ -1,17 +1,17 @@ -"use client"; -import HeaderWithLogo from "@/components/layouts/dashboard/headerWithLogo"; -import HeaderWithSidebar from "@/components/layouts/dashboard/headerWithSidebar"; -import { Stack } from "@mui/material"; -import { SWRConfig } from "swr"; - -const Layout = ({ children }) => { - return ( - new Map() }}> - - - {children} - - - ); -}; -export default Layout; +"use client"; +import HeaderWithLogo from "@/components/layouts/dashboard/headerWithLogo"; +import HeaderWithSidebar from "@/components/layouts/dashboard/headerWithSidebar"; +import { Stack } from "@mui/material"; +import { SWRConfig } from "swr"; + +const Layout = ({ children }) => { + return ( + new Map() }}> + + + {children} + + + ); +}; +export default Layout; diff --git a/src/app/(withAuth)/layout.js b/src/app/(withAuth)/layout.js index 62cbf6d..e14c227 100644 --- a/src/app/(withAuth)/layout.js +++ b/src/app/(withAuth)/layout.js @@ -1,31 +1,31 @@ -"use client"; -import { useAuth } from "@/lib/contexts/auth"; -import { Typography, Stack } from "@mui/material"; -import WithAuthMiddleware from "@/core/middlewares/withAuth"; -import LoadingHardPage from "@/core/components/LoadingHardPage"; - -const Layout = ({ children }) => { - const { isAuth, initAuthState, errorState } = useAuth(); - - if (!initAuthState && !isAuth) - return ( - - {errorState.message} - کد : {errorState.status} - - ) : ( - درحال احراز هویت... - ) - } - loading={true} - /> - ); - - return {children}; -}; - -export default Layout; +"use client"; +import { useAuth } from "@/lib/contexts/auth"; +import { Typography, Stack } from "@mui/material"; +import WithAuthMiddleware from "@/core/middlewares/withAuth"; +import LoadingHardPage from "@/core/components/LoadingHardPage"; + +const Layout = ({ children }) => { + const { isAuth, initAuthState, errorState } = useAuth(); + + if (!initAuthState && !isAuth) + return ( + + {errorState.message} + کد : {errorState.status} + + ) : ( + درحال احراز هویت... + ) + } + loading={true} + /> + ); + + return {children}; +}; + +export default Layout; diff --git a/src/app/api/fake-cities/route.js b/src/app/api/fake-cities/route.js index 091e090..ac9b26a 100644 --- a/src/app/api/fake-cities/route.js +++ b/src/app/api/fake-cities/route.js @@ -1,18 +1,18 @@ -const data = [ - { - id: 1, - name: "تهران", - }, - { - id: 2, - name: "ری", - }, - { - id: 3, - name: "اندیشه", - }, -]; - -export async function GET() { - return Response.json({ data }); -} +const data = [ + { + id: 1, + name: "تهران", + }, + { + id: 2, + name: "ری", + }, + { + id: 3, + name: "اندیشه", + }, +]; + +export async function GET() { + return Response.json({ data }); +} diff --git a/src/app/api/fake-data/route.js b/src/app/api/fake-data/route.js index 684c603..9b2d7aa 100644 --- a/src/app/api/fake-data/route.js +++ b/src/app/api/fake-data/route.js @@ -1,41 +1,41 @@ -const data = [ - { - id: 1, - aplication_number: 1, - application_date: "1", - province: "tehran", - city: "tehran", - }, - { - id: 2, - aplication_number: 2, - application_date: "1", - province: "tehran", - city: "tehran", - }, - { - id: 3, - aplication_number: 3, - application_date: "1", - province: "tehran", - city: "tehran", - }, - { - id: 4, - aplication_number: 4, - application_date: "1", - province: "tehran", - city: "tehran", - }, - { - id: 5, - aplication_number: 5, - application_date: "1", - province: "tehran", - city: "tehran", - }, -]; - -export async function GET() { - return Response.json({ data }); -} +const data = [ + { + id: 1, + aplication_number: 1, + application_date: "1", + province: "tehran", + city: "tehran", + }, + { + id: 2, + aplication_number: 2, + application_date: "1", + province: "tehran", + city: "tehran", + }, + { + id: 3, + aplication_number: 3, + application_date: "1", + province: "tehran", + city: "tehran", + }, + { + id: 4, + aplication_number: 4, + application_date: "1", + province: "tehran", + city: "tehran", + }, + { + id: 5, + aplication_number: 5, + application_date: "1", + province: "tehran", + city: "tehran", + }, +]; + +export async function GET() { + return Response.json({ data }); +} diff --git a/src/app/api/fake-prev-state-opinion/route.js b/src/app/api/fake-prev-state-opinion/route.js index abd03e4..43eb052 100644 --- a/src/app/api/fake-prev-state-opinion/route.js +++ b/src/app/api/fake-prev-state-opinion/route.js @@ -1,9 +1,9 @@ -export async function GET() { - return Response.json({ - message: - "به موجب این نامه، به استحضار جنابعالی می رساند، این‌ جانب ……… از تاریخ ……… افتخار همکاری\n" + - "با مجموعه ……… را دارم. اما متاسفانه، به علت ………، تقاضای استعفای خود را از تاریخ ………\n" + - "اعلام میدارم. ضمن تشکر پیشاپیش از همکاری شما خواهشمند است، دستور اقدامات لازم در این\n" + - "زمینه را صادر فرمایید.", - }); -} +export async function GET() { + return Response.json({ + message: + "به موجب این نامه، به استحضار جنابعالی می رساند، این‌ جانب ……… از تاریخ ……… افتخار همکاری\n" + + "با مجموعه ……… را دارم. اما متاسفانه، به علت ………، تقاضای استعفای خود را از تاریخ ………\n" + + "اعلام میدارم. ضمن تشکر پیشاپیش از همکاری شما خواهشمند است، دستور اقدامات لازم در این\n" + + "زمینه را صادر فرمایید.", + }); +} diff --git a/src/app/api/fake-provinces/route.js b/src/app/api/fake-provinces/route.js index d4bf49d..0e02451 100644 --- a/src/app/api/fake-provinces/route.js +++ b/src/app/api/fake-provinces/route.js @@ -1,18 +1,18 @@ -const data = [ - { - id: 1, - name: "تهران", - }, - { - id: 2, - name: "مشهد", - }, - { - id: 3, - name: "اصفهان", - }, -]; - -export async function GET() { - return Response.json({ data }); -} +const data = [ + { + id: 1, + name: "تهران", + }, + { + id: 2, + name: "مشهد", + }, + { + id: 3, + name: "اصفهان", + }, +]; + +export async function GET() { + return Response.json({ data }); +} diff --git a/src/app/api/fake-road-items/operator/route.js b/src/app/api/fake-road-items/operator/route.js index 49424bc..d1244f4 100644 --- a/src/app/api/fake-road-items/operator/route.js +++ b/src/app/api/fake-road-items/operator/route.js @@ -1,84 +1,84 @@ -const data = [ - { - id: 1, - province: "تهران", - office: "اداره کل", - action_item: "بررسی خودرو", // Replace with the correct label - observed_subject: "تنظیم سطح بستر حریم", // Replace with the correct label - value: "1 کیلومتر", // Replace with actual value - images: { - before: "https://cdn-icons-png.flaticon.com/512/783/783154.png", - after: "https://cdn-icons-png.flaticon.com/512/1651/1651833.png", - }, - location: [{ lat: 35.6892, lng: 51.389 }], // Add URLs to images if needed - register_date: "2024-11-03T11:01:14.000000Z", - start_date: "2024-11-02T11:48:22.000000Z", - status: 0, // Replace with actual status - car_id: 1, - person_id: [0, 1, 2], - description: "بررسی شد", // Replace with actual description - }, - { - id: 2, - province: "تهران", - office: "اداره کل", - action_item: "بررسی خودرو", // Replace with the correct label - observed_subject: "تنظیم سطح بستر حریم", // Replace with the correct label - value: "1 کیلومتر", // Replace with actual value - images: { - before: "https://cdn-icons-png.flaticon.com/512/783/783154.png", - after: "https://cdn-icons-png.flaticon.com/512/1651/1651833.png", - }, - location: [{ lat: 35.6892, lng: 51.389 }], // Add URLs to images if needed - register_date: "2024-11-03T11:01:14.000000Z", - start_date: "2024-11-02T11:48:22.000000Z", - status: 2, // Replace with actual status - car_id: 10, - person_id: [10, 11, 12], - description: "بررسی شد", // Replace with actual description - }, - { - id: 3, - province: "تهران", - office: "اداره کل", - action_item: "بررسی خودرو", // Replace with the correct label - observed_subject: "تنظیم سطح بستر حریم", // Replace with the correct label - value: "1 کیلومتر", // Replace with actual value - images: { - before: "https://cdn-icons-png.flaticon.com/512/783/783154.png", - after: "https://cdn-icons-png.flaticon.com/512/1651/1651833.png", - }, // Add URLs to images if needed - location: [{ lat: 35.6892, lng: 51.389 }], // Add URLs to images if needed - register_date: "2024-11-03T11:01:14.000000Z", - start_date: "2024-11-02T11:48:22.000000Z", - status: 0, // Replace with actual status - car_id: 11, - person_id: [20, 15, 29], - description: "بررسی شد", // Replace with actual description - }, - { - id: 4, - province: "تهران", - office: "اداره کل", - action_item: "بررسی خودرو", // Replace with the correct label - observed_subject: "تنظیم سطح بستر حریم", // Replace with the correct label - value: "1 کیلومتر", // Replace with actual value - images: { - before: "https://cdn-icons-png.flaticon.com/512/783/783154.png", - after: "https://cdn-icons-png.flaticon.com/512/1651/1651833.png", - }, // Add URLs to images if needed - location: [{ lat: 35.6892, lng: 51.389 }], // Add URLs to images if needed - register_date: "2024-11-03T11:01:14.000000Z", - start_date: "2024-11-02T11:48:22.000000Z", - status: 1, // Replace with actual status - car_id: 26, - person_id: [78, 18, 56], - description: "بررسی شد", // Replace with actual description - }, -]; - -export async function GET() { - return new Response(JSON.stringify({ data }), { - headers: { "Content-Type": "application/json" }, - }); -} +const data = [ + { + id: 1, + province: "تهران", + office: "اداره کل", + action_item: "بررسی خودرو", // Replace with the correct label + observed_subject: "تنظیم سطح بستر حریم", // Replace with the correct label + value: "1 کیلومتر", // Replace with actual value + images: { + before: "https://cdn-icons-png.flaticon.com/512/783/783154.png", + after: "https://cdn-icons-png.flaticon.com/512/1651/1651833.png", + }, + location: [{ lat: 35.6892, lng: 51.389 }], // Add URLs to images if needed + register_date: "2024-11-03T11:01:14.000000Z", + start_date: "2024-11-02T11:48:22.000000Z", + status: 0, // Replace with actual status + car_id: 1, + person_id: [0, 1, 2], + description: "بررسی شد", // Replace with actual description + }, + { + id: 2, + province: "تهران", + office: "اداره کل", + action_item: "بررسی خودرو", // Replace with the correct label + observed_subject: "تنظیم سطح بستر حریم", // Replace with the correct label + value: "1 کیلومتر", // Replace with actual value + images: { + before: "https://cdn-icons-png.flaticon.com/512/783/783154.png", + after: "https://cdn-icons-png.flaticon.com/512/1651/1651833.png", + }, + location: [{ lat: 35.6892, lng: 51.389 }], // Add URLs to images if needed + register_date: "2024-11-03T11:01:14.000000Z", + start_date: "2024-11-02T11:48:22.000000Z", + status: 2, // Replace with actual status + car_id: 10, + person_id: [10, 11, 12], + description: "بررسی شد", // Replace with actual description + }, + { + id: 3, + province: "تهران", + office: "اداره کل", + action_item: "بررسی خودرو", // Replace with the correct label + observed_subject: "تنظیم سطح بستر حریم", // Replace with the correct label + value: "1 کیلومتر", // Replace with actual value + images: { + before: "https://cdn-icons-png.flaticon.com/512/783/783154.png", + after: "https://cdn-icons-png.flaticon.com/512/1651/1651833.png", + }, // Add URLs to images if needed + location: [{ lat: 35.6892, lng: 51.389 }], // Add URLs to images if needed + register_date: "2024-11-03T11:01:14.000000Z", + start_date: "2024-11-02T11:48:22.000000Z", + status: 0, // Replace with actual status + car_id: 11, + person_id: [20, 15, 29], + description: "بررسی شد", // Replace with actual description + }, + { + id: 4, + province: "تهران", + office: "اداره کل", + action_item: "بررسی خودرو", // Replace with the correct label + observed_subject: "تنظیم سطح بستر حریم", // Replace with the correct label + value: "1 کیلومتر", // Replace with actual value + images: { + before: "https://cdn-icons-png.flaticon.com/512/783/783154.png", + after: "https://cdn-icons-png.flaticon.com/512/1651/1651833.png", + }, // Add URLs to images if needed + location: [{ lat: 35.6892, lng: 51.389 }], // Add URLs to images if needed + register_date: "2024-11-03T11:01:14.000000Z", + start_date: "2024-11-02T11:48:22.000000Z", + status: 1, // Replace with actual status + car_id: 26, + person_id: [78, 18, 56], + description: "بررسی شد", // Replace with actual description + }, +]; + +export async function GET() { + return new Response(JSON.stringify({ data }), { + headers: { "Content-Type": "application/json" }, + }); +} diff --git a/src/app/api/fake-road-items/supervisor/route.js b/src/app/api/fake-road-items/supervisor/route.js index f2ab2bc..8835a19 100644 --- a/src/app/api/fake-road-items/supervisor/route.js +++ b/src/app/api/fake-road-items/supervisor/route.js @@ -1,84 +1,84 @@ -const data = [ - { - id: 1, - province: "تهران", - office: "اداره کل", - action_item: "بررسی خودرو", // Replace with the correct label - observed_subject: "تنظیم سطح بستر حریم", // Replace with the correct label - value: "1 کیلومتر", // Replace with actual value - images: { - before: "https://cdn-icons-png.flaticon.com/512/783/783154.png", - after: "https://cdn-icons-png.flaticon.com/512/1651/1651833.png", - }, // Add URLs to images if needed - location: [{ lat: 35.6892, lng: 51.389 }], // Add URLs to images if needed - register_date: "2024-11-03T11:01:14.000000Z", - start_date: "2024-11-02T11:48:22.000000Z", - status: 0, // Replace with actual status - car_id: 1, - person_id: [0, 1, 2], - description: "بررسی شد", // Replace with actual description - }, - { - id: 2, - province: "تهران", - office: "اداره کل", - action_item: "بررسی خودرو", // Replace with the correct label - observed_subject: "تنظیم سطح بستر حریم", // Replace with the correct label - value: "1 کیلومتر", // Replace with actual value - images: { - before: "https://cdn-icons-png.flaticon.com/512/783/783154.png", - after: "https://cdn-icons-png.flaticon.com/512/1651/1651833.png", - }, // Add URLs to images if needed - location: [{ lat: 35.6892, lng: 51.389 }], // Add URLs to images if needed - register_date: "2024-11-03T11:01:14.000000Z", - start_date: "2024-11-02T11:48:22.000000Z", - status: 2, // Replace with actual status - car_id: 10, - person_id: [10, 11, 12], - description: "بررسی شد", // Replace with actual description - }, - { - id: 3, - province: "تهران", - office: "اداره کل", - action_item: "بررسی خودرو", // Replace with the correct label - observed_subject: "تنظیم سطح بستر حریم", // Replace with the correct label - value: "1 کیلومتر", // Replace with actual value - images: { - before: "https://cdn-icons-png.flaticon.com/512/783/783154.png", - after: "https://cdn-icons-png.flaticon.com/512/1651/1651833.png", - }, // Add URLs to images if needed - location: [{ lat: 35.6892, lng: 51.389 }], // Add URLs to images if needed - register_date: "2024-11-03T11:01:14.000000Z", - start_date: "2024-11-02T11:48:22.000000Z", - status: 0, // Replace with actual status - car_id: 11, - person_id: [20, 15, 29], - description: "بررسی شد", // Replace with actual description - }, - { - id: 4, - province: "تهران", - office: "اداره کل", - action_item: "بررسی خودرو", // Replace with the correct label - observed_subject: "تنظیم سطح بستر حریم", // Replace with the correct label - value: "1 کیلومتر", // Replace with actual value - images: { - before: "https://cdn-icons-png.flaticon.com/512/783/783154.png", - after: "https://cdn-icons-png.flaticon.com/512/1651/1651833.png", - }, // Add URLs to images if needed - location: [{ lat: 35.6892, lng: 51.389 }], // Add URLs to images if needed - register_date: "2024-11-03T11:01:14.000000Z", - start_date: "2024-11-02T11:48:22.000000Z", - status: 1, // Replace with actual status - car_id: 26, - person_id: [78, 18, 56], - description: "بررسی شد", // Replace with actual description - }, -]; - -export async function GET() { - return new Response(JSON.stringify({ data }), { - headers: { "Content-Type": "application/json" }, - }); -} +const data = [ + { + id: 1, + province: "تهران", + office: "اداره کل", + action_item: "بررسی خودرو", // Replace with the correct label + observed_subject: "تنظیم سطح بستر حریم", // Replace with the correct label + value: "1 کیلومتر", // Replace with actual value + images: { + before: "https://cdn-icons-png.flaticon.com/512/783/783154.png", + after: "https://cdn-icons-png.flaticon.com/512/1651/1651833.png", + }, // Add URLs to images if needed + location: [{ lat: 35.6892, lng: 51.389 }], // Add URLs to images if needed + register_date: "2024-11-03T11:01:14.000000Z", + start_date: "2024-11-02T11:48:22.000000Z", + status: 0, // Replace with actual status + car_id: 1, + person_id: [0, 1, 2], + description: "بررسی شد", // Replace with actual description + }, + { + id: 2, + province: "تهران", + office: "اداره کل", + action_item: "بررسی خودرو", // Replace with the correct label + observed_subject: "تنظیم سطح بستر حریم", // Replace with the correct label + value: "1 کیلومتر", // Replace with actual value + images: { + before: "https://cdn-icons-png.flaticon.com/512/783/783154.png", + after: "https://cdn-icons-png.flaticon.com/512/1651/1651833.png", + }, // Add URLs to images if needed + location: [{ lat: 35.6892, lng: 51.389 }], // Add URLs to images if needed + register_date: "2024-11-03T11:01:14.000000Z", + start_date: "2024-11-02T11:48:22.000000Z", + status: 2, // Replace with actual status + car_id: 10, + person_id: [10, 11, 12], + description: "بررسی شد", // Replace with actual description + }, + { + id: 3, + province: "تهران", + office: "اداره کل", + action_item: "بررسی خودرو", // Replace with the correct label + observed_subject: "تنظیم سطح بستر حریم", // Replace with the correct label + value: "1 کیلومتر", // Replace with actual value + images: { + before: "https://cdn-icons-png.flaticon.com/512/783/783154.png", + after: "https://cdn-icons-png.flaticon.com/512/1651/1651833.png", + }, // Add URLs to images if needed + location: [{ lat: 35.6892, lng: 51.389 }], // Add URLs to images if needed + register_date: "2024-11-03T11:01:14.000000Z", + start_date: "2024-11-02T11:48:22.000000Z", + status: 0, // Replace with actual status + car_id: 11, + person_id: [20, 15, 29], + description: "بررسی شد", // Replace with actual description + }, + { + id: 4, + province: "تهران", + office: "اداره کل", + action_item: "بررسی خودرو", // Replace with the correct label + observed_subject: "تنظیم سطح بستر حریم", // Replace with the correct label + value: "1 کیلومتر", // Replace with actual value + images: { + before: "https://cdn-icons-png.flaticon.com/512/783/783154.png", + after: "https://cdn-icons-png.flaticon.com/512/1651/1651833.png", + }, // Add URLs to images if needed + location: [{ lat: 35.6892, lng: 51.389 }], // Add URLs to images if needed + register_date: "2024-11-03T11:01:14.000000Z", + start_date: "2024-11-02T11:48:22.000000Z", + status: 1, // Replace with actual status + car_id: 26, + person_id: [78, 18, 56], + description: "بررسی شد", // Replace with actual description + }, +]; + +export async function GET() { + return new Response(JSON.stringify({ data }), { + headers: { "Content-Type": "application/json" }, + }); +} diff --git a/src/app/api/fake-road-patrol/operator/route.js b/src/app/api/fake-road-patrol/operator/route.js index 3261a0b..7a6b2f0 100644 --- a/src/app/api/fake-road-patrol/operator/route.js +++ b/src/app/api/fake-road-patrol/operator/route.js @@ -1,24 +1,24 @@ -const data = [ - { - id: 1, - operator_name: "امین", - phone_number: "09134849737", - car_id: "33", - start_date: "2024-11-02T11:48:22.000000Z", - end_date: "2024-11-03T11:01:14.000000Z", - register_date: "2024-11-03T11:01:14.000000Z", - }, - { - id: 2, - operator_name: "امیر", - phone_number: "09134844955", - car_id: "233", - start_date: "2024-11-02T11:48:22.000000Z", - end_date: "2024-11-03T11:01:14.000000Z", - register_date: "2024-11-03T11:01:14.000000Z", - }, -]; - -export async function GET() { - return Response.json({ data }); -} +const data = [ + { + id: 1, + operator_name: "امین", + phone_number: "09134849737", + car_id: "33", + start_date: "2024-11-02T11:48:22.000000Z", + end_date: "2024-11-03T11:01:14.000000Z", + register_date: "2024-11-03T11:01:14.000000Z", + }, + { + id: 2, + operator_name: "امیر", + phone_number: "09134844955", + car_id: "233", + start_date: "2024-11-02T11:48:22.000000Z", + end_date: "2024-11-03T11:01:14.000000Z", + register_date: "2024-11-03T11:01:14.000000Z", + }, +]; + +export async function GET() { + return Response.json({ data }); +} diff --git a/src/app/api/fake-road-patrol/supervisor/route.js b/src/app/api/fake-road-patrol/supervisor/route.js index 8435bca..d1f97f8 100644 --- a/src/app/api/fake-road-patrol/supervisor/route.js +++ b/src/app/api/fake-road-patrol/supervisor/route.js @@ -1,28 +1,28 @@ -const data = [ - { - id: 1, - operator_name: "امین", - phone_number: "09134849737", - province: "تهران", - office: "اداره کل", - car_id: "33", - start_date: "2024-11-02T11:48:22.000000Z", - end_date: "2024-11-03T11:01:14.000000Z", - register_date: "2024-11-03T11:01:14.000000Z", - }, - { - id: 2, - operator_name: "امیر", - phone_number: "09134844955", - province: "تهران", - office: "اداره کل", - car_id: "233", - start_date: "2024-11-02T11:48:22.000000Z", - end_date: "2024-11-03T11:01:14.000000Z", - register_date: "2024-11-03T11:01:14.000000Z", - }, -]; - -export async function GET() { - return Response.json({ data }); -} +const data = [ + { + id: 1, + operator_name: "امین", + phone_number: "09134849737", + province: "تهران", + office: "اداره کل", + car_id: "33", + start_date: "2024-11-02T11:48:22.000000Z", + end_date: "2024-11-03T11:01:14.000000Z", + register_date: "2024-11-03T11:01:14.000000Z", + }, + { + id: 2, + operator_name: "امیر", + phone_number: "09134844955", + province: "تهران", + office: "اداره کل", + car_id: "233", + start_date: "2024-11-02T11:48:22.000000Z", + end_date: "2024-11-03T11:01:14.000000Z", + register_date: "2024-11-03T11:01:14.000000Z", + }, +]; + +export async function GET() { + return Response.json({ data }); +} diff --git a/src/app/api/fake-submit/[id]/route.js b/src/app/api/fake-submit/[id]/route.js index 2ba57b2..bf1b442 100644 --- a/src/app/api/fake-submit/[id]/route.js +++ b/src/app/api/fake-submit/[id]/route.js @@ -1,3 +1,3 @@ -export async function POST() { - return Response.json({ message: "Done" }); -} +export async function POST() { + return Response.json({ message: "Done" }); +} diff --git a/src/app/api/fake-tests-type/route.js b/src/app/api/fake-tests-type/route.js index 7d41c3e..14e222b 100644 --- a/src/app/api/fake-tests-type/route.js +++ b/src/app/api/fake-tests-type/route.js @@ -1,18 +1,18 @@ -const data = [ - { - id: 1, - name: "تست نوع 1", - }, - { - id: 2, - name: "تست نوع 2", - }, - { - id: 3, - name: "تست نوع 3", - }, -]; - -export async function GET() { - return Response.json({ data }); -} +const data = [ + { + id: 1, + name: "تست نوع 1", + }, + { + id: 2, + name: "تست نوع 2", + }, + { + id: 3, + name: "تست نوع 3", + }, +]; + +export async function GET() { + return Response.json({ data }); +} diff --git a/src/app/api/fake-tests/route.js b/src/app/api/fake-tests/route.js index 3918bf0..addeb38 100644 --- a/src/app/api/fake-tests/route.js +++ b/src/app/api/fake-tests/route.js @@ -1,71 +1,71 @@ -const data = [ - { - id: 1, - test_type_name: 1, - project_name: "نوع پروژه", - employer: "کارفرما", - consultant: "مشاور", - contractor: "پیمانکار", - applicant: "متقاضی", - work_number: "شماره کار", - request_number: "شماره درخواست", - request_date: "تاریخ درخواست", - report_date: "تاریخ گزارش", - }, - { - id: 2, - test_type_name: 5, - project_name: "نوع پروژه", - employer: "کارفرما", - consultant: "مشاور", - contractor: "پیمانکار", - applicant: "متقاضی", - work_number: "شماره کار", - request_number: "شماره درخواست", - request_date: "تاریخ درخواست", - report_date: "تاریخ گزارش", - }, - { - id: 3, - test_type_name: 2, - project_name: "نوع پروژه", - employer: "کارفرما", - consultant: "مشاور", - contractor: "پیمانکار", - applicant: "متقاضی", - work_number: "شماره کار", - request_number: "شماره درخواست", - request_date: "تاریخ درخواست", - report_date: "تاریخ گزارش", - }, - { - id: 4, - test_type_name: 4, - project_name: "نوع پروژه", - employer: "کارفرما", - consultant: "مشاور", - contractor: "پیمانکار", - applicant: "متقاضی", - work_number: "شماره کار", - request_number: "شماره درخواست", - request_date: "تاریخ درخواست", - report_date: "تاریخ گزارش", - }, - { - id: 5, - test_type_name: 3, - project_name: "نوع پروژه", - employer: "کارفرما", - consultant: "مشاور", - contractor: "پیمانکار", - applicant: "متقاضی", - work_number: "شماره کار", - request_number: "شماره درخواست", - request_date: "تاریخ درخواست", - report_date: "تاریخ گزارش", - }, -]; - -export async function GET() { - return Response.json({ data }); -} +const data = [ + { + id: 1, + test_type_name: 1, + project_name: "نوع پروژه", + employer: "کارفرما", + consultant: "مشاور", + contractor: "پیمانکار", + applicant: "متقاضی", + work_number: "شماره کار", + request_number: "شماره درخواست", + request_date: "تاریخ درخواست", + report_date: "تاریخ گزارش", + }, + { + id: 2, + test_type_name: 5, + project_name: "نوع پروژه", + employer: "کارفرما", + consultant: "مشاور", + contractor: "پیمانکار", + applicant: "متقاضی", + work_number: "شماره کار", + request_number: "شماره درخواست", + request_date: "تاریخ درخواست", + report_date: "تاریخ گزارش", + }, + { + id: 3, + test_type_name: 2, + project_name: "نوع پروژه", + employer: "کارفرما", + consultant: "مشاور", + contractor: "پیمانکار", + applicant: "متقاضی", + work_number: "شماره کار", + request_number: "شماره درخواست", + request_date: "تاریخ درخواست", + report_date: "تاریخ گزارش", + }, + { + id: 4, + test_type_name: 4, + project_name: "نوع پروژه", + employer: "کارفرما", + consultant: "مشاور", + contractor: "پیمانکار", + applicant: "متقاضی", + work_number: "شماره کار", + request_number: "شماره درخواست", + request_date: "تاریخ درخواست", + report_date: "تاریخ گزارش", + }, + { + id: 5, + test_type_name: 3, + project_name: "نوع پروژه", + employer: "کارفرما", + consultant: "مشاور", + contractor: "پیمانکار", + applicant: "متقاضی", + work_number: "شماره کار", + request_number: "شماره درخواست", + request_date: "تاریخ درخواست", + report_date: "تاریخ گزارش", + }, +]; + +export async function GET() { + return Response.json({ data }); +} diff --git a/src/app/default.js b/src/app/default.js index d157a71..44d47d9 100644 --- a/src/app/default.js +++ b/src/app/default.js @@ -1,3 +1,3 @@ -export default function Default() { - return null; -} +export default function Default() { + return null; +} diff --git a/src/app/layout.js b/src/app/layout.js index 089cb8d..59f3281 100644 --- a/src/app/layout.js +++ b/src/app/layout.js @@ -1,25 +1,25 @@ -import favicon from "@/assets/images/favicon.svg"; -import { AuthProvider } from "@/lib/contexts/auth"; -import { TableSettingProvider } from "@/lib/contexts/tableSetting"; - -export const metadata = { - title: { - template: "%s | سامانه جامع راهداری", - default: "سامانه جامع راهداری", - }, -}; - -export default function RootLayout({ children }) { - return ( - - - - - - - {children} - - - - ); -} +import favicon from "@/assets/images/favicon.svg"; +import { AuthProvider } from "@/lib/contexts/auth"; +import { TableSettingProvider } from "@/lib/contexts/tableSetting"; + +export const metadata = { + title: { + template: "%s | سامانه جامع راهداری", + default: "سامانه جامع راهداری", + }, +}; + +export default function RootLayout({ children }) { + return ( + + + + + + + {children} + + + + ); +} diff --git a/src/app/lfwd/page.js b/src/app/lfwd/page.js index 70708e4..94ab024 100644 --- a/src/app/lfwd/page.js +++ b/src/app/lfwd/page.js @@ -1,61 +1,61 @@ -"use client"; - -import { GET_LOGIN_ROUTE } from "@/core/utils/routes"; -import { useAuth } from "@/lib/contexts/auth"; -import useRequest from "@/lib/hooks/useRequest"; -import { Button, Stack, Typography, Zoom } from "@mui/material"; -import Link from "next/link"; -import { useEffect, useState } from "react"; - -const Page = ({ searchParams }) => { - const { getUser } = useAuth(); - const { username } = searchParams; - const [login, setLogin] = useState(0); - const request = useRequest(); - - useEffect(() => { - const login = async () => { - try { - await request(`${GET_LOGIN_ROUTE}?username=${username}`); - await getUser(); - setLogin(1); - } catch (error) { - setLogin(2); - } - }; - - login(); - }, []); - - const retry = async () => { - setLogin(0); - try { - await request(`${GET_LOGIN_ROUTE}?username=${username}`); - await getUser(); - setLogin(1); - } catch (error) { - setLogin(2); - } - }; - - return ( - - - {login === 0 - ? "درحال دریافت مجوز برای ارتباط با سرور..." - : login === 1 - ? "ارتباط با سرور برقرار شد." - : "ارتباط با سرور برقرار نشد. مشکلی وجود دارد."} - - - - - - - - - ); -}; -export default Page; +"use client"; + +import { GET_LOGIN_ROUTE } from "@/core/utils/routes"; +import { useAuth } from "@/lib/contexts/auth"; +import useRequest from "@/lib/hooks/useRequest"; +import { Button, Stack, Typography, Zoom } from "@mui/material"; +import Link from "next/link"; +import { useEffect, useState } from "react"; + +const Page = ({ searchParams }) => { + const { getUser } = useAuth(); + const { username } = searchParams; + const [login, setLogin] = useState(0); + const request = useRequest(); + + useEffect(() => { + const login = async () => { + try { + await request(`${GET_LOGIN_ROUTE}?username=${username}`); + await getUser(); + setLogin(1); + } catch (error) { + setLogin(2); + } + }; + + login(); + }, []); + + const retry = async () => { + setLogin(0); + try { + await request(`${GET_LOGIN_ROUTE}?username=${username}`); + await getUser(); + setLogin(1); + } catch (error) { + setLogin(2); + } + }; + + return ( + + + {login === 0 + ? "درحال دریافت مجوز برای ارتباط با سرور..." + : login === 1 + ? "ارتباط با سرور برقرار شد." + : "ارتباط با سرور برقرار نشد. مشکلی وجود دارد."} + + + + + + + + + ); +}; +export default Page; diff --git a/src/app/not-found.js b/src/app/not-found.js index 5d38652..ade3eea 100644 --- a/src/app/not-found.js +++ b/src/app/not-found.js @@ -1,16 +1,16 @@ -"use client"; -import { Box, Stack, Typography } from "@mui/material"; -import SvgNotFound from "@/core/components/svgs/SvgNotFound"; - -export default function NotFound() { - return ( - - - - - - صفحه موردنظر یافت نشد ... - - - ); -} +"use client"; +import { Box, Stack, Typography } from "@mui/material"; +import SvgNotFound from "@/core/components/svgs/SvgNotFound"; + +export default function NotFound() { + return ( + + + + + + صفحه موردنظر یافت نشد ... + + + ); +} diff --git a/src/app/page.js b/src/app/page.js index 2997c35..7ecf2cc 100644 --- a/src/app/page.js +++ b/src/app/page.js @@ -1,8 +1,8 @@ -import { redirect } from "next/navigation"; - -function Page() { - redirect("/dashboard", "replace"); - return null; -} - -export default Page; +import { redirect } from "next/navigation"; + +function Page() { + redirect("/dashboard", "replace"); + return null; +} + +export default Page; diff --git a/src/app/template.js b/src/app/template.js index 359f234..8cf5503 100644 --- a/src/app/template.js +++ b/src/app/template.js @@ -1,40 +1,40 @@ -import cacheProviderRtl from "@/core/utils/cacheRtl"; -import { CssBaseline, GlobalStyles, ThemeProvider } from "@mui/material"; -import theme from "@/core/utils/theme"; -import { AppRouterCacheProvider } from "@mui/material-nextjs/v14-appRouter"; -import "@/assets/scss/global.scss"; -import { ToastContainer } from "react-toastify"; - -const Template = ({ children }) => { - return ( - - - - - {children} - - - - - ); -}; - -export default Template; +import cacheProviderRtl from "@/core/utils/cacheRtl"; +import { CssBaseline, GlobalStyles, ThemeProvider } from "@mui/material"; +import theme from "@/core/utils/theme"; +import { AppRouterCacheProvider } from "@mui/material-nextjs/v14-appRouter"; +import "@/assets/scss/global.scss"; +import { ToastContainer } from "react-toastify"; + +const Template = ({ children }) => { + return ( + + + + + {children} + + + + + ); +}; + +export default Template; diff --git a/src/assets/scss/fontiran.scss b/src/assets/scss/fontiran.scss index cb4e644..6606fd8 100644 --- a/src/assets/scss/fontiran.scss +++ b/src/assets/scss/fontiran.scss @@ -1,190 +1,190 @@ -/** -* -* Name: IRAN Sans-Serif Font -* Version: 5.0 -* Author: Moslem Ebrahimi (moslemebrahimi.com) -* Created on: Dec 25, 2012 -* Updated on: Sep 01, 2017 -* Website: http://fontiran.com -* Copyright: Commercial/Proprietary Software --------------------------------------------------------------------------------------- -فونت های ایران سن سریف یک نرم افزار مالکیتی محسوب می شود. جهت آگاهی از قوانین استفاده از این فونت ها لطفا به وب سایت (فونت ایران دات کام) مراجعه نمایید --------------------------------------------------------------------------------------- -IRAN Sans-serif fonts are considered a proprietary software. To gain information about the laws regarding the use of these fonts, please visit www.fontiran.com --------------------------------------------------------------------------------------- -This set of fonts are used in this project under the license: (.....) --------------------------------------------------------------------------------------- -* -**/ -@font-face { - font-family: IRANSansFaNum; - font-style: normal; - font-weight: 900; - src: url("../fonts/eot/IRANSansWeb(FaNum)_Black.eot"); - src: - url("../fonts/eot/IRANSansWeb(FaNum)_Black.eot?#iefix") format("embedded-opentype"), - /* IE6-8 */ url("../fonts/woff2/IRANSansWeb(FaNum)_Black.woff2") format("woff2"), - /* FF39+,Chrome36+, Opera24+*/ url("../fonts/woff/IRANSansWeb(FaNum)_Black.woff") format("woff"), - /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/IRANSansWeb(FaNum)_Black.ttf") format("truetype"); -} - -@font-face { - font-family: IRANSansFaNum; - font-style: normal; - font-weight: bold; - src: url("../fonts/eot/IRANSansWeb(FaNum)_Bold.eot"); - src: - url("../fonts/eot/IRANSansWeb(FaNum)_Bold.eot?#iefix") format("embedded-opentype"), - /* IE6-8 */ url("../fonts/woff2/IRANSansWeb(FaNum)_Bold.woff2") format("woff2"), - /* FF39+,Chrome36+, Opera24+*/ url("../fonts/woff/IRANSansWeb(FaNum)_Bold.woff") format("woff"), - /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/IRANSansWeb(FaNum)_Bold.ttf") format("truetype"); -} - -@font-face { - font-family: IRANSansFaNum; - font-style: normal; - font-weight: 500; - src: url("../fonts/eot/IRANSansWeb(FaNum)_Medium.eot"); - src: - url("../fonts/eot/IRANSansWeb(FaNum)_Medium.eot?#iefix") format("embedded-opentype"), - /* IE6-8 */ url("../fonts/woff2/IRANSansWeb(FaNum)_Medium.woff2") format("woff2"), - /* FF39+,Chrome36+, Opera24+*/ url("../fonts/woff/IRANSansWeb(FaNum)_Medium.woff") format("woff"), - /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/IRANSansWeb(FaNum)_Medium.ttf") format("truetype"); -} - -@font-face { - font-family: IRANSansFaNum; - font-style: normal; - font-weight: 300; - src: url("../fonts/eot/IRANSansWeb(FaNum)_Light.eot"); - src: - url("../fonts/eot/IRANSansWeb(FaNum)_Light.eot?#iefix") format("embedded-opentype"), - /* IE6-8 */ url("../fonts/woff2/IRANSansWeb(FaNum)_Light.woff2") format("woff2"), - /* FF39+,Chrome36+, Opera24+*/ url("../fonts/woff/IRANSansWeb(FaNum)_Light.woff") format("woff"), - /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/IRANSansWeb(FaNum)_Light.ttf") format("truetype"); -} - -@font-face { - font-family: IRANSansFaNum; - font-style: normal; - font-weight: 200; - src: url("../fonts/eot/IRANSansWeb(FaNum)_UltraLight.eot"); - src: - url("../fonts/eot/IRANSansWeb(FaNum)_UltraLight.eot?#iefix") format("embedded-opentype"), - /* IE6-8 */ url("../fonts/woff2/IRANSansWeb(FaNum)_UltraLight.woff2") format("woff2"), - /* FF39+,Chrome36+, Opera24+*/ url("../fonts/woff/IRANSansWeb(FaNum)_UltraLight.woff") format("woff"), - /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/IRANSansWeb(FaNum)_UltraLight.ttf") format("truetype"); -} - -@font-face { - font-family: IRANSansFaNum; - font-style: normal; - font-weight: normal; - src: url("../fonts/eot/IRANSansWeb(FaNum).eot"); - src: - url("../fonts/eot/IRANSansWeb(FaNum).eot?#iefix") format("embedded-opentype"), - /* IE6-8 */ url("../fonts/woff2/IRANSansWeb(FaNum).woff2") format("woff2"), - /* FF39+,Chrome36+, Opera24+*/ url("../fonts/woff/IRANSansWeb(FaNum).woff") format("woff"), - /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/IRANSansWeb(FaNum).ttf") format("truetype"); -} - -@font-face { - font-family: IRANSans; - font-style: normal; - font-weight: 900; - src: url("../fonts/eot/IRANSansWeb_Black.eot"); - src: - url("../fonts/eot/IRANSansWeb_Black.eot?#iefix") format("embedded-opentype"), - /* IE6-8 */ url("../fonts/woff2/IRANSansWeb_Black.woff2") format("woff2"), - /* FF39+,Chrome36+, Opera24+*/ url("../fonts/woff/IRANSansWeb_Black.woff") format("woff"), - /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/IRANSansWeb_Black.ttf") format("truetype"); -} - -@font-face { - font-family: IRANSans; - font-style: normal; - font-weight: bold; - src: url("../fonts/eot/IRANSansWeb_Bold.eot"); - src: - url("../fonts/eot/IRANSansWeb_Bold.eot?#iefix") format("embedded-opentype"), - /* IE6-8 */ url("../fonts/woff2/IRANSansWeb_Bold.woff2") format("woff2"), - /* FF39+,Chrome36+, Opera24+*/ url("../fonts/woff/IRANSansWeb_Bold.woff") format("woff"), - /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/IRANSansWeb_Bold.ttf") format("truetype"); -} - -@font-face { - font-family: IRANSans; - font-style: normal; - font-weight: 500; - src: url("../fonts/eot/IRANSansWeb_Medium.eot"); - src: - url("../fonts/eot/IRANSansWeb_Medium.eot?#iefix") format("embedded-opentype"), - /* IE6-8 */ url("../fonts/woff2/IRANSansWeb_Medium.woff2") format("woff2"), - /* FF39+,Chrome36+, Opera24+*/ url("../fonts/woff/IRANSansWeb_Medium.woff") format("woff"), - /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/IRANSansWeb_Medium.ttf") format("truetype"); -} - -@font-face { - font-family: IRANSans; - font-style: normal; - font-weight: 300; - src: url("../fonts/eot/IRANSansWeb_Light.eot"); - src: - url("../fonts/eot/IRANSansWeb_Light.eot?#iefix") format("embedded-opentype"), - /* IE6-8 */ url("../fonts/woff2/IRANSansWeb_Light.woff2") format("woff2"), - /* FF39+,Chrome36+, Opera24+*/ url("../fonts/woff/IRANSansWeb_Light.woff") format("woff"), - /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/IRANSansWeb_Light.ttf") format("truetype"); -} - -@font-face { - font-family: IRANSans; - font-style: normal; - font-weight: 200; - src: url("../fonts/eot/IRANSansWeb_UltraLight.eot"); - src: - url("../fonts/eot/IRANSansWeb_UltraLight.eot?#iefix") format("embedded-opentype"), - /* IE6-8 */ url("../fonts/woff2/IRANSansWeb_UltraLight.woff2") format("woff2"), - /* FF39+,Chrome36+, Opera24+*/ url("../fonts/woff/IRANSansWeb_UltraLight.woff") format("woff"), - /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/IRANSansWeb_UltraLight.ttf") format("truetype"); -} - -@font-face { - font-family: IRANSans; - font-style: normal; - font-weight: normal; - src: url("../fonts/eot/IRANSansWeb.eot"); - src: - url("../fonts/eot/IRANSansWeb.eot?#iefix") format("embedded-opentype"), - /* IE6-8 */ url("../fonts/woff2/IRANSansWeb.woff2") format("woff2"), - /* FF39+,Chrome36+, Opera24+*/ url("../fonts/woff/IRANSansWeb.woff") format("woff"), - /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/IRANSansWeb.ttf") format("truetype"); -} - -@font-face { - font-family: Parastoo; - font-style: normal; - font-weight: normal; - src: url("../fonts/eot/Parastoo.eot"); - src: - url("../fonts/eot/Parastoo.eot?#iefix") format("embedded-opentype"), - /* IE6-8 */ url("../fonts/woff/Parastoo.woff") format("woff"), - /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/Parastoo.ttf") format("truetype"); -} - -@font-face { - font-family: Parastoo; - font-style: normal; - font-weight: bold; - src: url("../fonts/eot/Parastoo-Bold.eot"); - src: - url("../fonts/eot/Parastoo-Bold.eot?#iefix") format("embedded-opentype"), - /* IE6-8 */ url("../fonts/woff/Parastoo-Bold.woff") format("woff"), - /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/Parastoo-Bold.ttf") format("truetype"); -} - -@font-face { - font-family: Bnazanin; - font-style: normal; - font-weight: normal; - src: url("../fonts/ttf/BNazanin.ttf") format("truetype"); -} +/** +* +* Name: IRAN Sans-Serif Font +* Version: 5.0 +* Author: Moslem Ebrahimi (moslemebrahimi.com) +* Created on: Dec 25, 2012 +* Updated on: Sep 01, 2017 +* Website: http://fontiran.com +* Copyright: Commercial/Proprietary Software +-------------------------------------------------------------------------------------- +فونت های ایران سن سریف یک نرم افزار مالکیتی محسوب می شود. جهت آگاهی از قوانین استفاده از این فونت ها لطفا به وب سایت (فونت ایران دات کام) مراجعه نمایید +-------------------------------------------------------------------------------------- +IRAN Sans-serif fonts are considered a proprietary software. To gain information about the laws regarding the use of these fonts, please visit www.fontiran.com +-------------------------------------------------------------------------------------- +This set of fonts are used in this project under the license: (.....) +-------------------------------------------------------------------------------------- +* +**/ +@font-face { + font-family: IRANSansFaNum; + font-style: normal; + font-weight: 900; + src: url("../fonts/eot/IRANSansWeb(FaNum)_Black.eot"); + src: + url("../fonts/eot/IRANSansWeb(FaNum)_Black.eot?#iefix") format("embedded-opentype"), + /* IE6-8 */ url("../fonts/woff2/IRANSansWeb(FaNum)_Black.woff2") format("woff2"), + /* FF39+,Chrome36+, Opera24+*/ url("../fonts/woff/IRANSansWeb(FaNum)_Black.woff") format("woff"), + /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/IRANSansWeb(FaNum)_Black.ttf") format("truetype"); +} + +@font-face { + font-family: IRANSansFaNum; + font-style: normal; + font-weight: bold; + src: url("../fonts/eot/IRANSansWeb(FaNum)_Bold.eot"); + src: + url("../fonts/eot/IRANSansWeb(FaNum)_Bold.eot?#iefix") format("embedded-opentype"), + /* IE6-8 */ url("../fonts/woff2/IRANSansWeb(FaNum)_Bold.woff2") format("woff2"), + /* FF39+,Chrome36+, Opera24+*/ url("../fonts/woff/IRANSansWeb(FaNum)_Bold.woff") format("woff"), + /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/IRANSansWeb(FaNum)_Bold.ttf") format("truetype"); +} + +@font-face { + font-family: IRANSansFaNum; + font-style: normal; + font-weight: 500; + src: url("../fonts/eot/IRANSansWeb(FaNum)_Medium.eot"); + src: + url("../fonts/eot/IRANSansWeb(FaNum)_Medium.eot?#iefix") format("embedded-opentype"), + /* IE6-8 */ url("../fonts/woff2/IRANSansWeb(FaNum)_Medium.woff2") format("woff2"), + /* FF39+,Chrome36+, Opera24+*/ url("../fonts/woff/IRANSansWeb(FaNum)_Medium.woff") format("woff"), + /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/IRANSansWeb(FaNum)_Medium.ttf") format("truetype"); +} + +@font-face { + font-family: IRANSansFaNum; + font-style: normal; + font-weight: 300; + src: url("../fonts/eot/IRANSansWeb(FaNum)_Light.eot"); + src: + url("../fonts/eot/IRANSansWeb(FaNum)_Light.eot?#iefix") format("embedded-opentype"), + /* IE6-8 */ url("../fonts/woff2/IRANSansWeb(FaNum)_Light.woff2") format("woff2"), + /* FF39+,Chrome36+, Opera24+*/ url("../fonts/woff/IRANSansWeb(FaNum)_Light.woff") format("woff"), + /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/IRANSansWeb(FaNum)_Light.ttf") format("truetype"); +} + +@font-face { + font-family: IRANSansFaNum; + font-style: normal; + font-weight: 200; + src: url("../fonts/eot/IRANSansWeb(FaNum)_UltraLight.eot"); + src: + url("../fonts/eot/IRANSansWeb(FaNum)_UltraLight.eot?#iefix") format("embedded-opentype"), + /* IE6-8 */ url("../fonts/woff2/IRANSansWeb(FaNum)_UltraLight.woff2") format("woff2"), + /* FF39+,Chrome36+, Opera24+*/ url("../fonts/woff/IRANSansWeb(FaNum)_UltraLight.woff") format("woff"), + /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/IRANSansWeb(FaNum)_UltraLight.ttf") format("truetype"); +} + +@font-face { + font-family: IRANSansFaNum; + font-style: normal; + font-weight: normal; + src: url("../fonts/eot/IRANSansWeb(FaNum).eot"); + src: + url("../fonts/eot/IRANSansWeb(FaNum).eot?#iefix") format("embedded-opentype"), + /* IE6-8 */ url("../fonts/woff2/IRANSansWeb(FaNum).woff2") format("woff2"), + /* FF39+,Chrome36+, Opera24+*/ url("../fonts/woff/IRANSansWeb(FaNum).woff") format("woff"), + /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/IRANSansWeb(FaNum).ttf") format("truetype"); +} + +@font-face { + font-family: IRANSans; + font-style: normal; + font-weight: 900; + src: url("../fonts/eot/IRANSansWeb_Black.eot"); + src: + url("../fonts/eot/IRANSansWeb_Black.eot?#iefix") format("embedded-opentype"), + /* IE6-8 */ url("../fonts/woff2/IRANSansWeb_Black.woff2") format("woff2"), + /* FF39+,Chrome36+, Opera24+*/ url("../fonts/woff/IRANSansWeb_Black.woff") format("woff"), + /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/IRANSansWeb_Black.ttf") format("truetype"); +} + +@font-face { + font-family: IRANSans; + font-style: normal; + font-weight: bold; + src: url("../fonts/eot/IRANSansWeb_Bold.eot"); + src: + url("../fonts/eot/IRANSansWeb_Bold.eot?#iefix") format("embedded-opentype"), + /* IE6-8 */ url("../fonts/woff2/IRANSansWeb_Bold.woff2") format("woff2"), + /* FF39+,Chrome36+, Opera24+*/ url("../fonts/woff/IRANSansWeb_Bold.woff") format("woff"), + /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/IRANSansWeb_Bold.ttf") format("truetype"); +} + +@font-face { + font-family: IRANSans; + font-style: normal; + font-weight: 500; + src: url("../fonts/eot/IRANSansWeb_Medium.eot"); + src: + url("../fonts/eot/IRANSansWeb_Medium.eot?#iefix") format("embedded-opentype"), + /* IE6-8 */ url("../fonts/woff2/IRANSansWeb_Medium.woff2") format("woff2"), + /* FF39+,Chrome36+, Opera24+*/ url("../fonts/woff/IRANSansWeb_Medium.woff") format("woff"), + /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/IRANSansWeb_Medium.ttf") format("truetype"); +} + +@font-face { + font-family: IRANSans; + font-style: normal; + font-weight: 300; + src: url("../fonts/eot/IRANSansWeb_Light.eot"); + src: + url("../fonts/eot/IRANSansWeb_Light.eot?#iefix") format("embedded-opentype"), + /* IE6-8 */ url("../fonts/woff2/IRANSansWeb_Light.woff2") format("woff2"), + /* FF39+,Chrome36+, Opera24+*/ url("../fonts/woff/IRANSansWeb_Light.woff") format("woff"), + /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/IRANSansWeb_Light.ttf") format("truetype"); +} + +@font-face { + font-family: IRANSans; + font-style: normal; + font-weight: 200; + src: url("../fonts/eot/IRANSansWeb_UltraLight.eot"); + src: + url("../fonts/eot/IRANSansWeb_UltraLight.eot?#iefix") format("embedded-opentype"), + /* IE6-8 */ url("../fonts/woff2/IRANSansWeb_UltraLight.woff2") format("woff2"), + /* FF39+,Chrome36+, Opera24+*/ url("../fonts/woff/IRANSansWeb_UltraLight.woff") format("woff"), + /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/IRANSansWeb_UltraLight.ttf") format("truetype"); +} + +@font-face { + font-family: IRANSans; + font-style: normal; + font-weight: normal; + src: url("../fonts/eot/IRANSansWeb.eot"); + src: + url("../fonts/eot/IRANSansWeb.eot?#iefix") format("embedded-opentype"), + /* IE6-8 */ url("../fonts/woff2/IRANSansWeb.woff2") format("woff2"), + /* FF39+,Chrome36+, Opera24+*/ url("../fonts/woff/IRANSansWeb.woff") format("woff"), + /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/IRANSansWeb.ttf") format("truetype"); +} + +@font-face { + font-family: Parastoo; + font-style: normal; + font-weight: normal; + src: url("../fonts/eot/Parastoo.eot"); + src: + url("../fonts/eot/Parastoo.eot?#iefix") format("embedded-opentype"), + /* IE6-8 */ url("../fonts/woff/Parastoo.woff") format("woff"), + /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/Parastoo.ttf") format("truetype"); +} + +@font-face { + font-family: Parastoo; + font-style: normal; + font-weight: bold; + src: url("../fonts/eot/Parastoo-Bold.eot"); + src: + url("../fonts/eot/Parastoo-Bold.eot?#iefix") format("embedded-opentype"), + /* IE6-8 */ url("../fonts/woff/Parastoo-Bold.woff") format("woff"), + /* FF3.6+, IE9, Chrome6+, Saf5.1+*/ url("../fonts/ttf/Parastoo-Bold.ttf") format("truetype"); +} + +@font-face { + font-family: Bnazanin; + font-style: normal; + font-weight: normal; + src: url("../fonts/ttf/BNazanin.ttf") format("truetype"); +} diff --git a/src/assets/scss/global.scss b/src/assets/scss/global.scss index 1fc9f82..13dd62b 100644 --- a/src/assets/scss/global.scss +++ b/src/assets/scss/global.scss @@ -1,11 +1,12 @@ -@import "fontiran"; -@import "leaflet/dist/leaflet.css"; -@import "react-toastify/dist/ReactToastify.css"; -@import "./map-styles.scss"; - -.filter-toast { - box-shadow: - rgba(50, 50, 93, 0.25) 0px 13px 27px -5px, - rgba(0, 0, 0, 0.3) 0px 8px 16px -8px; - background-color: #d0dfe8; -} +@import "fontiran"; +@import "leaflet/dist/leaflet.css"; +@import "leaflet-draw/dist/leaflet.draw.css"; +@import "react-toastify/dist/ReactToastify.css"; +@import "./map-styles.scss"; + +.filter-toast { + box-shadow: + rgba(50, 50, 93, 0.25) 0px 13px 27px -5px, + rgba(0, 0, 0, 0.3) 0px 8px 16px -8px; + background-color: #d0dfe8; +} diff --git a/src/assets/scss/map-styles.scss b/src/assets/scss/map-styles.scss index 595f664..44a88a0 100644 --- a/src/assets/scss/map-styles.scss +++ b/src/assets/scss/map-styles.scss @@ -1,9 +1,29 @@ -.custom-marker-cluster { - font-family: IRANSansFaNum; - background-color: rgba(51, 181, 229, 0.6); - color: #fff; - border-radius: 50%; - text-align: center; - font-size: 14px; - line-height: 40px; -} +.custom-marker-cluster { + font-family: IRANSansFaNum; + background-color: rgba(51, 181, 229, 0.6); + color: #fff; + border-radius: 50%; + text-align: center; + font-size: 14px; + line-height: 40px; +} + +.leaflet-draw { + display: none; +} + +.leaflet-draw-tooltip { + margin-left: 0; + margin-right: 20px; +} +.leaflet-draw-tooltip::before { + border-left: 6px solid black; + border-left-color: rgba(0, 0, 0, 0.5); + border-right: 0; + right: -7px; + left: auto; +} + +.leaflet-editing-icon { + border-radius: 50%; +} diff --git a/src/components/dashboard/azmayesh/Actions/Create/index.jsx b/src/components/dashboard/azmayesh/Actions/Create/index.jsx index 414dca1..6bc11a9 100644 --- a/src/components/dashboard/azmayesh/Actions/Create/index.jsx +++ b/src/components/dashboard/azmayesh/Actions/Create/index.jsx @@ -1,33 +1,33 @@ -"use client"; - -import { Button, IconButton, useMediaQuery } from "@mui/material"; -import { useTheme } from "@emotion/react"; -import { useState } from "react"; -import { AddCircle } from "@mui/icons-material"; -import CandUAzmayesh from "@/components/dashboard/azmayesh/Forms/CandUAzmayesh"; - -const AzmayeshCreate = ({ mutate }) => { - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const [open, setOpen] = useState(false); - - const handleOpen = () => { - setOpen(true); - }; - - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - {open && } - - ); -}; -export default AzmayeshCreate; +"use client"; + +import { Button, IconButton, useMediaQuery } from "@mui/material"; +import { useTheme } from "@emotion/react"; +import { useState } from "react"; +import { AddCircle } from "@mui/icons-material"; +import CandUAzmayesh from "@/components/dashboard/azmayesh/Forms/CandUAzmayesh"; + +const AzmayeshCreate = ({ mutate }) => { + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const [open, setOpen] = useState(false); + + const handleOpen = () => { + setOpen(true); + }; + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + {open && } + + ); +}; +export default AzmayeshCreate; diff --git a/src/components/dashboard/azmayesh/AzmayeshList.jsx b/src/components/dashboard/azmayesh/AzmayeshList.jsx index 904c50c..1b980e6 100644 --- a/src/components/dashboard/azmayesh/AzmayeshList.jsx +++ b/src/components/dashboard/azmayesh/AzmayeshList.jsx @@ -1,216 +1,216 @@ -"use client"; - -import { useMemo } from "react"; -import { Box, Typography } from "@mui/material"; -import DataTableWithAuth from "@/core/components/DataTableWithAuth"; -import Toolbar from "./Toolbar"; -import { GET_AZMAYESH_LIST } from "@/core/utils/routes"; -import ShowLocation from "./ShowLocation"; -import moment from "jalali-moment"; -import RowActions from "./RowActions"; -import ShowSampleOfAzmayesh from "./RowActions/ShowSampleOfAzmayesh"; - -const AzmayeshList = () => { - const columns = useMemo( - () => [ - { - accessorKey: "id", - header: "کد یکتا", - id: "id", - enableColumnFilter: false, - datatype: "text", - filterMode: "notEquals", - grow: false, - size: 100, - }, - { - accessorKey: "province_name", - header: "استان", - id: "province_name", - enableColumnFilter: false, - datatype: "text", - filterMode: "notEquals", - }, - { - accessorKey: "azmayesh_type_name", - header: "نوع آزمایش", - id: "azmayesh_type_name", - enableColumnFilter: false, - datatype: "text", - filterMode: "notEquals", - }, - { - accessorKey: "contract_subitem_id", - header: "کد یکتا پروژه", - id: "contract_subitem_id", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "project_name", - header: "پروژه", - id: "project_name", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "location", - header: "نمایش مختصات", - id: "location", - enableColumnFilter: false, - datatype: "text", - enableSorting: false, - filterMode: "equals", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ row }) => , - }, - { - accessorKey: "employer", - header: "کارفرما", - id: "employer", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "consultant", - header: "مشاور", - id: "consultant", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "contractor", - header: "پیمانکار", - id: "contractor", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "applicant", - header: "متقاضی", - id: "applicant", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "work_number", - header: "شماره کار", - id: "work_number", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "request_number", - header: "شماره درخواست", - id: "request_number", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "request_date", - header: "تاریخ درخواست", - id: "request_date", - enableColumnFilter: false, - datatype: "date", - filterMode: "equals", - grow: false, - size: 100, - Cell: ({ renderedCellValue }) => ( - - {renderedCellValue ? moment(renderedCellValue).locale("fa").format("YYYY/MM/DD") : "-"} - - ), - }, - { - accessorKey: "report_date", - header: "تاریخ گزارش", - id: "report_date", - enableColumnFilter: false, - datatype: "date", - filterMode: "equals", - grow: false, - size: 100, - Cell: ({ renderedCellValue }) => ( - - {renderedCellValue ? moment(renderedCellValue).locale("fa").format("YYYY/MM/DD") : "-"} - - ), - }, - { - accessorKey: "updated_at", - header: "تاریخ بروزرسانی", - id: "updated_at", - enableColumnFilter: false, - datatype: "date", - filterMode: "equals", - grow: false, - size: 100, - Cell: ({ renderedCellValue }) => ( - - {renderedCellValue ? moment(renderedCellValue).locale("fa").format("HH:mm | YYYY/MM/DD") : "-"} - - ), - }, - { - accessorKey: "samples", - header: "نمونه ها", - id: "samples", - enableColumnFilter: false, - datatype: "text", - enableSorting: false, - filterMode: "equals", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ row }) => , - }, - ], - [] - ); - - return ( - <> - - - - - ); -}; -export default AzmayeshList; +"use client"; + +import { useMemo } from "react"; +import { Box, Typography } from "@mui/material"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import Toolbar from "./Toolbar"; +import { GET_AZMAYESH_LIST } from "@/core/utils/routes"; +import ShowLocation from "./ShowLocation"; +import moment from "jalali-moment"; +import RowActions from "./RowActions"; +import ShowSampleOfAzmayesh from "./RowActions/ShowSampleOfAzmayesh"; + +const AzmayeshList = () => { + const columns = useMemo( + () => [ + { + accessorKey: "id", + header: "کد یکتا", + id: "id", + enableColumnFilter: false, + datatype: "text", + filterMode: "notEquals", + grow: false, + size: 100, + }, + { + accessorKey: "province_name", + header: "استان", + id: "province_name", + enableColumnFilter: false, + datatype: "text", + filterMode: "notEquals", + }, + { + accessorKey: "azmayesh_type_name", + header: "نوع آزمایش", + id: "azmayesh_type_name", + enableColumnFilter: false, + datatype: "text", + filterMode: "notEquals", + }, + { + accessorKey: "contract_subitem_id", + header: "کد یکتا پروژه", + id: "contract_subitem_id", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "project_name", + header: "پروژه", + id: "project_name", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "location", + header: "نمایش مختصات", + id: "location", + enableColumnFilter: false, + datatype: "text", + enableSorting: false, + filterMode: "equals", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => , + }, + { + accessorKey: "employer", + header: "کارفرما", + id: "employer", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "consultant", + header: "مشاور", + id: "consultant", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "contractor", + header: "پیمانکار", + id: "contractor", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "applicant", + header: "متقاضی", + id: "applicant", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "work_number", + header: "شماره کار", + id: "work_number", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "request_number", + header: "شماره درخواست", + id: "request_number", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "request_date", + header: "تاریخ درخواست", + id: "request_date", + enableColumnFilter: false, + datatype: "date", + filterMode: "equals", + grow: false, + size: 100, + Cell: ({ renderedCellValue }) => ( + + {renderedCellValue ? moment(renderedCellValue).locale("fa").format("YYYY/MM/DD") : "-"} + + ), + }, + { + accessorKey: "report_date", + header: "تاریخ گزارش", + id: "report_date", + enableColumnFilter: false, + datatype: "date", + filterMode: "equals", + grow: false, + size: 100, + Cell: ({ renderedCellValue }) => ( + + {renderedCellValue ? moment(renderedCellValue).locale("fa").format("YYYY/MM/DD") : "-"} + + ), + }, + { + accessorKey: "updated_at", + header: "تاریخ بروزرسانی", + id: "updated_at", + enableColumnFilter: false, + datatype: "date", + filterMode: "equals", + grow: false, + size: 100, + Cell: ({ renderedCellValue }) => ( + + {renderedCellValue ? moment(renderedCellValue).locale("fa").format("HH:mm | YYYY/MM/DD") : "-"} + + ), + }, + { + accessorKey: "samples", + header: "نمونه ها", + id: "samples", + enableColumnFilter: false, + datatype: "text", + enableSorting: false, + filterMode: "equals", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => , + }, + ], + [] + ); + + return ( + <> + + + + + ); +}; +export default AzmayeshList; diff --git a/src/components/dashboard/azmayesh/Forms/CandUAzmayesh/CandUChooseLocation.jsx b/src/components/dashboard/azmayesh/Forms/CandUAzmayesh/CandUChooseLocation.jsx index afd329f..e113ab8 100644 --- a/src/components/dashboard/azmayesh/Forms/CandUAzmayesh/CandUChooseLocation.jsx +++ b/src/components/dashboard/azmayesh/Forms/CandUAzmayesh/CandUChooseLocation.jsx @@ -1,213 +1,213 @@ -"use client"; - -import { Marker, useMapEvents } from "react-leaflet"; -import { useEffect, useRef, useState } from "react"; -import L from "leaflet"; -import AzmayeshIcon from "@/assets/images/examine_marker.png"; -import AzmayeshActiveIcon from "@/assets/images/examine_marker_active.png"; -import { - Alert, - Box, - Button, - FormControl, - InputAdornment, - InputLabel, - OutlinedInput, - Stack, - Tooltip, - Zoom, - useMediaQuery, -} from "@mui/material"; -import NewReleasesIcon from "@mui/icons-material/NewReleases"; -import VerifiedIcon from "@mui/icons-material/Verified"; -import EditIcon from "@mui/icons-material/Edit"; -import { useTheme } from "@emotion/react"; - -const MAX_ZOOM_FOR_MARKER = 13; - -const CandUChooseLocation = ({ mapBoxData, setMapBoxData }) => { - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const [enableSend, setEnableSend] = useState(false); - - const mapAzmayeshMarker = useRef(); - const defaultIconSize = [35, 35]; - const createCustomIcon = (size, iconUrl) => { - return L.icon({ - iconUrl: iconUrl, - iconSize: size, - iconAnchor: [size[0] / 2, size[1]], - popupAnchor: [0, -size[1]], - }); - }; - - const map = useMapEvents({ - move(e) { - setEnableSend(e.target.getZoom() > MAX_ZOOM_FOR_MARKER); - if (!mapBoxData) { - mapAzmayeshMarker.current.setLatLng(e.target.getCenter()); - } - }, - movestart() { - if (!mapBoxData) { - mapAzmayeshMarker.current.setIcon(createCustomIcon([45, 45], AzmayeshIcon.src)); - } - }, - moveend() { - if (!mapBoxData) { - mapAzmayeshMarker.current.setIcon(createCustomIcon(defaultIconSize, AzmayeshIcon.src)); - } - }, - zoom(e) { - setEnableSend(e.target.getZoom() > MAX_ZOOM_FOR_MARKER); - }, - }); - - useEffect(() => { - if (!mapAzmayeshMarker.current) return; - if (mapBoxData) { - mapAzmayeshMarker.current.setIcon(createCustomIcon([45, 45], AzmayeshActiveIcon.src)); - mapAzmayeshMarker.current.setLatLng(mapBoxData); - map.setView(mapBoxData, 14); - } else { - mapAzmayeshMarker.current.setIcon(createCustomIcon(defaultIconSize, AzmayeshIcon.src)); - } - }, [mapBoxData, mapAzmayeshMarker.current]); - - const handleMarkerClick = () => { - if (!enableSend) return; - if (!mapBoxData) { - setMapBoxData({ - lat: mapAzmayeshMarker.current.getLatLng().lat, - lng: mapAzmayeshMarker.current.getLatLng().lng, - }); - } - }; - - const handleEditLocation = () => { - setMapBoxData(null); - }; - - return ( - <> - - - - - برای ثبت محل آزمایش، لطفاً نقشه را بیشتر زوم کنید. - - - - - - - - - - طول جغرافیایی - - - {mapBoxData ? ( - - ) : ( - - )} - - } - label="طول جغرافیایی" - /> - - - - - - عرض جغرافیایی - - - {mapBoxData ? ( - - ) : ( - - )} - - } - label="عرض جغرافیایی" - /> - - - - - - - - ); -}; - -export default CandUChooseLocation; +"use client"; + +import { Marker, useMapEvents } from "react-leaflet"; +import { useEffect, useRef, useState } from "react"; +import L from "leaflet"; +import AzmayeshIcon from "@/assets/images/examine_marker.png"; +import AzmayeshActiveIcon from "@/assets/images/examine_marker_active.png"; +import { + Alert, + Box, + Button, + FormControl, + InputAdornment, + InputLabel, + OutlinedInput, + Stack, + Tooltip, + Zoom, + useMediaQuery, +} from "@mui/material"; +import NewReleasesIcon from "@mui/icons-material/NewReleases"; +import VerifiedIcon from "@mui/icons-material/Verified"; +import EditIcon from "@mui/icons-material/Edit"; +import { useTheme } from "@emotion/react"; + +const MAX_ZOOM_FOR_MARKER = 13; + +const CandUChooseLocation = ({ mapBoxData, setMapBoxData }) => { + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const [enableSend, setEnableSend] = useState(false); + + const mapAzmayeshMarker = useRef(); + const defaultIconSize = [35, 35]; + const createCustomIcon = (size, iconUrl) => { + return L.icon({ + iconUrl: iconUrl, + iconSize: size, + iconAnchor: [size[0] / 2, size[1]], + popupAnchor: [0, -size[1]], + }); + }; + + const map = useMapEvents({ + move(e) { + setEnableSend(e.target.getZoom() > MAX_ZOOM_FOR_MARKER); + if (!mapBoxData) { + mapAzmayeshMarker.current.setLatLng(e.target.getCenter()); + } + }, + movestart() { + if (!mapBoxData) { + mapAzmayeshMarker.current.setIcon(createCustomIcon([45, 45], AzmayeshIcon.src)); + } + }, + moveend() { + if (!mapBoxData) { + mapAzmayeshMarker.current.setIcon(createCustomIcon(defaultIconSize, AzmayeshIcon.src)); + } + }, + zoom(e) { + setEnableSend(e.target.getZoom() > MAX_ZOOM_FOR_MARKER); + }, + }); + + useEffect(() => { + if (!mapAzmayeshMarker.current) return; + if (mapBoxData) { + mapAzmayeshMarker.current.setIcon(createCustomIcon([45, 45], AzmayeshActiveIcon.src)); + mapAzmayeshMarker.current.setLatLng(mapBoxData); + map.setView(mapBoxData, 14); + } else { + mapAzmayeshMarker.current.setIcon(createCustomIcon(defaultIconSize, AzmayeshIcon.src)); + } + }, [mapBoxData, mapAzmayeshMarker.current]); + + const handleMarkerClick = () => { + if (!enableSend) return; + if (!mapBoxData) { + setMapBoxData({ + lat: mapAzmayeshMarker.current.getLatLng().lat, + lng: mapAzmayeshMarker.current.getLatLng().lng, + }); + } + }; + + const handleEditLocation = () => { + setMapBoxData(null); + }; + + return ( + <> + + + + + برای ثبت محل آزمایش، لطفاً نقشه را بیشتر زوم کنید. + + + + + + + + + + طول جغرافیایی + + + {mapBoxData ? ( + + ) : ( + + )} + + } + label="طول جغرافیایی" + /> + + + + + + عرض جغرافیایی + + + {mapBoxData ? ( + + ) : ( + + )} + + } + label="عرض جغرافیایی" + /> + + + + + + + + ); +}; + +export default CandUChooseLocation; diff --git a/src/components/dashboard/azmayesh/Forms/CandUAzmayesh/CandUGeneralInfo.jsx b/src/components/dashboard/azmayesh/Forms/CandUAzmayesh/CandUGeneralInfo.jsx index 359e5b9..b1085f6 100644 --- a/src/components/dashboard/azmayesh/Forms/CandUAzmayesh/CandUGeneralInfo.jsx +++ b/src/components/dashboard/azmayesh/Forms/CandUAzmayesh/CandUGeneralInfo.jsx @@ -1,373 +1,373 @@ -"use client"; - -import { Controller } from "react-hook-form"; -import { - Autocomplete, - CircularProgress, - FormControl, - FormHelperText, - Grid, - IconButton, - InputAdornment, - InputLabel, - OutlinedInput, - TextField, - Typography, -} from "@mui/material"; -import useAzmayesh from "@/lib/hooks/useAzmayesh"; -import useProvinces from "@/lib/hooks/useProvince"; -import { LocalizationProvider, MobileDatePicker } from "@mui/x-date-pickers"; -import { AdapterDateFnsJalali } from "@mui/x-date-pickers/AdapterDateFnsJalali"; -import { faIR } from "@mui/x-date-pickers/locales"; -import ClearIcon from "@mui/icons-material/Clear"; -import React from "react"; - -const CandUGeneralInfo = ({ control, register, setValue, errors }) => { - const { azmayeshes, errorAzmayeshes, loadingAzmayeshes } = useAzmayesh(); - const { provinces, errorProvinces, loadingProvinces } = useProvinces(); - - return ( - - - ( - - - {errorAzmayeshes ? ( - - خطایی در دریافت لیست آزمایش ها رخ داده است! - - ) : loadingAzmayeshes ? ( - - - درحال دریافت لیست آزمایش ها - - ) : ( - azmayesh.id === value) || null} - disablePortal - options={azmayeshes} - getOptionLabel={(azmayesh) => azmayesh.name} - isOptionEqualToValue={(option, value) => option.id === value?.id} - onChange={(event, newValue) => { - onChange(newValue ? newValue.id : ""); - setValue("azmayesh_type_name", newValue ? newValue.name : ""); - }} - renderInput={(params) => ( - - )} - renderOption={(props, option) => ( -
  • - {option.name} -
  • - )} - /> - )} - - {errors.azmayesh_type_id ? errors.azmayesh_type_id.message : null} - -
    - )} - /> -
    - - ( - - - {errorProvinces ? ( - - خطایی در دریافت لیست استان ها رخ داده است! - - ) : loadingProvinces ? ( - - - درحال دریافت لیست استان ها - - ) : ( - province.id === value) || null} - disablePortal - options={provinces} - getOptionLabel={(province) => province.name_fa} - isOptionEqualToValue={(option, value) => option.id === value?.id} - onChange={(event, newValue) => { - onChange(newValue ? newValue.id : ""); - setValue("province_name", newValue ? newValue.name_fa : ""); - }} - renderInput={(params) => ( - - )} - /> - )} - - {errors.province_id ? errors.province_id.message : null} - - - )} - /> - - - - کد یکتا پروژه - - - {errors.contract_subitem_id ? errors.contract_subitem_id.message : null} - - - - - - پروژه - - - {errors.project_name ? errors.project_name.message : null} - - - - - - کارفرما - - {errors.employer ? errors.employer.message : null} - - - - - مشاور - - - {errors.consultant ? errors.consultant.message : null} - - - - - - پیمانکار - - - {errors.contractor ? errors.contractor.message : null} - - - - - - متقاضی - - {errors.applicant ? errors.applicant.message : null} - - - - - شماره کار - - - {errors.work_number ? errors.work_number.message : null} - - - - - - شماره درخواست - - - {errors.request_number ? errors.request_number.message : null} - - - - - ( - - - { - onChange(newValue); - }} - closeOnSelect - slotProps={{ - textField: { - size: "small", - error: !!errors.request_date, - placeholder: "تاریخ درخواست", - InputProps: { - endAdornment: ( - - { - event.stopPropagation(); - setValue("request_date", ""); - }} - sx={{ - color: "#bfbfbf", - "&:hover": { - backgroundColor: "rgba(189, 189, 189, 0.1)", - color: "#363434", - }, - }} - > - - - - ), - }, - }, - }} - /> - - - {errors.request_date ? errors.request_date.message : null} - - - )} - /> - - - ( - - - { - onChange(newValue); - }} - closeOnSelect - slotProps={{ - textField: { - size: "small", - error: !!errors.report_date, - placeholder: "تاریخ گزارش", - InputProps: { - endAdornment: ( - - { - event.stopPropagation(); - setValue("report_date", ""); - }} - sx={{ - color: "#bfbfbf", - "&:hover": { - backgroundColor: "rgba(189, 189, 189, 0.1)", - color: "#363434", - }, - }} - > - - - - ), - }, - }, - }} - /> - - - {errors.report_date ? errors.report_date.message : null} - - - )} - /> - -
    - ); -}; -export default CandUGeneralInfo; +"use client"; + +import { Controller } from "react-hook-form"; +import { + Autocomplete, + CircularProgress, + FormControl, + FormHelperText, + Grid, + IconButton, + InputAdornment, + InputLabel, + OutlinedInput, + TextField, + Typography, +} from "@mui/material"; +import useAzmayesh from "@/lib/hooks/useAzmayesh"; +import useProvinces from "@/lib/hooks/useProvince"; +import { LocalizationProvider, MobileDatePicker } from "@mui/x-date-pickers"; +import { AdapterDateFnsJalali } from "@mui/x-date-pickers/AdapterDateFnsJalali"; +import { faIR } from "@mui/x-date-pickers/locales"; +import ClearIcon from "@mui/icons-material/Clear"; +import React from "react"; + +const CandUGeneralInfo = ({ control, register, setValue, errors }) => { + const { azmayeshes, errorAzmayeshes, loadingAzmayeshes } = useAzmayesh(); + const { provinces, errorProvinces, loadingProvinces } = useProvinces(); + + return ( + + + ( + + + {errorAzmayeshes ? ( + + خطایی در دریافت لیست آزمایش ها رخ داده است! + + ) : loadingAzmayeshes ? ( + + + درحال دریافت لیست آزمایش ها + + ) : ( + azmayesh.id === value) || null} + disablePortal + options={azmayeshes} + getOptionLabel={(azmayesh) => azmayesh.name} + isOptionEqualToValue={(option, value) => option.id === value?.id} + onChange={(event, newValue) => { + onChange(newValue ? newValue.id : ""); + setValue("azmayesh_type_name", newValue ? newValue.name : ""); + }} + renderInput={(params) => ( + + )} + renderOption={(props, option) => ( +
  • + {option.name} +
  • + )} + /> + )} + + {errors.azmayesh_type_id ? errors.azmayesh_type_id.message : null} + +
    + )} + /> +
    + + ( + + + {errorProvinces ? ( + + خطایی در دریافت لیست استان ها رخ داده است! + + ) : loadingProvinces ? ( + + + درحال دریافت لیست استان ها + + ) : ( + province.id === value) || null} + disablePortal + options={provinces} + getOptionLabel={(province) => province.name_fa} + isOptionEqualToValue={(option, value) => option.id === value?.id} + onChange={(event, newValue) => { + onChange(newValue ? newValue.id : ""); + setValue("province_name", newValue ? newValue.name_fa : ""); + }} + renderInput={(params) => ( + + )} + /> + )} + + {errors.province_id ? errors.province_id.message : null} + + + )} + /> + + + + کد یکتا پروژه + + + {errors.contract_subitem_id ? errors.contract_subitem_id.message : null} + + + + + + پروژه + + + {errors.project_name ? errors.project_name.message : null} + + + + + + کارفرما + + {errors.employer ? errors.employer.message : null} + + + + + مشاور + + + {errors.consultant ? errors.consultant.message : null} + + + + + + پیمانکار + + + {errors.contractor ? errors.contractor.message : null} + + + + + + متقاضی + + {errors.applicant ? errors.applicant.message : null} + + + + + شماره کار + + + {errors.work_number ? errors.work_number.message : null} + + + + + + شماره درخواست + + + {errors.request_number ? errors.request_number.message : null} + + + + + ( + + + { + onChange(newValue); + }} + closeOnSelect + slotProps={{ + textField: { + size: "small", + error: !!errors.request_date, + placeholder: "تاریخ درخواست", + InputProps: { + endAdornment: ( + + { + event.stopPropagation(); + setValue("request_date", ""); + }} + sx={{ + color: "#bfbfbf", + "&:hover": { + backgroundColor: "rgba(189, 189, 189, 0.1)", + color: "#363434", + }, + }} + > + + + + ), + }, + }, + }} + /> + + + {errors.request_date ? errors.request_date.message : null} + + + )} + /> + + + ( + + + { + onChange(newValue); + }} + closeOnSelect + slotProps={{ + textField: { + size: "small", + error: !!errors.report_date, + placeholder: "تاریخ گزارش", + InputProps: { + endAdornment: ( + + { + event.stopPropagation(); + setValue("report_date", ""); + }} + sx={{ + color: "#bfbfbf", + "&:hover": { + backgroundColor: "rgba(189, 189, 189, 0.1)", + color: "#363434", + }, + }} + > + + + + ), + }, + }, + }} + /> + + + {errors.report_date ? errors.report_date.message : null} + + + )} + /> + +
    + ); +}; +export default CandUGeneralInfo; diff --git a/src/components/dashboard/azmayesh/Forms/CandUAzmayesh/CandUMapBox.jsx b/src/components/dashboard/azmayesh/Forms/CandUAzmayesh/CandUMapBox.jsx index 1907436..497b634 100644 --- a/src/components/dashboard/azmayesh/Forms/CandUAzmayesh/CandUMapBox.jsx +++ b/src/components/dashboard/azmayesh/Forms/CandUAzmayesh/CandUMapBox.jsx @@ -1,41 +1,41 @@ -"use client"; - -import { Box, Stack } from "@mui/material"; -import dynamic from "next/dynamic"; -import MapLoading from "@/core/components/MapLayer/Loading"; -import CandUChooseLocation from "./CandUChooseLocation"; - -const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { - loading: () => , - ssr: false, -}); - -const CandUMapBox = ({ mapBoxData, setMapBoxData }) => { - return ( - - - - - - - - - - ); -}; -export default CandUMapBox; +"use client"; + +import { Box, Stack } from "@mui/material"; +import dynamic from "next/dynamic"; +import MapLoading from "@/core/components/MapLayer/Loading"; +import CandUChooseLocation from "./CandUChooseLocation"; + +const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { + loading: () => , + ssr: false, +}); + +const CandUMapBox = ({ mapBoxData, setMapBoxData }) => { + return ( + + + + + + + + + + ); +}; +export default CandUMapBox; diff --git a/src/components/dashboard/azmayesh/Forms/CandUAzmayesh/CandUTimeLine.jsx b/src/components/dashboard/azmayesh/Forms/CandUAzmayesh/CandUTimeLine.jsx index bcf43b3..abc1415 100644 --- a/src/components/dashboard/azmayesh/Forms/CandUAzmayesh/CandUTimeLine.jsx +++ b/src/components/dashboard/azmayesh/Forms/CandUAzmayesh/CandUTimeLine.jsx @@ -1,65 +1,65 @@ -"use client"; - -import { Box, Typography } from "@mui/material"; -import TextSnippetIcon from "@mui/icons-material/TextSnippet"; -import TravelExploreIcon from "@mui/icons-material/TravelExplore"; -import { - Timeline, - TimelineConnector, - TimelineContent, - TimelineDot, - TimelineItem, - timelineItemClasses, - TimelineSeparator, -} from "@mui/lab"; - -const CandUCreateTimeLine = ({ tabState }) => { - return ( - - - - - - - - - - - - نقشه - - ثبت مختصات محل آزمایش - - - - - - - - - - - - - مشخصات آزمایش - - ثبت مشخصات اولیه - - - - - - ); -}; -export default CandUCreateTimeLine; +"use client"; + +import { Box, Typography } from "@mui/material"; +import TextSnippetIcon from "@mui/icons-material/TextSnippet"; +import TravelExploreIcon from "@mui/icons-material/TravelExplore"; +import { + Timeline, + TimelineConnector, + TimelineContent, + TimelineDot, + TimelineItem, + timelineItemClasses, + TimelineSeparator, +} from "@mui/lab"; + +const CandUCreateTimeLine = ({ tabState }) => { + return ( + + + + + + + + + + + + نقشه + + ثبت مختصات محل آزمایش + + + + + + + + + + + + + مشخصات آزمایش + + ثبت مشخصات اولیه + + + + + + ); +}; +export default CandUCreateTimeLine; diff --git a/src/components/dashboard/azmayesh/Forms/CandUAzmayesh/FormAndRequest.jsx b/src/components/dashboard/azmayesh/Forms/CandUAzmayesh/FormAndRequest.jsx index 14d5b3d..c1ca289 100644 --- a/src/components/dashboard/azmayesh/Forms/CandUAzmayesh/FormAndRequest.jsx +++ b/src/components/dashboard/azmayesh/Forms/CandUAzmayesh/FormAndRequest.jsx @@ -1,200 +1,200 @@ -"use client"; - -import { Box, Button, DialogActions, DialogContent, Tab, Tabs, useMediaQuery } from "@mui/material"; -import React, { useState } from "react"; -import { useTheme } from "@emotion/react"; -import useRequest from "@/lib/hooks/useRequest"; -import { object, string } from "yup"; -import { useForm } from "react-hook-form"; -import { yupResolver } from "@hookform/resolvers/yup"; -import moment from "jalali-moment"; -import { CREATE_AZMAYESH, UPDATE_AZMAYESH } from "@/core/utils/routes"; -import StyledForm from "@/core/components/StyledForm"; -import TravelExploreIcon from "@mui/icons-material/TravelExplore"; -import TextSnippetIcon from "@mui/icons-material/TextSnippet"; -import ExitToAppIcon from "@mui/icons-material/ExitToApp"; -import KeyboardDoubleArrowRightIcon from "@mui/icons-material/KeyboardDoubleArrowRight"; -import KeyboardDoubleArrowLeftIcon from "@mui/icons-material/KeyboardDoubleArrowLeft"; -import BeenhereIcon from "@mui/icons-material/Beenhere"; -import CandUMapBox from "./CandUMapBox"; -import CandUCreateTimeLine from "./CandUTimeLine"; -import CandUGeneralInfo from "./CandUGeneralInfo"; - -function TabPanel(props) { - const { children, value, index } = props; - - return ( - - ); -} - -const validationSchema = object({ - azmayesh_type_id: string().required("نوع آزمایش را مشخص کنید!"), - province_id: string().required("استان را وارد کنید!"), - contract_subitem_id: string().required("کد یکتا پروژه را وارد کنید!"), - project_name: string().required("عنوان پروژه را وارد کنید!"), - employer: string().required("کارفرما را وارد کنید!"), - consultant: string().required("مشاور را وارد کنید!"), - contractor: string().required("پیمانکار را وارد کنید!"), - applicant: string().required("متقاضی را وارد کنید!"), - work_number: string().required("شماره کار را وارد کنید!"), - request_number: string().required("شماره درخواست را وارد کنید!"), - request_date: string().required("تاریخ درخواست را وارد کنید!"), - report_date: string().required("تاریخ گزارش را وارد کنید!"), -}); - -const CandUAzmayesh = ({ setOpen, mutate, updateInfo, rowId }) => { - const theme = useTheme(); - const requestServer = useRequest({ notificationSuccess: true }); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const [tabState, setTabState] = useState(0); - const [mapBoxData, setMapBoxData] = useState(updateInfo ? { lat: updateInfo.lat, lng: updateInfo.lng } : null); - - const handleClose = () => { - setOpen(false); - }; - - const handleChangeTab = (event, newValue) => { - setTabState(newValue); - }; - - const handlePrev = () => { - if (tabState === 0) { - handleClose(); - } else { - setTabState(tabState - 1); - } - }; - - const defaultValues = { - azmayesh_type_id: updateInfo ? updateInfo.azmayesh_type_id : "", - azmayesh_type_name: updateInfo ? updateInfo.azmayesh_type_name : "", - province_id: updateInfo ? updateInfo.province_id : "", - province_name: updateInfo ? updateInfo.province_name : "", - contract_subitem_id: updateInfo ? updateInfo.contract_subitem_id : "", - project_name: updateInfo ? updateInfo.project_name : "", - employer: updateInfo ? updateInfo.employer : "", - consultant: updateInfo ? updateInfo.consultant : "", - contractor: updateInfo ? updateInfo.contractor : "", - applicant: updateInfo ? updateInfo.applicant : "", - work_number: updateInfo ? updateInfo.work_number : "", - request_number: updateInfo ? updateInfo.request_number : "", - request_date: updateInfo ? moment(updateInfo.request_date, "YYYY-MM-DD").toDate() : "", - report_date: updateInfo ? moment(updateInfo.report_date, "YYYY-MM-DD").toDate() : "", - }; - - const { - control, - register, - handleSubmit, - setValue, - formState: { isSubmitting, errors }, - } = useForm({ defaultValues, resolver: yupResolver(validationSchema), mode: "all" }); - - const onSubmit = async (data) => { - const formData = new FormData(); - formData.append("lat", mapBoxData.lat); - formData.append("lng", mapBoxData.lng); - formData.append("azmayesh_type_id", data.azmayesh_type_id); - formData.append("azmayesh_type_name", data.azmayesh_type_name); - formData.append("province_id", data.province_id); - formData.append("province_name", data.province_name); - formData.append("contract_subitem_id", data.contract_subitem_id); - formData.append("project_name", data.project_name); - formData.append("employer", data.employer); - formData.append("consultant", data.consultant); - formData.append("contractor", data.contractor); - formData.append("applicant", data.applicant); - formData.append("work_number", data.work_number); - formData.append("request_number", data.request_number); - formData.append("request_date", moment(new Date(data.request_date)).format("YYYY-MM-DD")); - formData.append("report_date", moment(new Date(data.report_date)).format("YYYY-MM-DD")); - - try { - await requestServer(updateInfo ? `${UPDATE_AZMAYESH}/${rowId}` : CREATE_AZMAYESH, "post", { - data: formData, - }); - mutate(); - handleClose(); - } catch (error) {} - }; - - return ( - - - } label="انتخاب محل آزمایش"> - } label="مشخصات آزمایش"> - - - - - - - - - - - {!isMobile && ( - - - - )} - - - - {tabState === 0 ? ( - - ) : ( - - )} - - - ); -}; -export default CandUAzmayesh; +"use client"; + +import { Box, Button, DialogActions, DialogContent, Tab, Tabs, useMediaQuery } from "@mui/material"; +import React, { useState } from "react"; +import { useTheme } from "@emotion/react"; +import useRequest from "@/lib/hooks/useRequest"; +import { object, string } from "yup"; +import { useForm } from "react-hook-form"; +import { yupResolver } from "@hookform/resolvers/yup"; +import moment from "jalali-moment"; +import { CREATE_AZMAYESH, UPDATE_AZMAYESH } from "@/core/utils/routes"; +import StyledForm from "@/core/components/StyledForm"; +import TravelExploreIcon from "@mui/icons-material/TravelExplore"; +import TextSnippetIcon from "@mui/icons-material/TextSnippet"; +import ExitToAppIcon from "@mui/icons-material/ExitToApp"; +import KeyboardDoubleArrowRightIcon from "@mui/icons-material/KeyboardDoubleArrowRight"; +import KeyboardDoubleArrowLeftIcon from "@mui/icons-material/KeyboardDoubleArrowLeft"; +import BeenhereIcon from "@mui/icons-material/Beenhere"; +import CandUMapBox from "./CandUMapBox"; +import CandUCreateTimeLine from "./CandUTimeLine"; +import CandUGeneralInfo from "./CandUGeneralInfo"; + +function TabPanel(props) { + const { children, value, index } = props; + + return ( + + ); +} + +const validationSchema = object({ + azmayesh_type_id: string().required("نوع آزمایش را مشخص کنید!"), + province_id: string().required("استان را وارد کنید!"), + contract_subitem_id: string().required("کد یکتا پروژه را وارد کنید!"), + project_name: string().required("عنوان پروژه را وارد کنید!"), + employer: string().required("کارفرما را وارد کنید!"), + consultant: string().required("مشاور را وارد کنید!"), + contractor: string().required("پیمانکار را وارد کنید!"), + applicant: string().required("متقاضی را وارد کنید!"), + work_number: string().required("شماره کار را وارد کنید!"), + request_number: string().required("شماره درخواست را وارد کنید!"), + request_date: string().required("تاریخ درخواست را وارد کنید!"), + report_date: string().required("تاریخ گزارش را وارد کنید!"), +}); + +const CandUAzmayesh = ({ setOpen, mutate, updateInfo, rowId }) => { + const theme = useTheme(); + const requestServer = useRequest({ notificationSuccess: true }); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const [tabState, setTabState] = useState(0); + const [mapBoxData, setMapBoxData] = useState(updateInfo ? { lat: updateInfo.lat, lng: updateInfo.lng } : null); + + const handleClose = () => { + setOpen(false); + }; + + const handleChangeTab = (event, newValue) => { + setTabState(newValue); + }; + + const handlePrev = () => { + if (tabState === 0) { + handleClose(); + } else { + setTabState(tabState - 1); + } + }; + + const defaultValues = { + azmayesh_type_id: updateInfo ? updateInfo.azmayesh_type_id : "", + azmayesh_type_name: updateInfo ? updateInfo.azmayesh_type_name : "", + province_id: updateInfo ? updateInfo.province_id : "", + province_name: updateInfo ? updateInfo.province_name : "", + contract_subitem_id: updateInfo ? updateInfo.contract_subitem_id : "", + project_name: updateInfo ? updateInfo.project_name : "", + employer: updateInfo ? updateInfo.employer : "", + consultant: updateInfo ? updateInfo.consultant : "", + contractor: updateInfo ? updateInfo.contractor : "", + applicant: updateInfo ? updateInfo.applicant : "", + work_number: updateInfo ? updateInfo.work_number : "", + request_number: updateInfo ? updateInfo.request_number : "", + request_date: updateInfo ? moment(updateInfo.request_date, "YYYY-MM-DD").toDate() : "", + report_date: updateInfo ? moment(updateInfo.report_date, "YYYY-MM-DD").toDate() : "", + }; + + const { + control, + register, + handleSubmit, + setValue, + formState: { isSubmitting, errors }, + } = useForm({ defaultValues, resolver: yupResolver(validationSchema), mode: "all" }); + + const onSubmit = async (data) => { + const formData = new FormData(); + formData.append("lat", mapBoxData.lat); + formData.append("lng", mapBoxData.lng); + formData.append("azmayesh_type_id", data.azmayesh_type_id); + formData.append("azmayesh_type_name", data.azmayesh_type_name); + formData.append("province_id", data.province_id); + formData.append("province_name", data.province_name); + formData.append("contract_subitem_id", data.contract_subitem_id); + formData.append("project_name", data.project_name); + formData.append("employer", data.employer); + formData.append("consultant", data.consultant); + formData.append("contractor", data.contractor); + formData.append("applicant", data.applicant); + formData.append("work_number", data.work_number); + formData.append("request_number", data.request_number); + formData.append("request_date", moment(new Date(data.request_date)).format("YYYY-MM-DD")); + formData.append("report_date", moment(new Date(data.report_date)).format("YYYY-MM-DD")); + + try { + await requestServer(updateInfo ? `${UPDATE_AZMAYESH}/${rowId}` : CREATE_AZMAYESH, "post", { + data: formData, + }); + mutate(); + handleClose(); + } catch (error) {} + }; + + return ( + + + } label="انتخاب محل آزمایش"> + } label="مشخصات آزمایش"> + + + + + + + + + + + {!isMobile && ( + + + + )} + + + + {tabState === 0 ? ( + + ) : ( + + )} + + + ); +}; +export default CandUAzmayesh; diff --git a/src/components/dashboard/azmayesh/Forms/CandUAzmayesh/index.jsx b/src/components/dashboard/azmayesh/Forms/CandUAzmayesh/index.jsx index 8ce5b88..10adcd5 100644 --- a/src/components/dashboard/azmayesh/Forms/CandUAzmayesh/index.jsx +++ b/src/components/dashboard/azmayesh/Forms/CandUAzmayesh/index.jsx @@ -1,38 +1,38 @@ -"use client"; - -import { Dialog, IconButton } from "@mui/material"; -import FormAndRequest from "./FormAndRequest"; -import DialogLoading from "@/core/components/DialogLoading"; -import CloseIcon from "@mui/icons-material/Close"; - -const CandUAzmayesh = ({ open, setOpen, mutate, updateInfo, rowId, loadingOpen, fromUpdate = false }) => { - const isUpdateReady = fromUpdate ? updateInfo !== null : true; - return ( - - setOpen(false)} - sx={(theme) => ({ - position: "absolute", - right: 8, - top: 8, - zIndex: 50, - color: theme.palette.grey[500], - })} - > - - - {isUpdateReady ? ( - - ) : ( - - )} - - ); -}; -export default CandUAzmayesh; +"use client"; + +import { Dialog, IconButton } from "@mui/material"; +import FormAndRequest from "./FormAndRequest"; +import DialogLoading from "@/core/components/DialogLoading"; +import CloseIcon from "@mui/icons-material/Close"; + +const CandUAzmayesh = ({ open, setOpen, mutate, updateInfo, rowId, loadingOpen, fromUpdate = false }) => { + const isUpdateReady = fromUpdate ? updateInfo !== null : true; + return ( + + setOpen(false)} + sx={(theme) => ({ + position: "absolute", + right: 8, + top: 8, + zIndex: 50, + color: theme.palette.grey[500], + })} + > + + + {isUpdateReady ? ( + + ) : ( + + )} + + ); +}; +export default CandUAzmayesh; diff --git a/src/components/dashboard/azmayesh/RowActions/AzmayeshUpdate/index.jsx b/src/components/dashboard/azmayesh/RowActions/AzmayeshUpdate/index.jsx index d1dc7b6..3730751 100644 --- a/src/components/dashboard/azmayesh/RowActions/AzmayeshUpdate/index.jsx +++ b/src/components/dashboard/azmayesh/RowActions/AzmayeshUpdate/index.jsx @@ -1,52 +1,52 @@ -import { IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import useRequest from "@/lib/hooks/useRequest"; -import EditIcon from "@mui/icons-material/Edit"; -import { GET_AZMAYESH_LIST } from "@/core/utils/routes"; -import CandUAzmayesh from "@/components/dashboard/azmayesh/Forms/CandUAzmayesh"; - -const AzmayeshUpdate = ({ rowId, mutate }) => { - const requestServer = useRequest(); - const [openUpdateDialog, setOpenUpdateDialog] = useState(false); - const [updateInfo, setUpdateInfo] = useState(null); - const [loadingOpen, setLoadingOpen] = useState(false); - - const handleGetInfo = () => { - setLoadingOpen(true); - setOpenUpdateDialog(true); - requestServer(`${GET_AZMAYESH_LIST}/${rowId}`, "get") - .then((response) => { - setUpdateInfo(response.data.data); - }) - .catch(() => {}) - .finally(() => { - setLoadingOpen(false); - }); - }; - - return ( - <> - - - - - - {openUpdateDialog && ( - - )} - - ); -}; -export default AzmayeshUpdate; +import { IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import useRequest from "@/lib/hooks/useRequest"; +import EditIcon from "@mui/icons-material/Edit"; +import { GET_AZMAYESH_LIST } from "@/core/utils/routes"; +import CandUAzmayesh from "@/components/dashboard/azmayesh/Forms/CandUAzmayesh"; + +const AzmayeshUpdate = ({ rowId, mutate }) => { + const requestServer = useRequest(); + const [openUpdateDialog, setOpenUpdateDialog] = useState(false); + const [updateInfo, setUpdateInfo] = useState(null); + const [loadingOpen, setLoadingOpen] = useState(false); + + const handleGetInfo = () => { + setLoadingOpen(true); + setOpenUpdateDialog(true); + requestServer(`${GET_AZMAYESH_LIST}/${rowId}`, "get") + .then((response) => { + setUpdateInfo(response.data.data); + }) + .catch(() => {}) + .finally(() => { + setLoadingOpen(false); + }); + }; + + return ( + <> + + + + + + {openUpdateDialog && ( + + )} + + ); +}; +export default AzmayeshUpdate; diff --git a/src/components/dashboard/azmayesh/RowActions/DeleteAzmayesh/index.jsx b/src/components/dashboard/azmayesh/RowActions/DeleteAzmayesh/index.jsx index ed25f23..9b6945b 100644 --- a/src/components/dashboard/azmayesh/RowActions/DeleteAzmayesh/index.jsx +++ b/src/components/dashboard/azmayesh/RowActions/DeleteAzmayesh/index.jsx @@ -1,78 +1,78 @@ -import { - Button, - Dialog, - DialogActions, - DialogContent, - DialogTitle, - IconButton, - Tooltip, - Typography, -} from "@mui/material"; -import { useState } from "react"; -import useRequest from "@/lib/hooks/useRequest"; -import DeleteIcon from "@mui/icons-material/Delete"; -import { DELETE_AZMAYESH } from "@/core/utils/routes"; - -const DeleteAzmayesh = ({ rowId, mutate }) => { - const requestServer = useRequest({ notificationSuccess: true }); - const [openDeleteDialog, setOpenDeleteDialog] = useState(false); - const [isSubmitting, setIsSubmitting] = useState(false); - - const handleSubmit = () => { - setIsSubmitting(true); - requestServer(`${DELETE_AZMAYESH}/${rowId}`, "post") - .then(() => { - setOpenDeleteDialog(false); - mutate(); - }) - .catch(() => {}) - .finally(() => { - setIsSubmitting(false); - }); - }; - - return ( - <> - - { - setOpenDeleteDialog(true); - }} - > - - - - - حذف آزمایش - - آیا از حذف این آزمایش مطمئن هستید؟ - - - - - - - - ); -}; -export default DeleteAzmayesh; +import { + Button, + Dialog, + DialogActions, + DialogContent, + DialogTitle, + IconButton, + Tooltip, + Typography, +} from "@mui/material"; +import { useState } from "react"; +import useRequest from "@/lib/hooks/useRequest"; +import DeleteIcon from "@mui/icons-material/Delete"; +import { DELETE_AZMAYESH } from "@/core/utils/routes"; + +const DeleteAzmayesh = ({ rowId, mutate }) => { + const requestServer = useRequest({ notificationSuccess: true }); + const [openDeleteDialog, setOpenDeleteDialog] = useState(false); + const [isSubmitting, setIsSubmitting] = useState(false); + + const handleSubmit = () => { + setIsSubmitting(true); + requestServer(`${DELETE_AZMAYESH}/${rowId}`, "post") + .then(() => { + setOpenDeleteDialog(false); + mutate(); + }) + .catch(() => {}) + .finally(() => { + setIsSubmitting(false); + }); + }; + + return ( + <> + + { + setOpenDeleteDialog(true); + }} + > + + + + + حذف آزمایش + + آیا از حذف این آزمایش مطمئن هستید؟ + + + + + + + + ); +}; +export default DeleteAzmayesh; diff --git a/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/Actions/Create/index.jsx b/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/Actions/Create/index.jsx index 2139d22..4f8d0df 100644 --- a/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/Actions/Create/index.jsx +++ b/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/Actions/Create/index.jsx @@ -1,59 +1,59 @@ -import { Button, IconButton, useMediaQuery } from "@mui/material"; -import useRequest from "@/lib/hooks/useRequest"; -import { useEffect, useState } from "react"; -import { GET_AZMAYESH_SAMPLE_FIELDS } from "@/core/utils/routes"; -import { AddCircle } from "@mui/icons-material"; -import { useTheme } from "@emotion/react"; -import CandUSampleOfAzmayesh from "@/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/Forms/CandUSampleOfAzmayesh"; - -const AddSampleToAzmayesh = ({ azmayeshTypeId, mutate, rowId }) => { - const requestServer = useRequest(); - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const [sampleInfo, setSampleInfo] = useState(null); - const [openAddSampleDialog, setOpenAddSampleDialog] = useState(false); - const [defaultValues, setDefaultValues] = useState({}); - - const handleGetFields = () => { - requestServer(`${GET_AZMAYESH_SAMPLE_FIELDS}/${azmayeshTypeId}`, "get") - .then((response) => { - setSampleInfo(response.data.data); - }) - .catch(() => {}) - .finally(() => { - setOpenAddSampleDialog(true); - }); - }; - - useEffect(() => { - const initialValues = sampleInfo?.reduce((acc, item) => { - acc[item.id] = ""; - return acc; - }, {}); - setDefaultValues(initialValues); - }, [sampleInfo]); - - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - - - ); -}; -export default AddSampleToAzmayesh; +import { Button, IconButton, useMediaQuery } from "@mui/material"; +import useRequest from "@/lib/hooks/useRequest"; +import { useEffect, useState } from "react"; +import { GET_AZMAYESH_SAMPLE_FIELDS } from "@/core/utils/routes"; +import { AddCircle } from "@mui/icons-material"; +import { useTheme } from "@emotion/react"; +import CandUSampleOfAzmayesh from "@/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/Forms/CandUSampleOfAzmayesh"; + +const AddSampleToAzmayesh = ({ azmayeshTypeId, mutate, rowId }) => { + const requestServer = useRequest(); + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const [sampleInfo, setSampleInfo] = useState(null); + const [openAddSampleDialog, setOpenAddSampleDialog] = useState(false); + const [defaultValues, setDefaultValues] = useState({}); + + const handleGetFields = () => { + requestServer(`${GET_AZMAYESH_SAMPLE_FIELDS}/${azmayeshTypeId}`, "get") + .then((response) => { + setSampleInfo(response.data.data); + }) + .catch(() => {}) + .finally(() => { + setOpenAddSampleDialog(true); + }); + }; + + useEffect(() => { + const initialValues = sampleInfo?.reduce((acc, item) => { + acc[item.id] = ""; + return acc; + }, {}); + setDefaultValues(initialValues); + }, [sampleInfo]); + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + + + ); +}; +export default AddSampleToAzmayesh; diff --git a/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/AzmayeshInfo.jsx b/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/AzmayeshInfo.jsx index e33593c..0562f1f 100644 --- a/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/AzmayeshInfo.jsx +++ b/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/AzmayeshInfo.jsx @@ -1,82 +1,82 @@ -"use client"; - -import { Box, Chip, Divider, Grid, Stack, Typography } from "@mui/material"; -import ScienceIcon from "@mui/icons-material/Science"; -import LocationCityIcon from "@mui/icons-material/LocationCity"; - -const AzmayeshInfo = ({ rowData }) => { - return ( - - - {rowData.project_name} - - - - - } - label={ - - نوع آزمایش - - } - /> - - - - {rowData.azmayesh_type_name} - - - - - } - label={ - - نام استان - - } - /> - - - - {rowData.province_name} - - - - - } - label={ - - شماره کار - - } - /> - - - - {rowData.work_number} - - - - - } - label={ - - شماره درخواست - - } - /> - - - - {rowData.request_number} - - - - - ); -}; -export default AzmayeshInfo; +"use client"; + +import { Box, Chip, Divider, Grid, Stack, Typography } from "@mui/material"; +import ScienceIcon from "@mui/icons-material/Science"; +import LocationCityIcon from "@mui/icons-material/LocationCity"; + +const AzmayeshInfo = ({ rowData }) => { + return ( + + + {rowData.project_name} + + + + + } + label={ + + نوع آزمایش + + } + /> + + + + {rowData.azmayesh_type_name} + + + + + } + label={ + + نام استان + + } + /> + + + + {rowData.province_name} + + + + + } + label={ + + شماره کار + + } + /> + + + + {rowData.work_number} + + + + + } + label={ + + شماره درخواست + + } + /> + + + + {rowData.request_number} + + + + + ); +}; +export default AzmayeshInfo; diff --git a/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/Forms/CandUSampleOfAzmayesh/FormAndRequest.jsx b/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/Forms/CandUSampleOfAzmayesh/FormAndRequest.jsx index a6c89fa..da183bb 100644 --- a/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/Forms/CandUSampleOfAzmayesh/FormAndRequest.jsx +++ b/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/Forms/CandUSampleOfAzmayesh/FormAndRequest.jsx @@ -1,76 +1,76 @@ -import { Button, DialogActions, DialogContent, DialogTitle } from "@mui/material"; -import useRequest from "@/lib/hooks/useRequest"; -import React, { useState } from "react"; -import { ADD_SAMPLE_TO_AZMAYESH, UPDATE_SAMPLE_OF_AZMAYESH } from "@/core/utils/routes"; -import FormMaker from "@/core/components/FormMaker"; -import { DialogHeader } from "next/dist/client/components/react-dev-overlay/internal/components/Dialog"; - -const CandUSampleOfAzmayesh = ({ - sampleInfo, - mutate, - rowId, - setOpenSampleDialog, - defaultValues, - setDefaultValues, - isUpdate, - azmayesh_id, -}) => { - const requestServer = useRequest({ notificationSuccess: true }); - const [isSubmitting, setIsSubmitting] = useState(false); - - const handleSubmit = async () => { - const data = {}; - setIsSubmitting(true); - const formData = new FormData(); - formData.append("azmayesh_id", isUpdate ? azmayesh_id : rowId); - Object.entries(defaultValues).forEach(([key, value]) => { - data[key] = value; - }); - formData.append("data", JSON.stringify(data)); - try { - await requestServer( - isUpdate ? `${UPDATE_SAMPLE_OF_AZMAYESH}/${rowId}` : `${ADD_SAMPLE_TO_AZMAYESH}`, - "post", - { - data: formData, - } - ); - mutate(); - setOpenSampleDialog(false); - setIsSubmitting(false); - } catch (error) { - setIsSubmitting(false); - } - }; - - return ( - <> - - {isUpdate ? "ویرایش نمونه" : "افزودن نمونه"} - - - - - - - - - - ); -}; -export default CandUSampleOfAzmayesh; +import { Button, DialogActions, DialogContent, DialogTitle } from "@mui/material"; +import useRequest from "@/lib/hooks/useRequest"; +import React, { useState } from "react"; +import { ADD_SAMPLE_TO_AZMAYESH, UPDATE_SAMPLE_OF_AZMAYESH } from "@/core/utils/routes"; +import FormMaker from "@/core/components/FormMaker"; +import { DialogHeader } from "next/dist/client/components/react-dev-overlay/internal/components/Dialog"; + +const CandUSampleOfAzmayesh = ({ + sampleInfo, + mutate, + rowId, + setOpenSampleDialog, + defaultValues, + setDefaultValues, + isUpdate, + azmayesh_id, +}) => { + const requestServer = useRequest({ notificationSuccess: true }); + const [isSubmitting, setIsSubmitting] = useState(false); + + const handleSubmit = async () => { + const data = {}; + setIsSubmitting(true); + const formData = new FormData(); + formData.append("azmayesh_id", isUpdate ? azmayesh_id : rowId); + Object.entries(defaultValues).forEach(([key, value]) => { + data[key] = value; + }); + formData.append("data", JSON.stringify(data)); + try { + await requestServer( + isUpdate ? `${UPDATE_SAMPLE_OF_AZMAYESH}/${rowId}` : `${ADD_SAMPLE_TO_AZMAYESH}`, + "post", + { + data: formData, + } + ); + mutate(); + setOpenSampleDialog(false); + setIsSubmitting(false); + } catch (error) { + setIsSubmitting(false); + } + }; + + return ( + <> + + {isUpdate ? "ویرایش نمونه" : "افزودن نمونه"} + + + + + + + + + + ); +}; +export default CandUSampleOfAzmayesh; diff --git a/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/Forms/CandUSampleOfAzmayesh/index.jsx b/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/Forms/CandUSampleOfAzmayesh/index.jsx index 5cabf7c..f8674e0 100644 --- a/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/Forms/CandUSampleOfAzmayesh/index.jsx +++ b/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/Forms/CandUSampleOfAzmayesh/index.jsx @@ -1,74 +1,74 @@ -import { Button, Dialog, DialogActions, DialogContent, DialogTitle } from "@mui/material"; -import useRequest from "@/lib/hooks/useRequest"; -import React, { useState } from "react"; -import { ADD_SAMPLE_TO_AZMAYESH, UPDATE_SAMPLE_OF_AZMAYESH } from "@/core/utils/routes"; -import FormMaker from "@/core/components/FormMaker"; -import { DialogHeader } from "next/dist/client/components/react-dev-overlay/internal/components/Dialog"; - -const CandUSampleOfAzmayesh = ({ - sampleInfo, - mutate, - rowId, - openSampleDialog, - setOpenSampleDialog, - defaultValues, - setDefaultValues, - isUpdate, - azmayesh_id, -}) => { - const requestServer = useRequest({ notificationSuccess: true }); - const [isSubmitting, setIsSubmitting] = useState(false); - - const handleSubmit = () => { - const data = {}; - setIsSubmitting(true); - const formData = new FormData(); - formData.append("azmayesh_id", isUpdate ? azmayesh_id : rowId); - Object.entries(defaultValues).forEach(([key, value]) => { - data[key] = value; - }); - formData.append("data", JSON.stringify(data)); - requestServer(isUpdate ? `${UPDATE_SAMPLE_OF_AZMAYESH}/${rowId}` : `${ADD_SAMPLE_TO_AZMAYESH}`, "post", { - data: formData, - }) - .then(() => { - mutate(); - }) - .catch(() => {}) - .finally(() => { - setOpenSampleDialog(false); - setIsSubmitting(false); - }); - }; - - return ( - - - {isUpdate ? "ویرایش نمونه" : "افزودن نمونه"} - - - - - - - - - - ); -}; -export default CandUSampleOfAzmayesh; +import { Button, Dialog, DialogActions, DialogContent, DialogTitle } from "@mui/material"; +import useRequest from "@/lib/hooks/useRequest"; +import React, { useState } from "react"; +import { ADD_SAMPLE_TO_AZMAYESH, UPDATE_SAMPLE_OF_AZMAYESH } from "@/core/utils/routes"; +import FormMaker from "@/core/components/FormMaker"; +import { DialogHeader } from "next/dist/client/components/react-dev-overlay/internal/components/Dialog"; + +const CandUSampleOfAzmayesh = ({ + sampleInfo, + mutate, + rowId, + openSampleDialog, + setOpenSampleDialog, + defaultValues, + setDefaultValues, + isUpdate, + azmayesh_id, +}) => { + const requestServer = useRequest({ notificationSuccess: true }); + const [isSubmitting, setIsSubmitting] = useState(false); + + const handleSubmit = () => { + const data = {}; + setIsSubmitting(true); + const formData = new FormData(); + formData.append("azmayesh_id", isUpdate ? azmayesh_id : rowId); + Object.entries(defaultValues).forEach(([key, value]) => { + data[key] = value; + }); + formData.append("data", JSON.stringify(data)); + requestServer(isUpdate ? `${UPDATE_SAMPLE_OF_AZMAYESH}/${rowId}` : `${ADD_SAMPLE_TO_AZMAYESH}`, "post", { + data: formData, + }) + .then(() => { + mutate(); + }) + .catch(() => {}) + .finally(() => { + setOpenSampleDialog(false); + setIsSubmitting(false); + }); + }; + + return ( + + + {isUpdate ? "ویرایش نمونه" : "افزودن نمونه"} + + + + + + + + + + ); +}; +export default CandUSampleOfAzmayesh; diff --git a/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/RowActions/DeleteSample.jsx b/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/RowActions/DeleteSample.jsx index b382fa1..14d69f6 100644 --- a/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/RowActions/DeleteSample.jsx +++ b/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/RowActions/DeleteSample.jsx @@ -1,78 +1,78 @@ -import { - Button, - Dialog, - DialogActions, - DialogContent, - DialogTitle, - IconButton, - Tooltip, - Typography, -} from "@mui/material"; -import { useState } from "react"; -import useRequest from "@/lib/hooks/useRequest"; -import DeleteIcon from "@mui/icons-material/Delete"; -import { DELETE_SAMPLE_LIST } from "@/core/utils/routes"; - -const DeleteSample = ({ rowId, mutate }) => { - const requestServer = useRequest({ notificationSuccess: true }); - const [openDeleteDialog, setOpenDeleteDialog] = useState(false); - const [isSubmitting, setIsSubmitting] = useState(false); - - const handleSubmit = () => { - setIsSubmitting(true); - requestServer(`${DELETE_SAMPLE_LIST}/${rowId}`, "post") - .then(() => { - setOpenDeleteDialog(false); - mutate(); - }) - .catch(() => {}) - .finally(() => { - setIsSubmitting(false); - }); - }; - - return ( - <> - - { - setOpenDeleteDialog(true); - }} - > - - - - - حذف نمونه - - آیا از حذف این نمونه مطمئن هستید؟ - - - - - - - - ); -}; -export default DeleteSample; +import { + Button, + Dialog, + DialogActions, + DialogContent, + DialogTitle, + IconButton, + Tooltip, + Typography, +} from "@mui/material"; +import { useState } from "react"; +import useRequest from "@/lib/hooks/useRequest"; +import DeleteIcon from "@mui/icons-material/Delete"; +import { DELETE_SAMPLE_LIST } from "@/core/utils/routes"; + +const DeleteSample = ({ rowId, mutate }) => { + const requestServer = useRequest({ notificationSuccess: true }); + const [openDeleteDialog, setOpenDeleteDialog] = useState(false); + const [isSubmitting, setIsSubmitting] = useState(false); + + const handleSubmit = () => { + setIsSubmitting(true); + requestServer(`${DELETE_SAMPLE_LIST}/${rowId}`, "post") + .then(() => { + setOpenDeleteDialog(false); + mutate(); + }) + .catch(() => {}) + .finally(() => { + setIsSubmitting(false); + }); + }; + + return ( + <> + + { + setOpenDeleteDialog(true); + }} + > + + + + + حذف نمونه + + آیا از حذف این نمونه مطمئن هستید؟ + + + + + + + + ); +}; +export default DeleteSample; diff --git a/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/RowActions/UpdateSample.jsx b/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/RowActions/UpdateSample.jsx index 3516f47..2cf2b02 100644 --- a/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/RowActions/UpdateSample.jsx +++ b/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/RowActions/UpdateSample.jsx @@ -1,60 +1,60 @@ -import { IconButton, Tooltip } from "@mui/material"; -import useRequest from "@/lib/hooks/useRequest"; -import { useEffect, useState } from "react"; -import { GET_AZMAYESH_SAMPLE_FIELDS, GET_SAMPLE_LIST } from "@/core/utils/routes"; -import CandUSampleOfAzmayesh from "@/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/Forms/CandUSampleOfAzmayesh"; -import EditIcon from "@mui/icons-material/Edit"; - -const UpdateSample = ({ azmayeshTypeId, mutate, rowId, azmayesh_id }) => { - const requestServer = useRequest(); - const [sampleInfo, setSampleInfo] = useState(null); - const [openUpdateSampleDialog, setOpenUpdateSampleDialog] = useState(false); - const [defaultValues, setDefaultValues] = useState({}); - const [sampleDetail, setSampleDetail] = useState({}); - - const handleGetFields = () => { - requestServer(`${GET_AZMAYESH_SAMPLE_FIELDS}/${azmayeshTypeId}`, "get") - .then((response) => { - setSampleInfo(response.data.data); - }) - .catch(() => {}); - requestServer(`${GET_SAMPLE_LIST}/${rowId}`, "get") - .then((response) => { - setSampleDetail(JSON.parse(response.data.data.data)); - }) - .catch(() => {}) - .finally(() => { - setOpenUpdateSampleDialog(true); - }); - }; - - useEffect(() => { - setDefaultValues(sampleDetail); - }, [sampleDetail]); - - return ( - <> - - - - - - - - ); -}; -export default UpdateSample; +import { IconButton, Tooltip } from "@mui/material"; +import useRequest from "@/lib/hooks/useRequest"; +import { useEffect, useState } from "react"; +import { GET_AZMAYESH_SAMPLE_FIELDS, GET_SAMPLE_LIST } from "@/core/utils/routes"; +import CandUSampleOfAzmayesh from "@/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/Forms/CandUSampleOfAzmayesh"; +import EditIcon from "@mui/icons-material/Edit"; + +const UpdateSample = ({ azmayeshTypeId, mutate, rowId, azmayesh_id }) => { + const requestServer = useRequest(); + const [sampleInfo, setSampleInfo] = useState(null); + const [openUpdateSampleDialog, setOpenUpdateSampleDialog] = useState(false); + const [defaultValues, setDefaultValues] = useState({}); + const [sampleDetail, setSampleDetail] = useState({}); + + const handleGetFields = () => { + requestServer(`${GET_AZMAYESH_SAMPLE_FIELDS}/${azmayeshTypeId}`, "get") + .then((response) => { + setSampleInfo(response.data.data); + }) + .catch(() => {}); + requestServer(`${GET_SAMPLE_LIST}/${rowId}`, "get") + .then((response) => { + setSampleDetail(JSON.parse(response.data.data.data)); + }) + .catch(() => {}) + .finally(() => { + setOpenUpdateSampleDialog(true); + }); + }; + + useEffect(() => { + setDefaultValues(sampleDetail); + }, [sampleDetail]); + + return ( + <> + + + + + + + + ); +}; +export default UpdateSample; diff --git a/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/RowActions/index.jsx b/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/RowActions/index.jsx index 5770586..87bf5ae 100644 --- a/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/RowActions/index.jsx +++ b/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/RowActions/index.jsx @@ -1,18 +1,18 @@ -import { Box } from "@mui/material"; -import DeleteSample from "./DeleteSample"; -import UpdateSample from "./UpdateSample"; - -const RowActions = ({ rowData, row, mutate }) => { - return ( - - - - - ); -}; -export default RowActions; +import { Box } from "@mui/material"; +import DeleteSample from "./DeleteSample"; +import UpdateSample from "./UpdateSample"; + +const RowActions = ({ rowData, row, mutate }) => { + return ( + + + + + ); +}; +export default RowActions; diff --git a/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/ShowSampleList.jsx b/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/ShowSampleList.jsx index e55d9ab..fa9c21d 100644 --- a/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/ShowSampleList.jsx +++ b/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/ShowSampleList.jsx @@ -1,80 +1,80 @@ -import { useMemo } from "react"; -import { Box, Typography } from "@mui/material"; -import DataTableWithAuth from "@/core/components/DataTableWithAuth"; -import { GET_SAMPLE_LIST } from "@/core/utils/routes"; -import RowActions from "./RowActions"; -import AzmayeshInfo from "@/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/AzmayeshInfo"; -import Toolbar from "./Toolbar"; -import moment from "jalali-moment"; - -const ShowSampleList = ({ sampleInfo, rowData }) => { - const parsedData = (data) => { - return data.data.map((item) => ({ - ...JSON.parse(item.data), - id: item.id, - updated_at: item.updated_at, - })); - }; - - const columns = useMemo( - () => [ - { - accessorKey: "id", - header: "کد یکتا", - id: "id", - enableColumnFilter: false, - datatype: "text", - grow: false, - size: 100, - }, - ...sampleInfo.map((item) => ({ - accessorKey: item.id.toString(), - header: item.unit ? `${item.name} (${item.unit})` : item.name, - id: item.id.toString(), - enableColumnFilter: false, - datatype: "text", - })), - { - accessorKey: "updated_at", - header: "تاریخ بروزرسانی", - id: "updated_at", - enableColumnFilter: false, - datatype: "date", - grow: false, - size: 100, - Cell: ({ renderedCellValue }) => ( - - {renderedCellValue ? moment(renderedCellValue).locale("fa").format("HH:mm | YYYY/MM/DD") : "-"} - - ), - }, - ], - [sampleInfo] - ); - - const ToolbarWithRowData = (props) => ; - const RowActionsWithRowData = (props) => ; - - return ( - - - - - - - ); -}; - -export default ShowSampleList; +import { useMemo } from "react"; +import { Box, Typography } from "@mui/material"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import { GET_SAMPLE_LIST } from "@/core/utils/routes"; +import RowActions from "./RowActions"; +import AzmayeshInfo from "@/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/AzmayeshInfo"; +import Toolbar from "./Toolbar"; +import moment from "jalali-moment"; + +const ShowSampleList = ({ sampleInfo, rowData }) => { + const parsedData = (data) => { + return data.data.map((item) => ({ + ...JSON.parse(item.data), + id: item.id, + updated_at: item.updated_at, + })); + }; + + const columns = useMemo( + () => [ + { + accessorKey: "id", + header: "کد یکتا", + id: "id", + enableColumnFilter: false, + datatype: "text", + grow: false, + size: 100, + }, + ...sampleInfo.map((item) => ({ + accessorKey: item.id.toString(), + header: item.unit ? `${item.name} (${item.unit})` : item.name, + id: item.id.toString(), + enableColumnFilter: false, + datatype: "text", + })), + { + accessorKey: "updated_at", + header: "تاریخ بروزرسانی", + id: "updated_at", + enableColumnFilter: false, + datatype: "date", + grow: false, + size: 100, + Cell: ({ renderedCellValue }) => ( + + {renderedCellValue ? moment(renderedCellValue).locale("fa").format("HH:mm | YYYY/MM/DD") : "-"} + + ), + }, + ], + [sampleInfo] + ); + + const ToolbarWithRowData = (props) => ; + const RowActionsWithRowData = (props) => ; + + return ( + + + + + + + ); +}; + +export default ShowSampleList; diff --git a/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/Toolbar.jsx b/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/Toolbar.jsx index 53e3eb3..efffe36 100644 --- a/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/Toolbar.jsx +++ b/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/Toolbar.jsx @@ -1,10 +1,10 @@ -import AddSampleToAzmayesh from "./Actions/Create"; - -const Toolbar = ({ mutate, rowData }) => { - return ( - <> - - - ); -}; -export default Toolbar; +import AddSampleToAzmayesh from "./Actions/Create"; + +const Toolbar = ({ mutate, rowData }) => { + return ( + <> + + + ); +}; +export default Toolbar; diff --git a/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/index.jsx b/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/index.jsx index a3ba7e9..a688bcf 100644 --- a/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/index.jsx +++ b/src/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh/index.jsx @@ -1,46 +1,46 @@ -import { Box, Button, Dialog, DialogActions, DialogContent, IconButton, Tooltip } from "@mui/material"; -import AssignmentIcon from "@mui/icons-material/Assignment"; -import { useState } from "react"; -import ShowSampleList from "./ShowSampleList"; -import { GET_AZMAYESH_SAMPLE_FIELDS } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; - -const ShowSampleOfAzmayesh = ({ rowData }) => { - const requestServer = useRequest(); - const [openShowSampleDialog, setOpenShowSampleDialog] = useState(false); - const [sampleInfo, setSampleInfo] = useState(null); - const handleGetSampleFields = () => { - requestServer(`${GET_AZMAYESH_SAMPLE_FIELDS}/${rowData.azmayesh_type_id}`, "get") - .then((response) => { - setSampleInfo(response.data.data); - }) - .catch(() => {}) - .finally(() => { - setOpenShowSampleDialog(true); - }); - }; - return ( - - - - - - - - - - - - - - - - ); -}; -export default ShowSampleOfAzmayesh; +import { Box, Button, Dialog, DialogActions, DialogContent, IconButton, Tooltip } from "@mui/material"; +import AssignmentIcon from "@mui/icons-material/Assignment"; +import { useState } from "react"; +import ShowSampleList from "./ShowSampleList"; +import { GET_AZMAYESH_SAMPLE_FIELDS } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; + +const ShowSampleOfAzmayesh = ({ rowData }) => { + const requestServer = useRequest(); + const [openShowSampleDialog, setOpenShowSampleDialog] = useState(false); + const [sampleInfo, setSampleInfo] = useState(null); + const handleGetSampleFields = () => { + requestServer(`${GET_AZMAYESH_SAMPLE_FIELDS}/${rowData.azmayesh_type_id}`, "get") + .then((response) => { + setSampleInfo(response.data.data); + }) + .catch(() => {}) + .finally(() => { + setOpenShowSampleDialog(true); + }); + }; + return ( + + + + + + + + + + + + + + + + ); +}; +export default ShowSampleOfAzmayesh; diff --git a/src/components/dashboard/azmayesh/RowActions/index.jsx b/src/components/dashboard/azmayesh/RowActions/index.jsx index 7f6440d..839f579 100644 --- a/src/components/dashboard/azmayesh/RowActions/index.jsx +++ b/src/components/dashboard/azmayesh/RowActions/index.jsx @@ -1,14 +1,14 @@ -import { Box } from "@mui/material"; -import DeleteAzmayesh from "./DeleteAzmayesh"; -import ShowSampleOfAzmayesh from "@/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh"; -import AzmayeshUpdate from "@/components/dashboard/azmayesh/RowActions/AzmayeshUpdate"; - -const RowActions = ({ row, mutate }) => { - return ( - - - - - ); -}; -export default RowActions; +import { Box } from "@mui/material"; +import DeleteAzmayesh from "./DeleteAzmayesh"; +import ShowSampleOfAzmayesh from "@/components/dashboard/azmayesh/RowActions/ShowSampleOfAzmayesh"; +import AzmayeshUpdate from "@/components/dashboard/azmayesh/RowActions/AzmayeshUpdate"; + +const RowActions = ({ row, mutate }) => { + return ( + + + + + ); +}; +export default RowActions; diff --git a/src/components/dashboard/azmayesh/ShowLocation/index.jsx b/src/components/dashboard/azmayesh/ShowLocation/index.jsx index 3289871..09652d7 100644 --- a/src/components/dashboard/azmayesh/ShowLocation/index.jsx +++ b/src/components/dashboard/azmayesh/ShowLocation/index.jsx @@ -1,52 +1,52 @@ -"use client"; - -import ExploreIcon from "@mui/icons-material/Explore"; -import { Box, Button, Dialog, DialogActions, DialogContent, IconButton } from "@mui/material"; -import { useState } from "react"; -import dynamic from "next/dynamic"; -import MapLoading from "@/core/components/MapLayer/Loading"; -import ShowLocationMarker from "@/core/components/ShowLocationMarker"; - -const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { - loading: () => , - ssr: false, -}); - -const ShowLocation = ({ lat, lng }) => { - const [openShowLocationModal, setOpenShowLocationModal] = useState(false); - - const handleOpenShowLocationModal = () => { - setOpenShowLocationModal(true); - }; - - const handleCloseShowLocationModal = () => { - setOpenShowLocationModal(false); - }; - - return ( - - - - - - - - - - - - - - - - - - ); -}; -export default ShowLocation; +"use client"; + +import ExploreIcon from "@mui/icons-material/Explore"; +import { Box, Button, Dialog, DialogActions, DialogContent, IconButton } from "@mui/material"; +import { useState } from "react"; +import dynamic from "next/dynamic"; +import MapLoading from "@/core/components/MapLayer/Loading"; +import ShowLocationMarker from "@/core/components/ShowLocationMarker"; + +const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { + loading: () => , + ssr: false, +}); + +const ShowLocation = ({ lat, lng }) => { + const [openShowLocationModal, setOpenShowLocationModal] = useState(false); + + const handleOpenShowLocationModal = () => { + setOpenShowLocationModal(true); + }; + + const handleCloseShowLocationModal = () => { + setOpenShowLocationModal(false); + }; + + return ( + + + + + + + + + + + + + + + + + + ); +}; +export default ShowLocation; diff --git a/src/components/dashboard/azmayesh/Toolbar.jsx b/src/components/dashboard/azmayesh/Toolbar.jsx index 0ba00a9..e976198 100644 --- a/src/components/dashboard/azmayesh/Toolbar.jsx +++ b/src/components/dashboard/azmayesh/Toolbar.jsx @@ -1,10 +1,10 @@ -import AzmayeshCreate from "./Actions/Create"; - -const Toolbar = ({ mutate }) => { - return ( - <> - - - ); -}; -export default Toolbar; +import AzmayeshCreate from "./Actions/Create"; + +const Toolbar = ({ mutate }) => { + return ( + <> + + + ); +}; +export default Toolbar; diff --git a/src/components/dashboard/azmayesh/index.jsx b/src/components/dashboard/azmayesh/index.jsx index 1b142c2..ec9e5e2 100644 --- a/src/components/dashboard/azmayesh/index.jsx +++ b/src/components/dashboard/azmayesh/index.jsx @@ -1,15 +1,15 @@ -"use client"; - -import PageTitle from "@/core/components/PageTitle"; -import { Stack } from "@mui/material"; -import AzmayeshList from "./AzmayeshList"; - -const AzmayeshPage = () => { - return ( - - - - - ); -}; -export default AzmayeshPage; +"use client"; + +import PageTitle from "@/core/components/PageTitle"; +import { Stack } from "@mui/material"; +import AzmayeshList from "./AzmayeshList"; + +const AzmayeshPage = () => { + return ( + + + + + ); +}; +export default AzmayeshPage; diff --git a/src/components/dashboard/azmayeshType/Actions/Create/index.jsx b/src/components/dashboard/azmayeshType/Actions/Create/index.jsx index 3605ffc..ecb44e4 100644 --- a/src/components/dashboard/azmayeshType/Actions/Create/index.jsx +++ b/src/components/dashboard/azmayeshType/Actions/Create/index.jsx @@ -1,33 +1,33 @@ -"use client"; - -import { Button, IconButton, useMediaQuery } from "@mui/material"; -import { useTheme } from "@emotion/react"; -import { useState } from "react"; -import { AddCircle } from "@mui/icons-material"; -import CandUAzmayeshType from "@/components/dashboard/azmayeshType/Forms/CandUAzmayeshType"; - -const AzmayeshTypeCreate = ({ mutate }) => { - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const [open, setOpen] = useState(false); - - const handleOpen = () => { - setOpen(true); - }; - - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - {open && } - - ); -}; -export default AzmayeshTypeCreate; +"use client"; + +import { Button, IconButton, useMediaQuery } from "@mui/material"; +import { useTheme } from "@emotion/react"; +import { useState } from "react"; +import { AddCircle } from "@mui/icons-material"; +import CandUAzmayeshType from "@/components/dashboard/azmayeshType/Forms/CandUAzmayeshType"; + +const AzmayeshTypeCreate = ({ mutate }) => { + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const [open, setOpen] = useState(false); + + const handleOpen = () => { + setOpen(true); + }; + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + {open && } + + ); +}; +export default AzmayeshTypeCreate; diff --git a/src/components/dashboard/azmayeshType/AzmayeshTypeList.jsx b/src/components/dashboard/azmayeshType/AzmayeshTypeList.jsx index 8aa0f4b..397066f 100644 --- a/src/components/dashboard/azmayeshType/AzmayeshTypeList.jsx +++ b/src/components/dashboard/azmayeshType/AzmayeshTypeList.jsx @@ -1,65 +1,65 @@ -"use client"; - -import { useMemo } from "react"; -import { Box, Typography } from "@mui/material"; -import DataTableWithAuth from "@/core/components/DataTableWithAuth"; -import Toolbar from "./Toolbar"; -import { GET_AZMAYESH_TYPE_LIST_TABLE } from "@/core/utils/routes"; -import moment from "jalali-moment"; -import RowActions from "./RowActions"; - -const AzmayeshTypeList = () => { - const columns = useMemo( - () => [ - { - accessorKey: "id", - header: "کد یکتا", - id: "id", - enableColumnFilter: false, - datatype: "text", - filterMode: "notEquals", - }, - { - accessorKey: "name", - header: "عنوان", - id: "name", - enableColumnFilter: false, - datatype: "text", - filterMode: "notEquals", - }, - { - accessorKey: "updated_at", - header: "تاریخ بروزرسانی", - id: "updated_at", - enableColumnFilter: false, - datatype: "date", - filterMode: "equals", - Cell: ({ renderedCellValue }) => ( - - {renderedCellValue ? moment(renderedCellValue).locale("fa").format("HH:mm | YYYY/MM/DD") : "-"} - - ), - }, - ], - [] - ); - - return ( - - - - ); -}; -export default AzmayeshTypeList; +"use client"; + +import { useMemo } from "react"; +import { Box, Typography } from "@mui/material"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import Toolbar from "./Toolbar"; +import { GET_AZMAYESH_TYPE_LIST_TABLE } from "@/core/utils/routes"; +import moment from "jalali-moment"; +import RowActions from "./RowActions"; + +const AzmayeshTypeList = () => { + const columns = useMemo( + () => [ + { + accessorKey: "id", + header: "کد یکتا", + id: "id", + enableColumnFilter: false, + datatype: "text", + filterMode: "notEquals", + }, + { + accessorKey: "name", + header: "عنوان", + id: "name", + enableColumnFilter: false, + datatype: "text", + filterMode: "notEquals", + }, + { + accessorKey: "updated_at", + header: "تاریخ بروزرسانی", + id: "updated_at", + enableColumnFilter: false, + datatype: "date", + filterMode: "equals", + Cell: ({ renderedCellValue }) => ( + + {renderedCellValue ? moment(renderedCellValue).locale("fa").format("HH:mm | YYYY/MM/DD") : "-"} + + ), + }, + ], + [] + ); + + return ( + + + + ); +}; +export default AzmayeshTypeList; diff --git a/src/components/dashboard/azmayeshType/Forms/CandUAzmayeshType/AzmayeshFields.jsx b/src/components/dashboard/azmayeshType/Forms/CandUAzmayeshType/AzmayeshFields.jsx index 4cd365f..69b950f 100644 --- a/src/components/dashboard/azmayeshType/Forms/CandUAzmayeshType/AzmayeshFields.jsx +++ b/src/components/dashboard/azmayeshType/Forms/CandUAzmayeshType/AzmayeshFields.jsx @@ -1,181 +1,181 @@ -"use client"; - -import React, { useEffect, useState } from "react"; -import { - Button, - Chip, - FormControl, - FormHelperText, - Grid, - InputAdornment, - InputLabel, - MenuItem, - OutlinedInput, - Select, - Typography, -} from "@mui/material"; -import ExtensionIcon from "@mui/icons-material/Extension"; -import SelectItemBox from "@/components/dashboard/azmayeshType/Forms/CandUAzmayeshType/SelectItemBox"; -import KeyboardIcon from "@mui/icons-material/Keyboard"; -import TextFieldsIcon from "@mui/icons-material/TextFields"; -import ViewListIcon from "@mui/icons-material/ViewList"; -import CalendarMonthIcon from "@mui/icons-material/CalendarMonth"; - -const fieldTypeList = [ - { value: "input", label: "متن", icon: }, - { value: "select", label: "انتخابی", icon: }, - { value: "date", label: "تاریخ", icon: }, -]; - -const AzmayeshFields = ({ errors, selectedListItem, register, setValue, fields, watch }) => { - const watchedFields = watch("fields"); - const [isSelectType, setIsSelectType] = useState(false); - const [openSelectItem, setOpenSelectItem] = useState(false); - const [typeIcon, setTypeIcon] = useState(); - - useEffect(() => { - const selectedIcon = fieldTypeList.find((option) => option.value === watchedFields?.[selectedListItem]?.type) - ?.icon || ; - setTypeIcon(selectedIcon); - setIsSelectType(watchedFields[selectedListItem]?.type === "select"); - }, [watchedFields, selectedListItem]); - - return ( - - - - نوع - - {errors.fields?.[selectedListItem]?.type?.message} - - - {isSelectType && ( - - - - - {errors.fields?.[selectedListItem]?.options?.message} - - {openSelectItem && ( - - )} - - )} - - - نام فیلد - setValue(`fields.${selectedListItem}.name`, event.target.value)} - size="small" - fullWidth - type="text" - /> - - {errors.fields?.[selectedListItem]?.name ? errors.fields[selectedListItem].name.message : null} - - - - - - واحد اندازه گیری - setValue(`fields.${selectedListItem}.unit`, event.target.value)} - size="small" - fullWidth - type="text" - /> - - {errors.fields?.[selectedListItem]?.unit ? errors.fields[selectedListItem].unit.message : null} - - - - - ); -}; -export default AzmayeshFields; +"use client"; + +import React, { useEffect, useState } from "react"; +import { + Button, + Chip, + FormControl, + FormHelperText, + Grid, + InputAdornment, + InputLabel, + MenuItem, + OutlinedInput, + Select, + Typography, +} from "@mui/material"; +import ExtensionIcon from "@mui/icons-material/Extension"; +import SelectItemBox from "@/components/dashboard/azmayeshType/Forms/CandUAzmayeshType/SelectItemBox"; +import KeyboardIcon from "@mui/icons-material/Keyboard"; +import TextFieldsIcon from "@mui/icons-material/TextFields"; +import ViewListIcon from "@mui/icons-material/ViewList"; +import CalendarMonthIcon from "@mui/icons-material/CalendarMonth"; + +const fieldTypeList = [ + { value: "input", label: "متن", icon: }, + { value: "select", label: "انتخابی", icon: }, + { value: "date", label: "تاریخ", icon: }, +]; + +const AzmayeshFields = ({ errors, selectedListItem, register, setValue, fields, watch }) => { + const watchedFields = watch("fields"); + const [isSelectType, setIsSelectType] = useState(false); + const [openSelectItem, setOpenSelectItem] = useState(false); + const [typeIcon, setTypeIcon] = useState(); + + useEffect(() => { + const selectedIcon = fieldTypeList.find((option) => option.value === watchedFields?.[selectedListItem]?.type) + ?.icon || ; + setTypeIcon(selectedIcon); + setIsSelectType(watchedFields[selectedListItem]?.type === "select"); + }, [watchedFields, selectedListItem]); + + return ( + + + + نوع + + {errors.fields?.[selectedListItem]?.type?.message} + + + {isSelectType && ( + + + + + {errors.fields?.[selectedListItem]?.options?.message} + + {openSelectItem && ( + + )} + + )} + + + نام فیلد + setValue(`fields.${selectedListItem}.name`, event.target.value)} + size="small" + fullWidth + type="text" + /> + + {errors.fields?.[selectedListItem]?.name ? errors.fields[selectedListItem].name.message : null} + + + + + + واحد اندازه گیری + setValue(`fields.${selectedListItem}.unit`, event.target.value)} + size="small" + fullWidth + type="text" + /> + + {errors.fields?.[selectedListItem]?.unit ? errors.fields[selectedListItem].unit.message : null} + + + + + ); +}; +export default AzmayeshFields; diff --git a/src/components/dashboard/azmayeshType/Forms/CandUAzmayeshType/FormAndRequest.jsx b/src/components/dashboard/azmayeshType/Forms/CandUAzmayeshType/FormAndRequest.jsx index 467fc91..271ee1d 100644 --- a/src/components/dashboard/azmayeshType/Forms/CandUAzmayeshType/FormAndRequest.jsx +++ b/src/components/dashboard/azmayeshType/Forms/CandUAzmayeshType/FormAndRequest.jsx @@ -1,218 +1,218 @@ -import { - Box, - Button, - Chip, - DialogActions, - DialogContent, - Divider, - FormControl, - FormHelperText, - Grid, - InputLabel, - List, - OutlinedInput, - Typography, -} from "@mui/material"; -import StyledForm from "@/core/components/StyledForm"; -import useRequest from "@/lib/hooks/useRequest"; -import { useState } from "react"; -import { useFieldArray, useForm } from "react-hook-form"; -import { array, object, string } from "yup"; -import { yupResolver } from "@hookform/resolvers/yup"; -import DataSaverOnIcon from "@mui/icons-material/DataSaverOn"; -import ListItems from "./ListItems"; -import AzmayeshFields from "./AzmayeshFields"; -import { ADD_AZMAYESH_TYPE, UPDATE_AZMAYESH_TYPE } from "@/core/utils/routes"; - -const validationSchema = object({ - name: string().required("عنوان نوع آزمایش را مشخص کنید!"), - fields: array() - .of( - object({ - name: string().required("نام فیلد الزامی است"), - type: string().required("نوع فیلد الزامی است"), - options: array().when("type", { - is: "select", - then: (schema) => schema.min(1, "حداقل باید یک آیتم برای نوع انتخابی ایجاد کنید."), - otherwise: (schema) => schema.notRequired(), - }), - }) - ) - .min(1, "حداقل باید یک فیلد ایجاد نمایید."), -}); - -const FormAndRequest = ({ setOpen, mutate, rowId, updateInfo }) => { - const requestServer = useRequest({ notificationSuccess: true }); - const [selectedListItem, setSelectedListItem] = useState(null); - - const handleClose = () => { - setOpen(false); - }; - - const defaultValues = { - name: updateInfo?.name || "", - fields: Array.isArray(updateInfo?.azmayesh_fields) - ? updateInfo.azmayesh_fields.map((field) => ({ - name: field.name || "", - type: field.type || "", - unit: field.unit || "", - options: field.option ? field.option : [], - })) - : [], - }; - - const { - control, - register, - handleSubmit, - setValue, - watch, - formState: { errors, isSubmitting }, - } = useForm({ defaultValues, resolver: yupResolver(validationSchema), mode: "all" }); - - const { fields, append, remove } = useFieldArray({ - control, - name: "fields", - }); - - const handleRemove = (index) => { - remove(index); - if (selectedListItem === index) { - setSelectedListItem(null); - } else if (selectedListItem > index) { - setSelectedListItem((prev) => prev - 1); - } - }; - - const handleAddField = () => { - append({ name: "", type: "", unit: "", options: [] }); - }; - - const onSubmit = async (data) => { - const formData = new FormData(); - formData.append("name", data.name); - data.fields.map((field, index) => { - formData.append(`fields[${index}][name]`, field.name); - if (field.unit !== "") formData.append(`fields[${index}][unit]`, field.unit); - formData.append(`fields[${index}][type]`, field.type); - if (field.options.length !== 0) formData.append(`fields[${index}][option]`, JSON.stringify(field.options)); - }); - - try { - await requestServer(updateInfo ? `${UPDATE_AZMAYESH_TYPE}/${rowId}` : ADD_AZMAYESH_TYPE, "post", { - data: formData, - }); - mutate(); - handleClose(); - } catch (error) {} - }; - - return ( - - - - - عنوان نوع آزمایش - - {errors.name ? errors.name.message : null} - - - - - - - - - - {fields.length !== 0 ? ( - fields.map((item, index) => ( - - )) - ) : ( - - فیلدی وجود ندارد - - )} - - - {errors.fields ? errors.fields.message : null} - - - - - - - - {selectedListItem !== null ? ( - - ) : ( - - - از بخش لیست فیلد ها یک آیتم را انتخاب نمایید - - - )} - - - - - - - - - ); -}; - -export default FormAndRequest; +import { + Box, + Button, + Chip, + DialogActions, + DialogContent, + Divider, + FormControl, + FormHelperText, + Grid, + InputLabel, + List, + OutlinedInput, + Typography, +} from "@mui/material"; +import StyledForm from "@/core/components/StyledForm"; +import useRequest from "@/lib/hooks/useRequest"; +import { useState } from "react"; +import { useFieldArray, useForm } from "react-hook-form"; +import { array, object, string } from "yup"; +import { yupResolver } from "@hookform/resolvers/yup"; +import DataSaverOnIcon from "@mui/icons-material/DataSaverOn"; +import ListItems from "./ListItems"; +import AzmayeshFields from "./AzmayeshFields"; +import { ADD_AZMAYESH_TYPE, UPDATE_AZMAYESH_TYPE } from "@/core/utils/routes"; + +const validationSchema = object({ + name: string().required("عنوان نوع آزمایش را مشخص کنید!"), + fields: array() + .of( + object({ + name: string().required("نام فیلد الزامی است"), + type: string().required("نوع فیلد الزامی است"), + options: array().when("type", { + is: "select", + then: (schema) => schema.min(1, "حداقل باید یک آیتم برای نوع انتخابی ایجاد کنید."), + otherwise: (schema) => schema.notRequired(), + }), + }) + ) + .min(1, "حداقل باید یک فیلد ایجاد نمایید."), +}); + +const FormAndRequest = ({ setOpen, mutate, rowId, updateInfo }) => { + const requestServer = useRequest({ notificationSuccess: true }); + const [selectedListItem, setSelectedListItem] = useState(null); + + const handleClose = () => { + setOpen(false); + }; + + const defaultValues = { + name: updateInfo?.name || "", + fields: Array.isArray(updateInfo?.azmayesh_fields) + ? updateInfo.azmayesh_fields.map((field) => ({ + name: field.name || "", + type: field.type || "", + unit: field.unit || "", + options: field.option ? field.option : [], + })) + : [], + }; + + const { + control, + register, + handleSubmit, + setValue, + watch, + formState: { errors, isSubmitting }, + } = useForm({ defaultValues, resolver: yupResolver(validationSchema), mode: "all" }); + + const { fields, append, remove } = useFieldArray({ + control, + name: "fields", + }); + + const handleRemove = (index) => { + remove(index); + if (selectedListItem === index) { + setSelectedListItem(null); + } else if (selectedListItem > index) { + setSelectedListItem((prev) => prev - 1); + } + }; + + const handleAddField = () => { + append({ name: "", type: "", unit: "", options: [] }); + }; + + const onSubmit = async (data) => { + const formData = new FormData(); + formData.append("name", data.name); + data.fields.map((field, index) => { + formData.append(`fields[${index}][name]`, field.name); + if (field.unit !== "") formData.append(`fields[${index}][unit]`, field.unit); + formData.append(`fields[${index}][type]`, field.type); + if (field.options.length !== 0) formData.append(`fields[${index}][option]`, JSON.stringify(field.options)); + }); + + try { + await requestServer(updateInfo ? `${UPDATE_AZMAYESH_TYPE}/${rowId}` : ADD_AZMAYESH_TYPE, "post", { + data: formData, + }); + mutate(); + handleClose(); + } catch (error) {} + }; + + return ( + + + + + عنوان نوع آزمایش + + {errors.name ? errors.name.message : null} + + + + + + + + + + {fields.length !== 0 ? ( + fields.map((item, index) => ( + + )) + ) : ( + + فیلدی وجود ندارد + + )} + + + {errors.fields ? errors.fields.message : null} + + + + + + + + {selectedListItem !== null ? ( + + ) : ( + + + از بخش لیست فیلد ها یک آیتم را انتخاب نمایید + + + )} + + + + + + + + + ); +}; + +export default FormAndRequest; diff --git a/src/components/dashboard/azmayeshType/Forms/CandUAzmayeshType/ListItems.jsx b/src/components/dashboard/azmayeshType/Forms/CandUAzmayeshType/ListItems.jsx index 4a6005e..c92d2d6 100644 --- a/src/components/dashboard/azmayeshType/Forms/CandUAzmayeshType/ListItems.jsx +++ b/src/components/dashboard/azmayeshType/Forms/CandUAzmayeshType/ListItems.jsx @@ -1,77 +1,77 @@ -"use client"; - -import { Box, IconButton, ListItem, Stack, Typography } from "@mui/material"; -import React from "react"; -import DeleteIcon from "@mui/icons-material/Delete"; -import SettingsIcon from "@mui/icons-material/Settings"; -import TextFieldsIcon from "@mui/icons-material/TextFields"; -import ViewListIcon from "@mui/icons-material/ViewList"; -import CalendarMonthIcon from "@mui/icons-material/CalendarMonth"; - -const fieldsType = { - input: "متن", - date: "تاریخ", - select: "انتخابی", -}; -const fieldsTypeIcon = { - input: , - date: , - select: , -}; - -const ListItems = ({ index, handleRemove, selectedListItem, setSelectedListItem, watch }) => { - const watchedFields = watch("fields"); - return ( - - setSelectedListItem(index)} - > - - - handleRemove(index)}> - - - - } - > - - - {watchedFields[index].name !== "" ? watchedFields[index].name : "نام تعیین نشده"} - - - {fieldsTypeIcon[watchedFields[index].type] || null} - - {watchedFields[index].type !== "" ? fieldsType[watchedFields[index].type] : "واحد تعیین نشده"} - - - - - ); -}; -export default ListItems; +"use client"; + +import { Box, IconButton, ListItem, Stack, Typography } from "@mui/material"; +import React from "react"; +import DeleteIcon from "@mui/icons-material/Delete"; +import SettingsIcon from "@mui/icons-material/Settings"; +import TextFieldsIcon from "@mui/icons-material/TextFields"; +import ViewListIcon from "@mui/icons-material/ViewList"; +import CalendarMonthIcon from "@mui/icons-material/CalendarMonth"; + +const fieldsType = { + input: "متن", + date: "تاریخ", + select: "انتخابی", +}; +const fieldsTypeIcon = { + input: , + date: , + select: , +}; + +const ListItems = ({ index, handleRemove, selectedListItem, setSelectedListItem, watch }) => { + const watchedFields = watch("fields"); + return ( + + setSelectedListItem(index)} + > + + + handleRemove(index)}> + + + + } + > + + + {watchedFields[index].name !== "" ? watchedFields[index].name : "نام تعیین نشده"} + + + {fieldsTypeIcon[watchedFields[index].type] || null} + + {watchedFields[index].type !== "" ? fieldsType[watchedFields[index].type] : "واحد تعیین نشده"} + + + + + ); +}; +export default ListItems; diff --git a/src/components/dashboard/azmayeshType/Forms/CandUAzmayeshType/SelectItemBox.jsx b/src/components/dashboard/azmayeshType/Forms/CandUAzmayeshType/SelectItemBox.jsx index 888be19..5548278 100644 --- a/src/components/dashboard/azmayeshType/Forms/CandUAzmayeshType/SelectItemBox.jsx +++ b/src/components/dashboard/azmayeshType/Forms/CandUAzmayeshType/SelectItemBox.jsx @@ -1,108 +1,108 @@ -import { - Box, - Button, - Chip, - Dialog, - DialogActions, - DialogContent, - Divider, - IconButton, - List, - ListItem, - ListItemText, - TextField, - Typography, -} from "@mui/material"; -import DeleteIcon from "@mui/icons-material/Delete"; -import React, { useState } from "react"; - -const SelectItemBox = ({ open, setOpen, setValue, index, watch }) => { - const watchedFields = watch("fields"); - const [itemValue, setItemValue] = useState(""); - const [listArr, setListArr] = useState(watchedFields?.[index]?.options); - - const addToList = () => { - if (itemValue) { - setListArr([...listArr, itemValue]); - setItemValue(""); - } - }; - - const removeFromList = (index) => { - setListArr(listArr.filter((_, i) => i !== index)); - }; - - const saveAndCloseList = () => { - setValue(`fields.${index}.options`, listArr); - closeModal(); - }; - - const closeModal = () => { - setOpen(false); - }; - - return ( - - - - { - setItemValue(event.target.value); - }} - /> - - - - - - - - {listArr.length !== 0 ? ( - listArr.map((item, index) => ( - removeFromList(index)} - > - - - } - > - - - )) - ) : ( - - هنوز آیتمی ثبت نشده است - - )} - - - - - - - - ); -}; - -export default SelectItemBox; +import { + Box, + Button, + Chip, + Dialog, + DialogActions, + DialogContent, + Divider, + IconButton, + List, + ListItem, + ListItemText, + TextField, + Typography, +} from "@mui/material"; +import DeleteIcon from "@mui/icons-material/Delete"; +import React, { useState } from "react"; + +const SelectItemBox = ({ open, setOpen, setValue, index, watch }) => { + const watchedFields = watch("fields"); + const [itemValue, setItemValue] = useState(""); + const [listArr, setListArr] = useState(watchedFields?.[index]?.options); + + const addToList = () => { + if (itemValue) { + setListArr([...listArr, itemValue]); + setItemValue(""); + } + }; + + const removeFromList = (index) => { + setListArr(listArr.filter((_, i) => i !== index)); + }; + + const saveAndCloseList = () => { + setValue(`fields.${index}.options`, listArr); + closeModal(); + }; + + const closeModal = () => { + setOpen(false); + }; + + return ( + + + + { + setItemValue(event.target.value); + }} + /> + + + + + + + + {listArr.length !== 0 ? ( + listArr.map((item, index) => ( + removeFromList(index)} + > + + + } + > + + + )) + ) : ( + + هنوز آیتمی ثبت نشده است + + )} + + + + + + + + ); +}; + +export default SelectItemBox; diff --git a/src/components/dashboard/azmayeshType/Forms/CandUAzmayeshType/index.jsx b/src/components/dashboard/azmayeshType/Forms/CandUAzmayeshType/index.jsx index 8808894..6f2fac5 100644 --- a/src/components/dashboard/azmayeshType/Forms/CandUAzmayeshType/index.jsx +++ b/src/components/dashboard/azmayeshType/Forms/CandUAzmayeshType/index.jsx @@ -1,37 +1,37 @@ -import { Dialog, IconButton } from "@mui/material"; -import FormAndRequest from "./FormAndRequest"; -import DialogLoading from "@/core/components/DialogLoading"; -import CloseIcon from "@mui/icons-material/Close"; - -const CandUAzmayeshType = ({ open, setOpen, mutate, rowId, updateInfo, loadingOpen, fromUpdate = false }) => { - const isUpdateReady = fromUpdate ? updateInfo !== null : true; - return ( - - setOpen(false)} - sx={(theme) => ({ - position: "absolute", - right: 8, - top: 8, - zIndex: 50, - color: theme.palette.grey[500], - })} - > - - - {isUpdateReady ? ( - - ) : ( - - )} - - ); -}; - -export default CandUAzmayeshType; +import { Dialog, IconButton } from "@mui/material"; +import FormAndRequest from "./FormAndRequest"; +import DialogLoading from "@/core/components/DialogLoading"; +import CloseIcon from "@mui/icons-material/Close"; + +const CandUAzmayeshType = ({ open, setOpen, mutate, rowId, updateInfo, loadingOpen, fromUpdate = false }) => { + const isUpdateReady = fromUpdate ? updateInfo !== null : true; + return ( + + setOpen(false)} + sx={(theme) => ({ + position: "absolute", + right: 8, + top: 8, + zIndex: 50, + color: theme.palette.grey[500], + })} + > + + + {isUpdateReady ? ( + + ) : ( + + )} + + ); +}; + +export default CandUAzmayeshType; diff --git a/src/components/dashboard/azmayeshType/RowActions/DeleteAzmayeshType/index.jsx b/src/components/dashboard/azmayeshType/RowActions/DeleteAzmayeshType/index.jsx index 78d400d..a16b349 100644 --- a/src/components/dashboard/azmayeshType/RowActions/DeleteAzmayeshType/index.jsx +++ b/src/components/dashboard/azmayeshType/RowActions/DeleteAzmayeshType/index.jsx @@ -1,78 +1,78 @@ -import { - Button, - Dialog, - DialogActions, - DialogContent, - DialogTitle, - IconButton, - Tooltip, - Typography, -} from "@mui/material"; -import DeleteIcon from "@mui/icons-material/Delete"; -import useRequest from "@/lib/hooks/useRequest"; -import { useState } from "react"; -import { DELETE_AZMAYESH_TYPE_LIST } from "@/core/utils/routes"; - -const DeleteAzmayeshType = ({ rowId, mutate }) => { - const requestServer = useRequest({ notificationSuccess: true }); - const [openDeleteDialog, setOpenDeleteDialog] = useState(false); - const [isSubmitting, setIsSubmitting] = useState(false); - - const handleSubmit = () => { - setIsSubmitting(true); - requestServer(`${DELETE_AZMAYESH_TYPE_LIST}/${rowId}`, "post") - .then(() => { - setOpenDeleteDialog(false); - mutate(); - }) - .catch(() => {}) - .finally(() => { - setIsSubmitting(false); - }); - }; - - return ( - <> - - { - setOpenDeleteDialog(true); - }} - > - - - - - حذف نوع آزمایش - - آیا از حذف این نوع آزمایش مطمئن هستید؟ - - - - - - - - ); -}; -export default DeleteAzmayeshType; +import { + Button, + Dialog, + DialogActions, + DialogContent, + DialogTitle, + IconButton, + Tooltip, + Typography, +} from "@mui/material"; +import DeleteIcon from "@mui/icons-material/Delete"; +import useRequest from "@/lib/hooks/useRequest"; +import { useState } from "react"; +import { DELETE_AZMAYESH_TYPE_LIST } from "@/core/utils/routes"; + +const DeleteAzmayeshType = ({ rowId, mutate }) => { + const requestServer = useRequest({ notificationSuccess: true }); + const [openDeleteDialog, setOpenDeleteDialog] = useState(false); + const [isSubmitting, setIsSubmitting] = useState(false); + + const handleSubmit = () => { + setIsSubmitting(true); + requestServer(`${DELETE_AZMAYESH_TYPE_LIST}/${rowId}`, "post") + .then(() => { + setOpenDeleteDialog(false); + mutate(); + }) + .catch(() => {}) + .finally(() => { + setIsSubmitting(false); + }); + }; + + return ( + <> + + { + setOpenDeleteDialog(true); + }} + > + + + + + حذف نوع آزمایش + + آیا از حذف این نوع آزمایش مطمئن هستید؟ + + + + + + + + ); +}; +export default DeleteAzmayeshType; diff --git a/src/components/dashboard/azmayeshType/RowActions/UpdateAzmayeshType/index.jsx b/src/components/dashboard/azmayeshType/RowActions/UpdateAzmayeshType/index.jsx index 7c7099f..adc74e3 100644 --- a/src/components/dashboard/azmayeshType/RowActions/UpdateAzmayeshType/index.jsx +++ b/src/components/dashboard/azmayeshType/RowActions/UpdateAzmayeshType/index.jsx @@ -1,53 +1,53 @@ -import { IconButton, Tooltip } from "@mui/material"; -import EditIcon from "@mui/icons-material/Edit"; -import { GET_AZMAYESH_TYPE_LIST_TABLE } from "@/core/utils/routes"; -import { useState } from "react"; -import useRequest from "@/lib/hooks/useRequest"; -import CandUAzmayeshType from "@/components/dashboard/azmayeshType/Forms/CandUAzmayeshType"; - -const UpdateAzmayeshType = ({ rowId, mutate }) => { - const requestServer = useRequest(); - const [openUpdateDialog, setOpenUpdateDialog] = useState(false); - const [updateInfo, setUpdateInfo] = useState(null); - const [loadingOpen, setLoadingOpen] = useState(false); - - const handleGetInfo = () => { - setLoadingOpen(true); - setOpenUpdateDialog(true); - requestServer(`${GET_AZMAYESH_TYPE_LIST_TABLE}/${rowId}`, "get") - .then((response) => { - setUpdateInfo(response.data.data); - }) - .catch(() => {}) - .finally(() => { - setLoadingOpen(false); - }); - }; - - return ( - <> - - - - - - {openUpdateDialog && ( - - )} - - ); -}; - -export default UpdateAzmayeshType; +import { IconButton, Tooltip } from "@mui/material"; +import EditIcon from "@mui/icons-material/Edit"; +import { GET_AZMAYESH_TYPE_LIST_TABLE } from "@/core/utils/routes"; +import { useState } from "react"; +import useRequest from "@/lib/hooks/useRequest"; +import CandUAzmayeshType from "@/components/dashboard/azmayeshType/Forms/CandUAzmayeshType"; + +const UpdateAzmayeshType = ({ rowId, mutate }) => { + const requestServer = useRequest(); + const [openUpdateDialog, setOpenUpdateDialog] = useState(false); + const [updateInfo, setUpdateInfo] = useState(null); + const [loadingOpen, setLoadingOpen] = useState(false); + + const handleGetInfo = () => { + setLoadingOpen(true); + setOpenUpdateDialog(true); + requestServer(`${GET_AZMAYESH_TYPE_LIST_TABLE}/${rowId}`, "get") + .then((response) => { + setUpdateInfo(response.data.data); + }) + .catch(() => {}) + .finally(() => { + setLoadingOpen(false); + }); + }; + + return ( + <> + + + + + + {openUpdateDialog && ( + + )} + + ); +}; + +export default UpdateAzmayeshType; diff --git a/src/components/dashboard/azmayeshType/RowActions/index.jsx b/src/components/dashboard/azmayeshType/RowActions/index.jsx index 43adc1b..f6aecd4 100644 --- a/src/components/dashboard/azmayeshType/RowActions/index.jsx +++ b/src/components/dashboard/azmayeshType/RowActions/index.jsx @@ -1,13 +1,13 @@ -import { Box } from "@mui/material"; -import UpdateAzmayeshType from "./UpdateAzmayeshType"; -import DeleteAzmayeshType from "./DeleteAzmayeshType"; - -const RowActions = ({ row, mutate }) => { - return ( - - - - - ); -}; -export default RowActions; +import { Box } from "@mui/material"; +import UpdateAzmayeshType from "./UpdateAzmayeshType"; +import DeleteAzmayeshType from "./DeleteAzmayeshType"; + +const RowActions = ({ row, mutate }) => { + return ( + + + + + ); +}; +export default RowActions; diff --git a/src/components/dashboard/azmayeshType/Toolbar.jsx b/src/components/dashboard/azmayeshType/Toolbar.jsx index b08bc4b..f5fdc2e 100644 --- a/src/components/dashboard/azmayeshType/Toolbar.jsx +++ b/src/components/dashboard/azmayeshType/Toolbar.jsx @@ -1,10 +1,10 @@ -import AzmayeshTypeCreate from "./Actions/Create"; - -const Toolbar = ({ mutate }) => { - return ( - <> - - - ); -}; -export default Toolbar; +import AzmayeshTypeCreate from "./Actions/Create"; + +const Toolbar = ({ mutate }) => { + return ( + <> + + + ); +}; +export default Toolbar; diff --git a/src/components/dashboard/azmayeshType/index.jsx b/src/components/dashboard/azmayeshType/index.jsx index 12c4aa9..f2bea01 100644 --- a/src/components/dashboard/azmayeshType/index.jsx +++ b/src/components/dashboard/azmayeshType/index.jsx @@ -1,15 +1,15 @@ -"use client"; - -import PageTitle from "@/core/components/PageTitle"; -import { Stack } from "@mui/material"; -import AzmayeshTypeList from "./AzmayeshTypeList"; - -const AzmayeshTypePage = () => { - return ( - - - - - ); -}; -export default AzmayeshTypePage; +"use client"; + +import PageTitle from "@/core/components/PageTitle"; +import { Stack } from "@mui/material"; +import AzmayeshTypeList from "./AzmayeshTypeList"; + +const AzmayeshTypePage = () => { + return ( + + + + + ); +}; +export default AzmayeshTypePage; diff --git a/src/components/dashboard/damageItems/Actions/Create/Form/CreateFormContent.jsx b/src/components/dashboard/damageItems/Actions/Create/Form/CreateFormContent.jsx index 53fd6a3..9960b7f 100644 --- a/src/components/dashboard/damageItems/Actions/Create/Form/CreateFormContent.jsx +++ b/src/components/dashboard/damageItems/Actions/Create/Form/CreateFormContent.jsx @@ -1,145 +1,145 @@ -import NumberField from "@/core/components/NumberField"; -import StyledForm from "@/core/components/StyledForm"; -import { CREATE_RECEIPT_DAMAGE_ITEMS } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { yupResolver } from "@hookform/resolvers/yup"; -import { Beenhere, ExitToApp } from "@mui/icons-material"; -import { Button, DialogActions, DialogContent, DialogTitle, Stack, TextField } from "@mui/material"; -import { DialogHeader } from "next/dist/client/components/react-dev-overlay/internal/components/Dialog"; -import { Controller, useForm } from "react-hook-form"; -import { object, string } from "yup"; - -const validationSchema = object({ - title: string().required("وارد کردن عنوان الزامیست!"), - unit: string().required("وارد کردن واحد الزامیست!"), - base_price: string().required("وارد کردن فی الزامیست!"), -}); - -const CreateFormContent = ({ setOpen, mutate }) => { - const requestServer = useRequest({ notificationSuccess: true }); - const defaultValues = { - title: "", - unit: "", - base_price: null, - }; - - const { - control, - handleSubmit, - formState: { isSubmitting }, - } = useForm({ - defaultValues, - resolver: yupResolver(validationSchema), - mode: "all", - }); - - const onSubmit = async (data) => { - const formData = new FormData(); - formData.append("title", data.title); - formData.append("unit", data.unit); - formData.append("base_price", data.base_price); - - try { - await requestServer(CREATE_RECEIPT_DAMAGE_ITEMS, "post", { - data: formData, - }); - mutate(); - setOpen(false); - } catch (error) {} - }; - - return ( - <> - - ثبت آیتم جدید - - - - - ( - - )} - /> - ( - - )} - /> - ( - { - if (!isNaN(event.target.value)) { - onChange(event.target.value); - } else { - onChange(value); - } - }} - helperText={error ? error.message : null} - variant="outlined" - fullWidth - /> - )} - /> - - - - - - - - - ); -}; -export default CreateFormContent; +import NumberField from "@/core/components/NumberField"; +import StyledForm from "@/core/components/StyledForm"; +import { CREATE_RECEIPT_DAMAGE_ITEMS } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { Beenhere, ExitToApp } from "@mui/icons-material"; +import { Button, DialogActions, DialogContent, DialogTitle, Stack, TextField } from "@mui/material"; +import { DialogHeader } from "next/dist/client/components/react-dev-overlay/internal/components/Dialog"; +import { Controller, useForm } from "react-hook-form"; +import { object, string } from "yup"; + +const validationSchema = object({ + title: string().required("وارد کردن عنوان الزامیست!"), + unit: string().required("وارد کردن واحد الزامیست!"), + base_price: string().required("وارد کردن فی الزامیست!"), +}); + +const CreateFormContent = ({ setOpen, mutate }) => { + const requestServer = useRequest({ notificationSuccess: true }); + const defaultValues = { + title: "", + unit: "", + base_price: null, + }; + + const { + control, + handleSubmit, + formState: { isSubmitting }, + } = useForm({ + defaultValues, + resolver: yupResolver(validationSchema), + mode: "all", + }); + + const onSubmit = async (data) => { + const formData = new FormData(); + formData.append("title", data.title); + formData.append("unit", data.unit); + formData.append("base_price", data.base_price); + + try { + await requestServer(CREATE_RECEIPT_DAMAGE_ITEMS, "post", { + data: formData, + }); + mutate(); + setOpen(false); + } catch (error) {} + }; + + return ( + <> + + ثبت آیتم جدید + + + + + ( + + )} + /> + ( + + )} + /> + ( + { + if (!isNaN(event.target.value)) { + onChange(event.target.value); + } else { + onChange(value); + } + }} + helperText={error ? error.message : null} + variant="outlined" + fullWidth + /> + )} + /> + + + + + + + + + ); +}; +export default CreateFormContent; diff --git a/src/components/dashboard/damageItems/Actions/Create/Form/index.jsx b/src/components/dashboard/damageItems/Actions/Create/Form/index.jsx index 4d04509..2fcff58 100644 --- a/src/components/dashboard/damageItems/Actions/Create/Form/index.jsx +++ b/src/components/dashboard/damageItems/Actions/Create/Form/index.jsx @@ -1,25 +1,25 @@ -import { Dialog, IconButton } from "@mui/material"; -import CreateFormContent from "./CreateFormContent"; -import CloseIcon from "@mui/icons-material/Close"; - -const CreateForm = ({ open, setOpen, mutate }) => { - return ( - - setOpen(false)} - sx={(theme) => ({ - position: "absolute", - right: 8, - top: 8, - zIndex: 50, - color: theme.palette.grey[500], - })} - > - - - {open && } - - ); -}; -export default CreateForm; +import { Dialog, IconButton } from "@mui/material"; +import CreateFormContent from "./CreateFormContent"; +import CloseIcon from "@mui/icons-material/Close"; + +const CreateForm = ({ open, setOpen, mutate }) => { + return ( + + setOpen(false)} + sx={(theme) => ({ + position: "absolute", + right: 8, + top: 8, + zIndex: 50, + color: theme.palette.grey[500], + })} + > + + + {open && } + + ); +}; +export default CreateForm; diff --git a/src/components/dashboard/damageItems/Actions/Create/index.jsx b/src/components/dashboard/damageItems/Actions/Create/index.jsx index a720b22..67cf78a 100644 --- a/src/components/dashboard/damageItems/Actions/Create/index.jsx +++ b/src/components/dashboard/damageItems/Actions/Create/index.jsx @@ -1,36 +1,36 @@ -import { AddCircle } from "@mui/icons-material"; -import { Button, IconButton, useMediaQuery, useTheme } from "@mui/material"; -import CreateForm from "./Form"; -import { useState } from "react"; - -const CreateDamage = ({ mutate }) => { - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const [open, setOpen] = useState(false); - - const handleOpen = () => { - setOpen(true); - }; - - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - - - ); -}; -export default CreateDamage; +import { AddCircle } from "@mui/icons-material"; +import { Button, IconButton, useMediaQuery, useTheme } from "@mui/material"; +import CreateForm from "./Form"; +import { useState } from "react"; + +const CreateDamage = ({ mutate }) => { + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const [open, setOpen] = useState(false); + + const handleOpen = () => { + setOpen(true); + }; + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + + + ); +}; +export default CreateDamage; diff --git a/src/components/dashboard/damageItems/DamagesList.jsx b/src/components/dashboard/damageItems/DamagesList.jsx index 2050359..32229aa 100644 --- a/src/components/dashboard/damageItems/DamagesList.jsx +++ b/src/components/dashboard/damageItems/DamagesList.jsx @@ -1,84 +1,84 @@ -"use client"; -import DataTableWithAuth from "@/core/components/DataTableWithAuth"; -import { GET_RECEIPT_DAMAGE_ITEMS_LIST } from "@/core/utils/routes"; -import { Box } from "@mui/material"; -import { useMemo } from "react"; -import Toolbar from "./Toolbar"; -import RowActions from "./RowActions"; - -const DamagesList = () => { - const columns = useMemo( - () => [ - { - accessorKey: "id", - header: "کد یکتا", - id: "id", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorKey: "title", - header: "عنوان", - id: "title", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorKey: "unit", - header: "واحد", - id: "unit", - enableColumnFilter: false, - grow: false, - size: 100, - }, - { - accessorKey: "base_price", - header: "فی (ریال)", - id: "base_price", - enableColumnFilter: false, - grow: false, - size: 100, - Cell: ({ renderedCellValue }) => (renderedCellValue / 1).toLocaleString(), - }, - { - accessorKey: "status", - header: "وضعیت", - id: "status", - enableColumnFilter: false, - grow: false, - size: 100, - Cell: ({ renderedCellValue }) => (renderedCellValue == 1 ? "فعال" : "غیرفعال"), - }, - ], - [] - ); - - return ( - <> - - - - - ); -}; -export default DamagesList; +"use client"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import { GET_RECEIPT_DAMAGE_ITEMS_LIST } from "@/core/utils/routes"; +import { Box } from "@mui/material"; +import { useMemo } from "react"; +import Toolbar from "./Toolbar"; +import RowActions from "./RowActions"; + +const DamagesList = () => { + const columns = useMemo( + () => [ + { + accessorKey: "id", + header: "کد یکتا", + id: "id", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "title", + header: "عنوان", + id: "title", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "unit", + header: "واحد", + id: "unit", + enableColumnFilter: false, + grow: false, + size: 100, + }, + { + accessorKey: "base_price", + header: "فی (ریال)", + id: "base_price", + enableColumnFilter: false, + grow: false, + size: 100, + Cell: ({ renderedCellValue }) => (renderedCellValue / 1).toLocaleString(), + }, + { + accessorKey: "status", + header: "وضعیت", + id: "status", + enableColumnFilter: false, + grow: false, + size: 100, + Cell: ({ renderedCellValue }) => (renderedCellValue == 1 ? "فعال" : "غیرفعال"), + }, + ], + [] + ); + + return ( + <> + + + + + ); +}; +export default DamagesList; diff --git a/src/components/dashboard/damageItems/RowActions/Activity/index.jsx b/src/components/dashboard/damageItems/RowActions/Activity/index.jsx index 3683899..63125ac 100644 --- a/src/components/dashboard/damageItems/RowActions/Activity/index.jsx +++ b/src/components/dashboard/damageItems/RowActions/Activity/index.jsx @@ -1,31 +1,31 @@ -import { ATIVITY_RECEIPT_DAMAGE_ITEMS } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { Switch } from "@mui/material"; -import { useState } from "react"; - -const Activity = ({ rowId, mutate, status }) => { - const [disabled, setDisabled] = useState(false); - const [checked, setChecked] = useState(status == 1); - const requestServer = useRequest(); - - const handleSwitch = (event) => { - const newChecked = event.target.checked; - setChecked(newChecked); - setDisabled(true); - - requestServer(`${ATIVITY_RECEIPT_DAMAGE_ITEMS}/${rowId}`, "post") - .then(() => { - mutate(); - }) - .catch(() => { - setChecked(!newChecked); - }) - .finally(() => { - setDisabled(false); - }); - }; - - return ; -}; - -export default Activity; +import { ATIVITY_RECEIPT_DAMAGE_ITEMS } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { Switch } from "@mui/material"; +import { useState } from "react"; + +const Activity = ({ rowId, mutate, status }) => { + const [disabled, setDisabled] = useState(false); + const [checked, setChecked] = useState(status == 1); + const requestServer = useRequest(); + + const handleSwitch = (event) => { + const newChecked = event.target.checked; + setChecked(newChecked); + setDisabled(true); + + requestServer(`${ATIVITY_RECEIPT_DAMAGE_ITEMS}/${rowId}`, "post") + .then(() => { + mutate(); + }) + .catch(() => { + setChecked(!newChecked); + }) + .finally(() => { + setDisabled(false); + }); + }; + + return ; +}; + +export default Activity; diff --git a/src/components/dashboard/damageItems/RowActions/Edit/Form/index.jsx b/src/components/dashboard/damageItems/RowActions/Edit/Form/index.jsx index e6c2efb..6480b96 100644 --- a/src/components/dashboard/damageItems/RowActions/Edit/Form/index.jsx +++ b/src/components/dashboard/damageItems/RowActions/Edit/Form/index.jsx @@ -1,145 +1,145 @@ -import NumberField from "@/core/components/NumberField"; -import StyledForm from "@/core/components/StyledForm"; -import { UPDATE_RECEIPT_DAMAGE_ITEMS } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { yupResolver } from "@hookform/resolvers/yup"; -import { Beenhere, ExitToApp } from "@mui/icons-material"; -import { Button, DialogActions, DialogContent, DialogTitle, Stack, TextField } from "@mui/material"; -import { DialogHeader } from "next/dist/client/components/react-dev-overlay/internal/components/Dialog"; -import { Controller, useForm } from "react-hook-form"; -import { object, string } from "yup"; - -const validationSchema = object({ - title: string().required("وارد کردن عنوان الزامیست!"), - unit: string().required("وارد کردن واحد الزامیست!"), - base_price: string().required("وارد کردن فی الزامیست!"), -}); - -const EditFormContent = ({ row, rowId, mutate, setOpen }) => { - const requestServer = useRequest({ notificationSuccess: true }); - const defaultValues = { - title: row.original.title, - unit: row.original.unit, - base_price: row.original.base_price, - }; - - const { - control, - handleSubmit, - formState: { isSubmitting }, - } = useForm({ - defaultValues, - resolver: yupResolver(validationSchema), - mode: "all", - }); - - const onSubmit = async (data) => { - const formData = new FormData(); - formData.append("title", data.title); - formData.append("unit", data.unit); - formData.append("base_price", data.base_price); - - try { - await requestServer(`${UPDATE_RECEIPT_DAMAGE_ITEMS}/${rowId}`, "post", { - data: formData, - }); - mutate(); - setOpen(false); - } catch (error) {} - }; - - return ( - <> - - ویرایش آیتم - - - - - ( - - )} - /> - ( - - )} - /> - ( - { - if (!isNaN(event.target.value)) { - onChange(event.target.value); - } else { - onChange(value); - } - }} - helperText={error ? error.message : null} - variant="outlined" - fullWidth - /> - )} - /> - - - - - - - - - ); -}; -export default EditFormContent; +import NumberField from "@/core/components/NumberField"; +import StyledForm from "@/core/components/StyledForm"; +import { UPDATE_RECEIPT_DAMAGE_ITEMS } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { Beenhere, ExitToApp } from "@mui/icons-material"; +import { Button, DialogActions, DialogContent, DialogTitle, Stack, TextField } from "@mui/material"; +import { DialogHeader } from "next/dist/client/components/react-dev-overlay/internal/components/Dialog"; +import { Controller, useForm } from "react-hook-form"; +import { object, string } from "yup"; + +const validationSchema = object({ + title: string().required("وارد کردن عنوان الزامیست!"), + unit: string().required("وارد کردن واحد الزامیست!"), + base_price: string().required("وارد کردن فی الزامیست!"), +}); + +const EditFormContent = ({ row, rowId, mutate, setOpen }) => { + const requestServer = useRequest({ notificationSuccess: true }); + const defaultValues = { + title: row.original.title, + unit: row.original.unit, + base_price: row.original.base_price, + }; + + const { + control, + handleSubmit, + formState: { isSubmitting }, + } = useForm({ + defaultValues, + resolver: yupResolver(validationSchema), + mode: "all", + }); + + const onSubmit = async (data) => { + const formData = new FormData(); + formData.append("title", data.title); + formData.append("unit", data.unit); + formData.append("base_price", data.base_price); + + try { + await requestServer(`${UPDATE_RECEIPT_DAMAGE_ITEMS}/${rowId}`, "post", { + data: formData, + }); + mutate(); + setOpen(false); + } catch (error) {} + }; + + return ( + <> + + ویرایش آیتم + + + + + ( + + )} + /> + ( + + )} + /> + ( + { + if (!isNaN(event.target.value)) { + onChange(event.target.value); + } else { + onChange(value); + } + }} + helperText={error ? error.message : null} + variant="outlined" + fullWidth + /> + )} + /> + + + + + + + + + ); +}; +export default EditFormContent; diff --git a/src/components/dashboard/damageItems/RowActions/Edit/index.jsx b/src/components/dashboard/damageItems/RowActions/Edit/index.jsx index 39447a8..a8a6ec7 100644 --- a/src/components/dashboard/damageItems/RowActions/Edit/index.jsx +++ b/src/components/dashboard/damageItems/RowActions/Edit/index.jsx @@ -1,44 +1,44 @@ -import BorderColorIcon from "@mui/icons-material/BorderColor"; -import { Dialog, IconButton, Tooltip } from "@mui/material"; -import EditFormContent from "./Form"; -import { useState } from "react"; -import CloseIcon from "@mui/icons-material/Close"; - -const Edit = ({ row, mutate, rowId }) => { - const [openEditDialog, setOpenEditDialog] = useState(false); - - return ( - <> - - { - setOpenEditDialog(true); - }} - > - - - - - setOpenEditDialog(false)} - sx={(theme) => ({ - position: "absolute", - right: 8, - top: 8, - zIndex: 50, - color: theme.palette.grey[500], - })} - > - - - {openEditDialog && ( - - )} - - - ); -}; -export default Edit; +import BorderColorIcon from "@mui/icons-material/BorderColor"; +import { Dialog, IconButton, Tooltip } from "@mui/material"; +import EditFormContent from "./Form"; +import { useState } from "react"; +import CloseIcon from "@mui/icons-material/Close"; + +const Edit = ({ row, mutate, rowId }) => { + const [openEditDialog, setOpenEditDialog] = useState(false); + + return ( + <> + + { + setOpenEditDialog(true); + }} + > + + + + + setOpenEditDialog(false)} + sx={(theme) => ({ + position: "absolute", + right: 8, + top: 8, + zIndex: 50, + color: theme.palette.grey[500], + })} + > + + + {openEditDialog && ( + + )} + + + ); +}; +export default Edit; diff --git a/src/components/dashboard/damageItems/RowActions/index.jsx b/src/components/dashboard/damageItems/RowActions/index.jsx index 8fbaea1..8814c5e 100644 --- a/src/components/dashboard/damageItems/RowActions/index.jsx +++ b/src/components/dashboard/damageItems/RowActions/index.jsx @@ -1,13 +1,13 @@ -import { Box } from "@mui/material"; -import Activity from "./Activity"; -import Edit from "./Edit"; - -const RowActions = ({ row, mutate }) => { - return ( - - - - - ); -}; -export default RowActions; +import { Box } from "@mui/material"; +import Activity from "./Activity"; +import Edit from "./Edit"; + +const RowActions = ({ row, mutate }) => { + return ( + + + + + ); +}; +export default RowActions; diff --git a/src/components/dashboard/damageItems/Toolbar.jsx b/src/components/dashboard/damageItems/Toolbar.jsx index b639318..065ecd8 100644 --- a/src/components/dashboard/damageItems/Toolbar.jsx +++ b/src/components/dashboard/damageItems/Toolbar.jsx @@ -1,10 +1,10 @@ -import CreateDamage from "./Actions/Create"; - -const Toolbar = ({ mutate }) => { - return ( - <> - - - ); -}; -export default Toolbar; +import CreateDamage from "./Actions/Create"; + +const Toolbar = ({ mutate }) => { + return ( + <> + + + ); +}; +export default Toolbar; diff --git a/src/components/dashboard/damageItems/index.jsx b/src/components/dashboard/damageItems/index.jsx index ac37d7d..b1dd284 100644 --- a/src/components/dashboard/damageItems/index.jsx +++ b/src/components/dashboard/damageItems/index.jsx @@ -1,13 +1,13 @@ -import PageTitle from "@/core/components/PageTitle"; -import { Stack } from "@mui/material"; -import DamagesList from "./DamagesList"; - -const DamagesPage = () => { - return ( - - - - - ); -}; -export default DamagesPage; +import PageTitle from "@/core/components/PageTitle"; +import { Stack } from "@mui/material"; +import DamagesList from "./DamagesList"; + +const DamagesPage = () => { + return ( + + + + + ); +}; +export default DamagesPage; diff --git a/src/components/dashboard/damages/operator/Actions/create/Forms/CityContent.jsx b/src/components/dashboard/damages/operator/Actions/create/Forms/CityContent.jsx index 5092ad9..3a17e10 100644 --- a/src/components/dashboard/damages/operator/Actions/create/Forms/CityContent.jsx +++ b/src/components/dashboard/damages/operator/Actions/create/Forms/CityContent.jsx @@ -1,33 +1,33 @@ -import SelectBox from "@/core/components/SelectBox"; -import useCities from "@/lib/hooks/useCities"; -import { useEffect, useState } from "react"; - -const CityContent = ({ provinceID, field, fieldState: { error } }) => { - const { cityList, loadingCityList, errorCityList } = useCities(provinceID); - const [prevDependency, setPrevDependency] = useState(provinceID); - - useEffect(() => { - if (prevDependency === provinceID) return; - field.onChange(null); - setPrevDependency(provinceID); - }, [provinceID]); - - return ( - - ); -}; -export default CityContent; +import SelectBox from "@/core/components/SelectBox"; +import useCities from "@/lib/hooks/useCities"; +import { useEffect, useState } from "react"; + +const CityContent = ({ provinceID, field, fieldState: { error } }) => { + const { cityList, loadingCityList, errorCityList } = useCities(provinceID); + const [prevDependency, setPrevDependency] = useState(provinceID); + + useEffect(() => { + if (prevDependency === provinceID) return; + field.onChange(null); + setPrevDependency(provinceID); + }, [provinceID]); + + return ( + + ); +}; +export default CityContent; diff --git a/src/components/dashboard/damages/operator/Actions/create/Forms/CityController.jsx b/src/components/dashboard/damages/operator/Actions/create/Forms/CityController.jsx index f5b46d4..6cea9b0 100644 --- a/src/components/dashboard/damages/operator/Actions/create/Forms/CityController.jsx +++ b/src/components/dashboard/damages/operator/Actions/create/Forms/CityController.jsx @@ -1,16 +1,16 @@ -import SelectBox from "@/core/components/SelectBox"; -import useEdaratLists from "@/lib/hooks/useEdaratLists"; -import { Controller, useWatch } from "react-hook-form"; -import CityContent from "./CityContent"; - -const CityController = ({ control }) => { - const provinceID = useWatch({ control, name: "province_id" }); - return ( - } - /> - ); -}; -export default CityController; +import SelectBox from "@/core/components/SelectBox"; +import useEdaratLists from "@/lib/hooks/useEdaratLists"; +import { Controller, useWatch } from "react-hook-form"; +import CityContent from "./CityContent"; + +const CityController = ({ control }) => { + const provinceID = useWatch({ control, name: "province_id" }); + return ( + } + /> + ); +}; +export default CityController; diff --git a/src/components/dashboard/damages/operator/Actions/create/Forms/CreateFormContent.jsx b/src/components/dashboard/damages/operator/Actions/create/Forms/CreateFormContent.jsx index e3bc1a2..b41c6ab 100644 --- a/src/components/dashboard/damages/operator/Actions/create/Forms/CreateFormContent.jsx +++ b/src/components/dashboard/damages/operator/Actions/create/Forms/CreateFormContent.jsx @@ -1,262 +1,262 @@ -import React, { useState } from "react"; -import { Controller, useForm } from "react-hook-form"; -import { yupResolver } from "@hookform/resolvers/yup"; -import { array, mixed, number, object, string } from "yup"; -import { Box, Button, DialogActions, DialogContent, Tab, Tabs } from "@mui/material"; -import StyledForm from "@/core/components/StyledForm"; -import InfoIcon from "@mui/icons-material/Info"; -import ExitToAppIcon from "@mui/icons-material/ExitToApp"; -import KeyboardDoubleArrowRightIcon from "@mui/icons-material/KeyboardDoubleArrowRight"; -import BeenhereIcon from "@mui/icons-material/Beenhere"; -import MinorCrashIcon from "@mui/icons-material/MinorCrash"; -import DamageInfo from "./DamageInfo"; -import KeyboardDoubleArrowLeftIcon from "@mui/icons-material/KeyboardDoubleArrowLeft"; -import DamageReport from "./DamageReport"; -import DamageItem from "./DamageItem"; -import validateNationalCode from "@/core/utils/nationalCodeValidation"; -import AssessmentIcon from "@mui/icons-material/Assessment"; - -function TabPanel(props) { - const { children, value, index } = props; - return ( - - ); -} - -const validationSchema = object({ - accident_date: string().required("لطفا تاریخ تصادف را وارد کنید!!!"), - accident_time: string().required("لطفا زمان تصادف را وارد کنید!!!"), - accident_type: string().required("لطفا نوع تصادف را وارد کنید!!!"), - province_id: number().required("لطفا استان را وارد کنید!!!"), - city_id: number().required("لطفا شهرستان را وارد کنید!!!"), - axis_name: string().required("لطفا نام محور را وارد کنید!!!"), - driver_name: string().when("isForeign", { - is: "0", - then: (schema) => schema.required("لطفا نام و نام خانوادگی را وارد کنید!!!"), - }), - phone_number: string().when("isForeign", { - is: "0", - then: (schema) => - schema - .matches(/^09\d{9}$/, "شماره موبایل باید با 09 شروع شده و 11 رقم باشد") - .required("لطفا تلفن همراه را وارد کنید!!!"), - }), - national_code: mixed().when("isForeign", { - is: "0", - then: (schema) => - schema - .test("max", "کد ملی باید شامل 10 رقم باشد", (value) => value.toString().length === 10) - .test("validation", "کد ملی صحیح نمی باشد", (value) => validateNationalCode(value)) - .required("لطفا کد ملی را وارد کنید!!!"), - }), - start_point: mixed() - .test("start-point-required", "لطفاً نقطه تصادف را مشخص کنید!", function (value) { - return !!value; - }) - .required("لطفاً نقطه تصادف را مشخص کنید!"), - plate_part1: mixed().when("isForeign", { - is: "0", - then: (schema) => - schema.test("max", "2رقم", (value) => value.toString().length === 2).required("plate_part1 الزامیست"), - }), - plate_part2: mixed().when("isForeign", { - is: "0", - then: (schema) => schema.required("plate_part2 الزامیست"), - }), - plate_part3: mixed().when("isForeign", { - is: "0", - then: (schema) => - schema.test("max", "3رقم", (value) => value.toString().length === 3).required("plate_part3الزامیست"), - }), - - plate_part4: mixed().when("isForeign", { - is: "0", - then: (schema) => - schema.test("max", "2رقم", (value) => value.toString().length === 2).required("plate_part4الزامیست"), - }), - damage_picture1: mixed().nullable().required("لطفا عکس تصادف را بارگذاری کنید!"), - damage_picture2: mixed().nullable().required("لطفا عکس تصادف را بارگذاری کنید!"), - police_serial: string().when("radio_button", { - is: "police_file_checkbox", // زمانی که گزینه "police_file_checkbox" انتخاب شده باشد - then: (schema) => schema.required("شماره کروکی یا نامه پلیس راه الزامی است"), - }), - police_file_date: string().when("radio_button", { - is: "police_file_checkbox", // زمانی که گزینه "police_file_checkbox" انتخاب شده باشد - then: (schema) => schema.required("تاریخ کروکی یا نامه پلیس راه الزامی است"), - }), - police_file: mixed().when("radio_button", { - is: "police_file_checkbox", // زمانی که گزینه "police_file_checkbox" انتخاب شده باشد - then: (schema) => schema.nullable().required("تصویر کروکی یا نامه پلیس راه الزامی است"), - otherwise: (schema) => schema.notRequired(), - }), - items_damage: array().min(1, "حداقل یک آیتم خسارت ضروریست!!!"), -}); - -const CreateFormContent = ({ setOpen, SubmitDamage, defaultData }) => { - const defaultValues = { - isForeign: defaultData.isForeign, - accident_date: defaultData.accident_date, - accident_time: defaultData.accident_time, - accident_type: defaultData.accident_type, - province_id: defaultData.province_id, - city_id: defaultData.city_id, - is_province: defaultData.is_province, - axis_name: defaultData.axis_name, - driver_name: defaultData.driver_name, - phone_number: defaultData.phone_number, - national_code: defaultData.national_code, - plate_part1: defaultData.plate_part1, - plate_part2: defaultData.plate_part2, - plate_part3: defaultData.plate_part3, - plate_part4: defaultData.plate_part4, - radio_button: defaultData.radio_button, - damage_picture1: defaultData.damage_picture1, - damage_picture2: defaultData.damage_picture2, - report_base: defaultData.report_base, - police_file_checkbox: defaultData.police_file_checkbox, - police_file: defaultData.police_file, - police_file_date: defaultData.police_file_date, - police_serial: defaultData.police_serial, - start_point: defaultData.start_point, - items_damage: defaultData.items_damage, - }; - - const [tabState, setTabState] = useState(0); - const handleClose = () => setOpen(false); - const handleChangeTab = (event, newValue) => setTabState(newValue); - const handlePrev = () => { - if (tabState === 0) { - handleClose(); - } else { - setTabState(tabState - 1); - } - }; - const { - control, - handleSubmit, - setValue, - trigger, - formState: { errors, isSubmitting, isValid }, - } = useForm({ - defaultValues, - resolver: yupResolver(validationSchema), - mode: "all", - }); - const onSubmitBase = async (data) => { - await SubmitDamage(data); - }; - const handleNext = async () => { - let fieldsToValidate = []; - if (tabState === 0) { - fieldsToValidate = [ - "phone_number", - "start_point", - "plate_part1", - "plate_part2", - "plate_part3", - "plate_part4", - "accident_date", - "accident_type", - "national_code", - "accident_time", - "province_id", - "city_id", - "axis_name", - "driver_name", - "damage_picture1", - "damage_picture2", - ]; - } else if (tabState === 1) { - fieldsToValidate = ["report_base", "police_file", "police_file_date", "police_serial"]; - } else if (tabState === 2) { - fieldsToValidate = ["items_damage"]; - } - const isValid = await trigger(fieldsToValidate); - if (isValid) { - setTabState(tabState + 1); - } - }; - return ( - - - } label="اطلاعات تصادف" /> - } label="گزارش خسارت" /> - } label="آیتم خسارت" /> - - - - - - - - - - - { - return ( - - ); - }} - /> - - - - - - {tabState !== 2 ? ( - - ) : ( - - )} - - - ); -}; -export default CreateFormContent; +import React, { useState } from "react"; +import { Controller, useForm } from "react-hook-form"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { array, mixed, number, object, string } from "yup"; +import { Box, Button, DialogActions, DialogContent, Tab, Tabs } from "@mui/material"; +import StyledForm from "@/core/components/StyledForm"; +import InfoIcon from "@mui/icons-material/Info"; +import ExitToAppIcon from "@mui/icons-material/ExitToApp"; +import KeyboardDoubleArrowRightIcon from "@mui/icons-material/KeyboardDoubleArrowRight"; +import BeenhereIcon from "@mui/icons-material/Beenhere"; +import MinorCrashIcon from "@mui/icons-material/MinorCrash"; +import DamageInfo from "./DamageInfo"; +import KeyboardDoubleArrowLeftIcon from "@mui/icons-material/KeyboardDoubleArrowLeft"; +import DamageReport from "./DamageReport"; +import DamageItem from "./DamageItem"; +import validateNationalCode from "@/core/utils/nationalCodeValidation"; +import AssessmentIcon from "@mui/icons-material/Assessment"; + +function TabPanel(props) { + const { children, value, index } = props; + return ( + + ); +} + +const validationSchema = object({ + accident_date: string().required("لطفا تاریخ تصادف را وارد کنید!!!"), + accident_time: string().required("لطفا زمان تصادف را وارد کنید!!!"), + accident_type: string().required("لطفا نوع تصادف را وارد کنید!!!"), + province_id: number().required("لطفا استان را وارد کنید!!!"), + city_id: number().required("لطفا شهرستان را وارد کنید!!!"), + axis_name: string().required("لطفا نام محور را وارد کنید!!!"), + driver_name: string().when("isForeign", { + is: "0", + then: (schema) => schema.required("لطفا نام و نام خانوادگی را وارد کنید!!!"), + }), + phone_number: string().when("isForeign", { + is: "0", + then: (schema) => + schema + .matches(/^09\d{9}$/, "شماره موبایل باید با 09 شروع شده و 11 رقم باشد") + .required("لطفا تلفن همراه را وارد کنید!!!"), + }), + national_code: mixed().when("isForeign", { + is: "0", + then: (schema) => + schema + .test("max", "کد ملی باید شامل 10 رقم باشد", (value) => value.toString().length === 10) + .test("validation", "کد ملی صحیح نمی باشد", (value) => validateNationalCode(value)) + .required("لطفا کد ملی را وارد کنید!!!"), + }), + start_point: mixed() + .test("start-point-required", "لطفاً نقطه تصادف را مشخص کنید!", function (value) { + return !!value; + }) + .required("لطفاً نقطه تصادف را مشخص کنید!"), + plate_part1: mixed().when("isForeign", { + is: "0", + then: (schema) => + schema.test("max", "2رقم", (value) => value.toString().length === 2).required("plate_part1 الزامیست"), + }), + plate_part2: mixed().when("isForeign", { + is: "0", + then: (schema) => schema.required("plate_part2 الزامیست"), + }), + plate_part3: mixed().when("isForeign", { + is: "0", + then: (schema) => + schema.test("max", "3رقم", (value) => value.toString().length === 3).required("plate_part3الزامیست"), + }), + + plate_part4: mixed().when("isForeign", { + is: "0", + then: (schema) => + schema.test("max", "2رقم", (value) => value.toString().length === 2).required("plate_part4الزامیست"), + }), + damage_picture1: mixed().nullable().required("لطفا عکس تصادف را بارگذاری کنید!"), + damage_picture2: mixed().nullable().required("لطفا عکس تصادف را بارگذاری کنید!"), + police_serial: string().when("radio_button", { + is: "police_file_checkbox", // زمانی که گزینه "police_file_checkbox" انتخاب شده باشد + then: (schema) => schema.required("شماره کروکی یا نامه پلیس راه الزامی است"), + }), + police_file_date: string().when("radio_button", { + is: "police_file_checkbox", // زمانی که گزینه "police_file_checkbox" انتخاب شده باشد + then: (schema) => schema.required("تاریخ کروکی یا نامه پلیس راه الزامی است"), + }), + police_file: mixed().when("radio_button", { + is: "police_file_checkbox", // زمانی که گزینه "police_file_checkbox" انتخاب شده باشد + then: (schema) => schema.nullable().required("تصویر کروکی یا نامه پلیس راه الزامی است"), + otherwise: (schema) => schema.notRequired(), + }), + items_damage: array().min(1, "حداقل یک آیتم خسارت ضروریست!!!"), +}); + +const CreateFormContent = ({ setOpen, SubmitDamage, defaultData }) => { + const defaultValues = { + isForeign: defaultData.isForeign, + accident_date: defaultData.accident_date, + accident_time: defaultData.accident_time, + accident_type: defaultData.accident_type, + province_id: defaultData.province_id, + city_id: defaultData.city_id, + is_province: defaultData.is_province, + axis_name: defaultData.axis_name, + driver_name: defaultData.driver_name, + phone_number: defaultData.phone_number, + national_code: defaultData.national_code, + plate_part1: defaultData.plate_part1, + plate_part2: defaultData.plate_part2, + plate_part3: defaultData.plate_part3, + plate_part4: defaultData.plate_part4, + radio_button: defaultData.radio_button, + damage_picture1: defaultData.damage_picture1, + damage_picture2: defaultData.damage_picture2, + report_base: defaultData.report_base, + police_file_checkbox: defaultData.police_file_checkbox, + police_file: defaultData.police_file, + police_file_date: defaultData.police_file_date, + police_serial: defaultData.police_serial, + start_point: defaultData.start_point, + items_damage: defaultData.items_damage, + }; + + const [tabState, setTabState] = useState(0); + const handleClose = () => setOpen(false); + const handleChangeTab = (event, newValue) => setTabState(newValue); + const handlePrev = () => { + if (tabState === 0) { + handleClose(); + } else { + setTabState(tabState - 1); + } + }; + const { + control, + handleSubmit, + setValue, + trigger, + formState: { errors, isSubmitting, isValid }, + } = useForm({ + defaultValues, + resolver: yupResolver(validationSchema), + mode: "all", + }); + const onSubmitBase = async (data) => { + await SubmitDamage(data); + }; + const handleNext = async () => { + let fieldsToValidate = []; + if (tabState === 0) { + fieldsToValidate = [ + "phone_number", + "start_point", + "plate_part1", + "plate_part2", + "plate_part3", + "plate_part4", + "accident_date", + "accident_type", + "national_code", + "accident_time", + "province_id", + "city_id", + "axis_name", + "driver_name", + "damage_picture1", + "damage_picture2", + ]; + } else if (tabState === 1) { + fieldsToValidate = ["report_base", "police_file", "police_file_date", "police_serial"]; + } else if (tabState === 2) { + fieldsToValidate = ["items_damage"]; + } + const isValid = await trigger(fieldsToValidate); + if (isValid) { + setTabState(tabState + 1); + } + }; + return ( + + + } label="اطلاعات تصادف" /> + } label="گزارش خسارت" /> + } label="آیتم خسارت" /> + + + + + + + + + + + { + return ( + + ); + }} + /> + + + + + + {tabState !== 2 ? ( + + ) : ( + + )} + + + ); +}; +export default CreateFormContent; diff --git a/src/components/dashboard/damages/operator/Actions/create/Forms/DamageAmount.jsx b/src/components/dashboard/damages/operator/Actions/create/Forms/DamageAmount.jsx index 35eb93f..9a29504 100644 --- a/src/components/dashboard/damages/operator/Actions/create/Forms/DamageAmount.jsx +++ b/src/components/dashboard/damages/operator/Actions/create/Forms/DamageAmount.jsx @@ -1,56 +1,56 @@ -import { Controller, useWatch } from "react-hook-form"; -import { Grid } from "@mui/material"; -import NumberField from "@/core/components/NumberField"; -import { useEffect } from "react"; - -const DamageAmount = ({ control, damageItemList, setValue }) => { - const itemDamage = useWatch({ control, name: "id" }); - const itemValue = useWatch({ control, name: "value" }); - const itemDamageId = damageItemList.find((damageItem) => damageItem.id === itemDamage); - const isDisabled = itemDamageId?.base_price ? itemDamageId?.base_price !== 0 : false; - const calculatedValue = itemValue * (itemDamageId?.base_price ? itemDamageId?.base_price : 0); - useEffect(() => { - if (isDisabled) { - setValue("amount", calculatedValue); - } - }, [itemValue, itemDamageId, isDisabled, setValue]); - return ( - - { - return ( - { - const inputValue = event.target.value; - if (isNaN(Number(inputValue))) { - return; - } - if (!isDisabled) { - field.onChange(inputValue); - } - }} - label={`هزینه خسارت (ریال)`} - placeholder="هزینه خسارت را وارد کنید" - fullWidth - size="small" - disabled={isDisabled || itemDamage === null} - error={error} - helperText={error?.message} - /> - ); - }} - /> - - ); -}; -export default DamageAmount; +import { Controller, useWatch } from "react-hook-form"; +import { Grid } from "@mui/material"; +import NumberField from "@/core/components/NumberField"; +import { useEffect } from "react"; + +const DamageAmount = ({ control, damageItemList, setValue }) => { + const itemDamage = useWatch({ control, name: "id" }); + const itemValue = useWatch({ control, name: "value" }); + const itemDamageId = damageItemList.find((damageItem) => damageItem.id === itemDamage); + const isDisabled = itemDamageId?.base_price ? itemDamageId?.base_price !== 0 : false; + const calculatedValue = itemValue * (itemDamageId?.base_price ? itemDamageId?.base_price : 0); + useEffect(() => { + if (isDisabled) { + setValue("amount", calculatedValue); + } + }, [itemValue, itemDamageId, isDisabled, setValue]); + return ( + + { + return ( + { + const inputValue = event.target.value; + if (isNaN(Number(inputValue))) { + return; + } + if (!isDisabled) { + field.onChange(inputValue); + } + }} + label={`هزینه خسارت (ریال)`} + placeholder="هزینه خسارت را وارد کنید" + fullWidth + size="small" + disabled={isDisabled || itemDamage === null} + error={error} + helperText={error?.message} + /> + ); + }} + /> + + ); +}; +export default DamageAmount; diff --git a/src/components/dashboard/damages/operator/Actions/create/Forms/DamageInfo.jsx b/src/components/dashboard/damages/operator/Actions/create/Forms/DamageInfo.jsx index 6744039..5669e83 100644 --- a/src/components/dashboard/damages/operator/Actions/create/Forms/DamageInfo.jsx +++ b/src/components/dashboard/damages/operator/Actions/create/Forms/DamageInfo.jsx @@ -1,253 +1,253 @@ -import { Controller, useWatch } from "react-hook-form"; -import { Grid, Stack, TextField, ToggleButton, ToggleButtonGroup } from "@mui/material"; -import MuiDatePicker from "@/core/components/MuiDatePicker"; -import MuiTimePicker from "@/core/components/MuiTimePicker"; -import SelectBox from "@/core/components/SelectBox"; -import PlateNumber from "@/core/components/PlateNumber"; -import ImageUpload from "./ImageUpload"; -import MapInfoOneMarker from "@/core/components/MapInfoOneMarker"; -import PersianTextField from "@/core/components/PersianTextField"; -import LogesticController from "./LogesticController"; - -const DamageInfo = ({ control, setValue, errors }) => { - const StartPoint = useWatch({ control, name: "start_point" }); - const IsForeign = useWatch({ control, name: "isForeign" }); - - return ( - - - - ( - field.onChange(newAlignment)} - > - ناوگان داخلی - ناوگان خارجی - - )} - /> - - {IsForeign == "0" && ( - <> - - - ( - - )} - /> - - - ( - { - const inputValue = event.target.value; - if (isNaN(Number(inputValue))) { - return; - } - field.onChange(inputValue); - }} - label="کد ملی راننده" - placeholder={"کد ملی راننده را وارد کنید"} - fullWidth - size="small" - error={error} - helperText={error?.message} - InputLabelProps={{ shrink: true }} - /> - )} - /> - - - - - ( - { - const inputValue = event.target.value; - if (isNaN(Number(inputValue))) { - return; - } - field.onChange(inputValue); - }} - label="شماره موبایل راننده" - placeholder={"شماره موبایل راننده را وارد کنید"} - fullWidth - size="small" - error={error} - helperText={error?.message} - InputLabelProps={{ shrink: true }} - /> - )} - /> - - - - - - - )} - - - { - return ( - field.onChange(value || [])} - helperText={error ? error.message : null} - /> - ); - }} - name={"accident_date"} - /> - - - { - return ( - field.onChange(value || null)} - helperText={error ? error.message : null} - /> - ); - }} - name={"accident_time"} - /> - - - { - return ( - - ); - }} - /> - - - - - ( - - )} - /> - - - ( - - )} - /> - - - - - - - ); -}; -export default DamageInfo; +import { Controller, useWatch } from "react-hook-form"; +import { Grid, Stack, TextField, ToggleButton, ToggleButtonGroup } from "@mui/material"; +import MuiDatePicker from "@/core/components/MuiDatePicker"; +import MuiTimePicker from "@/core/components/MuiTimePicker"; +import SelectBox from "@/core/components/SelectBox"; +import PlateNumber from "@/core/components/PlateNumber"; +import ImageUpload from "./ImageUpload"; +import MapInfoOneMarker from "@/core/components/MapInfoOneMarker"; +import PersianTextField from "@/core/components/PersianTextField"; +import LogesticController from "./LogesticController"; + +const DamageInfo = ({ control, setValue, errors }) => { + const StartPoint = useWatch({ control, name: "start_point" }); + const IsForeign = useWatch({ control, name: "isForeign" }); + + return ( + + + + ( + field.onChange(newAlignment)} + > + ناوگان داخلی + ناوگان خارجی + + )} + /> + + {IsForeign == "0" && ( + <> + + + ( + + )} + /> + + + ( + { + const inputValue = event.target.value; + if (isNaN(Number(inputValue))) { + return; + } + field.onChange(inputValue); + }} + label="کد ملی راننده" + placeholder={"کد ملی راننده را وارد کنید"} + fullWidth + size="small" + error={error} + helperText={error?.message} + InputLabelProps={{ shrink: true }} + /> + )} + /> + + + + + ( + { + const inputValue = event.target.value; + if (isNaN(Number(inputValue))) { + return; + } + field.onChange(inputValue); + }} + label="شماره موبایل راننده" + placeholder={"شماره موبایل راننده را وارد کنید"} + fullWidth + size="small" + error={error} + helperText={error?.message} + InputLabelProps={{ shrink: true }} + /> + )} + /> + + + + + + + )} + + + { + return ( + field.onChange(value || [])} + helperText={error ? error.message : null} + /> + ); + }} + name={"accident_date"} + /> + + + { + return ( + field.onChange(value || null)} + helperText={error ? error.message : null} + /> + ); + }} + name={"accident_time"} + /> + + + { + return ( + + ); + }} + /> + + + + + ( + + )} + /> + + + ( + + )} + /> + + + + + + + ); +}; +export default DamageInfo; diff --git a/src/components/dashboard/damages/operator/Actions/create/Forms/DamageItem.jsx b/src/components/dashboard/damages/operator/Actions/create/Forms/DamageItem.jsx index 5891455..521a6d4 100644 --- a/src/components/dashboard/damages/operator/Actions/create/Forms/DamageItem.jsx +++ b/src/components/dashboard/damages/operator/Actions/create/Forms/DamageItem.jsx @@ -1,167 +1,167 @@ -import { - Autocomplete, - Box, - Button, - Chip, - Divider, - Fade, - Grid, - Skeleton, - Stack, - TextField, - Typography, -} from "@mui/material"; -import { Controller, useForm, useWatch } from "react-hook-form"; -import LinearProgress from "@mui/material/LinearProgress"; -import { useEffect, useState } from "react"; -import DamageItemInfo from "./DamageItemInfo"; -import { number, object } from "yup"; -import useDamageItemList from "@/lib/hooks/useDamageItemList"; -import DamagePrice from "./DamagePrice"; -import { yupResolver } from "@hookform/resolvers/yup"; - -const schema = object({ - id: number().required("لطفا نوع خسارت را وارد کنید!!!"), - value: number().required("لطفا میزان خسارت را وارد کنید!!!"), - amount: number().required("لطفا هزینه خسارت را وارد کنید!!!"), -}); -const defaultValues = { - id: null, - value: null, - amount: null, -}; -const DamageItem = ({ baseOnChange, baseDamageItems }) => { - const flattenBaseDamageItems = (items) => { - return items.map((item) => ({ - id: item.id, - title: item.title, - unit: item.unit, - base_price: item.base_price, - status: item.status, - until_27_shahrivar: item.until_27_shahrivar, - ...item.pivot, // اضافه کردن مقادیر موجود در pivot به سطح بالا - })); - }; - const [selectedDamageItemList, setSelectedDamageItemList] = useState( - baseDamageItems.length !== 0 ? flattenBaseDamageItems(baseDamageItems) : [] - ); - const { damageItemList, loadingDamageItemList, errorDamageItemList } = useDamageItemList(); - const { control, handleSubmit, reset, setValue } = useForm({ - defaultValues, - resolver: yupResolver(schema), - mode: "all", - }); - const deleteDamageItem = (id) => { - setSelectedDamageItemList((prev) => prev.filter((DamageItem) => DamageItem.id !== id)); - }; - useEffect(() => { - baseOnChange(selectedDamageItemList); - }, [selectedDamageItemList]); - const handleCreateDamage = (data) => { - setSelectedDamageItemList((prev) => { - const isDuplicate = prev.some((item) => item.id === data.id); - if (!isDuplicate) { - return [...prev, data]; - } else { - return prev; - } - }); - reset(); - }; - - return ( - <> - - {loadingDamageItemList ? ( - - - - ) : ( - <> - - ( - option.title} - isOptionEqualToValue={(option, value) => option.id === value.id} - loading={loadingDamageItemList} - renderInput={(params) => ( - - )} - onChange={(_, value) => field.onChange(value?.id)} - value={damageItemList.find((item) => item.id === field.value) || null} - /> - )} - /> - - - - - - - - - - - )} - - - - - {selectedDamageItemList.length === 0 && ( - - - ابتدا اطلاعات بالا را تکمیل نمایید - - - )} - - - {loadingDamageItemList ? ( - - - - ) : ( - selectedDamageItemList.length !== 0 && - selectedDamageItemList.map((selectedDamageItem, index) => ( - - - - )) - )} - - - - ); -}; -export default DamageItem; +import { + Autocomplete, + Box, + Button, + Chip, + Divider, + Fade, + Grid, + Skeleton, + Stack, + TextField, + Typography, +} from "@mui/material"; +import { Controller, useForm, useWatch } from "react-hook-form"; +import LinearProgress from "@mui/material/LinearProgress"; +import { useEffect, useState } from "react"; +import DamageItemInfo from "./DamageItemInfo"; +import { number, object } from "yup"; +import useDamageItemList from "@/lib/hooks/useDamageItemList"; +import DamagePrice from "./DamagePrice"; +import { yupResolver } from "@hookform/resolvers/yup"; + +const schema = object({ + id: number().required("لطفا نوع خسارت را وارد کنید!!!"), + value: number().required("لطفا میزان خسارت را وارد کنید!!!"), + amount: number().required("لطفا هزینه خسارت را وارد کنید!!!"), +}); +const defaultValues = { + id: null, + value: null, + amount: null, +}; +const DamageItem = ({ baseOnChange, baseDamageItems }) => { + const flattenBaseDamageItems = (items) => { + return items.map((item) => ({ + id: item.id, + title: item.title, + unit: item.unit, + base_price: item.base_price, + status: item.status, + until_27_shahrivar: item.until_27_shahrivar, + ...item.pivot, // اضافه کردن مقادیر موجود در pivot به سطح بالا + })); + }; + const [selectedDamageItemList, setSelectedDamageItemList] = useState( + baseDamageItems.length !== 0 ? flattenBaseDamageItems(baseDamageItems) : [] + ); + const { damageItemList, loadingDamageItemList, errorDamageItemList } = useDamageItemList(); + const { control, handleSubmit, reset, setValue } = useForm({ + defaultValues, + resolver: yupResolver(schema), + mode: "all", + }); + const deleteDamageItem = (id) => { + setSelectedDamageItemList((prev) => prev.filter((DamageItem) => DamageItem.id !== id)); + }; + useEffect(() => { + baseOnChange(selectedDamageItemList); + }, [selectedDamageItemList]); + const handleCreateDamage = (data) => { + setSelectedDamageItemList((prev) => { + const isDuplicate = prev.some((item) => item.id === data.id); + if (!isDuplicate) { + return [...prev, data]; + } else { + return prev; + } + }); + reset(); + }; + + return ( + <> + + {loadingDamageItemList ? ( + + + + ) : ( + <> + + ( + option.title} + isOptionEqualToValue={(option, value) => option.id === value.id} + loading={loadingDamageItemList} + renderInput={(params) => ( + + )} + onChange={(_, value) => field.onChange(value?.id)} + value={damageItemList.find((item) => item.id === field.value) || null} + /> + )} + /> + + + + + + + + + + + )} + + + + + {selectedDamageItemList.length === 0 && ( + + + ابتدا اطلاعات بالا را تکمیل نمایید + + + )} + + + {loadingDamageItemList ? ( + + + + ) : ( + selectedDamageItemList.length !== 0 && + selectedDamageItemList.map((selectedDamageItem, index) => ( + + + + )) + )} + + + + ); +}; +export default DamageItem; diff --git a/src/components/dashboard/damages/operator/Actions/create/Forms/DamageItemInfo.jsx b/src/components/dashboard/damages/operator/Actions/create/Forms/DamageItemInfo.jsx index ca95574..32118ba 100644 --- a/src/components/dashboard/damages/operator/Actions/create/Forms/DamageItemInfo.jsx +++ b/src/components/dashboard/damages/operator/Actions/create/Forms/DamageItemInfo.jsx @@ -1,60 +1,60 @@ -import { Box, Card, IconButton, Stack, Typography } from "@mui/material"; -import DeleteIcon from "@mui/icons-material/Delete"; -import React from "react"; -import MinorCrashIcon from "@mui/icons-material/MinorCrash"; - -const DamageItemInfo = ({ deleteDamageItem, selectedDamageItem, damageItemList }) => { - const itemDamageId = damageItemList.find((item) => item.id == selectedDamageItem.id); - return ( - - - - - - {itemDamageId.title} - - - - میزان خسارت ({itemDamageId.unit}) :{" "} - - {(selectedDamageItem.value / 1).toLocaleString()} - - - - - هزینه خسارت (ریال) :{" "} - - {(selectedDamageItem.amount / 1).toLocaleString()} - - - - - - - deleteDamageItem(selectedDamageItem.id)}> - - - - - ); -}; -export default DamageItemInfo; +import { Box, Card, IconButton, Stack, Typography } from "@mui/material"; +import DeleteIcon from "@mui/icons-material/Delete"; +import React from "react"; +import MinorCrashIcon from "@mui/icons-material/MinorCrash"; + +const DamageItemInfo = ({ deleteDamageItem, selectedDamageItem, damageItemList }) => { + const itemDamageId = damageItemList.find((item) => item.id == selectedDamageItem.id); + return ( + + + + + + {itemDamageId.title} + + + + میزان خسارت ({itemDamageId.unit}) :{" "} + + {(selectedDamageItem.value / 1).toLocaleString()} + + + + + هزینه خسارت (ریال) :{" "} + + {(selectedDamageItem.amount / 1).toLocaleString()} + + + + + + + deleteDamageItem(selectedDamageItem.id)}> + + + + + ); +}; +export default DamageItemInfo; diff --git a/src/components/dashboard/damages/operator/Actions/create/Forms/DamagePrice.jsx b/src/components/dashboard/damages/operator/Actions/create/Forms/DamagePrice.jsx index 96ff80a..3b0ca45 100644 --- a/src/components/dashboard/damages/operator/Actions/create/Forms/DamagePrice.jsx +++ b/src/components/dashboard/damages/operator/Actions/create/Forms/DamagePrice.jsx @@ -1,48 +1,48 @@ -import { Controller, useWatch } from "react-hook-form"; -import { Grid, TextField } from "@mui/material"; -import DamageAmount from "./DamageAmount"; - -const DamagePrice = ({ damageItemList, control, setValue }) => { - const itemDamage = useWatch({ control, name: "id" }); - const itemDamageId = damageItemList.find((damageItem) => damageItem.id === itemDamage); - - return ( - <> - - { - return ( - { - const inputValue = event.target.value; - if (isNaN(Number(inputValue))) { - return; - } - field.onChange(inputValue); - }} - label={`میزان خسارت ${itemDamageId?.unit ? `(${itemDamageId?.unit})` : ""}`} - fullWidth - size="small" - error={error} - helperText={error?.message} - /> - ); - }} - /> - - - - ); -}; -export default DamagePrice; +import { Controller, useWatch } from "react-hook-form"; +import { Grid, TextField } from "@mui/material"; +import DamageAmount from "./DamageAmount"; + +const DamagePrice = ({ damageItemList, control, setValue }) => { + const itemDamage = useWatch({ control, name: "id" }); + const itemDamageId = damageItemList.find((damageItem) => damageItem.id === itemDamage); + + return ( + <> + + { + return ( + { + const inputValue = event.target.value; + if (isNaN(Number(inputValue))) { + return; + } + field.onChange(inputValue); + }} + label={`میزان خسارت ${itemDamageId?.unit ? `(${itemDamageId?.unit})` : ""}`} + fullWidth + size="small" + error={error} + helperText={error?.message} + /> + ); + }} + /> + + + + ); +}; +export default DamagePrice; diff --git a/src/components/dashboard/damages/operator/Actions/create/Forms/DamageReport.jsx b/src/components/dashboard/damages/operator/Actions/create/Forms/DamageReport.jsx index d994aff..857a6f6 100644 --- a/src/components/dashboard/damages/operator/Actions/create/Forms/DamageReport.jsx +++ b/src/components/dashboard/damages/operator/Actions/create/Forms/DamageReport.jsx @@ -1,51 +1,51 @@ -import { FormControlLabel, RadioGroup, Stack } from "@mui/material"; -import { Controller, useWatch } from "react-hook-form"; -import { useState } from "react"; -import PoliceFileReport from "./PoliceFileReport"; -import Radio from "@mui/material/Radio"; - -const DamageReport = ({ control }) => { - const watchedStatus = useWatch({ control, name: "radio_button" }); - const [selectedOption, setSelectedOption] = useState(watchedStatus || null); - // const [selectedOption, setSelectedOption] = useState("report_base"); - - const handleOptionChange = (e) => { - setSelectedOption(e.target.value); - }; - - return ( - <> - - - } - /> - } - label="بازدید عوامل و کارشناسان راهداری" - /> - } - /> - } - label="کروکی یا نامه پلیس راه (معرفی فرد به اداره)" - /> - - - {selectedOption === "police_file_checkbox" && } - - ); -}; -export default DamageReport; +import { FormControlLabel, RadioGroup, Stack } from "@mui/material"; +import { Controller, useWatch } from "react-hook-form"; +import { useState } from "react"; +import PoliceFileReport from "./PoliceFileReport"; +import Radio from "@mui/material/Radio"; + +const DamageReport = ({ control }) => { + const watchedStatus = useWatch({ control, name: "radio_button" }); + const [selectedOption, setSelectedOption] = useState(watchedStatus || null); + // const [selectedOption, setSelectedOption] = useState("report_base"); + + const handleOptionChange = (e) => { + setSelectedOption(e.target.value); + }; + + return ( + <> + + + } + /> + } + label="بازدید عوامل و کارشناسان راهداری" + /> + } + /> + } + label="کروکی یا نامه پلیس راه (معرفی فرد به اداره)" + /> + + + {selectedOption === "police_file_checkbox" && } + + ); +}; +export default DamageReport; diff --git a/src/components/dashboard/damages/operator/Actions/create/Forms/ImageUpload.jsx b/src/components/dashboard/damages/operator/Actions/create/Forms/ImageUpload.jsx index 5186a4b..7697cfb 100644 --- a/src/components/dashboard/damages/operator/Actions/create/Forms/ImageUpload.jsx +++ b/src/components/dashboard/damages/operator/Actions/create/Forms/ImageUpload.jsx @@ -1,77 +1,77 @@ -import { FormControl, FormHelperText } from "@mui/material"; -import UploadSystem from "@/core/components/UploadSystem"; -import React, { useEffect, useState } from "react"; - -const ImageUpload = ({ name, value, onChange, error, title }) => { - const [beforeImg, setBeforeImg] = useState(value ? value : null); - const [beforeFileType, setBeforeFileType] = useState(value ? "image/" : null); - const [beforeFileName, setBeforeFileName] = useState(null); - const [showBeforeImage, setShowBeforeImage] = useState(!value); - - useEffect(() => { - if (value) { - setShowBeforeImage(false); - if (typeof value === "string") { - setBeforeImg(value); - setBeforeFileType("image/"); - } else if (value instanceof File) { - setBeforeImg(URL.createObjectURL(value)); - setBeforeFileType(value.type); - } - } - }, [value]); - - const handleFileChange = (event) => { - const uploadedFile = event.target?.files?.[0]; - if (uploadedFile) { - const fileType = event.target?.files?.[0].type; - const fileName = event.target?.files?.[0].name; - setBeforeImg(URL.createObjectURL(uploadedFile)); - setBeforeFileType(fileType); - setBeforeFileName(fileName); - onChange(uploadedFile); - setShowBeforeImage(false); - } - }; - - return ( - - - {title} - - - {error ? error.message : null} - - ); -}; -export default ImageUpload; +import { FormControl, FormHelperText } from "@mui/material"; +import UploadSystem from "@/core/components/UploadSystem"; +import React, { useEffect, useState } from "react"; + +const ImageUpload = ({ name, value, onChange, error, title }) => { + const [beforeImg, setBeforeImg] = useState(value ? value : null); + const [beforeFileType, setBeforeFileType] = useState(value ? "image/" : null); + const [beforeFileName, setBeforeFileName] = useState(null); + const [showBeforeImage, setShowBeforeImage] = useState(!value); + + useEffect(() => { + if (value) { + setShowBeforeImage(false); + if (typeof value === "string") { + setBeforeImg(value); + setBeforeFileType("image/"); + } else if (value instanceof File) { + setBeforeImg(URL.createObjectURL(value)); + setBeforeFileType(value.type); + } + } + }, [value]); + + const handleFileChange = (event) => { + const uploadedFile = event.target?.files?.[0]; + if (uploadedFile) { + const fileType = event.target?.files?.[0].type; + const fileName = event.target?.files?.[0].name; + setBeforeImg(URL.createObjectURL(uploadedFile)); + setBeforeFileType(fileType); + setBeforeFileName(fileName); + onChange(uploadedFile); + setShowBeforeImage(false); + } + }; + + return ( + + + {title} + + + {error ? error.message : null} + + ); +}; +export default ImageUpload; diff --git a/src/components/dashboard/damages/operator/Actions/create/Forms/LogesticController.jsx b/src/components/dashboard/damages/operator/Actions/create/Forms/LogesticController.jsx index a53059b..cb6bf31 100644 --- a/src/components/dashboard/damages/operator/Actions/create/Forms/LogesticController.jsx +++ b/src/components/dashboard/damages/operator/Actions/create/Forms/LogesticController.jsx @@ -1,64 +1,64 @@ -import { Controller, useWatch } from "react-hook-form"; -import SelectBox from "@/core/components/SelectBox"; -import useProvinces from "@/lib/hooks/useProvince"; -import { Grid } from "@mui/material"; -import CityController from "./CityController"; -import PersianTextField from "@/core/components/PersianTextField"; - -const LogesticController = ({ control }) => { - const { provinces, errorProvinces, loadingProvinces } = useProvinces(); - const isProvince = useWatch({ control, name: "is_province" }); - return ( - - {!isProvince ? ( - - { - return ( - - ); - }} - /> - - ) : null} - - - - - ( - - )} - /> - - - ); -}; -export default LogesticController; +import { Controller, useWatch } from "react-hook-form"; +import SelectBox from "@/core/components/SelectBox"; +import useProvinces from "@/lib/hooks/useProvince"; +import { Grid } from "@mui/material"; +import CityController from "./CityController"; +import PersianTextField from "@/core/components/PersianTextField"; + +const LogesticController = ({ control }) => { + const { provinces, errorProvinces, loadingProvinces } = useProvinces(); + const isProvince = useWatch({ control, name: "is_province" }); + return ( + + {!isProvince ? ( + + { + return ( + + ); + }} + /> + + ) : null} + + + + + ( + + )} + /> + + + ); +}; +export default LogesticController; diff --git a/src/components/dashboard/damages/operator/Actions/create/Forms/PoliceFileReport.jsx b/src/components/dashboard/damages/operator/Actions/create/Forms/PoliceFileReport.jsx index 64f1067..524f5f5 100644 --- a/src/components/dashboard/damages/operator/Actions/create/Forms/PoliceFileReport.jsx +++ b/src/components/dashboard/damages/operator/Actions/create/Forms/PoliceFileReport.jsx @@ -1,67 +1,67 @@ -import { Controller } from "react-hook-form"; -import { Grid, Stack, TextField } from "@mui/material"; -import MuiDatePicker from "@/core/components/MuiDatePicker"; -import ImageUpload from "./ImageUpload"; - -const PoliceFileReport = ({ control }) => { - return ( - - - - - ( - - )} - /> - - - { - return ( - field.onChange(value || [])} - helperText={error ? error.message : null} - /> - ); - }} - name={"police_file_date"} - /> - - - - { - return ( - - ); - }} - /> - - ); -}; -export default PoliceFileReport; +import { Controller } from "react-hook-form"; +import { Grid, Stack, TextField } from "@mui/material"; +import MuiDatePicker from "@/core/components/MuiDatePicker"; +import ImageUpload from "./ImageUpload"; + +const PoliceFileReport = ({ control }) => { + return ( + + + + + ( + + )} + /> + + + { + return ( + field.onChange(value || [])} + helperText={error ? error.message : null} + /> + ); + }} + name={"police_file_date"} + /> + + + + { + return ( + + ); + }} + /> + + ); +}; +export default PoliceFileReport; diff --git a/src/components/dashboard/damages/operator/Actions/create/Forms/index.jsx b/src/components/dashboard/damages/operator/Actions/create/Forms/index.jsx index 8624134..eea9507 100644 --- a/src/components/dashboard/damages/operator/Actions/create/Forms/index.jsx +++ b/src/components/dashboard/damages/operator/Actions/create/Forms/index.jsx @@ -1,112 +1,112 @@ -"use client"; -import { Dialog, IconButton } from "@mui/material"; -import CreateFormContent from "./CreateFormContent"; -import { format } from "date-fns"; -import { CREATE_DAMAGE } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import CloseIcon from "@mui/icons-material/Close"; -import { usePermissions } from "@/lib/hooks/usePermissions"; -import { useAuth } from "@/lib/contexts/auth"; - -const OperatorCreateForm = ({ open, setOpen, mutate }) => { - const requestServer = useRequest({ notificationSuccess: true }); - const { user } = useAuth(); - const { data: userPermissions } = usePermissions(); - const hasCreateProvincePermission = userPermissions.some((item) => ["add-receipt"].includes(item)); - const SubmitCreateDamage = async (result) => { - const PlateNumber = `${result.plate_part1}-${result.plate_part2}-${result.plate_part3}-${result.plate_part4}`; - const formData = new FormData(); - formData.append("accident_date", result.accident_date); - formData.append("accident_time", format(new Date(result.accident_time), "HH:mm")); - formData.append("accident_type", result.accident_type); - formData.append("province_id", result.province_id); - formData.append("city_id", result.city_id); - formData.append("axis_name", result.axis_name); - formData.append("is_foreign", result.isForeign); - if (result.isForeign == "0") { - formData.append("driver_name", result.driver_name); - formData.append("driver_phone_number", result.phone_number); - formData.append("driver_national_code", result.national_code); - formData.append("plaque", PlateNumber); - } - formData.append("damage_picture1", result.damage_picture1); - formData.append("damage_picture2", result.damage_picture2); - formData.append("lat", result.start_point.lat); - formData.append("lng", result.start_point.lng); - result.items_damage.map((item, index) => { - formData.append(`damage_items[${index}][id]`, item.id); - formData.append(`damage_items[${index}][value]`, item.value); - formData.append(`damage_items[${index}][amount]`, item.amount); - }); - if (result.radio_button === "report_base") { - formData.append("report_base", 1); - } - if (result.radio_button === "police_file_checkbox") { - formData.append("report_base", 0); - formData.append("police_file", result.police_file); - formData.append("police_file_date", result.police_file_date); - formData.append("police_serial", result.police_serial); - } - await requestServer(`${CREATE_DAMAGE}`, "post", { - data: formData, - }) - .then(() => { - mutate(); - setOpen(false); - }) - .catch(() => {}); - }; - const defaultData = { - isForeign: "0", - accident_date: "", - accident_time: "", - accident_type: "", - province_id: !hasCreateProvincePermission ? user.province_id : null, - is_province: !hasCreateProvincePermission, - city_id: null, - axis_name: "", - driver_name: "", - phone_number: "", - national_code: "", - plate_part1: "", - plate_part2: "الف", - plate_part3: "", - plate_part4: "", - radio_button: "report_base", - damage_picture1: null, - damage_picture2: null, - report_base: "", - police_file_checkbox: "", - police_file: null, - police_file_date: "", - police_serial: "", - start_point: "", - items_damage: [], - }; - return ( - - setOpen(false)} - sx={(theme) => ({ - position: "absolute", - right: 8, - top: 8, - zIndex: 50, - color: theme.palette.grey[500], - })} - > - - - {open && ( - - )} - - ); -}; -export default OperatorCreateForm; +"use client"; +import { Dialog, IconButton } from "@mui/material"; +import CreateFormContent from "./CreateFormContent"; +import { format } from "date-fns"; +import { CREATE_DAMAGE } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import CloseIcon from "@mui/icons-material/Close"; +import { usePermissions } from "@/lib/hooks/usePermissions"; +import { useAuth } from "@/lib/contexts/auth"; + +const OperatorCreateForm = ({ open, setOpen, mutate }) => { + const requestServer = useRequest({ notificationSuccess: true }); + const { user } = useAuth(); + const { data: userPermissions } = usePermissions(); + const hasCreateProvincePermission = userPermissions.some((item) => ["add-receipt"].includes(item)); + const SubmitCreateDamage = async (result) => { + const PlateNumber = `${result.plate_part1}-${result.plate_part2}-${result.plate_part3}-${result.plate_part4}`; + const formData = new FormData(); + formData.append("accident_date", result.accident_date); + formData.append("accident_time", format(new Date(result.accident_time), "HH:mm")); + formData.append("accident_type", result.accident_type); + formData.append("province_id", result.province_id); + formData.append("city_id", result.city_id); + formData.append("axis_name", result.axis_name); + formData.append("is_foreign", result.isForeign); + if (result.isForeign == "0") { + formData.append("driver_name", result.driver_name); + formData.append("driver_phone_number", result.phone_number); + formData.append("driver_national_code", result.national_code); + formData.append("plaque", PlateNumber); + } + formData.append("damage_picture1", result.damage_picture1); + formData.append("damage_picture2", result.damage_picture2); + formData.append("lat", result.start_point.lat); + formData.append("lng", result.start_point.lng); + result.items_damage.map((item, index) => { + formData.append(`damage_items[${index}][id]`, item.id); + formData.append(`damage_items[${index}][value]`, item.value); + formData.append(`damage_items[${index}][amount]`, item.amount); + }); + if (result.radio_button === "report_base") { + formData.append("report_base", 1); + } + if (result.radio_button === "police_file_checkbox") { + formData.append("report_base", 0); + formData.append("police_file", result.police_file); + formData.append("police_file_date", result.police_file_date); + formData.append("police_serial", result.police_serial); + } + await requestServer(`${CREATE_DAMAGE}`, "post", { + data: formData, + }) + .then(() => { + mutate(); + setOpen(false); + }) + .catch(() => {}); + }; + const defaultData = { + isForeign: "0", + accident_date: "", + accident_time: "", + accident_type: "", + province_id: !hasCreateProvincePermission ? user.province_id : null, + is_province: !hasCreateProvincePermission, + city_id: null, + axis_name: "", + driver_name: "", + phone_number: "", + national_code: "", + plate_part1: "", + plate_part2: "الف", + plate_part3: "", + plate_part4: "", + radio_button: "report_base", + damage_picture1: null, + damage_picture2: null, + report_base: "", + police_file_checkbox: "", + police_file: null, + police_file_date: "", + police_serial: "", + start_point: "", + items_damage: [], + }; + return ( + + setOpen(false)} + sx={(theme) => ({ + position: "absolute", + right: 8, + top: 8, + zIndex: 50, + color: theme.palette.grey[500], + })} + > + + + {open && ( + + )} + + ); +}; +export default OperatorCreateForm; diff --git a/src/components/dashboard/damages/operator/Actions/create/index.jsx b/src/components/dashboard/damages/operator/Actions/create/index.jsx index 5816c12..2e1c0e9 100644 --- a/src/components/dashboard/damages/operator/Actions/create/index.jsx +++ b/src/components/dashboard/damages/operator/Actions/create/index.jsx @@ -1,38 +1,38 @@ -"use client"; -import { Button, IconButton, useMediaQuery } from "@mui/material"; -import { useTheme } from "@emotion/react"; -import { useState } from "react"; -import { AddCircle } from "@mui/icons-material"; -import OperatorCreateForm from "./Forms"; - -const OperatorCreate = ({ mutate }) => { - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const [open, setOpen] = useState(false); - - const handleOpen = () => { - setOpen(true); - }; - - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - - - ); -}; -export default OperatorCreate; +"use client"; +import { Button, IconButton, useMediaQuery } from "@mui/material"; +import { useTheme } from "@emotion/react"; +import { useState } from "react"; +import { AddCircle } from "@mui/icons-material"; +import OperatorCreateForm from "./Forms"; + +const OperatorCreate = ({ mutate }) => { + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const [open, setOpen] = useState(false); + + const handleOpen = () => { + setOpen(true); + }; + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + + + ); +}; +export default OperatorCreate; diff --git a/src/components/dashboard/damages/operator/ExcelPrint/index.jsx b/src/components/dashboard/damages/operator/ExcelPrint/index.jsx index f38d451..096389f 100644 --- a/src/components/dashboard/damages/operator/ExcelPrint/index.jsx +++ b/src/components/dashboard/damages/operator/ExcelPrint/index.jsx @@ -1,75 +1,75 @@ -"use client"; -import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; -import { useMemo, useState } from "react"; -import moment from "jalali-moment"; -import FileSaver from "file-saver"; -import DescriptionIcon from "@mui/icons-material/Description"; -import useRequest from "@/lib/hooks/useRequest"; -import { useTheme } from "@emotion/react"; -import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; -import isArrayEmpty from "@/core/utils/isArrayEmpty"; -import { EXPORT_DAMAGES_OPERATOR_LIST } from "@/core/utils/routes"; - -const PrintExcel = ({ table, filterData }) => { - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const [loading, setLoading] = useState(false); - const requestServer = useRequest({ notificationSuccess: true }); - const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { - if (filter.value && (!Array.isArray(filter.value) || filter.value.some((item) => item.trim() !== ""))) { - acc.push({ id: key, value: filter.value }); - } - return acc; - }, []); - - const filterParams = useMemo(() => { - const params = new URLSearchParams(); - if (activeFilters.length > 0) { - activeFilters.map((filter, index) => { - const filteredFilterData = DataTableFilterDataStructure(filterData, isArrayEmpty); - params.set("filters", JSON.stringify(filteredFilterData.length === 0 ? [] : filteredFilterData)); - }); - } else { - params.set("filters", JSON.stringify([])); - } - return params; - }, [activeFilters]); - - const clickHandler = () => { - setLoading(true); - requestServer(`${EXPORT_DAMAGES_OPERATOR_LIST}?${filterParams}`, "get", { - requestOptions: { responseType: "blob" }, - }) - .then((response) => { - const filename = `خروجی کارتابل عملیات فعالیت روزانه تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; - FileSaver.saveAs(response.data, filename); - }) - .catch(() => {}) - .finally(() => { - setLoading(false); - }); - }; - - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - - ); -}; -export default PrintExcel; +"use client"; +import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; +import { useMemo, useState } from "react"; +import moment from "jalali-moment"; +import FileSaver from "file-saver"; +import DescriptionIcon from "@mui/icons-material/Description"; +import useRequest from "@/lib/hooks/useRequest"; +import { useTheme } from "@emotion/react"; +import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; +import isArrayEmpty from "@/core/utils/isArrayEmpty"; +import { EXPORT_DAMAGES_OPERATOR_LIST } from "@/core/utils/routes"; + +const PrintExcel = ({ table, filterData }) => { + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const [loading, setLoading] = useState(false); + const requestServer = useRequest({ notificationSuccess: true }); + const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { + if (filter.value && (!Array.isArray(filter.value) || filter.value.some((item) => item.trim() !== ""))) { + acc.push({ id: key, value: filter.value }); + } + return acc; + }, []); + + const filterParams = useMemo(() => { + const params = new URLSearchParams(); + if (activeFilters.length > 0) { + activeFilters.map((filter, index) => { + const filteredFilterData = DataTableFilterDataStructure(filterData, isArrayEmpty); + params.set("filters", JSON.stringify(filteredFilterData.length === 0 ? [] : filteredFilterData)); + }); + } else { + params.set("filters", JSON.stringify([])); + } + return params; + }, [activeFilters]); + + const clickHandler = () => { + setLoading(true); + requestServer(`${EXPORT_DAMAGES_OPERATOR_LIST}?${filterParams}`, "get", { + requestOptions: { responseType: "blob" }, + }) + .then((response) => { + const filename = `خروجی کارتابل عملیات فعالیت روزانه تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; + FileSaver.saveAs(response.data, filename); + }) + .catch(() => {}) + .finally(() => { + setLoading(false); + }); + }; + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + + ); +}; +export default PrintExcel; diff --git a/src/components/dashboard/damages/operator/Form/CreateFactor/CreateFactorContent.jsx b/src/components/dashboard/damages/operator/Form/CreateFactor/CreateFactorContent.jsx index 640e00c..b538199 100644 --- a/src/components/dashboard/damages/operator/Form/CreateFactor/CreateFactorContent.jsx +++ b/src/components/dashboard/damages/operator/Form/CreateFactor/CreateFactorContent.jsx @@ -1,219 +1,219 @@ -import { CHECK_PAYMENT_STATUS, CREATE_FACTOR_DAMAGE, SEND_SMS_AGAIN } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import PaymentIcon from "@mui/icons-material/Payment"; -import ReceiptLongIcon from "@mui/icons-material/ReceiptLong"; -import RequestQuoteIcon from "@mui/icons-material/RequestQuote"; -import WebAssetIcon from "@mui/icons-material/WebAsset"; -import { - Alert, - Box, - Button, - Chip, - DialogActions, - DialogContent, - Divider, - Grid, - Stack, - Typography, -} from "@mui/material"; -import { useReducer, useState } from "react"; - -const initialState = { - submittingCreateFactor: false, - submittingCheckFactor: false, - submittingSms: false, -}; - -const reducer = (state, action) => { - switch (action.type) { - case "SET_SUBMITTING_CREATE_FACTOR": - return { ...state, submittingCreateFactor: action.payload }; - case "SET_SUBMITTING_CHECK_FACTOR": - return { ...state, submittingCheckFactor: action.payload }; - case "SET_SUBMITTING_SMS": - return { ...state, submittingSms: action.payload }; - default: - return state; - } -}; -const CreateFactorContent = ({ row, mutate, rowId, setOpenCreateFactorDialog }) => { - const [state, dispatch] = useReducer(reducer, initialState); - const requestServer = useRequest({ notificationSuccess: true }); - const [factorCreated, setFactorCreated] = useState(row.original?.status === 3); - const handleCreateFactor = () => { - dispatch({ type: "SET_SUBMITTING_CREATE_FACTOR", payload: true }); - requestServer(`${CREATE_FACTOR_DAMAGE}/${rowId}`, "get") - .then(() => { - mutate(); - dispatch({ type: "SET_SUBMITTING_CREATE_FACTOR", payload: false }); - setFactorCreated(true); - }) - .catch(() => { - dispatch({ type: "SET_SUBMITTING_CREATE_FACTOR", payload: false }); - }); - }; - const handleCheckPaymentStatus = () => { - dispatch({ type: "SET_SUBMITTING_CHECK_FACTOR", payload: true }); - requestServer(`${CHECK_PAYMENT_STATUS}/${rowId}`, "get") - .then(() => { - setOpenCreateFactorDialog(false); - mutate(); - dispatch({ type: "SET_SUBMITTING_CHECK_FACTOR", payload: false }); - }) - .catch(() => { - dispatch({ type: "SET_SUBMITTING_CHECK_FACTOR", payload: false }); - }); - }; - const handleSendSMS = () => { - dispatch({ type: "SET_SUBMITTING_SMS", payload: true }); - requestServer(`${SEND_SMS_AGAIN}/${rowId}`, "get") - .then(() => { - dispatch({ type: "SET_SUBMITTING_SMS", payload: false }); - }) - .catch(() => { - dispatch({ type: "SET_SUBMITTING_SMS", payload: false }); - }); - }; - - return ( - <> - - - - - } - label={ - - مبلغ کل خسارت برآورد شده - - } - /> - - - - {(row.original?.sum / 1).toLocaleString() || "0"} ریال - - - - - } - label={ - - مبلغ کسری بیمه - - } - /> - - - - {(row.original?.deposit_insurance_amount / 1).toLocaleString() || "0"} ریال - - - - - } - label={ - - مبلغ کسری داغی - - } - /> - - - - {(row.original?.deposit_daghi_amount / 1).toLocaleString() || "0"} ریال - - - - - } - label={ - - مبلغ قابل پرداخت - - } - /> - - - - {( - row.original?.sum - - (row.original?.deposit_insurance_amount + row.original?.deposit_daghi_amount) - ).toLocaleString() || "0"}{" "} - ریال - - - {!factorCreated && ( - - - - پس از صدور فاکتور، امکان ویرایش مبالغ بیمه و داغی وجود نخواهد داشت - - - لینک پرداخت فاکتور به شماره {row.original?.driver_phone_number} ارسال می شود. - - - - )} - - - - {factorCreated ? ( - <> - - - - - ) : ( - <> - - - - )} - - - ); -}; -export default CreateFactorContent; +import { CHECK_PAYMENT_STATUS, CREATE_FACTOR_DAMAGE, SEND_SMS_AGAIN } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import PaymentIcon from "@mui/icons-material/Payment"; +import ReceiptLongIcon from "@mui/icons-material/ReceiptLong"; +import RequestQuoteIcon from "@mui/icons-material/RequestQuote"; +import WebAssetIcon from "@mui/icons-material/WebAsset"; +import { + Alert, + Box, + Button, + Chip, + DialogActions, + DialogContent, + Divider, + Grid, + Stack, + Typography, +} from "@mui/material"; +import { useReducer, useState } from "react"; + +const initialState = { + submittingCreateFactor: false, + submittingCheckFactor: false, + submittingSms: false, +}; + +const reducer = (state, action) => { + switch (action.type) { + case "SET_SUBMITTING_CREATE_FACTOR": + return { ...state, submittingCreateFactor: action.payload }; + case "SET_SUBMITTING_CHECK_FACTOR": + return { ...state, submittingCheckFactor: action.payload }; + case "SET_SUBMITTING_SMS": + return { ...state, submittingSms: action.payload }; + default: + return state; + } +}; +const CreateFactorContent = ({ row, mutate, rowId, setOpenCreateFactorDialog }) => { + const [state, dispatch] = useReducer(reducer, initialState); + const requestServer = useRequest({ notificationSuccess: true }); + const [factorCreated, setFactorCreated] = useState(row.original?.status === 3); + const handleCreateFactor = () => { + dispatch({ type: "SET_SUBMITTING_CREATE_FACTOR", payload: true }); + requestServer(`${CREATE_FACTOR_DAMAGE}/${rowId}`, "get") + .then(() => { + mutate(); + dispatch({ type: "SET_SUBMITTING_CREATE_FACTOR", payload: false }); + setFactorCreated(true); + }) + .catch(() => { + dispatch({ type: "SET_SUBMITTING_CREATE_FACTOR", payload: false }); + }); + }; + const handleCheckPaymentStatus = () => { + dispatch({ type: "SET_SUBMITTING_CHECK_FACTOR", payload: true }); + requestServer(`${CHECK_PAYMENT_STATUS}/${rowId}`, "get") + .then(() => { + setOpenCreateFactorDialog(false); + mutate(); + dispatch({ type: "SET_SUBMITTING_CHECK_FACTOR", payload: false }); + }) + .catch(() => { + dispatch({ type: "SET_SUBMITTING_CHECK_FACTOR", payload: false }); + }); + }; + const handleSendSMS = () => { + dispatch({ type: "SET_SUBMITTING_SMS", payload: true }); + requestServer(`${SEND_SMS_AGAIN}/${rowId}`, "get") + .then(() => { + dispatch({ type: "SET_SUBMITTING_SMS", payload: false }); + }) + .catch(() => { + dispatch({ type: "SET_SUBMITTING_SMS", payload: false }); + }); + }; + + return ( + <> + + + + + } + label={ + + مبلغ کل خسارت برآورد شده + + } + /> + + + + {(row.original?.sum / 1).toLocaleString() || "0"} ریال + + + + + } + label={ + + مبلغ کسری بیمه + + } + /> + + + + {(row.original?.deposit_insurance_amount / 1).toLocaleString() || "0"} ریال + + + + + } + label={ + + مبلغ کسری داغی + + } + /> + + + + {(row.original?.deposit_daghi_amount / 1).toLocaleString() || "0"} ریال + + + + + } + label={ + + مبلغ قابل پرداخت + + } + /> + + + + {( + row.original?.sum - + (row.original?.deposit_insurance_amount + row.original?.deposit_daghi_amount) + ).toLocaleString() || "0"}{" "} + ریال + + + {!factorCreated && ( + + + + پس از صدور فاکتور، امکان ویرایش مبالغ بیمه و داغی وجود نخواهد داشت + + + لینک پرداخت فاکتور به شماره {row.original?.driver_phone_number} ارسال می شود. + + + + )} + + + + {factorCreated ? ( + <> + + + + + ) : ( + <> + + + + )} + + + ); +}; +export default CreateFactorContent; diff --git a/src/components/dashboard/damages/operator/Form/CreateFactor/index.jsx b/src/components/dashboard/damages/operator/Form/CreateFactor/index.jsx index 86804a7..43ae1d6 100644 --- a/src/components/dashboard/damages/operator/Form/CreateFactor/index.jsx +++ b/src/components/dashboard/damages/operator/Form/CreateFactor/index.jsx @@ -1,43 +1,43 @@ -import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import ReceiptLongIcon from "@mui/icons-material/ReceiptLong"; -import CreateFactorContent from "./CreateFactorContent"; - -const CreateFactor = ({ row, rowId, mutate }) => { - const [openCreateFactorDialog, setOpenCreateFactorDialog] = useState(false); - - return ( - <> - - setOpenCreateFactorDialog(true)}> - - - - setOpenCreateFactorDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - maxWidth={"sm"} - scroll="paper" - > - - {row.original?.status == 2 ? "صدور فاکتور" : "استعلام پرداخت"} - - {openCreateFactorDialog && ( - - )} - - - ); -}; -export default CreateFactor; +import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import ReceiptLongIcon from "@mui/icons-material/ReceiptLong"; +import CreateFactorContent from "./CreateFactorContent"; + +const CreateFactor = ({ row, rowId, mutate }) => { + const [openCreateFactorDialog, setOpenCreateFactorDialog] = useState(false); + + return ( + <> + + setOpenCreateFactorDialog(true)}> + + + + setOpenCreateFactorDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + maxWidth={"sm"} + scroll="paper" + > + + {row.original?.status == 2 ? "صدور فاکتور" : "استعلام پرداخت"} + + {openCreateFactorDialog && ( + + )} + + + ); +}; +export default CreateFactor; diff --git a/src/components/dashboard/damages/operator/Form/EditForm/EditController.jsx b/src/components/dashboard/damages/operator/Form/EditForm/EditController.jsx index c925cdf..1bbfb03 100644 --- a/src/components/dashboard/damages/operator/Form/EditForm/EditController.jsx +++ b/src/components/dashboard/damages/operator/Form/EditForm/EditController.jsx @@ -1,123 +1,123 @@ -import useRequest from "@/lib/hooks/useRequest"; -import CreateFormContent from "@/components/dashboard/damages/operator/Actions/create/Forms/CreateFormContent"; -import { useEffect, useState } from "react"; -import { GET_DAMAGE_ITEM_DETAILS, UPDATE_DAMAGE_ITEM } from "@/core/utils/routes"; -import DialogLoading from "@/core/components/DialogLoading"; -import { format } from "date-fns"; -import moment from "jalali-moment"; -import { useAuth } from "@/lib/contexts/auth"; -import { usePermissions } from "@/lib/hooks/usePermissions"; - -const EditController = ({ rowId, mutate, setOpenEditDialog }) => { - const requestServer = useRequest(); - const [damageItemDetails, setDamageItemDetails] = useState(null); - const [damageItemDetailsLoading, setDamageItemDetailsLoading] = useState(false); - const { user } = useAuth(); - const { data: userPermissions } = usePermissions(); - const hasCreateProvincePermission = userPermissions.some((item) => ["add-receipt"].includes(item)); - - useEffect(() => { - setDamageItemDetailsLoading(true); - requestServer(`${GET_DAMAGE_ITEM_DETAILS}/${rowId}`, "get") - .then((response) => { - setDamageItemDetails(response.data.data); - setDamageItemDetailsLoading(false); - }) - .catch((e) => { - setDamageItemDetailsLoading(false); - }); - }, [rowId]); - - const today = new Date().toISOString().split("T")[0]; - const plaqueNumber = damageItemDetails?.is_foreign == 0 ? damageItemDetails?.plaque.split("-") || [] : []; - const defaultData = { - isForeign: String(damageItemDetails?.is_foreign), - damage_picture1: damageItemDetails?.damage_picture1 || null, - damage_picture2: damageItemDetails?.damage_picture2 || null, - accident_date: new Date(damageItemDetails?.accident_date) || "", - accident_time: new Date(`${today} ${damageItemDetails?.accident_time || ""}`), - accident_type: damageItemDetails?.accident_type || "", - axis_name: damageItemDetails?.axis_name || "", - driver_name: damageItemDetails?.driver_name || "", - police_file: damageItemDetails?.police_file || null, - police_file_date: damageItemDetails?.police_file_date || "", - police_serial: damageItemDetails?.police_serial || "", - items_damage: damageItemDetails?.damages || [], - phone_number: damageItemDetails?.driver_phone_number || "", - national_code: damageItemDetails?.driver_national_code || "", - plate_part1: plaqueNumber[0] || "", - plate_part2: plaqueNumber[1] || "", - plate_part3: plaqueNumber[2] || "", - plate_part4: plaqueNumber[3] || "", - radio_button: damageItemDetails?.report_base === 1 ? "report_base" : "police_file_checkbox", - report_base: damageItemDetails?.report_base, - province_id: damageItemDetails?.province_id || null, - is_province: !hasCreateProvincePermission, - city_id: damageItemDetails?.city_id || null, - start_point: { lat: damageItemDetails?.lat || "", lng: damageItemDetails?.lng || "" }, - }; - const HandleSubmit = async (result) => { - const PlateNumber = `${result.plate_part1}-${result.plate_part2}-${result.plate_part3}-${result.plate_part4}`; - const formData = new FormData(); - const accidentDate = - result.accident_date == defaultData.accident_date - ? moment(result.accident_date).locale("en").format("YYYY-MM-DD") - : result.accident_date; - formData.append("accident_date", accidentDate); - formData.append("accident_time", format(new Date(result.accident_time), "HH:mm")); - formData.append("accident_type", result.accident_type); - formData.append("province_id", result.province_id); - formData.append("city_id", result.city_id); - formData.append("axis_name", result.axis_name); - formData.append("is_foreign", result.isForeign); - if (result.isForeign == "0") { - formData.append("driver_name", result.driver_name); - formData.append("driver_phone_number", result.phone_number); - formData.append("driver_national_code", result.national_code); - formData.append("plaque", PlateNumber); - } - result.damage_picture1 !== defaultData.damage_picture1 && - formData.append("damage_picture1", result.damage_picture1); - result.damage_picture2 !== defaultData.damage_picture2 && - formData.append("damage_picture2", result.damage_picture2); - formData.append("lat", result.start_point.lat); - formData.append("lng", result.start_point.lng); - result.items_damage.map((item, index) => { - formData.append(`damage_items[${index}][id]`, item.id); - formData.append(`damage_items[${index}][value]`, item.value); - formData.append(`damage_items[${index}][amount]`, item.amount); - }); - if (result.radio_button === "report_base") { - formData.append("report_base", 1); - } - if (result.radio_button === "police_file_checkbox") { - formData.append("report_base", 0); - result.police_file !== defaultData.police_file && formData.append("police_file", result.police_file); - formData.append("police_file_date", result.police_file_date); - formData.append("police_serial", result.police_serial); - } - await requestServer(`${UPDATE_DAMAGE_ITEM}/${rowId}`, "post", { - data: formData, - }) - .then(() => { - mutate(); - setOpenEditDialog(false); - }) - .catch(() => {}); - }; - return ( - <> - {damageItemDetailsLoading ? ( - - ) : ( - - )} - - ); -}; -export default EditController; +import useRequest from "@/lib/hooks/useRequest"; +import CreateFormContent from "@/components/dashboard/damages/operator/Actions/create/Forms/CreateFormContent"; +import { useEffect, useState } from "react"; +import { GET_DAMAGE_ITEM_DETAILS, UPDATE_DAMAGE_ITEM } from "@/core/utils/routes"; +import DialogLoading from "@/core/components/DialogLoading"; +import { format } from "date-fns"; +import moment from "jalali-moment"; +import { useAuth } from "@/lib/contexts/auth"; +import { usePermissions } from "@/lib/hooks/usePermissions"; + +const EditController = ({ rowId, mutate, setOpenEditDialog }) => { + const requestServer = useRequest(); + const [damageItemDetails, setDamageItemDetails] = useState(null); + const [damageItemDetailsLoading, setDamageItemDetailsLoading] = useState(false); + const { user } = useAuth(); + const { data: userPermissions } = usePermissions(); + const hasCreateProvincePermission = userPermissions.some((item) => ["add-receipt"].includes(item)); + + useEffect(() => { + setDamageItemDetailsLoading(true); + requestServer(`${GET_DAMAGE_ITEM_DETAILS}/${rowId}`, "get") + .then((response) => { + setDamageItemDetails(response.data.data); + setDamageItemDetailsLoading(false); + }) + .catch((e) => { + setDamageItemDetailsLoading(false); + }); + }, [rowId]); + + const today = new Date().toISOString().split("T")[0]; + const plaqueNumber = damageItemDetails?.is_foreign == 0 ? damageItemDetails?.plaque.split("-") || [] : []; + const defaultData = { + isForeign: String(damageItemDetails?.is_foreign), + damage_picture1: damageItemDetails?.damage_picture1 || null, + damage_picture2: damageItemDetails?.damage_picture2 || null, + accident_date: new Date(damageItemDetails?.accident_date) || "", + accident_time: new Date(`${today} ${damageItemDetails?.accident_time || ""}`), + accident_type: damageItemDetails?.accident_type || "", + axis_name: damageItemDetails?.axis_name || "", + driver_name: damageItemDetails?.driver_name || "", + police_file: damageItemDetails?.police_file || null, + police_file_date: damageItemDetails?.police_file_date || "", + police_serial: damageItemDetails?.police_serial || "", + items_damage: damageItemDetails?.damages || [], + phone_number: damageItemDetails?.driver_phone_number || "", + national_code: damageItemDetails?.driver_national_code || "", + plate_part1: plaqueNumber[0] || "", + plate_part2: plaqueNumber[1] || "", + plate_part3: plaqueNumber[2] || "", + plate_part4: plaqueNumber[3] || "", + radio_button: damageItemDetails?.report_base === 1 ? "report_base" : "police_file_checkbox", + report_base: damageItemDetails?.report_base, + province_id: damageItemDetails?.province_id || null, + is_province: !hasCreateProvincePermission, + city_id: damageItemDetails?.city_id || null, + start_point: { lat: damageItemDetails?.lat || "", lng: damageItemDetails?.lng || "" }, + }; + const HandleSubmit = async (result) => { + const PlateNumber = `${result.plate_part1}-${result.plate_part2}-${result.plate_part3}-${result.plate_part4}`; + const formData = new FormData(); + const accidentDate = + result.accident_date == defaultData.accident_date + ? moment(result.accident_date).locale("en").format("YYYY-MM-DD") + : result.accident_date; + formData.append("accident_date", accidentDate); + formData.append("accident_time", format(new Date(result.accident_time), "HH:mm")); + formData.append("accident_type", result.accident_type); + formData.append("province_id", result.province_id); + formData.append("city_id", result.city_id); + formData.append("axis_name", result.axis_name); + formData.append("is_foreign", result.isForeign); + if (result.isForeign == "0") { + formData.append("driver_name", result.driver_name); + formData.append("driver_phone_number", result.phone_number); + formData.append("driver_national_code", result.national_code); + formData.append("plaque", PlateNumber); + } + result.damage_picture1 !== defaultData.damage_picture1 && + formData.append("damage_picture1", result.damage_picture1); + result.damage_picture2 !== defaultData.damage_picture2 && + formData.append("damage_picture2", result.damage_picture2); + formData.append("lat", result.start_point.lat); + formData.append("lng", result.start_point.lng); + result.items_damage.map((item, index) => { + formData.append(`damage_items[${index}][id]`, item.id); + formData.append(`damage_items[${index}][value]`, item.value); + formData.append(`damage_items[${index}][amount]`, item.amount); + }); + if (result.radio_button === "report_base") { + formData.append("report_base", 1); + } + if (result.radio_button === "police_file_checkbox") { + formData.append("report_base", 0); + result.police_file !== defaultData.police_file && formData.append("police_file", result.police_file); + formData.append("police_file_date", result.police_file_date); + formData.append("police_serial", result.police_serial); + } + await requestServer(`${UPDATE_DAMAGE_ITEM}/${rowId}`, "post", { + data: formData, + }) + .then(() => { + mutate(); + setOpenEditDialog(false); + }) + .catch(() => {}); + }; + return ( + <> + {damageItemDetailsLoading ? ( + + ) : ( + + )} + + ); +}; +export default EditController; diff --git a/src/components/dashboard/damages/operator/Form/EditForm/index.jsx b/src/components/dashboard/damages/operator/Form/EditForm/index.jsx index e608b32..64cbe54 100644 --- a/src/components/dashboard/damages/operator/Form/EditForm/index.jsx +++ b/src/components/dashboard/damages/operator/Form/EditForm/index.jsx @@ -1,59 +1,59 @@ -import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import BorderColorIcon from "@mui/icons-material/BorderColor"; -import EditController from "./EditController"; -import CloseIcon from "@mui/icons-material/Close"; - -const EditForm = ({ row, mutate, rowId }) => { - const [openEditDialog, setOpenEditDialog] = useState(false); - - return ( - <> - - { - setOpenEditDialog(true); - }} - > - - - - - setOpenEditDialog(false)} - sx={(theme) => ({ - position: "absolute", - right: 8, - top: 8, - zIndex: 50, - color: theme.palette.grey[500], - })} - > - - - {openEditDialog && ( - - )} - - - ); -}; -export default EditForm; +import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import BorderColorIcon from "@mui/icons-material/BorderColor"; +import EditController from "./EditController"; +import CloseIcon from "@mui/icons-material/Close"; + +const EditForm = ({ row, mutate, rowId }) => { + const [openEditDialog, setOpenEditDialog] = useState(false); + + return ( + <> + + { + setOpenEditDialog(true); + }} + > + + + + + setOpenEditDialog(false)} + sx={(theme) => ({ + position: "absolute", + right: 8, + top: 8, + zIndex: 50, + color: theme.palette.grey[500], + })} + > + + + {openEditDialog && ( + + )} + + + ); +}; +export default EditForm; diff --git a/src/components/dashboard/damages/operator/Form/RegisterInsurance/DaghiFile.jsx b/src/components/dashboard/damages/operator/Form/RegisterInsurance/DaghiFile.jsx index 9f9670a..70005e7 100644 --- a/src/components/dashboard/damages/operator/Form/RegisterInsurance/DaghiFile.jsx +++ b/src/components/dashboard/damages/operator/Form/RegisterInsurance/DaghiFile.jsx @@ -1,48 +1,48 @@ -import { Grid, Stack, TextField } from "@mui/material"; -import { Controller } from "react-hook-form"; -import ImageUpload from "./ImageUpload"; -import NumberField from "@/core/components/NumberField"; - -const DaghiFile = ({ control }) => { - return ( - - - - - ( - - )} - /> - - - - ( - - )} - /> - - ); -}; -export default DaghiFile; +import { Grid, Stack, TextField } from "@mui/material"; +import { Controller } from "react-hook-form"; +import ImageUpload from "./ImageUpload"; +import NumberField from "@/core/components/NumberField"; + +const DaghiFile = ({ control }) => { + return ( + + + + + ( + + )} + /> + + + + ( + + )} + /> + + ); +}; +export default DaghiFile; diff --git a/src/components/dashboard/damages/operator/Form/RegisterInsurance/DaghiPayment.jsx b/src/components/dashboard/damages/operator/Form/RegisterInsurance/DaghiPayment.jsx index 91c4430..da9a0d4 100644 --- a/src/components/dashboard/damages/operator/Form/RegisterInsurance/DaghiPayment.jsx +++ b/src/components/dashboard/damages/operator/Form/RegisterInsurance/DaghiPayment.jsx @@ -1,53 +1,53 @@ -import { useState } from "react"; -import { FormControlLabel, RadioGroup, Stack } from "@mui/material"; -import { Controller, useWatch } from "react-hook-form"; -import Radio from "@mui/material/Radio"; -import DaghiFile from "./DaghiFile"; - -const DaghiPayment = ({ control }) => { - const watchedStatus = useWatch({ control, name: "deposit_daghi_status" }); - const [selectedOption, setSelectedOption] = useState(watchedStatus || null); - - const handleOptionChange = (e) => { - setSelectedOption(e.target.value); - }; - - return ( - <> - - - } - /> - } - label="صورتجلسه تحویل داغی به انبار ندارد" - /> - } - /> - } - label="صورتجلسه تحویل داغی به انبار دارد" - /> - - - - {selectedOption === "has_daghi" && } - - ); -}; -export default DaghiPayment; +import { useState } from "react"; +import { FormControlLabel, RadioGroup, Stack } from "@mui/material"; +import { Controller, useWatch } from "react-hook-form"; +import Radio from "@mui/material/Radio"; +import DaghiFile from "./DaghiFile"; + +const DaghiPayment = ({ control }) => { + const watchedStatus = useWatch({ control, name: "deposit_daghi_status" }); + const [selectedOption, setSelectedOption] = useState(watchedStatus || null); + + const handleOptionChange = (e) => { + setSelectedOption(e.target.value); + }; + + return ( + <> + + + } + /> + } + label="صورتجلسه تحویل داغی به انبار ندارد" + /> + } + /> + } + label="صورتجلسه تحویل داغی به انبار دارد" + /> + + + + {selectedOption === "has_daghi" && } + + ); +}; +export default DaghiPayment; diff --git a/src/components/dashboard/damages/operator/Form/RegisterInsurance/ImageUpload.jsx b/src/components/dashboard/damages/operator/Form/RegisterInsurance/ImageUpload.jsx index 107d640..2a2c9e6 100644 --- a/src/components/dashboard/damages/operator/Form/RegisterInsurance/ImageUpload.jsx +++ b/src/components/dashboard/damages/operator/Form/RegisterInsurance/ImageUpload.jsx @@ -1,77 +1,77 @@ -import { FormControl, FormHelperText } from "@mui/material"; -import UploadSystem from "@/core/components/UploadSystem"; -import React, { useEffect, useState } from "react"; - -const ImageUpload = ({ name, value, onChange, error, beforeImage = null, title }) => { - const [beforeImg, setBeforeImg] = useState(beforeImage ? beforeImage : null); - const [beforeFileType, setBeforeFileType] = useState(beforeImage ? "image/" : null); - const [beforeFileName, setBeforeFileName] = useState(null); - const [showBeforeImage, setShowBeforeImage] = useState(!beforeImage); - - useEffect(() => { - if (value) { - setShowBeforeImage(false); - if (typeof value === "string") { - setBeforeImg(value); - setBeforeFileType("image/"); - } else if (value instanceof File) { - setBeforeImg(URL.createObjectURL(value)); - setBeforeFileType(value.type); - } - } - }, [value]); - - const handleFileChange = (event) => { - const uploadedFile = event.target?.files?.[0]; - if (uploadedFile) { - const fileType = event.target?.files?.[0].type; - const fileName = event.target?.files?.[0].name; - setBeforeImg(URL.createObjectURL(uploadedFile)); - setBeforeFileType(fileType); - setBeforeFileName(fileName); - onChange(uploadedFile); - setShowBeforeImage(false); - } - }; - - return ( - - - {title} - - - {error ? error.message : null} - - ); -}; -export default ImageUpload; +import { FormControl, FormHelperText } from "@mui/material"; +import UploadSystem from "@/core/components/UploadSystem"; +import React, { useEffect, useState } from "react"; + +const ImageUpload = ({ name, value, onChange, error, beforeImage = null, title }) => { + const [beforeImg, setBeforeImg] = useState(beforeImage ? beforeImage : null); + const [beforeFileType, setBeforeFileType] = useState(beforeImage ? "image/" : null); + const [beforeFileName, setBeforeFileName] = useState(null); + const [showBeforeImage, setShowBeforeImage] = useState(!beforeImage); + + useEffect(() => { + if (value) { + setShowBeforeImage(false); + if (typeof value === "string") { + setBeforeImg(value); + setBeforeFileType("image/"); + } else if (value instanceof File) { + setBeforeImg(URL.createObjectURL(value)); + setBeforeFileType(value.type); + } + } + }, [value]); + + const handleFileChange = (event) => { + const uploadedFile = event.target?.files?.[0]; + if (uploadedFile) { + const fileType = event.target?.files?.[0].type; + const fileName = event.target?.files?.[0].name; + setBeforeImg(URL.createObjectURL(uploadedFile)); + setBeforeFileType(fileType); + setBeforeFileName(fileName); + onChange(uploadedFile); + setShowBeforeImage(false); + } + }; + + return ( + + + {title} + + + {error ? error.message : null} + + ); +}; +export default ImageUpload; diff --git a/src/components/dashboard/damages/operator/Form/RegisterInsurance/InsuranceFile.jsx b/src/components/dashboard/damages/operator/Form/RegisterInsurance/InsuranceFile.jsx index da88acd..8476132 100644 --- a/src/components/dashboard/damages/operator/Form/RegisterInsurance/InsuranceFile.jsx +++ b/src/components/dashboard/damages/operator/Form/RegisterInsurance/InsuranceFile.jsx @@ -1,48 +1,48 @@ -import NumberField from "@/core/components/NumberField"; -import { Grid, Stack } from "@mui/material"; -import { Controller } from "react-hook-form"; -import ImageUpload from "./ImageUpload"; - -const InsuranceFile = ({ control }) => { - return ( - - - - - ( - - )} - /> - - - - ( - - )} - /> - - ); -}; -export default InsuranceFile; +import NumberField from "@/core/components/NumberField"; +import { Grid, Stack } from "@mui/material"; +import { Controller } from "react-hook-form"; +import ImageUpload from "./ImageUpload"; + +const InsuranceFile = ({ control }) => { + return ( + + + + + ( + + )} + /> + + + + ( + + )} + /> + + ); +}; +export default InsuranceFile; diff --git a/src/components/dashboard/damages/operator/Form/RegisterInsurance/InsurancePayment.jsx b/src/components/dashboard/damages/operator/Form/RegisterInsurance/InsurancePayment.jsx index 50ee912..b759c85 100644 --- a/src/components/dashboard/damages/operator/Form/RegisterInsurance/InsurancePayment.jsx +++ b/src/components/dashboard/damages/operator/Form/RegisterInsurance/InsurancePayment.jsx @@ -1,52 +1,52 @@ -import { FormControlLabel, FormHelperText, RadioGroup, Stack } from "@mui/material"; -import { Controller, useWatch } from "react-hook-form"; -import Radio from "@mui/material/Radio"; -import { useState } from "react"; -import InsuranceFile from "./InsuranceFile"; - -const InsurancePayment = ({ control }) => { - const watchedStatus = useWatch({ control, name: "deposit_insurance_status" }); - const [selectedOption, setSelectedOption] = useState(watchedStatus || null); - - const handleOptionChange = (e) => { - setSelectedOption(e.target.value); - }; - - return ( - <> - - - } - /> - } - label="فیش واریزی (بیمه) ندارد" - /> - } - /> - } - label="فیش واریزی (بیمه) دارد" - /> - - - {selectedOption === "has_insurance" && } - - ); -}; -export default InsurancePayment; +import { FormControlLabel, FormHelperText, RadioGroup, Stack } from "@mui/material"; +import { Controller, useWatch } from "react-hook-form"; +import Radio from "@mui/material/Radio"; +import { useState } from "react"; +import InsuranceFile from "./InsuranceFile"; + +const InsurancePayment = ({ control }) => { + const watchedStatus = useWatch({ control, name: "deposit_insurance_status" }); + const [selectedOption, setSelectedOption] = useState(watchedStatus || null); + + const handleOptionChange = (e) => { + setSelectedOption(e.target.value); + }; + + return ( + <> + + + } + /> + } + label="فیش واریزی (بیمه) ندارد" + /> + } + /> + } + label="فیش واریزی (بیمه) دارد" + /> + + + {selectedOption === "has_insurance" && } + + ); +}; +export default InsurancePayment; diff --git a/src/components/dashboard/damages/operator/Form/RegisterInsurance/RegisterInsuranceContent.jsx b/src/components/dashboard/damages/operator/Form/RegisterInsurance/RegisterInsuranceContent.jsx index b33b433..9470c5e 100644 --- a/src/components/dashboard/damages/operator/Form/RegisterInsurance/RegisterInsuranceContent.jsx +++ b/src/components/dashboard/damages/operator/Form/RegisterInsurance/RegisterInsuranceContent.jsx @@ -1,203 +1,203 @@ -import { Box, Button, DialogActions, DialogContent, Tab, Tabs, Typography } from "@mui/material"; -import ExitToAppIcon from "@mui/icons-material/ExitToApp"; -import KeyboardDoubleArrowRightIcon from "@mui/icons-material/KeyboardDoubleArrowRight"; -import KeyboardDoubleArrowLeftIcon from "@mui/icons-material/KeyboardDoubleArrowLeft"; -import LocalPostOfficeIcon from "@mui/icons-material/LocalPostOffice"; -import BeenhereIcon from "@mui/icons-material/Beenhere"; -import StyledForm from "@/core/components/StyledForm"; -import PaymentIcon from "@mui/icons-material/Payment"; -import React, { useState } from "react"; -import { useForm } from "react-hook-form"; -import { yupResolver } from "@hookform/resolvers/yup"; -import { mixed, object, string } from "yup"; -import InsurancePayment from "./InsurancePayment"; -import DaghiPayment from "./DaghiPayment"; -import { CONFIRM_PAYMENT_INFO } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -function TabPanel(props) { - const { children, value, index } = props; - return ( - - ); -} -const validationSchema = object({ - deposit_insurance_status: string().required("انتخاب یک گزینه الزامیست."), - deposit_daghi_status: string().required("انتخاب یک گزینه الزامیست."), - deposit_insurance_amount: string().when("deposit_insurance_status", { - is: "has_insurance", - then: (schema) => schema.required("مبلغ بیمه الزامی است."), - otherwise: (schema) => schema.notRequired(), - }), - deposit_insurance_image: mixed().when("deposit_insurance_status", { - is: "has_insurance", - then: (schema) => schema.required("تصویر فیش واریزی بیمه الزامی است."), - otherwise: (schema) => schema.notRequired(), - }), - deposit_daghi_amount: string() - .when("deposit_daghi_status", { - is: "has_daghi", - then: (schema) => schema.required("مبلغ داغی الزامی است."), - otherwise: (schema) => schema.notRequired(), - }) - .test("max-percentage", "مبلغ داغی نباید بیشتر از ۳۰ درصد مبلغ کل خسارت باشد.", function (value) { - const sum = this.options.context.sum || 0; - if (!value || isNaN(value) || !sum) return true; - return parseFloat(value) <= sum * 0.3; - }), - deposit_daghi_image: mixed().when("deposit_daghi_status", { - is: "has_daghi", - then: (schema) => schema.required("تصویر صورتجلسه تحویل داغی به انبار الزامی است."), - otherwise: (schema) => schema.notRequired(), - }), -}).test("total-amount-limit", "مجموع مبلغ بیمه و داغی نباید از کل مبلغ خسارت بیشتر باشد.", function (values) { - const sum = this.options.context.sum || 0; - const depositInsuranceAmount = parseFloat(values.deposit_insurance_amount) || 0; - const depositDaghiAmount = parseFloat(values.deposit_daghi_amount) || 0; - return depositInsuranceAmount + depositDaghiAmount <= sum; -}); - -const RegisterInsuranceContent = ({ setOpenRegisterInsuranceDialog, row, mutate, rowId }) => { - const [tabState, setTabState] = useState(0); - const requestServer = useRequest({ notificationSuccess: true }); - const handleClose = () => setOpenRegisterInsuranceDialog(false); - const handleChangeTab = (event, newValue) => setTabState(newValue); - - const defaultValues = { - deposit_insurance_status: "no_insurance", - deposit_insurance_amount: "", - deposit_insurance_image: null, - deposit_daghi_status: "no_daghi", - deposit_daghi_amount: "", - deposit_daghi_image: null, - }; - const handlePrev = () => { - if (tabState === 0) { - handleClose(); - } else { - setTabState(tabState - 1); - } - }; - const handleNext = async () => { - let fieldsToValidate = []; - if (tabState === 0) { - fieldsToValidate = ["deposit_insurance_status", "deposit_insurance_amount", "deposit_insurance_image"]; - } - if (tabState === 1) { - fieldsToValidate = ["deposit_daghi_status", "deposit_daghi_amount", "deposit_daghi_image"]; - } - - const isValid = await trigger(fieldsToValidate); - if (isValid) { - setTabState(tabState + 1); - } - }; - - const { - control, - handleSubmit, - trigger, - formState: { isSubmitting, errors }, - } = useForm({ - defaultValues, - resolver: yupResolver(validationSchema), - mode: "all", - context: { sum: row?.original?.sum }, - }); - - const onSubmitBase = async (data) => { - const formData = new FormData(); - const depositDaghiStatus = data.deposit_daghi_status === "no_daghi" ? 0 : 1; - const depositInsuranceStatus = data.deposit_insurance_status === "no_insurance" ? 0 : 1; - - if (data.deposit_daghi_status === "has_daghi") { - formData.append("deposit_daghi_status", depositDaghiStatus); - formData.append("deposit_daghi_amount", data.deposit_daghi_amount); - formData.append("deposit_daghi_image", data.deposit_daghi_image); - } - if (data.deposit_insurance_status === "has_insurance") { - formData.append("deposit_insurance_status", depositInsuranceStatus); - formData.append("deposit_insurance_amount", data.deposit_insurance_amount); - formData.append("deposit_insurance_image", data.deposit_insurance_image); - } - try { - await requestServer(`${CONFIRM_PAYMENT_INFO}/${rowId}`, "post", { - data: formData, - }); - mutate(); - setOpenRegisterInsuranceDialog(false); - } catch (error) {} - }; - return ( - - - } label="فیش واریزی بیمه" /> - } label="صورتجلسه تحویل داغی به انبار" /> - - - - - - - - - - - - {errors[""]?.message && ( - - {errors[""].message} - - )} - - - {tabState !== 1 && ( - - )} - {tabState === 1 && ( - - )} - - - ); -}; -export default RegisterInsuranceContent; +import { Box, Button, DialogActions, DialogContent, Tab, Tabs, Typography } from "@mui/material"; +import ExitToAppIcon from "@mui/icons-material/ExitToApp"; +import KeyboardDoubleArrowRightIcon from "@mui/icons-material/KeyboardDoubleArrowRight"; +import KeyboardDoubleArrowLeftIcon from "@mui/icons-material/KeyboardDoubleArrowLeft"; +import LocalPostOfficeIcon from "@mui/icons-material/LocalPostOffice"; +import BeenhereIcon from "@mui/icons-material/Beenhere"; +import StyledForm from "@/core/components/StyledForm"; +import PaymentIcon from "@mui/icons-material/Payment"; +import React, { useState } from "react"; +import { useForm } from "react-hook-form"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { mixed, object, string } from "yup"; +import InsurancePayment from "./InsurancePayment"; +import DaghiPayment from "./DaghiPayment"; +import { CONFIRM_PAYMENT_INFO } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +function TabPanel(props) { + const { children, value, index } = props; + return ( + + ); +} +const validationSchema = object({ + deposit_insurance_status: string().required("انتخاب یک گزینه الزامیست."), + deposit_daghi_status: string().required("انتخاب یک گزینه الزامیست."), + deposit_insurance_amount: string().when("deposit_insurance_status", { + is: "has_insurance", + then: (schema) => schema.required("مبلغ بیمه الزامی است."), + otherwise: (schema) => schema.notRequired(), + }), + deposit_insurance_image: mixed().when("deposit_insurance_status", { + is: "has_insurance", + then: (schema) => schema.required("تصویر فیش واریزی بیمه الزامی است."), + otherwise: (schema) => schema.notRequired(), + }), + deposit_daghi_amount: string() + .when("deposit_daghi_status", { + is: "has_daghi", + then: (schema) => schema.required("مبلغ داغی الزامی است."), + otherwise: (schema) => schema.notRequired(), + }) + .test("max-percentage", "مبلغ داغی نباید بیشتر از ۳۰ درصد مبلغ کل خسارت باشد.", function (value) { + const sum = this.options.context.sum || 0; + if (!value || isNaN(value) || !sum) return true; + return parseFloat(value) <= sum * 0.3; + }), + deposit_daghi_image: mixed().when("deposit_daghi_status", { + is: "has_daghi", + then: (schema) => schema.required("تصویر صورتجلسه تحویل داغی به انبار الزامی است."), + otherwise: (schema) => schema.notRequired(), + }), +}).test("total-amount-limit", "مجموع مبلغ بیمه و داغی نباید از کل مبلغ خسارت بیشتر باشد.", function (values) { + const sum = this.options.context.sum || 0; + const depositInsuranceAmount = parseFloat(values.deposit_insurance_amount) || 0; + const depositDaghiAmount = parseFloat(values.deposit_daghi_amount) || 0; + return depositInsuranceAmount + depositDaghiAmount <= sum; +}); + +const RegisterInsuranceContent = ({ setOpenRegisterInsuranceDialog, row, mutate, rowId }) => { + const [tabState, setTabState] = useState(0); + const requestServer = useRequest({ notificationSuccess: true }); + const handleClose = () => setOpenRegisterInsuranceDialog(false); + const handleChangeTab = (event, newValue) => setTabState(newValue); + + const defaultValues = { + deposit_insurance_status: "no_insurance", + deposit_insurance_amount: "", + deposit_insurance_image: null, + deposit_daghi_status: "no_daghi", + deposit_daghi_amount: "", + deposit_daghi_image: null, + }; + const handlePrev = () => { + if (tabState === 0) { + handleClose(); + } else { + setTabState(tabState - 1); + } + }; + const handleNext = async () => { + let fieldsToValidate = []; + if (tabState === 0) { + fieldsToValidate = ["deposit_insurance_status", "deposit_insurance_amount", "deposit_insurance_image"]; + } + if (tabState === 1) { + fieldsToValidate = ["deposit_daghi_status", "deposit_daghi_amount", "deposit_daghi_image"]; + } + + const isValid = await trigger(fieldsToValidate); + if (isValid) { + setTabState(tabState + 1); + } + }; + + const { + control, + handleSubmit, + trigger, + formState: { isSubmitting, errors }, + } = useForm({ + defaultValues, + resolver: yupResolver(validationSchema), + mode: "all", + context: { sum: row?.original?.sum }, + }); + + const onSubmitBase = async (data) => { + const formData = new FormData(); + const depositDaghiStatus = data.deposit_daghi_status === "no_daghi" ? 0 : 1; + const depositInsuranceStatus = data.deposit_insurance_status === "no_insurance" ? 0 : 1; + + if (data.deposit_daghi_status === "has_daghi") { + formData.append("deposit_daghi_status", depositDaghiStatus); + formData.append("deposit_daghi_amount", data.deposit_daghi_amount); + formData.append("deposit_daghi_image", data.deposit_daghi_image); + } + if (data.deposit_insurance_status === "has_insurance") { + formData.append("deposit_insurance_status", depositInsuranceStatus); + formData.append("deposit_insurance_amount", data.deposit_insurance_amount); + formData.append("deposit_insurance_image", data.deposit_insurance_image); + } + try { + await requestServer(`${CONFIRM_PAYMENT_INFO}/${rowId}`, "post", { + data: formData, + }); + mutate(); + setOpenRegisterInsuranceDialog(false); + } catch (error) {} + }; + return ( + + + } label="فیش واریزی بیمه" /> + } label="صورتجلسه تحویل داغی به انبار" /> + + + + + + + + + + + + {errors[""]?.message && ( + + {errors[""].message} + + )} + + + {tabState !== 1 && ( + + )} + {tabState === 1 && ( + + )} + + + ); +}; +export default RegisterInsuranceContent; diff --git a/src/components/dashboard/damages/operator/Form/RegisterInsurance/index.jsx b/src/components/dashboard/damages/operator/Form/RegisterInsurance/index.jsx index 9a4e05e..de6e2ac 100644 --- a/src/components/dashboard/damages/operator/Form/RegisterInsurance/index.jsx +++ b/src/components/dashboard/damages/operator/Form/RegisterInsurance/index.jsx @@ -1,53 +1,53 @@ -import { Dialog, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import ReceiptIcon from "@mui/icons-material/Receipt"; -import RegisterInsuranceContent from "./RegisterInsuranceContent"; -import CloseIcon from "@mui/icons-material/Close"; - -const RegisterInsurance = ({ row, mutate, rowId }) => { - const [openRegisterInsuranceDialog, setOpenRegisterInsuranceDialog] = useState(false); - - return ( - <> - - setOpenRegisterInsuranceDialog(true)}> - - - - - setOpenRegisterInsuranceDialog(false)} - sx={(theme) => ({ - position: "absolute", - right: 8, - top: 8, - zIndex: 50, - color: theme.palette.grey[500], - })} - > - - - {openRegisterInsuranceDialog && ( - - )} - - - ); -}; -export default RegisterInsurance; +import { Dialog, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import ReceiptIcon from "@mui/icons-material/Receipt"; +import RegisterInsuranceContent from "./RegisterInsuranceContent"; +import CloseIcon from "@mui/icons-material/Close"; + +const RegisterInsurance = ({ row, mutate, rowId }) => { + const [openRegisterInsuranceDialog, setOpenRegisterInsuranceDialog] = useState(false); + + return ( + <> + + setOpenRegisterInsuranceDialog(true)}> + + + + + setOpenRegisterInsuranceDialog(false)} + sx={(theme) => ({ + position: "absolute", + right: 8, + top: 8, + zIndex: 50, + color: theme.palette.grey[500], + })} + > + + + {openRegisterInsuranceDialog && ( + + )} + + + ); +}; +export default RegisterInsurance; diff --git a/src/components/dashboard/damages/operator/OperatorList.jsx b/src/components/dashboard/damages/operator/OperatorList.jsx index 4fdac6e..308ac7c 100644 --- a/src/components/dashboard/damages/operator/OperatorList.jsx +++ b/src/components/dashboard/damages/operator/OperatorList.jsx @@ -1,504 +1,504 @@ -"use client"; -import CustomSelectByDependency from "@/core/components/DataTable/filter/fieldsType/CustomSelectByDependency"; -import DataTableWithAuth from "@/core/components/DataTableWithAuth"; -import { GET_TECHNICAL_DAMAGE_OPERATOR_LIST } from "@/core/utils/routes"; -import useCities from "@/lib/hooks/useCities"; -import useProvinces from "@/lib/hooks/useProvince"; -import { Box, Stack, Typography } from "@mui/material"; -import moment from "jalali-moment"; -import { useEffect, useMemo, useState } from "react"; -import RowActions from "./RowActions"; -import DamageItemDialog from "./RowActions/DamageItemDialog"; -import DamageReportDialog from "./RowActions/DamageReport"; -import ImageDialog from "./RowActions/ImageDialog"; -import LocationForm from "./RowActions/LocationForm"; -import ShowPlate from "./RowActions/ShowPlate"; -import Toolbar from "./Toolbar"; -import { usePermissions } from "@/lib/hooks/usePermissions"; -import { useAuth } from "@/lib/contexts/auth"; - -const OperatorList = () => { - const { data: userPermissions } = usePermissions(); - const hasCountryPermission = userPermissions?.includes("show-receipt"); - const { user } = useAuth(); - const foreginOptions = [ - { value: "", label: "همه ناوگان ها" }, - { value: 0, label: "داخلی" }, - { value: 1, label: "خارجی" }, - ]; - const statusOptions = [ - { value: "", label: "همه وضعیت ها" }, - { value: 0, label: "بدون اقدام" }, - { value: 1, label: "صدور نامه بیمه و کارشناسی داغی" }, - { value: 2, label: "فیش ها ثبت شده است" }, - { value: 3, label: "فاکتور صادر شده است" }, - { value: 4, label: "فاکتور پرداخت شده است" }, - { value: 5, label: "نامه پلیس راه صادر شده است" }, - ]; - const columns = useMemo(() => { - const provinceColumn = { - accessorKey: "province_id", - header: "استان", - id: "province_id", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - grow: false, - size: 130, - ColumnSelectComponent: (props) => { - const { provinces, errorProvinces, loadingProvinces } = useProvinces(); - const getColumnSelectOptions = useMemo(() => { - if (loadingProvinces) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorProvinces) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: "کل کشور" }, - ...provinces.map((province) => ({ - value: province.id, - label: province.name_fa, - })), - ]; - }, [provinces, errorProvinces, loadingProvinces]); - return ( - - ); - }, - Cell: ({ row }) => <>{row.original.province_fa}, - }; - return [ - { - accessorKey: "id", - header: "کد یکتا", // Unique Code - id: "id", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorKey: "status", - header: "وضعیت", - id: "status", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - grow: false, - size: 100, - columnSelectOption: () => { - return statusOptions.map((status) => ({ - value: status.value, - label: status.label, - })); - }, - Cell: ({ row }) => { - return {row.original.status_fa}; - }, - }, - { - header: "اطلاعات تصادف", - id: "accidentInfo", - enableColumnFilter: false, - enableSorting: false, - grow: false, - size: 50, - columns: [ - ...(hasCountryPermission ? [provinceColumn] : []), - { - accessorKey: "city_id", - header: "شهرستان", // Office - id: "city_id", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - dependencyId: hasCountryPermission ? "province_id" : null, - grow: false, - size: 120, - ColumnSelectComponent: (props) => { - const { cityList, loadingCityList, errorCityList } = useCities( - hasCountryPermission ? props.dependencyFieldValue.value : user.province_id - ); - const [prevDependency, setPrevDependency] = useState( - hasCountryPermission ? props.dependencyFieldValue.value : user.province_id - ); - - const getColumnSelectOptions = useMemo(() => { - if (hasCountryPermission && props.dependencyFieldValue.value === "") { - return [{ value: "empty", label: "ابتدا استان را انتخاب کنید" }]; - } - if (loadingCityList) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorCityList) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: "کل شهر ها" }, - ...cityList.map((city) => ({ - value: city.id, - label: city.name_fa, - })), - ]; - }, [cityList, loadingCityList, errorCityList]); - useEffect(() => { - if (hasCountryPermission) return; - if (prevDependency === props.dependencyFieldValue?.value) return; - props.handleChange({ ...props.filterParameters, value: "" }); - setPrevDependency(props.dependencyFieldValue?.value); - }, [props.dependencyFieldValue?.value, hasCountryPermission]); - return ( - - ); - }, - Cell: ({ row }) => <>{row.original.city_fa}, - }, - { - accessorKey: "axis_name", - header: "نام محور", - id: "axis_name", - enableColumnFilter: true, - enableSorting: true, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 120, - }, - { - accessorKey: "is_foreign", - header: "نوع ناوگان", - id: "is_foreign", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - grow: false, - size: 100, - columnSelectOption: () => { - return foreginOptions.map((status) => ({ - value: status.value, - label: status.label, - })); - }, - Cell: ({ row }) => { - return ( - - {row.original.is_foreign == "0" ? "داخلی" : "خارجی"} - - ); - }, - }, - { - accessorKey: "driver_name", - header: "نام راننده", - id: "driver_name", - enableColumnFilter: true, - enableSorting: true, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 120, - }, - { - accessorKey: "driver_national_code", - header: "کد ملی راننده", - id: "driver_national_code", - enableColumnFilter: true, - enableSorting: true, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 120, - }, - { - accessorKey: "driver_phone_number", - header: "شماره موبایل راننده", - id: "driver_phone_number", - enableColumnFilter: true, - enableSorting: true, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 120, - }, - { - accessorKey: "plaque", - header: "پلاک", - id: "plaque", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - enableSorting: false, - grow: false, - size: 100, - Cell: ({ row, renderedCellValue }) => - row.original.is_foreign == "0" ? : "", - }, - { - accessorKey: "accident_type", - header: "نوع تصادف", // Value - id: "accident_type", - enableColumnFilter: true, - enableSorting: true, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 120, - Cell: ({ row }) => <>{row.original.accident_type_fa}, - }, - { - accessorFn: (row) => { - const formattedDate = moment(row.accident_date, "YYYY-MM-DD"); // تنظیم فرمت صحیح تاریخ - const formattedTime = row.accident_time || "00:00:00"; // در صورت خالی بودن مقدار، مقدار پیش‌فرض داده شود - return moment(`${formattedDate.format("YYYY-MM-DD")}T${formattedTime}`) - .locale("fa") - .format("HH:mm | YYYY/MM/DD"); - }, - header: "تاریخ تصادف", - id: "accident_date", - enableColumnFilter: true, - datatype: "date", - filterMode: "between", - grow: false, - size: 100, - }, - { - accessorKey: "files", - header: "تصاویر", - id: "files", - enableColumnFilter: false, - enableSorting: false, - datatype: "array", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ row }) => { - if (row.original.damage_picture1) { - const imagesList = [row.original.damage_picture1, row.original.damage_picture2]; - return ( - - - - ); - } - return ( - - - - - ); - }, - }, - { - accessorKey: "location", - header: "موقعیت", - id: "location", - enableColumnFilter: false, - enableSorting: false, - datatype: "array", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ row }) => { - return ( - - - - ); - }, - }, - ], - }, - { - header: "اطلاعات خسارت", - id: "damagesInfo", - enableColumnFilter: false, - enableSorting: false, - grow: false, - size: 50, - columns: [ - { - header: "گزارش خسارت", - id: "damageReport", - enableColumnFilter: false, - enableSorting: false, - datatype: "array", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ row }) => { - return ( - - - - ); - }, - }, - { - header: "آیتم های خسارت", - id: "damageItems", - enableColumnFilter: false, - enableSorting: false, - datatype: "array", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ row }) => { - return ( - - - - ); - }, - }, - { - accessorKey: "sum", - header: "مبلغ کل خسارت (ریال)", - id: "sum", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - sortDescFirst: true, - grow: false, - size: 100, - Cell: ({ row }) => ( - - {(row.original.sum / 1).toLocaleString()} - - ), - }, - ], - }, - { - header: "اطلاعات واریز", - id: "items", - enableColumnFilter: false, - enableSorting: false, - grow: false, - size: 50, - columns: [ - { - header: "مبلغ فاکتور (ریال)", - id: "final_amount", - enableColumnFilter: false, - grow: false, - size: 100, - Cell: ({ row }) => ( - - {(row.original.final_amount / 1).toLocaleString()} - - ), - }, - { - header: "مبلغ بیمه (ریال)", - id: "deposit_insurance_amount", - enableColumnFilter: false, - grow: false, - size: 100, - Cell: ({ row }) => ( - - {(row.original.deposit_insurance_amount / 1).toLocaleString()} - - ), - }, - { - header: "مبلغ داغی (ریال)", - id: "deposit_daghi_amount", - enableColumnFilter: false, - grow: false, - size: 100, - Cell: ({ row }) => ( - - {(row.original.deposit_daghi_amount / 1).toLocaleString()} - - ), - }, - ], - }, - { - accessorFn: (row) => moment(row.created_at).locale("fa").format("HH:mm | yyyy/MM/DD"), - header: "تاریخ ثبت", - id: "created_at", - enableColumnFilter: true, - datatype: "date", - filterMode: "between", - grow: false, - size: 100, - }, - ]; - }, []); - - return ( - <> - - - - - ); -}; -export default OperatorList; +"use client"; +import CustomSelectByDependency from "@/core/components/DataTable/filter/fieldsType/CustomSelectByDependency"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import { GET_TECHNICAL_DAMAGE_OPERATOR_LIST } from "@/core/utils/routes"; +import useCities from "@/lib/hooks/useCities"; +import useProvinces from "@/lib/hooks/useProvince"; +import { Box, Stack, Typography } from "@mui/material"; +import moment from "jalali-moment"; +import { useEffect, useMemo, useState } from "react"; +import RowActions from "./RowActions"; +import DamageItemDialog from "./RowActions/DamageItemDialog"; +import DamageReportDialog from "./RowActions/DamageReport"; +import ImageDialog from "./RowActions/ImageDialog"; +import LocationForm from "./RowActions/LocationForm"; +import ShowPlate from "./RowActions/ShowPlate"; +import Toolbar from "./Toolbar"; +import { usePermissions } from "@/lib/hooks/usePermissions"; +import { useAuth } from "@/lib/contexts/auth"; + +const OperatorList = () => { + const { data: userPermissions } = usePermissions(); + const hasCountryPermission = userPermissions?.includes("show-receipt"); + const { user } = useAuth(); + const foreginOptions = [ + { value: "", label: "همه ناوگان ها" }, + { value: 0, label: "داخلی" }, + { value: 1, label: "خارجی" }, + ]; + const statusOptions = [ + { value: "", label: "همه وضعیت ها" }, + { value: 0, label: "بدون اقدام" }, + { value: 1, label: "صدور نامه بیمه و کارشناسی داغی" }, + { value: 2, label: "فیش ها ثبت شده است" }, + { value: 3, label: "فاکتور صادر شده است" }, + { value: 4, label: "فاکتور پرداخت شده است" }, + { value: 5, label: "نامه پلیس راه صادر شده است" }, + ]; + const columns = useMemo(() => { + const provinceColumn = { + accessorKey: "province_id", + header: "استان", + id: "province_id", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 130, + ColumnSelectComponent: (props) => { + const { provinces, errorProvinces, loadingProvinces } = useProvinces(); + const getColumnSelectOptions = useMemo(() => { + if (loadingProvinces) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorProvinces) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: "کل کشور" }, + ...provinces.map((province) => ({ + value: province.id, + label: province.name_fa, + })), + ]; + }, [provinces, errorProvinces, loadingProvinces]); + return ( + + ); + }, + Cell: ({ row }) => <>{row.original.province_fa}, + }; + return [ + { + accessorKey: "id", + header: "کد یکتا", // Unique Code + id: "id", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "status", + header: "وضعیت", + id: "status", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 100, + columnSelectOption: () => { + return statusOptions.map((status) => ({ + value: status.value, + label: status.label, + })); + }, + Cell: ({ row }) => { + return {row.original.status_fa}; + }, + }, + { + header: "اطلاعات تصادف", + id: "accidentInfo", + enableColumnFilter: false, + enableSorting: false, + grow: false, + size: 50, + columns: [ + ...(hasCountryPermission ? [provinceColumn] : []), + { + accessorKey: "city_id", + header: "شهرستان", // Office + id: "city_id", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + dependencyId: hasCountryPermission ? "province_id" : null, + grow: false, + size: 120, + ColumnSelectComponent: (props) => { + const { cityList, loadingCityList, errorCityList } = useCities( + hasCountryPermission ? props.dependencyFieldValue.value : user.province_id + ); + const [prevDependency, setPrevDependency] = useState( + hasCountryPermission ? props.dependencyFieldValue.value : user.province_id + ); + + const getColumnSelectOptions = useMemo(() => { + if (hasCountryPermission && props.dependencyFieldValue.value === "") { + return [{ value: "empty", label: "ابتدا استان را انتخاب کنید" }]; + } + if (loadingCityList) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorCityList) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: "کل شهر ها" }, + ...cityList.map((city) => ({ + value: city.id, + label: city.name_fa, + })), + ]; + }, [cityList, loadingCityList, errorCityList]); + useEffect(() => { + if (hasCountryPermission) return; + if (prevDependency === props.dependencyFieldValue?.value) return; + props.handleChange({ ...props.filterParameters, value: "" }); + setPrevDependency(props.dependencyFieldValue?.value); + }, [props.dependencyFieldValue?.value, hasCountryPermission]); + return ( + + ); + }, + Cell: ({ row }) => <>{row.original.city_fa}, + }, + { + accessorKey: "axis_name", + header: "نام محور", + id: "axis_name", + enableColumnFilter: true, + enableSorting: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 120, + }, + { + accessorKey: "is_foreign", + header: "نوع ناوگان", + id: "is_foreign", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 100, + columnSelectOption: () => { + return foreginOptions.map((status) => ({ + value: status.value, + label: status.label, + })); + }, + Cell: ({ row }) => { + return ( + + {row.original.is_foreign == "0" ? "داخلی" : "خارجی"} + + ); + }, + }, + { + accessorKey: "driver_name", + header: "نام راننده", + id: "driver_name", + enableColumnFilter: true, + enableSorting: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 120, + }, + { + accessorKey: "driver_national_code", + header: "کد ملی راننده", + id: "driver_national_code", + enableColumnFilter: true, + enableSorting: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 120, + }, + { + accessorKey: "driver_phone_number", + header: "شماره موبایل راننده", + id: "driver_phone_number", + enableColumnFilter: true, + enableSorting: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 120, + }, + { + accessorKey: "plaque", + header: "پلاک", + id: "plaque", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + enableSorting: false, + grow: false, + size: 100, + Cell: ({ row, renderedCellValue }) => + row.original.is_foreign == "0" ? : "", + }, + { + accessorKey: "accident_type", + header: "نوع تصادف", // Value + id: "accident_type", + enableColumnFilter: true, + enableSorting: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 120, + Cell: ({ row }) => <>{row.original.accident_type_fa}, + }, + { + accessorFn: (row) => { + const formattedDate = moment(row.accident_date, "YYYY-MM-DD"); // تنظیم فرمت صحیح تاریخ + const formattedTime = row.accident_time || "00:00:00"; // در صورت خالی بودن مقدار، مقدار پیش‌فرض داده شود + return moment(`${formattedDate.format("YYYY-MM-DD")}T${formattedTime}`) + .locale("fa") + .format("HH:mm | YYYY/MM/DD"); + }, + header: "تاریخ تصادف", + id: "accident_date", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + { + accessorKey: "files", + header: "تصاویر", + id: "files", + enableColumnFilter: false, + enableSorting: false, + datatype: "array", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => { + if (row.original.damage_picture1) { + const imagesList = [row.original.damage_picture1, row.original.damage_picture2]; + return ( + + + + ); + } + return ( + + - + + ); + }, + }, + { + accessorKey: "location", + header: "موقعیت", + id: "location", + enableColumnFilter: false, + enableSorting: false, + datatype: "array", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => { + return ( + + + + ); + }, + }, + ], + }, + { + header: "اطلاعات خسارت", + id: "damagesInfo", + enableColumnFilter: false, + enableSorting: false, + grow: false, + size: 50, + columns: [ + { + header: "گزارش خسارت", + id: "damageReport", + enableColumnFilter: false, + enableSorting: false, + datatype: "array", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => { + return ( + + + + ); + }, + }, + { + header: "آیتم های خسارت", + id: "damageItems", + enableColumnFilter: false, + enableSorting: false, + datatype: "array", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => { + return ( + + + + ); + }, + }, + { + accessorKey: "sum", + header: "مبلغ کل خسارت (ریال)", + id: "sum", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + sortDescFirst: true, + grow: false, + size: 100, + Cell: ({ row }) => ( + + {(row.original.sum / 1).toLocaleString()} + + ), + }, + ], + }, + { + header: "اطلاعات واریز", + id: "items", + enableColumnFilter: false, + enableSorting: false, + grow: false, + size: 50, + columns: [ + { + header: "مبلغ فاکتور (ریال)", + id: "final_amount", + enableColumnFilter: false, + grow: false, + size: 100, + Cell: ({ row }) => ( + + {(row.original.final_amount / 1).toLocaleString()} + + ), + }, + { + header: "مبلغ بیمه (ریال)", + id: "deposit_insurance_amount", + enableColumnFilter: false, + grow: false, + size: 100, + Cell: ({ row }) => ( + + {(row.original.deposit_insurance_amount / 1).toLocaleString()} + + ), + }, + { + header: "مبلغ داغی (ریال)", + id: "deposit_daghi_amount", + enableColumnFilter: false, + grow: false, + size: 100, + Cell: ({ row }) => ( + + {(row.original.deposit_daghi_amount / 1).toLocaleString()} + + ), + }, + ], + }, + { + accessorFn: (row) => moment(row.created_at).locale("fa").format("HH:mm | yyyy/MM/DD"), + header: "تاریخ ثبت", + id: "created_at", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + ]; + }, []); + + return ( + <> + + + + + ); +}; +export default OperatorList; diff --git a/src/components/dashboard/damages/operator/RowActions/DamageItemDialog/DamageItemContent.jsx b/src/components/dashboard/damages/operator/RowActions/DamageItemDialog/DamageItemContent.jsx index 74ef578..cd69833 100644 --- a/src/components/dashboard/damages/operator/RowActions/DamageItemDialog/DamageItemContent.jsx +++ b/src/components/dashboard/damages/operator/RowActions/DamageItemDialog/DamageItemContent.jsx @@ -1,82 +1,82 @@ -import DialogLoading from "@/core/components/DialogLoading"; -import { GET_DAMAGE_ITEM_DETAILS, GET_RAHDARAN_ROAD_ITEM } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { - DialogContent, - Table, - TableBody, - TableCell, - TableContainer, - TableHead, - TableRow, - Typography, -} from "@mui/material"; -import { useEffect, useState } from "react"; - -const DamageItemContent = ({ rowId }) => { - const [loading, setLoading] = useState(true); - const [data, setData] = useState(null); - const request = useRequest(); - - useEffect(() => { - const fetchData = async () => { - try { - setLoading(true); - const response = await request(`${GET_DAMAGE_ITEM_DETAILS}/${rowId}`); - setData(response.data.data); - } catch (error) { - } finally { - setLoading(false); - } - }; - - fetchData(); - }, [rowId]); - - return ( - <> - - {loading ? ( - - ) : data.damages ? ( - - - - - نوع خسارت - میزان خسارت - هزینه خسارت (ریال) - - - - {data.damages.map((item) => { - return ( - - {item?.title} - - {(item?.pivot?.value / 1).toLocaleString()} ({item?.pivot?.unit}) - - {(item?.pivot?.amount / 1).toLocaleString()} - - ); - })} - - - اجرت نصب - - {(data.ojrate_nasb / 1).toLocaleString()} - - -
    -
    - ) : ( - اطلاعات یافت نشد - )} -
    - - ); -}; -export default DamageItemContent; +import DialogLoading from "@/core/components/DialogLoading"; +import { GET_DAMAGE_ITEM_DETAILS, GET_RAHDARAN_ROAD_ITEM } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { + DialogContent, + Table, + TableBody, + TableCell, + TableContainer, + TableHead, + TableRow, + Typography, +} from "@mui/material"; +import { useEffect, useState } from "react"; + +const DamageItemContent = ({ rowId }) => { + const [loading, setLoading] = useState(true); + const [data, setData] = useState(null); + const request = useRequest(); + + useEffect(() => { + const fetchData = async () => { + try { + setLoading(true); + const response = await request(`${GET_DAMAGE_ITEM_DETAILS}/${rowId}`); + setData(response.data.data); + } catch (error) { + } finally { + setLoading(false); + } + }; + + fetchData(); + }, [rowId]); + + return ( + <> + + {loading ? ( + + ) : data.damages ? ( + + + + + نوع خسارت + میزان خسارت + هزینه خسارت (ریال) + + + + {data.damages.map((item) => { + return ( + + {item?.title} + + {(item?.pivot?.value / 1).toLocaleString()} ({item?.pivot?.unit}) + + {(item?.pivot?.amount / 1).toLocaleString()} + + ); + })} + + + اجرت نصب + + {(data.ojrate_nasb / 1).toLocaleString()} + + +
    +
    + ) : ( + اطلاعات یافت نشد + )} +
    + + ); +}; +export default DamageItemContent; diff --git a/src/components/dashboard/damages/operator/RowActions/DamageItemDialog/index.jsx b/src/components/dashboard/damages/operator/RowActions/DamageItemDialog/index.jsx index 6164de2..d2ff78d 100644 --- a/src/components/dashboard/damages/operator/RowActions/DamageItemDialog/index.jsx +++ b/src/components/dashboard/damages/operator/RowActions/DamageItemDialog/index.jsx @@ -1,43 +1,43 @@ -import { Button, Dialog, DialogActions, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import MinorCrashIcon from "@mui/icons-material/MinorCrash"; -import { useState } from "react"; -import DamageItemContent from "./DamageItemContent"; - -const DamageItemDialog = ({ rowId }) => { - const [openDamageItemDialog, setOpenDamageItemDialog] = useState(false); - return ( - <> - - setOpenDamageItemDialog(true)}> - - - - setOpenDamageItemDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - آیتم های خسارت - {openDamageItemDialog && } - - - - - - ); -}; -export default DamageItemDialog; +import { Button, Dialog, DialogActions, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import MinorCrashIcon from "@mui/icons-material/MinorCrash"; +import { useState } from "react"; +import DamageItemContent from "./DamageItemContent"; + +const DamageItemDialog = ({ rowId }) => { + const [openDamageItemDialog, setOpenDamageItemDialog] = useState(false); + return ( + <> + + setOpenDamageItemDialog(true)}> + + + + setOpenDamageItemDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + آیتم های خسارت + {openDamageItemDialog && } + + + + + + ); +}; +export default DamageItemDialog; diff --git a/src/components/dashboard/damages/operator/RowActions/DamageReport/DamageReportContent.jsx b/src/components/dashboard/damages/operator/RowActions/DamageReport/DamageReportContent.jsx index 3876c57..8c8ba70 100644 --- a/src/components/dashboard/damages/operator/RowActions/DamageReport/DamageReportContent.jsx +++ b/src/components/dashboard/damages/operator/RowActions/DamageReport/DamageReportContent.jsx @@ -1,103 +1,103 @@ -import { Box, Button, Chip, DialogContent, Divider, Grid, Typography } from "@mui/material"; -import PaymentIcon from "@mui/icons-material/Payment"; -import moment from "jalali-moment"; -import DownloadIcon from "@mui/icons-material/Download"; -import FormatListNumberedIcon from "@mui/icons-material/FormatListNumbered"; -import EventNoteIcon from "@mui/icons-material/EventNote"; -import ImageIcon from "@mui/icons-material/Image"; - -const DamageReportContent = ({ damageReportDetails }) => { - return ( - <> - - - - - } - label={ - - نوع گزارش - - } - /> - - - - {damageReportDetails?.report_base === 1 - ? "بازدید عوامل و کارشناسان راهداری" - : "کروکی یا نامه پلیس راه"} - - - {damageReportDetails?.report_base === 0 && ( - <> - - - } - label={ - - شماره کروکی یا نامه پلیس راه - - } - /> - - - - {damageReportDetails?.police_serial} - - - - - } - label={ - - تاریخ کروکی یا نامه پلیس راه - - } - /> - - - - {moment(damageReportDetails?.police_file_date, "YYYY-MM-DD HH:mm:ss") - .locale("fa") - .format("YYYY/MM/DD")} - - - - - } - label={ - - تصویر کروکی یا نامه پلیس راه - - } - /> - - - - - - )} - - - - ); -}; -export default DamageReportContent; +import { Box, Button, Chip, DialogContent, Divider, Grid, Typography } from "@mui/material"; +import PaymentIcon from "@mui/icons-material/Payment"; +import moment from "jalali-moment"; +import DownloadIcon from "@mui/icons-material/Download"; +import FormatListNumberedIcon from "@mui/icons-material/FormatListNumbered"; +import EventNoteIcon from "@mui/icons-material/EventNote"; +import ImageIcon from "@mui/icons-material/Image"; + +const DamageReportContent = ({ damageReportDetails }) => { + return ( + <> + + + + + } + label={ + + نوع گزارش + + } + /> + + + + {damageReportDetails?.report_base === 1 + ? "بازدید عوامل و کارشناسان راهداری" + : "کروکی یا نامه پلیس راه"} + + + {damageReportDetails?.report_base === 0 && ( + <> + + + } + label={ + + شماره کروکی یا نامه پلیس راه + + } + /> + + + + {damageReportDetails?.police_serial} + + + + + } + label={ + + تاریخ کروکی یا نامه پلیس راه + + } + /> + + + + {moment(damageReportDetails?.police_file_date, "YYYY-MM-DD HH:mm:ss") + .locale("fa") + .format("YYYY/MM/DD")} + + + + + } + label={ + + تصویر کروکی یا نامه پلیس راه + + } + /> + + + + + + )} + + + + ); +}; +export default DamageReportContent; diff --git a/src/components/dashboard/damages/operator/RowActions/DamageReport/DamageReportController.jsx b/src/components/dashboard/damages/operator/RowActions/DamageReport/DamageReportController.jsx index 402911f..b83f7ba 100644 --- a/src/components/dashboard/damages/operator/RowActions/DamageReport/DamageReportController.jsx +++ b/src/components/dashboard/damages/operator/RowActions/DamageReport/DamageReportController.jsx @@ -1,34 +1,34 @@ -import useRequest from "@/lib/hooks/useRequest"; -import { useEffect, useState } from "react"; -import { GET_DAMAGE_ITEM_DETAILS } from "@/core/utils/routes"; -import DialogLoading from "@/core/components/DialogLoading"; -import DamageReportContent from "./DamageReportContent"; - -const DamageReportController = ({ rowId }) => { - const requestServer = useRequest(); - const [damageReportDetails, setDamageReportDetails] = useState(null); - const [damageItemDetailsLoading, setDamageItemDetailsLoading] = useState(false); - - useEffect(() => { - setDamageItemDetailsLoading(true); - requestServer(`${GET_DAMAGE_ITEM_DETAILS}/${rowId}`, "get") - .then((response) => { - setDamageReportDetails(response.data.data); - setDamageItemDetailsLoading(false); - }) - .catch((e) => { - setDamageItemDetailsLoading(false); - }); - }, [rowId]); - - return ( - <> - {damageItemDetailsLoading ? ( - - ) : ( - - )} - - ); -}; -export default DamageReportController; +import useRequest from "@/lib/hooks/useRequest"; +import { useEffect, useState } from "react"; +import { GET_DAMAGE_ITEM_DETAILS } from "@/core/utils/routes"; +import DialogLoading from "@/core/components/DialogLoading"; +import DamageReportContent from "./DamageReportContent"; + +const DamageReportController = ({ rowId }) => { + const requestServer = useRequest(); + const [damageReportDetails, setDamageReportDetails] = useState(null); + const [damageItemDetailsLoading, setDamageItemDetailsLoading] = useState(false); + + useEffect(() => { + setDamageItemDetailsLoading(true); + requestServer(`${GET_DAMAGE_ITEM_DETAILS}/${rowId}`, "get") + .then((response) => { + setDamageReportDetails(response.data.data); + setDamageItemDetailsLoading(false); + }) + .catch((e) => { + setDamageItemDetailsLoading(false); + }); + }, [rowId]); + + return ( + <> + {damageItemDetailsLoading ? ( + + ) : ( + + )} + + ); +}; +export default DamageReportController; diff --git a/src/components/dashboard/damages/operator/RowActions/DamageReport/index.jsx b/src/components/dashboard/damages/operator/RowActions/DamageReport/index.jsx index be283ab..ed48fb5 100644 --- a/src/components/dashboard/damages/operator/RowActions/DamageReport/index.jsx +++ b/src/components/dashboard/damages/operator/RowActions/DamageReport/index.jsx @@ -1,38 +1,38 @@ -import React, { useState } from "react"; -import { Tooltip, IconButton, Dialog, DialogTitle, DialogActions, Button } from "@mui/material"; -import AssessmentIcon from "@mui/icons-material/Assessment"; -import DamageReportController from "./DamageReportController"; -const DamageReportDialog = ({ rowId }) => { - const [openDamageReportDialog, setOpenDamageReportDialog] = useState(false); - - return ( - <> - - setOpenDamageReportDialog(true)}> - - - - setOpenDamageReportDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"sm"} - fullWidth - > - گزارش خسارت - {openDamageReportDialog && } - - - - - - ); -}; -export default DamageReportDialog; +import React, { useState } from "react"; +import { Tooltip, IconButton, Dialog, DialogTitle, DialogActions, Button } from "@mui/material"; +import AssessmentIcon from "@mui/icons-material/Assessment"; +import DamageReportController from "./DamageReportController"; +const DamageReportDialog = ({ rowId }) => { + const [openDamageReportDialog, setOpenDamageReportDialog] = useState(false); + + return ( + <> + + setOpenDamageReportDialog(true)}> + + + + setOpenDamageReportDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"sm"} + fullWidth + > + گزارش خسارت + {openDamageReportDialog && } + + + + + + ); +}; +export default DamageReportDialog; diff --git a/src/components/dashboard/damages/operator/RowActions/DeleteDialog/DeleteContent.jsx b/src/components/dashboard/damages/operator/RowActions/DeleteDialog/DeleteContent.jsx index 28791c7..3517f9f 100644 --- a/src/components/dashboard/damages/operator/RowActions/DeleteDialog/DeleteContent.jsx +++ b/src/components/dashboard/damages/operator/RowActions/DeleteDialog/DeleteContent.jsx @@ -1,39 +1,39 @@ -import { Button, DialogActions, DialogContent, Stack, Typography } from "@mui/material"; -import React, { useState } from "react"; -import useRequest from "@/lib/hooks/useRequest"; -import { DELETE_DAMAGE_ITEM } from "@/core/utils/routes"; - -const DeleteContent = ({ rowId, mutate, setOpenDeleteDialog }) => { - const [submitting, setSubmitting] = useState(false); - const requestServer = useRequest({ notificationSuccess: true }); - const handleClick = () => { - setSubmitting(true); - requestServer(`${DELETE_DAMAGE_ITEM}/${rowId}`, "delete") - .then(() => { - mutate(); - setOpenDeleteDialog(false); - setSubmitting(false); - }) - .catch(() => { - setSubmitting(false); - }); - }; - return ( - <> - - - آیا از حذف فعالیت اطمینان دارید؟ - - - - - - - - ); -}; -export default DeleteContent; +import { Button, DialogActions, DialogContent, Stack, Typography } from "@mui/material"; +import React, { useState } from "react"; +import useRequest from "@/lib/hooks/useRequest"; +import { DELETE_DAMAGE_ITEM } from "@/core/utils/routes"; + +const DeleteContent = ({ rowId, mutate, setOpenDeleteDialog }) => { + const [submitting, setSubmitting] = useState(false); + const requestServer = useRequest({ notificationSuccess: true }); + const handleClick = () => { + setSubmitting(true); + requestServer(`${DELETE_DAMAGE_ITEM}/${rowId}`, "delete") + .then(() => { + mutate(); + setOpenDeleteDialog(false); + setSubmitting(false); + }) + .catch(() => { + setSubmitting(false); + }); + }; + return ( + <> + + + آیا از حذف فعالیت اطمینان دارید؟ + + + + + + + + ); +}; +export default DeleteContent; diff --git a/src/components/dashboard/damages/operator/RowActions/DeleteDialog/index.jsx b/src/components/dashboard/damages/operator/RowActions/DeleteDialog/index.jsx index 145e323..b840802 100644 --- a/src/components/dashboard/damages/operator/RowActions/DeleteDialog/index.jsx +++ b/src/components/dashboard/damages/operator/RowActions/DeleteDialog/index.jsx @@ -1,34 +1,34 @@ -import DeleteIcon from "@mui/icons-material/Delete"; -import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import DeleteContent from "./DeleteContent"; -const DeleteDialog = ({ rowId, mutate }) => { - const [openDeleteDialog, setOpenDeleteDialog] = useState(false); - - return ( - <> - - setOpenDeleteDialog(true)}> - - - - setOpenDeleteDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - حذف فعالیت - {openDeleteDialog && ( - - )} - - - ); -}; -export default DeleteDialog; +import DeleteIcon from "@mui/icons-material/Delete"; +import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import DeleteContent from "./DeleteContent"; +const DeleteDialog = ({ rowId, mutate }) => { + const [openDeleteDialog, setOpenDeleteDialog] = useState(false); + + return ( + <> + + setOpenDeleteDialog(true)}> + + + + setOpenDeleteDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + حذف فعالیت + {openDeleteDialog && ( + + )} + + + ); +}; +export default DeleteDialog; diff --git a/src/components/dashboard/damages/operator/RowActions/ImageDialog/ImageFormContent.jsx b/src/components/dashboard/damages/operator/RowActions/ImageDialog/ImageFormContent.jsx index c8f22d0..f8fd088 100644 --- a/src/components/dashboard/damages/operator/RowActions/ImageDialog/ImageFormContent.jsx +++ b/src/components/dashboard/damages/operator/RowActions/ImageDialog/ImageFormContent.jsx @@ -1,45 +1,45 @@ -import { Box, Stack, Typography, useTheme } from "@mui/material"; -import Image from "next/image"; - -const ImageFormContent = ({ image, title }) => { - const theme = useTheme(); - return ( - - - {title} - - - Image - - - ); -}; -export default ImageFormContent; +import { Box, Stack, Typography, useTheme } from "@mui/material"; +import Image from "next/image"; + +const ImageFormContent = ({ image, title }) => { + const theme = useTheme(); + return ( + + + {title} + + + Image + + + ); +}; +export default ImageFormContent; diff --git a/src/components/dashboard/damages/operator/RowActions/ImageDialog/index.jsx b/src/components/dashboard/damages/operator/RowActions/ImageDialog/index.jsx index 74ade1d..10c7b28 100644 --- a/src/components/dashboard/damages/operator/RowActions/ImageDialog/index.jsx +++ b/src/components/dashboard/damages/operator/RowActions/ImageDialog/index.jsx @@ -1,44 +1,44 @@ -import { Button, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, Paper, Tooltip } from "@mui/material"; -import { useState } from "react"; -import PhotoLibraryIcon from "@mui/icons-material/PhotoLibrary"; -import ImageFormContent from "./ImageFormContent"; - -const ImageDialog = ({ images }) => { - const [openImageDialog, setOpenImageDialog] = useState(false); - - return ( - <> - - setOpenImageDialog(true)}> - - - - setOpenImageDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - maxWidth={"sm"} - scroll="paper" - > - تصاویر - {openImageDialog && ( - - - - - )} - - - - - - ); -}; -export default ImageDialog; +import { Button, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, Paper, Tooltip } from "@mui/material"; +import { useState } from "react"; +import PhotoLibraryIcon from "@mui/icons-material/PhotoLibrary"; +import ImageFormContent from "./ImageFormContent"; + +const ImageDialog = ({ images }) => { + const [openImageDialog, setOpenImageDialog] = useState(false); + + return ( + <> + + setOpenImageDialog(true)}> + + + + setOpenImageDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + maxWidth={"sm"} + scroll="paper" + > + تصاویر + {openImageDialog && ( + + + + + )} + + + + + + ); +}; +export default ImageDialog; diff --git a/src/components/dashboard/damages/operator/RowActions/LocationForm/LocationFormContent.jsx b/src/components/dashboard/damages/operator/RowActions/LocationForm/LocationFormContent.jsx index 14b3db3..08e4730 100644 --- a/src/components/dashboard/damages/operator/RowActions/LocationForm/LocationFormContent.jsx +++ b/src/components/dashboard/damages/operator/RowActions/LocationForm/LocationFormContent.jsx @@ -1,35 +1,35 @@ -"use client"; -import { Box, Button, DialogActions, DialogContent, Stack } from "@mui/material"; -import React from "react"; -import dynamic from "next/dynamic"; -import MapLoading from "@/core/components/MapLayer/Loading"; -import ShowLocationMarker from "@/core/components/ShowLocationMarker"; -const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { - loading: () => , - ssr: false, -}); - -const LocationFormContent = ({ setOpenLocationDialog, start_lat, start_lng, end_lat, end_lng }) => { - return ( - <> - - - - - - - - - - - - ); -}; -export default LocationFormContent; +"use client"; +import { Box, Button, DialogActions, DialogContent, Stack } from "@mui/material"; +import React from "react"; +import dynamic from "next/dynamic"; +import MapLoading from "@/core/components/MapLayer/Loading"; +import ShowLocationMarker from "@/core/components/ShowLocationMarker"; +const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { + loading: () => , + ssr: false, +}); + +const LocationFormContent = ({ setOpenLocationDialog, start_lat, start_lng, end_lat, end_lng }) => { + return ( + <> + + + + + + + + + + + + ); +}; +export default LocationFormContent; diff --git a/src/components/dashboard/damages/operator/RowActions/LocationForm/index.jsx b/src/components/dashboard/damages/operator/RowActions/LocationForm/index.jsx index d614215..6c90746 100644 --- a/src/components/dashboard/damages/operator/RowActions/LocationForm/index.jsx +++ b/src/components/dashboard/damages/operator/RowActions/LocationForm/index.jsx @@ -1,40 +1,40 @@ -import React, { useState } from "react"; -import { Tooltip, IconButton, Dialog, DialogTitle } from "@mui/material"; -import ExploreIcon from "@mui/icons-material/Explore"; -import LocationFormContent from "./LocationFormContent"; -const LocationForm = ({ start_lat, start_lng, end_lat, end_lng }) => { - const [openLocationDialog, setOpenLocationDialog] = useState(false); - - return ( - <> - - setOpenLocationDialog(true)}> - - - - setOpenLocationDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - موقعیت - {openLocationDialog && ( - - )} - - - ); -}; -export default LocationForm; +import React, { useState } from "react"; +import { Tooltip, IconButton, Dialog, DialogTitle } from "@mui/material"; +import ExploreIcon from "@mui/icons-material/Explore"; +import LocationFormContent from "./LocationFormContent"; +const LocationForm = ({ start_lat, start_lng, end_lat, end_lng }) => { + const [openLocationDialog, setOpenLocationDialog] = useState(false); + + return ( + <> + + setOpenLocationDialog(true)}> + + + + setOpenLocationDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + موقعیت + {openLocationDialog && ( + + )} + + + ); +}; +export default LocationForm; diff --git a/src/components/dashboard/damages/operator/RowActions/PoliceRahLetter/PoliceRahLetterContent.jsx b/src/components/dashboard/damages/operator/RowActions/PoliceRahLetter/PoliceRahLetterContent.jsx index a4d4b63..23943b6 100644 --- a/src/components/dashboard/damages/operator/RowActions/PoliceRahLetter/PoliceRahLetterContent.jsx +++ b/src/components/dashboard/damages/operator/RowActions/PoliceRahLetter/PoliceRahLetterContent.jsx @@ -1,40 +1,40 @@ -import { Button, DialogActions, DialogContent, Stack, Typography } from "@mui/material"; -import React, { useState } from "react"; -import useRequest from "@/lib/hooks/useRequest"; -import { GET_POLICERAH, GET_POLICERAH_PAGE } from "@/core/utils/routes"; - -const PoliceRahLetterContent = ({ setOpenPoliceRahDialog, rowId, mutate }) => { - const [submitting, setSubmitting] = useState(false); - const requestServer = useRequest(); - const handleClick = () => { - setSubmitting(true); - requestServer(`${GET_POLICERAH}/${rowId}`, "get") - .then(() => { - mutate(); - window.open(`${GET_POLICERAH_PAGE}/${rowId}`, "_blank"); - setSubmitting(false); - setOpenPoliceRahDialog(false); - }) - .catch(() => { - setSubmitting(false); - }); - }; - return ( - <> - - - آیا از صدور نامه به پلیس راه اطمینان دارید؟ - - - - - - - - ); -}; -export default PoliceRahLetterContent; +import { Button, DialogActions, DialogContent, Stack, Typography } from "@mui/material"; +import React, { useState } from "react"; +import useRequest from "@/lib/hooks/useRequest"; +import { GET_POLICERAH, GET_POLICERAH_PAGE } from "@/core/utils/routes"; + +const PoliceRahLetterContent = ({ setOpenPoliceRahDialog, rowId, mutate }) => { + const [submitting, setSubmitting] = useState(false); + const requestServer = useRequest(); + const handleClick = () => { + setSubmitting(true); + requestServer(`${GET_POLICERAH}/${rowId}`, "get") + .then(() => { + mutate(); + window.open(`${GET_POLICERAH_PAGE}/${rowId}`, "_blank"); + setSubmitting(false); + setOpenPoliceRahDialog(false); + }) + .catch(() => { + setSubmitting(false); + }); + }; + return ( + <> + + + آیا از صدور نامه به پلیس راه اطمینان دارید؟ + + + + + + + + ); +}; +export default PoliceRahLetterContent; diff --git a/src/components/dashboard/damages/operator/RowActions/PoliceRahLetter/index.jsx b/src/components/dashboard/damages/operator/RowActions/PoliceRahLetter/index.jsx index ab064d9..4bf152c 100644 --- a/src/components/dashboard/damages/operator/RowActions/PoliceRahLetter/index.jsx +++ b/src/components/dashboard/damages/operator/RowActions/PoliceRahLetter/index.jsx @@ -1,38 +1,38 @@ -import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import GarageIcon from "@mui/icons-material/Garage"; -import React, { useState } from "react"; -import PoliceRahLetterContent from "./PoliceRahLetterContent"; - -const PoliceRahLetter = ({ rowId, mutate }) => { - const [openPoliceRahDialog, setOpenPoliceRahDialog] = useState(false); - return ( - <> - - setOpenPoliceRahDialog(true)}> - - - - setOpenPoliceRahDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - maxWidth={"xs"} - scroll="paper" - > - صدور نامه پلیس راه - {openPoliceRahDialog && ( - - )} - - - ); -}; -export default PoliceRahLetter; +import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import GarageIcon from "@mui/icons-material/Garage"; +import React, { useState } from "react"; +import PoliceRahLetterContent from "./PoliceRahLetterContent"; + +const PoliceRahLetter = ({ rowId, mutate }) => { + const [openPoliceRahDialog, setOpenPoliceRahDialog] = useState(false); + return ( + <> + + setOpenPoliceRahDialog(true)}> + + + + setOpenPoliceRahDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + maxWidth={"xs"} + scroll="paper" + > + صدور نامه پلیس راه + {openPoliceRahDialog && ( + + )} + + + ); +}; +export default PoliceRahLetter; diff --git a/src/components/dashboard/damages/operator/RowActions/SendToInsurance/SendToInsuranceContent.jsx b/src/components/dashboard/damages/operator/RowActions/SendToInsurance/SendToInsuranceContent.jsx index 4747d12..83b9d44 100644 --- a/src/components/dashboard/damages/operator/RowActions/SendToInsurance/SendToInsuranceContent.jsx +++ b/src/components/dashboard/damages/operator/RowActions/SendToInsurance/SendToInsuranceContent.jsx @@ -1,43 +1,43 @@ -import { Alert, Button, DialogActions, DialogContent, Stack, Typography } from "@mui/material"; -import React, { useState } from "react"; -import useRequest from "@/lib/hooks/useRequest"; -import { GET_INSURANCE, GET_INSURANCE_PAGE } from "@/core/utils/routes"; - -const SendToInsuranceContent = ({ setOpenSendInsuranceDialog, rowId, mutate }) => { - const [submitting, setSubmitting] = useState(false); - const requestServer = useRequest(); - const handleClick = () => { - setSubmitting(true); - requestServer(`${GET_INSURANCE}/${rowId}`, "get") - .then(() => { - mutate(); - window.open(`${GET_INSURANCE_PAGE}/${rowId}`, "_blank"); - setSubmitting(false); - setOpenSendInsuranceDialog(false); - }) - .catch(() => { - setSubmitting(false); - }); - }; - return ( - <> - - - آیا از صدور نامه بیمه اطمینان دارید؟ - - در صورت صدور نامه بیمه، اطلاعات قابل ویرایش یا حذف نخواهند بود - - - - - - - - - ); -}; -export default SendToInsuranceContent; +import { Alert, Button, DialogActions, DialogContent, Stack, Typography } from "@mui/material"; +import React, { useState } from "react"; +import useRequest from "@/lib/hooks/useRequest"; +import { GET_INSURANCE, GET_INSURANCE_PAGE } from "@/core/utils/routes"; + +const SendToInsuranceContent = ({ setOpenSendInsuranceDialog, rowId, mutate }) => { + const [submitting, setSubmitting] = useState(false); + const requestServer = useRequest(); + const handleClick = () => { + setSubmitting(true); + requestServer(`${GET_INSURANCE}/${rowId}`, "get") + .then(() => { + mutate(); + window.open(`${GET_INSURANCE_PAGE}/${rowId}`, "_blank"); + setSubmitting(false); + setOpenSendInsuranceDialog(false); + }) + .catch(() => { + setSubmitting(false); + }); + }; + return ( + <> + + + آیا از صدور نامه بیمه اطمینان دارید؟ + + در صورت صدور نامه بیمه، اطلاعات قابل ویرایش یا حذف نخواهند بود + + + + + + + + + ); +}; +export default SendToInsuranceContent; diff --git a/src/components/dashboard/damages/operator/RowActions/SendToInsurance/index.jsx b/src/components/dashboard/damages/operator/RowActions/SendToInsurance/index.jsx index d1d578a..940e661 100644 --- a/src/components/dashboard/damages/operator/RowActions/SendToInsurance/index.jsx +++ b/src/components/dashboard/damages/operator/RowActions/SendToInsurance/index.jsx @@ -1,38 +1,38 @@ -import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import EmailIcon from "@mui/icons-material/Email"; -import React, { useState } from "react"; -import SendToInsuranceContent from "./SendToInsuranceContent"; - -const SendToInsurance = ({ rowId, mutate }) => { - const [openSendInsuranceDialog, setOpenSendInsuranceDialog] = useState(false); - return ( - <> - - setOpenSendInsuranceDialog(true)}> - - - - setOpenSendInsuranceDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - maxWidth={"xs"} - scroll="paper" - > - نامه بیمه - {openSendInsuranceDialog && ( - - )} - - - ); -}; -export default SendToInsurance; +import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import EmailIcon from "@mui/icons-material/Email"; +import React, { useState } from "react"; +import SendToInsuranceContent from "./SendToInsuranceContent"; + +const SendToInsurance = ({ rowId, mutate }) => { + const [openSendInsuranceDialog, setOpenSendInsuranceDialog] = useState(false); + return ( + <> + + setOpenSendInsuranceDialog(true)}> + + + + setOpenSendInsuranceDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + maxWidth={"xs"} + scroll="paper" + > + نامه بیمه + {openSendInsuranceDialog && ( + + )} + + + ); +}; +export default SendToInsurance; diff --git a/src/components/dashboard/damages/operator/RowActions/ShowPlate/index.jsx b/src/components/dashboard/damages/operator/RowActions/ShowPlate/index.jsx index af1f495..47b53e8 100644 --- a/src/components/dashboard/damages/operator/RowActions/ShowPlate/index.jsx +++ b/src/components/dashboard/damages/operator/RowActions/ShowPlate/index.jsx @@ -1,38 +1,38 @@ -import { Stack } from "@mui/material"; - -const ShowPlate = ({ plate }) => { - return ( - - - {plate.split("-")[3]} - - - - {plate.split("-")[2]} - - - {plate.split("-")[1]} - - - {plate.split("-")[0]} - - - - ); -}; -export default ShowPlate; +import { Stack } from "@mui/material"; + +const ShowPlate = ({ plate }) => { + return ( + + + {plate.split("-")[3]} + + + + {plate.split("-")[2]} + + + {plate.split("-")[1]} + + + {plate.split("-")[0]} + + + + ); +}; +export default ShowPlate; diff --git a/src/components/dashboard/damages/operator/RowActions/index.jsx b/src/components/dashboard/damages/operator/RowActions/index.jsx index bd0a83f..c1e47d2 100644 --- a/src/components/dashboard/damages/operator/RowActions/index.jsx +++ b/src/components/dashboard/damages/operator/RowActions/index.jsx @@ -1,35 +1,35 @@ -import { Box } from "@mui/material"; -import RegisterInsurance from "../Form/RegisterInsurance"; -import CreateFactor from "../Form/CreateFactor"; -import DeleteDialog from "./DeleteDialog"; -import SendToInsurance from "./SendToInsurance"; -import PoliceRahLetter from "./PoliceRahLetter"; -import EditForm from "../Form/EditForm"; -import { usePermissions } from "@/lib/hooks/usePermissions"; - -const RowActions = ({ row, mutate }) => { - const { data: userPermissions } = usePermissions(); - const hasDeletePermission = userPermissions.some((item) => - ["delete-receipt", "delete-receipt-province"].includes(item) - ); - const hasEditPermission = userPermissions.some((item) => ["edit-receipt", "edit-receipt-province"].includes(item)); - return ( - - {[4, 5].includes(row.original?.status) && } - {[2, 3].includes(row.original?.status) && ( - - )} - {[1, 2].includes(row.original?.status) && ( - - )} - {[0, 1, 2].includes(row.original?.status) && } - {hasEditPermission && [0].includes(row.original?.status) && ( - - )} - {hasDeletePermission && [0].includes(row.original?.status) && ( - - )} - - ); -}; -export default RowActions; +import { Box } from "@mui/material"; +import RegisterInsurance from "../Form/RegisterInsurance"; +import CreateFactor from "../Form/CreateFactor"; +import DeleteDialog from "./DeleteDialog"; +import SendToInsurance from "./SendToInsurance"; +import PoliceRahLetter from "./PoliceRahLetter"; +import EditForm from "../Form/EditForm"; +import { usePermissions } from "@/lib/hooks/usePermissions"; + +const RowActions = ({ row, mutate }) => { + const { data: userPermissions } = usePermissions(); + const hasDeletePermission = userPermissions.some((item) => + ["delete-receipt", "delete-receipt-province"].includes(item) + ); + const hasEditPermission = userPermissions.some((item) => ["edit-receipt", "edit-receipt-province"].includes(item)); + return ( + + {[4, 5].includes(row.original?.status) && } + {[2, 3].includes(row.original?.status) && ( + + )} + {[1, 2].includes(row.original?.status) && ( + + )} + {[0, 1, 2].includes(row.original?.status) && } + {hasEditPermission && [0].includes(row.original?.status) && ( + + )} + {hasDeletePermission && [0].includes(row.original?.status) && ( + + )} + + ); +}; +export default RowActions; diff --git a/src/components/dashboard/damages/operator/Toolbar.jsx b/src/components/dashboard/damages/operator/Toolbar.jsx index 3024621..195bf0f 100644 --- a/src/components/dashboard/damages/operator/Toolbar.jsx +++ b/src/components/dashboard/damages/operator/Toolbar.jsx @@ -1,16 +1,16 @@ -import { Box } from "@mui/material"; -import OperatorCreate from "./Actions/create"; -import PrintExcel from "./ExcelPrint"; -import { usePermissions } from "@/lib/hooks/usePermissions"; - -const Toolbar = ({ table, filterData, mutate }) => { - const { data: userPermissions } = usePermissions(); - const hasAddPermission = userPermissions.some((item) => ["add-receipt", "add-receipt-province"].includes(item)); - return ( - - - {hasAddPermission && } - - ); -}; -export default Toolbar; +import { Box } from "@mui/material"; +import OperatorCreate from "./Actions/create"; +import PrintExcel from "./ExcelPrint"; +import { usePermissions } from "@/lib/hooks/usePermissions"; + +const Toolbar = ({ table, filterData, mutate }) => { + const { data: userPermissions } = usePermissions(); + const hasAddPermission = userPermissions.some((item) => ["add-receipt", "add-receipt-province"].includes(item)); + return ( + + + {hasAddPermission && } + + ); +}; +export default Toolbar; diff --git a/src/components/dashboard/damages/operator/index.jsx b/src/components/dashboard/damages/operator/index.jsx index 8bbaeb6..9fc6158 100644 --- a/src/components/dashboard/damages/operator/index.jsx +++ b/src/components/dashboard/damages/operator/index.jsx @@ -1,14 +1,14 @@ -"use client"; -import PageTitle from "@/core/components/PageTitle"; -import { Stack } from "@mui/material"; -import OperatorList from "./OperatorList"; - -const OperatorPage = () => { - return ( - - - - - ); -}; -export default OperatorPage; +"use client"; +import PageTitle from "@/core/components/PageTitle"; +import { Stack } from "@mui/material"; +import OperatorList from "./OperatorList"; + +const OperatorPage = () => { + return ( + + + + + ); +}; +export default OperatorPage; diff --git a/src/components/dashboard/damages/report/ExcelPrint/index.jsx b/src/components/dashboard/damages/report/ExcelPrint/index.jsx index 2922a18..defc12f 100644 --- a/src/components/dashboard/damages/report/ExcelPrint/index.jsx +++ b/src/components/dashboard/damages/report/ExcelPrint/index.jsx @@ -1,72 +1,72 @@ -"use client"; -import { EXPORT_COUNTRY_RECEIPT_REPORT, EXPORT_PROVINCE_RECEIPT_REPORT } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { useTheme } from "@emotion/react"; -import DescriptionIcon from "@mui/icons-material/Description"; -import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; -import FileSaver from "file-saver"; -import moment from "jalali-moment"; -import { useMemo, useState } from "react"; - -const PrintExcel = ({ table, filterData }) => { - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const [loading, setLoading] = useState(false); - const requestServer = useRequest({ notificationSuccess: true }); - const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { - if (filter.value) { - acc.push({ id: filter.id, value: filter.value }); - } - return acc; - }, []); - - const filterParams = useMemo(() => { - const params = new URLSearchParams(); - activeFilters.length > 0 && - activeFilters.map((filter, index) => { - params.set(`${filter.id}`, filter.value); - }); - return params; - }, [activeFilters]); - - const clickHandler = () => { - setLoading(true); - const CountryOrProvince = activeFilters.find((item) => item.id === "province_id"); - const requestUrl = - CountryOrProvince.value === "-1" ? EXPORT_COUNTRY_RECEIPT_REPORT : EXPORT_PROVINCE_RECEIPT_REPORT; - requestServer(`${requestUrl}?${filterParams}`, "get", { - requestOptions: { responseType: "blob" }, - }) - .then((response) => { - const filename = `خروجی کارتابل گزارشات خسارات وارده بر ابنیه فنی تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; - FileSaver.saveAs(response.data, filename); - }) - .catch(() => {}) - .finally(() => { - setLoading(false); - }); - }; - - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - - ); -}; -export default PrintExcel; +"use client"; +import { EXPORT_COUNTRY_RECEIPT_REPORT, EXPORT_PROVINCE_RECEIPT_REPORT } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { useTheme } from "@emotion/react"; +import DescriptionIcon from "@mui/icons-material/Description"; +import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; +import FileSaver from "file-saver"; +import moment from "jalali-moment"; +import { useMemo, useState } from "react"; + +const PrintExcel = ({ table, filterData }) => { + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const [loading, setLoading] = useState(false); + const requestServer = useRequest({ notificationSuccess: true }); + const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { + if (filter.value) { + acc.push({ id: filter.id, value: filter.value }); + } + return acc; + }, []); + + const filterParams = useMemo(() => { + const params = new URLSearchParams(); + activeFilters.length > 0 && + activeFilters.map((filter, index) => { + params.set(`${filter.id}`, filter.value); + }); + return params; + }, [activeFilters]); + + const clickHandler = () => { + setLoading(true); + const CountryOrProvince = activeFilters.find((item) => item.id === "province_id"); + const requestUrl = + CountryOrProvince.value === "-1" ? EXPORT_COUNTRY_RECEIPT_REPORT : EXPORT_PROVINCE_RECEIPT_REPORT; + requestServer(`${requestUrl}?${filterParams}`, "get", { + requestOptions: { responseType: "blob" }, + }) + .then((response) => { + const filename = `خروجی کارتابل گزارشات خسارات وارده بر ابنیه فنی تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; + FileSaver.saveAs(response.data, filename); + }) + .catch(() => {}) + .finally(() => { + setLoading(false); + }); + }; + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + + ); +}; +export default PrintExcel; diff --git a/src/components/dashboard/damages/report/ReportLists.jsx b/src/components/dashboard/damages/report/ReportLists.jsx index 88ce8d5..16572cf 100644 --- a/src/components/dashboard/damages/report/ReportLists.jsx +++ b/src/components/dashboard/damages/report/ReportLists.jsx @@ -1,323 +1,323 @@ -"use client"; -import DataTableWithAuth from "@/core/components/DataTableWithAuth"; -import { Box } from "@mui/material"; -import { useMemo } from "react"; -import Toolbar from "./Toolbar"; - -const ReportLists = ({ data, specialFilter }) => { - const columns = useMemo(() => { - return [ - { - accessorKey: "edare_name", - header: "اداره", - id: "edare_name", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - }, - { - header: "تعداد خسارات ثبت شده", - id: "countAll", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - columns: [ - { - accessorKey: "tedade", - header: "کل", - id: "tedade", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - { - accessorKey: "egdam", - header: "در دست اقدام", - id: "egdam", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - { - accessorKey: "pardakht", - header: "در حال پرداخت", - id: "pardakht", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - { - accessorKey: "khatm", - header: "خاتمه یافته", - id: "khatm", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - ], - }, - { - header: "تعداد نحوه شناسایی خسارت", - id: "police_rah_All", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - columns: [ - { - accessorKey: "police_rah", - header: "گزارش پلیس راه", - id: "police_rah", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - { - accessorKey: "gozaresh_gasht", - header: "گزارش گشت راهداری", - id: "gozaresh_gasht", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - ], - }, - { - accessorKey: "kol_sabt_shode", - header: "مبلغ کل خسارات ثبت شده (ریال)", - id: "kol_sabt_shode", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - { - accessorKey: "vasel_shode", - header: "کل مبلغ وصول شده (ریال)", - id: "vasel_shode", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - { - header: "مبلغ وصول شده به تفکیک نوع پرداخت (ریال)", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - columns: [ - { - accessorKey: "vasel_shode_final", - header: "فاکتور", - id: "vasel_shode_final", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - { - accessorKey: "vasel_shode_bimeh", - header: "بیمه", - id: "vasel_shode_bimeh", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - { - accessorKey: "vasel_shode_daghi", - header: "داغی", - id: "vasel_shode_daghi", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - ], - }, - ]; - }, []); - - return ( - - - - ); -}; - -export default ReportLists; +"use client"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import { Box } from "@mui/material"; +import { useMemo } from "react"; +import Toolbar from "./Toolbar"; + +const ReportLists = ({ data, specialFilter }) => { + const columns = useMemo(() => { + return [ + { + accessorKey: "edare_name", + header: "اداره", + id: "edare_name", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + }, + { + header: "تعداد خسارات ثبت شده", + id: "countAll", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + columns: [ + { + accessorKey: "tedade", + header: "کل", + id: "tedade", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + { + accessorKey: "egdam", + header: "در دست اقدام", + id: "egdam", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + { + accessorKey: "pardakht", + header: "در حال پرداخت", + id: "pardakht", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + { + accessorKey: "khatm", + header: "خاتمه یافته", + id: "khatm", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + ], + }, + { + header: "تعداد نحوه شناسایی خسارت", + id: "police_rah_All", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + columns: [ + { + accessorKey: "police_rah", + header: "گزارش پلیس راه", + id: "police_rah", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + { + accessorKey: "gozaresh_gasht", + header: "گزارش گشت راهداری", + id: "gozaresh_gasht", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + ], + }, + { + accessorKey: "kol_sabt_shode", + header: "مبلغ کل خسارات ثبت شده (ریال)", + id: "kol_sabt_shode", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + { + accessorKey: "vasel_shode", + header: "کل مبلغ وصول شده (ریال)", + id: "vasel_shode", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + { + header: "مبلغ وصول شده به تفکیک نوع پرداخت (ریال)", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + columns: [ + { + accessorKey: "vasel_shode_final", + header: "فاکتور", + id: "vasel_shode_final", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + { + accessorKey: "vasel_shode_bimeh", + header: "بیمه", + id: "vasel_shode_bimeh", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + { + accessorKey: "vasel_shode_daghi", + header: "داغی", + id: "vasel_shode_daghi", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + ], + }, + ]; + }, []); + + return ( + + + + ); +}; + +export default ReportLists; diff --git a/src/components/dashboard/damages/report/Search/FromDateController.jsx b/src/components/dashboard/damages/report/Search/FromDateController.jsx index 02d92bd..2303eba 100644 --- a/src/components/dashboard/damages/report/Search/FromDateController.jsx +++ b/src/components/dashboard/damages/report/Search/FromDateController.jsx @@ -1,28 +1,28 @@ -import { Controller } from "react-hook-form"; -import MuiDatePicker from "@/core/components/MuiDatePicker"; -import React from "react"; -import moment from "jalali-moment"; - -const FromDateController = ({ control }) => { - return ( - ( - { - const formattedDate = moment(new Date(newValue)).locale("en").format("YYYY-MM-DD"); - onChange(formattedDate); // Update the field value in react-hook-form - }} - helperText={error ? error.message : null} - /> - )} - /> - ); -}; -export default FromDateController; +import { Controller } from "react-hook-form"; +import MuiDatePicker from "@/core/components/MuiDatePicker"; +import React from "react"; +import moment from "jalali-moment"; + +const FromDateController = ({ control }) => { + return ( + ( + { + const formattedDate = moment(new Date(newValue)).locale("en").format("YYYY-MM-DD"); + onChange(formattedDate); // Update the field value in react-hook-form + }} + helperText={error ? error.message : null} + /> + )} + /> + ); +}; +export default FromDateController; diff --git a/src/components/dashboard/damages/report/Search/SearchReportField.jsx b/src/components/dashboard/damages/report/Search/SearchReportField.jsx index ab8442c..5c6aa23 100644 --- a/src/components/dashboard/damages/report/Search/SearchReportField.jsx +++ b/src/components/dashboard/damages/report/Search/SearchReportField.jsx @@ -1,45 +1,45 @@ -import { Button, Grid, LinearProgress, Typography } from "@mui/material"; -import SearchIcon from "@mui/icons-material/Search"; -import React from "react"; -import FromDateController from "./FromDateController"; -import ToDateController from "./ToDateController"; -import SelectProvince from "./SelectProvince"; -import { Controller } from "react-hook-form"; - -const SearchReportField = ({ control, hasProvincesPermission }) => { - return ( - - - - - - - - {hasProvincesPermission && ( - - - - )} - - ( - - )} - /> - - - ); -}; - -export default SearchReportField; +import { Button, Grid, LinearProgress, Typography } from "@mui/material"; +import SearchIcon from "@mui/icons-material/Search"; +import React from "react"; +import FromDateController from "./FromDateController"; +import ToDateController from "./ToDateController"; +import SelectProvince from "./SelectProvince"; +import { Controller } from "react-hook-form"; + +const SearchReportField = ({ control, hasProvincesPermission }) => { + return ( + + + + + + + + {hasProvincesPermission && ( + + + + )} + + ( + + )} + /> + + + ); +}; + +export default SearchReportField; diff --git a/src/components/dashboard/damages/report/Search/SelectProvince.jsx b/src/components/dashboard/damages/report/Search/SelectProvince.jsx index b1d8a39..7f738bc 100644 --- a/src/components/dashboard/damages/report/Search/SelectProvince.jsx +++ b/src/components/dashboard/damages/report/Search/SelectProvince.jsx @@ -1,47 +1,47 @@ -import { Controller } from "react-hook-form"; -import MuiDatePicker from "@/core/components/MuiDatePicker"; -import React from "react"; -import { FormControl, FormHelperText, InputLabel, LinearProgress, MenuItem, Select, Typography } from "@mui/material"; -import useProvinces from "@/lib/hooks/useProvince"; - -const SelectProvince = ({ control }) => { - const { provinces, loadingProvinces, errorProvinces } = useProvinces(); - return ( - ( - - استان - - {error && {error.message}} - - )} - /> - ); -}; -export default SelectProvince; +import { Controller } from "react-hook-form"; +import MuiDatePicker from "@/core/components/MuiDatePicker"; +import React from "react"; +import { FormControl, FormHelperText, InputLabel, LinearProgress, MenuItem, Select, Typography } from "@mui/material"; +import useProvinces from "@/lib/hooks/useProvince"; + +const SelectProvince = ({ control }) => { + const { provinces, loadingProvinces, errorProvinces } = useProvinces(); + return ( + ( + + استان + + {error && {error.message}} + + )} + /> + ); +}; +export default SelectProvince; diff --git a/src/components/dashboard/damages/report/Search/ToDateController.jsx b/src/components/dashboard/damages/report/Search/ToDateController.jsx index 4e41124..8e23f76 100644 --- a/src/components/dashboard/damages/report/Search/ToDateController.jsx +++ b/src/components/dashboard/damages/report/Search/ToDateController.jsx @@ -1,30 +1,30 @@ -import { Controller, useWatch } from "react-hook-form"; -import MuiDatePicker from "@/core/components/MuiDatePicker"; -import React from "react"; -import moment from "jalali-moment"; - -const ToDateController = ({ control }) => { - const minDate = useWatch({ control, name: "from_date" }); - return ( - ( - { - const formattedDate = moment(new Date(newValue)).locale("en").format("YYYY-MM-DD"); - onChange(formattedDate); // Update the field value in react-hook-form - }} - helperText={error ? error.message : null} - /> - )} - /> - ); -}; -export default ToDateController; +import { Controller, useWatch } from "react-hook-form"; +import MuiDatePicker from "@/core/components/MuiDatePicker"; +import React from "react"; +import moment from "jalali-moment"; + +const ToDateController = ({ control }) => { + const minDate = useWatch({ control, name: "from_date" }); + return ( + ( + { + const formattedDate = moment(new Date(newValue)).locale("en").format("YYYY-MM-DD"); + onChange(formattedDate); // Update the field value in react-hook-form + }} + helperText={error ? error.message : null} + /> + )} + /> + ); +}; +export default ToDateController; diff --git a/src/components/dashboard/damages/report/Search/index.jsx b/src/components/dashboard/damages/report/Search/index.jsx index f29d302..9d504f2 100644 --- a/src/components/dashboard/damages/report/Search/index.jsx +++ b/src/components/dashboard/damages/report/Search/index.jsx @@ -1,13 +1,13 @@ -import StyledForm from "@/core/components/StyledForm"; -import SearchReportField from "./SearchReportField"; - -const SearchReportList = ({ handleSubmit, onSearchSubmit, control, hasProvincesPermission }) => { - return ( - <> - - - - - ); -}; -export default SearchReportList; +import StyledForm from "@/core/components/StyledForm"; +import SearchReportField from "./SearchReportField"; + +const SearchReportList = ({ handleSubmit, onSearchSubmit, control, hasProvincesPermission }) => { + return ( + <> + + + + + ); +}; +export default SearchReportList; diff --git a/src/components/dashboard/damages/report/Toolbar.jsx b/src/components/dashboard/damages/report/Toolbar.jsx index 7dd930f..3e5ab8c 100644 --- a/src/components/dashboard/damages/report/Toolbar.jsx +++ b/src/components/dashboard/damages/report/Toolbar.jsx @@ -1,11 +1,11 @@ -import PrintExcel from "./ExcelPrint"; -import { Box } from "@mui/material"; - -const Toolbar = ({ table, filterData, mutate }) => { - return ( - - - - ); -}; -export default Toolbar; +import PrintExcel from "./ExcelPrint"; +import { Box } from "@mui/material"; + +const Toolbar = ({ table, filterData, mutate }) => { + return ( + + + + ); +}; +export default Toolbar; diff --git a/src/components/dashboard/damages/report/index.jsx b/src/components/dashboard/damages/report/index.jsx index 8505f2f..799ec2c 100644 --- a/src/components/dashboard/damages/report/index.jsx +++ b/src/components/dashboard/damages/report/index.jsx @@ -1,137 +1,137 @@ -"use client"; -import PageTitle from "@/core/components/PageTitle"; -import { GET_PROVINCE_RECEIPT_REPORT, GET_COUNTRY_RECEIPT_REPORT } from "@/core/utils/routes"; -import { useAuth } from "@/lib/contexts/auth"; -import { usePermissions } from "@/lib/hooks/usePermissions"; -import useRequest from "@/lib/hooks/useRequest"; -import { yupResolver } from "@hookform/resolvers/yup"; -import { LinearProgress, Stack } from "@mui/material"; -import moment from "jalali-moment"; -import { useEffect, useState } from "react"; -import { useForm } from "react-hook-form"; -import * as yup from "yup"; -import SearchReportList from "./Search"; -import ReportLists from "./ReportLists"; - -const DamagesReportPage = () => { - const [data, setData] = useState(null); - const { data: userPermissions } = usePermissions(); - const { user } = useAuth(); - const requestServer = useRequest(); - const hasProvincesPermission = userPermissions?.includes("show-receipt"); - - const defaultValues = { - from_date: moment(new Date()).format("YYYY-MM-DD"), - date_to: moment(new Date()).format("YYYY-MM-DD"), - province_id: hasProvincesPermission ? "-1" : user.province_id, - }; - const defaultFilter = [ - { value: `${defaultValues.province_id}`, datatype: "numeric", id: "province_id", fn: "equals" }, - { value: `${defaultValues.from_date}`, datatype: "date", id: "from_date", fn: "between" }, - { value: `${defaultValues.date_to}`, datatype: "date", id: "date_to", fn: "between" }, - ]; - const [specialFilter, setSpecialFilter] = useState(defaultFilter); - - const onSearchSubmit = async (data) => { - const params = new URLSearchParams(); - params.set("from_date", `${data.from_date}`); - params.set("date_to", `${data.date_to}`); - setSpecialFilter([ - { value: `${data.province_id}`, datatype: "numeric", id: "province_id", fn: "equals" }, - { value: `${data.from_date}`, datatype: "date", id: "from_date", fn: "between" }, - { value: `${data.date_to}`, datatype: "date", id: "date_to", fn: "between" }, - ]); - if (data.province_id === "-1") { - try { - const response = await requestServer(`${GET_COUNTRY_RECEIPT_REPORT}?${params}`); - const result = response.data.data; - const nationalReportForItem = result.activities.find((report) => report.province_id == -1); - const nationalReport = { - edare_name: "کل کشور", - ...nationalReportForItem, - }; - - setData({ - data: [ - nationalReport, - ...result.provinces.map((province) => { - const filteredReports = result.activities.find( - (report) => report.province_id == province.id - ); - return { - ...filteredReports, - edare_name: province.name_fa, - }; - }), - ], - filters: data, - }); - } catch (e) { - console.log(e); - } - } else { - try { - params.set("province_id", `${data.province_id}`); - const response = await requestServer(`${GET_PROVINCE_RECEIPT_REPORT}?${params}`); - const result = response.data.data; - const nationalReportForItem = result.activities.find((report) => report.city_id == "-1"); - const nationalReport = { - ...nationalReportForItem, - edare_name: "کل استان", - }; - setData({ - data: [ - nationalReport, - ...result.cities.map((city) => { - const filteredReports = result.activities.find((report) => report.city_id == city.id); - return { - edare_name: city.name_fa, - ...filteredReports, - }; - }), - ], - filters: data, - }); - } catch (e) {} - } - }; - - useEffect(() => { - if (!userPermissions) return; - onSearchSubmit(defaultValues); - }, [userPermissions]); - - const validationSchema = yup.object().shape({ - from_date: yup - .string() - .required("تاریخ شروع الزامی است!") - .matches(/^\d{4}-\d{2}-\d{2}$/, "تاریخ شروع الزامی است!") - .test("is-valid-date", "تاریخ شروع معتبر نیست!", (value) => moment(value, "YYYY-MM-DD", true).isValid()), - date_to: yup - .string() - .required("تاریخ پایان الزامی است!") - .matches(/^\d{4}-\d{2}-\d{2}$/, "تاریخ پایان الزامی است!") - .test("is-valid-date", "تاریخ پایان معتبر نیست!", (value) => moment(value, "YYYY-MM-DD", true).isValid()), - province_id: yup.string().nullable(), - }); - - const { control, handleSubmit } = useForm({ - defaultValues, - resolver: yupResolver(validationSchema), - mode: "all", - }); - - return ( - - - - {!data ? : } - - ); -}; -export default DamagesReportPage; +"use client"; +import PageTitle from "@/core/components/PageTitle"; +import { GET_PROVINCE_RECEIPT_REPORT, GET_COUNTRY_RECEIPT_REPORT } from "@/core/utils/routes"; +import { useAuth } from "@/lib/contexts/auth"; +import { usePermissions } from "@/lib/hooks/usePermissions"; +import useRequest from "@/lib/hooks/useRequest"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { LinearProgress, Stack } from "@mui/material"; +import moment from "jalali-moment"; +import { useEffect, useState } from "react"; +import { useForm } from "react-hook-form"; +import * as yup from "yup"; +import SearchReportList from "./Search"; +import ReportLists from "./ReportLists"; + +const DamagesReportPage = () => { + const [data, setData] = useState(null); + const { data: userPermissions } = usePermissions(); + const { user } = useAuth(); + const requestServer = useRequest(); + const hasProvincesPermission = userPermissions?.includes("show-receipt"); + + const defaultValues = { + from_date: moment(new Date()).format("YYYY-MM-DD"), + date_to: moment(new Date()).format("YYYY-MM-DD"), + province_id: hasProvincesPermission ? "-1" : user.province_id, + }; + const defaultFilter = [ + { value: `${defaultValues.province_id}`, datatype: "numeric", id: "province_id", fn: "equals" }, + { value: `${defaultValues.from_date}`, datatype: "date", id: "from_date", fn: "between" }, + { value: `${defaultValues.date_to}`, datatype: "date", id: "date_to", fn: "between" }, + ]; + const [specialFilter, setSpecialFilter] = useState(defaultFilter); + + const onSearchSubmit = async (data) => { + const params = new URLSearchParams(); + params.set("from_date", `${data.from_date}`); + params.set("date_to", `${data.date_to}`); + setSpecialFilter([ + { value: `${data.province_id}`, datatype: "numeric", id: "province_id", fn: "equals" }, + { value: `${data.from_date}`, datatype: "date", id: "from_date", fn: "between" }, + { value: `${data.date_to}`, datatype: "date", id: "date_to", fn: "between" }, + ]); + if (data.province_id === "-1") { + try { + const response = await requestServer(`${GET_COUNTRY_RECEIPT_REPORT}?${params}`); + const result = response.data.data; + const nationalReportForItem = result.activities.find((report) => report.province_id == -1); + const nationalReport = { + edare_name: "کل کشور", + ...nationalReportForItem, + }; + + setData({ + data: [ + nationalReport, + ...result.provinces.map((province) => { + const filteredReports = result.activities.find( + (report) => report.province_id == province.id + ); + return { + ...filteredReports, + edare_name: province.name_fa, + }; + }), + ], + filters: data, + }); + } catch (e) { + console.log(e); + } + } else { + try { + params.set("province_id", `${data.province_id}`); + const response = await requestServer(`${GET_PROVINCE_RECEIPT_REPORT}?${params}`); + const result = response.data.data; + const nationalReportForItem = result.activities.find((report) => report.city_id == "-1"); + const nationalReport = { + ...nationalReportForItem, + edare_name: "کل استان", + }; + setData({ + data: [ + nationalReport, + ...result.cities.map((city) => { + const filteredReports = result.activities.find((report) => report.city_id == city.id); + return { + edare_name: city.name_fa, + ...filteredReports, + }; + }), + ], + filters: data, + }); + } catch (e) {} + } + }; + + useEffect(() => { + if (!userPermissions) return; + onSearchSubmit(defaultValues); + }, [userPermissions]); + + const validationSchema = yup.object().shape({ + from_date: yup + .string() + .required("تاریخ شروع الزامی است!") + .matches(/^\d{4}-\d{2}-\d{2}$/, "تاریخ شروع الزامی است!") + .test("is-valid-date", "تاریخ شروع معتبر نیست!", (value) => moment(value, "YYYY-MM-DD", true).isValid()), + date_to: yup + .string() + .required("تاریخ پایان الزامی است!") + .matches(/^\d{4}-\d{2}-\d{2}$/, "تاریخ پایان الزامی است!") + .test("is-valid-date", "تاریخ پایان معتبر نیست!", (value) => moment(value, "YYYY-MM-DD", true).isValid()), + province_id: yup.string().nullable(), + }); + + const { control, handleSubmit } = useForm({ + defaultValues, + resolver: yupResolver(validationSchema), + mode: "all", + }); + + return ( + + + + {!data ? : } + + ); +}; +export default DamagesReportPage; diff --git a/src/components/dashboard/fastReact/complaintList/ComplaintListTable.jsx b/src/components/dashboard/fastReact/complaintList/ComplaintListTable.jsx index c5535a5..fc0cb52 100644 --- a/src/components/dashboard/fastReact/complaintList/ComplaintListTable.jsx +++ b/src/components/dashboard/fastReact/complaintList/ComplaintListTable.jsx @@ -1,281 +1,281 @@ -import { useEffect, useMemo, useState } from "react"; -import { Box, Button, Dialog, DialogActions, Stack, Typography } from "@mui/material"; -import DataTableWithAuth from "@/core/components/DataTableWithAuth"; -import Toolbar from "./Toolbar"; -import RowActions from "./RowActions"; -import { GET_FAST_REACT_COMPLAINTS } from "@/core/utils/routes"; -import useProvinces from "@/lib/hooks/useProvince"; -import CustomSelectByDependency from "@/core/components/DataTable/filter/fieldsType/CustomSelectByDependency"; -import { usePermissions } from "@/lib/hooks/usePermissions"; -import { useAuth } from "@/lib/contexts/auth"; -import useEdaratLists from "@/lib/hooks/useEdaratLists"; -import DescriptionForm from "./RowActions/DescriptionDialog"; -import LocationForm from "./RowActions/LocationDialog"; -import moment from "jalali-moment"; - -const ComplaintListTable = ({ open, setOpen, mutate }) => { - const { data: userPermissions } = usePermissions(); - const hasCountryPermission = userPermissions?.includes("show-fast-react"); - const { user } = useAuth(); - const columns = useMemo(() => { - const dynamicColumns = { - header: "استان", - id: "road_observeds__province_id", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - grow: false, - size: 130, - ColumnSelectComponent: (props) => { - const { provinces, errorProvinces, loadingProvinces } = useProvinces(); - const getColumnSelectOptions = useMemo(() => { - if (loadingProvinces) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorProvinces) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: "کل کشور" }, - ...provinces.map((province) => ({ - value: province.id, - label: province.name_fa, - })), - ]; - }, [provinces, errorProvinces, loadingProvinces]); - return ( - - ); - }, - Cell: ({ row }) => <>{row.original.province_fa}, - }; - return [ - { - accessorKey: "id", - header: "کد یکتا", - id: "road_observeds__id", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - ...(hasCountryPermission ? [dynamicColumns] : []), - { - header: "اداره", - id: "road_observeds__edarate_shahri_id", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - dependencyId: hasCountryPermission ? "road_observeds__province_id" : null, - grow: false, - size: 120, - ColumnSelectComponent: (props) => { - const { edaratList, loadingEdaratList, errorEdaratList } = useEdaratLists( - hasCountryPermission ? props.dependencyFieldValue.value : user.province_id - ); - const [prevDependency, setPrevDependency] = useState( - hasCountryPermission ? props.dependencyFieldValue.value : user.province_id - ); - - const getColumnSelectOptions = useMemo(() => { - if (hasCountryPermission && props.dependencyFieldValue.value === "") { - return [{ value: "empty", label: "ابتدا استان را انتخاب کنید" }]; - } - if (loadingEdaratList) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorEdaratList) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: "کل ادارات" }, - ...edaratList.map((edare) => ({ - value: edare.id, - label: edare.name_fa, - })), - ]; - }, [edaratList, loadingEdaratList, errorEdaratList]); - useEffect(() => { - if (hasCountryPermission) return; - if (prevDependency === props.dependencyFieldValue?.value) return; - props.handleChange({ ...props.filterParameters, value: "" }); - setPrevDependency(props.dependencyFieldValue?.value); - }, [props.dependencyFieldValue?.value, hasCountryPermission]); - return ( - - ); - }, - Cell: ({ row }) => <>{row.original.edarate_shahri_name_fa}, - }, - { - header: "اطلاعات ثبت‌ شده در سامانه سوانح", - id: "fkInfo", - enableColumnFilter: false, - enableSorting: false, - grow: false, - size: 50, - columns: [ - { - accessorKey: "fk_RegisteredEventMessage", - header: "کد سوانح", - id: "fk_RegisteredEventMessage", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorKey: "Title", - header: "موضوع گزارش", - id: "Title", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorKey: "FeatureTypeTitle", - header: "نوع گزارش", - id: "FeatureTypeTitle", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorKey: "Description", - header: "توضیح گزارش", - id: "Description", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - if (renderedCellValue) { - return ( - - - - ); - } - return -; - }, - }, - { - header: "موقعیت", - id: "location", - enableColumnFilter: false, - enableSorting: false, - datatype: "array", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ row }) => { - return ( - - - - ); - }, - }, - { - accessorKey: "MobileForSendEventSms", - header: "شماره تماس گیرنده", - id: "MobileForSendEventSms", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorFn: (row) => moment(row.StartTime_DateTime).locale("fa").format("HH:mm | yyyy/MM/DD"), - header: "تاریخ ثبت", - id: "StartTime_DateTime", - enableColumnFilter: true, - datatype: "date", - filterMode: "between", - grow: false, - size: 100, - }, - ], - }, - ]; - }, []); - - return ( - setOpen(false)} open={open} fullWidth maxWidth={"xl"}> - {open && ( - - } - /> - - )} - - - - - ); -}; -export default ComplaintListTable; +import { useEffect, useMemo, useState } from "react"; +import { Box, Button, Dialog, DialogActions, Stack, Typography } from "@mui/material"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import Toolbar from "./Toolbar"; +import RowActions from "./RowActions"; +import { GET_FAST_REACT_COMPLAINTS } from "@/core/utils/routes"; +import useProvinces from "@/lib/hooks/useProvince"; +import CustomSelectByDependency from "@/core/components/DataTable/filter/fieldsType/CustomSelectByDependency"; +import { usePermissions } from "@/lib/hooks/usePermissions"; +import { useAuth } from "@/lib/contexts/auth"; +import useEdaratLists from "@/lib/hooks/useEdaratLists"; +import DescriptionForm from "./RowActions/DescriptionDialog"; +import LocationForm from "./RowActions/LocationDialog"; +import moment from "jalali-moment"; + +const ComplaintListTable = ({ open, setOpen, mutate }) => { + const { data: userPermissions } = usePermissions(); + const hasCountryPermission = userPermissions?.includes("show-fast-react"); + const { user } = useAuth(); + const columns = useMemo(() => { + const dynamicColumns = { + header: "استان", + id: "road_observeds__province_id", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 130, + ColumnSelectComponent: (props) => { + const { provinces, errorProvinces, loadingProvinces } = useProvinces(); + const getColumnSelectOptions = useMemo(() => { + if (loadingProvinces) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorProvinces) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: "کل کشور" }, + ...provinces.map((province) => ({ + value: province.id, + label: province.name_fa, + })), + ]; + }, [provinces, errorProvinces, loadingProvinces]); + return ( + + ); + }, + Cell: ({ row }) => <>{row.original.province_fa}, + }; + return [ + { + accessorKey: "id", + header: "کد یکتا", + id: "road_observeds__id", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + ...(hasCountryPermission ? [dynamicColumns] : []), + { + header: "اداره", + id: "road_observeds__edarate_shahri_id", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + dependencyId: hasCountryPermission ? "road_observeds__province_id" : null, + grow: false, + size: 120, + ColumnSelectComponent: (props) => { + const { edaratList, loadingEdaratList, errorEdaratList } = useEdaratLists( + hasCountryPermission ? props.dependencyFieldValue.value : user.province_id + ); + const [prevDependency, setPrevDependency] = useState( + hasCountryPermission ? props.dependencyFieldValue.value : user.province_id + ); + + const getColumnSelectOptions = useMemo(() => { + if (hasCountryPermission && props.dependencyFieldValue.value === "") { + return [{ value: "empty", label: "ابتدا استان را انتخاب کنید" }]; + } + if (loadingEdaratList) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorEdaratList) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: "کل ادارات" }, + ...edaratList.map((edare) => ({ + value: edare.id, + label: edare.name_fa, + })), + ]; + }, [edaratList, loadingEdaratList, errorEdaratList]); + useEffect(() => { + if (hasCountryPermission) return; + if (prevDependency === props.dependencyFieldValue?.value) return; + props.handleChange({ ...props.filterParameters, value: "" }); + setPrevDependency(props.dependencyFieldValue?.value); + }, [props.dependencyFieldValue?.value, hasCountryPermission]); + return ( + + ); + }, + Cell: ({ row }) => <>{row.original.edarate_shahri_name_fa}, + }, + { + header: "اطلاعات ثبت‌ شده در سامانه سوانح", + id: "fkInfo", + enableColumnFilter: false, + enableSorting: false, + grow: false, + size: 50, + columns: [ + { + accessorKey: "fk_RegisteredEventMessage", + header: "کد سوانح", + id: "fk_RegisteredEventMessage", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "Title", + header: "موضوع گزارش", + id: "Title", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "FeatureTypeTitle", + header: "نوع گزارش", + id: "FeatureTypeTitle", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "Description", + header: "توضیح گزارش", + id: "Description", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + if (renderedCellValue) { + return ( + + + + ); + } + return -; + }, + }, + { + header: "موقعیت", + id: "location", + enableColumnFilter: false, + enableSorting: false, + datatype: "array", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => { + return ( + + + + ); + }, + }, + { + accessorKey: "MobileForSendEventSms", + header: "شماره تماس گیرنده", + id: "MobileForSendEventSms", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorFn: (row) => moment(row.StartTime_DateTime).locale("fa").format("HH:mm | yyyy/MM/DD"), + header: "تاریخ ثبت", + id: "StartTime_DateTime", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + ], + }, + ]; + }, []); + + return ( + setOpen(false)} open={open} fullWidth maxWidth={"xl"}> + {open && ( + + } + /> + + )} + + + + + ); +}; +export default ComplaintListTable; diff --git a/src/components/dashboard/fastReact/complaintList/ExcelPrint/index.jsx b/src/components/dashboard/fastReact/complaintList/ExcelPrint/index.jsx index 05f3362..6a6870e 100644 --- a/src/components/dashboard/fastReact/complaintList/ExcelPrint/index.jsx +++ b/src/components/dashboard/fastReact/complaintList/ExcelPrint/index.jsx @@ -1,74 +1,74 @@ -import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; -import { useMemo, useState } from "react"; -import moment from "jalali-moment"; -import FileSaver from "file-saver"; -import DescriptionIcon from "@mui/icons-material/Description"; -import useRequest from "@/lib/hooks/useRequest"; -import { EXPORT_FAST_REACT_COMPLAINT_LIST } from "@/core/utils/routes"; -import { useTheme } from "@emotion/react"; -import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; -import isArrayEmpty from "@/core/utils/isArrayEmpty"; - -const PrintExcel = ({ table, filterData }) => { - const [loading, setLoading] = useState(false); - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const requestServer = useRequest(); - const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { - if (filter.value && (!Array.isArray(filter.value) || filter.value.some((item) => item.trim() !== ""))) { - acc.push({ id: key, value: filter.value }); - } - return acc; - }, []); - - const filterParams = useMemo(() => { - const params = new URLSearchParams(); - if (activeFilters.length > 0) { - activeFilters.map((filter, index) => { - const filteredFilterData = DataTableFilterDataStructure(filterData, isArrayEmpty); - params.set("filters", JSON.stringify(filteredFilterData.length === 0 ? [] : filteredFilterData)); - }); - } else { - params.set("filters", JSON.stringify([])); - } - return params; - }, [activeFilters]); - - const clickHandler = () => { - setLoading(true); - requestServer(`${EXPORT_FAST_REACT_COMPLAINT_LIST}?${filterParams}`, "get", { - requestOptions: { responseType: "blob" }, - }) - .then((response) => { - const filename = `خروجی لیست شکایات واکنش سریع تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; - FileSaver.saveAs(response.data, filename); - }) - .catch(() => {}) - .finally(() => { - setLoading(false); - }); - }; - - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - - ); -}; -export default PrintExcel; +import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; +import { useMemo, useState } from "react"; +import moment from "jalali-moment"; +import FileSaver from "file-saver"; +import DescriptionIcon from "@mui/icons-material/Description"; +import useRequest from "@/lib/hooks/useRequest"; +import { EXPORT_FAST_REACT_COMPLAINT_LIST } from "@/core/utils/routes"; +import { useTheme } from "@emotion/react"; +import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; +import isArrayEmpty from "@/core/utils/isArrayEmpty"; + +const PrintExcel = ({ table, filterData }) => { + const [loading, setLoading] = useState(false); + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const requestServer = useRequest(); + const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { + if (filter.value && (!Array.isArray(filter.value) || filter.value.some((item) => item.trim() !== ""))) { + acc.push({ id: key, value: filter.value }); + } + return acc; + }, []); + + const filterParams = useMemo(() => { + const params = new URLSearchParams(); + if (activeFilters.length > 0) { + activeFilters.map((filter, index) => { + const filteredFilterData = DataTableFilterDataStructure(filterData, isArrayEmpty); + params.set("filters", JSON.stringify(filteredFilterData.length === 0 ? [] : filteredFilterData)); + }); + } else { + params.set("filters", JSON.stringify([])); + } + return params; + }, [activeFilters]); + + const clickHandler = () => { + setLoading(true); + requestServer(`${EXPORT_FAST_REACT_COMPLAINT_LIST}?${filterParams}`, "get", { + requestOptions: { responseType: "blob" }, + }) + .then((response) => { + const filename = `خروجی لیست شکایات واکنش سریع تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; + FileSaver.saveAs(response.data, filename); + }) + .catch(() => {}) + .finally(() => { + setLoading(false); + }); + }; + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + + ); +}; +export default PrintExcel; diff --git a/src/components/dashboard/fastReact/complaintList/Form/registerAction/ImageUpload.jsx b/src/components/dashboard/fastReact/complaintList/Form/registerAction/ImageUpload.jsx index 5186a4b..7697cfb 100644 --- a/src/components/dashboard/fastReact/complaintList/Form/registerAction/ImageUpload.jsx +++ b/src/components/dashboard/fastReact/complaintList/Form/registerAction/ImageUpload.jsx @@ -1,77 +1,77 @@ -import { FormControl, FormHelperText } from "@mui/material"; -import UploadSystem from "@/core/components/UploadSystem"; -import React, { useEffect, useState } from "react"; - -const ImageUpload = ({ name, value, onChange, error, title }) => { - const [beforeImg, setBeforeImg] = useState(value ? value : null); - const [beforeFileType, setBeforeFileType] = useState(value ? "image/" : null); - const [beforeFileName, setBeforeFileName] = useState(null); - const [showBeforeImage, setShowBeforeImage] = useState(!value); - - useEffect(() => { - if (value) { - setShowBeforeImage(false); - if (typeof value === "string") { - setBeforeImg(value); - setBeforeFileType("image/"); - } else if (value instanceof File) { - setBeforeImg(URL.createObjectURL(value)); - setBeforeFileType(value.type); - } - } - }, [value]); - - const handleFileChange = (event) => { - const uploadedFile = event.target?.files?.[0]; - if (uploadedFile) { - const fileType = event.target?.files?.[0].type; - const fileName = event.target?.files?.[0].name; - setBeforeImg(URL.createObjectURL(uploadedFile)); - setBeforeFileType(fileType); - setBeforeFileName(fileName); - onChange(uploadedFile); - setShowBeforeImage(false); - } - }; - - return ( - - - {title} - - - {error ? error.message : null} - - ); -}; -export default ImageUpload; +import { FormControl, FormHelperText } from "@mui/material"; +import UploadSystem from "@/core/components/UploadSystem"; +import React, { useEffect, useState } from "react"; + +const ImageUpload = ({ name, value, onChange, error, title }) => { + const [beforeImg, setBeforeImg] = useState(value ? value : null); + const [beforeFileType, setBeforeFileType] = useState(value ? "image/" : null); + const [beforeFileName, setBeforeFileName] = useState(null); + const [showBeforeImage, setShowBeforeImage] = useState(!value); + + useEffect(() => { + if (value) { + setShowBeforeImage(false); + if (typeof value === "string") { + setBeforeImg(value); + setBeforeFileType("image/"); + } else if (value instanceof File) { + setBeforeImg(URL.createObjectURL(value)); + setBeforeFileType(value.type); + } + } + }, [value]); + + const handleFileChange = (event) => { + const uploadedFile = event.target?.files?.[0]; + if (uploadedFile) { + const fileType = event.target?.files?.[0].type; + const fileName = event.target?.files?.[0].name; + setBeforeImg(URL.createObjectURL(uploadedFile)); + setBeforeFileType(fileType); + setBeforeFileName(fileName); + onChange(uploadedFile); + setShowBeforeImage(false); + } + }; + + return ( + + + {title} + + + {error ? error.message : null} + + ); +}; +export default ImageUpload; diff --git a/src/components/dashboard/fastReact/complaintList/Form/registerAction/RegisterActionContent.jsx b/src/components/dashboard/fastReact/complaintList/Form/registerAction/RegisterActionContent.jsx index 131e72e..25aed74 100644 --- a/src/components/dashboard/fastReact/complaintList/Form/registerAction/RegisterActionContent.jsx +++ b/src/components/dashboard/fastReact/complaintList/Form/registerAction/RegisterActionContent.jsx @@ -1,111 +1,111 @@ -import StyledForm from "@/core/components/StyledForm"; -import { yupResolver } from "@hookform/resolvers/yup"; -import BeenhereIcon from "@mui/icons-material/Beenhere"; -import { Button, DialogActions, DialogContent, FormControlLabel, RadioGroup, Stack } from "@mui/material"; -import Radio from "@mui/material/Radio"; -import { useState } from "react"; -import { Controller, useForm } from "react-hook-form"; -import { mixed, object, string } from "yup"; -import RegisterActionDone from "./RegisterActionDone"; -import RegisterActionUndone from "./RegisterActionUndone"; - -const RegisterActionContent = ({ setOpen, defaultValues, onBaseSubmit }) => { - const [selectedOption, setSelectedOption] = useState(defaultValues?.rms_status || "1"); - - const handleOptionChange = (e) => { - setSelectedOption(e.target.value); - }; - const validationSchema = object({ - description: string().required("توضیحات الزامی است"), - start_point: mixed().when("rms_status", { - is: "1", - then: (schema) => - schema - .test("start-point-required", "مکان اقدام الزامی است", function (value) { - return !!value; - }) - .required("مکان اقدام الزامی است"), - otherwise: (schema) => schema.notRequired(), - }), - image_before_1: mixed().when("rms_status", { - is: "1", - then: (schema) => schema.required("تصویر قبل از اقدام الزامی است"), - otherwise: (schema) => schema.notRequired(), - }), - image_after_1: mixed().when("rms_status", { - is: "1", - then: (schema) => schema.required("تصویر بعد از اقدام الزامی است"), - otherwise: (schema) => schema.notRequired(), - }), - }); - - const { - control, - handleSubmit, - setValue, - formState: { isSubmitting, errors }, - } = useForm({ - defaultValues, - resolver: yupResolver(validationSchema), - mode: "all", - }); - - const onSubmit = async (data) => { - await onBaseSubmit(data); - }; - return ( - - - - - } - /> - } - label="اقدام انجام شد" - /> - } - /> - } - label="اقدام انجام نشد" - /> - - - {selectedOption === "1" ? ( - - ) : ( - - )} - - - - - - - ); -}; -export default RegisterActionContent; +import StyledForm from "@/core/components/StyledForm"; +import { yupResolver } from "@hookform/resolvers/yup"; +import BeenhereIcon from "@mui/icons-material/Beenhere"; +import { Button, DialogActions, DialogContent, FormControlLabel, RadioGroup, Stack } from "@mui/material"; +import Radio from "@mui/material/Radio"; +import { useState } from "react"; +import { Controller, useForm } from "react-hook-form"; +import { mixed, object, string } from "yup"; +import RegisterActionDone from "./RegisterActionDone"; +import RegisterActionUndone from "./RegisterActionUndone"; + +const RegisterActionContent = ({ setOpen, defaultValues, onBaseSubmit }) => { + const [selectedOption, setSelectedOption] = useState(defaultValues?.rms_status || "1"); + + const handleOptionChange = (e) => { + setSelectedOption(e.target.value); + }; + const validationSchema = object({ + description: string().required("توضیحات الزامی است"), + start_point: mixed().when("rms_status", { + is: "1", + then: (schema) => + schema + .test("start-point-required", "مکان اقدام الزامی است", function (value) { + return !!value; + }) + .required("مکان اقدام الزامی است"), + otherwise: (schema) => schema.notRequired(), + }), + image_before_1: mixed().when("rms_status", { + is: "1", + then: (schema) => schema.required("تصویر قبل از اقدام الزامی است"), + otherwise: (schema) => schema.notRequired(), + }), + image_after_1: mixed().when("rms_status", { + is: "1", + then: (schema) => schema.required("تصویر بعد از اقدام الزامی است"), + otherwise: (schema) => schema.notRequired(), + }), + }); + + const { + control, + handleSubmit, + setValue, + formState: { isSubmitting, errors }, + } = useForm({ + defaultValues, + resolver: yupResolver(validationSchema), + mode: "all", + }); + + const onSubmit = async (data) => { + await onBaseSubmit(data); + }; + return ( + + + + + } + /> + } + label="اقدام انجام شد" + /> + } + /> + } + label="اقدام انجام نشد" + /> + + + {selectedOption === "1" ? ( + + ) : ( + + )} + + + + + + + ); +}; +export default RegisterActionContent; diff --git a/src/components/dashboard/fastReact/complaintList/Form/registerAction/RegisterActionDone.jsx b/src/components/dashboard/fastReact/complaintList/Form/registerAction/RegisterActionDone.jsx index 567832d..e3ca025 100644 --- a/src/components/dashboard/fastReact/complaintList/Form/registerAction/RegisterActionDone.jsx +++ b/src/components/dashboard/fastReact/complaintList/Form/registerAction/RegisterActionDone.jsx @@ -1,86 +1,86 @@ -import { Controller, useWatch } from "react-hook-form"; -import { Grid, Stack, TextField } from "@mui/material"; -import ImageUpload from "./ImageUpload"; -import MapInfoOneMarker from "@/core/components/MapInfoOneMarker"; - -const RegisterActionDone = ({ control, setValue, errors }) => { - const StartPoint = useWatch({ control, name: "start_point" }); - return ( - - - - - { - return ( - - ); - }} - /> - - - - - - - ( - - )} - /> - - - ( - - )} - /> - - - - - - - - - - - - ); -}; -export default RegisterActionDone; +import { Controller, useWatch } from "react-hook-form"; +import { Grid, Stack, TextField } from "@mui/material"; +import ImageUpload from "./ImageUpload"; +import MapInfoOneMarker from "@/core/components/MapInfoOneMarker"; + +const RegisterActionDone = ({ control, setValue, errors }) => { + const StartPoint = useWatch({ control, name: "start_point" }); + return ( + + + + + { + return ( + + ); + }} + /> + + + + + + + ( + + )} + /> + + + ( + + )} + /> + + + + + + + + + + + + ); +}; +export default RegisterActionDone; diff --git a/src/components/dashboard/fastReact/complaintList/Form/registerAction/RegisterActionUndone.jsx b/src/components/dashboard/fastReact/complaintList/Form/registerAction/RegisterActionUndone.jsx index dd2b43b..efcbc4d 100644 --- a/src/components/dashboard/fastReact/complaintList/Form/registerAction/RegisterActionUndone.jsx +++ b/src/components/dashboard/fastReact/complaintList/Form/registerAction/RegisterActionUndone.jsx @@ -1,37 +1,37 @@ -import { Grid, Stack, TextField } from "@mui/material"; -import { Controller } from "react-hook-form"; - -const RegisterActionUndone = ({ control }) => { - return ( - - - - - { - return ( - - ); - }} - /> - - - - - ); -}; -export default RegisterActionUndone; +import { Grid, Stack, TextField } from "@mui/material"; +import { Controller } from "react-hook-form"; + +const RegisterActionUndone = ({ control }) => { + return ( + + + + + { + return ( + + ); + }} + /> + + + + + ); +}; +export default RegisterActionUndone; diff --git a/src/components/dashboard/fastReact/complaintList/Form/registerAction/index.jsx b/src/components/dashboard/fastReact/complaintList/Form/registerAction/index.jsx index 850bc7d..9e75e90 100644 --- a/src/components/dashboard/fastReact/complaintList/Form/registerAction/index.jsx +++ b/src/components/dashboard/fastReact/complaintList/Form/registerAction/index.jsx @@ -1,67 +1,67 @@ -import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import RegisterActionContent from "./RegisterActionContent"; -import AppRegistrationIcon from "@mui/icons-material/AppRegistration"; -import useRequest from "@/lib/hooks/useRequest"; -import { REGISTER_COMPLAINTS_LIST } from "@/core/utils/routes"; -const RegisterAction = ({ rowId, mutate, mutateParentTable }) => { - const requestServer = useRequest({ notificationSuccess: true }); - const [openRegisterActionDialog, setOpenRegisterActionDialog] = useState(false); - const defaultValues = { - rms_status: "1", - description: "", - start_point: "", - image_before_1: null, - image_after_1: null, - }; - const onBaseSubmit = async (result) => { - const formData = new FormData(); - const rmsLatLng = `${result.start_point.lat},${result.start_point.lng}`; - if (result.rms_status === "1") { - formData.append("rms_description", result.description); - formData.append("rms_status", 1); - formData.append("start_point", rmsLatLng); - formData.append("image_before", result.image_before_1); - formData.append("image_after", result.image_after_1); - } else { - formData.append("rms_description", result.description); - formData.append("rms_status", 2); - } - await requestServer(`${REGISTER_COMPLAINTS_LIST}/${rowId}`, "post", { - data: formData, - hasSidebarUpdate: true, - }) - .then((res) => { - mutate(); - mutateParentTable(); - setOpenRegisterActionDialog(false); - }) - .catch(() => {}); - }; - return ( - <> - - setOpenRegisterActionDialog(true)}> - - - - - ثبت اقدام - - - - ); -}; -export default RegisterAction; +import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import RegisterActionContent from "./RegisterActionContent"; +import AppRegistrationIcon from "@mui/icons-material/AppRegistration"; +import useRequest from "@/lib/hooks/useRequest"; +import { REGISTER_COMPLAINTS_LIST } from "@/core/utils/routes"; +const RegisterAction = ({ rowId, mutate, mutateParentTable }) => { + const requestServer = useRequest({ notificationSuccess: true }); + const [openRegisterActionDialog, setOpenRegisterActionDialog] = useState(false); + const defaultValues = { + rms_status: "1", + description: "", + start_point: "", + image_before_1: null, + image_after_1: null, + }; + const onBaseSubmit = async (result) => { + const formData = new FormData(); + const rmsLatLng = `${result.start_point.lat},${result.start_point.lng}`; + if (result.rms_status === "1") { + formData.append("rms_description", result.description); + formData.append("rms_status", 1); + formData.append("start_point", rmsLatLng); + formData.append("image_before", result.image_before_1); + formData.append("image_after", result.image_after_1); + } else { + formData.append("rms_description", result.description); + formData.append("rms_status", 2); + } + await requestServer(`${REGISTER_COMPLAINTS_LIST}/${rowId}`, "post", { + data: formData, + hasSidebarUpdate: true, + }) + .then((res) => { + mutate(); + mutateParentTable(); + setOpenRegisterActionDialog(false); + }) + .catch(() => {}); + }; + return ( + <> + + setOpenRegisterActionDialog(true)}> + + + + + ثبت اقدام + + + + ); +}; +export default RegisterAction; diff --git a/src/components/dashboard/fastReact/complaintList/RowActions/DescriptionDialog/index.jsx b/src/components/dashboard/fastReact/complaintList/RowActions/DescriptionDialog/index.jsx index 4d80ac4..06b3cdf 100644 --- a/src/components/dashboard/fastReact/complaintList/RowActions/DescriptionDialog/index.jsx +++ b/src/components/dashboard/fastReact/complaintList/RowActions/DescriptionDialog/index.jsx @@ -1,50 +1,50 @@ -import { Dialog, DialogContent, DialogTitle, IconButton, Tooltip, Typography, Card, CardContent } from "@mui/material"; -import { useState } from "react"; -import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye"; -import CloseIcon from "@mui/icons-material/Close"; - -const DescriptionForm = ({ description, title, icon: IconComponent = RemoveRedEyeIcon }) => { - const [openOfficerDescriptionDialog, setOpenOfficerDescriptionDialog] = useState(false); - - return ( - <> - - setOpenOfficerDescriptionDialog(true)}> - - - - setOpenOfficerDescriptionDialog(false)} - PaperProps={{ - sx: { - transition: "all .3s", - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - borderRadius: 2, - padding: 1, - }, - }} - maxWidth="sm" - fullWidth - dir="rtl" - > - - - {title} - - setOpenOfficerDescriptionDialog(false)} size="small"> - - - - - - - {description || "هیچ توضیحی موجود نیست"} - - - - - - ); -}; -export default DescriptionForm; +import { Dialog, DialogContent, DialogTitle, IconButton, Tooltip, Typography, Card, CardContent } from "@mui/material"; +import { useState } from "react"; +import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye"; +import CloseIcon from "@mui/icons-material/Close"; + +const DescriptionForm = ({ description, title, icon: IconComponent = RemoveRedEyeIcon }) => { + const [openOfficerDescriptionDialog, setOpenOfficerDescriptionDialog] = useState(false); + + return ( + <> + + setOpenOfficerDescriptionDialog(true)}> + + + + setOpenOfficerDescriptionDialog(false)} + PaperProps={{ + sx: { + transition: "all .3s", + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + borderRadius: 2, + padding: 1, + }, + }} + maxWidth="sm" + fullWidth + dir="rtl" + > + + + {title} + + setOpenOfficerDescriptionDialog(false)} size="small"> + + + + + + + {description || "هیچ توضیحی موجود نیست"} + + + + + + ); +}; +export default DescriptionForm; diff --git a/src/components/dashboard/fastReact/complaintList/RowActions/LocationDialog/LocationFormContent.jsx b/src/components/dashboard/fastReact/complaintList/RowActions/LocationDialog/LocationFormContent.jsx index 94f091d..9c8253c 100644 --- a/src/components/dashboard/fastReact/complaintList/RowActions/LocationDialog/LocationFormContent.jsx +++ b/src/components/dashboard/fastReact/complaintList/RowActions/LocationDialog/LocationFormContent.jsx @@ -1,30 +1,30 @@ -"use client"; -import { Box, Button, DialogActions, DialogContent, Stack } from "@mui/material"; -import React from "react"; -import dynamic from "next/dynamic"; -import MapLoading from "@/core/components/MapLayer/Loading"; -import ShowLocationMarker from "@/core/components/ShowLocationMarker"; -const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { - loading: () => , - ssr: false, -}); - -const LocationFormContent = ({ setOpenLocationDialog, start_lat, start_lng }) => { - return ( - <> - - - - - - - - - - - - ); -}; -export default LocationFormContent; +"use client"; +import { Box, Button, DialogActions, DialogContent, Stack } from "@mui/material"; +import React from "react"; +import dynamic from "next/dynamic"; +import MapLoading from "@/core/components/MapLayer/Loading"; +import ShowLocationMarker from "@/core/components/ShowLocationMarker"; +const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { + loading: () => , + ssr: false, +}); + +const LocationFormContent = ({ setOpenLocationDialog, start_lat, start_lng }) => { + return ( + <> + + + + + + + + + + + + ); +}; +export default LocationFormContent; diff --git a/src/components/dashboard/fastReact/complaintList/RowActions/LocationDialog/index.jsx b/src/components/dashboard/fastReact/complaintList/RowActions/LocationDialog/index.jsx index 09df6ad..0b917b4 100644 --- a/src/components/dashboard/fastReact/complaintList/RowActions/LocationDialog/index.jsx +++ b/src/components/dashboard/fastReact/complaintList/RowActions/LocationDialog/index.jsx @@ -1,36 +1,36 @@ -import React, { useState } from "react"; -import { Tooltip, IconButton, Dialog, DialogTitle } from "@mui/material"; -import ExploreIcon from "@mui/icons-material/Explore"; -import LocationFormContent from "./LocationFormContent"; -const LocationForm = ({ start_lat, start_lng }) => { - const [openLocationDialog, setOpenLocationDialog] = useState(false); - - return ( - <> - - setOpenLocationDialog(true)}> - - - - setOpenLocationDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - موقعیت - - - - ); -}; -export default LocationForm; +import React, { useState } from "react"; +import { Tooltip, IconButton, Dialog, DialogTitle } from "@mui/material"; +import ExploreIcon from "@mui/icons-material/Explore"; +import LocationFormContent from "./LocationFormContent"; +const LocationForm = ({ start_lat, start_lng }) => { + const [openLocationDialog, setOpenLocationDialog] = useState(false); + + return ( + <> + + setOpenLocationDialog(true)}> + + + + setOpenLocationDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + موقعیت + + + + ); +}; +export default LocationForm; diff --git a/src/components/dashboard/fastReact/complaintList/RowActions/Refer/EdarateShahriField.jsx b/src/components/dashboard/fastReact/complaintList/RowActions/Refer/EdarateShahriField.jsx index f44d8e1..58a4e6d 100644 --- a/src/components/dashboard/fastReact/complaintList/RowActions/Refer/EdarateShahriField.jsx +++ b/src/components/dashboard/fastReact/complaintList/RowActions/Refer/EdarateShahriField.jsx @@ -1,70 +1,70 @@ -"use client"; -import useEdaratLists from "@/lib/hooks/useEdaratLists"; -import { FormControl, FormHelperText, InputLabel, MenuItem, OutlinedInput, Select } from "@mui/material"; -import { useEffect, useMemo, useState } from "react"; -import { useWatch } from "react-hook-form"; - -const EdarateShahriField = ({ control, field, fieldState: { error } }) => { - const dependencyField = useWatch({ control, name: "province_id" }); - return ( - - ); -}; - -const EdarehShahriController = ({ value, onChange, dependencyField, error }) => { - const { edaratList, loadingEdaratList, errorEdaratList } = useEdaratLists(dependencyField); - const [prevDependency, setPrevDependency] = useState(dependencyField); - - const columnSelectOption = useMemo(() => { - if (dependencyField === "") { - return [{ value: "empty", label: "ابتدا استان را انتخاب کنید" }]; - } - if (loadingEdaratList) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorEdaratList) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return edaratList.map((edare) => ({ - value: edare.id, - label: edare.name_fa, - })); - }, [edaratList, loadingEdaratList, errorEdaratList]); - - useEffect(() => { - if (prevDependency === dependencyField) return; - onChange(""); - setPrevDependency(dependencyField); - }, [dependencyField]); - - return ( - - - اداره - - - {error && {error.message}} - - ); -}; -export default EdarateShahriField; +"use client"; +import useEdaratLists from "@/lib/hooks/useEdaratLists"; +import { FormControl, FormHelperText, InputLabel, MenuItem, OutlinedInput, Select } from "@mui/material"; +import { useEffect, useMemo, useState } from "react"; +import { useWatch } from "react-hook-form"; + +const EdarateShahriField = ({ control, field, fieldState: { error } }) => { + const dependencyField = useWatch({ control, name: "province_id" }); + return ( + + ); +}; + +const EdarehShahriController = ({ value, onChange, dependencyField, error }) => { + const { edaratList, loadingEdaratList, errorEdaratList } = useEdaratLists(dependencyField); + const [prevDependency, setPrevDependency] = useState(dependencyField); + + const columnSelectOption = useMemo(() => { + if (dependencyField === "") { + return [{ value: "empty", label: "ابتدا استان را انتخاب کنید" }]; + } + if (loadingEdaratList) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorEdaratList) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return edaratList.map((edare) => ({ + value: edare.id, + label: edare.name_fa, + })); + }, [edaratList, loadingEdaratList, errorEdaratList]); + + useEffect(() => { + if (prevDependency === dependencyField) return; + onChange(""); + setPrevDependency(dependencyField); + }, [dependencyField]); + + return ( + + + اداره + + + {error && {error.message}} + + ); +}; +export default EdarateShahriField; diff --git a/src/components/dashboard/fastReact/complaintList/RowActions/Refer/ProvinceField.jsx b/src/components/dashboard/fastReact/complaintList/RowActions/Refer/ProvinceField.jsx index 455339e..08d6a17 100644 --- a/src/components/dashboard/fastReact/complaintList/RowActions/Refer/ProvinceField.jsx +++ b/src/components/dashboard/fastReact/complaintList/RowActions/Refer/ProvinceField.jsx @@ -1,33 +1,33 @@ -import useProvinces from "@/lib/hooks/useProvince"; -import { FormControl, FormHelperText, InputLabel, MenuItem, Select } from "@mui/material"; - -const ProvinceField = ({ field, fieldState: { error } }) => { - const { provinces, loadingProvinces, errorProvinces } = useProvinces(); - return ( - - استان - - {error && {error.message}} - - ); -}; -export default ProvinceField; +import useProvinces from "@/lib/hooks/useProvince"; +import { FormControl, FormHelperText, InputLabel, MenuItem, Select } from "@mui/material"; + +const ProvinceField = ({ field, fieldState: { error } }) => { + const { provinces, loadingProvinces, errorProvinces } = useProvinces(); + return ( + + استان + + {error && {error.message}} + + ); +}; +export default ProvinceField; diff --git a/src/components/dashboard/fastReact/complaintList/RowActions/Refer/ReferContent.jsx b/src/components/dashboard/fastReact/complaintList/RowActions/Refer/ReferContent.jsx index 43f249c..84f6aec 100644 --- a/src/components/dashboard/fastReact/complaintList/RowActions/Refer/ReferContent.jsx +++ b/src/components/dashboard/fastReact/complaintList/RowActions/Refer/ReferContent.jsx @@ -1,102 +1,102 @@ -import { REFER_FAST_REACT } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { yupResolver } from "@hookform/resolvers/yup"; -import { Button, DialogActions, DialogContent, Stack, TextField } from "@mui/material"; -import { Controller, useForm } from "react-hook-form"; -import * as Yup from "yup"; -import EdarateShahriField from "./EdarateShahriField"; -import ProvinceField from "./ProvinceField"; - -const ReferContent = ({ row, mutate, setOpenReferDialog }) => { - const requestServer = useRequest({ notificationSuccess: true }); - - const validationSchema = Yup.object().shape({ - province_id: Yup.string().required("لطفاً استان را وارد کنید."), - edarat_shahri_id: Yup.string().required("لطفاً اداره را وارد کنید."), - description: Yup.string().required("لطفاً توضیحات را وارد کنید."), - }); - - const { - control, - register, - handleSubmit, - formState: { errors, isSubmitting }, - } = useForm({ - defaultValues: { - province_id: row.original.province_id, - edarat_shahri_id: "", - description: "", - }, - resolver: yupResolver(validationSchema), - mode: "all", - }); - - const onSubmit = async (data) => { - const formData = new FormData(); - formData.append("province_id", data.province_id); - formData.append("edarate_shahri_id", data.edarat_shahri_id); - formData.append("refer_description", data.description); - await requestServer(`${REFER_FAST_REACT}/${row.original.id}`, "post", { - data: formData, - hasSidebarUpdate: true, - }) - .then(() => { - mutate(); - setOpenReferDialog(false); - }) - .catch(() => {}); - }; - - return ( - <> - - - {/* { - return ; - }} - /> */} - { - return ; - }} - /> - - - - - - - - - - - ); -}; -export default ReferContent; +import { REFER_FAST_REACT } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { Button, DialogActions, DialogContent, Stack, TextField } from "@mui/material"; +import { Controller, useForm } from "react-hook-form"; +import * as Yup from "yup"; +import EdarateShahriField from "./EdarateShahriField"; +import ProvinceField from "./ProvinceField"; + +const ReferContent = ({ row, mutate, setOpenReferDialog }) => { + const requestServer = useRequest({ notificationSuccess: true }); + + const validationSchema = Yup.object().shape({ + province_id: Yup.string().required("لطفاً استان را وارد کنید."), + edarat_shahri_id: Yup.string().required("لطفاً اداره را وارد کنید."), + description: Yup.string().required("لطفاً توضیحات را وارد کنید."), + }); + + const { + control, + register, + handleSubmit, + formState: { errors, isSubmitting }, + } = useForm({ + defaultValues: { + province_id: row.original.province_id, + edarat_shahri_id: "", + description: "", + }, + resolver: yupResolver(validationSchema), + mode: "all", + }); + + const onSubmit = async (data) => { + const formData = new FormData(); + formData.append("province_id", data.province_id); + formData.append("edarate_shahri_id", data.edarat_shahri_id); + formData.append("refer_description", data.description); + await requestServer(`${REFER_FAST_REACT}/${row.original.id}`, "post", { + data: formData, + hasSidebarUpdate: true, + }) + .then(() => { + mutate(); + setOpenReferDialog(false); + }) + .catch(() => {}); + }; + + return ( + <> + + + {/* { + return ; + }} + /> */} + { + return ; + }} + /> + + + + + + + + + + + ); +}; +export default ReferContent; diff --git a/src/components/dashboard/fastReact/complaintList/RowActions/Refer/index.jsx b/src/components/dashboard/fastReact/complaintList/RowActions/Refer/index.jsx index 31c1cd5..0c67222 100644 --- a/src/components/dashboard/fastReact/complaintList/RowActions/Refer/index.jsx +++ b/src/components/dashboard/fastReact/complaintList/RowActions/Refer/index.jsx @@ -1,32 +1,32 @@ -import SettingsBackupRestoreIcon from "@mui/icons-material/SettingsBackupRestore"; -import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import ReferContent from "./ReferContent"; - -const Refer = ({ row, mutate }) => { - const [openReferDialog, setOpenReferDialog] = useState(false); - - return ( - <> - - setOpenReferDialog(true)}> - - - - - ارجاع - {openReferDialog && } - - - ); -}; -export default Refer; +import SettingsBackupRestoreIcon from "@mui/icons-material/SettingsBackupRestore"; +import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import ReferContent from "./ReferContent"; + +const Refer = ({ row, mutate }) => { + const [openReferDialog, setOpenReferDialog] = useState(false); + + return ( + <> + + setOpenReferDialog(true)}> + + + + + ارجاع + {openReferDialog && } + + + ); +}; +export default Refer; diff --git a/src/components/dashboard/fastReact/complaintList/RowActions/ReferList/ReferListContent.jsx b/src/components/dashboard/fastReact/complaintList/RowActions/ReferList/ReferListContent.jsx index aa8ba3d..fec5c81 100644 --- a/src/components/dashboard/fastReact/complaintList/RowActions/ReferList/ReferListContent.jsx +++ b/src/components/dashboard/fastReact/complaintList/RowActions/ReferList/ReferListContent.jsx @@ -1,82 +1,82 @@ -import DialogLoading from "@/core/components/DialogLoading"; -import { GET_FAST_REACT_REFER_LIST } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { - DialogContent, - Table, - TableBody, - TableCell, - TableContainer, - TableHead, - TableRow, - Typography, -} from "@mui/material"; -import moment from "jalali-moment"; -import { useEffect, useState } from "react"; - -const ReferListContent = ({ rowId }) => { - const [loading, setLoading] = useState(true); - const [data, setData] = useState(null); - const request = useRequest(); - - useEffect(() => { - const fetchData = async () => { - try { - setLoading(true); - const response = await request(`${GET_FAST_REACT_REFER_LIST}/${rowId}`); - setData(response.data.data); - } catch (error) { - } finally { - setLoading(false); - } - }; - - fetchData(); - }, [rowId]); - - return ( - <> - - {loading ? ( - - ) : data.length !== 0 ? ( - - - - - کاربر - از اداره - به اداره - تاریخ - توضیحات - - - - {data.map((refer, index) => { - const formatLocation = (province, edareh) => - province ? `${province} | ${edareh}` : edareh; - return ( - - {refer.user} - - {formatLocation(refer.from_province, refer.from_edareh)} - - {formatLocation(refer.to_province, refer.to_edareh)} - - {moment(refer.created_at).locale("fa").format("HH:mm | yyyy/MM/DD")} - - {refer.description} - - ); - })} - -
    -
    - ) : ( - ارجاعی در سامانه یافت نشد - )} -
    - - ); -}; -export default ReferListContent; +import DialogLoading from "@/core/components/DialogLoading"; +import { GET_FAST_REACT_REFER_LIST } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { + DialogContent, + Table, + TableBody, + TableCell, + TableContainer, + TableHead, + TableRow, + Typography, +} from "@mui/material"; +import moment from "jalali-moment"; +import { useEffect, useState } from "react"; + +const ReferListContent = ({ rowId }) => { + const [loading, setLoading] = useState(true); + const [data, setData] = useState(null); + const request = useRequest(); + + useEffect(() => { + const fetchData = async () => { + try { + setLoading(true); + const response = await request(`${GET_FAST_REACT_REFER_LIST}/${rowId}`); + setData(response.data.data); + } catch (error) { + } finally { + setLoading(false); + } + }; + + fetchData(); + }, [rowId]); + + return ( + <> + + {loading ? ( + + ) : data.length !== 0 ? ( + + + + + کاربر + از اداره + به اداره + تاریخ + توضیحات + + + + {data.map((refer, index) => { + const formatLocation = (province, edareh) => + province ? `${province} | ${edareh}` : edareh; + return ( + + {refer.user} + + {formatLocation(refer.from_province, refer.from_edareh)} + + {formatLocation(refer.to_province, refer.to_edareh)} + + {moment(refer.created_at).locale("fa").format("HH:mm | yyyy/MM/DD")} + + {refer.description} + + ); + })} + +
    +
    + ) : ( + ارجاعی در سامانه یافت نشد + )} +
    + + ); +}; +export default ReferListContent; diff --git a/src/components/dashboard/fastReact/complaintList/RowActions/ReferList/index.jsx b/src/components/dashboard/fastReact/complaintList/RowActions/ReferList/index.jsx index 619bd98..238ac72 100644 --- a/src/components/dashboard/fastReact/complaintList/RowActions/ReferList/index.jsx +++ b/src/components/dashboard/fastReact/complaintList/RowActions/ReferList/index.jsx @@ -1,43 +1,43 @@ -import { Button, Dialog, DialogActions, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import ListAltIcon from "@mui/icons-material/ListAlt"; -import ReferListContent from "./ReferListContent"; -import { useState } from "react"; - -const ReferList = ({ rowId }) => { - const [openReferListDialog, setOpenReferListDialog] = useState(false); - return ( - <> - - setOpenReferListDialog(true)}> - - - - setOpenReferListDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - لیست ارجاعات - {openReferListDialog && } - - - - - - ); -}; -export default ReferList; +import { Button, Dialog, DialogActions, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import ListAltIcon from "@mui/icons-material/ListAlt"; +import ReferListContent from "./ReferListContent"; +import { useState } from "react"; + +const ReferList = ({ rowId }) => { + const [openReferListDialog, setOpenReferListDialog] = useState(false); + return ( + <> + + setOpenReferListDialog(true)}> + + + + setOpenReferListDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + لیست ارجاعات + {openReferListDialog && } + + + + + + ); +}; +export default ReferList; diff --git a/src/components/dashboard/fastReact/complaintList/RowActions/index.jsx b/src/components/dashboard/fastReact/complaintList/RowActions/index.jsx index f272407..dadade5 100644 --- a/src/components/dashboard/fastReact/complaintList/RowActions/index.jsx +++ b/src/components/dashboard/fastReact/complaintList/RowActions/index.jsx @@ -1,24 +1,24 @@ -import { Box } from "@mui/material"; -import RegisterAction from "../Form/registerAction"; -import ReferList from "./ReferList"; -import Refer from "./Refer"; -import { usePermissions } from "@/lib/hooks/usePermissions"; - -const RowActions = ({ row, mutate, mutateParentTable }) => { - const { data: userPermissions } = usePermissions(); - const hasActionPermission = userPermissions.includes("show-fast-react-edarate-shahri"); - return ( - - {hasActionPermission && ( - - )} - - - - ); -}; -export default RowActions; +import { Box } from "@mui/material"; +import RegisterAction from "../Form/registerAction"; +import ReferList from "./ReferList"; +import Refer from "./Refer"; +import { usePermissions } from "@/lib/hooks/usePermissions"; + +const RowActions = ({ row, mutate, mutateParentTable }) => { + const { data: userPermissions } = usePermissions(); + const hasActionPermission = userPermissions.includes("show-fast-react-edarate-shahri"); + return ( + + {hasActionPermission && ( + + )} + + + + ); +}; +export default RowActions; diff --git a/src/components/dashboard/fastReact/complaintList/Toolbar.jsx b/src/components/dashboard/fastReact/complaintList/Toolbar.jsx index 22d8bd3..90edaea 100644 --- a/src/components/dashboard/fastReact/complaintList/Toolbar.jsx +++ b/src/components/dashboard/fastReact/complaintList/Toolbar.jsx @@ -1,11 +1,11 @@ -import { Stack } from "@mui/material"; -import PrintExcel from "./ExcelPrint"; - -const Toolbar = ({ table, filterData, mutate }) => { - return ( - - - - ); -}; -export default Toolbar; +import { Stack } from "@mui/material"; +import PrintExcel from "./ExcelPrint"; + +const Toolbar = ({ table, filterData, mutate }) => { + return ( + + + + ); +}; +export default Toolbar; diff --git a/src/components/dashboard/fastReact/complaintList/index.jsx b/src/components/dashboard/fastReact/complaintList/index.jsx index cf2fb55..9c3a77e 100644 --- a/src/components/dashboard/fastReact/complaintList/index.jsx +++ b/src/components/dashboard/fastReact/complaintList/index.jsx @@ -1,45 +1,45 @@ -import { Badge, Button, IconButton, useMediaQuery } from "@mui/material"; -import ChecklistIcon from "@mui/icons-material/Checklist"; -import { useTheme } from "@emotion/react"; -import { useState } from "react"; -import ComplaintListTable from "./ComplaintListTable"; -import { useSidebarBadge } from "@/lib/hooks/useSidebarBadge"; -import { getValueByPath } from "@/core/utils/getValueByPath"; - -const ComplaintList = ({ mutate }) => { - const { data } = useSidebarBadge(); - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const [open, setOpen] = useState(false); - - const handleOpen = () => { - setOpen(true); - }; - return ( - <> - {isMobile ? ( - - - - ) : ( - - - - )} - - - ); -}; -export default ComplaintList; +import { Badge, Button, IconButton, useMediaQuery } from "@mui/material"; +import ChecklistIcon from "@mui/icons-material/Checklist"; +import { useTheme } from "@emotion/react"; +import { useState } from "react"; +import ComplaintListTable from "./ComplaintListTable"; +import { useSidebarBadge } from "@/lib/hooks/useSidebarBadge"; +import { getValueByPath } from "@/core/utils/getValueByPath"; + +const ComplaintList = ({ mutate }) => { + const { data } = useSidebarBadge(); + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const [open, setOpen] = useState(false); + + const handleOpen = () => { + setOpen(true); + }; + return ( + <> + {isMobile ? ( + + + + ) : ( + + + + )} + + + ); +}; +export default ComplaintList; diff --git a/src/components/dashboard/fastReact/operator/ExcelPrint/index.jsx b/src/components/dashboard/fastReact/operator/ExcelPrint/index.jsx index c1e2bea..57ebe0c 100644 --- a/src/components/dashboard/fastReact/operator/ExcelPrint/index.jsx +++ b/src/components/dashboard/fastReact/operator/ExcelPrint/index.jsx @@ -1,75 +1,75 @@ -import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; -import { useMemo, useState } from "react"; -import moment from "jalali-moment"; -import FileSaver from "file-saver"; -import DescriptionIcon from "@mui/icons-material/Description"; -import useRequest from "@/lib/hooks/useRequest"; -import { EXPORT_FAST_REACT_OPERATOR_LIST } from "@/core/utils/routes"; -import { useTheme } from "@emotion/react"; -import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; -import isArrayEmpty from "@/core/utils/isArrayEmpty"; - -const PrintExcel = ({ table, filterData }) => { - const [loading, setLoading] = useState(false); - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const requestServer = useRequest(); - const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { - if (filter.value && (!Array.isArray(filter.value) || filter.value.some((item) => item.trim() !== ""))) { - acc.push({ id: key, value: filter.value }); - } - return acc; - }, []); - - const filterParams = useMemo(() => { - const params = new URLSearchParams(); - if (activeFilters.length > 0) { - activeFilters.map((filter, index) => { - const filteredFilterData = DataTableFilterDataStructure(filterData, isArrayEmpty); - params.set("filters", JSON.stringify(filteredFilterData.length === 0 ? [] : filteredFilterData)); - }); - } else { - params.set("filters", JSON.stringify([])); - } - return params; - }, [activeFilters]); - - const clickHandler = () => { - setLoading(true); - requestServer(`${EXPORT_FAST_REACT_OPERATOR_LIST}?${filterParams}`, "get", { - requestOptions: { responseType: "blob" }, - }) - .then((response) => { - const filename = `خروجی کارتابل عملیات واکنش سریع تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; - FileSaver.saveAs(response.data, filename); - }) - .catch(() => {}) - .finally(() => { - setLoading(false); - }); - }; - - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - - ); -}; - -export default PrintExcel; +import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; +import { useMemo, useState } from "react"; +import moment from "jalali-moment"; +import FileSaver from "file-saver"; +import DescriptionIcon from "@mui/icons-material/Description"; +import useRequest from "@/lib/hooks/useRequest"; +import { EXPORT_FAST_REACT_OPERATOR_LIST } from "@/core/utils/routes"; +import { useTheme } from "@emotion/react"; +import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; +import isArrayEmpty from "@/core/utils/isArrayEmpty"; + +const PrintExcel = ({ table, filterData }) => { + const [loading, setLoading] = useState(false); + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const requestServer = useRequest(); + const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { + if (filter.value && (!Array.isArray(filter.value) || filter.value.some((item) => item.trim() !== ""))) { + acc.push({ id: key, value: filter.value }); + } + return acc; + }, []); + + const filterParams = useMemo(() => { + const params = new URLSearchParams(); + if (activeFilters.length > 0) { + activeFilters.map((filter, index) => { + const filteredFilterData = DataTableFilterDataStructure(filterData, isArrayEmpty); + params.set("filters", JSON.stringify(filteredFilterData.length === 0 ? [] : filteredFilterData)); + }); + } else { + params.set("filters", JSON.stringify([])); + } + return params; + }, [activeFilters]); + + const clickHandler = () => { + setLoading(true); + requestServer(`${EXPORT_FAST_REACT_OPERATOR_LIST}?${filterParams}`, "get", { + requestOptions: { responseType: "blob" }, + }) + .then((response) => { + const filename = `خروجی کارتابل عملیات واکنش سریع تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; + FileSaver.saveAs(response.data, filename); + }) + .catch(() => {}) + .finally(() => { + setLoading(false); + }); + }; + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + + ); +}; + +export default PrintExcel; diff --git a/src/components/dashboard/fastReact/operator/Form/EditForm/EditController.jsx b/src/components/dashboard/fastReact/operator/Form/EditForm/EditController.jsx index f20797f..710364c 100644 --- a/src/components/dashboard/fastReact/operator/Form/EditForm/EditController.jsx +++ b/src/components/dashboard/fastReact/operator/Form/EditForm/EditController.jsx @@ -1,72 +1,72 @@ -import useRequest from "@/lib/hooks/useRequest"; -import { useEffect, useState } from "react"; -import { GET_FAST_REACT_ITEM_DETAIL, UPDATE_FAST_REACT } from "@/core/utils/routes"; -import DialogLoading from "@/core/components/DialogLoading"; -import RegisterActionContent from "@/components/dashboard/fastReact/complaintList/Form/registerAction/RegisterActionContent"; - -const EditController = ({ rowId, mutate, setOpenEditDialog }) => { - const requestServer = useRequest(); - const [fastReactItemDetails, setFastReactItemDetails] = useState(null); - const [fastReactItemDetailsLoading, setFastReactItemDetailsLoading] = useState(false); - - useEffect(() => { - setFastReactItemDetailsLoading(true); - requestServer(`${GET_FAST_REACT_ITEM_DETAIL}/${rowId}`, "get") - .then((response) => { - setFastReactItemDetails(response.data.data); - setFastReactItemDetailsLoading(false); - }) - .catch((e) => { - setFastReactItemDetailsLoading(false); - }); - }, [rowId]); - const startPoint = fastReactItemDetails?.rms_start_latlng - ? { lat: fastReactItemDetails?.rms_start_latlng[0], lng: fastReactItemDetails?.rms_start_latlng[1] } - : { lat: "", lng: "" }; - const defaultData = { - rms_status: `${fastReactItemDetails?.rms_status || "1"}`, - description: fastReactItemDetails?.rms_description || "", - start_point: startPoint, - image_before_1: fastReactItemDetails?.image_before || null, - image_after_1: fastReactItemDetails?.image_after || null, - }; - const HandleSubmit = async (result) => { - const formData = new FormData(); - const rmsLatLng = `${result.start_point.lat},${result.start_point.lng}`; - if (result.rms_status === "1") { - formData.append("rms_description", result.description); - formData.append("rms_status", 1); - formData.append("start_point", rmsLatLng); - result.image_before_1 !== defaultData.image_before_1 && - formData.append("image_before", result.image_before_1); - result.image_after_1 !== defaultData.image_after_1 && formData.append("image_after", result.image_after_1); - } else { - formData.append("rms_description", result.description); - formData.append("rms_status", 2); - } - - await requestServer(`${UPDATE_FAST_REACT}/${rowId}`, "post", { - data: formData, - hasSidebarUpdate: true, - }) - .then(() => { - mutate(); - setOpenEditDialog(false); - }) - .catch(() => {}); - }; - return ( - <> - {fastReactItemDetailsLoading ? ( - - ) : ( - - )} - - ); -}; -export default EditController; +import useRequest from "@/lib/hooks/useRequest"; +import { useEffect, useState } from "react"; +import { GET_FAST_REACT_ITEM_DETAIL, UPDATE_FAST_REACT } from "@/core/utils/routes"; +import DialogLoading from "@/core/components/DialogLoading"; +import RegisterActionContent from "@/components/dashboard/fastReact/complaintList/Form/registerAction/RegisterActionContent"; + +const EditController = ({ rowId, mutate, setOpenEditDialog }) => { + const requestServer = useRequest(); + const [fastReactItemDetails, setFastReactItemDetails] = useState(null); + const [fastReactItemDetailsLoading, setFastReactItemDetailsLoading] = useState(false); + + useEffect(() => { + setFastReactItemDetailsLoading(true); + requestServer(`${GET_FAST_REACT_ITEM_DETAIL}/${rowId}`, "get") + .then((response) => { + setFastReactItemDetails(response.data.data); + setFastReactItemDetailsLoading(false); + }) + .catch((e) => { + setFastReactItemDetailsLoading(false); + }); + }, [rowId]); + const startPoint = fastReactItemDetails?.rms_start_latlng + ? { lat: fastReactItemDetails?.rms_start_latlng[0], lng: fastReactItemDetails?.rms_start_latlng[1] } + : { lat: "", lng: "" }; + const defaultData = { + rms_status: `${fastReactItemDetails?.rms_status || "1"}`, + description: fastReactItemDetails?.rms_description || "", + start_point: startPoint, + image_before_1: fastReactItemDetails?.image_before || null, + image_after_1: fastReactItemDetails?.image_after || null, + }; + const HandleSubmit = async (result) => { + const formData = new FormData(); + const rmsLatLng = `${result.start_point.lat},${result.start_point.lng}`; + if (result.rms_status === "1") { + formData.append("rms_description", result.description); + formData.append("rms_status", 1); + formData.append("start_point", rmsLatLng); + result.image_before_1 !== defaultData.image_before_1 && + formData.append("image_before", result.image_before_1); + result.image_after_1 !== defaultData.image_after_1 && formData.append("image_after", result.image_after_1); + } else { + formData.append("rms_description", result.description); + formData.append("rms_status", 2); + } + + await requestServer(`${UPDATE_FAST_REACT}/${rowId}`, "post", { + data: formData, + hasSidebarUpdate: true, + }) + .then(() => { + mutate(); + setOpenEditDialog(false); + }) + .catch(() => {}); + }; + return ( + <> + {fastReactItemDetailsLoading ? ( + + ) : ( + + )} + + ); +}; +export default EditController; diff --git a/src/components/dashboard/fastReact/operator/Form/EditForm/index.jsx b/src/components/dashboard/fastReact/operator/Form/EditForm/index.jsx index 0af8244..a47474e 100644 --- a/src/components/dashboard/fastReact/operator/Form/EditForm/index.jsx +++ b/src/components/dashboard/fastReact/operator/Form/EditForm/index.jsx @@ -1,58 +1,58 @@ -import BorderColorIcon from "@mui/icons-material/BorderColor"; -import CloseIcon from "@mui/icons-material/Close"; -import { Dialog, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import EditController from "./EditController"; - -const EditForm = ({ row, mutate, rowId }) => { - const [openEditDialog, setOpenEditDialog] = useState(false); - - return ( - <> - - { - setOpenEditDialog(true); - }} - > - - - - - setOpenEditDialog(false)} - sx={(theme) => ({ - position: "absolute", - right: 8, - top: 8, - zIndex: 50, - color: theme.palette.grey[500], - })} - > - - - {openEditDialog && ( - - )} - - - ); -}; -export default EditForm; +import BorderColorIcon from "@mui/icons-material/BorderColor"; +import CloseIcon from "@mui/icons-material/Close"; +import { Dialog, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import EditController from "./EditController"; + +const EditForm = ({ row, mutate, rowId }) => { + const [openEditDialog, setOpenEditDialog] = useState(false); + + return ( + <> + + { + setOpenEditDialog(true); + }} + > + + + + + setOpenEditDialog(false)} + sx={(theme) => ({ + position: "absolute", + right: 8, + top: 8, + zIndex: 50, + color: theme.palette.grey[500], + })} + > + + + {openEditDialog && ( + + )} + + + ); +}; +export default EditForm; diff --git a/src/components/dashboard/fastReact/operator/OperatorList.jsx b/src/components/dashboard/fastReact/operator/OperatorList.jsx index 7812d65..3154f6d 100644 --- a/src/components/dashboard/fastReact/operator/OperatorList.jsx +++ b/src/components/dashboard/fastReact/operator/OperatorList.jsx @@ -1,370 +1,370 @@ -import DataTableWithAuth from "@/core/components/DataTableWithAuth"; -import { GET_FAST_REACT_OPERATOR } from "@/core/utils/routes"; -import EngineeringIcon from "@mui/icons-material/Engineering"; -import ThreePIcon from "@mui/icons-material/ThreeP"; -import { Box, Stack, Typography } from "@mui/material"; -import moment from "jalali-moment"; -import { useMemo } from "react"; -import RowActions from "./RowActions"; -import DescriptionForm from "./RowActions/DescriptionDialog"; -import ImageDialog from "./RowActions/ImageDialog"; -import LocationForm from "./RowActions/LocationDialog"; -import Toolbar from "./Toolbar"; -import BlinkingCell from "@/core/components/BlinkingCell"; - -const OperatorList = () => { - const statusOptions = [ - { value: "", label: "همه وضعیت ها" }, - { value: 0, label: "درحال بررسی" }, - { value: 1, label: "تایید شده" }, - { value: 2, label: "عدم تایید" }, - ]; - - const columns = useMemo( - () => [ - { - accessorKey: "id", - header: "کد یکتا", - id: "road_observeds__id", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - Cell: ({ row }) => , - }, - { - header: "اطلاعات ثبت‌ شده در سامانه سوانح", - id: "fkInfo", - enableColumnFilter: false, - enableSorting: false, - grow: false, - size: 50, - columns: [ - { - accessorKey: "fk_RegisteredEventMessage", - header: "کد سوانح", - id: "fk_RegisteredEventMessage", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorKey: "Title", - header: "موضوع گزارش", - id: "Title", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorKey: "FeatureTypeTitle", - header: "نوع گزارش", - id: "FeatureTypeTitle", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorKey: "Description", - header: "توضیح گزارش", - id: "Description", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - if (renderedCellValue) { - return ( - - - - ); - } - return -; - }, - }, - { - header: "موقعیت", - id: "location", - enableColumnFilter: false, - enableSorting: false, - datatype: "array", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ row }) => { - if (!row.original.lat) return <>-; - return ( - - - - ); - }, - }, - { - accessorKey: "MobileForSendEventSms", - header: "شماره تماس گیرنده", - id: "MobileForSendEventSms", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorFn: (row) => moment(row.StartTime_DateTime).locale("fa").format("HH:mm | yyyy/MM/DD"), - header: "تاریخ ثبت", - id: "StartTime_DateTime", - enableColumnFilter: true, - datatype: "date", - filterMode: "between", - grow: false, - size: 100, - }, - ], - }, - { - header: "اطلاعات اقدام", - id: "rms_register", - enableColumnFilter: false, - enableSorting: false, - grow: false, - size: 50, - columns: [ - { - accessorFn: (row) => (row.rms_status == 1 ? "اقدام انجام شد" : "اقدام انجام نشد"), - header: "وضعیت اقدام", - id: "rms_register_status", - enableColumnFilter: false, - enableSorting: false, - grow: false, - size: 50, - }, - { - accessorKey: "rms_description", - header: "توضیح مامور", - id: "rms_description", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - if (renderedCellValue) { - return ( - - - - ); - } - return -; - }, - }, - { - header: "تصاویر", - id: "rms_images", - enableColumnFilter: false, - enableSorting: false, - datatype: "array", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ row }) => { - if (!row.original?.image_before && !row.original?.image_after) return <>-; - return ( - - {row.original?.image_before && row.original?.image_after && ( - - )} - - ); - }, - }, - { - header: "موقعیت", - id: "rms_location", - enableColumnFilter: false, - enableSorting: false, - datatype: "array", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ row }) => { - if (!row.original.rms_start_latlng) return <>-; - return ( - - - - ); - }, - }, - { - accessorFn: (row) => { - return row.rms_last_activity - ? moment(row?.rms_last_activity).locale("fa").format("HH:mm | yyyy/MM/DD") - : "-"; - }, - header: "تاریخ اقدام", - id: "rms_last_activity", - enableColumnFilter: true, - datatype: "date", - filterMode: "between", - grow: false, - size: 100, - }, - ], - }, - { - accessorKey: "status", - header: "وضعیت نظارت", - id: "status", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - sortDescFirst: true, - grow: false, - size: 100, - columnSelectOption: () => { - return statusOptions.map((status) => ({ - value: status.value, - label: status.label, - })); - }, - Cell: ({ row }) => <>{row.original.status_fa}, - }, - { - accessorKey: "supervisor_description", - header: "توضیح ناظر", - id: "supervisor_description", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - if (renderedCellValue) { - return ( - - - - ); - } - return -; - }, - }, - ], - [] - ); - - return ( - <> - - - - - ); -}; -export default OperatorList; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import { GET_FAST_REACT_OPERATOR } from "@/core/utils/routes"; +import EngineeringIcon from "@mui/icons-material/Engineering"; +import ThreePIcon from "@mui/icons-material/ThreeP"; +import { Box, Stack, Typography } from "@mui/material"; +import moment from "jalali-moment"; +import { useMemo } from "react"; +import RowActions from "./RowActions"; +import DescriptionForm from "./RowActions/DescriptionDialog"; +import ImageDialog from "./RowActions/ImageDialog"; +import LocationForm from "./RowActions/LocationDialog"; +import Toolbar from "./Toolbar"; +import BlinkingCell from "@/core/components/BlinkingCell"; + +const OperatorList = () => { + const statusOptions = [ + { value: "", label: "همه وضعیت ها" }, + { value: 0, label: "درحال بررسی" }, + { value: 1, label: "تایید شده" }, + { value: 2, label: "عدم تایید" }, + ]; + + const columns = useMemo( + () => [ + { + accessorKey: "id", + header: "کد یکتا", + id: "road_observeds__id", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + Cell: ({ row }) => , + }, + { + header: "اطلاعات ثبت‌ شده در سامانه سوانح", + id: "fkInfo", + enableColumnFilter: false, + enableSorting: false, + grow: false, + size: 50, + columns: [ + { + accessorKey: "fk_RegisteredEventMessage", + header: "کد سوانح", + id: "fk_RegisteredEventMessage", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "Title", + header: "موضوع گزارش", + id: "Title", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "FeatureTypeTitle", + header: "نوع گزارش", + id: "FeatureTypeTitle", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "Description", + header: "توضیح گزارش", + id: "Description", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + if (renderedCellValue) { + return ( + + + + ); + } + return -; + }, + }, + { + header: "موقعیت", + id: "location", + enableColumnFilter: false, + enableSorting: false, + datatype: "array", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => { + if (!row.original.lat) return <>-; + return ( + + + + ); + }, + }, + { + accessorKey: "MobileForSendEventSms", + header: "شماره تماس گیرنده", + id: "MobileForSendEventSms", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorFn: (row) => moment(row.StartTime_DateTime).locale("fa").format("HH:mm | yyyy/MM/DD"), + header: "تاریخ ثبت", + id: "StartTime_DateTime", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + ], + }, + { + header: "اطلاعات اقدام", + id: "rms_register", + enableColumnFilter: false, + enableSorting: false, + grow: false, + size: 50, + columns: [ + { + accessorFn: (row) => (row.rms_status == 1 ? "اقدام انجام شد" : "اقدام انجام نشد"), + header: "وضعیت اقدام", + id: "rms_register_status", + enableColumnFilter: false, + enableSorting: false, + grow: false, + size: 50, + }, + { + accessorKey: "rms_description", + header: "توضیح مامور", + id: "rms_description", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + if (renderedCellValue) { + return ( + + + + ); + } + return -; + }, + }, + { + header: "تصاویر", + id: "rms_images", + enableColumnFilter: false, + enableSorting: false, + datatype: "array", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => { + if (!row.original?.image_before && !row.original?.image_after) return <>-; + return ( + + {row.original?.image_before && row.original?.image_after && ( + + )} + + ); + }, + }, + { + header: "موقعیت", + id: "rms_location", + enableColumnFilter: false, + enableSorting: false, + datatype: "array", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => { + if (!row.original.rms_start_latlng) return <>-; + return ( + + + + ); + }, + }, + { + accessorFn: (row) => { + return row.rms_last_activity + ? moment(row?.rms_last_activity).locale("fa").format("HH:mm | yyyy/MM/DD") + : "-"; + }, + header: "تاریخ اقدام", + id: "rms_last_activity", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + ], + }, + { + accessorKey: "status", + header: "وضعیت نظارت", + id: "status", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + sortDescFirst: true, + grow: false, + size: 100, + columnSelectOption: () => { + return statusOptions.map((status) => ({ + value: status.value, + label: status.label, + })); + }, + Cell: ({ row }) => <>{row.original.status_fa}, + }, + { + accessorKey: "supervisor_description", + header: "توضیح ناظر", + id: "supervisor_description", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + if (renderedCellValue) { + return ( + + + + ); + } + return -; + }, + }, + ], + [] + ); + + return ( + <> + + + + + ); +}; +export default OperatorList; diff --git a/src/components/dashboard/fastReact/operator/RowActions/DescriptionDialog/index.jsx b/src/components/dashboard/fastReact/operator/RowActions/DescriptionDialog/index.jsx index 4d80ac4..06b3cdf 100644 --- a/src/components/dashboard/fastReact/operator/RowActions/DescriptionDialog/index.jsx +++ b/src/components/dashboard/fastReact/operator/RowActions/DescriptionDialog/index.jsx @@ -1,50 +1,50 @@ -import { Dialog, DialogContent, DialogTitle, IconButton, Tooltip, Typography, Card, CardContent } from "@mui/material"; -import { useState } from "react"; -import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye"; -import CloseIcon from "@mui/icons-material/Close"; - -const DescriptionForm = ({ description, title, icon: IconComponent = RemoveRedEyeIcon }) => { - const [openOfficerDescriptionDialog, setOpenOfficerDescriptionDialog] = useState(false); - - return ( - <> - - setOpenOfficerDescriptionDialog(true)}> - - - - setOpenOfficerDescriptionDialog(false)} - PaperProps={{ - sx: { - transition: "all .3s", - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - borderRadius: 2, - padding: 1, - }, - }} - maxWidth="sm" - fullWidth - dir="rtl" - > - - - {title} - - setOpenOfficerDescriptionDialog(false)} size="small"> - - - - - - - {description || "هیچ توضیحی موجود نیست"} - - - - - - ); -}; -export default DescriptionForm; +import { Dialog, DialogContent, DialogTitle, IconButton, Tooltip, Typography, Card, CardContent } from "@mui/material"; +import { useState } from "react"; +import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye"; +import CloseIcon from "@mui/icons-material/Close"; + +const DescriptionForm = ({ description, title, icon: IconComponent = RemoveRedEyeIcon }) => { + const [openOfficerDescriptionDialog, setOpenOfficerDescriptionDialog] = useState(false); + + return ( + <> + + setOpenOfficerDescriptionDialog(true)}> + + + + setOpenOfficerDescriptionDialog(false)} + PaperProps={{ + sx: { + transition: "all .3s", + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + borderRadius: 2, + padding: 1, + }, + }} + maxWidth="sm" + fullWidth + dir="rtl" + > + + + {title} + + setOpenOfficerDescriptionDialog(false)} size="small"> + + + + + + + {description || "هیچ توضیحی موجود نیست"} + + + + + + ); +}; +export default DescriptionForm; diff --git a/src/components/dashboard/fastReact/operator/RowActions/ImageDialog/ImageFormContent.jsx b/src/components/dashboard/fastReact/operator/RowActions/ImageDialog/ImageFormContent.jsx index c8f22d0..f8fd088 100644 --- a/src/components/dashboard/fastReact/operator/RowActions/ImageDialog/ImageFormContent.jsx +++ b/src/components/dashboard/fastReact/operator/RowActions/ImageDialog/ImageFormContent.jsx @@ -1,45 +1,45 @@ -import { Box, Stack, Typography, useTheme } from "@mui/material"; -import Image from "next/image"; - -const ImageFormContent = ({ image, title }) => { - const theme = useTheme(); - return ( - - - {title} - - - Image - - - ); -}; -export default ImageFormContent; +import { Box, Stack, Typography, useTheme } from "@mui/material"; +import Image from "next/image"; + +const ImageFormContent = ({ image, title }) => { + const theme = useTheme(); + return ( + + + {title} + + + Image + + + ); +}; +export default ImageFormContent; diff --git a/src/components/dashboard/fastReact/operator/RowActions/ImageDialog/index.jsx b/src/components/dashboard/fastReact/operator/RowActions/ImageDialog/index.jsx index de3b76a..8d1c546 100644 --- a/src/components/dashboard/fastReact/operator/RowActions/ImageDialog/index.jsx +++ b/src/components/dashboard/fastReact/operator/RowActions/ImageDialog/index.jsx @@ -1,46 +1,46 @@ -import PhotoLibraryIcon from "@mui/icons-material/PhotoLibrary"; -import { Button, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import ImageFormContent from "./ImageFormContent"; - -const ImageDialog = ({ image_before, image_after }) => { - const [openImageDialog, setOpenImageDialog] = useState(false); - - return ( - <> - - setOpenImageDialog(true)}> - - - - setOpenImageDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - maxWidth={"sm"} - scroll="paper" - > - تصاویر - - {openImageDialog && ( - <> - - - - )} - - - - - - - ); -}; -export default ImageDialog; +import PhotoLibraryIcon from "@mui/icons-material/PhotoLibrary"; +import { Button, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import ImageFormContent from "./ImageFormContent"; + +const ImageDialog = ({ image_before, image_after }) => { + const [openImageDialog, setOpenImageDialog] = useState(false); + + return ( + <> + + setOpenImageDialog(true)}> + + + + setOpenImageDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + maxWidth={"sm"} + scroll="paper" + > + تصاویر + + {openImageDialog && ( + <> + + + + )} + + + + + + + ); +}; +export default ImageDialog; diff --git a/src/components/dashboard/fastReact/operator/RowActions/LocationDialog/LocationFormContent.jsx b/src/components/dashboard/fastReact/operator/RowActions/LocationDialog/LocationFormContent.jsx index 94f091d..9c8253c 100644 --- a/src/components/dashboard/fastReact/operator/RowActions/LocationDialog/LocationFormContent.jsx +++ b/src/components/dashboard/fastReact/operator/RowActions/LocationDialog/LocationFormContent.jsx @@ -1,30 +1,30 @@ -"use client"; -import { Box, Button, DialogActions, DialogContent, Stack } from "@mui/material"; -import React from "react"; -import dynamic from "next/dynamic"; -import MapLoading from "@/core/components/MapLayer/Loading"; -import ShowLocationMarker from "@/core/components/ShowLocationMarker"; -const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { - loading: () => , - ssr: false, -}); - -const LocationFormContent = ({ setOpenLocationDialog, start_lat, start_lng }) => { - return ( - <> - - - - - - - - - - - - ); -}; -export default LocationFormContent; +"use client"; +import { Box, Button, DialogActions, DialogContent, Stack } from "@mui/material"; +import React from "react"; +import dynamic from "next/dynamic"; +import MapLoading from "@/core/components/MapLayer/Loading"; +import ShowLocationMarker from "@/core/components/ShowLocationMarker"; +const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { + loading: () => , + ssr: false, +}); + +const LocationFormContent = ({ setOpenLocationDialog, start_lat, start_lng }) => { + return ( + <> + + + + + + + + + + + + ); +}; +export default LocationFormContent; diff --git a/src/components/dashboard/fastReact/operator/RowActions/LocationDialog/index.jsx b/src/components/dashboard/fastReact/operator/RowActions/LocationDialog/index.jsx index 09df6ad..0b917b4 100644 --- a/src/components/dashboard/fastReact/operator/RowActions/LocationDialog/index.jsx +++ b/src/components/dashboard/fastReact/operator/RowActions/LocationDialog/index.jsx @@ -1,36 +1,36 @@ -import React, { useState } from "react"; -import { Tooltip, IconButton, Dialog, DialogTitle } from "@mui/material"; -import ExploreIcon from "@mui/icons-material/Explore"; -import LocationFormContent from "./LocationFormContent"; -const LocationForm = ({ start_lat, start_lng }) => { - const [openLocationDialog, setOpenLocationDialog] = useState(false); - - return ( - <> - - setOpenLocationDialog(true)}> - - - - setOpenLocationDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - موقعیت - - - - ); -}; -export default LocationForm; +import React, { useState } from "react"; +import { Tooltip, IconButton, Dialog, DialogTitle } from "@mui/material"; +import ExploreIcon from "@mui/icons-material/Explore"; +import LocationFormContent from "./LocationFormContent"; +const LocationForm = ({ start_lat, start_lng }) => { + const [openLocationDialog, setOpenLocationDialog] = useState(false); + + return ( + <> + + setOpenLocationDialog(true)}> + + + + setOpenLocationDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + موقعیت + + + + ); +}; +export default LocationForm; diff --git a/src/components/dashboard/fastReact/operator/RowActions/index.jsx b/src/components/dashboard/fastReact/operator/RowActions/index.jsx index 5b632d6..a47490f 100644 --- a/src/components/dashboard/fastReact/operator/RowActions/index.jsx +++ b/src/components/dashboard/fastReact/operator/RowActions/index.jsx @@ -1,13 +1,13 @@ -import { Box } from "@mui/material"; -import EditForm from "../Form/EditForm"; - -const RowActions = ({ row, mutate }) => { - return ( - - {row.original.status === 2 && ( - - )} - - ); -}; -export default RowActions; +import { Box } from "@mui/material"; +import EditForm from "../Form/EditForm"; + +const RowActions = ({ row, mutate }) => { + return ( + + {row.original.status === 2 && ( + + )} + + ); +}; +export default RowActions; diff --git a/src/components/dashboard/fastReact/operator/Toolbar.jsx b/src/components/dashboard/fastReact/operator/Toolbar.jsx index 7db297e..c427536 100644 --- a/src/components/dashboard/fastReact/operator/Toolbar.jsx +++ b/src/components/dashboard/fastReact/operator/Toolbar.jsx @@ -1,13 +1,13 @@ -import PrintExcel from "./ExcelPrint"; -import ComplaintList from "../complaintList"; -import { Stack } from "@mui/material"; - -const Toolbar = ({ table, filterData, mutate }) => { - return ( - - - - - ); -}; -export default Toolbar; +import PrintExcel from "./ExcelPrint"; +import ComplaintList from "../complaintList"; +import { Stack } from "@mui/material"; + +const Toolbar = ({ table, filterData, mutate }) => { + return ( + + + + + ); +}; +export default Toolbar; diff --git a/src/components/dashboard/fastReact/operator/index.jsx b/src/components/dashboard/fastReact/operator/index.jsx index e95336c..26f9e34 100644 --- a/src/components/dashboard/fastReact/operator/index.jsx +++ b/src/components/dashboard/fastReact/operator/index.jsx @@ -1,14 +1,14 @@ -"use client"; -import PageTitle from "@/core/components/PageTitle"; -import { Stack } from "@mui/material"; -import OperatorList from "./OperatorList"; - -const OperatorPage = () => { - return ( - - - - - ); -}; -export default OperatorPage; +"use client"; +import PageTitle from "@/core/components/PageTitle"; +import { Stack } from "@mui/material"; +import OperatorList from "./OperatorList"; + +const OperatorPage = () => { + return ( + + + + + ); +}; +export default OperatorPage; diff --git a/src/components/dashboard/fastReact/supervisor/ExcelPrint/index.jsx b/src/components/dashboard/fastReact/supervisor/ExcelPrint/index.jsx index 120a8f0..51b7c09 100644 --- a/src/components/dashboard/fastReact/supervisor/ExcelPrint/index.jsx +++ b/src/components/dashboard/fastReact/supervisor/ExcelPrint/index.jsx @@ -1,75 +1,75 @@ -import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; -import { useMemo, useState } from "react"; -import moment from "jalali-moment"; -import FileSaver from "file-saver"; -import DescriptionIcon from "@mui/icons-material/Description"; -import useRequest from "@/lib/hooks/useRequest"; -import { EXPORT_FAST_REACT_SUPERVISOR_LIST } from "@/core/utils/routes"; -import { useTheme } from "@emotion/react"; -import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; -import isArrayEmpty from "@/core/utils/isArrayEmpty"; - -const PrintExcel = ({ table, filterData }) => { - const [loading, setLoading] = useState(false); - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const requestServer = useRequest(); - const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { - if (filter.value && (!Array.isArray(filter.value) || filter.value.some((item) => item.trim() !== ""))) { - acc.push({ id: key, value: filter.value }); - } - return acc; - }, []); - - const filterParams = useMemo(() => { - const params = new URLSearchParams(); - if (activeFilters.length > 0) { - activeFilters.map((filter, index) => { - const filteredFilterData = DataTableFilterDataStructure(filterData, isArrayEmpty); - params.set("filters", JSON.stringify(filteredFilterData.length === 0 ? [] : filteredFilterData)); - }); - } else { - params.set("filters", JSON.stringify([])); - } - return params; - }, [activeFilters]); - - const clickHandler = () => { - setLoading(true); - requestServer(`${EXPORT_FAST_REACT_SUPERVISOR_LIST}?${filterParams}`, "get", { - requestOptions: { responseType: "blob" }, - }) - .then((response) => { - const filename = `خروجی کارتابل ارزیابی واکنش سریع تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; - FileSaver.saveAs(response.data, filename); - }) - .catch(() => {}) - .finally(() => { - setLoading(false); - }); - }; - - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - - ); -}; - -export default PrintExcel; +import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; +import { useMemo, useState } from "react"; +import moment from "jalali-moment"; +import FileSaver from "file-saver"; +import DescriptionIcon from "@mui/icons-material/Description"; +import useRequest from "@/lib/hooks/useRequest"; +import { EXPORT_FAST_REACT_SUPERVISOR_LIST } from "@/core/utils/routes"; +import { useTheme } from "@emotion/react"; +import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; +import isArrayEmpty from "@/core/utils/isArrayEmpty"; + +const PrintExcel = ({ table, filterData }) => { + const [loading, setLoading] = useState(false); + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const requestServer = useRequest(); + const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { + if (filter.value && (!Array.isArray(filter.value) || filter.value.some((item) => item.trim() !== ""))) { + acc.push({ id: key, value: filter.value }); + } + return acc; + }, []); + + const filterParams = useMemo(() => { + const params = new URLSearchParams(); + if (activeFilters.length > 0) { + activeFilters.map((filter, index) => { + const filteredFilterData = DataTableFilterDataStructure(filterData, isArrayEmpty); + params.set("filters", JSON.stringify(filteredFilterData.length === 0 ? [] : filteredFilterData)); + }); + } else { + params.set("filters", JSON.stringify([])); + } + return params; + }, [activeFilters]); + + const clickHandler = () => { + setLoading(true); + requestServer(`${EXPORT_FAST_REACT_SUPERVISOR_LIST}?${filterParams}`, "get", { + requestOptions: { responseType: "blob" }, + }) + .then((response) => { + const filename = `خروجی کارتابل ارزیابی واکنش سریع تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; + FileSaver.saveAs(response.data, filename); + }) + .catch(() => {}) + .finally(() => { + setLoading(false); + }); + }; + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + + ); +}; + +export default PrintExcel; diff --git a/src/components/dashboard/fastReact/supervisor/RowActions/ConfirmDialog/ConfirmContent.jsx b/src/components/dashboard/fastReact/supervisor/RowActions/ConfirmDialog/ConfirmContent.jsx index 2a27c3e..552024d 100644 --- a/src/components/dashboard/fastReact/supervisor/RowActions/ConfirmDialog/ConfirmContent.jsx +++ b/src/components/dashboard/fastReact/supervisor/RowActions/ConfirmDialog/ConfirmContent.jsx @@ -1,70 +1,70 @@ -import { Button, DialogActions, DialogContent, Stack, TextField } from "@mui/material"; -import { useForm } from "react-hook-form"; -import useRequest from "@/lib/hooks/useRequest"; -import { VERIFY_BY_FAST_REACT_SUPERVISOR } from "@/core/utils/routes"; - -const ConfirmContent = ({ rowId, mutate, setOpenConfirmDialog }) => { - const requestServer = useRequest({ notificationSuccess: true }); - - const { - register, - handleSubmit, - formState: { isSubmitting }, - } = useForm({ - defaultValues: { - description: "", - }, - }); - - const onSubmit = async (data) => { - const formData = new FormData(); - data.description !== "" && formData.append("description", data.description); - formData.append("verify", 1); - requestServer(`${VERIFY_BY_FAST_REACT_SUPERVISOR}/${rowId}`, "post", { - data: formData, - hasSidebarUpdate: true, - }) - .then(() => { - mutate(); - setOpenConfirmDialog(false); - }) - .catch(() => {}); - }; - - return ( - <> - - - - - - - - - - - - - ); -}; -export default ConfirmContent; +import { Button, DialogActions, DialogContent, Stack, TextField } from "@mui/material"; +import { useForm } from "react-hook-form"; +import useRequest from "@/lib/hooks/useRequest"; +import { VERIFY_BY_FAST_REACT_SUPERVISOR } from "@/core/utils/routes"; + +const ConfirmContent = ({ rowId, mutate, setOpenConfirmDialog }) => { + const requestServer = useRequest({ notificationSuccess: true }); + + const { + register, + handleSubmit, + formState: { isSubmitting }, + } = useForm({ + defaultValues: { + description: "", + }, + }); + + const onSubmit = async (data) => { + const formData = new FormData(); + data.description !== "" && formData.append("description", data.description); + formData.append("verify", 1); + requestServer(`${VERIFY_BY_FAST_REACT_SUPERVISOR}/${rowId}`, "post", { + data: formData, + hasSidebarUpdate: true, + }) + .then(() => { + mutate(); + setOpenConfirmDialog(false); + }) + .catch(() => {}); + }; + + return ( + <> + + + + + + + + + + + + + ); +}; +export default ConfirmContent; diff --git a/src/components/dashboard/fastReact/supervisor/RowActions/ConfirmDialog/index.jsx b/src/components/dashboard/fastReact/supervisor/RowActions/ConfirmDialog/index.jsx index 10e6048..0d42be0 100644 --- a/src/components/dashboard/fastReact/supervisor/RowActions/ConfirmDialog/index.jsx +++ b/src/components/dashboard/fastReact/supervisor/RowActions/ConfirmDialog/index.jsx @@ -1,29 +1,29 @@ -import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import ConfirmContent from "./ConfirmContent"; -import DoneIcon from "@mui/icons-material/Done"; -const ConfirmForm = ({ rowId, mutate }) => { - const [openConfirmDialog, setOpenConfirmDialog] = useState(false); - return ( - <> - - setOpenConfirmDialog(true)}> - - - - - تایید اقدام - - - - ); -}; -export default ConfirmForm; +import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import ConfirmContent from "./ConfirmContent"; +import DoneIcon from "@mui/icons-material/Done"; +const ConfirmForm = ({ rowId, mutate }) => { + const [openConfirmDialog, setOpenConfirmDialog] = useState(false); + return ( + <> + + setOpenConfirmDialog(true)}> + + + + + تایید اقدام + + + + ); +}; +export default ConfirmForm; diff --git a/src/components/dashboard/fastReact/supervisor/RowActions/DescriptionDialog/index.jsx b/src/components/dashboard/fastReact/supervisor/RowActions/DescriptionDialog/index.jsx index 4d80ac4..06b3cdf 100644 --- a/src/components/dashboard/fastReact/supervisor/RowActions/DescriptionDialog/index.jsx +++ b/src/components/dashboard/fastReact/supervisor/RowActions/DescriptionDialog/index.jsx @@ -1,50 +1,50 @@ -import { Dialog, DialogContent, DialogTitle, IconButton, Tooltip, Typography, Card, CardContent } from "@mui/material"; -import { useState } from "react"; -import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye"; -import CloseIcon from "@mui/icons-material/Close"; - -const DescriptionForm = ({ description, title, icon: IconComponent = RemoveRedEyeIcon }) => { - const [openOfficerDescriptionDialog, setOpenOfficerDescriptionDialog] = useState(false); - - return ( - <> - - setOpenOfficerDescriptionDialog(true)}> - - - - setOpenOfficerDescriptionDialog(false)} - PaperProps={{ - sx: { - transition: "all .3s", - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - borderRadius: 2, - padding: 1, - }, - }} - maxWidth="sm" - fullWidth - dir="rtl" - > - - - {title} - - setOpenOfficerDescriptionDialog(false)} size="small"> - - - - - - - {description || "هیچ توضیحی موجود نیست"} - - - - - - ); -}; -export default DescriptionForm; +import { Dialog, DialogContent, DialogTitle, IconButton, Tooltip, Typography, Card, CardContent } from "@mui/material"; +import { useState } from "react"; +import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye"; +import CloseIcon from "@mui/icons-material/Close"; + +const DescriptionForm = ({ description, title, icon: IconComponent = RemoveRedEyeIcon }) => { + const [openOfficerDescriptionDialog, setOpenOfficerDescriptionDialog] = useState(false); + + return ( + <> + + setOpenOfficerDescriptionDialog(true)}> + + + + setOpenOfficerDescriptionDialog(false)} + PaperProps={{ + sx: { + transition: "all .3s", + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + borderRadius: 2, + padding: 1, + }, + }} + maxWidth="sm" + fullWidth + dir="rtl" + > + + + {title} + + setOpenOfficerDescriptionDialog(false)} size="small"> + + + + + + + {description || "هیچ توضیحی موجود نیست"} + + + + + + ); +}; +export default DescriptionForm; diff --git a/src/components/dashboard/fastReact/supervisor/RowActions/ImageDialog/ImageFormContent.jsx b/src/components/dashboard/fastReact/supervisor/RowActions/ImageDialog/ImageFormContent.jsx index c8f22d0..f8fd088 100644 --- a/src/components/dashboard/fastReact/supervisor/RowActions/ImageDialog/ImageFormContent.jsx +++ b/src/components/dashboard/fastReact/supervisor/RowActions/ImageDialog/ImageFormContent.jsx @@ -1,45 +1,45 @@ -import { Box, Stack, Typography, useTheme } from "@mui/material"; -import Image from "next/image"; - -const ImageFormContent = ({ image, title }) => { - const theme = useTheme(); - return ( - - - {title} - - - Image - - - ); -}; -export default ImageFormContent; +import { Box, Stack, Typography, useTheme } from "@mui/material"; +import Image from "next/image"; + +const ImageFormContent = ({ image, title }) => { + const theme = useTheme(); + return ( + + + {title} + + + Image + + + ); +}; +export default ImageFormContent; diff --git a/src/components/dashboard/fastReact/supervisor/RowActions/ImageDialog/index.jsx b/src/components/dashboard/fastReact/supervisor/RowActions/ImageDialog/index.jsx index de3b76a..8d1c546 100644 --- a/src/components/dashboard/fastReact/supervisor/RowActions/ImageDialog/index.jsx +++ b/src/components/dashboard/fastReact/supervisor/RowActions/ImageDialog/index.jsx @@ -1,46 +1,46 @@ -import PhotoLibraryIcon from "@mui/icons-material/PhotoLibrary"; -import { Button, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import ImageFormContent from "./ImageFormContent"; - -const ImageDialog = ({ image_before, image_after }) => { - const [openImageDialog, setOpenImageDialog] = useState(false); - - return ( - <> - - setOpenImageDialog(true)}> - - - - setOpenImageDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - maxWidth={"sm"} - scroll="paper" - > - تصاویر - - {openImageDialog && ( - <> - - - - )} - - - - - - - ); -}; -export default ImageDialog; +import PhotoLibraryIcon from "@mui/icons-material/PhotoLibrary"; +import { Button, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import ImageFormContent from "./ImageFormContent"; + +const ImageDialog = ({ image_before, image_after }) => { + const [openImageDialog, setOpenImageDialog] = useState(false); + + return ( + <> + + setOpenImageDialog(true)}> + + + + setOpenImageDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + maxWidth={"sm"} + scroll="paper" + > + تصاویر + + {openImageDialog && ( + <> + + + + )} + + + + + + + ); +}; +export default ImageDialog; diff --git a/src/components/dashboard/fastReact/supervisor/RowActions/LocationDialog/LocationFormContent.jsx b/src/components/dashboard/fastReact/supervisor/RowActions/LocationDialog/LocationFormContent.jsx index 94f091d..9c8253c 100644 --- a/src/components/dashboard/fastReact/supervisor/RowActions/LocationDialog/LocationFormContent.jsx +++ b/src/components/dashboard/fastReact/supervisor/RowActions/LocationDialog/LocationFormContent.jsx @@ -1,30 +1,30 @@ -"use client"; -import { Box, Button, DialogActions, DialogContent, Stack } from "@mui/material"; -import React from "react"; -import dynamic from "next/dynamic"; -import MapLoading from "@/core/components/MapLayer/Loading"; -import ShowLocationMarker from "@/core/components/ShowLocationMarker"; -const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { - loading: () => , - ssr: false, -}); - -const LocationFormContent = ({ setOpenLocationDialog, start_lat, start_lng }) => { - return ( - <> - - - - - - - - - - - - ); -}; -export default LocationFormContent; +"use client"; +import { Box, Button, DialogActions, DialogContent, Stack } from "@mui/material"; +import React from "react"; +import dynamic from "next/dynamic"; +import MapLoading from "@/core/components/MapLayer/Loading"; +import ShowLocationMarker from "@/core/components/ShowLocationMarker"; +const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { + loading: () => , + ssr: false, +}); + +const LocationFormContent = ({ setOpenLocationDialog, start_lat, start_lng }) => { + return ( + <> + + + + + + + + + + + + ); +}; +export default LocationFormContent; diff --git a/src/components/dashboard/fastReact/supervisor/RowActions/LocationDialog/index.jsx b/src/components/dashboard/fastReact/supervisor/RowActions/LocationDialog/index.jsx index 09df6ad..0b917b4 100644 --- a/src/components/dashboard/fastReact/supervisor/RowActions/LocationDialog/index.jsx +++ b/src/components/dashboard/fastReact/supervisor/RowActions/LocationDialog/index.jsx @@ -1,36 +1,36 @@ -import React, { useState } from "react"; -import { Tooltip, IconButton, Dialog, DialogTitle } from "@mui/material"; -import ExploreIcon from "@mui/icons-material/Explore"; -import LocationFormContent from "./LocationFormContent"; -const LocationForm = ({ start_lat, start_lng }) => { - const [openLocationDialog, setOpenLocationDialog] = useState(false); - - return ( - <> - - setOpenLocationDialog(true)}> - - - - setOpenLocationDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - موقعیت - - - - ); -}; -export default LocationForm; +import React, { useState } from "react"; +import { Tooltip, IconButton, Dialog, DialogTitle } from "@mui/material"; +import ExploreIcon from "@mui/icons-material/Explore"; +import LocationFormContent from "./LocationFormContent"; +const LocationForm = ({ start_lat, start_lng }) => { + const [openLocationDialog, setOpenLocationDialog] = useState(false); + + return ( + <> + + setOpenLocationDialog(true)}> + + + + setOpenLocationDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + موقعیت + + + + ); +}; +export default LocationForm; diff --git a/src/components/dashboard/fastReact/supervisor/RowActions/RejectDialog/RejectFormContent.jsx b/src/components/dashboard/fastReact/supervisor/RowActions/RejectDialog/RejectFormContent.jsx index b5feca5..f89df6a 100644 --- a/src/components/dashboard/fastReact/supervisor/RowActions/RejectDialog/RejectFormContent.jsx +++ b/src/components/dashboard/fastReact/supervisor/RowActions/RejectDialog/RejectFormContent.jsx @@ -1,84 +1,84 @@ -import { Button, DialogActions, DialogContent, Stack, TextField } from "@mui/material"; -import { useForm } from "react-hook-form"; -import { yupResolver } from "@hookform/resolvers/yup"; -import * as Yup from "yup"; -import useRequest from "@/lib/hooks/useRequest"; -import { REJECT_BY_FAST_REACT_SUPERVISOR } from "@/core/utils/routes"; - -const RejectContent = ({ rowId, mutate, setOpenRejectDialog }) => { - const requestServer = useRequest({ notificationSuccess: true }); - - const validationSchema = Yup.object().shape({ - description: Yup.string().required("لطفاً توضیحات را وارد کنید."), - }); - - const { - register, - handleSubmit, - formState: { errors, isSubmitting }, - reset, - } = useForm({ - defaultValues: { - description: "", - }, - resolver: yupResolver(validationSchema), - mode: "all", - }); - - const onSubmit = async (data) => { - const formData = new FormData(); - formData.append("description", data.description); - formData.append("verify", 2); - requestServer(`${REJECT_BY_FAST_REACT_SUPERVISOR}/${rowId}`, "post", { - data: formData, - hasSidebarUpdate: true, - }) - .then(() => { - mutate(); - setOpenRejectDialog(false); - }) - .catch(() => {}) - .finally(() => { - reset(); - }); - }; - - return ( - <> - - - - - - - - - - - - - ); -}; -export default RejectContent; +import { Button, DialogActions, DialogContent, Stack, TextField } from "@mui/material"; +import { useForm } from "react-hook-form"; +import { yupResolver } from "@hookform/resolvers/yup"; +import * as Yup from "yup"; +import useRequest from "@/lib/hooks/useRequest"; +import { REJECT_BY_FAST_REACT_SUPERVISOR } from "@/core/utils/routes"; + +const RejectContent = ({ rowId, mutate, setOpenRejectDialog }) => { + const requestServer = useRequest({ notificationSuccess: true }); + + const validationSchema = Yup.object().shape({ + description: Yup.string().required("لطفاً توضیحات را وارد کنید."), + }); + + const { + register, + handleSubmit, + formState: { errors, isSubmitting }, + reset, + } = useForm({ + defaultValues: { + description: "", + }, + resolver: yupResolver(validationSchema), + mode: "all", + }); + + const onSubmit = async (data) => { + const formData = new FormData(); + formData.append("description", data.description); + formData.append("verify", 2); + requestServer(`${REJECT_BY_FAST_REACT_SUPERVISOR}/${rowId}`, "post", { + data: formData, + hasSidebarUpdate: true, + }) + .then(() => { + mutate(); + setOpenRejectDialog(false); + }) + .catch(() => {}) + .finally(() => { + reset(); + }); + }; + + return ( + <> + + + + + + + + + + + + + ); +}; +export default RejectContent; diff --git a/src/components/dashboard/fastReact/supervisor/RowActions/RejectDialog/index.jsx b/src/components/dashboard/fastReact/supervisor/RowActions/RejectDialog/index.jsx index 5d754a5..9c1b890 100644 --- a/src/components/dashboard/fastReact/supervisor/RowActions/RejectDialog/index.jsx +++ b/src/components/dashboard/fastReact/supervisor/RowActions/RejectDialog/index.jsx @@ -1,29 +1,29 @@ -import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import ClearIcon from "@mui/icons-material/Clear"; -import RejectContent from "./RejectFormContent"; -const RejectForm = ({ rowId, mutate }) => { - const [openRejectDialog, setOpenRejectDialog] = useState(false); - return ( - <> - - setOpenRejectDialog(true)}> - - - - - عدم تایید اقدام - - - - ); -}; -export default RejectForm; +import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import ClearIcon from "@mui/icons-material/Clear"; +import RejectContent from "./RejectFormContent"; +const RejectForm = ({ rowId, mutate }) => { + const [openRejectDialog, setOpenRejectDialog] = useState(false); + return ( + <> + + setOpenRejectDialog(true)}> + + + + + عدم تایید اقدام + + + + ); +}; +export default RejectForm; diff --git a/src/components/dashboard/fastReact/supervisor/RowActions/RestoreForm/RestoreContent.jsx b/src/components/dashboard/fastReact/supervisor/RowActions/RestoreForm/RestoreContent.jsx index b62566f..3fc30f4 100644 --- a/src/components/dashboard/fastReact/supervisor/RowActions/RestoreForm/RestoreContent.jsx +++ b/src/components/dashboard/fastReact/supervisor/RowActions/RestoreForm/RestoreContent.jsx @@ -1,42 +1,42 @@ -import { RESTORE_FAST_REACT } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { Button, DialogActions, DialogContent, Stack, Typography } from "@mui/material"; -import { useState } from "react"; - -const RestoreContent = ({ rowId, mutate, setOpenRestoreDialog }) => { - const [submitting, setSubmitting] = useState(false); - const requestServer = useRequest({ notificationSuccess: true }); - const handleClick = () => { - setSubmitting(true); - requestServer(`${RESTORE_FAST_REACT}/${rowId}`, "post", { hasSidebarUpdate: true }) - .then(() => { - mutate(); - setOpenRestoreDialog(false); - setSubmitting(false); - }) - .catch(() => { - setSubmitting(false); - }); - }; - return ( - <> - - - - آیا از بازگردانی فعالیت اطمینان دارید؟ - - - - - - - - - ); -}; - -export default RestoreContent; +import { RESTORE_FAST_REACT } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { Button, DialogActions, DialogContent, Stack, Typography } from "@mui/material"; +import { useState } from "react"; + +const RestoreContent = ({ rowId, mutate, setOpenRestoreDialog }) => { + const [submitting, setSubmitting] = useState(false); + const requestServer = useRequest({ notificationSuccess: true }); + const handleClick = () => { + setSubmitting(true); + requestServer(`${RESTORE_FAST_REACT}/${rowId}`, "post", { hasSidebarUpdate: true }) + .then(() => { + mutate(); + setOpenRestoreDialog(false); + setSubmitting(false); + }) + .catch(() => { + setSubmitting(false); + }); + }; + return ( + <> + + + + آیا از بازگردانی فعالیت اطمینان دارید؟ + + + + + + + + + ); +}; + +export default RestoreContent; diff --git a/src/components/dashboard/fastReact/supervisor/RowActions/RestoreForm/index.jsx b/src/components/dashboard/fastReact/supervisor/RowActions/RestoreForm/index.jsx index 2632c20..08668c9 100644 --- a/src/components/dashboard/fastReact/supervisor/RowActions/RestoreForm/index.jsx +++ b/src/components/dashboard/fastReact/supervisor/RowActions/RestoreForm/index.jsx @@ -1,32 +1,32 @@ -import React, { useState } from "react"; -import { Tooltip, IconButton, Dialog, DialogTitle } from "@mui/material"; -import ReplyIcon from "@mui/icons-material/Reply"; -import RestoreContent from "./RestoreContent"; -const RestoreForm = ({ rowId, mutate }) => { - const [openRestoreDialog, setOpenRestoreDialog] = useState(false); - - return ( - <> - - setOpenRestoreDialog(true)}> - - - - setOpenRestoreDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - بازگردانی فعالیت - - - - ); -}; -export default RestoreForm; +import React, { useState } from "react"; +import { Tooltip, IconButton, Dialog, DialogTitle } from "@mui/material"; +import ReplyIcon from "@mui/icons-material/Reply"; +import RestoreContent from "./RestoreContent"; +const RestoreForm = ({ rowId, mutate }) => { + const [openRestoreDialog, setOpenRestoreDialog] = useState(false); + + return ( + <> + + setOpenRestoreDialog(true)}> + + + + setOpenRestoreDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + بازگردانی فعالیت + + + + ); +}; +export default RestoreForm; diff --git a/src/components/dashboard/fastReact/supervisor/RowActions/index.jsx b/src/components/dashboard/fastReact/supervisor/RowActions/index.jsx index 10461f2..763173b 100644 --- a/src/components/dashboard/fastReact/supervisor/RowActions/index.jsx +++ b/src/components/dashboard/fastReact/supervisor/RowActions/index.jsx @@ -1,20 +1,20 @@ -import { Box } from "@mui/material"; -import ConfirmForm from "./ConfirmDialog"; -import RejectForm from "./RejectDialog"; -import { usePermissions } from "@/lib/hooks/usePermissions"; -import RestoreForm from "./RestoreForm"; - -const RowActions = ({ row, mutate }) => { - const { data: userPermissions } = usePermissions(); - const hasRestorePermission = userPermissions.includes("restore-fast-react"); - return ( - - {row.original?.status === 0 && } - {row.original?.status === 0 && } - {hasRestorePermission && row.original?.status !== 0 && ( - - )} - - ); -}; -export default RowActions; +import { Box } from "@mui/material"; +import ConfirmForm from "./ConfirmDialog"; +import RejectForm from "./RejectDialog"; +import { usePermissions } from "@/lib/hooks/usePermissions"; +import RestoreForm from "./RestoreForm"; + +const RowActions = ({ row, mutate }) => { + const { data: userPermissions } = usePermissions(); + const hasRestorePermission = userPermissions.includes("restore-fast-react"); + return ( + + {row.original?.status === 0 && } + {row.original?.status === 0 && } + {hasRestorePermission && row.original?.status !== 0 && ( + + )} + + ); +}; +export default RowActions; diff --git a/src/components/dashboard/fastReact/supervisor/SupervisorList.jsx b/src/components/dashboard/fastReact/supervisor/SupervisorList.jsx index 5d29f8d..0df0b24 100644 --- a/src/components/dashboard/fastReact/supervisor/SupervisorList.jsx +++ b/src/components/dashboard/fastReact/supervisor/SupervisorList.jsx @@ -1,470 +1,470 @@ -import { useEffect, useMemo, useState } from "react"; -import { Box, Stack, Typography } from "@mui/material"; -import DataTableWithAuth from "@/core/components/DataTableWithAuth"; -import Toolbar from "./Toolbar"; -import moment from "jalali-moment"; -import RowActions from "./RowActions"; -import { GET_FAST_REACT_SUPERVISOR } from "@/core/utils/routes"; -import useProvinces from "@/lib/hooks/useProvince"; -import CustomSelectByDependency from "@/core/components/DataTable/filter/fieldsType/CustomSelectByDependency"; -import { usePermissions } from "@/lib/hooks/usePermissions"; -import { useAuth } from "@/lib/contexts/auth"; -import useEdaratLists from "@/lib/hooks/useEdaratLists"; -import DescriptionForm from "./RowActions/DescriptionDialog"; -import LocationForm from "./RowActions/LocationDialog"; -import EngineeringIcon from "@mui/icons-material/Engineering"; -import ThreePIcon from "@mui/icons-material/ThreeP"; -import ImageDialog from "./RowActions/ImageDialog"; -import BlinkingCell from "@/core/components/BlinkingCell"; - -const SupervisorList = () => { - const { data: userPermissions } = usePermissions(); - const hasCountryPermission = userPermissions?.includes("show-fast-react"); - const { user } = useAuth(); - const statusOptions = [ - { value: "", label: "همه وضعیت ها" }, - { value: 0, label: "درحال بررسی" }, - { value: 1, label: "تایید شده" }, - { value: 2, label: "عدم تایید" }, - ]; - - const columns = useMemo(() => { - const dynamicColumns = { - header: "استان", - id: "road_observeds__province_id", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - grow: false, - size: 130, - ColumnSelectComponent: (props) => { - const { provinces, errorProvinces, loadingProvinces } = useProvinces(); - const getColumnSelectOptions = useMemo(() => { - if (loadingProvinces) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorProvinces) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: "کل کشور" }, - ...provinces.map((province) => ({ - value: province.id, - label: province.name_fa, - })), - ]; - }, [provinces, errorProvinces, loadingProvinces]); - return ( - - ); - }, - Cell: ({ row }) => <>{row.original.province_fa}, - }; - return [ - { - accessorKey: "id", - header: "کد یکتا", - id: "road_observeds__id", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - Cell: ({ row }) => , - }, - ...(hasCountryPermission ? [dynamicColumns] : []), - { - header: "اداره", - id: "edarate_shahri_id", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - dependencyId: hasCountryPermission ? "road_observeds__province_id" : null, - grow: false, - size: 120, - ColumnSelectComponent: (props) => { - const { edaratList, loadingEdaratList, errorEdaratList } = useEdaratLists( - hasCountryPermission ? props.dependencyFieldValue.value : user.province_id - ); - const [prevDependency, setPrevDependency] = useState( - hasCountryPermission ? props.dependencyFieldValue.value : user.province_id - ); - - const getColumnSelectOptions = useMemo(() => { - if (hasCountryPermission && props.dependencyFieldValue.value === "") { - return [{ value: "empty", label: "ابتدا استان را انتخاب کنید" }]; - } - if (loadingEdaratList) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorEdaratList) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: "کل ادارات" }, - ...edaratList.map((edare) => ({ - value: edare.id, - label: edare.name_fa, - })), - ]; - }, [edaratList, loadingEdaratList, errorEdaratList]); - useEffect(() => { - if (hasCountryPermission) return; - if (prevDependency === props.dependencyFieldValue?.value) return; - props.handleChange({ ...props.filterParameters, value: "" }); - setPrevDependency(props.dependencyFieldValue?.value); - }, [props.dependencyFieldValue?.value, hasCountryPermission]); - return ( - - ); - }, - Cell: ({ renderedCellValue, row }) => <>{row.original.name_fa}, - }, - { - header: "اطلاعات ثبت‌ شده در سامانه سوانح", - id: "fkInfo", - enableColumnFilter: false, - enableSorting: false, - grow: false, - size: 50, - columns: [ - { - accessorKey: "fk_RegisteredEventMessage", - header: "کد سوانح", - id: "fk_RegisteredEventMessage", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorKey: "Title", - header: "موضوع گزارش", - id: "Title", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorKey: "FeatureTypeTitle", - header: "نوع گزارش", - id: "FeatureTypeTitle", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorKey: "Description", - header: "توضیح گزارش", - id: "Description", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - if (renderedCellValue) { - return ( - - - - ); - } - return -; - }, - }, - { - header: "موقعیت", - id: "location", - enableColumnFilter: false, - enableSorting: false, - datatype: "array", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ row }) => { - if (!row.original.lat) return <>-; - return ( - - - - ); - }, - }, - { - accessorKey: "MobileForSendEventSms", - header: "شماره تماس گیرنده", - id: "MobileForSendEventSms", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorFn: (row) => moment(row.StartTime_DateTime).locale("fa").format("HH:mm | yyyy/MM/DD"), - header: "تاریخ ثبت", - id: "StartTime_DateTime", - enableColumnFilter: true, - datatype: "date", - filterMode: "between", - grow: false, - size: 100, - }, - ], - }, - { - header: "اطلاعات اقدام", - id: "rms_register", - enableColumnFilter: false, - enableSorting: false, - grow: false, - size: 50, - columns: [ - { - accessorFn: (row) => (row.rms_status == 1 ? "اقدام انجام شد" : "اقدام انجام نشد"), - header: "وضعیت اقدام", - id: "rms_register_status", - enableColumnFilter: false, - enableSorting: false, - grow: false, - size: 50, - }, - { - accessorKey: "rms_description", - header: "توضیح مامور", - id: "rms_description", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - if (renderedCellValue) { - return ( - - - - ); - } - return -; - }, - }, - { - header: "تصاویر", - id: "rms_images", - enableColumnFilter: false, - enableSorting: false, - datatype: "array", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ row }) => { - if (!row.original?.image_before && !row.original?.image_after) return <>-; - return ( - - {row.original?.image_before && row.original?.image_after && ( - - )} - - ); - }, - }, - { - header: "موقعیت", - id: "rms_location", - enableColumnFilter: false, - enableSorting: false, - datatype: "array", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ row }) => { - if (!row.original.rms_start_latlng) return <>-; - return ( - - - - ); - }, - }, - { - accessorFn: (row) => { - return row.rms_last_activity - ? moment(row?.rms_last_activity).locale("fa").format("HH:mm | yyyy/MM/DD") - : "-"; - }, - header: "تاریخ اقدام", - id: "rms_last_activity", - enableColumnFilter: true, - datatype: "date", - filterMode: "between", - grow: false, - size: 100, - }, - ], - }, - { - accessorKey: "status", - header: "وضعیت نظارت", - id: "status", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - sortDescFirst: true, - grow: false, - size: 100, - columnSelectOption: () => { - return statusOptions.map((status) => ({ - value: status.value, - label: status.label, - })); - }, - Cell: ({ row }) => <>{row.original.status_fa}, - }, - { - accessorKey: "supervisor_description", - header: "توضیح ناظر", - id: "supervisor_description", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - if (renderedCellValue) { - return ( - - - - ); - } - return -; - }, - }, - ]; - }, []); - - return ( - <> - - - - - ); -}; -export default SupervisorList; +import { useEffect, useMemo, useState } from "react"; +import { Box, Stack, Typography } from "@mui/material"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import Toolbar from "./Toolbar"; +import moment from "jalali-moment"; +import RowActions from "./RowActions"; +import { GET_FAST_REACT_SUPERVISOR } from "@/core/utils/routes"; +import useProvinces from "@/lib/hooks/useProvince"; +import CustomSelectByDependency from "@/core/components/DataTable/filter/fieldsType/CustomSelectByDependency"; +import { usePermissions } from "@/lib/hooks/usePermissions"; +import { useAuth } from "@/lib/contexts/auth"; +import useEdaratLists from "@/lib/hooks/useEdaratLists"; +import DescriptionForm from "./RowActions/DescriptionDialog"; +import LocationForm from "./RowActions/LocationDialog"; +import EngineeringIcon from "@mui/icons-material/Engineering"; +import ThreePIcon from "@mui/icons-material/ThreeP"; +import ImageDialog from "./RowActions/ImageDialog"; +import BlinkingCell from "@/core/components/BlinkingCell"; + +const SupervisorList = () => { + const { data: userPermissions } = usePermissions(); + const hasCountryPermission = userPermissions?.includes("show-fast-react"); + const { user } = useAuth(); + const statusOptions = [ + { value: "", label: "همه وضعیت ها" }, + { value: 0, label: "درحال بررسی" }, + { value: 1, label: "تایید شده" }, + { value: 2, label: "عدم تایید" }, + ]; + + const columns = useMemo(() => { + const dynamicColumns = { + header: "استان", + id: "road_observeds__province_id", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 130, + ColumnSelectComponent: (props) => { + const { provinces, errorProvinces, loadingProvinces } = useProvinces(); + const getColumnSelectOptions = useMemo(() => { + if (loadingProvinces) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorProvinces) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: "کل کشور" }, + ...provinces.map((province) => ({ + value: province.id, + label: province.name_fa, + })), + ]; + }, [provinces, errorProvinces, loadingProvinces]); + return ( + + ); + }, + Cell: ({ row }) => <>{row.original.province_fa}, + }; + return [ + { + accessorKey: "id", + header: "کد یکتا", + id: "road_observeds__id", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + Cell: ({ row }) => , + }, + ...(hasCountryPermission ? [dynamicColumns] : []), + { + header: "اداره", + id: "edarate_shahri_id", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + dependencyId: hasCountryPermission ? "road_observeds__province_id" : null, + grow: false, + size: 120, + ColumnSelectComponent: (props) => { + const { edaratList, loadingEdaratList, errorEdaratList } = useEdaratLists( + hasCountryPermission ? props.dependencyFieldValue.value : user.province_id + ); + const [prevDependency, setPrevDependency] = useState( + hasCountryPermission ? props.dependencyFieldValue.value : user.province_id + ); + + const getColumnSelectOptions = useMemo(() => { + if (hasCountryPermission && props.dependencyFieldValue.value === "") { + return [{ value: "empty", label: "ابتدا استان را انتخاب کنید" }]; + } + if (loadingEdaratList) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorEdaratList) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: "کل ادارات" }, + ...edaratList.map((edare) => ({ + value: edare.id, + label: edare.name_fa, + })), + ]; + }, [edaratList, loadingEdaratList, errorEdaratList]); + useEffect(() => { + if (hasCountryPermission) return; + if (prevDependency === props.dependencyFieldValue?.value) return; + props.handleChange({ ...props.filterParameters, value: "" }); + setPrevDependency(props.dependencyFieldValue?.value); + }, [props.dependencyFieldValue?.value, hasCountryPermission]); + return ( + + ); + }, + Cell: ({ renderedCellValue, row }) => <>{row.original.name_fa}, + }, + { + header: "اطلاعات ثبت‌ شده در سامانه سوانح", + id: "fkInfo", + enableColumnFilter: false, + enableSorting: false, + grow: false, + size: 50, + columns: [ + { + accessorKey: "fk_RegisteredEventMessage", + header: "کد سوانح", + id: "fk_RegisteredEventMessage", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "Title", + header: "موضوع گزارش", + id: "Title", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "FeatureTypeTitle", + header: "نوع گزارش", + id: "FeatureTypeTitle", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "Description", + header: "توضیح گزارش", + id: "Description", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + if (renderedCellValue) { + return ( + + + + ); + } + return -; + }, + }, + { + header: "موقعیت", + id: "location", + enableColumnFilter: false, + enableSorting: false, + datatype: "array", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => { + if (!row.original.lat) return <>-; + return ( + + + + ); + }, + }, + { + accessorKey: "MobileForSendEventSms", + header: "شماره تماس گیرنده", + id: "MobileForSendEventSms", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorFn: (row) => moment(row.StartTime_DateTime).locale("fa").format("HH:mm | yyyy/MM/DD"), + header: "تاریخ ثبت", + id: "StartTime_DateTime", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + ], + }, + { + header: "اطلاعات اقدام", + id: "rms_register", + enableColumnFilter: false, + enableSorting: false, + grow: false, + size: 50, + columns: [ + { + accessorFn: (row) => (row.rms_status == 1 ? "اقدام انجام شد" : "اقدام انجام نشد"), + header: "وضعیت اقدام", + id: "rms_register_status", + enableColumnFilter: false, + enableSorting: false, + grow: false, + size: 50, + }, + { + accessorKey: "rms_description", + header: "توضیح مامور", + id: "rms_description", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + if (renderedCellValue) { + return ( + + + + ); + } + return -; + }, + }, + { + header: "تصاویر", + id: "rms_images", + enableColumnFilter: false, + enableSorting: false, + datatype: "array", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => { + if (!row.original?.image_before && !row.original?.image_after) return <>-; + return ( + + {row.original?.image_before && row.original?.image_after && ( + + )} + + ); + }, + }, + { + header: "موقعیت", + id: "rms_location", + enableColumnFilter: false, + enableSorting: false, + datatype: "array", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => { + if (!row.original.rms_start_latlng) return <>-; + return ( + + + + ); + }, + }, + { + accessorFn: (row) => { + return row.rms_last_activity + ? moment(row?.rms_last_activity).locale("fa").format("HH:mm | yyyy/MM/DD") + : "-"; + }, + header: "تاریخ اقدام", + id: "rms_last_activity", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + ], + }, + { + accessorKey: "status", + header: "وضعیت نظارت", + id: "status", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + sortDescFirst: true, + grow: false, + size: 100, + columnSelectOption: () => { + return statusOptions.map((status) => ({ + value: status.value, + label: status.label, + })); + }, + Cell: ({ row }) => <>{row.original.status_fa}, + }, + { + accessorKey: "supervisor_description", + header: "توضیح ناظر", + id: "supervisor_description", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + if (renderedCellValue) { + return ( + + + + ); + } + return -; + }, + }, + ]; + }, []); + + return ( + <> + + + + + ); +}; +export default SupervisorList; diff --git a/src/components/dashboard/fastReact/supervisor/Toolbar.jsx b/src/components/dashboard/fastReact/supervisor/Toolbar.jsx index 7db297e..c427536 100644 --- a/src/components/dashboard/fastReact/supervisor/Toolbar.jsx +++ b/src/components/dashboard/fastReact/supervisor/Toolbar.jsx @@ -1,13 +1,13 @@ -import PrintExcel from "./ExcelPrint"; -import ComplaintList from "../complaintList"; -import { Stack } from "@mui/material"; - -const Toolbar = ({ table, filterData, mutate }) => { - return ( - - - - - ); -}; -export default Toolbar; +import PrintExcel from "./ExcelPrint"; +import ComplaintList from "../complaintList"; +import { Stack } from "@mui/material"; + +const Toolbar = ({ table, filterData, mutate }) => { + return ( + + + + + ); +}; +export default Toolbar; diff --git a/src/components/dashboard/fastReact/supervisor/index.jsx b/src/components/dashboard/fastReact/supervisor/index.jsx index 03adf90..8443e66 100644 --- a/src/components/dashboard/fastReact/supervisor/index.jsx +++ b/src/components/dashboard/fastReact/supervisor/index.jsx @@ -1,14 +1,14 @@ -"use client"; -import PageTitle from "@/core/components/PageTitle"; -import { Stack } from "@mui/material"; -import SupervisorList from "./SupervisorList"; - -const SupervisorPage = () => { - return ( - - - - - ); -}; -export default SupervisorPage; +"use client"; +import PageTitle from "@/core/components/PageTitle"; +import { Stack } from "@mui/material"; +import SupervisorList from "./SupervisorList"; + +const SupervisorPage = () => { + return ( + + + + + ); +}; +export default SupervisorPage; diff --git a/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/RoadSafetyForm/DescriptionForm.jsx b/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/RoadSafetyForm/DescriptionForm.jsx index 49ffa3c..ba2cdeb 100644 --- a/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/RoadSafetyForm/DescriptionForm.jsx +++ b/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/RoadSafetyForm/DescriptionForm.jsx @@ -1,29 +1,29 @@ -import { FormControl, FormHelperText, InputLabel, OutlinedInput, Stack } from "@mui/material"; - -const DescriptionForm = ({ errors, register }) => { - return ( - - - - توضیحات - - - - {errors.description ? errors.description.message : null} - - - - ); -}; -export default DescriptionForm; +import { FormControl, FormHelperText, InputLabel, OutlinedInput, Stack } from "@mui/material"; + +const DescriptionForm = ({ errors, register }) => { + return ( + + + + توضیحات + + + + {errors.description ? errors.description.message : null} + + + + ); +}; +export default DescriptionForm; diff --git a/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/RoadSafetyForm/ManagerOrAssistantSubmit.jsx b/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/RoadSafetyForm/ManagerOrAssistantSubmit.jsx index a515950..d755b7c 100644 --- a/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/RoadSafetyForm/ManagerOrAssistantSubmit.jsx +++ b/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/RoadSafetyForm/ManagerOrAssistantSubmit.jsx @@ -1,15 +1,15 @@ -import { Button } from "@mui/material"; - -const ManagerOrAssistantSubmit = ({ isSubmitting }) => { - return ( - <> - - - - ); -}; -export default ManagerOrAssistantSubmit; +import { Button } from "@mui/material"; + +const ManagerOrAssistantSubmit = ({ isSubmitting }) => { + return ( + <> + + + + ); +}; +export default ManagerOrAssistantSubmit; diff --git a/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/RoadSafetyForm/PrevCartableOpinion.jsx b/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/RoadSafetyForm/PrevCartableOpinion.jsx index 6197267..d6df4b1 100644 --- a/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/RoadSafetyForm/PrevCartableOpinion.jsx +++ b/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/RoadSafetyForm/PrevCartableOpinion.jsx @@ -1,25 +1,25 @@ -import { Card, CardContent, CardHeader, CircularProgress, Divider, Stack, Typography } from "@mui/material"; - -const PrevCartableOpinion = ({ message, loadingMessage, errorMessage }) => { - return ( - - - - - {errorMessage ? ( - خطا در دریافت اطلاعات !!! - ) : loadingMessage ? ( - - - درحال دریافت اطلاعات - - ) : ( - {message} - )} - - - - - ); -}; -export default PrevCartableOpinion; +import { Card, CardContent, CardHeader, CircularProgress, Divider, Stack, Typography } from "@mui/material"; + +const PrevCartableOpinion = ({ message, loadingMessage, errorMessage }) => { + return ( + + + + + {errorMessage ? ( + خطا در دریافت اطلاعات !!! + ) : loadingMessage ? ( + + + درحال دریافت اطلاعات + + ) : ( + {message} + )} + + + + + ); +}; +export default PrevCartableOpinion; diff --git a/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/RoadSafetyForm/QuestionSafetyForm.jsx b/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/RoadSafetyForm/QuestionSafetyForm.jsx index cc9be16..5410d66 100644 --- a/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/RoadSafetyForm/QuestionSafetyForm.jsx +++ b/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/RoadSafetyForm/QuestionSafetyForm.jsx @@ -1,33 +1,33 @@ -import { Card, CardContent, FormControl, FormLabel, Stack, Typography } from "@mui/material"; - -const QuestionSafetyForm = () => { - return ( - - - - - - - آیا ایمنی راه این طرح مورد تایید است ؟ - - - - دفتر حریم راه : - - بله - - - - - - - ); -}; -export default QuestionSafetyForm; +import { Card, CardContent, FormControl, FormLabel, Stack, Typography } from "@mui/material"; + +const QuestionSafetyForm = () => { + return ( + + + + + + + آیا ایمنی راه این طرح مورد تایید است ؟ + + + + دفتر حریم راه : + + بله + + + + + + + ); +}; +export default QuestionSafetyForm; diff --git a/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/RoadSafetyForm/RoadSafetyFormContext.jsx b/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/RoadSafetyForm/RoadSafetyFormContext.jsx index 4f3f740..75a279c 100644 --- a/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/RoadSafetyForm/RoadSafetyFormContext.jsx +++ b/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/RoadSafetyForm/RoadSafetyFormContext.jsx @@ -1,82 +1,82 @@ -import { DialogActions, DialogContent, Stack } from "@mui/material"; -import StyledForm from "@/core/components/StyledForm"; -import useRequest from "@/lib/hooks/useRequest"; -import { useForm } from "react-hook-form"; -import { yupResolver } from "@hookform/resolvers/yup"; -import { object, string } from "yup"; -import { SUBMIT_ROAD_SAFETY_FORM } from "@/core/utils/routes"; -import usePrevStateOpinion from "@/lib/hooks/usePrevStateopinion"; -import QuestionSafetyForm from "./QuestionSafetyForm"; -import PrevCartableOpinion from "./PrevCartableOpinion"; -import DescriptionForm from "./DescriptionForm"; -import ManagerOrAssistantSubmit from "./ManagerOrAssistantSubmit"; -import ApplicantRequestDetail from "@/core/components/ApplicantRequestDetail"; -const fakeData = { - id: 1, - shomareh_darkhast: "2124", - ostan: "ostan", - shahr: "shahr", - shahrestan: "shahrestan", - bakhsh: "bakhsh", - roosta: "roosta", - tarikh_darkhast: "tarikh_darkhast", - sazman: "sazman", - masahat_zamin: "masahat_zamin", - masahat_tarh: "masahat_tarh", - gorooh_tarh: "gorooh_tarh", - onvane_tarh: "onvane_tarh", - address: "کرج - فلان جا - جنب پاساژ - نزدیک اونجا - اونور خیابون - زیر رو گذر - روی زیر گذر", - file_mosavab: "file", - polygon: [ - [51.515, -0.09], - [51.52, -0.1], - [51.52, -0.12], - ], -}; -const validationSchema = object({ - description: string().required("وارد کردن توضیحات الزامیست!"), -}); -const RoadSafetyFormContext = ({ rowId, mutate, setOpenRoadSafetyForm }) => { - const defaultValues = { - description: "", - }; - const requestServer = useRequest({ notificationSuccess: true }); - const { message, loadingMessage, errorMessage } = usePrevStateOpinion(); - const { - register, - handleSubmit, - formState: { isSubmitting, errors }, - } = useForm({ defaultValues, resolver: yupResolver(validationSchema), mode: "all" }); - const onSubmit = async (data) => { - const formData = new FormData(); - formData.append("description", data.description); - requestServer(`${SUBMIT_ROAD_SAFETY_FORM}/${rowId}`, "post", { - data: formData, - }) - .then(() => { - setOpenRoadSafetyForm(false); - mutate(); - }) - .catch(() => {}); - }; - return ( - - - - - - - - - - - - - - ); -}; -export default RoadSafetyFormContext; +import { DialogActions, DialogContent, Stack } from "@mui/material"; +import StyledForm from "@/core/components/StyledForm"; +import useRequest from "@/lib/hooks/useRequest"; +import { useForm } from "react-hook-form"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { object, string } from "yup"; +import { SUBMIT_ROAD_SAFETY_FORM } from "@/core/utils/routes"; +import usePrevStateOpinion from "@/lib/hooks/usePrevStateopinion"; +import QuestionSafetyForm from "./QuestionSafetyForm"; +import PrevCartableOpinion from "./PrevCartableOpinion"; +import DescriptionForm from "./DescriptionForm"; +import ManagerOrAssistantSubmit from "./ManagerOrAssistantSubmit"; +import ApplicantRequestDetail from "@/core/components/ApplicantRequestDetail"; +const fakeData = { + id: 1, + shomareh_darkhast: "2124", + ostan: "ostan", + shahr: "shahr", + shahrestan: "shahrestan", + bakhsh: "bakhsh", + roosta: "roosta", + tarikh_darkhast: "tarikh_darkhast", + sazman: "sazman", + masahat_zamin: "masahat_zamin", + masahat_tarh: "masahat_tarh", + gorooh_tarh: "gorooh_tarh", + onvane_tarh: "onvane_tarh", + address: "کرج - فلان جا - جنب پاساژ - نزدیک اونجا - اونور خیابون - زیر رو گذر - روی زیر گذر", + file_mosavab: "file", + polygon: [ + [51.515, -0.09], + [51.52, -0.1], + [51.52, -0.12], + ], +}; +const validationSchema = object({ + description: string().required("وارد کردن توضیحات الزامیست!"), +}); +const RoadSafetyFormContext = ({ rowId, mutate, setOpenRoadSafetyForm }) => { + const defaultValues = { + description: "", + }; + const requestServer = useRequest({ notificationSuccess: true }); + const { message, loadingMessage, errorMessage } = usePrevStateOpinion(); + const { + register, + handleSubmit, + formState: { isSubmitting, errors }, + } = useForm({ defaultValues, resolver: yupResolver(validationSchema), mode: "all" }); + const onSubmit = async (data) => { + const formData = new FormData(); + formData.append("description", data.description); + requestServer(`${SUBMIT_ROAD_SAFETY_FORM}/${rowId}`, "post", { + data: formData, + }) + .then(() => { + setOpenRoadSafetyForm(false); + mutate(); + }) + .catch(() => {}); + }; + return ( + + + + + + + + + + + + + + ); +}; +export default RoadSafetyFormContext; diff --git a/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/RoadSafetyForm/index.jsx b/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/RoadSafetyForm/index.jsx index 9c57473..a4de0d7 100644 --- a/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/RoadSafetyForm/index.jsx +++ b/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/RoadSafetyForm/index.jsx @@ -1,52 +1,52 @@ -import { Dialog, IconButton, Stack, Tooltip } from "@mui/material"; -import EngineeringIcon from "@mui/icons-material/Engineering"; -import DialogTransition from "@/core/components/DialogTransition"; -import { useState } from "react"; -import { Close } from "@mui/icons-material"; -import RoadSafetyFormContext from "./RoadSafetyFormContext"; - -const RoadSafetyForm = ({ rowId, mutate }) => { - const [openRoadSafetyForm, setOpenRoadSafetyForm] = useState(false); - return ( - - - { - setOpenRoadSafetyForm(true); - }} - > - - - - - setOpenRoadSafetyForm(false)} - sx={{ - position: "absolute", - right: 8, - top: 8, - zIndex: 10, - color: (theme) => theme.palette.grey[500], - }} - > - - - - - - ); -}; -export default RoadSafetyForm; +import { Dialog, IconButton, Stack, Tooltip } from "@mui/material"; +import EngineeringIcon from "@mui/icons-material/Engineering"; +import DialogTransition from "@/core/components/DialogTransition"; +import { useState } from "react"; +import { Close } from "@mui/icons-material"; +import RoadSafetyFormContext from "./RoadSafetyFormContext"; + +const RoadSafetyForm = ({ rowId, mutate }) => { + const [openRoadSafetyForm, setOpenRoadSafetyForm] = useState(false); + return ( + + + { + setOpenRoadSafetyForm(true); + }} + > + + + + + setOpenRoadSafetyForm(false)} + sx={{ + position: "absolute", + right: 8, + top: 8, + zIndex: 10, + color: (theme) => theme.palette.grey[500], + }} + > + + + + + + ); +}; +export default RoadSafetyForm; diff --git a/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/TaskDetail/DetailDialog.jsx b/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/TaskDetail/DetailDialog.jsx index 7b50738..777eecf 100644 --- a/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/TaskDetail/DetailDialog.jsx +++ b/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/TaskDetail/DetailDialog.jsx @@ -1,75 +1,75 @@ -"use client"; - -import { Dialog, DialogContent } from "@mui/material"; -import { object, string } from "yup"; -import useRequest from "@/lib/hooks/useRequest"; -import { useForm } from "react-hook-form"; -import { yupResolver } from "@hookform/resolvers/yup"; -import StyledForm from "@/core/components/StyledForm"; -import ApplicantRequestDetail from "@/core/components/ApplicantRequestDetail"; - -const fakeData = { - id: 1, - shomareh_darkhast: "2124", - ostan: "ostan", - shahr: "shahr", - shahrestan: "shahrestan", - bakhsh: "bakhsh", - roosta: "roosta", - tarikh_darkhast: "tarikh_darkhast", - sazman: "sazman", - masahat_zamin: "masahat_zamin", - masahat_tarh: "masahat_tarh", - gorooh_tarh: "gorooh_tarh", - onvane_tarh: "onvane_tarh", - address: "کرج - فلان جا - جنب پاساژ - نزدیک اونجا - اونور خیابون - زیر رو گذر - روی زیر گذر", - file_mosavab: "file", - polygon: [ - [51.515, -0.09], - [51.52, -0.1], - [51.52, -0.12], - ], -}; - -const validationSchema = object({ - description: string().required("وارد کردن توضیحات الزامیست!"), -}); - -const DetailDialog = ({ taskModal, setTaskModal, rowId, mutate }) => { - const requestServer = useRequest({ auth: true }); - const defaultValues = { - description: "", - }; - const handleClose = () => { - setTaskModal(false); - }; - - const { - register, - handleSubmit, - formState: { isSubmitting, errors, touchedFields }, - } = useForm({ defaultValues, resolver: yupResolver(validationSchema), mode: "all" }); - - const onSubmit = async (data) => { - const formData = new FormData(); - formData.append("description", data.description); - requestServer(`api-for-send-to-harim/${rowId}`, "post", { - data: formData, - }) - .then(() => { - handleClose(); - mutate(); - }) - .catch(() => {}); - }; - return ( - - - - - - - - ); -}; -export default DetailDialog; +"use client"; + +import { Dialog, DialogContent } from "@mui/material"; +import { object, string } from "yup"; +import useRequest from "@/lib/hooks/useRequest"; +import { useForm } from "react-hook-form"; +import { yupResolver } from "@hookform/resolvers/yup"; +import StyledForm from "@/core/components/StyledForm"; +import ApplicantRequestDetail from "@/core/components/ApplicantRequestDetail"; + +const fakeData = { + id: 1, + shomareh_darkhast: "2124", + ostan: "ostan", + shahr: "shahr", + shahrestan: "shahrestan", + bakhsh: "bakhsh", + roosta: "roosta", + tarikh_darkhast: "tarikh_darkhast", + sazman: "sazman", + masahat_zamin: "masahat_zamin", + masahat_tarh: "masahat_tarh", + gorooh_tarh: "gorooh_tarh", + onvane_tarh: "onvane_tarh", + address: "کرج - فلان جا - جنب پاساژ - نزدیک اونجا - اونور خیابون - زیر رو گذر - روی زیر گذر", + file_mosavab: "file", + polygon: [ + [51.515, -0.09], + [51.52, -0.1], + [51.52, -0.12], + ], +}; + +const validationSchema = object({ + description: string().required("وارد کردن توضیحات الزامیست!"), +}); + +const DetailDialog = ({ taskModal, setTaskModal, rowId, mutate }) => { + const requestServer = useRequest({ auth: true }); + const defaultValues = { + description: "", + }; + const handleClose = () => { + setTaskModal(false); + }; + + const { + register, + handleSubmit, + formState: { isSubmitting, errors, touchedFields }, + } = useForm({ defaultValues, resolver: yupResolver(validationSchema), mode: "all" }); + + const onSubmit = async (data) => { + const formData = new FormData(); + formData.append("description", data.description); + requestServer(`api-for-send-to-harim/${rowId}`, "post", { + data: formData, + }) + .then(() => { + handleClose(); + mutate(); + }) + .catch(() => {}); + }; + return ( + + + + + + + + ); +}; +export default DetailDialog; diff --git a/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/TaskDetail/index.jsx b/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/TaskDetail/index.jsx index 24f6b31..1641840 100644 --- a/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/TaskDetail/index.jsx +++ b/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/TaskDetail/index.jsx @@ -1,26 +1,26 @@ -"use client"; - -import { IconButton, Tooltip } from "@mui/material"; -import AssignmentIcon from "@mui/icons-material/Assignment"; -import DetailDialog from "./DetailDialog"; -import { useState } from "react"; - -const TaskDetail = ({ rowId, mutate }) => { - const [taskModal, setTaskModal] = useState(false); - - const openDetailDialog = () => { - setTaskModal(true); - }; - - return ( - <> - - - - - - - - ); -}; -export default TaskDetail; +"use client"; + +import { IconButton, Tooltip } from "@mui/material"; +import AssignmentIcon from "@mui/icons-material/Assignment"; +import DetailDialog from "./DetailDialog"; +import { useState } from "react"; + +const TaskDetail = ({ rowId, mutate }) => { + const [taskModal, setTaskModal] = useState(false); + + const openDetailDialog = () => { + setTaskModal(true); + }; + + return ( + <> + + + + + + + + ); +}; +export default TaskDetail; diff --git a/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/index.jsx b/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/index.jsx index b7434f8..ae4213c 100644 --- a/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/index.jsx +++ b/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/RowActions/index.jsx @@ -1,13 +1,13 @@ -import TaskDetail from "./TaskDetail"; -import { Box } from "@mui/material"; -import RoadSafetyForm from "./RoadSafetyForm"; - -const RowActions = ({ row, mutate }) => { - return ( - - - - - ); -}; -export default RowActions; +import TaskDetail from "./TaskDetail"; +import { Box } from "@mui/material"; +import RoadSafetyForm from "./RoadSafetyForm"; + +const RowActions = ({ row, mutate }) => { + return ( + + + + + ); +}; +export default RowActions; diff --git a/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/TaskList.jsx b/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/TaskList.jsx index 20e8300..31452f6 100644 --- a/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/TaskList.jsx +++ b/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/TaskList.jsx @@ -1,145 +1,145 @@ -"use client"; - -import { useMemo } from "react"; -import { Box } from "@mui/material"; -import DataTableWithAuth from "@/core/components/DataTableWithAuth"; -import RowActions from "./RowActions"; - -const TaskList = () => { - const columns = useMemo( - () => [ - { - accessorKey: "id", - header: "کد یکتا", - id: "id", - enableColumnFilter: false, - datatype: "text", - filterMode: "notEquals", - }, - { - accessorKey: "aplication_number", - header: "شماره درخواست", - id: "aplication_number", - enableColumnFilter: false, - datatype: "text", - filterMode: "notEquals", - }, - { - accessorKey: "application_date", - header: "تاریخ درخواست", - id: "application_date", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "province", - header: "استان", - id: "province", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "township", - header: "شهرستان", - id: "township", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "city", - header: "شهر", - id: "city", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "county", - header: "بخش", - id: "county", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "village", - header: "روستا", - id: "village", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "land_area", - header: "مساحت زمین", - id: "land_area", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "design_area", - header: "مساحت طرح", - id: "design_area", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "organization", - header: "سازمان", - id: "organization", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "design_group", - header: "گروه طرح", - id: "design_group", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "design_title", - header: "عنوان طرح", - id: "design_title", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "state", - header: "وضعیت درخواست", - id: "state", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - ], - [] - ); - - return ( - <> - - - - - ); -}; -export default TaskList; +"use client"; + +import { useMemo } from "react"; +import { Box } from "@mui/material"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import RowActions from "./RowActions"; + +const TaskList = () => { + const columns = useMemo( + () => [ + { + accessorKey: "id", + header: "کد یکتا", + id: "id", + enableColumnFilter: false, + datatype: "text", + filterMode: "notEquals", + }, + { + accessorKey: "aplication_number", + header: "شماره درخواست", + id: "aplication_number", + enableColumnFilter: false, + datatype: "text", + filterMode: "notEquals", + }, + { + accessorKey: "application_date", + header: "تاریخ درخواست", + id: "application_date", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "province", + header: "استان", + id: "province", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "township", + header: "شهرستان", + id: "township", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "city", + header: "شهر", + id: "city", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "county", + header: "بخش", + id: "county", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "village", + header: "روستا", + id: "village", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "land_area", + header: "مساحت زمین", + id: "land_area", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "design_area", + header: "مساحت طرح", + id: "design_area", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "organization", + header: "سازمان", + id: "organization", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "design_group", + header: "گروه طرح", + id: "design_group", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "design_title", + header: "عنوان طرح", + id: "design_title", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "state", + header: "وضعیت درخواست", + id: "state", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + ], + [] + ); + + return ( + <> + + + + + ); +}; +export default TaskList; diff --git a/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/index.jsx b/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/index.jsx index 6de55e0..a6a53cf 100644 --- a/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/index.jsx +++ b/src/components/dashboard/inquiryPrivacy/assistant/zaminGov/index.jsx @@ -1,15 +1,15 @@ -"use client"; - -import PageTitle from "@/core/components/PageTitle"; -import { Stack } from "@mui/material"; -import TaskList from "./TaskList"; - -const AssistantZaminGovComponent = () => { - return ( - - - - - ); -}; -export default AssistantZaminGovComponent; +"use client"; + +import PageTitle from "@/core/components/PageTitle"; +import { Stack } from "@mui/material"; +import TaskList from "./TaskList"; + +const AssistantZaminGovComponent = () => { + return ( + + + + + ); +}; +export default AssistantZaminGovComponent; diff --git a/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/RowActions/Refer/ReferFormContext.jsx b/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/RowActions/Refer/ReferFormContext.jsx index ea2440e..604e141 100644 --- a/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/RowActions/Refer/ReferFormContext.jsx +++ b/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/RowActions/Refer/ReferFormContext.jsx @@ -1,138 +1,138 @@ -import { - Autocomplete, - Button, - CircularProgress, - DialogActions, - DialogContent, - FormControl, - FormHelperText, - InputLabel, - OutlinedInput, - Stack, - TextField, - Typography, -} from "@mui/material"; -import { Controller, useForm } from "react-hook-form"; -import { yupResolver } from "@hookform/resolvers/yup"; -import { object, string } from "yup"; -import StyledForm from "@/core/components/StyledForm"; -import useCities from "@/lib/hooks/useCities"; -import useRequest from "@/lib/hooks/useRequest"; -import { REFER_ADMIN_CITY } from "@/core/utils/routes"; - -const validationSchema = object({ - description: string().required("وارد کردن توضیحات الزامیست!"), - city: string().required("وارد کردن شهرستان الزامیست!"), -}); - -const ReferFormContext = ({ setOpenReferDialog, rowId, mutate }) => { - const defaultValues = { - description: "", - city: "", - }; - const { cities, loadingCities, errorCities } = useCities(); - const requestServer = useRequest({ notificationSuccess: true }); - const { - control, - register, - handleSubmit, - formState: { isSubmitting, errors, touchedFields }, - } = useForm({ defaultValues, resolver: yupResolver(validationSchema), mode: "all" }); - - const onSubmit = async (data) => { - const formData = new FormData(); - formData.append("description", data.description); - formData.append("cityId", data.city); - requestServer(`${REFER_ADMIN_CITY}/${rowId}`, "post", { - data: formData, - }) - .then(() => { - setOpenReferDialog(false); - mutate(); - }) - .catch(() => {}); - }; - return ( - - - - - - - توضیحات - - - - {errors.description ? errors.description.message : null} - - - - - ( - - - {errorCities ? ( - خطایی در دریافت شهرستان ها رخ داده است! - ) : loadingCities ? ( - - - درحال دریافت لیست شهرستان ها - - ) : ( - city.id === value) || null} - disablePortal - options={cities} - getOptionLabel={(city) => city.name} - isOptionEqualToValue={(option, value) => option.id === value.id} - onChange={(event, newValue) => { - onChange(newValue ? newValue.id : ""); - }} - renderInput={(params) => ( - - )} - /> - )} - - {errors.city ? errors.city.message : null} - - - )} - /> - - - - - - - - - ); -}; -export default ReferFormContext; +import { + Autocomplete, + Button, + CircularProgress, + DialogActions, + DialogContent, + FormControl, + FormHelperText, + InputLabel, + OutlinedInput, + Stack, + TextField, + Typography, +} from "@mui/material"; +import { Controller, useForm } from "react-hook-form"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { object, string } from "yup"; +import StyledForm from "@/core/components/StyledForm"; +import useCities from "@/lib/hooks/useCities"; +import useRequest from "@/lib/hooks/useRequest"; +import { REFER_ADMIN_CITY } from "@/core/utils/routes"; + +const validationSchema = object({ + description: string().required("وارد کردن توضیحات الزامیست!"), + city: string().required("وارد کردن شهرستان الزامیست!"), +}); + +const ReferFormContext = ({ setOpenReferDialog, rowId, mutate }) => { + const defaultValues = { + description: "", + city: "", + }; + const { cities, loadingCities, errorCities } = useCities(); + const requestServer = useRequest({ notificationSuccess: true }); + const { + control, + register, + handleSubmit, + formState: { isSubmitting, errors, touchedFields }, + } = useForm({ defaultValues, resolver: yupResolver(validationSchema), mode: "all" }); + + const onSubmit = async (data) => { + const formData = new FormData(); + formData.append("description", data.description); + formData.append("cityId", data.city); + requestServer(`${REFER_ADMIN_CITY}/${rowId}`, "post", { + data: formData, + }) + .then(() => { + setOpenReferDialog(false); + mutate(); + }) + .catch(() => {}); + }; + return ( + + + + + + + توضیحات + + + + {errors.description ? errors.description.message : null} + + + + + ( + + + {errorCities ? ( + خطایی در دریافت شهرستان ها رخ داده است! + ) : loadingCities ? ( + + + درحال دریافت لیست شهرستان ها + + ) : ( + city.id === value) || null} + disablePortal + options={cities} + getOptionLabel={(city) => city.name} + isOptionEqualToValue={(option, value) => option.id === value.id} + onChange={(event, newValue) => { + onChange(newValue ? newValue.id : ""); + }} + renderInput={(params) => ( + + )} + /> + )} + + {errors.city ? errors.city.message : null} + + + )} + /> + + + + + + + + + ); +}; +export default ReferFormContext; diff --git a/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/RowActions/Refer/index.jsx b/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/RowActions/Refer/index.jsx index 8e77435..a8ebdc2 100644 --- a/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/RowActions/Refer/index.jsx +++ b/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/RowActions/Refer/index.jsx @@ -1,41 +1,41 @@ -import { Dialog, DialogTitle, IconButton, Stack, Tooltip } from "@mui/material"; -import ReplyIcon from "@mui/icons-material/Reply"; -import DialogTransition from "@/core/components/DialogTransition"; -import ReferFormContext from "./ReferFormContext"; -import { useState } from "react"; - -const ReferForm = ({ rowId, mutate }) => { - const [openReferDialog, setOpenReferDialog] = useState(false); - return ( - - - { - setOpenReferDialog(true); - }} - > - - - - - - ارجاع به شهرستان دیگر - - - - - ); -}; -export default ReferForm; +import { Dialog, DialogTitle, IconButton, Stack, Tooltip } from "@mui/material"; +import ReplyIcon from "@mui/icons-material/Reply"; +import DialogTransition from "@/core/components/DialogTransition"; +import ReferFormContext from "./ReferFormContext"; +import { useState } from "react"; + +const ReferForm = ({ rowId, mutate }) => { + const [openReferDialog, setOpenReferDialog] = useState(false); + return ( + + + { + setOpenReferDialog(true); + }} + > + + + + + + ارجاع به شهرستان دیگر + + + + + ); +}; +export default ReferForm; diff --git a/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/RowActions/TaskDetail/DetailDialog.jsx b/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/RowActions/TaskDetail/DetailDialog.jsx index bd2f835..3c25592 100644 --- a/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/RowActions/TaskDetail/DetailDialog.jsx +++ b/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/RowActions/TaskDetail/DetailDialog.jsx @@ -1,109 +1,109 @@ -"use client"; - -import { - Button, - Dialog, - DialogActions, - DialogContent, - FormControl, - FormHelperText, - InputLabel, - OutlinedInput, -} from "@mui/material"; -import { object, string } from "yup"; -import useRequest from "@/lib/hooks/useRequest"; -import { useForm } from "react-hook-form"; -import { yupResolver } from "@hookform/resolvers/yup"; -import StyledForm from "@/core/components/StyledForm"; -import ApplicantRequestDetail from "@/core/components/ApplicantRequestDetail"; - -const fakeData = { - id: 1, - shomareh_darkhast: "2124", - ostan: "ostan", - shahr: "shahr", - shahrestan: "shahrestan", - bakhsh: "bakhsh", - roosta: "roosta", - tarikh_darkhast: "tarikh_darkhast", - sazman: "sazman", - masahat_zamin: "masahat_zamin", - masahat_tarh: "masahat_tarh", - gorooh_tarh: "gorooh_tarh", - onvane_tarh: "onvane_tarh", - address: "کرج - فلان جا - جنب پاساژ - نزدیک اونجا - اونور خیابون - زیر رو گذر - روی زیر گذر", - file_mosavab: "file", - polygon: [ - [51.515, -0.09], - [51.52, -0.1], - [51.52, -0.12], - ], -}; - -const validationSchema = object({ - description: string().required("وارد کردن توضیحات الزامیست!"), -}); - -const DetailDialog = ({ taskModal, setTaskModal, rowId, mutate }) => { - const requestServer = useRequest({ auth: true }); - const defaultValues = { - description: "", - }; - const handleClose = () => { - setTaskModal(false); - }; - - const { - register, - handleSubmit, - formState: { isSubmitting, errors, touchedFields }, - } = useForm({ defaultValues, resolver: yupResolver(validationSchema), mode: "all" }); - - const onSubmit = async (data) => { - const formData = new FormData(); - formData.append("description", data.description); - requestServer(`api-for-send-to-harim/${rowId}`, "post", { - data: formData, - }) - .then(() => { - handleClose(); - mutate(); - }) - .catch(() => {}); - }; - return ( - - - - - - - توضیحات - - - - {errors.description ? errors.description.message : null} - - - - - - - - - ); -}; -export default DetailDialog; +"use client"; + +import { + Button, + Dialog, + DialogActions, + DialogContent, + FormControl, + FormHelperText, + InputLabel, + OutlinedInput, +} from "@mui/material"; +import { object, string } from "yup"; +import useRequest from "@/lib/hooks/useRequest"; +import { useForm } from "react-hook-form"; +import { yupResolver } from "@hookform/resolvers/yup"; +import StyledForm from "@/core/components/StyledForm"; +import ApplicantRequestDetail from "@/core/components/ApplicantRequestDetail"; + +const fakeData = { + id: 1, + shomareh_darkhast: "2124", + ostan: "ostan", + shahr: "shahr", + shahrestan: "shahrestan", + bakhsh: "bakhsh", + roosta: "roosta", + tarikh_darkhast: "tarikh_darkhast", + sazman: "sazman", + masahat_zamin: "masahat_zamin", + masahat_tarh: "masahat_tarh", + gorooh_tarh: "gorooh_tarh", + onvane_tarh: "onvane_tarh", + address: "کرج - فلان جا - جنب پاساژ - نزدیک اونجا - اونور خیابون - زیر رو گذر - روی زیر گذر", + file_mosavab: "file", + polygon: [ + [51.515, -0.09], + [51.52, -0.1], + [51.52, -0.12], + ], +}; + +const validationSchema = object({ + description: string().required("وارد کردن توضیحات الزامیست!"), +}); + +const DetailDialog = ({ taskModal, setTaskModal, rowId, mutate }) => { + const requestServer = useRequest({ auth: true }); + const defaultValues = { + description: "", + }; + const handleClose = () => { + setTaskModal(false); + }; + + const { + register, + handleSubmit, + formState: { isSubmitting, errors, touchedFields }, + } = useForm({ defaultValues, resolver: yupResolver(validationSchema), mode: "all" }); + + const onSubmit = async (data) => { + const formData = new FormData(); + formData.append("description", data.description); + requestServer(`api-for-send-to-harim/${rowId}`, "post", { + data: formData, + }) + .then(() => { + handleClose(); + mutate(); + }) + .catch(() => {}); + }; + return ( + + + + + + + توضیحات + + + + {errors.description ? errors.description.message : null} + + + + + + + + + ); +}; +export default DetailDialog; diff --git a/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/RowActions/TaskDetail/index.jsx b/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/RowActions/TaskDetail/index.jsx index 24f6b31..1641840 100644 --- a/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/RowActions/TaskDetail/index.jsx +++ b/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/RowActions/TaskDetail/index.jsx @@ -1,26 +1,26 @@ -"use client"; - -import { IconButton, Tooltip } from "@mui/material"; -import AssignmentIcon from "@mui/icons-material/Assignment"; -import DetailDialog from "./DetailDialog"; -import { useState } from "react"; - -const TaskDetail = ({ rowId, mutate }) => { - const [taskModal, setTaskModal] = useState(false); - - const openDetailDialog = () => { - setTaskModal(true); - }; - - return ( - <> - - - - - - - - ); -}; -export default TaskDetail; +"use client"; + +import { IconButton, Tooltip } from "@mui/material"; +import AssignmentIcon from "@mui/icons-material/Assignment"; +import DetailDialog from "./DetailDialog"; +import { useState } from "react"; + +const TaskDetail = ({ rowId, mutate }) => { + const [taskModal, setTaskModal] = useState(false); + + const openDetailDialog = () => { + setTaskModal(true); + }; + + return ( + <> + + + + + + + + ); +}; +export default TaskDetail; diff --git a/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/RowActions/index.jsx b/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/RowActions/index.jsx index 0b936c3..2ed70e0 100644 --- a/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/RowActions/index.jsx +++ b/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/RowActions/index.jsx @@ -1,15 +1,15 @@ -"use client"; - -import ReferForm from "./Refer"; -import TaskDetail from "./TaskDetail"; -import { Box } from "@mui/material"; - -const RowActions = ({ row, mutate }) => { - return ( - - - - - ); -}; -export default RowActions; +"use client"; + +import ReferForm from "./Refer"; +import TaskDetail from "./TaskDetail"; +import { Box } from "@mui/material"; + +const RowActions = ({ row, mutate }) => { + return ( + + + + + ); +}; +export default RowActions; diff --git a/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/TaskList.jsx b/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/TaskList.jsx index 6345432..14a0e35 100644 --- a/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/TaskList.jsx +++ b/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/TaskList.jsx @@ -1,145 +1,145 @@ -"use client"; - -import { useMemo } from "react"; -import { Box } from "@mui/material"; -import DataTableWithAuth from "@/core/components/DataTableWithAuth"; -import RowActions from "./RowActions"; - -const TaskList = () => { - const columns = useMemo( - () => [ - { - accessorKey: "id", - header: "کد یکتا", - id: "id", - enableColumnFilter: false, - datatype: "text", - filterMode: "notEquals", - }, - { - accessorKey: "aplication_number", - header: "شماره درخواست", - id: "aplication_number", - enableColumnFilter: false, - datatype: "text", - filterMode: "notEquals", - }, - { - accessorKey: "application_date", - header: "تاریخ درخواست", - id: "application_date", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "province", - header: "استان", - id: "province", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "township", - header: "شهرستان", - id: "township", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "city", - header: "شهر", - id: "city", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "county", - header: "بخش", - id: "county", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "village", - header: "روستا", - id: "village", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "land_area", - header: "مساحت زمین", - id: "land_area", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "design_area", - header: "مساحت طرح", - id: "design_area", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "organization", - header: "سازمان", - id: "organization", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "design_group", - header: "گروه طرح", - id: "design_group", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "design_title", - header: "عنوان طرح", - id: "design_title", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "state", - header: "وضعیت درخواست", - id: "state", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - ], - [] - ); - - return ( - <> - - - - - ); -}; -export default TaskList; +"use client"; + +import { useMemo } from "react"; +import { Box } from "@mui/material"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import RowActions from "./RowActions"; + +const TaskList = () => { + const columns = useMemo( + () => [ + { + accessorKey: "id", + header: "کد یکتا", + id: "id", + enableColumnFilter: false, + datatype: "text", + filterMode: "notEquals", + }, + { + accessorKey: "aplication_number", + header: "شماره درخواست", + id: "aplication_number", + enableColumnFilter: false, + datatype: "text", + filterMode: "notEquals", + }, + { + accessorKey: "application_date", + header: "تاریخ درخواست", + id: "application_date", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "province", + header: "استان", + id: "province", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "township", + header: "شهرستان", + id: "township", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "city", + header: "شهر", + id: "city", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "county", + header: "بخش", + id: "county", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "village", + header: "روستا", + id: "village", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "land_area", + header: "مساحت زمین", + id: "land_area", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "design_area", + header: "مساحت طرح", + id: "design_area", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "organization", + header: "سازمان", + id: "organization", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "design_group", + header: "گروه طرح", + id: "design_group", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "design_title", + header: "عنوان طرح", + id: "design_title", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "state", + header: "وضعیت درخواست", + id: "state", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + ], + [] + ); + + return ( + <> + + + + + ); +}; +export default TaskList; diff --git a/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/index.jsx b/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/index.jsx index 49ba4a2..4af891c 100644 --- a/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/index.jsx +++ b/src/components/dashboard/inquiryPrivacy/cityAdmin/zaminGov/index.jsx @@ -1,14 +1,14 @@ -"use client"; -import PageTitle from "@/core/components/PageTitle"; -import { Stack } from "@mui/material"; -import TaskList from "./TaskList"; - -const CityAdminZaminGovComponent = () => { - return ( - - - - - ); -}; -export default CityAdminZaminGovComponent; +"use client"; +import PageTitle from "@/core/components/PageTitle"; +import { Stack } from "@mui/material"; +import TaskList from "./TaskList"; + +const CityAdminZaminGovComponent = () => { + return ( + + + + + ); +}; +export default CityAdminZaminGovComponent; diff --git a/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/RoadSafetyForm/DescriptionForm.jsx b/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/RoadSafetyForm/DescriptionForm.jsx index 49ffa3c..ba2cdeb 100644 --- a/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/RoadSafetyForm/DescriptionForm.jsx +++ b/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/RoadSafetyForm/DescriptionForm.jsx @@ -1,29 +1,29 @@ -import { FormControl, FormHelperText, InputLabel, OutlinedInput, Stack } from "@mui/material"; - -const DescriptionForm = ({ errors, register }) => { - return ( - - - - توضیحات - - - - {errors.description ? errors.description.message : null} - - - - ); -}; -export default DescriptionForm; +import { FormControl, FormHelperText, InputLabel, OutlinedInput, Stack } from "@mui/material"; + +const DescriptionForm = ({ errors, register }) => { + return ( + + + + توضیحات + + + + {errors.description ? errors.description.message : null} + + + + ); +}; +export default DescriptionForm; diff --git a/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/RoadSafetyForm/ManagerOrAssistantSubmit.jsx b/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/RoadSafetyForm/ManagerOrAssistantSubmit.jsx index a515950..d755b7c 100644 --- a/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/RoadSafetyForm/ManagerOrAssistantSubmit.jsx +++ b/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/RoadSafetyForm/ManagerOrAssistantSubmit.jsx @@ -1,15 +1,15 @@ -import { Button } from "@mui/material"; - -const ManagerOrAssistantSubmit = ({ isSubmitting }) => { - return ( - <> - - - - ); -}; -export default ManagerOrAssistantSubmit; +import { Button } from "@mui/material"; + +const ManagerOrAssistantSubmit = ({ isSubmitting }) => { + return ( + <> + + + + ); +}; +export default ManagerOrAssistantSubmit; diff --git a/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/RoadSafetyForm/PrevCartableOpinion.jsx b/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/RoadSafetyForm/PrevCartableOpinion.jsx index d2587c5..365c1b4 100644 --- a/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/RoadSafetyForm/PrevCartableOpinion.jsx +++ b/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/RoadSafetyForm/PrevCartableOpinion.jsx @@ -1,26 +1,26 @@ -import { Card, CardContent, CardHeader, CircularProgress, Divider, Stack, Typography } from "@mui/material"; -import usePrevStateOpinion from "@/lib/hooks/usePrevStateopinion"; - -const PrevCartableOpinion = ({ message, loadingMessage, errorMessage }) => { - return ( - - - - - {errorMessage ? ( - خطا در دریافت اطلاعات !!! - ) : loadingMessage ? ( - - - درحال دریافت اطلاعات - - ) : ( - {message} - )} - - - - - ); -}; -export default PrevCartableOpinion; +import { Card, CardContent, CardHeader, CircularProgress, Divider, Stack, Typography } from "@mui/material"; +import usePrevStateOpinion from "@/lib/hooks/usePrevStateopinion"; + +const PrevCartableOpinion = ({ message, loadingMessage, errorMessage }) => { + return ( + + + + + {errorMessage ? ( + خطا در دریافت اطلاعات !!! + ) : loadingMessage ? ( + + + درحال دریافت اطلاعات + + ) : ( + {message} + )} + + + + + ); +}; +export default PrevCartableOpinion; diff --git a/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/RoadSafetyForm/QuestionSafetyForm.jsx b/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/RoadSafetyForm/QuestionSafetyForm.jsx index cc9be16..5410d66 100644 --- a/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/RoadSafetyForm/QuestionSafetyForm.jsx +++ b/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/RoadSafetyForm/QuestionSafetyForm.jsx @@ -1,33 +1,33 @@ -import { Card, CardContent, FormControl, FormLabel, Stack, Typography } from "@mui/material"; - -const QuestionSafetyForm = () => { - return ( - - - - - - - آیا ایمنی راه این طرح مورد تایید است ؟ - - - - دفتر حریم راه : - - بله - - - - - - - ); -}; -export default QuestionSafetyForm; +import { Card, CardContent, FormControl, FormLabel, Stack, Typography } from "@mui/material"; + +const QuestionSafetyForm = () => { + return ( + + + + + + + آیا ایمنی راه این طرح مورد تایید است ؟ + + + + دفتر حریم راه : + + بله + + + + + + + ); +}; +export default QuestionSafetyForm; diff --git a/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/RoadSafetyForm/RoadSafetyFormContext.jsx b/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/RoadSafetyForm/RoadSafetyFormContext.jsx index f952d45..68ffecf 100644 --- a/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/RoadSafetyForm/RoadSafetyFormContext.jsx +++ b/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/RoadSafetyForm/RoadSafetyFormContext.jsx @@ -1,82 +1,82 @@ -import { DialogActions, DialogContent, Stack } from "@mui/material"; -import StyledForm from "@/core/components/StyledForm"; -import useRequest from "@/lib/hooks/useRequest"; -import { useForm } from "react-hook-form"; -import { yupResolver } from "@hookform/resolvers/yup"; -import { object, string } from "yup"; -import { SUBMIT_ROAD_SAFETY_FORM } from "@/core/utils/routes"; -import QuestionSafetyForm from "./QuestionSafetyForm"; -import PrevCartableOpinion from "./PrevCartableOpinion"; -import DescriptionForm from "./DescriptionForm"; -import ManagerOrAssistantSubmit from "./ManagerOrAssistantSubmit"; -import usePrevStateOpinion from "@/lib/hooks/usePrevStateopinion"; -import ApplicantRequestDetail from "@/core/components/ApplicantRequestDetail"; -const fakeData = { - id: 1, - shomareh_darkhast: "2124", - ostan: "ostan", - shahr: "shahr", - shahrestan: "shahrestan", - bakhsh: "bakhsh", - roosta: "roosta", - tarikh_darkhast: "tarikh_darkhast", - sazman: "sazman", - masahat_zamin: "masahat_zamin", - masahat_tarh: "masahat_tarh", - gorooh_tarh: "gorooh_tarh", - onvane_tarh: "onvane_tarh", - address: "کرج - فلان جا - جنب پاساژ - نزدیک اونجا - اونور خیابون - زیر رو گذر - روی زیر گذر", - file_mosavab: "file", - polygon: [ - [51.515, -0.09], - [51.52, -0.1], - [51.52, -0.12], - ], -}; -const validationSchema = object({ - description: string().required("وارد کردن توضیحات الزامیست!"), -}); -const RoadSafetyFormContext = ({ rowId, mutate, setOpenRoadSafetyForm }) => { - const defaultValues = { - description: "", - }; - const requestServer = useRequest({ notificationSuccess: true }); - const { message, loadingMessage, errorMessage } = usePrevStateOpinion(); - const { - register, - handleSubmit, - formState: { isSubmitting, errors }, - } = useForm({ defaultValues, resolver: yupResolver(validationSchema), mode: "all" }); - const onSubmit = async (data) => { - const formData = new FormData(); - formData.append("description", data.description); - requestServer(`${SUBMIT_ROAD_SAFETY_FORM}/${rowId}`, "post", { - data: formData, - }) - .then(() => { - setOpenRoadSafetyForm(false); - mutate(); - }) - .catch(() => {}); - }; - return ( - - - - - - - - - - - - - - ); -}; -export default RoadSafetyFormContext; +import { DialogActions, DialogContent, Stack } from "@mui/material"; +import StyledForm from "@/core/components/StyledForm"; +import useRequest from "@/lib/hooks/useRequest"; +import { useForm } from "react-hook-form"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { object, string } from "yup"; +import { SUBMIT_ROAD_SAFETY_FORM } from "@/core/utils/routes"; +import QuestionSafetyForm from "./QuestionSafetyForm"; +import PrevCartableOpinion from "./PrevCartableOpinion"; +import DescriptionForm from "./DescriptionForm"; +import ManagerOrAssistantSubmit from "./ManagerOrAssistantSubmit"; +import usePrevStateOpinion from "@/lib/hooks/usePrevStateopinion"; +import ApplicantRequestDetail from "@/core/components/ApplicantRequestDetail"; +const fakeData = { + id: 1, + shomareh_darkhast: "2124", + ostan: "ostan", + shahr: "shahr", + shahrestan: "shahrestan", + bakhsh: "bakhsh", + roosta: "roosta", + tarikh_darkhast: "tarikh_darkhast", + sazman: "sazman", + masahat_zamin: "masahat_zamin", + masahat_tarh: "masahat_tarh", + gorooh_tarh: "gorooh_tarh", + onvane_tarh: "onvane_tarh", + address: "کرج - فلان جا - جنب پاساژ - نزدیک اونجا - اونور خیابون - زیر رو گذر - روی زیر گذر", + file_mosavab: "file", + polygon: [ + [51.515, -0.09], + [51.52, -0.1], + [51.52, -0.12], + ], +}; +const validationSchema = object({ + description: string().required("وارد کردن توضیحات الزامیست!"), +}); +const RoadSafetyFormContext = ({ rowId, mutate, setOpenRoadSafetyForm }) => { + const defaultValues = { + description: "", + }; + const requestServer = useRequest({ notificationSuccess: true }); + const { message, loadingMessage, errorMessage } = usePrevStateOpinion(); + const { + register, + handleSubmit, + formState: { isSubmitting, errors }, + } = useForm({ defaultValues, resolver: yupResolver(validationSchema), mode: "all" }); + const onSubmit = async (data) => { + const formData = new FormData(); + formData.append("description", data.description); + requestServer(`${SUBMIT_ROAD_SAFETY_FORM}/${rowId}`, "post", { + data: formData, + }) + .then(() => { + setOpenRoadSafetyForm(false); + mutate(); + }) + .catch(() => {}); + }; + return ( + + + + + + + + + + + + + + ); +}; +export default RoadSafetyFormContext; diff --git a/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/RoadSafetyForm/index.jsx b/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/RoadSafetyForm/index.jsx index 9c57473..a4de0d7 100644 --- a/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/RoadSafetyForm/index.jsx +++ b/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/RoadSafetyForm/index.jsx @@ -1,52 +1,52 @@ -import { Dialog, IconButton, Stack, Tooltip } from "@mui/material"; -import EngineeringIcon from "@mui/icons-material/Engineering"; -import DialogTransition from "@/core/components/DialogTransition"; -import { useState } from "react"; -import { Close } from "@mui/icons-material"; -import RoadSafetyFormContext from "./RoadSafetyFormContext"; - -const RoadSafetyForm = ({ rowId, mutate }) => { - const [openRoadSafetyForm, setOpenRoadSafetyForm] = useState(false); - return ( - - - { - setOpenRoadSafetyForm(true); - }} - > - - - - - setOpenRoadSafetyForm(false)} - sx={{ - position: "absolute", - right: 8, - top: 8, - zIndex: 10, - color: (theme) => theme.palette.grey[500], - }} - > - - - - - - ); -}; -export default RoadSafetyForm; +import { Dialog, IconButton, Stack, Tooltip } from "@mui/material"; +import EngineeringIcon from "@mui/icons-material/Engineering"; +import DialogTransition from "@/core/components/DialogTransition"; +import { useState } from "react"; +import { Close } from "@mui/icons-material"; +import RoadSafetyFormContext from "./RoadSafetyFormContext"; + +const RoadSafetyForm = ({ rowId, mutate }) => { + const [openRoadSafetyForm, setOpenRoadSafetyForm] = useState(false); + return ( + + + { + setOpenRoadSafetyForm(true); + }} + > + + + + + setOpenRoadSafetyForm(false)} + sx={{ + position: "absolute", + right: 8, + top: 8, + zIndex: 10, + color: (theme) => theme.palette.grey[500], + }} + > + + + + + + ); +}; +export default RoadSafetyForm; diff --git a/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/TaskDetail/DetailDialog.jsx b/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/TaskDetail/DetailDialog.jsx index 7b50738..777eecf 100644 --- a/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/TaskDetail/DetailDialog.jsx +++ b/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/TaskDetail/DetailDialog.jsx @@ -1,75 +1,75 @@ -"use client"; - -import { Dialog, DialogContent } from "@mui/material"; -import { object, string } from "yup"; -import useRequest from "@/lib/hooks/useRequest"; -import { useForm } from "react-hook-form"; -import { yupResolver } from "@hookform/resolvers/yup"; -import StyledForm from "@/core/components/StyledForm"; -import ApplicantRequestDetail from "@/core/components/ApplicantRequestDetail"; - -const fakeData = { - id: 1, - shomareh_darkhast: "2124", - ostan: "ostan", - shahr: "shahr", - shahrestan: "shahrestan", - bakhsh: "bakhsh", - roosta: "roosta", - tarikh_darkhast: "tarikh_darkhast", - sazman: "sazman", - masahat_zamin: "masahat_zamin", - masahat_tarh: "masahat_tarh", - gorooh_tarh: "gorooh_tarh", - onvane_tarh: "onvane_tarh", - address: "کرج - فلان جا - جنب پاساژ - نزدیک اونجا - اونور خیابون - زیر رو گذر - روی زیر گذر", - file_mosavab: "file", - polygon: [ - [51.515, -0.09], - [51.52, -0.1], - [51.52, -0.12], - ], -}; - -const validationSchema = object({ - description: string().required("وارد کردن توضیحات الزامیست!"), -}); - -const DetailDialog = ({ taskModal, setTaskModal, rowId, mutate }) => { - const requestServer = useRequest({ auth: true }); - const defaultValues = { - description: "", - }; - const handleClose = () => { - setTaskModal(false); - }; - - const { - register, - handleSubmit, - formState: { isSubmitting, errors, touchedFields }, - } = useForm({ defaultValues, resolver: yupResolver(validationSchema), mode: "all" }); - - const onSubmit = async (data) => { - const formData = new FormData(); - formData.append("description", data.description); - requestServer(`api-for-send-to-harim/${rowId}`, "post", { - data: formData, - }) - .then(() => { - handleClose(); - mutate(); - }) - .catch(() => {}); - }; - return ( - - - - - - - - ); -}; -export default DetailDialog; +"use client"; + +import { Dialog, DialogContent } from "@mui/material"; +import { object, string } from "yup"; +import useRequest from "@/lib/hooks/useRequest"; +import { useForm } from "react-hook-form"; +import { yupResolver } from "@hookform/resolvers/yup"; +import StyledForm from "@/core/components/StyledForm"; +import ApplicantRequestDetail from "@/core/components/ApplicantRequestDetail"; + +const fakeData = { + id: 1, + shomareh_darkhast: "2124", + ostan: "ostan", + shahr: "shahr", + shahrestan: "shahrestan", + bakhsh: "bakhsh", + roosta: "roosta", + tarikh_darkhast: "tarikh_darkhast", + sazman: "sazman", + masahat_zamin: "masahat_zamin", + masahat_tarh: "masahat_tarh", + gorooh_tarh: "gorooh_tarh", + onvane_tarh: "onvane_tarh", + address: "کرج - فلان جا - جنب پاساژ - نزدیک اونجا - اونور خیابون - زیر رو گذر - روی زیر گذر", + file_mosavab: "file", + polygon: [ + [51.515, -0.09], + [51.52, -0.1], + [51.52, -0.12], + ], +}; + +const validationSchema = object({ + description: string().required("وارد کردن توضیحات الزامیست!"), +}); + +const DetailDialog = ({ taskModal, setTaskModal, rowId, mutate }) => { + const requestServer = useRequest({ auth: true }); + const defaultValues = { + description: "", + }; + const handleClose = () => { + setTaskModal(false); + }; + + const { + register, + handleSubmit, + formState: { isSubmitting, errors, touchedFields }, + } = useForm({ defaultValues, resolver: yupResolver(validationSchema), mode: "all" }); + + const onSubmit = async (data) => { + const formData = new FormData(); + formData.append("description", data.description); + requestServer(`api-for-send-to-harim/${rowId}`, "post", { + data: formData, + }) + .then(() => { + handleClose(); + mutate(); + }) + .catch(() => {}); + }; + return ( + + + + + + + + ); +}; +export default DetailDialog; diff --git a/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/TaskDetail/index.jsx b/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/TaskDetail/index.jsx index 24f6b31..1641840 100644 --- a/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/TaskDetail/index.jsx +++ b/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/TaskDetail/index.jsx @@ -1,26 +1,26 @@ -"use client"; - -import { IconButton, Tooltip } from "@mui/material"; -import AssignmentIcon from "@mui/icons-material/Assignment"; -import DetailDialog from "./DetailDialog"; -import { useState } from "react"; - -const TaskDetail = ({ rowId, mutate }) => { - const [taskModal, setTaskModal] = useState(false); - - const openDetailDialog = () => { - setTaskModal(true); - }; - - return ( - <> - - - - - - - - ); -}; -export default TaskDetail; +"use client"; + +import { IconButton, Tooltip } from "@mui/material"; +import AssignmentIcon from "@mui/icons-material/Assignment"; +import DetailDialog from "./DetailDialog"; +import { useState } from "react"; + +const TaskDetail = ({ rowId, mutate }) => { + const [taskModal, setTaskModal] = useState(false); + + const openDetailDialog = () => { + setTaskModal(true); + }; + + return ( + <> + + + + + + + + ); +}; +export default TaskDetail; diff --git a/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/index.jsx b/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/index.jsx index b7434f8..ae4213c 100644 --- a/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/index.jsx +++ b/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/RowActions/index.jsx @@ -1,13 +1,13 @@ -import TaskDetail from "./TaskDetail"; -import { Box } from "@mui/material"; -import RoadSafetyForm from "./RoadSafetyForm"; - -const RowActions = ({ row, mutate }) => { - return ( - - - - - ); -}; -export default RowActions; +import TaskDetail from "./TaskDetail"; +import { Box } from "@mui/material"; +import RoadSafetyForm from "./RoadSafetyForm"; + +const RowActions = ({ row, mutate }) => { + return ( + + + + + ); +}; +export default RowActions; diff --git a/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/TaskList.jsx b/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/TaskList.jsx index dcb9084..cb0bd3d 100644 --- a/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/TaskList.jsx +++ b/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/TaskList.jsx @@ -1,145 +1,145 @@ -"use client"; - -import { useMemo } from "react"; -import { Box } from "@mui/material"; -import DataTableWithAuth from "@/core/components/DataTableWithAuth"; -import RowActions from "./RowActions"; - -const TaskList = () => { - const columns = useMemo( - () => [ - { - accessorKey: "id", - header: "کد یکتا", - id: "id", - enableColumnFilter: false, - datatype: "text", - filterMode: "notEquals", - }, - { - accessorKey: "aplication_number", - header: "شماره درخواست", - id: "aplication_number", - enableColumnFilter: false, - datatype: "text", - filterMode: "notEquals", - }, - { - accessorKey: "application_date", - header: "تاریخ درخواست", - id: "application_date", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "province", - header: "استان", - id: "province", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "township", - header: "شهرستان", - id: "township", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "city", - header: "شهر", - id: "city", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "county", - header: "بخش", - id: "county", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "village", - header: "روستا", - id: "village", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "land_area", - header: "مساحت زمین", - id: "land_area", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "design_area", - header: "مساحت طرح", - id: "design_area", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "organization", - header: "سازمان", - id: "organization", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "design_group", - header: "گروه طرح", - id: "design_group", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "design_title", - header: "عنوان طرح", - id: "design_title", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "state", - header: "وضعیت درخواست", - id: "state", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - ], - [] - ); - - return ( - <> - - - - - ); -}; -export default TaskList; +"use client"; + +import { useMemo } from "react"; +import { Box } from "@mui/material"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import RowActions from "./RowActions"; + +const TaskList = () => { + const columns = useMemo( + () => [ + { + accessorKey: "id", + header: "کد یکتا", + id: "id", + enableColumnFilter: false, + datatype: "text", + filterMode: "notEquals", + }, + { + accessorKey: "aplication_number", + header: "شماره درخواست", + id: "aplication_number", + enableColumnFilter: false, + datatype: "text", + filterMode: "notEquals", + }, + { + accessorKey: "application_date", + header: "تاریخ درخواست", + id: "application_date", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "province", + header: "استان", + id: "province", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "township", + header: "شهرستان", + id: "township", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "city", + header: "شهر", + id: "city", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "county", + header: "بخش", + id: "county", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "village", + header: "روستا", + id: "village", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "land_area", + header: "مساحت زمین", + id: "land_area", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "design_area", + header: "مساحت طرح", + id: "design_area", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "organization", + header: "سازمان", + id: "organization", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "design_group", + header: "گروه طرح", + id: "design_group", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "design_title", + header: "عنوان طرح", + id: "design_title", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "state", + header: "وضعیت درخواست", + id: "state", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + ], + [] + ); + + return ( + <> + + + + + ); +}; +export default TaskList; diff --git a/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/index.jsx b/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/index.jsx index f348745..ef66f17 100644 --- a/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/index.jsx +++ b/src/components/dashboard/inquiryPrivacy/generalManager/zaminGov/index.jsx @@ -1,15 +1,15 @@ -"use client"; - -import PageTitle from "@/core/components/PageTitle"; -import { Stack } from "@mui/material"; -import TaskList from "./TaskList"; - -const GeneralManagerZaminGovComponent = () => { - return ( - - - - - ); -}; -export default GeneralManagerZaminGovComponent; +"use client"; + +import PageTitle from "@/core/components/PageTitle"; +import { Stack } from "@mui/material"; +import TaskList from "./TaskList"; + +const GeneralManagerZaminGovComponent = () => { + return ( + + + + + ); +}; +export default GeneralManagerZaminGovComponent; diff --git a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/MapModify/MapActionButtons.jsx b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/MapModify/MapActionButtons.jsx index 0476d00..600372d 100644 --- a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/MapModify/MapActionButtons.jsx +++ b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/MapModify/MapActionButtons.jsx @@ -1,100 +1,100 @@ -import { Box, Button, ButtonGroup } from "@mui/material"; -import AutoModeIcon from "@mui/icons-material/AutoMode"; -import DeleteIcon from "@mui/icons-material/Delete"; -import EditLocationAltIcon from "@mui/icons-material/EditLocationAlt"; -import SaveIcon from "@mui/icons-material/Save"; -import CancelIcon from "@mui/icons-material/Cancel"; - -const MapActionButtons = ({ - disableToCreate, - disableToEditAndDelete, - disableToSaveAndCancel, - onDraw, - onEdit, - onRemove, - onSave, - onCancel, -}) => ( - <> - - - - - - - - - - - - - -); - -export default MapActionButtons; +import { Box, Button, ButtonGroup } from "@mui/material"; +import AutoModeIcon from "@mui/icons-material/AutoMode"; +import DeleteIcon from "@mui/icons-material/Delete"; +import EditLocationAltIcon from "@mui/icons-material/EditLocationAlt"; +import SaveIcon from "@mui/icons-material/Save"; +import CancelIcon from "@mui/icons-material/Cancel"; + +const MapActionButtons = ({ + disableToCreate, + disableToEditAndDelete, + disableToSaveAndCancel, + onDraw, + onEdit, + onRemove, + onSave, + onCancel, +}) => ( + <> + + + + + + + + + + + + + +); + +export default MapActionButtons; diff --git a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/MapModify/MapModifyDialog.jsx b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/MapModify/MapModifyDialog.jsx index 463b607..218cce5 100644 --- a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/MapModify/MapModifyDialog.jsx +++ b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/MapModify/MapModifyDialog.jsx @@ -1,96 +1,96 @@ -"use client"; - -import { - Box, - Button, - Chip, - Dialog, - DialogActions, - DialogContent, - Divider, - FormControl, - FormControlLabel, - FormLabel, - Radio, - RadioGroup, - Typography, -} from "@mui/material"; -import dynamic from "next/dynamic"; -import MapLoading from "@/core/components/MapLayer/Loading"; -import "leaflet-draw/dist/leaflet.draw.css"; -import GppMaybeIcon from "@mui/icons-material/GppMaybe"; -import PolygonForDesign from "./PolygonForDesign"; - -const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { - loading: () => , - ssr: false, -}); - -const MapModifyDialog = ({ mapModifyModal, setMapModifyModal }) => { - const handleClose = () => { - setMapModifyModal(false); - }; - - return ( - - - - - - - - - - - - - - نکته: اصلاح ننمودن طرح به منزله تایید طرح میباشد. - - - - - - آیا طرح نیاز به ایجاد راه دسترسی دارد؟ - - - } label="بله" /> - } label="خیر" /> - - - - - - - - - - ); -}; - -export default MapModifyDialog; +"use client"; + +import { + Box, + Button, + Chip, + Dialog, + DialogActions, + DialogContent, + Divider, + FormControl, + FormControlLabel, + FormLabel, + Radio, + RadioGroup, + Typography, +} from "@mui/material"; +import dynamic from "next/dynamic"; +import MapLoading from "@/core/components/MapLayer/Loading"; +import "leaflet-draw/dist/leaflet.draw.css"; +import GppMaybeIcon from "@mui/icons-material/GppMaybe"; +import PolygonForDesign from "./PolygonForDesign"; + +const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { + loading: () => , + ssr: false, +}); + +const MapModifyDialog = ({ mapModifyModal, setMapModifyModal }) => { + const handleClose = () => { + setMapModifyModal(false); + }; + + return ( + + + + + + + + + + + + + + نکته: اصلاح ننمودن طرح به منزله تایید طرح میباشد. + + + + + + آیا طرح نیاز به ایجاد راه دسترسی دارد؟ + + + } label="بله" /> + } label="خیر" /> + + + + + + + + + + ); +}; + +export default MapModifyDialog; diff --git a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/MapModify/PolygonForDesign.jsx b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/MapModify/PolygonForDesign.jsx index 4e1bb43..f765e41 100644 --- a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/MapModify/PolygonForDesign.jsx +++ b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/MapModify/PolygonForDesign.jsx @@ -1,115 +1,115 @@ -"use client"; - -import { FeatureGroup, useMap } from "react-leaflet"; -import { EditControl } from "react-leaflet-draw"; -import { useEffect, useRef, useState } from "react"; -import MapActionButtons from "./MapActionButtons"; - -const PolygonForDesign = () => { - const map = useMap(); - const editableFG = useRef(null); - const [polygonLayer, setPolygonLayer] = useState(null); - const [disableToCreate, setDisableToCreate] = useState(false); - const [disableToEditAndDelete, setDisableToEditAndDelete] = useState(true); - const [disableToSaveAndCancel, setDisableToSaveAndCancel] = useState(true); - const [editToolbar, setEditToolbar] = useState(null); - - useEffect(() => { - const { L } = window; - L.drawLocal.draw.handlers.polygon.tooltip = { - start: "برای شروع کشیدن پلیگان، کلیک کنید.", - cont: "گوشه های دیگر پلیگان را نیز انتخاب کنید.", - end: "برای اتمام رسم پلیگان، نقطه آخر را به اول متصل نمایید.", - }; - L.drawLocal.edit.handlers.edit.tooltip = { - text: "برای ذخیر یا لغو تغییرات، از دکمه های بالا سمت چپ استفاده نمایید.", - subtext: "نقاط مشخص شده را گرفته و برای ویرایش جابجا نمایید.", - }; - }, []); - - const handleDrawPolygon = () => { - const { L } = window; - const drawControl = new L.Draw.Polygon(map); - drawControl.enable(); - setDisableToCreate(true); - }; - - const handleEditPolygon = () => { - const { L } = window; - if (editableFG.current && polygonLayer) { - const editControlInstance = new L.EditToolbar.Edit(map, { - featureGroup: editableFG.current, - }); - editControlInstance.enable(); - setEditToolbar(editControlInstance); - setDisableToEditAndDelete(true); - setDisableToSaveAndCancel(false); - } - }; - - const handleRemovePolygon = () => { - if (polygonLayer && editableFG.current) { - editableFG.current.removeLayer(polygonLayer); - setPolygonLayer(null); - setDisableToEditAndDelete(true); - setDisableToCreate(false); - } - }; - - const handleSavePolygon = () => { - if (editToolbar) { - editToolbar.save(); - editToolbar.disable(); - setDisableToEditAndDelete(false); - setDisableToSaveAndCancel(true); - } - }; - - const handleCancelEdit = () => { - if (editToolbar) { - editToolbar.revertLayers(); - editToolbar.disable(); - setDisableToEditAndDelete(false); - setDisableToSaveAndCancel(true); - } - }; - - const handlePolygonCreate = (e) => { - const layer = e.layer; - setPolygonLayer(layer); - editableFG.current.addLayer(layer); - setDisableToEditAndDelete(false); - }; - - return ( - <> - - - - - - ); -}; - -export default PolygonForDesign; +"use client"; + +import { FeatureGroup, useMap } from "react-leaflet"; +import { EditControl } from "react-leaflet-draw"; +import { useEffect, useRef, useState } from "react"; +import MapActionButtons from "./MapActionButtons"; + +const PolygonForDesign = () => { + const map = useMap(); + const editableFG = useRef(null); + const [polygonLayer, setPolygonLayer] = useState(null); + const [disableToCreate, setDisableToCreate] = useState(false); + const [disableToEditAndDelete, setDisableToEditAndDelete] = useState(true); + const [disableToSaveAndCancel, setDisableToSaveAndCancel] = useState(true); + const [editToolbar, setEditToolbar] = useState(null); + + useEffect(() => { + const { L } = window; + L.drawLocal.draw.handlers.polygon.tooltip = { + start: "برای شروع کشیدن پلیگان، کلیک کنید.", + cont: "گوشه های دیگر پلیگان را نیز انتخاب کنید.", + end: "برای اتمام رسم پلیگان، نقطه آخر را به اول متصل نمایید.", + }; + L.drawLocal.edit.handlers.edit.tooltip = { + text: "برای ذخیر یا لغو تغییرات، از دکمه های بالا سمت چپ استفاده نمایید.", + subtext: "نقاط مشخص شده را گرفته و برای ویرایش جابجا نمایید.", + }; + }, []); + + const handleDrawPolygon = () => { + const { L } = window; + const drawControl = new L.Draw.Polygon(map); + drawControl.enable(); + setDisableToCreate(true); + }; + + const handleEditPolygon = () => { + const { L } = window; + if (editableFG.current && polygonLayer) { + const editControlInstance = new L.EditToolbar.Edit(map, { + featureGroup: editableFG.current, + }); + editControlInstance.enable(); + setEditToolbar(editControlInstance); + setDisableToEditAndDelete(true); + setDisableToSaveAndCancel(false); + } + }; + + const handleRemovePolygon = () => { + if (polygonLayer && editableFG.current) { + editableFG.current.removeLayer(polygonLayer); + setPolygonLayer(null); + setDisableToEditAndDelete(true); + setDisableToCreate(false); + } + }; + + const handleSavePolygon = () => { + if (editToolbar) { + editToolbar.save(); + editToolbar.disable(); + setDisableToEditAndDelete(false); + setDisableToSaveAndCancel(true); + } + }; + + const handleCancelEdit = () => { + if (editToolbar) { + editToolbar.revertLayers(); + editToolbar.disable(); + setDisableToEditAndDelete(false); + setDisableToSaveAndCancel(true); + } + }; + + const handlePolygonCreate = (e) => { + const layer = e.layer; + setPolygonLayer(layer); + editableFG.current.addLayer(layer); + setDisableToEditAndDelete(false); + }; + + return ( + <> + + + + + + ); +}; + +export default PolygonForDesign; diff --git a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/MapModify/index.jsx b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/MapModify/index.jsx index 9349557..970f93c 100644 --- a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/MapModify/index.jsx +++ b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/MapModify/index.jsx @@ -1,29 +1,29 @@ -import { IconButton, Tooltip } from "@mui/material"; -import MapIcon from "@mui/icons-material/Map"; -import { useState } from "react"; -import MapModifyDialog from "./MapModifyDialog"; - -const MapModify = ({ rowId, mutate }) => { - const [mapModifyModal, setMapModifyModal] = useState(false); - - const openMapModifyDialog = () => { - setMapModifyModal(true); - }; - - return ( - <> - - - - - - - - ); -}; -export default MapModify; +import { IconButton, Tooltip } from "@mui/material"; +import MapIcon from "@mui/icons-material/Map"; +import { useState } from "react"; +import MapModifyDialog from "./MapModifyDialog"; + +const MapModify = ({ rowId, mutate }) => { + const [mapModifyModal, setMapModifyModal] = useState(false); + + const openMapModifyDialog = () => { + setMapModifyModal(true); + }; + + return ( + <> + + + + + + + + ); +}; +export default MapModify; diff --git a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/Refer/ReferFormContext.jsx b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/Refer/ReferFormContext.jsx index 5a6b1e8..221e411 100644 --- a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/Refer/ReferFormContext.jsx +++ b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/Refer/ReferFormContext.jsx @@ -1,139 +1,139 @@ -import { - Autocomplete, - Button, - CircularProgress, - DialogActions, - DialogContent, - FormControl, - FormHelperText, - InputLabel, - OutlinedInput, - Stack, - TextField, - Typography, -} from "@mui/material"; -import { Controller, useForm } from "react-hook-form"; -import { yupResolver } from "@hookform/resolvers/yup"; -import { object, string } from "yup"; -import StyledForm from "@/core/components/StyledForm"; -import useProvinces from "@/lib/hooks/useProvince"; -import useRequest from "@/lib/hooks/useRequest"; -import { REFER_ADMIN_PROVINCE } from "@/core/utils/routes"; - -const validationSchema = object({ - description: string().required("وارد کردن توضیحات الزامیست!"), - province: string().required("وارد کردن استان الزامیست!"), -}); - -const ReferFormContext = ({ setOpenReferDialog, rowId, mutate }) => { - const defaultValues = { - description: "", - province: "", - }; - const { provinces, loadingProvinces, errorProvinces } = useProvinces(); - const requestServer = useRequest({ notificationSuccess: true }); - const { - control, - register, - handleSubmit, - formState: { isSubmitting, errors, touchedFields }, - } = useForm({ defaultValues, resolver: yupResolver(validationSchema), mode: "all" }); - - const onSubmit = async (data) => { - const formData = new FormData(); - formData.append("description", data.description); - formData.append("provinceId", data.province); - - requestServer(`${REFER_ADMIN_PROVINCE}/${rowId}`, "post", { - data: formData, - }) - .then(() => { - setOpenReferDialog(false); - mutate(); - }) - .catch(() => {}); - }; - return ( - - - - - - - توضیحات - - - - {errors.description ? errors.description.message : null} - - - - - ( - - - {errorProvinces ? ( - خطایی در دریافت استان ها رخ داده است! - ) : loadingProvinces ? ( - - - درحال دریافت لیست استان ها - - ) : ( - province.id === value) || null} - disablePortal - options={provinces} - getOptionLabel={(province) => province.name_fa} - isOptionEqualToValue={(option, value) => option.id === value.id} - onChange={(event, newValue) => { - onChange(newValue ? newValue.id : ""); - }} - renderInput={(params) => ( - - )} - /> - )} - - {errors.province ? errors.province.message : null} - - - )} - /> - - - - - - - - - ); -}; -export default ReferFormContext; +import { + Autocomplete, + Button, + CircularProgress, + DialogActions, + DialogContent, + FormControl, + FormHelperText, + InputLabel, + OutlinedInput, + Stack, + TextField, + Typography, +} from "@mui/material"; +import { Controller, useForm } from "react-hook-form"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { object, string } from "yup"; +import StyledForm from "@/core/components/StyledForm"; +import useProvinces from "@/lib/hooks/useProvince"; +import useRequest from "@/lib/hooks/useRequest"; +import { REFER_ADMIN_PROVINCE } from "@/core/utils/routes"; + +const validationSchema = object({ + description: string().required("وارد کردن توضیحات الزامیست!"), + province: string().required("وارد کردن استان الزامیست!"), +}); + +const ReferFormContext = ({ setOpenReferDialog, rowId, mutate }) => { + const defaultValues = { + description: "", + province: "", + }; + const { provinces, loadingProvinces, errorProvinces } = useProvinces(); + const requestServer = useRequest({ notificationSuccess: true }); + const { + control, + register, + handleSubmit, + formState: { isSubmitting, errors, touchedFields }, + } = useForm({ defaultValues, resolver: yupResolver(validationSchema), mode: "all" }); + + const onSubmit = async (data) => { + const formData = new FormData(); + formData.append("description", data.description); + formData.append("provinceId", data.province); + + requestServer(`${REFER_ADMIN_PROVINCE}/${rowId}`, "post", { + data: formData, + }) + .then(() => { + setOpenReferDialog(false); + mutate(); + }) + .catch(() => {}); + }; + return ( + + + + + + + توضیحات + + + + {errors.description ? errors.description.message : null} + + + + + ( + + + {errorProvinces ? ( + خطایی در دریافت استان ها رخ داده است! + ) : loadingProvinces ? ( + + + درحال دریافت لیست استان ها + + ) : ( + province.id === value) || null} + disablePortal + options={provinces} + getOptionLabel={(province) => province.name_fa} + isOptionEqualToValue={(option, value) => option.id === value.id} + onChange={(event, newValue) => { + onChange(newValue ? newValue.id : ""); + }} + renderInput={(params) => ( + + )} + /> + )} + + {errors.province ? errors.province.message : null} + + + )} + /> + + + + + + + + + ); +}; +export default ReferFormContext; diff --git a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/Refer/index.jsx b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/Refer/index.jsx index c3a3012..ee76b95 100644 --- a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/Refer/index.jsx +++ b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/Refer/index.jsx @@ -1,41 +1,41 @@ -import { Dialog, DialogTitle, IconButton, Stack, Tooltip } from "@mui/material"; -import ReplyIcon from "@mui/icons-material/Reply"; -import DialogTransition from "@/core/components/DialogTransition"; -import { useState } from "react"; -import ReferFormContext from "./ReferFormContext"; - -const ReferForm = ({ rowId, mutate }) => { - const [openReferDialog, setOpenReferDialog] = useState(false); - return ( - - - { - setOpenReferDialog(true); - }} - > - - - - - - ارجاع به استان دیگر - - - - - ); -}; -export default ReferForm; +import { Dialog, DialogTitle, IconButton, Stack, Tooltip } from "@mui/material"; +import ReplyIcon from "@mui/icons-material/Reply"; +import DialogTransition from "@/core/components/DialogTransition"; +import { useState } from "react"; +import ReferFormContext from "./ReferFormContext"; + +const ReferForm = ({ rowId, mutate }) => { + const [openReferDialog, setOpenReferDialog] = useState(false); + return ( + + + { + setOpenReferDialog(true); + }} + > + + + + + + ارجاع به استان دیگر + + + + + ); +}; +export default ReferForm; diff --git a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/RoadSafetyForm/DescriptionForm.jsx b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/RoadSafetyForm/DescriptionForm.jsx index 49ffa3c..ba2cdeb 100644 --- a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/RoadSafetyForm/DescriptionForm.jsx +++ b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/RoadSafetyForm/DescriptionForm.jsx @@ -1,29 +1,29 @@ -import { FormControl, FormHelperText, InputLabel, OutlinedInput, Stack } from "@mui/material"; - -const DescriptionForm = ({ errors, register }) => { - return ( - - - - توضیحات - - - - {errors.description ? errors.description.message : null} - - - - ); -}; -export default DescriptionForm; +import { FormControl, FormHelperText, InputLabel, OutlinedInput, Stack } from "@mui/material"; + +const DescriptionForm = ({ errors, register }) => { + return ( + + + + توضیحات + + + + {errors.description ? errors.description.message : null} + + + + ); +}; +export default DescriptionForm; diff --git a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/RoadSafetyForm/PrevCartableOpinion.jsx b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/RoadSafetyForm/PrevCartableOpinion.jsx index 8d14fd0..74f9b45 100644 --- a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/RoadSafetyForm/PrevCartableOpinion.jsx +++ b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/RoadSafetyForm/PrevCartableOpinion.jsx @@ -1,27 +1,27 @@ -import { Card, CardContent, CardHeader, CircularProgress, Divider, Stack, Typography } from "@mui/material"; -import usePrevStateOpinion from "@/lib/hooks/usePrevStateopinion"; - -const PrevCartableOpinion = () => { - const { message, loadingMessage, errorMessage } = usePrevStateOpinion(); - return ( - - - - - {errorMessage ? ( - خطا در دریافت اطلاعات !!! - ) : loadingMessage ? ( - - - درحال دریافت اطلاعات - - ) : ( - {message} - )} - - - - - ); -}; -export default PrevCartableOpinion; +import { Card, CardContent, CardHeader, CircularProgress, Divider, Stack, Typography } from "@mui/material"; +import usePrevStateOpinion from "@/lib/hooks/usePrevStateopinion"; + +const PrevCartableOpinion = () => { + const { message, loadingMessage, errorMessage } = usePrevStateOpinion(); + return ( + + + + + {errorMessage ? ( + خطا در دریافت اطلاعات !!! + ) : loadingMessage ? ( + + + درحال دریافت اطلاعات + + ) : ( + {message} + )} + + + + + ); +}; +export default PrevCartableOpinion; diff --git a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/RoadSafetyForm/QuestionSafetyForm.jsx b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/RoadSafetyForm/QuestionSafetyForm.jsx index 4c5faae..ef005b8 100644 --- a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/RoadSafetyForm/QuestionSafetyForm.jsx +++ b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/RoadSafetyForm/QuestionSafetyForm.jsx @@ -1,57 +1,57 @@ -import { - Card, - CardContent, - FormControl, - FormControlLabel, - FormLabel, - RadioGroup, - Stack, - Typography, -} from "@mui/material"; -import Radio from "@mui/material/Radio"; - -const QuestionSafetyForm = ({ register, errors }) => { - return ( - - - - - - - آیا ایمنی راه این طرح مورد تایید است ؟ - - - - - } - label="بله" - {...register("RadioGroup")} - /> - } - label="خیر" - {...register("RadioGroup")} - /> - - - {errors.RadioGroup && ( - - {errors.RadioGroup.message} - - )} - - - - - ); -}; -export default QuestionSafetyForm; +import { + Card, + CardContent, + FormControl, + FormControlLabel, + FormLabel, + RadioGroup, + Stack, + Typography, +} from "@mui/material"; +import Radio from "@mui/material/Radio"; + +const QuestionSafetyForm = ({ register, errors }) => { + return ( + + + + + + + آیا ایمنی راه این طرح مورد تایید است ؟ + + + + + } + label="بله" + {...register("RadioGroup")} + /> + } + label="خیر" + {...register("RadioGroup")} + /> + + + {errors.RadioGroup && ( + + {errors.RadioGroup.message} + + )} + + + + + ); +}; +export default QuestionSafetyForm; diff --git a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/RoadSafetyForm/RoadSaftyFormContext.jsx b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/RoadSafetyForm/RoadSaftyFormContext.jsx index 353fe19..8be0c6c 100644 --- a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/RoadSafetyForm/RoadSaftyFormContext.jsx +++ b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/RoadSafetyForm/RoadSaftyFormContext.jsx @@ -1,80 +1,80 @@ -import { DialogActions, DialogContent, Stack } from "@mui/material"; -import StyledForm from "@/core/components/StyledForm"; -import useRequest from "@/lib/hooks/useRequest"; -import { useForm } from "react-hook-form"; -import { yupResolver } from "@hookform/resolvers/yup"; -import { object, string } from "yup"; -import QuestionSafetyForm from "./QuestionSafetyForm"; -import PrevCartableOpinion from "./PrevCartableOpinion"; -import DescriptionForm from "./DescriptionForm"; -import SubmitButtonsAdmin from "./SubmitButtonsAdmin"; -import { SUBMIT_ROAD_SAFETY_FORM } from "@/core/utils/routes"; -import ApplicantRequestDetail from "@/core/components/ApplicantRequestDetail"; -const fakeData = { - id: 1, - shomareh_darkhast: "2124", - ostan: "ostan", - shahr: "shahr", - shahrestan: "shahrestan", - bakhsh: "bakhsh", - roosta: "roosta", - tarikh_darkhast: "tarikh_darkhast", - sazman: "sazman", - masahat_zamin: "masahat_zamin", - masahat_tarh: "masahat_tarh", - gorooh_tarh: "gorooh_tarh", - onvane_tarh: "onvane_tarh", - address: "کرج - فلان جا - جنب پاساژ - نزدیک اونجا - اونور خیابون - زیر رو گذر - روی زیر گذر", - file_mosavab: "file", - polygon: [ - [51.515, -0.09], - [51.52, -0.1], - [51.52, -0.12], - ], -}; -const validationSchema = object({ - description: string().required("وارد کردن توضیحات الزامیست!"), - RadioGroup: string().required("تاییدیه ایمنی راه ضروریست!"), -}); -const RoadSafetyFormContext = ({ rowId, mutate, setOpenRoadSafetyForm }) => { - const defaultValues = { - description: "", - RadioGroup: "", - }; - const requestServer = useRequest({ notificationSuccess: true }); - const { - register, - handleSubmit, - formState: { isSubmitting, errors }, - } = useForm({ defaultValues, resolver: yupResolver(validationSchema), mode: "all" }); - const onSubmit = async (data) => { - const formData = new FormData(); - formData.append("description", data.description); - formData.append("provinceId", data.RadioGroup); - - requestServer(`${SUBMIT_ROAD_SAFETY_FORM}/${rowId}`, "post", { - data: formData, - }) - .then(() => { - setOpenRoadSafetyForm(false); - mutate(); - }) - .catch(() => {}); - }; - return ( - - - - - - - - - - - - - - ); -}; -export default RoadSafetyFormContext; +import { DialogActions, DialogContent, Stack } from "@mui/material"; +import StyledForm from "@/core/components/StyledForm"; +import useRequest from "@/lib/hooks/useRequest"; +import { useForm } from "react-hook-form"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { object, string } from "yup"; +import QuestionSafetyForm from "./QuestionSafetyForm"; +import PrevCartableOpinion from "./PrevCartableOpinion"; +import DescriptionForm from "./DescriptionForm"; +import SubmitButtonsAdmin from "./SubmitButtonsAdmin"; +import { SUBMIT_ROAD_SAFETY_FORM } from "@/core/utils/routes"; +import ApplicantRequestDetail from "@/core/components/ApplicantRequestDetail"; +const fakeData = { + id: 1, + shomareh_darkhast: "2124", + ostan: "ostan", + shahr: "shahr", + shahrestan: "shahrestan", + bakhsh: "bakhsh", + roosta: "roosta", + tarikh_darkhast: "tarikh_darkhast", + sazman: "sazman", + masahat_zamin: "masahat_zamin", + masahat_tarh: "masahat_tarh", + gorooh_tarh: "gorooh_tarh", + onvane_tarh: "onvane_tarh", + address: "کرج - فلان جا - جنب پاساژ - نزدیک اونجا - اونور خیابون - زیر رو گذر - روی زیر گذر", + file_mosavab: "file", + polygon: [ + [51.515, -0.09], + [51.52, -0.1], + [51.52, -0.12], + ], +}; +const validationSchema = object({ + description: string().required("وارد کردن توضیحات الزامیست!"), + RadioGroup: string().required("تاییدیه ایمنی راه ضروریست!"), +}); +const RoadSafetyFormContext = ({ rowId, mutate, setOpenRoadSafetyForm }) => { + const defaultValues = { + description: "", + RadioGroup: "", + }; + const requestServer = useRequest({ notificationSuccess: true }); + const { + register, + handleSubmit, + formState: { isSubmitting, errors }, + } = useForm({ defaultValues, resolver: yupResolver(validationSchema), mode: "all" }); + const onSubmit = async (data) => { + const formData = new FormData(); + formData.append("description", data.description); + formData.append("provinceId", data.RadioGroup); + + requestServer(`${SUBMIT_ROAD_SAFETY_FORM}/${rowId}`, "post", { + data: formData, + }) + .then(() => { + setOpenRoadSafetyForm(false); + mutate(); + }) + .catch(() => {}); + }; + return ( + + + + + + + + + + + + + + ); +}; +export default RoadSafetyFormContext; diff --git a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/RoadSafetyForm/SubmitButtonsAdmin.jsx b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/RoadSafetyForm/SubmitButtonsAdmin.jsx index 6b46447..611457f 100644 --- a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/RoadSafetyForm/SubmitButtonsAdmin.jsx +++ b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/RoadSafetyForm/SubmitButtonsAdmin.jsx @@ -1,21 +1,21 @@ -import { Button } from "@mui/material"; - -const SubmitButtonsAdmin = ({ setOpenRoadSafetyForm, isSubmitting }) => { - return ( - <> - - - - ); -}; -export default SubmitButtonsAdmin; +import { Button } from "@mui/material"; + +const SubmitButtonsAdmin = ({ setOpenRoadSafetyForm, isSubmitting }) => { + return ( + <> + + + + ); +}; +export default SubmitButtonsAdmin; diff --git a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/RoadSafetyForm/index.jsx b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/RoadSafetyForm/index.jsx index 652e809..9787ef5 100644 --- a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/RoadSafetyForm/index.jsx +++ b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/RoadSafetyForm/index.jsx @@ -1,52 +1,52 @@ -import { Dialog, IconButton, Stack, Tooltip } from "@mui/material"; -import EngineeringIcon from "@mui/icons-material/Engineering"; -import DialogTransition from "@/core/components/DialogTransition"; -import { useState } from "react"; -import RoadSafetyFormContext from "./RoadSaftyFormContext"; -import { Close } from "@mui/icons-material"; - -const RoadSafetyForm = ({ rowId, mutate }) => { - const [openRoadSafetyForm, setOpenRoadSafetyForm] = useState(false); - return ( - - - { - setOpenRoadSafetyForm(true); - }} - > - - - - - setOpenRoadSafetyForm(false)} - sx={{ - position: "absolute", - right: 8, - top: 8, - zIndex: 10, - color: (theme) => theme.palette.grey[500], - }} - > - - - - - - ); -}; -export default RoadSafetyForm; +import { Dialog, IconButton, Stack, Tooltip } from "@mui/material"; +import EngineeringIcon from "@mui/icons-material/Engineering"; +import DialogTransition from "@/core/components/DialogTransition"; +import { useState } from "react"; +import RoadSafetyFormContext from "./RoadSaftyFormContext"; +import { Close } from "@mui/icons-material"; + +const RoadSafetyForm = ({ rowId, mutate }) => { + const [openRoadSafetyForm, setOpenRoadSafetyForm] = useState(false); + return ( + + + { + setOpenRoadSafetyForm(true); + }} + > + + + + + setOpenRoadSafetyForm(false)} + sx={{ + position: "absolute", + right: 8, + top: 8, + zIndex: 10, + color: (theme) => theme.palette.grey[500], + }} + > + + + + + + ); +}; +export default RoadSafetyForm; diff --git a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/TaskDetail/DetailDialog.jsx b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/TaskDetail/DetailDialog.jsx index 7b50738..777eecf 100644 --- a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/TaskDetail/DetailDialog.jsx +++ b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/TaskDetail/DetailDialog.jsx @@ -1,75 +1,75 @@ -"use client"; - -import { Dialog, DialogContent } from "@mui/material"; -import { object, string } from "yup"; -import useRequest from "@/lib/hooks/useRequest"; -import { useForm } from "react-hook-form"; -import { yupResolver } from "@hookform/resolvers/yup"; -import StyledForm from "@/core/components/StyledForm"; -import ApplicantRequestDetail from "@/core/components/ApplicantRequestDetail"; - -const fakeData = { - id: 1, - shomareh_darkhast: "2124", - ostan: "ostan", - shahr: "shahr", - shahrestan: "shahrestan", - bakhsh: "bakhsh", - roosta: "roosta", - tarikh_darkhast: "tarikh_darkhast", - sazman: "sazman", - masahat_zamin: "masahat_zamin", - masahat_tarh: "masahat_tarh", - gorooh_tarh: "gorooh_tarh", - onvane_tarh: "onvane_tarh", - address: "کرج - فلان جا - جنب پاساژ - نزدیک اونجا - اونور خیابون - زیر رو گذر - روی زیر گذر", - file_mosavab: "file", - polygon: [ - [51.515, -0.09], - [51.52, -0.1], - [51.52, -0.12], - ], -}; - -const validationSchema = object({ - description: string().required("وارد کردن توضیحات الزامیست!"), -}); - -const DetailDialog = ({ taskModal, setTaskModal, rowId, mutate }) => { - const requestServer = useRequest({ auth: true }); - const defaultValues = { - description: "", - }; - const handleClose = () => { - setTaskModal(false); - }; - - const { - register, - handleSubmit, - formState: { isSubmitting, errors, touchedFields }, - } = useForm({ defaultValues, resolver: yupResolver(validationSchema), mode: "all" }); - - const onSubmit = async (data) => { - const formData = new FormData(); - formData.append("description", data.description); - requestServer(`api-for-send-to-harim/${rowId}`, "post", { - data: formData, - }) - .then(() => { - handleClose(); - mutate(); - }) - .catch(() => {}); - }; - return ( - - - - - - - - ); -}; -export default DetailDialog; +"use client"; + +import { Dialog, DialogContent } from "@mui/material"; +import { object, string } from "yup"; +import useRequest from "@/lib/hooks/useRequest"; +import { useForm } from "react-hook-form"; +import { yupResolver } from "@hookform/resolvers/yup"; +import StyledForm from "@/core/components/StyledForm"; +import ApplicantRequestDetail from "@/core/components/ApplicantRequestDetail"; + +const fakeData = { + id: 1, + shomareh_darkhast: "2124", + ostan: "ostan", + shahr: "shahr", + shahrestan: "shahrestan", + bakhsh: "bakhsh", + roosta: "roosta", + tarikh_darkhast: "tarikh_darkhast", + sazman: "sazman", + masahat_zamin: "masahat_zamin", + masahat_tarh: "masahat_tarh", + gorooh_tarh: "gorooh_tarh", + onvane_tarh: "onvane_tarh", + address: "کرج - فلان جا - جنب پاساژ - نزدیک اونجا - اونور خیابون - زیر رو گذر - روی زیر گذر", + file_mosavab: "file", + polygon: [ + [51.515, -0.09], + [51.52, -0.1], + [51.52, -0.12], + ], +}; + +const validationSchema = object({ + description: string().required("وارد کردن توضیحات الزامیست!"), +}); + +const DetailDialog = ({ taskModal, setTaskModal, rowId, mutate }) => { + const requestServer = useRequest({ auth: true }); + const defaultValues = { + description: "", + }; + const handleClose = () => { + setTaskModal(false); + }; + + const { + register, + handleSubmit, + formState: { isSubmitting, errors, touchedFields }, + } = useForm({ defaultValues, resolver: yupResolver(validationSchema), mode: "all" }); + + const onSubmit = async (data) => { + const formData = new FormData(); + formData.append("description", data.description); + requestServer(`api-for-send-to-harim/${rowId}`, "post", { + data: formData, + }) + .then(() => { + handleClose(); + mutate(); + }) + .catch(() => {}); + }; + return ( + + + + + + + + ); +}; +export default DetailDialog; diff --git a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/TaskDetail/index.jsx b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/TaskDetail/index.jsx index 24f6b31..1641840 100644 --- a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/TaskDetail/index.jsx +++ b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/TaskDetail/index.jsx @@ -1,26 +1,26 @@ -"use client"; - -import { IconButton, Tooltip } from "@mui/material"; -import AssignmentIcon from "@mui/icons-material/Assignment"; -import DetailDialog from "./DetailDialog"; -import { useState } from "react"; - -const TaskDetail = ({ rowId, mutate }) => { - const [taskModal, setTaskModal] = useState(false); - - const openDetailDialog = () => { - setTaskModal(true); - }; - - return ( - <> - - - - - - - - ); -}; -export default TaskDetail; +"use client"; + +import { IconButton, Tooltip } from "@mui/material"; +import AssignmentIcon from "@mui/icons-material/Assignment"; +import DetailDialog from "./DetailDialog"; +import { useState } from "react"; + +const TaskDetail = ({ rowId, mutate }) => { + const [taskModal, setTaskModal] = useState(false); + + const openDetailDialog = () => { + setTaskModal(true); + }; + + return ( + <> + + + + + + + + ); +}; +export default TaskDetail; diff --git a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/index.jsx b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/index.jsx index e6c9e51..2d324bc 100644 --- a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/index.jsx +++ b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/RowActions/index.jsx @@ -1,17 +1,17 @@ -import ReferForm from "./Refer"; -import TaskDetail from "./TaskDetail"; -import { Box } from "@mui/material"; -import RoadSafetyForm from "./RoadSafetyForm"; -import MapModify from "./MapModify"; - -const RowActions = ({ row, mutate }) => { - return ( - - - - - - - ); -}; -export default RowActions; +import ReferForm from "./Refer"; +import TaskDetail from "./TaskDetail"; +import { Box } from "@mui/material"; +import RoadSafetyForm from "./RoadSafetyForm"; +import MapModify from "./MapModify"; + +const RowActions = ({ row, mutate }) => { + return ( + + + + + + + ); +}; +export default RowActions; diff --git a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/TaskList.jsx b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/TaskList.jsx index d059812..188c1d6 100644 --- a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/TaskList.jsx +++ b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/TaskList.jsx @@ -1,145 +1,145 @@ -"use client"; - -import { useMemo } from "react"; -import { Box } from "@mui/material"; -import DataTableWithAuth from "@/core/components/DataTableWithAuth"; -import RowActions from "./RowActions"; - -const TaskList = () => { - const columns = useMemo( - () => [ - { - accessorKey: "id", - header: "کد یکتا", - id: "id", - enableColumnFilter: false, - datatype: "text", - filterMode: "notEquals", - }, - { - accessorKey: "aplication_number", - header: "شماره درخواست", - id: "aplication_number", - enableColumnFilter: false, - datatype: "text", - filterMode: "notEquals", - }, - { - accessorKey: "application_date", - header: "تاریخ درخواست", - id: "application_date", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "province", - header: "استان", - id: "province", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "township", - header: "شهرستان", - id: "township", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "city", - header: "شهر", - id: "city", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "county", - header: "بخش", - id: "county", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "village", - header: "روستا", - id: "village", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "land_area", - header: "مساحت زمین", - id: "land_area", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "design_area", - header: "مساحت طرح", - id: "design_area", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "organization", - header: "سازمان", - id: "organization", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "design_group", - header: "گروه طرح", - id: "design_group", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "design_title", - header: "عنوان طرح", - id: "design_title", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - { - accessorKey: "state", - header: "وضعیت درخواست", - id: "state", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - }, - ], - [] - ); - - return ( - <> - - - - - ); -}; -export default TaskList; +"use client"; + +import { useMemo } from "react"; +import { Box } from "@mui/material"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import RowActions from "./RowActions"; + +const TaskList = () => { + const columns = useMemo( + () => [ + { + accessorKey: "id", + header: "کد یکتا", + id: "id", + enableColumnFilter: false, + datatype: "text", + filterMode: "notEquals", + }, + { + accessorKey: "aplication_number", + header: "شماره درخواست", + id: "aplication_number", + enableColumnFilter: false, + datatype: "text", + filterMode: "notEquals", + }, + { + accessorKey: "application_date", + header: "تاریخ درخواست", + id: "application_date", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "province", + header: "استان", + id: "province", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "township", + header: "شهرستان", + id: "township", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "city", + header: "شهر", + id: "city", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "county", + header: "بخش", + id: "county", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "village", + header: "روستا", + id: "village", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "land_area", + header: "مساحت زمین", + id: "land_area", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "design_area", + header: "مساحت طرح", + id: "design_area", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "organization", + header: "سازمان", + id: "organization", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "design_group", + header: "گروه طرح", + id: "design_group", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "design_title", + header: "عنوان طرح", + id: "design_title", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + { + accessorKey: "state", + header: "وضعیت درخواست", + id: "state", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + }, + ], + [] + ); + + return ( + <> + + + + + ); +}; +export default TaskList; diff --git a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/index.jsx b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/index.jsx index a8609f8..936d610 100644 --- a/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/index.jsx +++ b/src/components/dashboard/inquiryPrivacy/provinceAdmin/zaminGov/index.jsx @@ -1,15 +1,15 @@ -"use client"; - -import PageTitle from "@/core/components/PageTitle"; -import { Stack } from "@mui/material"; -import TaskList from "./TaskList"; - -const ProvinceAdminZaminGovComponent = () => { - return ( - - - - - ); -}; -export default ProvinceAdminZaminGovComponent; +"use client"; + +import PageTitle from "@/core/components/PageTitle"; +import { Stack } from "@mui/material"; +import TaskList from "./TaskList"; + +const ProvinceAdminZaminGovComponent = () => { + return ( + + + + + ); +}; +export default ProvinceAdminZaminGovComponent; diff --git a/src/components/dashboard/permissionTable/Actions/Create/Form/CreateFormContent.jsx b/src/components/dashboard/permissionTable/Actions/Create/Form/CreateFormContent.jsx index dd9fede..771d647 100644 --- a/src/components/dashboard/permissionTable/Actions/Create/Form/CreateFormContent.jsx +++ b/src/components/dashboard/permissionTable/Actions/Create/Form/CreateFormContent.jsx @@ -1,218 +1,218 @@ -import StyledForm from "@/core/components/StyledForm"; -import { yupResolver } from "@hookform/resolvers/yup"; -import { Beenhere, ExitToApp } from "@mui/icons-material"; -import { - Button, - DialogActions, - DialogContent, - Grid, - Stack, - TextField, - FormControlLabel, - Checkbox, -} from "@mui/material"; -import { Controller, useForm } from "react-hook-form"; -import { object, string } from "yup"; -import PersianTextField from "@/core/components/PersianTextField"; - -const validationSchema = object({ - name: string().required("وارد کردن نام انگلیسی الزامیست!"), - name_fa: string().required("وارد کردن نام فارسی الزامیست!"), - type: string().required("وارد کردن گروه (انگلیسی) الزامیست!"), - type_fa: string().required("وارد کردن گروه (فارسی) الزامیست!"), -}); - -const CreateFormContent = ({ setOpen, defaultValues, onSubmitBase }) => { - const { - control, - handleSubmit, - formState: { isSubmitting, errors }, - } = useForm({ - defaultValues, - resolver: yupResolver(validationSchema), - mode: "all", - }); - const handleOnSubmit = async (data) => { - await onSubmitBase(data); - }; - - return ( - <> - - - - - - - ( - - )} - /> - - - ( - - )} - /> - - - - - - - ( - - )} - /> - - - ( - - )} - /> - - - - - - - ( - - )} - /> - - - - - - - ( - - } - label="دسترسی استانی" - /> - )} - /> - - - ( - - } - label="دسترسی اداره شهری" - /> - )} - /> - - - - - - - - - - - - ); -}; -export default CreateFormContent; +import StyledForm from "@/core/components/StyledForm"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { Beenhere, ExitToApp } from "@mui/icons-material"; +import { + Button, + DialogActions, + DialogContent, + Grid, + Stack, + TextField, + FormControlLabel, + Checkbox, +} from "@mui/material"; +import { Controller, useForm } from "react-hook-form"; +import { object, string } from "yup"; +import PersianTextField from "@/core/components/PersianTextField"; + +const validationSchema = object({ + name: string().required("وارد کردن نام انگلیسی الزامیست!"), + name_fa: string().required("وارد کردن نام فارسی الزامیست!"), + type: string().required("وارد کردن گروه (انگلیسی) الزامیست!"), + type_fa: string().required("وارد کردن گروه (فارسی) الزامیست!"), +}); + +const CreateFormContent = ({ setOpen, defaultValues, onSubmitBase }) => { + const { + control, + handleSubmit, + formState: { isSubmitting, errors }, + } = useForm({ + defaultValues, + resolver: yupResolver(validationSchema), + mode: "all", + }); + const handleOnSubmit = async (data) => { + await onSubmitBase(data); + }; + + return ( + <> + + + + + + + ( + + )} + /> + + + ( + + )} + /> + + + + + + + ( + + )} + /> + + + ( + + )} + /> + + + + + + + ( + + )} + /> + + + + + + + ( + + } + label="دسترسی استانی" + /> + )} + /> + + + ( + + } + label="دسترسی اداره شهری" + /> + )} + /> + + + + + + + + + + + + ); +}; +export default CreateFormContent; diff --git a/src/components/dashboard/permissionTable/Actions/Create/Form/index.jsx b/src/components/dashboard/permissionTable/Actions/Create/Form/index.jsx index 2c01835..7ea6f20 100644 --- a/src/components/dashboard/permissionTable/Actions/Create/Form/index.jsx +++ b/src/components/dashboard/permissionTable/Actions/Create/Form/index.jsx @@ -1,66 +1,66 @@ -import { Dialog, DialogTitle, IconButton } from "@mui/material"; -import CreateFormContent from "./CreateFormContent"; -import CloseIcon from "@mui/icons-material/Close"; -import useRequest from "@/lib/hooks/useRequest"; -import { CREATE_PERMISSION } from "@/core/utils/routes"; -import { DialogHeader } from "next/dist/client/components/react-dev-overlay/internal/components/Dialog"; - -const CreateForm = ({ open, setOpen, mutate }) => { - const requestServer = useRequest({ notificationSuccess: true }); - const defaultValues = { - name: "", - name_fa: "", - description: "", - type: "", - type_fa: "", - need_province: false, - need_edare_shahri: false, - }; - const onSubmit = async (result) => { - const formData = new FormData(); - formData.append("name", result.name); - formData.append("name_fa", result.name_fa); - formData.append("description", result.description); - formData.append("type", result.type); - formData.append("type_fa", result.type_fa); - formData.append("need_province", result.need_province ? 1 : 0); - formData.append("need_edare_shahri", result.need_edare_shahri ? 1 : 0); - await requestServer(CREATE_PERMISSION, "post", { - data: formData, - }) - .then(() => { - mutate(); - setOpen(false); - }) - .catch(() => {}); - }; - return ( - - setOpen(false)} - sx={(theme) => ({ - position: "absolute", - right: 8, - top: 8, - zIndex: 50, - color: theme.palette.grey[500], - })} - > - - - - ثبت سطح دسترسی جدید - - {open && ( - - )} - - ); -}; -export default CreateForm; +import { Dialog, DialogTitle, IconButton } from "@mui/material"; +import CreateFormContent from "./CreateFormContent"; +import CloseIcon from "@mui/icons-material/Close"; +import useRequest from "@/lib/hooks/useRequest"; +import { CREATE_PERMISSION } from "@/core/utils/routes"; +import { DialogHeader } from "next/dist/client/components/react-dev-overlay/internal/components/Dialog"; + +const CreateForm = ({ open, setOpen, mutate }) => { + const requestServer = useRequest({ notificationSuccess: true }); + const defaultValues = { + name: "", + name_fa: "", + description: "", + type: "", + type_fa: "", + need_province: false, + need_edare_shahri: false, + }; + const onSubmit = async (result) => { + const formData = new FormData(); + formData.append("name", result.name); + formData.append("name_fa", result.name_fa); + formData.append("description", result.description); + formData.append("type", result.type); + formData.append("type_fa", result.type_fa); + formData.append("need_province", result.need_province ? 1 : 0); + formData.append("need_edare_shahri", result.need_edare_shahri ? 1 : 0); + await requestServer(CREATE_PERMISSION, "post", { + data: formData, + }) + .then(() => { + mutate(); + setOpen(false); + }) + .catch(() => {}); + }; + return ( + + setOpen(false)} + sx={(theme) => ({ + position: "absolute", + right: 8, + top: 8, + zIndex: 50, + color: theme.palette.grey[500], + })} + > + + + + ثبت سطح دسترسی جدید + + {open && ( + + )} + + ); +}; +export default CreateForm; diff --git a/src/components/dashboard/permissionTable/Actions/Create/index.jsx b/src/components/dashboard/permissionTable/Actions/Create/index.jsx index c558a8b..9faef9c 100644 --- a/src/components/dashboard/permissionTable/Actions/Create/index.jsx +++ b/src/components/dashboard/permissionTable/Actions/Create/index.jsx @@ -1,36 +1,36 @@ -import { AddCircle } from "@mui/icons-material"; -import { Button, IconButton, useMediaQuery, useTheme } from "@mui/material"; -import CreateForm from "./Form"; -import { useState } from "react"; - -const CreatePermission = ({ mutate }) => { - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const [open, setOpen] = useState(false); - - const handleOpen = () => { - setOpen(true); - }; - - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - - - ); -}; -export default CreatePermission; +import { AddCircle } from "@mui/icons-material"; +import { Button, IconButton, useMediaQuery, useTheme } from "@mui/material"; +import CreateForm from "./Form"; +import { useState } from "react"; + +const CreatePermission = ({ mutate }) => { + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const [open, setOpen] = useState(false); + + const handleOpen = () => { + setOpen(true); + }; + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + + + ); +}; +export default CreatePermission; diff --git a/src/components/dashboard/permissionTable/Actions/Edit/EditController.jsx b/src/components/dashboard/permissionTable/Actions/Edit/EditController.jsx index d2baab2..221d008 100644 --- a/src/components/dashboard/permissionTable/Actions/Edit/EditController.jsx +++ b/src/components/dashboard/permissionTable/Actions/Edit/EditController.jsx @@ -1,46 +1,46 @@ -import useRequest from "@/lib/hooks/useRequest"; -import CreateFormContent from "../Create/Form/CreateFormContent"; -import { UPDATE_PERMISSION } from "@/core/utils/routes"; -import { DialogTitle } from "@mui/material"; -import { DialogHeader } from "next/dist/client/components/react-dev-overlay/internal/components/Dialog"; - -const EditController = ({ rowId, mutate, setOpen, row }) => { - const requestServer = useRequest({ notificationSuccess: true }); - - const defaultData = { - name: row.original?.name || "", - name_fa: row.original?.name_fa || "", - description: row.original?.description || "", - type: row.original?.type || "", - type_fa: row.original?.type_fa || "", - need_province: row.original?.need_province || false, - need_edare_shahri: row.original?.need_edare_shahri || false, - }; - const handleSubmit = async (result) => { - const formData = new FormData(); - formData.append("name", result.name); - formData.append("name_fa", result.name_fa); - formData.append("description", result.description); - formData.append("type", result.type); - formData.append("type_fa", result.type_fa); - formData.append("need_province", result.need_province ? 1 : 0); - formData.append("need_edare_shahri", result.need_edare_shahri ? 1 : 0); - await requestServer(`${UPDATE_PERMISSION}/${rowId}`, "post", { - data: formData, - }) - .then(() => { - mutate(); - setOpen(false); - }) - .catch(() => {}); - }; - return ( - <> - - ویرایش سطح دسترسی - - - - ); -}; -export default EditController; +import useRequest from "@/lib/hooks/useRequest"; +import CreateFormContent from "../Create/Form/CreateFormContent"; +import { UPDATE_PERMISSION } from "@/core/utils/routes"; +import { DialogTitle } from "@mui/material"; +import { DialogHeader } from "next/dist/client/components/react-dev-overlay/internal/components/Dialog"; + +const EditController = ({ rowId, mutate, setOpen, row }) => { + const requestServer = useRequest({ notificationSuccess: true }); + + const defaultData = { + name: row.original?.name || "", + name_fa: row.original?.name_fa || "", + description: row.original?.description || "", + type: row.original?.type || "", + type_fa: row.original?.type_fa || "", + need_province: row.original?.need_province || false, + need_edare_shahri: row.original?.need_edare_shahri || false, + }; + const handleSubmit = async (result) => { + const formData = new FormData(); + formData.append("name", result.name); + formData.append("name_fa", result.name_fa); + formData.append("description", result.description); + formData.append("type", result.type); + formData.append("type_fa", result.type_fa); + formData.append("need_province", result.need_province ? 1 : 0); + formData.append("need_edare_shahri", result.need_edare_shahri ? 1 : 0); + await requestServer(`${UPDATE_PERMISSION}/${rowId}`, "post", { + data: formData, + }) + .then(() => { + mutate(); + setOpen(false); + }) + .catch(() => {}); + }; + return ( + <> + + ویرایش سطح دسترسی + + + + ); +}; +export default EditController; diff --git a/src/components/dashboard/permissionTable/Actions/Edit/index.jsx b/src/components/dashboard/permissionTable/Actions/Edit/index.jsx index b7d98a9..5c8e760 100644 --- a/src/components/dashboard/permissionTable/Actions/Edit/index.jsx +++ b/src/components/dashboard/permissionTable/Actions/Edit/index.jsx @@ -1,51 +1,51 @@ -import { useState } from "react"; -import { Dialog, IconButton, Tooltip } from "@mui/material"; -import BorderColorIcon from "@mui/icons-material/BorderColor"; -import CloseIcon from "@mui/icons-material/Close"; -import EditController from "./EditController"; - -const EditPermission = ({ mutate, row, rowId }) => { - const [open, setOpen] = useState(false); - - return ( - <> - - { - setOpen(true); - }} - > - - - - - setOpen(false)} - sx={(theme) => ({ - position: "absolute", - right: 8, - top: 8, - zIndex: 50, - color: theme.palette.grey[500], - })} - > - - - {open && } - - - ); -}; -export default EditPermission; +import { useState } from "react"; +import { Dialog, IconButton, Tooltip } from "@mui/material"; +import BorderColorIcon from "@mui/icons-material/BorderColor"; +import CloseIcon from "@mui/icons-material/Close"; +import EditController from "./EditController"; + +const EditPermission = ({ mutate, row, rowId }) => { + const [open, setOpen] = useState(false); + + return ( + <> + + { + setOpen(true); + }} + > + + + + + setOpen(false)} + sx={(theme) => ({ + position: "absolute", + right: 8, + top: 8, + zIndex: 50, + color: theme.palette.grey[500], + })} + > + + + {open && } + + + ); +}; +export default EditPermission; diff --git a/src/components/dashboard/permissionTable/PermissionList.jsx b/src/components/dashboard/permissionTable/PermissionList.jsx index 05f53af..16c6ec0 100644 --- a/src/components/dashboard/permissionTable/PermissionList.jsx +++ b/src/components/dashboard/permissionTable/PermissionList.jsx @@ -1,157 +1,157 @@ -"use client"; -import DataTableWithAuth from "@/core/components/DataTableWithAuth"; -import { GET_PERMISSION_TABLE_LIST } from "@/core/utils/routes"; -import { Box, Stack, Typography } from "@mui/material"; -import { useMemo } from "react"; -import Toolbar from "./Toolbar"; -import RowActions from "./RowActions"; -import moment from "jalali-moment"; -import DoneIcon from "@mui/icons-material/Done"; -import ClearIcon from "@mui/icons-material/Clear"; - -const PermissionList = () => { - const columns = useMemo( - () => [ - { - accessorKey: "id", - header: "کد یکتا", - id: "id", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorKey: "type", - header: "گروه (انگلیسی)", - id: "type", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorKey: "type_fa", - header: "گروه (فارسی)", - id: "type_fa", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorKey: "name", - header: "نام انگلیسی", - id: "name", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorKey: "name_fa", - header: "نام فارسی", - id: "name_fa", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorKey: "need_province", - header: "دسترسی استانی", - id: "need_province", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - Cell: ({ renderedCellValue }) => ( - <> - {renderedCellValue === 1 ? ( - - - - ) : ( - - - - )} - - ), - }, - { - accessorKey: "need_edare_shahri", - header: "دسترسی اداره شهری", - id: "need_edare_shahri", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - Cell: ({ renderedCellValue }) => ( - <> - {renderedCellValue === 1 ? ( - - - - ) : ( - - - - )} - - ), - }, - { - accessorFn: (row) => { - const date = row.created_at ? new Date(row.created_at) : null; - return date ? moment(date).locale("fa").format("HH:mm | jYYYY/jMM/jDD") : "-"; - }, - header: "تاریخ ثبت", - id: "created_at", - enableColumnFilter: true, - datatype: "date", - filterMode: "between", - grow: false, - size: 100, - }, - ], - [] - ); - - return ( - <> - - - - - ); -}; -export default PermissionList; +"use client"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import { GET_PERMISSION_TABLE_LIST } from "@/core/utils/routes"; +import { Box, Stack, Typography } from "@mui/material"; +import { useMemo } from "react"; +import Toolbar from "./Toolbar"; +import RowActions from "./RowActions"; +import moment from "jalali-moment"; +import DoneIcon from "@mui/icons-material/Done"; +import ClearIcon from "@mui/icons-material/Clear"; + +const PermissionList = () => { + const columns = useMemo( + () => [ + { + accessorKey: "id", + header: "کد یکتا", + id: "id", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "type", + header: "گروه (انگلیسی)", + id: "type", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "type_fa", + header: "گروه (فارسی)", + id: "type_fa", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "name", + header: "نام انگلیسی", + id: "name", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "name_fa", + header: "نام فارسی", + id: "name_fa", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "need_province", + header: "دسترسی استانی", + id: "need_province", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + Cell: ({ renderedCellValue }) => ( + <> + {renderedCellValue === 1 ? ( + + + + ) : ( + + + + )} + + ), + }, + { + accessorKey: "need_edare_shahri", + header: "دسترسی اداره شهری", + id: "need_edare_shahri", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + Cell: ({ renderedCellValue }) => ( + <> + {renderedCellValue === 1 ? ( + + + + ) : ( + + + + )} + + ), + }, + { + accessorFn: (row) => { + const date = row.created_at ? new Date(row.created_at) : null; + return date ? moment(date).locale("fa").format("HH:mm | jYYYY/jMM/jDD") : "-"; + }, + header: "تاریخ ثبت", + id: "created_at", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + ], + [] + ); + + return ( + <> + + + + + ); +}; +export default PermissionList; diff --git a/src/components/dashboard/permissionTable/RowActions/DeleteDialog/DeleteContent.jsx b/src/components/dashboard/permissionTable/RowActions/DeleteDialog/DeleteContent.jsx index 2bf7bc1..e9bcc0b 100644 --- a/src/components/dashboard/permissionTable/RowActions/DeleteDialog/DeleteContent.jsx +++ b/src/components/dashboard/permissionTable/RowActions/DeleteDialog/DeleteContent.jsx @@ -1,39 +1,39 @@ -import { Button, DialogActions, DialogContent, Stack, Typography } from "@mui/material"; -import React, { useState } from "react"; -import useRequest from "@/lib/hooks/useRequest"; -import { DELETE_PERMISSION } from "@/core/utils/routes"; - -const DeleteContent = ({ rowId, mutate, setOpenDeleteDialog }) => { - const [submitting, setSubmitting] = useState(false); - const requestServer = useRequest({ notificationSuccess: true }); - const handleClick = () => { - setSubmitting(true); - requestServer(`${DELETE_PERMISSION}/${rowId}`, "delete") - .then(() => { - mutate(); - setSubmitting(false); - setOpenDeleteDialog(false); - }) - .catch(() => { - setSubmitting(false); - }); - }; - return ( - <> - - - آیا از حذف سطح دسترسی اطمینان دارید؟ - - - - - - - - ); -}; -export default DeleteContent; +import { Button, DialogActions, DialogContent, Stack, Typography } from "@mui/material"; +import React, { useState } from "react"; +import useRequest from "@/lib/hooks/useRequest"; +import { DELETE_PERMISSION } from "@/core/utils/routes"; + +const DeleteContent = ({ rowId, mutate, setOpenDeleteDialog }) => { + const [submitting, setSubmitting] = useState(false); + const requestServer = useRequest({ notificationSuccess: true }); + const handleClick = () => { + setSubmitting(true); + requestServer(`${DELETE_PERMISSION}/${rowId}`, "delete") + .then(() => { + mutate(); + setSubmitting(false); + setOpenDeleteDialog(false); + }) + .catch(() => { + setSubmitting(false); + }); + }; + return ( + <> + + + آیا از حذف سطح دسترسی اطمینان دارید؟ + + + + + + + + ); +}; +export default DeleteContent; diff --git a/src/components/dashboard/permissionTable/RowActions/DeleteDialog/index.jsx b/src/components/dashboard/permissionTable/RowActions/DeleteDialog/index.jsx index 2578e2a..64cd3cc 100644 --- a/src/components/dashboard/permissionTable/RowActions/DeleteDialog/index.jsx +++ b/src/components/dashboard/permissionTable/RowActions/DeleteDialog/index.jsx @@ -1,34 +1,34 @@ -import DeleteIcon from "@mui/icons-material/Delete"; -import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import DeleteContent from "./DeleteContent"; -const DeleteDialog = ({ rowId, mutate }) => { - const [openDeleteDialog, setOpenDeleteDialog] = useState(false); - - return ( - <> - - setOpenDeleteDialog(true)}> - - - - setOpenDeleteDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - حذف سطح دسترسی - {openDeleteDialog && ( - - )} - - - ); -}; -export default DeleteDialog; +import DeleteIcon from "@mui/icons-material/Delete"; +import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import DeleteContent from "./DeleteContent"; +const DeleteDialog = ({ rowId, mutate }) => { + const [openDeleteDialog, setOpenDeleteDialog] = useState(false); + + return ( + <> + + setOpenDeleteDialog(true)}> + + + + setOpenDeleteDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + حذف سطح دسترسی + {openDeleteDialog && ( + + )} + + + ); +}; +export default DeleteDialog; diff --git a/src/components/dashboard/permissionTable/RowActions/index.jsx b/src/components/dashboard/permissionTable/RowActions/index.jsx index cb78144..3a9eba2 100644 --- a/src/components/dashboard/permissionTable/RowActions/index.jsx +++ b/src/components/dashboard/permissionTable/RowActions/index.jsx @@ -1,12 +1,12 @@ -import { Box } from "@mui/material"; -import EditPermission from "../Actions/Edit"; -import DeleteDialog from "./DeleteDialog"; -const RowActions = ({ row, mutate }) => { - return ( - - - - - ); -}; -export default RowActions; +import { Box } from "@mui/material"; +import EditPermission from "../Actions/Edit"; +import DeleteDialog from "./DeleteDialog"; +const RowActions = ({ row, mutate }) => { + return ( + + + + + ); +}; +export default RowActions; diff --git a/src/components/dashboard/permissionTable/Toolbar.jsx b/src/components/dashboard/permissionTable/Toolbar.jsx index 1f6422e..208c2db 100644 --- a/src/components/dashboard/permissionTable/Toolbar.jsx +++ b/src/components/dashboard/permissionTable/Toolbar.jsx @@ -1,9 +1,9 @@ -import CreatePermission from "./Actions/Create"; -const Toolbar = ({ mutate }) => { - return ( - <> - - - ); -}; -export default Toolbar; +import CreatePermission from "./Actions/Create"; +const Toolbar = ({ mutate }) => { + return ( + <> + + + ); +}; +export default Toolbar; diff --git a/src/components/dashboard/permissionTable/index.jsx b/src/components/dashboard/permissionTable/index.jsx index bbbce86..7a9d7c2 100644 --- a/src/components/dashboard/permissionTable/index.jsx +++ b/src/components/dashboard/permissionTable/index.jsx @@ -1,13 +1,13 @@ -import PageTitle from "@/core/components/PageTitle"; -import { Stack } from "@mui/material"; -import PermissionList from "./PermissionList"; - -const PermissionTablePage = () => { - return ( - - - - - ); -}; -export default PermissionTablePage; +import PageTitle from "@/core/components/PageTitle"; +import { Stack } from "@mui/material"; +import PermissionList from "./PermissionList"; + +const PermissionTablePage = () => { + return ( + + + + + ); +}; +export default PermissionTablePage; diff --git a/src/components/dashboard/roadItems/operator/Actions/Create/Forms/CreateFormContent.jsx b/src/components/dashboard/roadItems/operator/Actions/Create/Forms/CreateFormContent.jsx index 2e7a775..293c6a7 100644 --- a/src/components/dashboard/roadItems/operator/Actions/Create/Forms/CreateFormContent.jsx +++ b/src/components/dashboard/roadItems/operator/Actions/Create/Forms/CreateFormContent.jsx @@ -1,306 +1,306 @@ -import React, { useState } from "react"; -import { useForm } from "react-hook-form"; -import { yupResolver } from "@hookform/resolvers/yup"; -import { array, mixed, number, object, string } from "yup"; -import { useTheme } from "@emotion/react"; -import { Box, Button, DialogActions, DialogContent, Tab, Tabs, useMediaQuery } from "@mui/material"; -import StyledForm from "@/core/components/StyledForm"; -import InsertDriveFileIcon from "@mui/icons-material/InsertDriveFile"; -import FileCopyIcon from "@mui/icons-material/FileCopy"; -import InfoIcon from "@mui/icons-material/Info"; -import ExitToAppIcon from "@mui/icons-material/ExitToApp"; -import KeyboardDoubleArrowRightIcon from "@mui/icons-material/KeyboardDoubleArrowRight"; -import BeenhereIcon from "@mui/icons-material/Beenhere"; -import GetItemsForm from "@/components/dashboard/roadItems/operator/Actions/Create/Forms/GetItemsForm"; -import GetSubItemsForm from "@/components/dashboard/roadItems/operator/Actions/Create/Forms/GetSubItemsForm"; -import GetItemInfo from "@/components/dashboard/roadItems/operator/Actions/Create/Forms/GetItemInfo"; -import { format } from "date-fns"; - -function TabPanel(props) { - const { children, value, index } = props; - return ( - - ); -} - -const validationSchema = object({ - item_id: number().required("نوع آیتم را مشخص کنید!"), - sub_item_id: number().required("اقدام انجام شده را مشخص کنید!"), - amount: string().required("وارد کردن مقدار الزامیست!"), - cmms_machines: array() - .test("cmms-machines-conditional", "وارد کردن کد خودرو الزامیست!", function (value) { - const { is_gasht } = this.options.context; - if (is_gasht) { - return true; // اگر is_gasht true باشد، این فیلد نیاز به اعتبارسنجی ندارد - } - return Array.isArray(value) && value.length > 0; // حداقل یک کد باید وجود داشته باشد - }) - .min(1, "حداقل یک کد خودرو باید وارد شود!"), // پیام خطا برای زمانی که شرط تست برقرار باشد - rahdaran_id: array() - .test("rahdaran-id-conditional", "وارد کردن کد راهداران الزامیست!", function (value) { - const { is_gasht } = this.options.context; - if (is_gasht) { - return true; // اگر is_gasht true باشد، این فیلد نیاز به اعتبارسنجی ندارد - } - return Array.isArray(value) && value.length > 0; // حداقل یک کد باید وجود داشته باشد - }) - .min(1, "حداقل یک کد راهدار باید وارد شود!"), // پیام خطا برای زمانی که شرط تست برقرار باشد - activity_time: string().test("activity-time-conditional", "لطفا زمان فعالیت را انتخاب کنید!", function (value) { - const { is_gasht } = this.options.context; // دسترسی به context - if (is_gasht) { - return true; // اگر is_gasht true باشد، این فیلد نیاز به اعتبارسنجی ندارد - } - return !!value; // در غیر این صورت مقدار فیلد باید وجود داشته باشد - }), - activity_date: string().test( - "activity-date-conditional", - "لطفاً تاریخ شروع فعالیت را انتخاب کنید!", - function (value) { - const { is_gasht } = this.options.context; // دسترسی به context - if (is_gasht) { - return true; // اگر is_gasht true باشد، این فیلد نیاز به اعتبارسنجی ندارد - } - return !!value; // در غیر این صورت مقدار فیلد باید وجود داشته باشد - } - ), - before_image: mixed() - .nullable() - .test("before-image-required", "لطفا عکس قبل از اقدام را بارگذاری کنید!", function (value) { - const { subItemsList } = this.options.context; - const needsImage = subItemsList?.needs_image === 1; - if (needsImage) { - return !!value; - } - return true; - }), - after_image: mixed() - .nullable() - .test("after-image-required", "لطفا عکس بعد از اقدام را بارگذاری کنید!", function (value) { - const { subItemsList } = this.options.context; - const needsImage = subItemsList?.needs_image === 1; - if (needsImage) { - return !!value; - } - return true; - }), - start_point: mixed() - .test("start-point-required", "لطفاً نقطه شروع را مشخص کنید!", function (value) { - return !!value; // چک می‌کند که مقدار موجود است - }) - .required("لطفاً نقطه شروع را مشخص کنید!"), - end_point: mixed().test("end-point-required", "لطفاً نقطه پایان را مشخص کنید!", function (value) { - const { subItemsList } = this.options.context; - const needsEndPoint = subItemsList?.needs_end_point === 1; - if (needsEndPoint) { - return !!value; // چک می‌کند که مقدار موجود است - } - return true; - }), -}); - -const CreateFormContent = ({ setOpen, onSubmit, is_gasht = false }) => { - const defaultValues = { - item_id: null, - sub_item_id: null, - amount: "", - before_image: null, - after_image: null, - start_point: "", - end_point: "", - ...(!is_gasht && { - activity_time: "", - activity_date: "", - cmms_machines: [], - rahdaran_id: [], - }), - }; - - const [tabState, setTabState] = useState(0); - const [itemsList, setItemsList] = useState(); - const [subItemsList, setSubItemsList] = useState([]); - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - - const handleClose = () => { - setOpen(false); - }; - - const handleChangeTab = (event, newValue) => { - setTabState(newValue); - }; - - const handlePrev = () => { - if (tabState === 2) { - const fieldsToReset = [ - "amount", - "activity_time", - "activity_date", - "before_image", - "after_image", - "cmms_machines", - "rahdaran_id", - "start_point", - "end_point", - ]; - fieldsToReset.forEach((field) => resetField(field)); - } - if (tabState === 0) { - handleClose(); - } else { - setTabState(tabState - 1); - } - }; - const { - control, - watch, - getValues, - register, - handleSubmit, - setValue, - resetField, - formState: { errors, isSubmitting }, - } = useForm({ - defaultValues, - resolver: yupResolver(validationSchema), - mode: "all", - context: { subItemsList, is_gasht }, - }); - const onSubmitBase = async (data) => { - let result = { ...data }; - - if (result.before_image === null) { - delete result.before_image; - delete data.before_image; - } - - if (result.after_image === null) { - delete result.after_image; - delete data.after_image; - } - - if (result.end_point === "") { - delete result.end_point; - delete data.end_point; - } else { - result.end_point = `${result.end_point.lat},${result.end_point.lng}`; - } - - if (result.start_point === "") { - delete result.start_point; - delete data.start_point; - } else { - result.start_point = `${result.start_point.lat},${result.start_point.lng}`; - } - - if (!is_gasht) { - result.rahdaran_id.forEach((rahdar, index) => { - result[`rahdaran_id[${index}]`] = rahdar.id; - }); - delete result.rahdaran_id; - - result.cmms_machines.forEach((cmms_machine, index) => { - result[`machines_id[${index}]`] = cmms_machine.id; - }); - delete result.cmms_machines; - - result[`activity_time`] = format(new Date(result.activity_time), "HH:mm"); - } else { - delete result.rahdaran_id; - delete result.cmms_machines; - delete result.activity_date; - delete result.activity_time; - } - - await onSubmit({ - result, - data: { - ...data, - item_name: itemsList.name, - sub_item_name: subItemsList.name, - unit_fa: subItemsList.unit, - }, - }); - }; - - return ( - - - } label="انتخاب آیتم" /> - } label="انتخاب اقدام انجام شده" /> - } label="اطلاعات فعالیت" /> - - - - - - - - - - - - - - - - - {tabState === 2 && ( - - )} - - - ); -}; -export default CreateFormContent; +import React, { useState } from "react"; +import { useForm } from "react-hook-form"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { array, mixed, number, object, string } from "yup"; +import { useTheme } from "@emotion/react"; +import { Box, Button, DialogActions, DialogContent, Tab, Tabs, useMediaQuery } from "@mui/material"; +import StyledForm from "@/core/components/StyledForm"; +import InsertDriveFileIcon from "@mui/icons-material/InsertDriveFile"; +import FileCopyIcon from "@mui/icons-material/FileCopy"; +import InfoIcon from "@mui/icons-material/Info"; +import ExitToAppIcon from "@mui/icons-material/ExitToApp"; +import KeyboardDoubleArrowRightIcon from "@mui/icons-material/KeyboardDoubleArrowRight"; +import BeenhereIcon from "@mui/icons-material/Beenhere"; +import GetItemsForm from "@/components/dashboard/roadItems/operator/Actions/Create/Forms/GetItemsForm"; +import GetSubItemsForm from "@/components/dashboard/roadItems/operator/Actions/Create/Forms/GetSubItemsForm"; +import GetItemInfo from "@/components/dashboard/roadItems/operator/Actions/Create/Forms/GetItemInfo"; +import { format } from "date-fns"; + +function TabPanel(props) { + const { children, value, index } = props; + return ( + + ); +} + +const validationSchema = object({ + item_id: number().required("نوع آیتم را مشخص کنید!"), + sub_item_id: number().required("اقدام انجام شده را مشخص کنید!"), + amount: string().required("وارد کردن مقدار الزامیست!"), + cmms_machines: array() + .test("cmms-machines-conditional", "وارد کردن کد خودرو الزامیست!", function (value) { + const { is_gasht } = this.options.context; + if (is_gasht) { + return true; // اگر is_gasht true باشد، این فیلد نیاز به اعتبارسنجی ندارد + } + return Array.isArray(value) && value.length > 0; // حداقل یک کد باید وجود داشته باشد + }) + .min(1, "حداقل یک کد خودرو باید وارد شود!"), // پیام خطا برای زمانی که شرط تست برقرار باشد + rahdaran_id: array() + .test("rahdaran-id-conditional", "وارد کردن کد راهداران الزامیست!", function (value) { + const { is_gasht } = this.options.context; + if (is_gasht) { + return true; // اگر is_gasht true باشد، این فیلد نیاز به اعتبارسنجی ندارد + } + return Array.isArray(value) && value.length > 0; // حداقل یک کد باید وجود داشته باشد + }) + .min(1, "حداقل یک کد راهدار باید وارد شود!"), // پیام خطا برای زمانی که شرط تست برقرار باشد + activity_time: string().test("activity-time-conditional", "لطفا زمان فعالیت را انتخاب کنید!", function (value) { + const { is_gasht } = this.options.context; // دسترسی به context + if (is_gasht) { + return true; // اگر is_gasht true باشد، این فیلد نیاز به اعتبارسنجی ندارد + } + return !!value; // در غیر این صورت مقدار فیلد باید وجود داشته باشد + }), + activity_date: string().test( + "activity-date-conditional", + "لطفاً تاریخ شروع فعالیت را انتخاب کنید!", + function (value) { + const { is_gasht } = this.options.context; // دسترسی به context + if (is_gasht) { + return true; // اگر is_gasht true باشد، این فیلد نیاز به اعتبارسنجی ندارد + } + return !!value; // در غیر این صورت مقدار فیلد باید وجود داشته باشد + } + ), + before_image: mixed() + .nullable() + .test("before-image-required", "لطفا عکس قبل از اقدام را بارگذاری کنید!", function (value) { + const { subItemsList } = this.options.context; + const needsImage = subItemsList?.needs_image === 1; + if (needsImage) { + return !!value; + } + return true; + }), + after_image: mixed() + .nullable() + .test("after-image-required", "لطفا عکس بعد از اقدام را بارگذاری کنید!", function (value) { + const { subItemsList } = this.options.context; + const needsImage = subItemsList?.needs_image === 1; + if (needsImage) { + return !!value; + } + return true; + }), + start_point: mixed() + .test("start-point-required", "لطفاً نقطه شروع را مشخص کنید!", function (value) { + return !!value; // چک می‌کند که مقدار موجود است + }) + .required("لطفاً نقطه شروع را مشخص کنید!"), + end_point: mixed().test("end-point-required", "لطفاً نقطه پایان را مشخص کنید!", function (value) { + const { subItemsList } = this.options.context; + const needsEndPoint = subItemsList?.needs_end_point === 1; + if (needsEndPoint) { + return !!value; // چک می‌کند که مقدار موجود است + } + return true; + }), +}); + +const CreateFormContent = ({ setOpen, onSubmit, is_gasht = false }) => { + const defaultValues = { + item_id: null, + sub_item_id: null, + amount: "", + before_image: null, + after_image: null, + start_point: "", + end_point: "", + ...(!is_gasht && { + activity_time: "", + activity_date: "", + cmms_machines: [], + rahdaran_id: [], + }), + }; + + const [tabState, setTabState] = useState(0); + const [itemsList, setItemsList] = useState(); + const [subItemsList, setSubItemsList] = useState([]); + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + + const handleClose = () => { + setOpen(false); + }; + + const handleChangeTab = (event, newValue) => { + setTabState(newValue); + }; + + const handlePrev = () => { + if (tabState === 2) { + const fieldsToReset = [ + "amount", + "activity_time", + "activity_date", + "before_image", + "after_image", + "cmms_machines", + "rahdaran_id", + "start_point", + "end_point", + ]; + fieldsToReset.forEach((field) => resetField(field)); + } + if (tabState === 0) { + handleClose(); + } else { + setTabState(tabState - 1); + } + }; + const { + control, + watch, + getValues, + register, + handleSubmit, + setValue, + resetField, + formState: { errors, isSubmitting }, + } = useForm({ + defaultValues, + resolver: yupResolver(validationSchema), + mode: "all", + context: { subItemsList, is_gasht }, + }); + const onSubmitBase = async (data) => { + let result = { ...data }; + + if (result.before_image === null) { + delete result.before_image; + delete data.before_image; + } + + if (result.after_image === null) { + delete result.after_image; + delete data.after_image; + } + + if (result.end_point === "") { + delete result.end_point; + delete data.end_point; + } else { + result.end_point = `${result.end_point.lat},${result.end_point.lng}`; + } + + if (result.start_point === "") { + delete result.start_point; + delete data.start_point; + } else { + result.start_point = `${result.start_point.lat},${result.start_point.lng}`; + } + + if (!is_gasht) { + result.rahdaran_id.forEach((rahdar, index) => { + result[`rahdaran_id[${index}]`] = rahdar.id; + }); + delete result.rahdaran_id; + + result.cmms_machines.forEach((cmms_machine, index) => { + result[`machines_id[${index}]`] = cmms_machine.id; + }); + delete result.cmms_machines; + + result[`activity_time`] = format(new Date(result.activity_time), "HH:mm"); + } else { + delete result.rahdaran_id; + delete result.cmms_machines; + delete result.activity_date; + delete result.activity_time; + } + + await onSubmit({ + result, + data: { + ...data, + item_name: itemsList.name, + sub_item_name: subItemsList.name, + unit_fa: subItemsList.unit, + }, + }); + }; + + return ( + + + } label="انتخاب آیتم" /> + } label="انتخاب اقدام انجام شده" /> + } label="اطلاعات فعالیت" /> + + + + + + + + + + + + + + + + + {tabState === 2 && ( + + )} + + + ); +}; +export default CreateFormContent; diff --git a/src/components/dashboard/roadItems/operator/Actions/Create/Forms/GetItemInfo.jsx b/src/components/dashboard/roadItems/operator/Actions/Create/Forms/GetItemInfo.jsx index bb9cbe0..82d5cca 100644 --- a/src/components/dashboard/roadItems/operator/Actions/Create/Forms/GetItemInfo.jsx +++ b/src/components/dashboard/roadItems/operator/Actions/Create/Forms/GetItemInfo.jsx @@ -1,124 +1,124 @@ -import { Grid, Stack } from "@mui/material"; -import ImageUpload from "./ImageUpload"; -import MuiDatePicker from "@/core/components/MuiDatePicker"; -import MuiTimePicker from "@/core/components/MuiTimePicker"; -import MapInfoTwoMarker from "@/core/components/MapInfoTwoMarker"; -import MapInfoOneMarker from "@/core/components/MapInfoOneMarker"; -import { Controller } from "react-hook-form"; -import CarCode from "@/core/components/CarCode"; -import RahdarCode from "@/core/components/RahdarCode"; -import PreviousStatesInfo from "./PreviousStatesInfo"; -import NumberField from "@/core/components/NumberField"; - -const GetItemInfo = ({ register, itemsList, subItemsList, control, setValue, errors, watch, getValues, is_gasht }) => { - return ( - - - - - - { - if (!isNaN(event.target.value)) { - setValue("amount", event.target.value); - } else { - setValue("amount", watch("amount")); - } - }} - helperText={errors.amount ? errors.amount.message : null} - variant="outlined" - fullWidth - /> - - {!is_gasht && ( - - { - return ( - field.onChange(value || [])} - error={error} - multiple={true} - /> - ); - }} - name={"cmms_machines"} - /> - - )} - {!is_gasht && ( - - { - return ( - field.onChange(value || [])} - error={error} - /> - ); - }} - name={"rahdaran_id"} - /> - - )} - - {subItemsList.needs_image ? ( - - ) : null} - - {!is_gasht ? ( - - - - - - - - - - - ) : null} - - {subItemsList?.needs_end_point === 1 ? ( - - ) : ( - - )} - - - ); -}; -export default GetItemInfo; +import { Grid, Stack } from "@mui/material"; +import ImageUpload from "./ImageUpload"; +import MuiDatePicker from "@/core/components/MuiDatePicker"; +import MuiTimePicker from "@/core/components/MuiTimePicker"; +import MapInfoTwoMarker from "@/core/components/MapInfoTwoMarker"; +import MapInfoOneMarker from "@/core/components/MapInfoOneMarker"; +import { Controller } from "react-hook-form"; +import CarCode from "@/core/components/CarCode"; +import RahdarCode from "@/core/components/RahdarCode"; +import PreviousStatesInfo from "./PreviousStatesInfo"; +import NumberField from "@/core/components/NumberField"; + +const GetItemInfo = ({ register, itemsList, subItemsList, control, setValue, errors, watch, getValues, is_gasht }) => { + return ( + + + + + + { + if (!isNaN(event.target.value)) { + setValue("amount", event.target.value); + } else { + setValue("amount", watch("amount")); + } + }} + helperText={errors.amount ? errors.amount.message : null} + variant="outlined" + fullWidth + /> + + {!is_gasht && ( + + { + return ( + field.onChange(value || [])} + error={error} + multiple={true} + /> + ); + }} + name={"cmms_machines"} + /> + + )} + {!is_gasht && ( + + { + return ( + field.onChange(value || [])} + error={error} + /> + ); + }} + name={"rahdaran_id"} + /> + + )} + + {subItemsList.needs_image ? ( + + ) : null} + + {!is_gasht ? ( + + + + + + + + + + + ) : null} + + {subItemsList?.needs_end_point === 1 ? ( + + ) : ( + + )} + + + ); +}; +export default GetItemInfo; diff --git a/src/components/dashboard/roadItems/operator/Actions/Create/Forms/GetItemsForm.jsx b/src/components/dashboard/roadItems/operator/Actions/Create/Forms/GetItemsForm.jsx index de689e1..02ba9a9 100644 --- a/src/components/dashboard/roadItems/operator/Actions/Create/Forms/GetItemsForm.jsx +++ b/src/components/dashboard/roadItems/operator/Actions/Create/Forms/GetItemsForm.jsx @@ -1,64 +1,64 @@ -import DialogLoading from "@/core/components/DialogLoading"; -import useRoadItemGetItems from "@/lib/hooks/useRoadItemGetItems"; -import { Card, CardActionArea, Grid, Typography } from "@mui/material"; -import Image from "next/image"; - -const GetItemsForm = ({ setValue, setItemsList, tabState, setTabState }) => { - const { itemsList, loadingItemsList, errorItemsList } = useRoadItemGetItems(); - - return ( - <> - {errorItemsList ? ( - - خطا در دریافت لیست آیتم ها - - ) : loadingItemsList ? ( - - ) : ( - - {itemsList.map((item) => ( - - { - setValue("item_id", item.id); - setItemsList(item); - setTabState(tabState + 1); - }} - > - - {"icon"} - {item.name} - - - - ))} - - )} - - ); -}; -export default GetItemsForm; +import DialogLoading from "@/core/components/DialogLoading"; +import useRoadItemGetItems from "@/lib/hooks/useRoadItemGetItems"; +import { Card, CardActionArea, Grid, Typography } from "@mui/material"; +import Image from "next/image"; + +const GetItemsForm = ({ setValue, setItemsList, tabState, setTabState }) => { + const { itemsList, loadingItemsList, errorItemsList } = useRoadItemGetItems(); + + return ( + <> + {errorItemsList ? ( + + خطا در دریافت لیست آیتم ها + + ) : loadingItemsList ? ( + + ) : ( + + {itemsList.map((item) => ( + + { + setValue("item_id", item.id); + setItemsList(item); + setTabState(tabState + 1); + }} + > + + {"icon"} + {item.name} + + + + ))} + + )} + + ); +}; +export default GetItemsForm; diff --git a/src/components/dashboard/roadItems/operator/Actions/Create/Forms/GetSubItemsForm.jsx b/src/components/dashboard/roadItems/operator/Actions/Create/Forms/GetSubItemsForm.jsx index dc84c40..e8d4226 100644 --- a/src/components/dashboard/roadItems/operator/Actions/Create/Forms/GetSubItemsForm.jsx +++ b/src/components/dashboard/roadItems/operator/Actions/Create/Forms/GetSubItemsForm.jsx @@ -1,53 +1,53 @@ -import DialogLoading from "@/core/components/DialogLoading"; -import useRoadItemGetSubItems from "@/lib/hooks/useRoadItemGetISubtems"; -import { Card, CardActionArea, Grid, Typography } from "@mui/material"; - -const GetSubItemsForm = ({ setValue, watch, setSubItemsList, tabState, setTabState }) => { - const { subItemsList, loadingSubItemsList, errorSubItemsList } = useRoadItemGetSubItems(watch("item_id")); - - return ( - <> - {errorSubItemsList ? ( - - خطا در دریافت اقدام انجام شده - - ) : loadingSubItemsList ? ( - - ) : ( - - {subItemsList.map((item) => ( - - { - setValue("sub_item_id", item.sub_item); - setSubItemsList(item); - setTabState(tabState + 1); - }} - > - - {item.name} - - - - ))} - - )} - - ); -}; -export default GetSubItemsForm; +import DialogLoading from "@/core/components/DialogLoading"; +import useRoadItemGetSubItems from "@/lib/hooks/useRoadItemGetISubtems"; +import { Card, CardActionArea, Grid, Typography } from "@mui/material"; + +const GetSubItemsForm = ({ setValue, watch, setSubItemsList, tabState, setTabState }) => { + const { subItemsList, loadingSubItemsList, errorSubItemsList } = useRoadItemGetSubItems(watch("item_id")); + + return ( + <> + {errorSubItemsList ? ( + + خطا در دریافت اقدام انجام شده + + ) : loadingSubItemsList ? ( + + ) : ( + + {subItemsList.map((item) => ( + + { + setValue("sub_item_id", item.sub_item); + setSubItemsList(item); + setTabState(tabState + 1); + }} + > + + {item.name} + + + + ))} + + )} + + ); +}; +export default GetSubItemsForm; diff --git a/src/components/dashboard/roadItems/operator/Actions/Create/Forms/ImageUpload.jsx b/src/components/dashboard/roadItems/operator/Actions/Create/Forms/ImageUpload.jsx index 17a9904..8460525 100644 --- a/src/components/dashboard/roadItems/operator/Actions/Create/Forms/ImageUpload.jsx +++ b/src/components/dashboard/roadItems/operator/Actions/Create/Forms/ImageUpload.jsx @@ -1,173 +1,173 @@ -import { FormControl, FormHelperText, Grid } from "@mui/material"; -import UploadSystem from "@/core/components/UploadSystem"; -import { Controller } from "react-hook-form"; -import React, { useEffect, useState } from "react"; - -const ImageUpload = ({ control, setValue, errors, getValues, beforeImage = null, afterImage = null }) => { - const [beforeImg, setBeforeImg] = useState(beforeImage ? beforeImage : null); - const [beforeFileType, setBeforeFileType] = useState(beforeImage ? "image/" : null); - const [beforeFileName, setBeforeFileName] = useState(null); - const [showBeforeImage, setShowBeforeImage] = useState(!beforeImage); - - const [afterImg, setAfterImg] = useState(afterImage ? afterImage : null); - const [afterFileType, setAfterFileType] = useState(afterImage ? "image/" : null); - const [afterFileName, setAfterFileName] = useState(null); - const [showAfterImage, setShowAfterImage] = useState(!afterImage); - - useEffect(() => { - const beforeImage = getValues("before_image"); - const afterImage = getValues("after_image"); - - if (beforeImage) { - setShowBeforeImage(false); - - if (typeof beforeImage === "string") { - setBeforeImg(beforeImage); - setBeforeFileType("image/"); - } else if (beforeImage instanceof File) { - setBeforeImg(URL.createObjectURL(beforeImage)); - setBeforeFileType(beforeImage.type); - } - } - - if (afterImage) { - setShowAfterImage(false); - - if (typeof afterImage === "string") { - setAfterImg(afterImage); - setAfterFileType("image/"); - } else if (afterImage instanceof File) { - setAfterImg(URL.createObjectURL(afterImage)); - setAfterFileType(afterImage.type); - } - } - }, [getValues]); - - const handleBeforeFileChange = (event) => { - const uploadedFile = event.target?.files?.[0]; - if (uploadedFile) { - const fileType = event.target?.files?.[0].type; - const fileName = event.target?.files?.[0].name; - setBeforeImg(URL.createObjectURL(uploadedFile)); - setBeforeFileType(fileType); - setBeforeFileName(fileName); - setValue("before_image", uploadedFile); - setShowBeforeImage(false); - } - }; - const handleAfterFileChange = (event) => { - const uploadedFile = event.target?.files?.[0]; - if (uploadedFile) { - const fileType = event.target?.files?.[0].type; - const fileName = event.target?.files?.[0].name; - setAfterImg(URL.createObjectURL(uploadedFile)); - setAfterFileType(fileType); - setAfterFileName(fileName); - setValue("after_image", uploadedFile); - setShowAfterImage(false); - } - }; - return ( - - - { - return ( - - - عکس قبل از اقدام - - - - {errors.before_image ? errors.before_image.message : null} - - - ); - }} - /> - - - { - return ( - - - عکس بعد از اقدام - - - - {errors.after_image ? errors.after_image.message : null} - - - ); - }} - /> - - - ); -}; -export default ImageUpload; +import { FormControl, FormHelperText, Grid } from "@mui/material"; +import UploadSystem from "@/core/components/UploadSystem"; +import { Controller } from "react-hook-form"; +import React, { useEffect, useState } from "react"; + +const ImageUpload = ({ control, setValue, errors, getValues, beforeImage = null, afterImage = null }) => { + const [beforeImg, setBeforeImg] = useState(beforeImage ? beforeImage : null); + const [beforeFileType, setBeforeFileType] = useState(beforeImage ? "image/" : null); + const [beforeFileName, setBeforeFileName] = useState(null); + const [showBeforeImage, setShowBeforeImage] = useState(!beforeImage); + + const [afterImg, setAfterImg] = useState(afterImage ? afterImage : null); + const [afterFileType, setAfterFileType] = useState(afterImage ? "image/" : null); + const [afterFileName, setAfterFileName] = useState(null); + const [showAfterImage, setShowAfterImage] = useState(!afterImage); + + useEffect(() => { + const beforeImage = getValues("before_image"); + const afterImage = getValues("after_image"); + + if (beforeImage) { + setShowBeforeImage(false); + + if (typeof beforeImage === "string") { + setBeforeImg(beforeImage); + setBeforeFileType("image/"); + } else if (beforeImage instanceof File) { + setBeforeImg(URL.createObjectURL(beforeImage)); + setBeforeFileType(beforeImage.type); + } + } + + if (afterImage) { + setShowAfterImage(false); + + if (typeof afterImage === "string") { + setAfterImg(afterImage); + setAfterFileType("image/"); + } else if (afterImage instanceof File) { + setAfterImg(URL.createObjectURL(afterImage)); + setAfterFileType(afterImage.type); + } + } + }, [getValues]); + + const handleBeforeFileChange = (event) => { + const uploadedFile = event.target?.files?.[0]; + if (uploadedFile) { + const fileType = event.target?.files?.[0].type; + const fileName = event.target?.files?.[0].name; + setBeforeImg(URL.createObjectURL(uploadedFile)); + setBeforeFileType(fileType); + setBeforeFileName(fileName); + setValue("before_image", uploadedFile); + setShowBeforeImage(false); + } + }; + const handleAfterFileChange = (event) => { + const uploadedFile = event.target?.files?.[0]; + if (uploadedFile) { + const fileType = event.target?.files?.[0].type; + const fileName = event.target?.files?.[0].name; + setAfterImg(URL.createObjectURL(uploadedFile)); + setAfterFileType(fileType); + setAfterFileName(fileName); + setValue("after_image", uploadedFile); + setShowAfterImage(false); + } + }; + return ( + + + { + return ( + + + عکس قبل از اقدام + + + + {errors.before_image ? errors.before_image.message : null} + + + ); + }} + /> + + + { + return ( + + + عکس بعد از اقدام + + + + {errors.after_image ? errors.after_image.message : null} + + + ); + }} + /> + + + ); +}; +export default ImageUpload; diff --git a/src/components/dashboard/roadItems/operator/Actions/Create/Forms/PreviousStatesInfo.jsx b/src/components/dashboard/roadItems/operator/Actions/Create/Forms/PreviousStatesInfo.jsx index 51fac42..a944ccd 100644 --- a/src/components/dashboard/roadItems/operator/Actions/Create/Forms/PreviousStatesInfo.jsx +++ b/src/components/dashboard/roadItems/operator/Actions/Create/Forms/PreviousStatesInfo.jsx @@ -1,43 +1,43 @@ -import { Box, Chip, Divider, Grid, Typography } from "@mui/material"; -import InsertDriveFileIcon from "@mui/icons-material/InsertDriveFile"; -import FileCopyIcon from "@mui/icons-material/FileCopy"; - -const PreviousStatesInfo = ({ itemsList, subItemsList }) => { - return ( - - - - } - label={ - - آیتم انتخاب ‌شده - - } - /> - - - - {itemsList.name || "هیچ آیتمی انتخاب نشده است"} - - - - - } - label={ - - اقدام انجام شده - - } - /> - - - - {subItemsList?.name || "هیچ اقدامی انتخاب نشده است"} - - - - ); -}; -export default PreviousStatesInfo; +import { Box, Chip, Divider, Grid, Typography } from "@mui/material"; +import InsertDriveFileIcon from "@mui/icons-material/InsertDriveFile"; +import FileCopyIcon from "@mui/icons-material/FileCopy"; + +const PreviousStatesInfo = ({ itemsList, subItemsList }) => { + return ( + + + + } + label={ + + آیتم انتخاب ‌شده + + } + /> + + + + {itemsList.name || "هیچ آیتمی انتخاب نشده است"} + + + + + } + label={ + + اقدام انجام شده + + } + /> + + + + {subItemsList?.name || "هیچ اقدامی انتخاب نشده است"} + + + + ); +}; +export default PreviousStatesInfo; diff --git a/src/components/dashboard/roadItems/operator/Actions/Create/Forms/index.jsx b/src/components/dashboard/roadItems/operator/Actions/Create/Forms/index.jsx index 40d0c2a..ac45261 100644 --- a/src/components/dashboard/roadItems/operator/Actions/Create/Forms/index.jsx +++ b/src/components/dashboard/roadItems/operator/Actions/Create/Forms/index.jsx @@ -1,44 +1,44 @@ -"use client"; -import { Dialog, IconButton } from "@mui/material"; -import CreateFormContent from "@/components/dashboard/roadItems/operator/Actions/Create/Forms/CreateFormContent"; -import { CREATE_ROAD_ITEMS } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import CloseIcon from "@mui/icons-material/Close"; - -const OperatorCreateForm = ({ open, setOpen, mutate }) => { - const requestServer = useRequest({ notificationSuccess: true }); - const HandleSubmit = async ({ result }) => { - const formData = new FormData(); - for (const [key, value] of Object.entries(result)) { - formData.append(key, value); - } - await requestServer(CREATE_ROAD_ITEMS, "post", { - data: formData, - hasSidebarUpdate: true, - }) - .then((response) => { - mutate(); - setOpen(false); - }) - .catch((error) => {}); - }; - return ( - - setOpen(false)} - sx={(theme) => ({ - position: "absolute", - right: 8, - top: 8, - zIndex: 50, - color: theme.palette.grey[500], - })} - > - - - {open && } - - ); -}; -export default OperatorCreateForm; +"use client"; +import { Dialog, IconButton } from "@mui/material"; +import CreateFormContent from "@/components/dashboard/roadItems/operator/Actions/Create/Forms/CreateFormContent"; +import { CREATE_ROAD_ITEMS } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import CloseIcon from "@mui/icons-material/Close"; + +const OperatorCreateForm = ({ open, setOpen, mutate }) => { + const requestServer = useRequest({ notificationSuccess: true }); + const HandleSubmit = async ({ result }) => { + const formData = new FormData(); + for (const [key, value] of Object.entries(result)) { + formData.append(key, value); + } + await requestServer(CREATE_ROAD_ITEMS, "post", { + data: formData, + hasSidebarUpdate: true, + }) + .then((response) => { + mutate(); + setOpen(false); + }) + .catch((error) => {}); + }; + return ( + + setOpen(false)} + sx={(theme) => ({ + position: "absolute", + right: 8, + top: 8, + zIndex: 50, + color: theme.palette.grey[500], + })} + > + + + {open && } + + ); +}; +export default OperatorCreateForm; diff --git a/src/components/dashboard/roadItems/operator/Actions/Create/index.jsx b/src/components/dashboard/roadItems/operator/Actions/Create/index.jsx index a503283..e107500 100644 --- a/src/components/dashboard/roadItems/operator/Actions/Create/index.jsx +++ b/src/components/dashboard/roadItems/operator/Actions/Create/index.jsx @@ -1,38 +1,38 @@ -"use client"; -import { Button, IconButton, useMediaQuery } from "@mui/material"; -import { useTheme } from "@emotion/react"; -import { useState } from "react"; -import { AddCircle } from "@mui/icons-material"; -import OperatorCreateForm from "./Forms"; - -const OperatorCreate = ({ mutate }) => { - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const [open, setOpen] = useState(false); - - const handleOpen = () => { - setOpen(true); - }; - - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - - - ); -}; -export default OperatorCreate; +"use client"; +import { Button, IconButton, useMediaQuery } from "@mui/material"; +import { useTheme } from "@emotion/react"; +import { useState } from "react"; +import { AddCircle } from "@mui/icons-material"; +import OperatorCreateForm from "./Forms"; + +const OperatorCreate = ({ mutate }) => { + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const [open, setOpen] = useState(false); + + const handleOpen = () => { + setOpen(true); + }; + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + + + ); +}; +export default OperatorCreate; diff --git a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/GashtCreate.jsx b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/GashtCreate.jsx index 4784f26..3574ffd 100644 --- a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/GashtCreate.jsx +++ b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/GashtCreate.jsx @@ -1,29 +1,29 @@ -import { Dialog, IconButton } from "@mui/material"; -import GashtCreateContent from "./GashtCreateContent"; -import { useState } from "react"; -import CloseIcon from "@mui/icons-material/Close"; - -const GashtCreate = ({ open, setOpen, mutate, rowId }) => { - const [tabState, setTabState] = useState(0); - return ( - - setOpen(false)} - sx={(theme) => ({ - position: "absolute", - right: 8, - top: 8, - zIndex: 50, - color: theme.palette.grey[500], - })} - > - - - {open && ( - - )} - - ); -}; -export default GashtCreate; +import { Dialog, IconButton } from "@mui/material"; +import GashtCreateContent from "./GashtCreateContent"; +import { useState } from "react"; +import CloseIcon from "@mui/icons-material/Close"; + +const GashtCreate = ({ open, setOpen, mutate, rowId }) => { + const [tabState, setTabState] = useState(0); + return ( + + setOpen(false)} + sx={(theme) => ({ + position: "absolute", + right: 8, + top: 8, + zIndex: 50, + color: theme.palette.grey[500], + })} + > + + + {open && ( + + )} + + ); +}; +export default GashtCreate; diff --git a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/GashtCreateContent.jsx b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/GashtCreateContent.jsx index 5816ddf..f6357cc 100644 --- a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/GashtCreateContent.jsx +++ b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/GashtCreateContent.jsx @@ -1,162 +1,162 @@ -import { Box, Button, DialogActions, DialogContent, Tab, Tabs } from "@mui/material"; -import { useForm } from "react-hook-form"; -import { yupResolver } from "@hookform/resolvers/yup"; -import * as yup from "yup"; -import InsertDriveFileIcon from "@mui/icons-material/InsertDriveFile"; -import FileCopyIcon from "@mui/icons-material/FileCopy"; -import ExitToAppIcon from "@mui/icons-material/ExitToApp"; -import KeyboardDoubleArrowRightIcon from "@mui/icons-material/KeyboardDoubleArrowRight"; -import BeenhereIcon from "@mui/icons-material/Beenhere"; -import StyledForm from "@/core/components/StyledForm"; -import React, { useState } from "react"; -import SearchItemInfo from "./SearchItemInfo"; -import moment from "jalali-moment"; -import GetItemInfo from "./RowActions/GetItemInfo"; - -function TabPanel(props) { - const { children, value, index } = props; - return ( - - ); -} - -const defaultValues = { - start_date: moment(new Date()).format("YYYY-MM-DD"), - end_date: moment(new Date()).format("YYYY-MM-DD"), - item_id: "", - road_patrol_id: "", -}; - -const defaultFilter = [ - { value: `${defaultValues.item_id}`, datatype: "text", id: "item_id", fn: "equals" }, - { value: `${defaultValues.road_patrol_id}`, datatype: "text", id: "road_patrol_id", fn: "equals" }, - { value: `${defaultValues.start_date}`, datatype: "date", id: "roadPatrol.start_time", fn: "equals" }, - { value: `${defaultValues.end_date}`, datatype: "date", id: "roadPatrol.end_time", fn: "equals" }, -]; - -const GashtCreateContent = ({ mutate, setOpen, tabState, setTabState }) => { - const [itemInfo, setItemInfo] = useState(null); - const [submitCompleteForm, setSubmitCompleteForm] = useState(false); - const [specialFilter, setSpecialFilter] = useState(defaultFilter); - - const validationSchema = yup - .object() - .shape({ - start_date: yup.string().nullable(), - end_date: yup.string().nullable(), - item_id: yup.string().nullable(), - road_patrol_id: yup.string().nullable(), - }) - .test("at-least-one", "وارد کردن مقدار ضروریست!!!", (values) => { - return (!!values.start_date && !!values.end_date) || !!values.item_id || !!values.road_patrol_id; - }); - - const handleChangeTab = (event, newValue) => { - setTabState(newValue); - }; - const handleClose = () => { - setOpen(false); - }; - - const handlePrev = () => { - if (tabState === 0) { - handleClose(); - } else { - setTabState(tabState - 1); - } - }; - - const { - control, - getValues, - watch, - register, - handleSubmit, - setValue, - formState: { errors, isSubmitting }, - } = useForm({ - defaultValues, - resolver: yupResolver(validationSchema), - mode: "all", - }); - const onSearchSubmit = async (data) => { - setSpecialFilter([ - { value: `${data.item_id}`, datatype: "text", id: "item_id", fn: "equals" }, - { value: `${data.road_patrol_id}`, datatype: "text", id: "road_patrol_id", fn: "equals" }, - { value: `${data.start_date}`, datatype: "date", id: "roadPatrol.start_time", fn: "equals" }, - { value: `${data.end_date}`, datatype: "date", id: "roadPatrol.end_time", fn: "equals" }, - ]); - }; - return ( - <> - - } label="انتخاب مورد مشاهده شده" /> - } label="اطلاعات مورد اقدام شده" /> - - - - - - - - - - - - - - - - {tabState === 1 && ( - - )} - - - ); -}; -export default GashtCreateContent; +import { Box, Button, DialogActions, DialogContent, Tab, Tabs } from "@mui/material"; +import { useForm } from "react-hook-form"; +import { yupResolver } from "@hookform/resolvers/yup"; +import * as yup from "yup"; +import InsertDriveFileIcon from "@mui/icons-material/InsertDriveFile"; +import FileCopyIcon from "@mui/icons-material/FileCopy"; +import ExitToAppIcon from "@mui/icons-material/ExitToApp"; +import KeyboardDoubleArrowRightIcon from "@mui/icons-material/KeyboardDoubleArrowRight"; +import BeenhereIcon from "@mui/icons-material/Beenhere"; +import StyledForm from "@/core/components/StyledForm"; +import React, { useState } from "react"; +import SearchItemInfo from "./SearchItemInfo"; +import moment from "jalali-moment"; +import GetItemInfo from "./RowActions/GetItemInfo"; + +function TabPanel(props) { + const { children, value, index } = props; + return ( + + ); +} + +const defaultValues = { + start_date: moment(new Date()).format("YYYY-MM-DD"), + end_date: moment(new Date()).format("YYYY-MM-DD"), + item_id: "", + road_patrol_id: "", +}; + +const defaultFilter = [ + { value: `${defaultValues.item_id}`, datatype: "text", id: "item_id", fn: "equals" }, + { value: `${defaultValues.road_patrol_id}`, datatype: "text", id: "road_patrol_id", fn: "equals" }, + { value: `${defaultValues.start_date}`, datatype: "date", id: "roadPatrol.start_time", fn: "equals" }, + { value: `${defaultValues.end_date}`, datatype: "date", id: "roadPatrol.end_time", fn: "equals" }, +]; + +const GashtCreateContent = ({ mutate, setOpen, tabState, setTabState }) => { + const [itemInfo, setItemInfo] = useState(null); + const [submitCompleteForm, setSubmitCompleteForm] = useState(false); + const [specialFilter, setSpecialFilter] = useState(defaultFilter); + + const validationSchema = yup + .object() + .shape({ + start_date: yup.string().nullable(), + end_date: yup.string().nullable(), + item_id: yup.string().nullable(), + road_patrol_id: yup.string().nullable(), + }) + .test("at-least-one", "وارد کردن مقدار ضروریست!!!", (values) => { + return (!!values.start_date && !!values.end_date) || !!values.item_id || !!values.road_patrol_id; + }); + + const handleChangeTab = (event, newValue) => { + setTabState(newValue); + }; + const handleClose = () => { + setOpen(false); + }; + + const handlePrev = () => { + if (tabState === 0) { + handleClose(); + } else { + setTabState(tabState - 1); + } + }; + + const { + control, + getValues, + watch, + register, + handleSubmit, + setValue, + formState: { errors, isSubmitting }, + } = useForm({ + defaultValues, + resolver: yupResolver(validationSchema), + mode: "all", + }); + const onSearchSubmit = async (data) => { + setSpecialFilter([ + { value: `${data.item_id}`, datatype: "text", id: "item_id", fn: "equals" }, + { value: `${data.road_patrol_id}`, datatype: "text", id: "road_patrol_id", fn: "equals" }, + { value: `${data.start_date}`, datatype: "date", id: "roadPatrol.start_time", fn: "equals" }, + { value: `${data.end_date}`, datatype: "date", id: "roadPatrol.end_time", fn: "equals" }, + ]); + }; + return ( + <> + + } label="انتخاب مورد مشاهده شده" /> + } label="اطلاعات مورد اقدام شده" /> + + + + + + + + + + + + + + + + {tabState === 1 && ( + + )} + + + ); +}; +export default GashtCreateContent; diff --git a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/LocationForm/LocationFormContent.jsx b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/LocationForm/LocationFormContent.jsx index f012434..4ca5635 100644 --- a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/LocationForm/LocationFormContent.jsx +++ b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/LocationForm/LocationFormContent.jsx @@ -1,31 +1,31 @@ -"use client"; -import { Box, Button, DialogActions, DialogContent, Stack } from "@mui/material"; -import React from "react"; -import dynamic from "next/dynamic"; -import MapLoading from "@/core/components/MapLayer/Loading"; -import ShowLocationMarker from "@/core/components/ShowLocationMarker"; -const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { - loading: () => , - ssr: false, -}); - -const LocationFormContent = ({ setOpenLocationDialog, start_lat, start_lng }) => { - return ( - <> - - - - - - - - - - - - ); -}; - -export default LocationFormContent; +"use client"; +import { Box, Button, DialogActions, DialogContent, Stack } from "@mui/material"; +import React from "react"; +import dynamic from "next/dynamic"; +import MapLoading from "@/core/components/MapLayer/Loading"; +import ShowLocationMarker from "@/core/components/ShowLocationMarker"; +const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { + loading: () => , + ssr: false, +}); + +const LocationFormContent = ({ setOpenLocationDialog, start_lat, start_lng }) => { + return ( + <> + + + + + + + + + + + + ); +}; + +export default LocationFormContent; diff --git a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/LocationForm/index.jsx b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/LocationForm/index.jsx index 09df6ad..0b917b4 100644 --- a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/LocationForm/index.jsx +++ b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/LocationForm/index.jsx @@ -1,36 +1,36 @@ -import React, { useState } from "react"; -import { Tooltip, IconButton, Dialog, DialogTitle } from "@mui/material"; -import ExploreIcon from "@mui/icons-material/Explore"; -import LocationFormContent from "./LocationFormContent"; -const LocationForm = ({ start_lat, start_lng }) => { - const [openLocationDialog, setOpenLocationDialog] = useState(false); - - return ( - <> - - setOpenLocationDialog(true)}> - - - - setOpenLocationDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - موقعیت - - - - ); -}; -export default LocationForm; +import React, { useState } from "react"; +import { Tooltip, IconButton, Dialog, DialogTitle } from "@mui/material"; +import ExploreIcon from "@mui/icons-material/Explore"; +import LocationFormContent from "./LocationFormContent"; +const LocationForm = ({ start_lat, start_lng }) => { + const [openLocationDialog, setOpenLocationDialog] = useState(false); + + return ( + <> + + setOpenLocationDialog(true)}> + + + + setOpenLocationDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + موقعیت + + + + ); +}; +export default LocationForm; diff --git a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/RowActions/CompleteItem.jsx b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/RowActions/CompleteItem.jsx index f0e048d..4c3dd74 100644 --- a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/RowActions/CompleteItem.jsx +++ b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/RowActions/CompleteItem.jsx @@ -1,235 +1,235 @@ -import { Grid, Stack } from "@mui/material"; -import PreviousStatesInfo from "./PreviousStatesInfo"; -import NumberField from "@/core/components/NumberField"; -import { Controller, useForm } from "react-hook-form"; -import CarCode from "@/core/components/CarCode"; -import RahdarCode from "@/core/components/RahdarCode"; -import ImageUpload from "@/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/RowActions/ImageUpload"; -import MuiDatePicker from "@/core/components/MuiDatePicker"; -import MuiTimePicker from "@/core/components/MuiTimePicker"; -import MapInfoTwoMarker from "@/core/components/MapInfoTwoMarker"; -import MapInfoOneMarker from "@/core/components/MapInfoOneMarker"; -import { yupResolver } from "@hookform/resolvers/yup"; -import StyledForm from "@/core/components/StyledForm"; -import { array, mixed, number, object, string } from "yup"; -import useRequest from "@/lib/hooks/useRequest"; -import React, { useEffect } from "react"; -import { CREATE_ROAD_ITEMS } from "@/core/utils/routes"; -import { format } from "date-fns"; - -const CompleteItem = ({ subItem, itemInfo, setSubmitCompleteForm, mutate, setOpen }) => { - const requestServer = useRequest({ notificationSuccess: true }); - - const defaultValues = { - item_id: itemInfo?.item_id || null, - sub_item_id: itemInfo?.sub_item_id || null, - amount: "", - activity_time: "", - activity_date: "", - before_image: null, - after_image: null, - cmms_machines: null, - rahdaran_id: null, - start_point: { lat: itemInfo?.start_lat || "", lng: itemInfo?.start_lon || "" }, - end_point: { lat: itemInfo?.end_lat || "", lng: itemInfo?.end_lon || "" }, - }; - - const validationSchema = object({ - item_id: number().required("نوع آیتم را مشخص کنید!"), - sub_item_id: number().required("اقدام انجام شده را مشخص کنید!"), - amount: string().required("وارد کردن مقدار الزامیست!"), - cmms_machines: array().required("وارد کردن کد خودرو الزامیست!").min(1, "حداقل یک کد خودرو باید وارد شود!"), - rahdaran_id: array().required("وارد کردن کد راهداران الزامیست!").min(1, "حداقل یک کد راهدار باید وارد شود!"), // بررسی حداقل یک آیتم, - activity_time: string().required("لطفا زمان فعالیت را انتخاب کنید!"), - activity_date: string().required("لطفاً تاریخ شروع فعالیت را انتخاب کنید!"), - before_image: mixed() - .nullable() - .test("before-image-required", "لطفا عکس قبل از اقدام را بارگذاری کنید!", function (value) { - const { subItem } = this.options.context; - const needsImage = subItem?.needs_image === 1; - if (needsImage) { - return !!value; - } - return true; - }), - after_image: mixed() - .nullable() - .test("after-image-required", "لطفا عکس بعد از اقدام را بارگذاری کنید!", function (value) { - const { subItem } = this.options.context; - const needsImage = subItem?.needs_image === 1; - if (needsImage) { - return !!value; - } - return true; - }), - start_point: mixed() - .test("start-point-required", "لطفاً نقطه شروع را مشخص کنید!", function (value) { - return !!value; // چک می‌کند که مقدار موجود است - }) - .required("لطفاً نقطه شروع را مشخص کنید!"), - end_point: mixed().test("end-point-required", "لطفاً نقطه پایان را مشخص کنید!", function (value) { - const { subItem } = this.options.context; - const needsEndPoint = subItem?.needs_end_point === 1; - if (needsEndPoint) { - return !!value; // چک می‌کند که مقدار موجود است - } - return true; - }), - }); - - const { - control, - watch, - getValues, - register, - handleSubmit, - setValue, - resetField, - formState: { errors, isSubmitting }, - } = useForm({ - defaultValues, - resolver: yupResolver(validationSchema), - mode: "all", - context: { subItem }, - }); - - useEffect(() => { - setSubmitCompleteForm(isSubmitting); - }, [isSubmitting]); - const onSubmit = async (data) => { - let endPoint; - let startPoint = `${data.start_point.lat},${data.start_point.lng}`; - if (subItem.needs_end_point === 1) { - endPoint = `${data.end_point.lat},${data.end_point.lng}`; - } - const formData = new FormData(); - data.after_image !== null && formData.append("after_image", data.after_image); - data.before_image !== null && formData.append("before_image", data.before_image); - subItem.needs_end_point === 1 && formData.append("end_point", endPoint); - formData.append("start_point", startPoint); - formData.append("activity_time", format(new Date(data.activity_time), "HH:mm")); - formData.append("activity_date", data.activity_date); - formData.append("amount", data.amount); - formData.append("item_id", data.item_id); - formData.append("sub_item_id", data.sub_item_id); - data.cmms_machines.forEach((machine, index) => formData.append(`machines_id[${index}]`, machine.id)); - data.rahdaran_id.forEach((rahdar, index) => formData.append(`rahdaran_id[${index}]`, rahdar.id)); - - await requestServer(CREATE_ROAD_ITEMS, "post", { - data: formData, - hasSidebarUpdate: true, - }) - .then((response) => { - mutate(); - setOpen(false); - }) - .catch((error) => {}); - }; - - return ( - - - - - - - { - if (!isNaN(event.target.value)) { - setValue("amount", event.target.value); - } else { - setValue("amount", watch("amount")); - } - }} - helperText={errors.amount ? errors.amount.message : null} - variant="outlined" - fullWidth - /> - - - { - return ( - field.onChange(value || [])} - error={error} - multiple={true} - /> - ); - }} - name={"cmms_machines"} - /> - - - { - return ( - field.onChange(value || [])} - error={error} - /> - ); - }} - name={"rahdaran_id"} - /> - - - {subItem.needs_image ? ( - - ) : null} - - - - - - - - - - - - - {subItem?.needs_end_point === 1 ? ( - - ) : ( - - )} - - - - ); -}; -export default CompleteItem; +import { Grid, Stack } from "@mui/material"; +import PreviousStatesInfo from "./PreviousStatesInfo"; +import NumberField from "@/core/components/NumberField"; +import { Controller, useForm } from "react-hook-form"; +import CarCode from "@/core/components/CarCode"; +import RahdarCode from "@/core/components/RahdarCode"; +import ImageUpload from "@/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/RowActions/ImageUpload"; +import MuiDatePicker from "@/core/components/MuiDatePicker"; +import MuiTimePicker from "@/core/components/MuiTimePicker"; +import MapInfoTwoMarker from "@/core/components/MapInfoTwoMarker"; +import MapInfoOneMarker from "@/core/components/MapInfoOneMarker"; +import { yupResolver } from "@hookform/resolvers/yup"; +import StyledForm from "@/core/components/StyledForm"; +import { array, mixed, number, object, string } from "yup"; +import useRequest from "@/lib/hooks/useRequest"; +import React, { useEffect } from "react"; +import { CREATE_ROAD_ITEMS } from "@/core/utils/routes"; +import { format } from "date-fns"; + +const CompleteItem = ({ subItem, itemInfo, setSubmitCompleteForm, mutate, setOpen }) => { + const requestServer = useRequest({ notificationSuccess: true }); + + const defaultValues = { + item_id: itemInfo?.item_id || null, + sub_item_id: itemInfo?.sub_item_id || null, + amount: "", + activity_time: "", + activity_date: "", + before_image: null, + after_image: null, + cmms_machines: null, + rahdaran_id: null, + start_point: { lat: itemInfo?.start_lat || "", lng: itemInfo?.start_lon || "" }, + end_point: { lat: itemInfo?.end_lat || "", lng: itemInfo?.end_lon || "" }, + }; + + const validationSchema = object({ + item_id: number().required("نوع آیتم را مشخص کنید!"), + sub_item_id: number().required("اقدام انجام شده را مشخص کنید!"), + amount: string().required("وارد کردن مقدار الزامیست!"), + cmms_machines: array().required("وارد کردن کد خودرو الزامیست!").min(1, "حداقل یک کد خودرو باید وارد شود!"), + rahdaran_id: array().required("وارد کردن کد راهداران الزامیست!").min(1, "حداقل یک کد راهدار باید وارد شود!"), // بررسی حداقل یک آیتم, + activity_time: string().required("لطفا زمان فعالیت را انتخاب کنید!"), + activity_date: string().required("لطفاً تاریخ شروع فعالیت را انتخاب کنید!"), + before_image: mixed() + .nullable() + .test("before-image-required", "لطفا عکس قبل از اقدام را بارگذاری کنید!", function (value) { + const { subItem } = this.options.context; + const needsImage = subItem?.needs_image === 1; + if (needsImage) { + return !!value; + } + return true; + }), + after_image: mixed() + .nullable() + .test("after-image-required", "لطفا عکس بعد از اقدام را بارگذاری کنید!", function (value) { + const { subItem } = this.options.context; + const needsImage = subItem?.needs_image === 1; + if (needsImage) { + return !!value; + } + return true; + }), + start_point: mixed() + .test("start-point-required", "لطفاً نقطه شروع را مشخص کنید!", function (value) { + return !!value; // چک می‌کند که مقدار موجود است + }) + .required("لطفاً نقطه شروع را مشخص کنید!"), + end_point: mixed().test("end-point-required", "لطفاً نقطه پایان را مشخص کنید!", function (value) { + const { subItem } = this.options.context; + const needsEndPoint = subItem?.needs_end_point === 1; + if (needsEndPoint) { + return !!value; // چک می‌کند که مقدار موجود است + } + return true; + }), + }); + + const { + control, + watch, + getValues, + register, + handleSubmit, + setValue, + resetField, + formState: { errors, isSubmitting }, + } = useForm({ + defaultValues, + resolver: yupResolver(validationSchema), + mode: "all", + context: { subItem }, + }); + + useEffect(() => { + setSubmitCompleteForm(isSubmitting); + }, [isSubmitting]); + const onSubmit = async (data) => { + let endPoint; + let startPoint = `${data.start_point.lat},${data.start_point.lng}`; + if (subItem.needs_end_point === 1) { + endPoint = `${data.end_point.lat},${data.end_point.lng}`; + } + const formData = new FormData(); + data.after_image !== null && formData.append("after_image", data.after_image); + data.before_image !== null && formData.append("before_image", data.before_image); + subItem.needs_end_point === 1 && formData.append("end_point", endPoint); + formData.append("start_point", startPoint); + formData.append("activity_time", format(new Date(data.activity_time), "HH:mm")); + formData.append("activity_date", data.activity_date); + formData.append("amount", data.amount); + formData.append("item_id", data.item_id); + formData.append("sub_item_id", data.sub_item_id); + data.cmms_machines.forEach((machine, index) => formData.append(`machines_id[${index}]`, machine.id)); + data.rahdaran_id.forEach((rahdar, index) => formData.append(`rahdaran_id[${index}]`, rahdar.id)); + + await requestServer(CREATE_ROAD_ITEMS, "post", { + data: formData, + hasSidebarUpdate: true, + }) + .then((response) => { + mutate(); + setOpen(false); + }) + .catch((error) => {}); + }; + + return ( + + + + + + + { + if (!isNaN(event.target.value)) { + setValue("amount", event.target.value); + } else { + setValue("amount", watch("amount")); + } + }} + helperText={errors.amount ? errors.amount.message : null} + variant="outlined" + fullWidth + /> + + + { + return ( + field.onChange(value || [])} + error={error} + multiple={true} + /> + ); + }} + name={"cmms_machines"} + /> + + + { + return ( + field.onChange(value || [])} + error={error} + /> + ); + }} + name={"rahdaran_id"} + /> + + + {subItem.needs_image ? ( + + ) : null} + + + + + + + + + + + + + {subItem?.needs_end_point === 1 ? ( + + ) : ( + + )} + + + + ); +}; +export default CompleteItem; diff --git a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/RowActions/GetItemInfo.jsx b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/RowActions/GetItemInfo.jsx index e11fbd3..637927e 100644 --- a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/RowActions/GetItemInfo.jsx +++ b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/RowActions/GetItemInfo.jsx @@ -1,28 +1,28 @@ -import { LinearProgress, Typography } from "@mui/material"; -import useRoadItemGetISubtems from "@/lib/hooks/useRoadItemGetISubtems"; -import CompleteItem from "./CompleteItem"; - -const GetItemInfo = ({ itemInfo, setSubmitCompleteForm, mutate, setOpen }) => { - const { subItemsList, loadingSubItemsList, errorSubItemsList } = useRoadItemGetISubtems(itemInfo?.item_id); - const subItem = subItemsList.find((SubItem) => SubItem.sub_item === itemInfo?.sub_item_id); - return ( - <> - {loadingSubItemsList ? ( - - ) : errorSubItemsList ? ( - - خطا در دریافت اطلاعات!!! - - ) : ( - - )} - - ); -}; -export default GetItemInfo; +import { LinearProgress, Typography } from "@mui/material"; +import useRoadItemGetISubtems from "@/lib/hooks/useRoadItemGetISubtems"; +import CompleteItem from "./CompleteItem"; + +const GetItemInfo = ({ itemInfo, setSubmitCompleteForm, mutate, setOpen }) => { + const { subItemsList, loadingSubItemsList, errorSubItemsList } = useRoadItemGetISubtems(itemInfo?.item_id); + const subItem = subItemsList.find((SubItem) => SubItem.sub_item === itemInfo?.sub_item_id); + return ( + <> + {loadingSubItemsList ? ( + + ) : errorSubItemsList ? ( + + خطا در دریافت اطلاعات!!! + + ) : ( + + )} + + ); +}; +export default GetItemInfo; diff --git a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/RowActions/ImageUpload.jsx b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/RowActions/ImageUpload.jsx index cef9b18..4e8ee62 100644 --- a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/RowActions/ImageUpload.jsx +++ b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/RowActions/ImageUpload.jsx @@ -1,157 +1,157 @@ -import { FormControl, FormHelperText, Grid } from "@mui/material"; -import UploadSystem from "@/core/components/UploadSystem"; -import { Controller } from "react-hook-form"; -import React, { useEffect, useState } from "react"; - -const ImageUpload = ({ control, setValue, errors, getValues, beforeImage = null, afterImage = null }) => { - const [beforeImg, setBeforeImg] = useState(beforeImage ? beforeImage : null); - const [beforeFileType, setBeforeFileType] = useState(beforeImage ? "image/" : null); - const [beforeFileName, setBeforeFileName] = useState(null); - const [showBeforeImage, setShowBeforeImage] = useState(!beforeImage); - - const [afterImg, setAfterImg] = useState(afterImage ? afterImage : null); - const [afterFileType, setAfterFileType] = useState(afterImage ? "image/" : null); - const [afterFileName, setAfterFileName] = useState(null); - const [showAfterImage, setShowAfterImage] = useState(!afterImage); - - useEffect(() => { - if (getValues("before_image")) { - setShowBeforeImage(false); - setBeforeImg(getValues("before_image")); - setBeforeFileType("image/"); - } - if (getValues("after_image")) { - setShowAfterImage(false); - setAfterImg(getValues("after_image")); - setAfterFileType("image/"); - } - }, [getValues]); - - const handleBeforeFileChange = (event) => { - const uploadedFile = event.target?.files?.[0]; - if (uploadedFile) { - const fileType = event.target?.files?.[0].type; - const fileName = event.target?.files?.[0].name; - setBeforeImg(URL.createObjectURL(uploadedFile)); - setBeforeFileType(fileType); - setBeforeFileName(fileName); - setValue("before_image", uploadedFile); - setShowBeforeImage(false); - } - }; - const handleAfterFileChange = (event) => { - const uploadedFile = event.target?.files?.[0]; - if (uploadedFile) { - const fileType = event.target?.files?.[0].type; - const fileName = event.target?.files?.[0].name; - setAfterImg(URL.createObjectURL(uploadedFile)); - setAfterFileType(fileType); - setAfterFileName(fileName); - setValue("after_image", uploadedFile); - setShowAfterImage(false); - } - }; - return ( - - - { - return ( - - - عکس قبل از اقدام - - - - {errors.before_image ? errors.before_image.message : null} - - - ); - }} - /> - - - { - return ( - - - عکس بعد از اقدام - - - - {errors.after_image ? errors.after_image.message : null} - - - ); - }} - /> - - - ); -}; -export default ImageUpload; +import { FormControl, FormHelperText, Grid } from "@mui/material"; +import UploadSystem from "@/core/components/UploadSystem"; +import { Controller } from "react-hook-form"; +import React, { useEffect, useState } from "react"; + +const ImageUpload = ({ control, setValue, errors, getValues, beforeImage = null, afterImage = null }) => { + const [beforeImg, setBeforeImg] = useState(beforeImage ? beforeImage : null); + const [beforeFileType, setBeforeFileType] = useState(beforeImage ? "image/" : null); + const [beforeFileName, setBeforeFileName] = useState(null); + const [showBeforeImage, setShowBeforeImage] = useState(!beforeImage); + + const [afterImg, setAfterImg] = useState(afterImage ? afterImage : null); + const [afterFileType, setAfterFileType] = useState(afterImage ? "image/" : null); + const [afterFileName, setAfterFileName] = useState(null); + const [showAfterImage, setShowAfterImage] = useState(!afterImage); + + useEffect(() => { + if (getValues("before_image")) { + setShowBeforeImage(false); + setBeforeImg(getValues("before_image")); + setBeforeFileType("image/"); + } + if (getValues("after_image")) { + setShowAfterImage(false); + setAfterImg(getValues("after_image")); + setAfterFileType("image/"); + } + }, [getValues]); + + const handleBeforeFileChange = (event) => { + const uploadedFile = event.target?.files?.[0]; + if (uploadedFile) { + const fileType = event.target?.files?.[0].type; + const fileName = event.target?.files?.[0].name; + setBeforeImg(URL.createObjectURL(uploadedFile)); + setBeforeFileType(fileType); + setBeforeFileName(fileName); + setValue("before_image", uploadedFile); + setShowBeforeImage(false); + } + }; + const handleAfterFileChange = (event) => { + const uploadedFile = event.target?.files?.[0]; + if (uploadedFile) { + const fileType = event.target?.files?.[0].type; + const fileName = event.target?.files?.[0].name; + setAfterImg(URL.createObjectURL(uploadedFile)); + setAfterFileType(fileType); + setAfterFileName(fileName); + setValue("after_image", uploadedFile); + setShowAfterImage(false); + } + }; + return ( + + + { + return ( + + + عکس قبل از اقدام + + + + {errors.before_image ? errors.before_image.message : null} + + + ); + }} + /> + + + { + return ( + + + عکس بعد از اقدام + + + + {errors.after_image ? errors.after_image.message : null} + + + ); + }} + /> + + + ); +}; +export default ImageUpload; diff --git a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/RowActions/PreviousStatesInfo.jsx b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/RowActions/PreviousStatesInfo.jsx index 6603df4..d245557 100644 --- a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/RowActions/PreviousStatesInfo.jsx +++ b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/RowActions/PreviousStatesInfo.jsx @@ -1,43 +1,43 @@ -import { Box, Chip, Divider, Grid, Typography } from "@mui/material"; -import InsertDriveFileIcon from "@mui/icons-material/InsertDriveFile"; -import FileCopyIcon from "@mui/icons-material/FileCopy"; - -const PreviousStatesInfo = ({ itemInfo }) => { - return ( - - - - } - label={ - - آیتم انتخاب ‌شده - - } - /> - - - - {itemInfo.item_name || "هیچ آیتمی انتخاب نشده است"} - - - - - } - label={ - - اقدام انجام شده - - } - /> - - - - {itemInfo?.sub_item_name || "هیچ اقدامی انتخاب نشده است"} - - - - ); -}; -export default PreviousStatesInfo; +import { Box, Chip, Divider, Grid, Typography } from "@mui/material"; +import InsertDriveFileIcon from "@mui/icons-material/InsertDriveFile"; +import FileCopyIcon from "@mui/icons-material/FileCopy"; + +const PreviousStatesInfo = ({ itemInfo }) => { + return ( + + + + } + label={ + + آیتم انتخاب ‌شده + + } + /> + + + + {itemInfo.item_name || "هیچ آیتمی انتخاب نشده است"} + + + + + } + label={ + + اقدام انجام شده + + } + /> + + + + {itemInfo?.sub_item_name || "هیچ اقدامی انتخاب نشده است"} + + + + ); +}; +export default PreviousStatesInfo; diff --git a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/RowActions/SubItemForm/index.jsx b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/RowActions/SubItemForm/index.jsx index ba8a902..a6a106c 100644 --- a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/RowActions/SubItemForm/index.jsx +++ b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/RowActions/SubItemForm/index.jsx @@ -1,21 +1,21 @@ -import React from "react"; -import { Tooltip, IconButton } from "@mui/material"; -import UndoIcon from "@mui/icons-material/Undo"; -const SubItemForm = ({ row, setTabState, setItemInfo }) => { - return ( - <> - - { - setTabState(1); - setItemInfo(row.original); - }} - > - - - - - ); -}; -export default SubItemForm; +import React from "react"; +import { Tooltip, IconButton } from "@mui/material"; +import UndoIcon from "@mui/icons-material/Undo"; +const SubItemForm = ({ row, setTabState, setItemInfo }) => { + return ( + <> + + { + setTabState(1); + setItemInfo(row.original); + }} + > + + + + + ); +}; +export default SubItemForm; diff --git a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/RowActions/index.jsx b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/RowActions/index.jsx index 84e8a31..9653286 100644 --- a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/RowActions/index.jsx +++ b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/RowActions/index.jsx @@ -1,11 +1,11 @@ -import { Box } from "@mui/material"; -import SubItemForm from "./SubItemForm"; - -const RowActions = ({ row, mutate, setTabState, setItemInfo }) => { - return ( - - - - ); -}; -export default RowActions; +import { Box } from "@mui/material"; +import SubItemForm from "./SubItemForm"; + +const RowActions = ({ row, mutate, setTabState, setItemInfo }) => { + return ( + + + + ); +}; +export default RowActions; diff --git a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/SearchItemInfo.jsx b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/SearchItemInfo.jsx index 6c270c9..50175b8 100644 --- a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/SearchItemInfo.jsx +++ b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/SearchItemInfo.jsx @@ -1,42 +1,42 @@ -import DialogLoading from "@/core/components/DialogLoading"; -import useRoadItemGetItems from "@/lib/hooks/useRoadItemGetItems"; -import { Typography } from "@mui/material"; -import SearchItems from "./SearchItems"; -import TableInfo from "./TableInfo"; - -const SearchItemInfo = ({ - watch, - errors, - setValue, - register, - specialFilter, - setTabState, - setItemInfo, - isSubmitting, -}) => { - const { itemsList, loadingItemsList, errorItemsList } = useRoadItemGetItems(); - return ( - <> - {loadingItemsList ? ( - - ) : errorItemsList ? ( - - خطا در دریافت اطلاعات!!! - - ) : ( - <> - - - - )} - - ); -}; -export default SearchItemInfo; +import DialogLoading from "@/core/components/DialogLoading"; +import useRoadItemGetItems from "@/lib/hooks/useRoadItemGetItems"; +import { Typography } from "@mui/material"; +import SearchItems from "./SearchItems"; +import TableInfo from "./TableInfo"; + +const SearchItemInfo = ({ + watch, + errors, + setValue, + register, + specialFilter, + setTabState, + setItemInfo, + isSubmitting, +}) => { + const { itemsList, loadingItemsList, errorItemsList } = useRoadItemGetItems(); + return ( + <> + {loadingItemsList ? ( + + ) : errorItemsList ? ( + + خطا در دریافت اطلاعات!!! + + ) : ( + <> + + + + )} + + ); +}; +export default SearchItemInfo; diff --git a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/SearchItems.jsx b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/SearchItems.jsx index 871ab06..a24bd66 100644 --- a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/SearchItems.jsx +++ b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/SearchItems.jsx @@ -1,92 +1,92 @@ -import { Button, FormControl, FormHelperText, InputLabel, MenuItem, Select, Stack, TextField } from "@mui/material"; -import MuiDatePicker from "@/core/components/MuiDatePicker"; -import SearchIcon from "@mui/icons-material/Search"; -import React from "react"; - -const SearchItems = ({ setValue, itemsList, watch, errors, register, isSubmitting }) => { - const disabledButton = - (!!watch("start_date") && !!watch("end_date")) || !!watch("item_id") || !!watch("road_patrol_id"); - - return ( - - - - - - - - - - آیتم فعالیت - - {errors.item_id ? errors.item_id.message : null} - - - - { - if (!isNaN(event.target.value)) { - setValue("road_patrol_id", event.target.value); - } else { - setValue("road_patrol_id", watch("road_patrol_id")); - } - }} - helperText={errors.road_patrol_id ? errors.road_patrol_id.message : null} - variant="outlined" - /> - - - - - - ); -}; -export default SearchItems; +import { Button, FormControl, FormHelperText, InputLabel, MenuItem, Select, Stack, TextField } from "@mui/material"; +import MuiDatePicker from "@/core/components/MuiDatePicker"; +import SearchIcon from "@mui/icons-material/Search"; +import React from "react"; + +const SearchItems = ({ setValue, itemsList, watch, errors, register, isSubmitting }) => { + const disabledButton = + (!!watch("start_date") && !!watch("end_date")) || !!watch("item_id") || !!watch("road_patrol_id"); + + return ( + + + + + + + + + + آیتم فعالیت + + {errors.item_id ? errors.item_id.message : null} + + + + { + if (!isNaN(event.target.value)) { + setValue("road_patrol_id", event.target.value); + } else { + setValue("road_patrol_id", watch("road_patrol_id")); + } + }} + helperText={errors.road_patrol_id ? errors.road_patrol_id.message : null} + variant="outlined" + /> + + + + + + ); +}; +export default SearchItems; diff --git a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/TableInfo.jsx b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/TableInfo.jsx index ca60b84..b8f3448 100644 --- a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/TableInfo.jsx +++ b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/TableInfo.jsx @@ -1,115 +1,115 @@ -import { useMemo } from "react"; -import { Box, Stack } from "@mui/material"; -import DataTableWithAuth from "@/core/components/DataTableWithAuth"; -import RowActions from "./RowActions"; -import { GET_OBSERVED_GASHT_LIST } from "@/core/utils/routes"; -import LocationForm from "./LocationForm"; - -const TableInfo = ({ specialFilter, setTabState, setItemInfo }) => { - const columns = useMemo( - () => [ - { - accessorKey: "road_patrol_id", - header: "کد یکتا گشت", - id: "road_patrol_id", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 50, - }, - { - accessorKey: "priority_fa", - header: "اولویت", - id: "priority_fa", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 80, - }, - { - accessorKey: "local_name", - header: "نام محلی", - id: "local_name", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorKey: "item_name", - header: "نام آیتم", - id: "item_name", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorKey: "sub_item_name", - header: "مشاهده انجام شده", - id: "sub_item_name", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorKey: "location", - header: "موقعیت", // Location - id: "location", - enableColumnFilter: false, - enableSorting: false, - datatype: "array", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue, row }) => { - return ( - - - - ); - }, - }, - ], - [] - ); - return ( - <> - - ( - - )} - /> - - - ); -}; -export default TableInfo; +import { useMemo } from "react"; +import { Box, Stack } from "@mui/material"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import RowActions from "./RowActions"; +import { GET_OBSERVED_GASHT_LIST } from "@/core/utils/routes"; +import LocationForm from "./LocationForm"; + +const TableInfo = ({ specialFilter, setTabState, setItemInfo }) => { + const columns = useMemo( + () => [ + { + accessorKey: "road_patrol_id", + header: "کد یکتا گشت", + id: "road_patrol_id", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 50, + }, + { + accessorKey: "priority_fa", + header: "اولویت", + id: "priority_fa", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 80, + }, + { + accessorKey: "local_name", + header: "نام محلی", + id: "local_name", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "item_name", + header: "نام آیتم", + id: "item_name", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "sub_item_name", + header: "مشاهده انجام شده", + id: "sub_item_name", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "location", + header: "موقعیت", // Location + id: "location", + enableColumnFilter: false, + enableSorting: false, + datatype: "array", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue, row }) => { + return ( + + + + ); + }, + }, + ], + [] + ); + return ( + <> + + ( + + )} + /> + + + ); +}; +export default TableInfo; diff --git a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/index.jsx b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/index.jsx index b6eb6b8..774b70c 100644 --- a/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/index.jsx +++ b/src/components/dashboard/roadItems/operator/Actions/ObservedGashtCreate/index.jsx @@ -1,42 +1,42 @@ -"use client"; -import { Button, IconButton, useMediaQuery } from "@mui/material"; -import { useTheme } from "@emotion/react"; -import { useState } from "react"; -import AddRoadIcon from "@mui/icons-material/AddRoad"; -import GashtCreate from "./GashtCreate"; - -const ObservedGashtCreate = ({ mutate }) => { - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const [open, setOpen] = useState(false); - - const handleOpen = () => { - setOpen(true); - }; - - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - - - ); -}; -export default ObservedGashtCreate; +"use client"; +import { Button, IconButton, useMediaQuery } from "@mui/material"; +import { useTheme } from "@emotion/react"; +import { useState } from "react"; +import AddRoadIcon from "@mui/icons-material/AddRoad"; +import GashtCreate from "./GashtCreate"; + +const ObservedGashtCreate = ({ mutate }) => { + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const [open, setOpen] = useState(false); + + const handleOpen = () => { + setOpen(true); + }; + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + + + ); +}; +export default ObservedGashtCreate; diff --git a/src/components/dashboard/roadItems/operator/ExcelPrint/index.jsx b/src/components/dashboard/roadItems/operator/ExcelPrint/index.jsx index 8862da8..3d0293f 100644 --- a/src/components/dashboard/roadItems/operator/ExcelPrint/index.jsx +++ b/src/components/dashboard/roadItems/operator/ExcelPrint/index.jsx @@ -1,76 +1,76 @@ -"use client"; -import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; -import { useMemo, useState } from "react"; -import moment from "jalali-moment"; -import FileSaver from "file-saver"; -import DescriptionIcon from "@mui/icons-material/Description"; -import useRequest from "@/lib/hooks/useRequest"; -import { EXPORT_ROAD_ITEMS_OPERATOR_LIST } from "@/core/utils/routes"; -import { useTheme } from "@emotion/react"; -import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; -import isArrayEmpty from "@/core/utils/isArrayEmpty"; - -const PrintExcel = ({ table, filterData }) => { - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const [loading, setLoading] = useState(false); - const requestServer = useRequest({ notificationSuccess: true }); - const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { - if (filter.value && (!Array.isArray(filter.value) || filter.value.some((item) => item.trim() !== ""))) { - acc.push({ id: key, value: filter.value }); - } - return acc; - }, []); - - const filterParams = useMemo(() => { - const params = new URLSearchParams(); - if (activeFilters.length > 0) { - activeFilters.map((filter, index) => { - const filteredFilterData = DataTableFilterDataStructure(filterData, isArrayEmpty); - params.set("filters", JSON.stringify(filteredFilterData.length === 0 ? [] : filteredFilterData)); - }); - } else { - params.set("filters", JSON.stringify([])); - } - return params; - }, [activeFilters]); - - const clickHandler = () => { - setLoading(true); - requestServer(`${EXPORT_ROAD_ITEMS_OPERATOR_LIST}?${filterParams}`, "get", { - requestOptions: { responseType: "blob" }, - }) - .then((response) => { - const filename = `خروجی کارتابل عملیات فعالیت روزانه تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; - FileSaver.saveAs(response.data, filename); - }) - .catch(() => {}) - .finally(() => { - setLoading(false); - }); - }; - - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - - ); -}; - -export default PrintExcel; +"use client"; +import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; +import { useMemo, useState } from "react"; +import moment from "jalali-moment"; +import FileSaver from "file-saver"; +import DescriptionIcon from "@mui/icons-material/Description"; +import useRequest from "@/lib/hooks/useRequest"; +import { EXPORT_ROAD_ITEMS_OPERATOR_LIST } from "@/core/utils/routes"; +import { useTheme } from "@emotion/react"; +import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; +import isArrayEmpty from "@/core/utils/isArrayEmpty"; + +const PrintExcel = ({ table, filterData }) => { + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const [loading, setLoading] = useState(false); + const requestServer = useRequest({ notificationSuccess: true }); + const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { + if (filter.value && (!Array.isArray(filter.value) || filter.value.some((item) => item.trim() !== ""))) { + acc.push({ id: key, value: filter.value }); + } + return acc; + }, []); + + const filterParams = useMemo(() => { + const params = new URLSearchParams(); + if (activeFilters.length > 0) { + activeFilters.map((filter, index) => { + const filteredFilterData = DataTableFilterDataStructure(filterData, isArrayEmpty); + params.set("filters", JSON.stringify(filteredFilterData.length === 0 ? [] : filteredFilterData)); + }); + } else { + params.set("filters", JSON.stringify([])); + } + return params; + }, [activeFilters]); + + const clickHandler = () => { + setLoading(true); + requestServer(`${EXPORT_ROAD_ITEMS_OPERATOR_LIST}?${filterParams}`, "get", { + requestOptions: { responseType: "blob" }, + }) + .then((response) => { + const filename = `خروجی کارتابل عملیات فعالیت روزانه تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; + FileSaver.saveAs(response.data, filename); + }) + .catch(() => {}) + .finally(() => { + setLoading(false); + }); + }; + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + + ); +}; + +export default PrintExcel; diff --git a/src/components/dashboard/roadItems/operator/OperatorList.jsx b/src/components/dashboard/roadItems/operator/OperatorList.jsx index 4f5d4d8..06b98ff 100644 --- a/src/components/dashboard/roadItems/operator/OperatorList.jsx +++ b/src/components/dashboard/roadItems/operator/OperatorList.jsx @@ -1,373 +1,373 @@ -"use client"; -import BlinkingCell from "@/core/components/BlinkingCell"; -import CustomSelectByDependency from "@/core/components/DataTable/filter/fieldsType/CustomSelectByDependency"; -import DataTableWithAuth from "@/core/components/DataTableWithAuth"; -import { GET_ROAD_ITEMS_OPERATOR_LIST } from "@/core/utils/routes"; -import useRoadItemGetSubItems from "@/lib/hooks/useRoadItemGetISubtems"; -import useRoadItemGetItems from "@/lib/hooks/useRoadItemGetItems"; -import { Box, Stack, Typography } from "@mui/material"; -import moment from "jalali-moment"; -import { useEffect, useMemo, useState } from "react"; -import RowActions from "./RowActions"; -import DescriptionForm from "./RowActions/DescriptionForm"; -import ImageDialog from "./RowActions/ImageForm"; -import LocationForm from "./RowActions/LocationForm"; -import MachinesCodeDialog from "./RowActions/MachinesCodeForm"; -import RahdaranDialog from "./RowActions/RahdaranForm"; -import Toolbar from "./Toolbar"; - -const OperatorList = () => { - const statusOptions = [ - { value: "", label: "همه وضعیت ها" }, - { value: 0, label: "درحال بررسی" }, - { value: 1, label: "تایید" }, - { value: 2, label: "عدم تایید" }, - ]; - const columns = useMemo( - () => [ - { - header: "کد یکتا", - id: "id", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - Cell: ({ row }) => , - }, - { - header: "اطلاعات فعالیت", - id: "info", - enableColumnFilter: false, - enableSorting: false, - grow: false, - size: 50, - columns: [ - { - accessorKey: "item", - header: "آیتم فعالیت", - id: "item", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - grow: false, - size: 100, - ColumnSelectComponent: (props) => { - const { itemsList, loadingItemsList, errorItemsList } = useRoadItemGetItems(); - - const getColumnSelectOptions = useMemo(() => { - if (loadingItemsList) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorItemsList) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: "همه آیتم ها" }, - ...itemsList.map((item) => ({ - value: item.id, - label: item.name, - })), - ]; - }, [itemsList, loadingItemsList, errorItemsList]); - - return ( - - ); - }, - Cell: ({ row }) => { - return row.original.item_fa; - }, - }, - { - accessorKey: "sub_item", - header: "اقدام انجام شده", - id: "sub_item", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - dependencyId: "item", - ColumnSelectComponent: (props) => { - const { subItemsList, loadingSubItemsList, errorSubItemsList } = useRoadItemGetSubItems( - props.dependencyFieldValue.value - ); - const [prevDependency, setPrevDependency] = useState(props.dependencyFieldValue.value); - - const getColumnSelectOptions = useMemo(() => { - if (props.dependencyFieldValue.value === "") { - return [{ value: "empty", label: "ابتدا آیتم فعالیت را انتخاب کنید" }]; - } - if (loadingSubItemsList) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorSubItemsList) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: "همه اقدام ها" }, - ...subItemsList.map((item) => ({ - value: item.sub_item, - label: item.name, - })), - ]; - }, [subItemsList, loadingSubItemsList, errorSubItemsList]); - - useEffect(() => { - if (prevDependency === props.dependencyFieldValue.value) return; - props.handleChange({ ...props.filterParameters, value: "" }); - setPrevDependency(props.dependencyFieldValue.value); - }, [props.dependencyFieldValue.value]); - return ( - - ); - }, - Cell: ({ row }) => { - return row.original.sub_item_fa; - }, - }, - { - accessorKey: "value", - header: "مقدار", // Value - id: "value", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 120, - Cell: ({ renderedCellValue, row }) => { - return ( - - - {(row.original.sub_item_data / 1).toLocaleString()} - - - {`(${row.original.unit_fa})`} - - - ); - }, - }, - { - header: "تصاویر", - id: "images", - enableColumnFilter: false, - enableSorting: false, - datatype: "array", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue, row }) => { - return ( - - - - ); - }, - }, - { - header: "موقعیت", // Location - id: "location", - enableColumnFilter: false, - enableSorting: false, - datatype: "array", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue, row }) => { - return ( - - - - ); - }, - }, - { - header: "خودرو ها", - id: "cmmsMachines__machine_code", - enableColumnFilter: true, - datatype: "text", - filterMode: "contains", - enableSorting: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue, row }) => { - return ( - - - - ); - }, - }, - { - header: "راهداران", - id: "rahdaran__code", - enableColumnFilter: true, - enableSorting: false, - datatype: "text", - filterMode: "contains", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue, row }) => { - return ( - - - - ); - }, - }, - { - accessorFn: (row) => moment(row.activity_date_time).locale("fa").format("HH:mm | yyyy/MM/DD"), - header: "تاریخ فعالیت", // Start Date - id: "activity_date_time", - enableColumnFilter: true, - datatype: "date", - filterMode: "between", - grow: false, - size: 100, - }, - ], - }, - { - accessorFn: (row) => moment(row.created_at).locale("fa").format("HH:mm | yyyy/MM/DD"), - header: "تاریخ ثبت", // Register Date - id: "created_at", - enableColumnFilter: true, - datatype: "date", - filterMode: "between", - grow: false, - size: 100, - }, - { - accessorKey: "status", - header: "وضعیت نظارت", - id: "status", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - sortDescFirst: true, - grow: false, - size: 100, - columnSelectOption: () => { - return statusOptions.map((status) => ({ - value: status.value, - label: status.label, - })); - }, - Cell: ({ renderedCellValue, row }) => <>{row.original.status_fa}, - }, - { - accessorKey: "supervisor_description", - header: "توضیحات ناظر", - id: "supervisor_description", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 70, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - if (renderedCellValue) { - return ( - - - - ); - } - return -; - }, - }, - ], - [] - ); - - return ( - <> - - - - - ); -}; -export default OperatorList; +"use client"; +import BlinkingCell from "@/core/components/BlinkingCell"; +import CustomSelectByDependency from "@/core/components/DataTable/filter/fieldsType/CustomSelectByDependency"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import { GET_ROAD_ITEMS_OPERATOR_LIST } from "@/core/utils/routes"; +import useRoadItemGetSubItems from "@/lib/hooks/useRoadItemGetISubtems"; +import useRoadItemGetItems from "@/lib/hooks/useRoadItemGetItems"; +import { Box, Stack, Typography } from "@mui/material"; +import moment from "jalali-moment"; +import { useEffect, useMemo, useState } from "react"; +import RowActions from "./RowActions"; +import DescriptionForm from "./RowActions/DescriptionForm"; +import ImageDialog from "./RowActions/ImageForm"; +import LocationForm from "./RowActions/LocationForm"; +import MachinesCodeDialog from "./RowActions/MachinesCodeForm"; +import RahdaranDialog from "./RowActions/RahdaranForm"; +import Toolbar from "./Toolbar"; + +const OperatorList = () => { + const statusOptions = [ + { value: "", label: "همه وضعیت ها" }, + { value: 0, label: "درحال بررسی" }, + { value: 1, label: "تایید" }, + { value: 2, label: "عدم تایید" }, + ]; + const columns = useMemo( + () => [ + { + header: "کد یکتا", + id: "id", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + Cell: ({ row }) => , + }, + { + header: "اطلاعات فعالیت", + id: "info", + enableColumnFilter: false, + enableSorting: false, + grow: false, + size: 50, + columns: [ + { + accessorKey: "item", + header: "آیتم فعالیت", + id: "item", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 100, + ColumnSelectComponent: (props) => { + const { itemsList, loadingItemsList, errorItemsList } = useRoadItemGetItems(); + + const getColumnSelectOptions = useMemo(() => { + if (loadingItemsList) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorItemsList) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: "همه آیتم ها" }, + ...itemsList.map((item) => ({ + value: item.id, + label: item.name, + })), + ]; + }, [itemsList, loadingItemsList, errorItemsList]); + + return ( + + ); + }, + Cell: ({ row }) => { + return row.original.item_fa; + }, + }, + { + accessorKey: "sub_item", + header: "اقدام انجام شده", + id: "sub_item", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + dependencyId: "item", + ColumnSelectComponent: (props) => { + const { subItemsList, loadingSubItemsList, errorSubItemsList } = useRoadItemGetSubItems( + props.dependencyFieldValue.value + ); + const [prevDependency, setPrevDependency] = useState(props.dependencyFieldValue.value); + + const getColumnSelectOptions = useMemo(() => { + if (props.dependencyFieldValue.value === "") { + return [{ value: "empty", label: "ابتدا آیتم فعالیت را انتخاب کنید" }]; + } + if (loadingSubItemsList) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorSubItemsList) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: "همه اقدام ها" }, + ...subItemsList.map((item) => ({ + value: item.sub_item, + label: item.name, + })), + ]; + }, [subItemsList, loadingSubItemsList, errorSubItemsList]); + + useEffect(() => { + if (prevDependency === props.dependencyFieldValue.value) return; + props.handleChange({ ...props.filterParameters, value: "" }); + setPrevDependency(props.dependencyFieldValue.value); + }, [props.dependencyFieldValue.value]); + return ( + + ); + }, + Cell: ({ row }) => { + return row.original.sub_item_fa; + }, + }, + { + accessorKey: "value", + header: "مقدار", // Value + id: "value", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 120, + Cell: ({ renderedCellValue, row }) => { + return ( + + + {(row.original.sub_item_data / 1).toLocaleString()} + + + {`(${row.original.unit_fa})`} + + + ); + }, + }, + { + header: "تصاویر", + id: "images", + enableColumnFilter: false, + enableSorting: false, + datatype: "array", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue, row }) => { + return ( + + + + ); + }, + }, + { + header: "موقعیت", // Location + id: "location", + enableColumnFilter: false, + enableSorting: false, + datatype: "array", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue, row }) => { + return ( + + + + ); + }, + }, + { + header: "خودرو ها", + id: "cmmsMachines__machine_code", + enableColumnFilter: true, + datatype: "text", + filterMode: "contains", + enableSorting: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue, row }) => { + return ( + + + + ); + }, + }, + { + header: "راهداران", + id: "rahdaran__code", + enableColumnFilter: true, + enableSorting: false, + datatype: "text", + filterMode: "contains", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue, row }) => { + return ( + + + + ); + }, + }, + { + accessorFn: (row) => moment(row.activity_date_time).locale("fa").format("HH:mm | yyyy/MM/DD"), + header: "تاریخ فعالیت", // Start Date + id: "activity_date_time", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + ], + }, + { + accessorFn: (row) => moment(row.created_at).locale("fa").format("HH:mm | yyyy/MM/DD"), + header: "تاریخ ثبت", // Register Date + id: "created_at", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + { + accessorKey: "status", + header: "وضعیت نظارت", + id: "status", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + sortDescFirst: true, + grow: false, + size: 100, + columnSelectOption: () => { + return statusOptions.map((status) => ({ + value: status.value, + label: status.label, + })); + }, + Cell: ({ renderedCellValue, row }) => <>{row.original.status_fa}, + }, + { + accessorKey: "supervisor_description", + header: "توضیحات ناظر", + id: "supervisor_description", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 70, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + if (renderedCellValue) { + return ( + + + + ); + } + return -; + }, + }, + ], + [] + ); + + return ( + <> + + + + + ); +}; +export default OperatorList; diff --git a/src/components/dashboard/roadItems/operator/RowActions/DescriptionForm/index.jsx b/src/components/dashboard/roadItems/operator/RowActions/DescriptionForm/index.jsx index 91b135a..efae7b0 100644 --- a/src/components/dashboard/roadItems/operator/RowActions/DescriptionForm/index.jsx +++ b/src/components/dashboard/roadItems/operator/RowActions/DescriptionForm/index.jsx @@ -1,51 +1,51 @@ -import { Dialog, DialogContent, DialogTitle, IconButton, Tooltip, Typography, Card, CardContent } from "@mui/material"; -import { useState } from "react"; -import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye"; -import CloseIcon from "@mui/icons-material/Close"; - -const DescriptionForm = ({ description }) => { - const [openOfficerDescriptionDialog, setOpenOfficerDescriptionDialog] = useState(false); - - return ( - <> - - setOpenOfficerDescriptionDialog(true)}> - - - - setOpenOfficerDescriptionDialog(false)} - PaperProps={{ - sx: { - transition: "all .3s", - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - borderRadius: 2, - padding: 1, - }, - }} - maxWidth="sm" - fullWidth - dir="rtl" - > - - - توضیحات ناظر - - setOpenOfficerDescriptionDialog(false)} size="small"> - - - - - - - {description || "هیچ توضیحی موجود نیست"} - - - - - - ); -}; - -export default DescriptionForm; +import { Dialog, DialogContent, DialogTitle, IconButton, Tooltip, Typography, Card, CardContent } from "@mui/material"; +import { useState } from "react"; +import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye"; +import CloseIcon from "@mui/icons-material/Close"; + +const DescriptionForm = ({ description }) => { + const [openOfficerDescriptionDialog, setOpenOfficerDescriptionDialog] = useState(false); + + return ( + <> + + setOpenOfficerDescriptionDialog(true)}> + + + + setOpenOfficerDescriptionDialog(false)} + PaperProps={{ + sx: { + transition: "all .3s", + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + borderRadius: 2, + padding: 1, + }, + }} + maxWidth="sm" + fullWidth + dir="rtl" + > + + + توضیحات ناظر + + setOpenOfficerDescriptionDialog(false)} size="small"> + + + + + + + {description || "هیچ توضیحی موجود نیست"} + + + + + + ); +}; + +export default DescriptionForm; diff --git a/src/components/dashboard/roadItems/operator/RowActions/EditForm/EditController.jsx b/src/components/dashboard/roadItems/operator/RowActions/EditForm/EditController.jsx index b18476c..a14106d 100644 --- a/src/components/dashboard/roadItems/operator/RowActions/EditForm/EditController.jsx +++ b/src/components/dashboard/roadItems/operator/RowActions/EditForm/EditController.jsx @@ -1,108 +1,108 @@ -import DialogLoading from "@/core/components/DialogLoading"; -import { - GET_CMMS_MACHINE_ROAD_ITEM, - GET_IMAGES_ROAD_ITEM, - GET_RAHDARAN_ROAD_ITEM, - UPDATE_ROAD_ITEMS, -} from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { Typography } from "@mui/material"; -import { useEffect, useState } from "react"; -import EditFormContent from "./EditFormContent"; - -const EditController = ({ rowId, mutate, setOpenEditDialog, openEditDialog, row }) => { - const requestServer = useRequest(); - const [loadingImages, setLoadingImages] = useState(true); - const [images, setImages] = useState(null); - const [loadingCmmsMachine, setLoadingCmmsMachine] = useState(true); - const [cmmsMachine, setCmmsMachine] = useState(null); - const [loadingRahdaran, setLoadingRahdaran] = useState(true); - const [rahdaran, setRahdaran] = useState(null); - - useEffect(() => { - const fetchData = async () => { - try { - setLoadingImages(true); - const response = await requestServer(`${GET_IMAGES_ROAD_ITEM}/${rowId}`); - setImages(response.data.data); - } catch (error) { - } finally { - setLoadingImages(false); - } - }; - - fetchData(); - }, [rowId]); - - useEffect(() => { - const fetchData = async () => { - try { - setLoadingCmmsMachine(true); - const response = await requestServer(`${GET_CMMS_MACHINE_ROAD_ITEM}/${rowId}`); - setCmmsMachine(response.data.data); - } catch (error) { - } finally { - setLoadingCmmsMachine(false); - } - }; - - fetchData(); - }, [rowId]); - - useEffect(() => { - const fetchData = async () => { - try { - setLoadingRahdaran(true); - const response = await requestServer(`${GET_RAHDARAN_ROAD_ITEM}/${rowId}`); - setRahdaran(response.data.data); - } catch (error) { - } finally { - setLoadingRahdaran(false); - } - }; - - fetchData(); - }, [rowId]); - - const HandleSubmit = async ({ result }) => { - const formData = new FormData(); - for (const [key, value] of Object.entries(result)) { - formData.append(key, value); - } - await requestServer(`${UPDATE_ROAD_ITEMS}/${rowId}`, "post", { - data: formData, - notificationSuccess: true, - hasSidebarUpdate: true, - }) - .then((response) => { - mutate(); - setOpenEditDialog(false); - }) - .catch((error) => {}); - }; - - return loadingImages || loadingCmmsMachine || loadingRahdaran ? ( - - ) : images && cmmsMachine && rahdaran ? ( - - ) : ( - - تمامی اطلاعات یافت نشد! - - ); -}; -export default EditController; +import DialogLoading from "@/core/components/DialogLoading"; +import { + GET_CMMS_MACHINE_ROAD_ITEM, + GET_IMAGES_ROAD_ITEM, + GET_RAHDARAN_ROAD_ITEM, + UPDATE_ROAD_ITEMS, +} from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { Typography } from "@mui/material"; +import { useEffect, useState } from "react"; +import EditFormContent from "./EditFormContent"; + +const EditController = ({ rowId, mutate, setOpenEditDialog, openEditDialog, row }) => { + const requestServer = useRequest(); + const [loadingImages, setLoadingImages] = useState(true); + const [images, setImages] = useState(null); + const [loadingCmmsMachine, setLoadingCmmsMachine] = useState(true); + const [cmmsMachine, setCmmsMachine] = useState(null); + const [loadingRahdaran, setLoadingRahdaran] = useState(true); + const [rahdaran, setRahdaran] = useState(null); + + useEffect(() => { + const fetchData = async () => { + try { + setLoadingImages(true); + const response = await requestServer(`${GET_IMAGES_ROAD_ITEM}/${rowId}`); + setImages(response.data.data); + } catch (error) { + } finally { + setLoadingImages(false); + } + }; + + fetchData(); + }, [rowId]); + + useEffect(() => { + const fetchData = async () => { + try { + setLoadingCmmsMachine(true); + const response = await requestServer(`${GET_CMMS_MACHINE_ROAD_ITEM}/${rowId}`); + setCmmsMachine(response.data.data); + } catch (error) { + } finally { + setLoadingCmmsMachine(false); + } + }; + + fetchData(); + }, [rowId]); + + useEffect(() => { + const fetchData = async () => { + try { + setLoadingRahdaran(true); + const response = await requestServer(`${GET_RAHDARAN_ROAD_ITEM}/${rowId}`); + setRahdaran(response.data.data); + } catch (error) { + } finally { + setLoadingRahdaran(false); + } + }; + + fetchData(); + }, [rowId]); + + const HandleSubmit = async ({ result }) => { + const formData = new FormData(); + for (const [key, value] of Object.entries(result)) { + formData.append(key, value); + } + await requestServer(`${UPDATE_ROAD_ITEMS}/${rowId}`, "post", { + data: formData, + notificationSuccess: true, + hasSidebarUpdate: true, + }) + .then((response) => { + mutate(); + setOpenEditDialog(false); + }) + .catch((error) => {}); + }; + + return loadingImages || loadingCmmsMachine || loadingRahdaran ? ( + + ) : images && cmmsMachine && rahdaran ? ( + + ) : ( + + تمامی اطلاعات یافت نشد! + + ); +}; +export default EditController; diff --git a/src/components/dashboard/roadItems/operator/RowActions/EditForm/EditFormContent.jsx b/src/components/dashboard/roadItems/operator/RowActions/EditForm/EditFormContent.jsx index 57fe5aa..40bfff2 100644 --- a/src/components/dashboard/roadItems/operator/RowActions/EditForm/EditFormContent.jsx +++ b/src/components/dashboard/roadItems/operator/RowActions/EditForm/EditFormContent.jsx @@ -1,97 +1,97 @@ -import EditFormCreate from "@/components/dashboard/roadItems/operator/RowActions/EditForm/EditFormCreate"; -import DialogLoading from "@/core/components/DialogLoading"; -import useRoadItemGetISubtems from "@/lib/hooks/useRoadItemGetISubtems"; -import { LinearProgress, Typography } from "@mui/material"; - -const EditFormContent = ({ setOpenEditDialog, onSubmit, defaultData, is_gasht }) => { - const { subItemsList, loadingSubItemsList, errorSubItemsList } = useRoadItemGetISubtems(defaultData?.item_id); - const subItem = subItemsList.find((SubItem) => SubItem.sub_item === defaultData?.sub_item_id); - - const defaultValues = { - before_image: defaultData?.before_image || null, - after_image: defaultData?.after_image || null, - amount: defaultData?.amount || null, - start_point: defaultData?.start_point || { lat: "", lng: "" }, - end_point: defaultData?.end_point || { lat: "", lng: "" }, - ...(!is_gasht && { - cmms_machines: defaultData?.cmms_machines || null, - rahdaran_id: defaultData?.rahdaran_id || null, - }), - }; - - const onSubmitBase = async (data) => { - let result = { ...data }; - if (result.before_image === null || typeof result.before_image === "string") { - delete result.before_image; - delete data.before_image; - } - - if (result.after_image === null || typeof result.after_image === "string") { - delete result.after_image; - delete data.after_image; - } - - if (result.end_point === "") { - delete result.end_point; - delete data.end_point; - } else { - result.end_point = `${result.end_point.lat},${result.end_point.lng}`; - } - - if (result.start_point === "") { - delete result.start_point; - delete data.start_point; - } else { - result.start_point = `${result.start_point.lat},${result.start_point.lng}`; - } - - if (!is_gasht) { - result.rahdaran_id.forEach((rahdar, index) => { - result[`rahdaran_id[${index}]`] = rahdar.id; - }); - delete result.rahdaran_id; - - result.cmms_machines.forEach((cmms_machine, index) => { - result[`machines_id[${index}]`] = cmms_machine.id; - }); - delete result.cmms_machines; - } else { - delete result.rahdaran_id; - delete result.cmms_machines; - } - - await onSubmit({ - result, - data: { - ...data, - item_name: subItem.item_str, - sub_item_name: subItem.name, - unit_fa: subItem.unit, - item_id: subItem.item, - sub_item_id: subItem.sub_item, - }, - }); - }; - - return ( - <> - {errorSubItemsList ? ( - - خطا در دریافت اطلاعات!!! - - ) : loadingSubItemsList ? ( - - ) : ( - - )} - - ); -}; -export default EditFormContent; +import EditFormCreate from "@/components/dashboard/roadItems/operator/RowActions/EditForm/EditFormCreate"; +import DialogLoading from "@/core/components/DialogLoading"; +import useRoadItemGetISubtems from "@/lib/hooks/useRoadItemGetISubtems"; +import { LinearProgress, Typography } from "@mui/material"; + +const EditFormContent = ({ setOpenEditDialog, onSubmit, defaultData, is_gasht }) => { + const { subItemsList, loadingSubItemsList, errorSubItemsList } = useRoadItemGetISubtems(defaultData?.item_id); + const subItem = subItemsList.find((SubItem) => SubItem.sub_item === defaultData?.sub_item_id); + + const defaultValues = { + before_image: defaultData?.before_image || null, + after_image: defaultData?.after_image || null, + amount: defaultData?.amount || null, + start_point: defaultData?.start_point || { lat: "", lng: "" }, + end_point: defaultData?.end_point || { lat: "", lng: "" }, + ...(!is_gasht && { + cmms_machines: defaultData?.cmms_machines || null, + rahdaran_id: defaultData?.rahdaran_id || null, + }), + }; + + const onSubmitBase = async (data) => { + let result = { ...data }; + if (result.before_image === null || typeof result.before_image === "string") { + delete result.before_image; + delete data.before_image; + } + + if (result.after_image === null || typeof result.after_image === "string") { + delete result.after_image; + delete data.after_image; + } + + if (result.end_point === "") { + delete result.end_point; + delete data.end_point; + } else { + result.end_point = `${result.end_point.lat},${result.end_point.lng}`; + } + + if (result.start_point === "") { + delete result.start_point; + delete data.start_point; + } else { + result.start_point = `${result.start_point.lat},${result.start_point.lng}`; + } + + if (!is_gasht) { + result.rahdaran_id.forEach((rahdar, index) => { + result[`rahdaran_id[${index}]`] = rahdar.id; + }); + delete result.rahdaran_id; + + result.cmms_machines.forEach((cmms_machine, index) => { + result[`machines_id[${index}]`] = cmms_machine.id; + }); + delete result.cmms_machines; + } else { + delete result.rahdaran_id; + delete result.cmms_machines; + } + + await onSubmit({ + result, + data: { + ...data, + item_name: subItem.item_str, + sub_item_name: subItem.name, + unit_fa: subItem.unit, + item_id: subItem.item, + sub_item_id: subItem.sub_item, + }, + }); + }; + + return ( + <> + {errorSubItemsList ? ( + + خطا در دریافت اطلاعات!!! + + ) : loadingSubItemsList ? ( + + ) : ( + + )} + + ); +}; +export default EditFormContent; diff --git a/src/components/dashboard/roadItems/operator/RowActions/EditForm/EditFormCreate.jsx b/src/components/dashboard/roadItems/operator/RowActions/EditForm/EditFormCreate.jsx index 4a3e6f6..4004086 100644 --- a/src/components/dashboard/roadItems/operator/RowActions/EditForm/EditFormCreate.jsx +++ b/src/components/dashboard/roadItems/operator/RowActions/EditForm/EditFormCreate.jsx @@ -1,198 +1,198 @@ -import { Button, DialogActions, DialogContent, Stack } from "@mui/material"; -import ImageUpload from "@/components/dashboard/roadItems/operator/Actions/Create/Forms/ImageUpload"; -import NumberField from "@/core/components/NumberField"; -import { Controller, useForm } from "react-hook-form"; -import CarCode from "@/core/components/CarCode"; -import RahdarCode from "@/core/components/RahdarCode"; -import MapInfoTwoMarker from "@/core/components/MapInfoTwoMarker"; -import MapInfoOneMarker from "@/core/components/MapInfoOneMarker"; -import StyledForm from "@/core/components/StyledForm"; -import React from "react"; -import { yupResolver } from "@hookform/resolvers/yup"; -import { array, mixed, object, string } from "yup"; - -const validationSchema = object({ - amount: string().required("وارد کردن مقدار الزامیست!"), - cmms_machines: array() - .test("cmms-machines-conditional", "وارد کردن کد خودرو الزامیست!", function (value) { - const { is_gasht } = this.options.context; - if (is_gasht) { - return true; // اگر is_gasht true باشد، این فیلد نیاز به اعتبارسنجی ندارد - } - return Array.isArray(value) && value.length > 0; // حداقل یک کد باید وجود داشته باشد - }) - .min(1, "حداقل یک کد خودرو باید وارد شود!"), // پیام خطا برای زمانی که شرط تست برقرار باشد - rahdaran_id: array() - .test("rahdaran-id-conditional", "وارد کردن کد راهداران الزامیست!", function (value) { - const { is_gasht } = this.options.context; - if (is_gasht) { - return true; // اگر is_gasht true باشد، این فیلد نیاز به اعتبارسنجی ندارد - } - return Array.isArray(value) && value.length > 0; // حداقل یک کد باید وجود داشته باشد - }) - .min(1, "حداقل یک کد راهدار باید وارد شود!"), - before_image: mixed() - .nullable() - .test("before-image-required", "لطفا عکس قبل از اقدام را بارگذاری کنید!", function (value) { - const { subItem } = this.options.context; - const needsImage = subItem?.needs_image === 1; - if (needsImage) { - return !!value; - } - return true; - }), - after_image: mixed() - .nullable() - .test("after-image-required", "لطفا عکس بعد از اقدام را بارگذاری کنید!", function (value) { - const { subItem } = this.options.context; - const needsImage = subItem?.needs_image === 1; - if (needsImage) { - return !!value; - } - return true; - }), - start_point: mixed() - .test("start-point-required", "لطفاً نقطه شروع را مشخص کنید!", function (value) { - return !!value; // چک می‌کند که مقدار موجود است - }) - .required("لطفاً نقطه شروع را مشخص کنید!"), - end_point: mixed().test("end-point-required", "لطفاً نقطه پایان را مشخص کنید!", function (value) { - const { subItem } = this.options.context; - const needsEndPoint = subItem?.needs_end_point === 1; - if (needsEndPoint) { - return !!value; - } - return true; - }), -}); - -const EditFormCreate = ({ defaultData, subItem, onSubmitBase, defaultValues, setOpenEditDialog, is_gasht }) => { - const { - control, - getValues, - watch, - register, - handleSubmit, - setValue, - formState: { errors, isSubmitting }, - } = useForm({ - defaultValues, - resolver: yupResolver(validationSchema), - mode: "all", - context: { subItem, is_gasht }, - }); - - return ( - - - - - {subItem.needs_image === 1 ? ( - - ) : null} - - - { - if (!isNaN(event.target.value)) { - setValue("amount", event.target.value); - } else { - setValue("amount", watch("amount")); - } - }} - helperText={errors.amount ? errors.amount.message : null} - variant="outlined" - fullWidth - /> - - {!is_gasht && ( - - { - return ( - field.onChange(value || [])} - inputValueDefault={defaultData?.cmms_machines} - multiple={true} - error={error} // اگر خطا وجود داشته باشد - /> - ); - }} - name={"cmms_machines"} - /> - - )} - {!is_gasht && ( - - { - return ( - field.onChange(value || [])} - error={error} - /> - ); - }} - name={"rahdaran_id"} - /> - - )} - - {subItem.needs_end_point === 1 ? ( - - ) : ( - - )} - - - - - - - - - ); -}; -export default EditFormCreate; +import { Button, DialogActions, DialogContent, Stack } from "@mui/material"; +import ImageUpload from "@/components/dashboard/roadItems/operator/Actions/Create/Forms/ImageUpload"; +import NumberField from "@/core/components/NumberField"; +import { Controller, useForm } from "react-hook-form"; +import CarCode from "@/core/components/CarCode"; +import RahdarCode from "@/core/components/RahdarCode"; +import MapInfoTwoMarker from "@/core/components/MapInfoTwoMarker"; +import MapInfoOneMarker from "@/core/components/MapInfoOneMarker"; +import StyledForm from "@/core/components/StyledForm"; +import React from "react"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { array, mixed, object, string } from "yup"; + +const validationSchema = object({ + amount: string().required("وارد کردن مقدار الزامیست!"), + cmms_machines: array() + .test("cmms-machines-conditional", "وارد کردن کد خودرو الزامیست!", function (value) { + const { is_gasht } = this.options.context; + if (is_gasht) { + return true; // اگر is_gasht true باشد، این فیلد نیاز به اعتبارسنجی ندارد + } + return Array.isArray(value) && value.length > 0; // حداقل یک کد باید وجود داشته باشد + }) + .min(1, "حداقل یک کد خودرو باید وارد شود!"), // پیام خطا برای زمانی که شرط تست برقرار باشد + rahdaran_id: array() + .test("rahdaran-id-conditional", "وارد کردن کد راهداران الزامیست!", function (value) { + const { is_gasht } = this.options.context; + if (is_gasht) { + return true; // اگر is_gasht true باشد، این فیلد نیاز به اعتبارسنجی ندارد + } + return Array.isArray(value) && value.length > 0; // حداقل یک کد باید وجود داشته باشد + }) + .min(1, "حداقل یک کد راهدار باید وارد شود!"), + before_image: mixed() + .nullable() + .test("before-image-required", "لطفا عکس قبل از اقدام را بارگذاری کنید!", function (value) { + const { subItem } = this.options.context; + const needsImage = subItem?.needs_image === 1; + if (needsImage) { + return !!value; + } + return true; + }), + after_image: mixed() + .nullable() + .test("after-image-required", "لطفا عکس بعد از اقدام را بارگذاری کنید!", function (value) { + const { subItem } = this.options.context; + const needsImage = subItem?.needs_image === 1; + if (needsImage) { + return !!value; + } + return true; + }), + start_point: mixed() + .test("start-point-required", "لطفاً نقطه شروع را مشخص کنید!", function (value) { + return !!value; // چک می‌کند که مقدار موجود است + }) + .required("لطفاً نقطه شروع را مشخص کنید!"), + end_point: mixed().test("end-point-required", "لطفاً نقطه پایان را مشخص کنید!", function (value) { + const { subItem } = this.options.context; + const needsEndPoint = subItem?.needs_end_point === 1; + if (needsEndPoint) { + return !!value; + } + return true; + }), +}); + +const EditFormCreate = ({ defaultData, subItem, onSubmitBase, defaultValues, setOpenEditDialog, is_gasht }) => { + const { + control, + getValues, + watch, + register, + handleSubmit, + setValue, + formState: { errors, isSubmitting }, + } = useForm({ + defaultValues, + resolver: yupResolver(validationSchema), + mode: "all", + context: { subItem, is_gasht }, + }); + + return ( + + + + + {subItem.needs_image === 1 ? ( + + ) : null} + + + { + if (!isNaN(event.target.value)) { + setValue("amount", event.target.value); + } else { + setValue("amount", watch("amount")); + } + }} + helperText={errors.amount ? errors.amount.message : null} + variant="outlined" + fullWidth + /> + + {!is_gasht && ( + + { + return ( + field.onChange(value || [])} + inputValueDefault={defaultData?.cmms_machines} + multiple={true} + error={error} // اگر خطا وجود داشته باشد + /> + ); + }} + name={"cmms_machines"} + /> + + )} + {!is_gasht && ( + + { + return ( + field.onChange(value || [])} + error={error} + /> + ); + }} + name={"rahdaran_id"} + /> + + )} + + {subItem.needs_end_point === 1 ? ( + + ) : ( + + )} + + + + + + + + + ); +}; +export default EditFormCreate; diff --git a/src/components/dashboard/roadItems/operator/RowActions/EditForm/index.jsx b/src/components/dashboard/roadItems/operator/RowActions/EditForm/index.jsx index 4548f15..9b0d343 100644 --- a/src/components/dashboard/roadItems/operator/RowActions/EditForm/index.jsx +++ b/src/components/dashboard/roadItems/operator/RowActions/EditForm/index.jsx @@ -1,60 +1,60 @@ -import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import BorderColorIcon from "@mui/icons-material/BorderColor"; -import EditController from "./EditController"; -import CloseIcon from "@mui/icons-material/Close"; - -const EditForm = ({ row, mutate, rowId }) => { - const [openEditDialog, setOpenEditDialog] = useState(false); - - return ( - <> - - { - setOpenEditDialog(true); - }} - > - - - - - ویرایش اطلاعات - setOpenEditDialog(false)} - sx={(theme) => ({ - position: "absolute", - right: 8, - top: 8, - zIndex: 50, - color: theme.palette.grey[500], - })} - > - - - {openEditDialog && ( - - )} - - - ); -}; -export default EditForm; +import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import BorderColorIcon from "@mui/icons-material/BorderColor"; +import EditController from "./EditController"; +import CloseIcon from "@mui/icons-material/Close"; + +const EditForm = ({ row, mutate, rowId }) => { + const [openEditDialog, setOpenEditDialog] = useState(false); + + return ( + <> + + { + setOpenEditDialog(true); + }} + > + + + + + ویرایش اطلاعات + setOpenEditDialog(false)} + sx={(theme) => ({ + position: "absolute", + right: 8, + top: 8, + zIndex: 50, + color: theme.palette.grey[500], + })} + > + + + {openEditDialog && ( + + )} + + + ); +}; +export default EditForm; diff --git a/src/components/dashboard/roadItems/operator/RowActions/ImageForm/ImageFormContent.jsx b/src/components/dashboard/roadItems/operator/RowActions/ImageForm/ImageFormContent.jsx index c8f22d0..f8fd088 100644 --- a/src/components/dashboard/roadItems/operator/RowActions/ImageForm/ImageFormContent.jsx +++ b/src/components/dashboard/roadItems/operator/RowActions/ImageForm/ImageFormContent.jsx @@ -1,45 +1,45 @@ -import { Box, Stack, Typography, useTheme } from "@mui/material"; -import Image from "next/image"; - -const ImageFormContent = ({ image, title }) => { - const theme = useTheme(); - return ( - - - {title} - - - Image - - - ); -}; -export default ImageFormContent; +import { Box, Stack, Typography, useTheme } from "@mui/material"; +import Image from "next/image"; + +const ImageFormContent = ({ image, title }) => { + const theme = useTheme(); + return ( + + + {title} + + + Image + + + ); +}; +export default ImageFormContent; diff --git a/src/components/dashboard/roadItems/operator/RowActions/ImageForm/ImagesContent.jsx b/src/components/dashboard/roadItems/operator/RowActions/ImageForm/ImagesContent.jsx index 6414e24..7c88f12 100644 --- a/src/components/dashboard/roadItems/operator/RowActions/ImageForm/ImagesContent.jsx +++ b/src/components/dashboard/roadItems/operator/RowActions/ImageForm/ImagesContent.jsx @@ -1,43 +1,43 @@ -import { useEffect, useState } from "react"; -import ImageFormContent from "./ImageFormContent"; -import DialogLoading from "@/core/components/DialogLoading"; -import useRequest from "@/lib/hooks/useRequest"; -import { GET_IMAGES_ROAD_ITEM } from "@/core/utils/routes"; -import { Typography } from "@mui/material"; - -const ImagesContent = ({ rowId }) => { - const [loading, setLoading] = useState(true); - const [data, setData] = useState(null); - const request = useRequest(); - - useEffect(() => { - const fetchData = async () => { - try { - setLoading(true); - const response = await request(`${GET_IMAGES_ROAD_ITEM}/${rowId}`); - setData(response.data.data); - } catch (error) { - } finally { - setLoading(false); - } - }; - - fetchData(); - }, [rowId]); - - return ( - <> - {loading ? ( - - ) : data ? ( - <> - - - - ) : ( - تصویری در سامانه یافت نشد - )} - - ); -}; -export default ImagesContent; +import { useEffect, useState } from "react"; +import ImageFormContent from "./ImageFormContent"; +import DialogLoading from "@/core/components/DialogLoading"; +import useRequest from "@/lib/hooks/useRequest"; +import { GET_IMAGES_ROAD_ITEM } from "@/core/utils/routes"; +import { Typography } from "@mui/material"; + +const ImagesContent = ({ rowId }) => { + const [loading, setLoading] = useState(true); + const [data, setData] = useState(null); + const request = useRequest(); + + useEffect(() => { + const fetchData = async () => { + try { + setLoading(true); + const response = await request(`${GET_IMAGES_ROAD_ITEM}/${rowId}`); + setData(response.data.data); + } catch (error) { + } finally { + setLoading(false); + } + }; + + fetchData(); + }, [rowId]); + + return ( + <> + {loading ? ( + + ) : data ? ( + <> + + + + ) : ( + تصویری در سامانه یافت نشد + )} + + ); +}; +export default ImagesContent; diff --git a/src/components/dashboard/roadItems/operator/RowActions/ImageForm/index.jsx b/src/components/dashboard/roadItems/operator/RowActions/ImageForm/index.jsx index 08e9cd9..5080908 100644 --- a/src/components/dashboard/roadItems/operator/RowActions/ImageForm/index.jsx +++ b/src/components/dashboard/roadItems/operator/RowActions/ImageForm/index.jsx @@ -1,40 +1,40 @@ -import PhotoLibraryIcon from "@mui/icons-material/PhotoLibrary"; -import { Button, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import ImagesContent from "./ImagesContent"; - -const ImageDialog = ({ rowId }) => { - const [openImageDialog, setOpenImageDialog] = useState(false); - - return ( - <> - - setOpenImageDialog(true)}> - - - - setOpenImageDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - maxWidth={"sm"} - scroll="paper" - > - تصاویر - {openImageDialog && } - - - - - - ); -}; - -export default ImageDialog; +import PhotoLibraryIcon from "@mui/icons-material/PhotoLibrary"; +import { Button, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import ImagesContent from "./ImagesContent"; + +const ImageDialog = ({ rowId }) => { + const [openImageDialog, setOpenImageDialog] = useState(false); + + return ( + <> + + setOpenImageDialog(true)}> + + + + setOpenImageDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + maxWidth={"sm"} + scroll="paper" + > + تصاویر + {openImageDialog && } + + + + + + ); +}; + +export default ImageDialog; diff --git a/src/components/dashboard/roadItems/operator/RowActions/LocationForm/LocationFormContent.jsx b/src/components/dashboard/roadItems/operator/RowActions/LocationForm/LocationFormContent.jsx index 14b3db3..08e4730 100644 --- a/src/components/dashboard/roadItems/operator/RowActions/LocationForm/LocationFormContent.jsx +++ b/src/components/dashboard/roadItems/operator/RowActions/LocationForm/LocationFormContent.jsx @@ -1,35 +1,35 @@ -"use client"; -import { Box, Button, DialogActions, DialogContent, Stack } from "@mui/material"; -import React from "react"; -import dynamic from "next/dynamic"; -import MapLoading from "@/core/components/MapLayer/Loading"; -import ShowLocationMarker from "@/core/components/ShowLocationMarker"; -const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { - loading: () => , - ssr: false, -}); - -const LocationFormContent = ({ setOpenLocationDialog, start_lat, start_lng, end_lat, end_lng }) => { - return ( - <> - - - - - - - - - - - - ); -}; -export default LocationFormContent; +"use client"; +import { Box, Button, DialogActions, DialogContent, Stack } from "@mui/material"; +import React from "react"; +import dynamic from "next/dynamic"; +import MapLoading from "@/core/components/MapLayer/Loading"; +import ShowLocationMarker from "@/core/components/ShowLocationMarker"; +const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { + loading: () => , + ssr: false, +}); + +const LocationFormContent = ({ setOpenLocationDialog, start_lat, start_lng, end_lat, end_lng }) => { + return ( + <> + + + + + + + + + + + + ); +}; +export default LocationFormContent; diff --git a/src/components/dashboard/roadItems/operator/RowActions/LocationForm/index.jsx b/src/components/dashboard/roadItems/operator/RowActions/LocationForm/index.jsx index f578ca8..90a5cb4 100644 --- a/src/components/dashboard/roadItems/operator/RowActions/LocationForm/index.jsx +++ b/src/components/dashboard/roadItems/operator/RowActions/LocationForm/index.jsx @@ -1,38 +1,38 @@ -import React, { useState } from "react"; -import { Tooltip, IconButton, Dialog, DialogTitle } from "@mui/material"; -import ExploreIcon from "@mui/icons-material/Explore"; -import LocationFormContent from "./LocationFormContent"; -const LocationForm = ({ start_lat, start_lng, end_lat, end_lng }) => { - const [openLocationDialog, setOpenLocationDialog] = useState(false); - - return ( - <> - - setOpenLocationDialog(true)}> - - - - setOpenLocationDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - موقعیت - - - - ); -}; -export default LocationForm; +import React, { useState } from "react"; +import { Tooltip, IconButton, Dialog, DialogTitle } from "@mui/material"; +import ExploreIcon from "@mui/icons-material/Explore"; +import LocationFormContent from "./LocationFormContent"; +const LocationForm = ({ start_lat, start_lng, end_lat, end_lng }) => { + const [openLocationDialog, setOpenLocationDialog] = useState(false); + + return ( + <> + + setOpenLocationDialog(true)}> + + + + setOpenLocationDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + موقعیت + + + + ); +}; +export default LocationForm; diff --git a/src/components/dashboard/roadItems/operator/RowActions/MachinesCodeForm/MachinesCodeContent.jsx b/src/components/dashboard/roadItems/operator/RowActions/MachinesCodeForm/MachinesCodeContent.jsx index c71be76..3c627f9 100644 --- a/src/components/dashboard/roadItems/operator/RowActions/MachinesCodeForm/MachinesCodeContent.jsx +++ b/src/components/dashboard/roadItems/operator/RowActions/MachinesCodeForm/MachinesCodeContent.jsx @@ -1,79 +1,79 @@ -import DialogLoading from "@/core/components/DialogLoading"; -import ShowPlak from "@/core/components/ShowPlak"; -import { GET_CMMS_MACHINE_ROAD_ITEM } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { - DialogContent, - Table, - TableBody, - TableCell, - TableContainer, - TableHead, - TableRow, - Typography, -} from "@mui/material"; -import { useEffect, useState } from "react"; - -const MachinesCodeContent = ({ rowId }) => { - const [loading, setLoading] = useState(true); - const [data, setData] = useState(null); - const request = useRequest(); - - useEffect(() => { - const fetchData = async () => { - try { - setLoading(true); - const response = await request(`${GET_CMMS_MACHINE_ROAD_ITEM}/${rowId}`); - setData(response.data.data); - } catch (error) { - } finally { - setLoading(false); - } - }; - - fetchData(); - }, [rowId]); - - return ( - <> - - {loading ? ( - - ) : data ? ( - - - - - کد ماشین - نام خودرو - پلاک - - - - {data.map((machine) => { - return ( - - {machine.machine_code} - {machine.car_name} - - {machine.plak_number ? ( - - ) : null} - - - ); - })} - -
    -
    - ) : ( - اطلاعات خودرویی در سامانه یافت نشد - )} -
    - - ); -}; -export default MachinesCodeContent; +import DialogLoading from "@/core/components/DialogLoading"; +import ShowPlak from "@/core/components/ShowPlak"; +import { GET_CMMS_MACHINE_ROAD_ITEM } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { + DialogContent, + Table, + TableBody, + TableCell, + TableContainer, + TableHead, + TableRow, + Typography, +} from "@mui/material"; +import { useEffect, useState } from "react"; + +const MachinesCodeContent = ({ rowId }) => { + const [loading, setLoading] = useState(true); + const [data, setData] = useState(null); + const request = useRequest(); + + useEffect(() => { + const fetchData = async () => { + try { + setLoading(true); + const response = await request(`${GET_CMMS_MACHINE_ROAD_ITEM}/${rowId}`); + setData(response.data.data); + } catch (error) { + } finally { + setLoading(false); + } + }; + + fetchData(); + }, [rowId]); + + return ( + <> + + {loading ? ( + + ) : data ? ( + + + + + کد ماشین + نام خودرو + پلاک + + + + {data.map((machine) => { + return ( + + {machine.machine_code} + {machine.car_name} + + {machine.plak_number ? ( + + ) : null} + + + ); + })} + +
    +
    + ) : ( + اطلاعات خودرویی در سامانه یافت نشد + )} +
    + + ); +}; +export default MachinesCodeContent; diff --git a/src/components/dashboard/roadItems/operator/RowActions/MachinesCodeForm/index.jsx b/src/components/dashboard/roadItems/operator/RowActions/MachinesCodeForm/index.jsx index 685fd06..fc0ce01 100644 --- a/src/components/dashboard/roadItems/operator/RowActions/MachinesCodeForm/index.jsx +++ b/src/components/dashboard/roadItems/operator/RowActions/MachinesCodeForm/index.jsx @@ -1,43 +1,43 @@ -import { Button, Dialog, DialogActions, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import DirectionsCarIcon from "@mui/icons-material/DirectionsCar"; -import { useState } from "react"; -import MachinesCodeContent from "./MachinesCodeContent"; - -const MachinesCodeDialog = ({ rowId }) => { - const [openMachinesCodeDialog, setOpenMachinesCodeDialog] = useState(false); - return ( - <> - - setOpenMachinesCodeDialog(true)}> - - - - setOpenMachinesCodeDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - خودرو ها - {openMachinesCodeDialog && } - - - - - - ); -}; -export default MachinesCodeDialog; +import { Button, Dialog, DialogActions, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import DirectionsCarIcon from "@mui/icons-material/DirectionsCar"; +import { useState } from "react"; +import MachinesCodeContent from "./MachinesCodeContent"; + +const MachinesCodeDialog = ({ rowId }) => { + const [openMachinesCodeDialog, setOpenMachinesCodeDialog] = useState(false); + return ( + <> + + setOpenMachinesCodeDialog(true)}> + + + + setOpenMachinesCodeDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + خودرو ها + {openMachinesCodeDialog && } + + + + + + ); +}; +export default MachinesCodeDialog; diff --git a/src/components/dashboard/roadItems/operator/RowActions/RahdaranForm/RahdaranContent.jsx b/src/components/dashboard/roadItems/operator/RowActions/RahdaranForm/RahdaranContent.jsx index c4e562f..0706033 100644 --- a/src/components/dashboard/roadItems/operator/RowActions/RahdaranForm/RahdaranContent.jsx +++ b/src/components/dashboard/roadItems/operator/RowActions/RahdaranForm/RahdaranContent.jsx @@ -1,72 +1,72 @@ -import DialogLoading from "@/core/components/DialogLoading"; -import { GET_RAHDARAN_ROAD_ITEM } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { - DialogContent, - Table, - TableBody, - TableCell, - TableContainer, - TableHead, - TableRow, - Typography, -} from "@mui/material"; -import { useEffect, useState } from "react"; - -const RahdaranContent = ({ rowId }) => { - const [loading, setLoading] = useState(true); - const [data, setData] = useState(null); - const request = useRequest(); - - useEffect(() => { - const fetchData = async () => { - try { - setLoading(true); - const response = await request(`${GET_RAHDARAN_ROAD_ITEM}/${rowId}`); - setData(response.data.data); - } catch (error) { - } finally { - setLoading(false); - } - }; - - fetchData(); - }, [rowId]); - - return ( - <> - - {loading ? ( - - ) : data ? ( - - - - - کد راهدار - نام - - - - {data.map((rahdar) => { - return ( - - {rahdar.code} - {rahdar.name} - - ); - })} - -
    -
    - ) : ( - اطلاعات راهداران در سامانه یافت نشد - )} -
    - - ); -}; -export default RahdaranContent; +import DialogLoading from "@/core/components/DialogLoading"; +import { GET_RAHDARAN_ROAD_ITEM } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { + DialogContent, + Table, + TableBody, + TableCell, + TableContainer, + TableHead, + TableRow, + Typography, +} from "@mui/material"; +import { useEffect, useState } from "react"; + +const RahdaranContent = ({ rowId }) => { + const [loading, setLoading] = useState(true); + const [data, setData] = useState(null); + const request = useRequest(); + + useEffect(() => { + const fetchData = async () => { + try { + setLoading(true); + const response = await request(`${GET_RAHDARAN_ROAD_ITEM}/${rowId}`); + setData(response.data.data); + } catch (error) { + } finally { + setLoading(false); + } + }; + + fetchData(); + }, [rowId]); + + return ( + <> + + {loading ? ( + + ) : data ? ( + + + + + کد راهدار + نام + + + + {data.map((rahdar) => { + return ( + + {rahdar.code} + {rahdar.name} + + ); + })} + +
    +
    + ) : ( + اطلاعات راهداران در سامانه یافت نشد + )} +
    + + ); +}; +export default RahdaranContent; diff --git a/src/components/dashboard/roadItems/operator/RowActions/RahdaranForm/index.jsx b/src/components/dashboard/roadItems/operator/RowActions/RahdaranForm/index.jsx index e3a2efc..a051c23 100644 --- a/src/components/dashboard/roadItems/operator/RowActions/RahdaranForm/index.jsx +++ b/src/components/dashboard/roadItems/operator/RowActions/RahdaranForm/index.jsx @@ -1,38 +1,38 @@ -import { Button, Dialog, DialogActions, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import GroupsIcon from "@mui/icons-material/Groups"; -import { useState } from "react"; -import RahdaranContent from "./RahdaranContent"; - -const RahdaranDialog = ({ rowId }) => { - const [openRahdaranDialog, setOpenRahdaranDialog] = useState(false); - return ( - <> - - setOpenRahdaranDialog(true)}> - - - - setOpenRahdaranDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - لیست راهداران - {openRahdaranDialog && } - - - - - - ); -}; -export default RahdaranDialog; +import { Button, Dialog, DialogActions, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import GroupsIcon from "@mui/icons-material/Groups"; +import { useState } from "react"; +import RahdaranContent from "./RahdaranContent"; + +const RahdaranDialog = ({ rowId }) => { + const [openRahdaranDialog, setOpenRahdaranDialog] = useState(false); + return ( + <> + + setOpenRahdaranDialog(true)}> + + + + setOpenRahdaranDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + لیست راهداران + {openRahdaranDialog && } + + + + + + ); +}; +export default RahdaranDialog; diff --git a/src/components/dashboard/roadItems/operator/RowActions/index.jsx b/src/components/dashboard/roadItems/operator/RowActions/index.jsx index 9e22226..0ac4dd7 100644 --- a/src/components/dashboard/roadItems/operator/RowActions/index.jsx +++ b/src/components/dashboard/roadItems/operator/RowActions/index.jsx @@ -1,11 +1,11 @@ -import { Box } from "@mui/material"; -import EditForm from "./EditForm"; - -const RowActions = ({ row, mutate }) => { - return ( - - {row.original.status === 2 && } - - ); -}; -export default RowActions; +import { Box } from "@mui/material"; +import EditForm from "./EditForm"; + +const RowActions = ({ row, mutate }) => { + return ( + + {row.original.status === 2 && } + + ); +}; +export default RowActions; diff --git a/src/components/dashboard/roadItems/operator/Toolbar.jsx b/src/components/dashboard/roadItems/operator/Toolbar.jsx index 37c8646..296cb65 100644 --- a/src/components/dashboard/roadItems/operator/Toolbar.jsx +++ b/src/components/dashboard/roadItems/operator/Toolbar.jsx @@ -1,15 +1,15 @@ -import PrintExcel from "./ExcelPrint"; -import OperatorCreate from "./Actions/Create"; -import { Stack } from "@mui/material"; -import ObservedGashtCreate from "./Actions/ObservedGashtCreate"; - -const Toolbar = ({ table, filterData, mutate }) => { - return ( - - - - - - ); -}; -export default Toolbar; +import PrintExcel from "./ExcelPrint"; +import OperatorCreate from "./Actions/Create"; +import { Stack } from "@mui/material"; +import ObservedGashtCreate from "./Actions/ObservedGashtCreate"; + +const Toolbar = ({ table, filterData, mutate }) => { + return ( + + + + + + ); +}; +export default Toolbar; diff --git a/src/components/dashboard/roadItems/operator/index.jsx b/src/components/dashboard/roadItems/operator/index.jsx index e1ec59d..0929354 100644 --- a/src/components/dashboard/roadItems/operator/index.jsx +++ b/src/components/dashboard/roadItems/operator/index.jsx @@ -1,14 +1,14 @@ -"use client"; -import PageTitle from "@/core/components/PageTitle"; -import { Stack } from "@mui/material"; -import OperatorList from "./OperatorList"; - -const OperatorPage = () => { - return ( - - - - - ); -}; -export default OperatorPage; +"use client"; +import PageTitle from "@/core/components/PageTitle"; +import { Stack } from "@mui/material"; +import OperatorList from "./OperatorList"; + +const OperatorPage = () => { + return ( + + + + + ); +}; +export default OperatorPage; diff --git a/src/components/dashboard/roadItems/reports/ItemsReports/ExcelPrint/index.jsx b/src/components/dashboard/roadItems/reports/ItemsReports/ExcelPrint/index.jsx index bf00587..7649cdb 100644 --- a/src/components/dashboard/roadItems/reports/ItemsReports/ExcelPrint/index.jsx +++ b/src/components/dashboard/roadItems/reports/ItemsReports/ExcelPrint/index.jsx @@ -1,78 +1,78 @@ -"use client"; -import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; -import { useMemo, useState } from "react"; -import moment from "jalali-moment"; -import FileSaver from "file-saver"; -import DescriptionIcon from "@mui/icons-material/Description"; -import useRequest from "@/lib/hooks/useRequest"; -import { - EXPORT_COUNTRY_ROAD_ITEM_REPORTS_PER_ITEM, - EXPORT_PROVINCE_ROAD_ITEM_REPORTS_PER_ITEM, -} from "@/core/utils/routes"; -import { useTheme } from "@emotion/react"; - -const PrintExcel = ({ table, filterData }) => { - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const [loading, setLoading] = useState(false); - const requestServer = useRequest({ notificationSuccess: true }); - const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { - if (filter.value) { - acc.push({ id: filter.id, value: filter.value }); - } - return acc; - }, []); - - const filterParams = useMemo(() => { - const params = new URLSearchParams(); - activeFilters.length > 0 && - activeFilters.map((filter, index) => { - params.set(`${filter.id}`, filter.value); - }); - return params; - }, [activeFilters]); - - const clickHandler = () => { - setLoading(true); - const CountryOrProvince = activeFilters.find((item) => item.id === "province_id"); - const requestUrl = - CountryOrProvince.value === "-1" - ? EXPORT_COUNTRY_ROAD_ITEM_REPORTS_PER_ITEM - : EXPORT_PROVINCE_ROAD_ITEM_REPORTS_PER_ITEM; - - requestServer(`${requestUrl}?${filterParams}`, "get", { - requestOptions: { responseType: "blob" }, - }) - .then((response) => { - const filename = `خروجی کارتابل گزارشات فعالیت روزانه براساس آیتم تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; - FileSaver.saveAs(response.data, filename); - }) - .catch(() => {}) - .finally(() => { - setLoading(false); - }); - }; - - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - - ); -}; -export default PrintExcel; +"use client"; +import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; +import { useMemo, useState } from "react"; +import moment from "jalali-moment"; +import FileSaver from "file-saver"; +import DescriptionIcon from "@mui/icons-material/Description"; +import useRequest from "@/lib/hooks/useRequest"; +import { + EXPORT_COUNTRY_ROAD_ITEM_REPORTS_PER_ITEM, + EXPORT_PROVINCE_ROAD_ITEM_REPORTS_PER_ITEM, +} from "@/core/utils/routes"; +import { useTheme } from "@emotion/react"; + +const PrintExcel = ({ table, filterData }) => { + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const [loading, setLoading] = useState(false); + const requestServer = useRequest({ notificationSuccess: true }); + const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { + if (filter.value) { + acc.push({ id: filter.id, value: filter.value }); + } + return acc; + }, []); + + const filterParams = useMemo(() => { + const params = new URLSearchParams(); + activeFilters.length > 0 && + activeFilters.map((filter, index) => { + params.set(`${filter.id}`, filter.value); + }); + return params; + }, [activeFilters]); + + const clickHandler = () => { + setLoading(true); + const CountryOrProvince = activeFilters.find((item) => item.id === "province_id"); + const requestUrl = + CountryOrProvince.value === "-1" + ? EXPORT_COUNTRY_ROAD_ITEM_REPORTS_PER_ITEM + : EXPORT_PROVINCE_ROAD_ITEM_REPORTS_PER_ITEM; + + requestServer(`${requestUrl}?${filterParams}`, "get", { + requestOptions: { responseType: "blob" }, + }) + .then((response) => { + const filename = `خروجی کارتابل گزارشات فعالیت روزانه براساس آیتم تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; + FileSaver.saveAs(response.data, filename); + }) + .catch(() => {}) + .finally(() => { + setLoading(false); + }); + }; + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + + ); +}; +export default PrintExcel; diff --git a/src/components/dashboard/roadItems/reports/ItemsReports/ReportLists.jsx b/src/components/dashboard/roadItems/reports/ItemsReports/ReportLists.jsx index b739780..3f713a2 100644 --- a/src/components/dashboard/roadItems/reports/ItemsReports/ReportLists.jsx +++ b/src/components/dashboard/roadItems/reports/ItemsReports/ReportLists.jsx @@ -1,96 +1,96 @@ -"use client"; -import DataTableWithAuth from "@/core/components/DataTableWithAuth"; -import { Box } from "@mui/material"; -import { useMemo } from "react"; -import Toolbar from "./TableToolbar"; - -const ReportLists = ({ itemsList, data, specialFilter }) => { - const columns = useMemo(() => { - const dynamicColumns = - itemsList?.map((item) => ({ - accessorKey: `item_${item.id}`, - header: `${item.name}`, - id: `item_${item.id}`, - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - size: 50, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - })) || []; - - return [ - { - accessorKey: "edare_name", - header: "اداره", - id: "edare_name", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - }, - { - accessorKey: "sum", - header: "مجموع", - id: "sum", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - grow: false, - size: 50, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - { - header: "آیتم های فعالیت روزانه", - id: "items", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - columns: [...dynamicColumns], - }, - ]; - }, [itemsList]); - - return ( - - - - ); -}; - -export default ReportLists; +"use client"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import { Box } from "@mui/material"; +import { useMemo } from "react"; +import Toolbar from "./TableToolbar"; + +const ReportLists = ({ itemsList, data, specialFilter }) => { + const columns = useMemo(() => { + const dynamicColumns = + itemsList?.map((item) => ({ + accessorKey: `item_${item.id}`, + header: `${item.name}`, + id: `item_${item.id}`, + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + size: 50, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + })) || []; + + return [ + { + accessorKey: "edare_name", + header: "اداره", + id: "edare_name", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + }, + { + accessorKey: "sum", + header: "مجموع", + id: "sum", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + grow: false, + size: 50, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + { + header: "آیتم های فعالیت روزانه", + id: "items", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + columns: [...dynamicColumns], + }, + ]; + }, [itemsList]); + + return ( + + + + ); +}; + +export default ReportLists; diff --git a/src/components/dashboard/roadItems/reports/ItemsReports/Search/FromDateController.jsx b/src/components/dashboard/roadItems/reports/ItemsReports/Search/FromDateController.jsx index 2e23def..562bf68 100644 --- a/src/components/dashboard/roadItems/reports/ItemsReports/Search/FromDateController.jsx +++ b/src/components/dashboard/roadItems/reports/ItemsReports/Search/FromDateController.jsx @@ -1,28 +1,28 @@ -import { Controller } from "react-hook-form"; -import MuiDatePicker from "@/core/components/MuiDatePicker"; -import React from "react"; -import moment from "jalali-moment"; - -const FromDateController = ({ control }) => { - return ( - ( - { - const formattedDate = moment(new Date(newValue)).locale("en").format("YYYY-MM-DD"); - onChange(formattedDate); // Update the field value in react-hook-form - }} - helperText={error ? error.message : null} - /> - )} - /> - ); -}; -export default FromDateController; +import { Controller } from "react-hook-form"; +import MuiDatePicker from "@/core/components/MuiDatePicker"; +import React from "react"; +import moment from "jalali-moment"; + +const FromDateController = ({ control }) => { + return ( + ( + { + const formattedDate = moment(new Date(newValue)).locale("en").format("YYYY-MM-DD"); + onChange(formattedDate); // Update the field value in react-hook-form + }} + helperText={error ? error.message : null} + /> + )} + /> + ); +}; +export default FromDateController; diff --git a/src/components/dashboard/roadItems/reports/ItemsReports/Search/SearchReportField.jsx b/src/components/dashboard/roadItems/reports/ItemsReports/Search/SearchReportField.jsx index 9cce1c1..01656ef 100644 --- a/src/components/dashboard/roadItems/reports/ItemsReports/Search/SearchReportField.jsx +++ b/src/components/dashboard/roadItems/reports/ItemsReports/Search/SearchReportField.jsx @@ -1,45 +1,45 @@ -import { Button, Grid } from "@mui/material"; -import SearchIcon from "@mui/icons-material/Search"; -import React from "react"; -import FromDateController from "./FromDateController"; -import ToDateController from "./ToDateController"; -import SelectProvince from "./SelectProvince"; -import { Controller } from "react-hook-form"; - -const SearchReportField = ({ control, hasProvincesPermission }) => { - return ( - - - - - - - - {hasProvincesPermission && ( - - - - )} - - ( - - )} - /> - - - ); -}; - -export default SearchReportField; +import { Button, Grid } from "@mui/material"; +import SearchIcon from "@mui/icons-material/Search"; +import React from "react"; +import FromDateController from "./FromDateController"; +import ToDateController from "./ToDateController"; +import SelectProvince from "./SelectProvince"; +import { Controller } from "react-hook-form"; + +const SearchReportField = ({ control, hasProvincesPermission }) => { + return ( + + + + + + + + {hasProvincesPermission && ( + + + + )} + + ( + + )} + /> + + + ); +}; + +export default SearchReportField; diff --git a/src/components/dashboard/roadItems/reports/ItemsReports/Search/SelectProvince.jsx b/src/components/dashboard/roadItems/reports/ItemsReports/Search/SelectProvince.jsx index b1d8a39..7f738bc 100644 --- a/src/components/dashboard/roadItems/reports/ItemsReports/Search/SelectProvince.jsx +++ b/src/components/dashboard/roadItems/reports/ItemsReports/Search/SelectProvince.jsx @@ -1,47 +1,47 @@ -import { Controller } from "react-hook-form"; -import MuiDatePicker from "@/core/components/MuiDatePicker"; -import React from "react"; -import { FormControl, FormHelperText, InputLabel, LinearProgress, MenuItem, Select, Typography } from "@mui/material"; -import useProvinces from "@/lib/hooks/useProvince"; - -const SelectProvince = ({ control }) => { - const { provinces, loadingProvinces, errorProvinces } = useProvinces(); - return ( - ( - - استان - - {error && {error.message}} - - )} - /> - ); -}; -export default SelectProvince; +import { Controller } from "react-hook-form"; +import MuiDatePicker from "@/core/components/MuiDatePicker"; +import React from "react"; +import { FormControl, FormHelperText, InputLabel, LinearProgress, MenuItem, Select, Typography } from "@mui/material"; +import useProvinces from "@/lib/hooks/useProvince"; + +const SelectProvince = ({ control }) => { + const { provinces, loadingProvinces, errorProvinces } = useProvinces(); + return ( + ( + + استان + + {error && {error.message}} + + )} + /> + ); +}; +export default SelectProvince; diff --git a/src/components/dashboard/roadItems/reports/ItemsReports/Search/ToDateController.jsx b/src/components/dashboard/roadItems/reports/ItemsReports/Search/ToDateController.jsx index 2429410..a147668 100644 --- a/src/components/dashboard/roadItems/reports/ItemsReports/Search/ToDateController.jsx +++ b/src/components/dashboard/roadItems/reports/ItemsReports/Search/ToDateController.jsx @@ -1,30 +1,30 @@ -import { Controller, useWatch } from "react-hook-form"; -import MuiDatePicker from "@/core/components/MuiDatePicker"; -import React from "react"; -import moment from "jalali-moment"; - -const ToDateController = ({ control }) => { - const minDate = useWatch({ control, name: "from_date" }); - return ( - ( - { - const formattedDate = moment(new Date(newValue)).locale("en").format("YYYY-MM-DD"); - onChange(formattedDate); // Update the field value in react-hook-form - }} - helperText={error ? error.message : null} - /> - )} - /> - ); -}; -export default ToDateController; +import { Controller, useWatch } from "react-hook-form"; +import MuiDatePicker from "@/core/components/MuiDatePicker"; +import React from "react"; +import moment from "jalali-moment"; + +const ToDateController = ({ control }) => { + const minDate = useWatch({ control, name: "from_date" }); + return ( + ( + { + const formattedDate = moment(new Date(newValue)).locale("en").format("YYYY-MM-DD"); + onChange(formattedDate); // Update the field value in react-hook-form + }} + helperText={error ? error.message : null} + /> + )} + /> + ); +}; +export default ToDateController; diff --git a/src/components/dashboard/roadItems/reports/ItemsReports/Search/index.jsx b/src/components/dashboard/roadItems/reports/ItemsReports/Search/index.jsx index f29d302..9d504f2 100644 --- a/src/components/dashboard/roadItems/reports/ItemsReports/Search/index.jsx +++ b/src/components/dashboard/roadItems/reports/ItemsReports/Search/index.jsx @@ -1,13 +1,13 @@ -import StyledForm from "@/core/components/StyledForm"; -import SearchReportField from "./SearchReportField"; - -const SearchReportList = ({ handleSubmit, onSearchSubmit, control, hasProvincesPermission }) => { - return ( - <> - - - - - ); -}; -export default SearchReportList; +import StyledForm from "@/core/components/StyledForm"; +import SearchReportField from "./SearchReportField"; + +const SearchReportList = ({ handleSubmit, onSearchSubmit, control, hasProvincesPermission }) => { + return ( + <> + + + + + ); +}; +export default SearchReportList; diff --git a/src/components/dashboard/roadItems/reports/ItemsReports/TableToolbar.jsx b/src/components/dashboard/roadItems/reports/ItemsReports/TableToolbar.jsx index 32c4395..b62f822 100644 --- a/src/components/dashboard/roadItems/reports/ItemsReports/TableToolbar.jsx +++ b/src/components/dashboard/roadItems/reports/ItemsReports/TableToolbar.jsx @@ -1,10 +1,10 @@ -import PrintExcel from "./ExcelPrint"; - -const Toolbar = ({ table, filterData }) => { - return ( - <> - - - ); -}; -export default Toolbar; +import PrintExcel from "./ExcelPrint"; + +const Toolbar = ({ table, filterData }) => { + return ( + <> + + + ); +}; +export default Toolbar; diff --git a/src/components/dashboard/roadItems/reports/ItemsReports/index.jsx b/src/components/dashboard/roadItems/reports/ItemsReports/index.jsx index 3b79841..429de79 100644 --- a/src/components/dashboard/roadItems/reports/ItemsReports/index.jsx +++ b/src/components/dashboard/roadItems/reports/ItemsReports/index.jsx @@ -1,179 +1,179 @@ -"use client"; -import PageTitle from "@/core/components/PageTitle"; -import { LinearProgress, Stack, Typography } from "@mui/material"; -import SearchReportList from "./Search"; -import { useEffect, useState } from "react"; -import ReportLists from "./ReportLists"; -import useRequest from "@/lib/hooks/useRequest"; -import { GET_CITY_ACTIVITY_PER_ITEM, GET_PROVINCE_ACTIVITY_PER_ITEM } from "@/core/utils/routes"; -import useRoadItemGetItems from "@/lib/hooks/useRoadItemGetItems"; -import moment from "jalali-moment"; -import * as yup from "yup"; -import { useForm } from "react-hook-form"; -import { yupResolver } from "@hookform/resolvers/yup"; -import { usePermissions } from "@/lib/hooks/usePermissions"; -import { useAuth } from "@/lib/contexts/auth"; - -const ReportPage = () => { - const [data, setData] = useState(null); - const { itemsList, loadingItemsList, errorItemsList } = useRoadItemGetItems(); - const { data: userPermissions } = usePermissions(); - - const { user } = useAuth(); - const requestServer = useRequest(); - const hasProvincesPermission = userPermissions?.includes("show-road-item-supervise-cartable"); - - const defaultValues = { - from_date: moment(new Date()).format("YYYY-MM-DD"), - date_to: moment(new Date()).format("YYYY-MM-DD"), - province_id: hasProvincesPermission ? "-1" : user.province_id, - }; - const defaultFilter = [ - { value: `${defaultValues.province_id}`, datatype: "numeric", id: "province_id", fn: "equals" }, - { value: `${defaultValues.from_date}`, datatype: "date", id: "from_date", fn: "between" }, - { value: `${defaultValues.date_to}`, datatype: "date", id: "date_to", fn: "between" }, - ]; - const [specialFilter, setSpecialFilter] = useState(defaultFilter); - - const onSearchSubmit = async (data) => { - const params = new URLSearchParams(); - params.set("from_date", `${data.from_date}`); - params.set("date_to", `${data.date_to}`); - setSpecialFilter([ - { value: `${data.province_id}`, datatype: "numeric", id: "province_id", fn: "equals" }, - { value: `${data.from_date}`, datatype: "date", id: "from_date", fn: "between" }, - { value: `${data.date_to}`, datatype: "date", id: "date_to", fn: "between" }, - ]); - if (data.province_id === "-1") { - try { - const response = await requestServer(`${GET_PROVINCE_ACTIVITY_PER_ITEM}?${params}`); - const result = response.data.data; - const nationalReport = { - edare_name: "کل کشور", - sum: result.activities.length - ? result.activities - .filter((report) => report.p === -1) - .reduce((acc, report) => acc + (report.s || 0), 0) - : 0, - }; - itemsList.forEach((item) => { - const nationalReportForItem = result.activities.find( - (report) => report.p === -1 && report.i === item.id - ); - nationalReport[`item_${item.id}`] = nationalReportForItem ? nationalReportForItem.s : 0; - }); - - setData({ - data: [ - nationalReport, - ...result.provinces.map((province) => { - const filteredReports = result.activities.filter((report) => report.p === province.id); - const sum = filteredReports.reduce((acc, report) => acc + (report.s || 0), 0); - const rowData = { - edare_name: province.name_fa, - sum, - }; - itemsList.forEach((item) => { - const reportForItem = filteredReports.find((report) => report.i === item.id); - rowData[`item_${item.id}`] = reportForItem ? reportForItem.s : 0; - }); - return rowData; - }), - ], - filters: data, - }); - } catch (e) {} - } else { - try { - params.set("province_id", `${data.province_id}`); - const response = await requestServer(`${GET_CITY_ACTIVITY_PER_ITEM}?${params}`); - const result = response.data.data; - const nationalReport = { - edare_name: "کل استان", - sum: result.activities.length - ? result.activities - .filter((report) => report.c === -1) - .reduce((acc, report) => acc + (report.s || 0), 0) - : 0, - }; - - itemsList.forEach((item) => { - const nationalReportForItem = result.activities.find( - (report) => report.c === -1 && report.i === item.id - ); - nationalReport[`item_${item.id}`] = nationalReportForItem ? nationalReportForItem.s : 0; - }); - - setData({ - data: [ - nationalReport, - ...result.edarateShahri.map((edare) => { - const filteredReports = result.activities.filter((report) => report.c === edare.id); - const sum = filteredReports.reduce((acc, report) => acc + (report.s || 0), 0); - - const rowData = { - edare_name: edare.name_fa, - sum, - }; - - itemsList.forEach((item) => { - const reportForItem = filteredReports.find((report) => report.i === item.id); - rowData[`item_${item.id}`] = reportForItem ? reportForItem.s : 0; - }); - - return rowData; - }), - ], - filters: data, - }); - } catch (e) {} - } - }; - - useEffect(() => { - if (!userPermissions) return; - if (itemsList.length === 0) return; - onSearchSubmit(defaultValues); - }, [itemsList, userPermissions]); - - const validationSchema = yup.object().shape({ - from_date: yup - .string() - .required("تاریخ شروع الزامی است!") - .matches(/^\d{4}-\d{2}-\d{2}$/, "تاریخ شروع الزامی است!") - .test("is-valid-date", "تاریخ شروع معتبر نیست!", (value) => moment(value, "YYYY-MM-DD", true).isValid()), - date_to: yup - .string() - .required("تاریخ پایان الزامی است!") - .matches(/^\d{4}-\d{2}-\d{2}$/, "تاریخ پایان الزامی است!") - .test("is-valid-date", "تاریخ پایان معتبر نیست!", (value) => moment(value, "YYYY-MM-DD", true).isValid()), - province_id: yup.string().nullable(), - }); - - const { control, handleSubmit } = useForm({ - defaultValues, - resolver: yupResolver(validationSchema), - mode: "all", - }); - return ( - - - - {!data || loadingItemsList ? ( - - ) : errorItemsList ? ( - - خطا در دریافت اطلاعات!!! - - ) : ( - - )} - - ); -}; -export default ReportPage; +"use client"; +import PageTitle from "@/core/components/PageTitle"; +import { LinearProgress, Stack, Typography } from "@mui/material"; +import SearchReportList from "./Search"; +import { useEffect, useState } from "react"; +import ReportLists from "./ReportLists"; +import useRequest from "@/lib/hooks/useRequest"; +import { GET_CITY_ACTIVITY_PER_ITEM, GET_PROVINCE_ACTIVITY_PER_ITEM } from "@/core/utils/routes"; +import useRoadItemGetItems from "@/lib/hooks/useRoadItemGetItems"; +import moment from "jalali-moment"; +import * as yup from "yup"; +import { useForm } from "react-hook-form"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { usePermissions } from "@/lib/hooks/usePermissions"; +import { useAuth } from "@/lib/contexts/auth"; + +const ReportPage = () => { + const [data, setData] = useState(null); + const { itemsList, loadingItemsList, errorItemsList } = useRoadItemGetItems(); + const { data: userPermissions } = usePermissions(); + + const { user } = useAuth(); + const requestServer = useRequest(); + const hasProvincesPermission = userPermissions?.includes("show-road-item-supervise-cartable"); + + const defaultValues = { + from_date: moment(new Date()).format("YYYY-MM-DD"), + date_to: moment(new Date()).format("YYYY-MM-DD"), + province_id: hasProvincesPermission ? "-1" : user.province_id, + }; + const defaultFilter = [ + { value: `${defaultValues.province_id}`, datatype: "numeric", id: "province_id", fn: "equals" }, + { value: `${defaultValues.from_date}`, datatype: "date", id: "from_date", fn: "between" }, + { value: `${defaultValues.date_to}`, datatype: "date", id: "date_to", fn: "between" }, + ]; + const [specialFilter, setSpecialFilter] = useState(defaultFilter); + + const onSearchSubmit = async (data) => { + const params = new URLSearchParams(); + params.set("from_date", `${data.from_date}`); + params.set("date_to", `${data.date_to}`); + setSpecialFilter([ + { value: `${data.province_id}`, datatype: "numeric", id: "province_id", fn: "equals" }, + { value: `${data.from_date}`, datatype: "date", id: "from_date", fn: "between" }, + { value: `${data.date_to}`, datatype: "date", id: "date_to", fn: "between" }, + ]); + if (data.province_id === "-1") { + try { + const response = await requestServer(`${GET_PROVINCE_ACTIVITY_PER_ITEM}?${params}`); + const result = response.data.data; + const nationalReport = { + edare_name: "کل کشور", + sum: result.activities.length + ? result.activities + .filter((report) => report.p === -1) + .reduce((acc, report) => acc + (report.s || 0), 0) + : 0, + }; + itemsList.forEach((item) => { + const nationalReportForItem = result.activities.find( + (report) => report.p === -1 && report.i === item.id + ); + nationalReport[`item_${item.id}`] = nationalReportForItem ? nationalReportForItem.s : 0; + }); + + setData({ + data: [ + nationalReport, + ...result.provinces.map((province) => { + const filteredReports = result.activities.filter((report) => report.p === province.id); + const sum = filteredReports.reduce((acc, report) => acc + (report.s || 0), 0); + const rowData = { + edare_name: province.name_fa, + sum, + }; + itemsList.forEach((item) => { + const reportForItem = filteredReports.find((report) => report.i === item.id); + rowData[`item_${item.id}`] = reportForItem ? reportForItem.s : 0; + }); + return rowData; + }), + ], + filters: data, + }); + } catch (e) {} + } else { + try { + params.set("province_id", `${data.province_id}`); + const response = await requestServer(`${GET_CITY_ACTIVITY_PER_ITEM}?${params}`); + const result = response.data.data; + const nationalReport = { + edare_name: "کل استان", + sum: result.activities.length + ? result.activities + .filter((report) => report.c === -1) + .reduce((acc, report) => acc + (report.s || 0), 0) + : 0, + }; + + itemsList.forEach((item) => { + const nationalReportForItem = result.activities.find( + (report) => report.c === -1 && report.i === item.id + ); + nationalReport[`item_${item.id}`] = nationalReportForItem ? nationalReportForItem.s : 0; + }); + + setData({ + data: [ + nationalReport, + ...result.edarateShahri.map((edare) => { + const filteredReports = result.activities.filter((report) => report.c === edare.id); + const sum = filteredReports.reduce((acc, report) => acc + (report.s || 0), 0); + + const rowData = { + edare_name: edare.name_fa, + sum, + }; + + itemsList.forEach((item) => { + const reportForItem = filteredReports.find((report) => report.i === item.id); + rowData[`item_${item.id}`] = reportForItem ? reportForItem.s : 0; + }); + + return rowData; + }), + ], + filters: data, + }); + } catch (e) {} + } + }; + + useEffect(() => { + if (!userPermissions) return; + if (itemsList.length === 0) return; + onSearchSubmit(defaultValues); + }, [itemsList, userPermissions]); + + const validationSchema = yup.object().shape({ + from_date: yup + .string() + .required("تاریخ شروع الزامی است!") + .matches(/^\d{4}-\d{2}-\d{2}$/, "تاریخ شروع الزامی است!") + .test("is-valid-date", "تاریخ شروع معتبر نیست!", (value) => moment(value, "YYYY-MM-DD", true).isValid()), + date_to: yup + .string() + .required("تاریخ پایان الزامی است!") + .matches(/^\d{4}-\d{2}-\d{2}$/, "تاریخ پایان الزامی است!") + .test("is-valid-date", "تاریخ پایان معتبر نیست!", (value) => moment(value, "YYYY-MM-DD", true).isValid()), + province_id: yup.string().nullable(), + }); + + const { control, handleSubmit } = useForm({ + defaultValues, + resolver: yupResolver(validationSchema), + mode: "all", + }); + return ( + + + + {!data || loadingItemsList ? ( + + ) : errorItemsList ? ( + + خطا در دریافت اطلاعات!!! + + ) : ( + + )} + + ); +}; +export default ReportPage; diff --git a/src/components/dashboard/roadItems/reports/Map/ClusterSwitch/index.jsx b/src/components/dashboard/roadItems/reports/Map/ClusterSwitch/index.jsx index e8fac87..29312eb 100644 --- a/src/components/dashboard/roadItems/reports/Map/ClusterSwitch/index.jsx +++ b/src/components/dashboard/roadItems/reports/Map/ClusterSwitch/index.jsx @@ -1,25 +1,25 @@ -import DoneIcon from "@mui/icons-material/Done"; -import { Chip, Tooltip, Zoom } from "@mui/material"; - -const ClusterSwitch = ({ isCluster, setCluster, disabled, max }) => { - return ( - - - setCluster((c) => !c)} - sx={{ borderRadius: 1 }} - icon={ - - - - } - /> - - - ); -}; -export default ClusterSwitch; +import DoneIcon from "@mui/icons-material/Done"; +import { Chip, Tooltip, Zoom } from "@mui/material"; + +const ClusterSwitch = ({ isCluster, setCluster, disabled, max }) => { + return ( + + + setCluster((c) => !c)} + sx={{ borderRadius: 1 }} + icon={ + + + + } + /> + + + ); +}; +export default ClusterSwitch; diff --git a/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/ActivityDateTimeFilter.jsx b/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/ActivityDateTimeFilter.jsx index cab7ddc..06acc06 100644 --- a/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/ActivityDateTimeFilter.jsx +++ b/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/ActivityDateTimeFilter.jsx @@ -1,32 +1,32 @@ -import MuiDatePicker from "@/core/components/DataTable/filter/fieldsType/CustomDate/MuiDatePicker"; -import { Box } from "@mui/material"; - -const ActivityDateTimeFilter = ({ value, onChange, error }) => { - return ( - - { - onChange([formattedDate, value[1]]); - }} - maxDate={value[1]} - placeholder={`از تاریخ`} - /> - { - onChange([value[0], formattedDate]); - }} - minDate={value[0]} - placeholder={`تا تاریخ`} - helperText={error ? error.message : null} - error={Boolean(error)} - /> - - ); -}; -export default ActivityDateTimeFilter; +import MuiDatePicker from "@/core/components/DataTable/filter/fieldsType/CustomDate/MuiDatePicker"; +import { Box } from "@mui/material"; + +const ActivityDateTimeFilter = ({ value, onChange, error }) => { + return ( + + { + onChange([formattedDate, value[1]]); + }} + maxDate={value[1]} + placeholder={`از تاریخ`} + /> + { + onChange([value[0], formattedDate]); + }} + minDate={value[0]} + placeholder={`تا تاریخ`} + helperText={error ? error.message : null} + error={Boolean(error)} + /> + + ); +}; +export default ActivityDateTimeFilter; diff --git a/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/EdarehShahriFilter.jsx b/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/EdarehShahriFilter.jsx index eb08e27..2e08557 100644 --- a/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/EdarehShahriFilter.jsx +++ b/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/EdarehShahriFilter.jsx @@ -1,65 +1,65 @@ -"use client"; -import useEdaratLists from "@/lib/hooks/useEdaratLists"; -import { FormControl, InputLabel, MenuItem, OutlinedInput, Select } from "@mui/material"; -import { useEffect, useMemo, useState } from "react"; -import { useWatch } from "react-hook-form"; - -const EdarehShahriFilter = ({ control, value, onChange }) => { - const dependencyField = useWatch({ control, name: "province_id" }); - return ; -}; - -const EdarehShahriController = ({ value, onChange, dependencyField }) => { - const { edaratList, loadingEdaratList, errorEdaratList } = useEdaratLists(dependencyField); - const [prevDependency, setPrevDependency] = useState(dependencyField); - - const columnSelectOption = useMemo(() => { - if (dependencyField === "") { - return [{ value: "empty", label: "ابتدا استان را انتخاب کنید" }]; - } - if (loadingEdaratList) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorEdaratList) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: "کل ادارات" }, - ...edaratList.map((edare) => ({ - value: edare.id, - label: edare.name_fa, - })), - ]; - }, [edaratList, loadingEdaratList, errorEdaratList]); - - useEffect(() => { - if (prevDependency === dependencyField) return; - onChange(""); - setPrevDependency(dependencyField); - }, [dependencyField]); - - return ( - - - اداره - - - - ); -}; -export default EdarehShahriFilter; +"use client"; +import useEdaratLists from "@/lib/hooks/useEdaratLists"; +import { FormControl, InputLabel, MenuItem, OutlinedInput, Select } from "@mui/material"; +import { useEffect, useMemo, useState } from "react"; +import { useWatch } from "react-hook-form"; + +const EdarehShahriFilter = ({ control, value, onChange }) => { + const dependencyField = useWatch({ control, name: "province_id" }); + return ; +}; + +const EdarehShahriController = ({ value, onChange, dependencyField }) => { + const { edaratList, loadingEdaratList, errorEdaratList } = useEdaratLists(dependencyField); + const [prevDependency, setPrevDependency] = useState(dependencyField); + + const columnSelectOption = useMemo(() => { + if (dependencyField === "") { + return [{ value: "empty", label: "ابتدا استان را انتخاب کنید" }]; + } + if (loadingEdaratList) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorEdaratList) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: "کل ادارات" }, + ...edaratList.map((edare) => ({ + value: edare.id, + label: edare.name_fa, + })), + ]; + }, [edaratList, loadingEdaratList, errorEdaratList]); + + useEffect(() => { + if (prevDependency === dependencyField) return; + onChange(""); + setPrevDependency(dependencyField); + }, [dependencyField]); + + return ( + + + اداره + + + + ); +}; +export default EdarehShahriFilter; diff --git a/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/ItemFilter.jsx b/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/ItemFilter.jsx index de27d11..47a19a9 100644 --- a/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/ItemFilter.jsx +++ b/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/ItemFilter.jsx @@ -1,47 +1,47 @@ -import useRoadItemGetItems from "@/lib/hooks/useRoadItemGetItems"; -import { FormControl, InputLabel, MenuItem, OutlinedInput, Select } from "@mui/material"; -import { useMemo } from "react"; - -const ItemFilter = ({ value, onChange }) => { - const { itemsList, loadingItemsList, errorItemsList } = useRoadItemGetItems(); - const columnSelectOption = useMemo(() => { - if (loadingItemsList) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorItemsList) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: "همه آیتم ها" }, - ...itemsList.map((item) => ({ - value: item.id, - label: item.name, - })), - ]; - }, [itemsList, loadingItemsList, errorItemsList]); - - return ( - - - آیتم فعالیت - - - - ); -}; -export default ItemFilter; +import useRoadItemGetItems from "@/lib/hooks/useRoadItemGetItems"; +import { FormControl, InputLabel, MenuItem, OutlinedInput, Select } from "@mui/material"; +import { useMemo } from "react"; + +const ItemFilter = ({ value, onChange }) => { + const { itemsList, loadingItemsList, errorItemsList } = useRoadItemGetItems(); + const columnSelectOption = useMemo(() => { + if (loadingItemsList) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorItemsList) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: "همه آیتم ها" }, + ...itemsList.map((item) => ({ + value: item.id, + label: item.name, + })), + ]; + }, [itemsList, loadingItemsList, errorItemsList]); + + return ( + + + آیتم فعالیت + + + + ); +}; +export default ItemFilter; diff --git a/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/ProvinceFilter.jsx b/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/ProvinceFilter.jsx index 4de3f9e..728e939 100644 --- a/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/ProvinceFilter.jsx +++ b/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/ProvinceFilter.jsx @@ -1,47 +1,47 @@ -import useProvinces from "@/lib/hooks/useProvince"; -import { FormControl, InputLabel, MenuItem, OutlinedInput, Select } from "@mui/material"; -import { useMemo } from "react"; - -const ProvinceFilter = ({ value, onChange }) => { - const { provinces, errorProvinces, loadingProvinces } = useProvinces(); - const columnSelectOption = useMemo(() => { - if (loadingProvinces) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorProvinces) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: "کل کشور" }, - ...provinces.map((province) => ({ - value: province.id, - label: province.name_fa, - })), - ]; - }, [provinces, errorProvinces, loadingProvinces]); - - return ( - - - استان - - - - ); -}; -export default ProvinceFilter; +import useProvinces from "@/lib/hooks/useProvince"; +import { FormControl, InputLabel, MenuItem, OutlinedInput, Select } from "@mui/material"; +import { useMemo } from "react"; + +const ProvinceFilter = ({ value, onChange }) => { + const { provinces, errorProvinces, loadingProvinces } = useProvinces(); + const columnSelectOption = useMemo(() => { + if (loadingProvinces) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorProvinces) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: "کل کشور" }, + ...provinces.map((province) => ({ + value: province.id, + label: province.name_fa, + })), + ]; + }, [provinces, errorProvinces, loadingProvinces]); + + return ( + + + استان + + + + ); +}; +export default ProvinceFilter; diff --git a/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/StatusFilter.jsx b/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/StatusFilter.jsx index dd52ea5..f9eccdf 100644 --- a/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/StatusFilter.jsx +++ b/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/StatusFilter.jsx @@ -1,35 +1,35 @@ -import { FormControl, InputLabel, MenuItem, OutlinedInput, Select } from "@mui/material"; - -const StatusFilter = ({ value, onChange }) => { - const statusOptions = [ - { value: "", label: "همه وضعیت ها" }, - { value: 0, label: "درحال بررسی" }, - { value: 1, label: "تایید" }, - { value: 2, label: "عدم تایید" }, - ]; - - return ( - - - وضعیت نظارت - - - - ); -}; -export default StatusFilter; +import { FormControl, InputLabel, MenuItem, OutlinedInput, Select } from "@mui/material"; + +const StatusFilter = ({ value, onChange }) => { + const statusOptions = [ + { value: "", label: "همه وضعیت ها" }, + { value: 0, label: "درحال بررسی" }, + { value: 1, label: "تایید" }, + { value: 2, label: "عدم تایید" }, + ]; + + return ( + + + وضعیت نظارت + + + + ); +}; +export default StatusFilter; diff --git a/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/SubItemFilter.jsx b/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/SubItemFilter.jsx index e9f973a..d30d322 100644 --- a/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/SubItemFilter.jsx +++ b/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/SubItemFilter.jsx @@ -1,65 +1,65 @@ -"use client"; -import useRoadItemGetSubItems from "@/lib/hooks/useRoadItemGetISubtems"; -import { FormControl, InputLabel, MenuItem, OutlinedInput, Select } from "@mui/material"; -import { useEffect, useMemo, useState } from "react"; -import { useWatch } from "react-hook-form"; - -const SubItemFilter = ({ control, value, onChange }) => { - const dependencyField = useWatch({ control, name: "item_id" }); - return ; -}; - -const SubItemController = ({ value, onChange, dependencyField }) => { - const { subItemsList, loadingSubItemsList, errorSubItemsList } = useRoadItemGetSubItems(dependencyField); - const [prevDependency, setPrevDependency] = useState(dependencyField); - - const columnSelectOption = useMemo(() => { - if (dependencyField === "") { - return [{ value: "empty", label: "ابتدا آیتم فعالیت را انتخاب کنید" }]; - } - if (loadingSubItemsList) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorSubItemsList) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: "همه اقدام ها" }, - ...subItemsList.map((item) => ({ - value: item.sub_item, - label: item.name, - })), - ]; - }, [subItemsList, loadingSubItemsList, errorSubItemsList]); - - useEffect(() => { - if (prevDependency === dependencyField) return; - onChange(""); - setPrevDependency(dependencyField); - }, [dependencyField]); - - return ( - - - اقدام انجام شده - - - - ); -}; -export default SubItemFilter; +"use client"; +import useRoadItemGetSubItems from "@/lib/hooks/useRoadItemGetISubtems"; +import { FormControl, InputLabel, MenuItem, OutlinedInput, Select } from "@mui/material"; +import { useEffect, useMemo, useState } from "react"; +import { useWatch } from "react-hook-form"; + +const SubItemFilter = ({ control, value, onChange }) => { + const dependencyField = useWatch({ control, name: "item_id" }); + return ; +}; + +const SubItemController = ({ value, onChange, dependencyField }) => { + const { subItemsList, loadingSubItemsList, errorSubItemsList } = useRoadItemGetSubItems(dependencyField); + const [prevDependency, setPrevDependency] = useState(dependencyField); + + const columnSelectOption = useMemo(() => { + if (dependencyField === "") { + return [{ value: "empty", label: "ابتدا آیتم فعالیت را انتخاب کنید" }]; + } + if (loadingSubItemsList) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorSubItemsList) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: "همه اقدام ها" }, + ...subItemsList.map((item) => ({ + value: item.sub_item, + label: item.name, + })), + ]; + }, [subItemsList, loadingSubItemsList, errorSubItemsList]); + + useEffect(() => { + if (prevDependency === dependencyField) return; + onChange(""); + setPrevDependency(dependencyField); + }, [dependencyField]); + + return ( + + + اقدام انجام شده + + + + ); +}; +export default SubItemFilter; diff --git a/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/index.jsx b/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/index.jsx index 074977e..007355a 100644 --- a/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/index.jsx +++ b/src/components/dashboard/roadItems/reports/Map/Filter/Drawer/index.jsx @@ -1,141 +1,141 @@ -import ScrollBox from "@/core/components/ScrollBox"; -import { Box, Button, IconButton, Typography } from "@mui/material"; -import CancelIcon from "@mui/icons-material/Cancel"; -import FilterAltIcon from "@mui/icons-material/FilterAlt"; -import { Controller, useForm } from "react-hook-form"; -import ProvinceFilter from "./ProvinceFilter"; -import EdarehShahriFilter from "./EdarehShahriFilter"; -import ItemFilter from "./ItemFilter"; -import SubItemFilter from "./SubItemFilter"; -import StatusFilter from "./StatusFilter"; -import ActivityDateTimeFilter from "./ActivityDateTimeFilter"; -import { yupResolver } from "@hookform/resolvers/yup"; -import * as Yup from "yup"; - -const validationSchema = Yup.object({ - activity_date_time: Yup.array() - .of(Yup.string().nullable()) - .test({ - test(value, ctx) { - const [start, end] = value || ["", ""]; - if ((start && !end) || (!start && end)) { - return ctx.createError({ message: "این بخش را تکمیل نمایید" }); - } - return true; - }, - }), -}); - -const headerSx = { - display: "flex", - alignItems: "center", - justifyContent: "space-between", - px: 2, - py: 1, - backgroundColor: "#155175", - boxShadow: "rgba(0, 0, 0, 0.19) 0px 10px 20px, rgba(0, 0, 0, 0.23) 0px 6px 6px", - maxWidth: "450px", -}; - -const headerTitleSx = { display: "flex", alignItems: "center" }; -const headerIconSx = { color: "#fff", mr: 1 }; -const iconButtonSx = { color: "#fff" }; - -const formContainerSx = { px: 2, py: 3 }; -const footerSx = { display: "flex", justifyContent: "center", alignItems: "center", pb: 2 }; - -const submitButtonSx = { - px: 8, - boxShadow: "rgba(0, 0, 0, 0.23) 0px 6px 6px, rgba(0, 0, 0, 0.19) 10px 0px 20px", - backgroundColor: "primary2", - ":hover": { backgroundColor: "primary2" }, -}; - -const FilterDrawer = ({ defaultValues, setFilterData, closeDrawer }) => { - const { - control, - handleSubmit, - formState: { isDirty }, - } = useForm({ - defaultValues, - resolver: yupResolver(validationSchema), - mode: "all", - }); - - const onSubmit = (data) => { - setFilterData(data); - closeDrawer(); - }; - - return ( - <> - - - - - فیلتر - - - - - - - - -
    - - ( - - )} - /> - ( - - )} - /> - ( - - )} - /> - ( - - )} - /> - ( - - )} - /> - ( - - )} - /> - - - - - -
    -
    - - ); -}; -export default FilterDrawer; +import ScrollBox from "@/core/components/ScrollBox"; +import { Box, Button, IconButton, Typography } from "@mui/material"; +import CancelIcon from "@mui/icons-material/Cancel"; +import FilterAltIcon from "@mui/icons-material/FilterAlt"; +import { Controller, useForm } from "react-hook-form"; +import ProvinceFilter from "./ProvinceFilter"; +import EdarehShahriFilter from "./EdarehShahriFilter"; +import ItemFilter from "./ItemFilter"; +import SubItemFilter from "./SubItemFilter"; +import StatusFilter from "./StatusFilter"; +import ActivityDateTimeFilter from "./ActivityDateTimeFilter"; +import { yupResolver } from "@hookform/resolvers/yup"; +import * as Yup from "yup"; + +const validationSchema = Yup.object({ + activity_date_time: Yup.array() + .of(Yup.string().nullable()) + .test({ + test(value, ctx) { + const [start, end] = value || ["", ""]; + if ((start && !end) || (!start && end)) { + return ctx.createError({ message: "این بخش را تکمیل نمایید" }); + } + return true; + }, + }), +}); + +const headerSx = { + display: "flex", + alignItems: "center", + justifyContent: "space-between", + px: 2, + py: 1, + backgroundColor: "#155175", + boxShadow: "rgba(0, 0, 0, 0.19) 0px 10px 20px, rgba(0, 0, 0, 0.23) 0px 6px 6px", + maxWidth: "450px", +}; + +const headerTitleSx = { display: "flex", alignItems: "center" }; +const headerIconSx = { color: "#fff", mr: 1 }; +const iconButtonSx = { color: "#fff" }; + +const formContainerSx = { px: 2, py: 3 }; +const footerSx = { display: "flex", justifyContent: "center", alignItems: "center", pb: 2 }; + +const submitButtonSx = { + px: 8, + boxShadow: "rgba(0, 0, 0, 0.23) 0px 6px 6px, rgba(0, 0, 0, 0.19) 10px 0px 20px", + backgroundColor: "primary2", + ":hover": { backgroundColor: "primary2" }, +}; + +const FilterDrawer = ({ defaultValues, setFilterData, closeDrawer }) => { + const { + control, + handleSubmit, + formState: { isDirty }, + } = useForm({ + defaultValues, + resolver: yupResolver(validationSchema), + mode: "all", + }); + + const onSubmit = (data) => { + setFilterData(data); + closeDrawer(); + }; + + return ( + <> + + + + + فیلتر + + + + + + + + +
    + + ( + + )} + /> + ( + + )} + /> + ( + + )} + /> + ( + + )} + /> + ( + + )} + /> + ( + + )} + /> + + + + + +
    +
    + + ); +}; +export default FilterDrawer; diff --git a/src/components/dashboard/roadItems/reports/Map/Filter/index.jsx b/src/components/dashboard/roadItems/reports/Map/Filter/index.jsx index c12a511..244193e 100644 --- a/src/components/dashboard/roadItems/reports/Map/Filter/index.jsx +++ b/src/components/dashboard/roadItems/reports/Map/Filter/index.jsx @@ -1,44 +1,44 @@ -"use client"; -import { Box, Button, Drawer } from "@mui/material"; -import FilterListIcon from "@mui/icons-material/FilterList"; -import { useCallback, useState } from "react"; -import FilterDrawer from "./Drawer"; - -const drawerSx = { - overflowY: "hidden", - display: "flex", - flexDirection: "column", - height: "100%", - zIndex: "1300", -}; - -const boxSx = { - width: { xs: 300, sm: 450 }, -}; - -const Filter = ({ filterData, setFilterData }) => { - const [open, setOpen] = useState(false); - - const openDrawer = useCallback(() => setOpen(true), []); - const closeDrawer = useCallback(() => setOpen(false), []); - - return ( - <> - - - - {open && ( - - )} - - - - ); -}; -export default Filter; +"use client"; +import { Box, Button, Drawer } from "@mui/material"; +import FilterListIcon from "@mui/icons-material/FilterList"; +import { useCallback, useState } from "react"; +import FilterDrawer from "./Drawer"; + +const drawerSx = { + overflowY: "hidden", + display: "flex", + flexDirection: "column", + height: "100%", + zIndex: "1300", +}; + +const boxSx = { + width: { xs: 300, sm: 450 }, +}; + +const Filter = ({ filterData, setFilterData }) => { + const [open, setOpen] = useState(false); + + const openDrawer = useCallback(() => setOpen(true), []); + const closeDrawer = useCallback(() => setOpen(false), []); + + return ( + <> + + + + {open && ( + + )} + + + + ); +}; +export default Filter; diff --git a/src/components/dashboard/roadItems/reports/Map/Legend/index.jsx b/src/components/dashboard/roadItems/reports/Map/Legend/index.jsx index 20707aa..5e3ab94 100644 --- a/src/components/dashboard/roadItems/reports/Map/Legend/index.jsx +++ b/src/components/dashboard/roadItems/reports/Map/Legend/index.jsx @@ -1,48 +1,48 @@ -import { Box, Stack, Typography } from "@mui/material"; - -const Legend = () => { - return ( - - - theme.palette.primary.main, - background: (theme) => theme.palette.primary.light, - }} - /> - در حال بررسی - - - theme.palette.success.main, - background: (theme) => theme.palette.success.light, - }} - /> - تایید شده - - - theme.palette.warning.main, - background: (theme) => theme.palette.warning.light, - }} - /> - عدم تایید - - - ); -}; -export default Legend; +import { Box, Stack, Typography } from "@mui/material"; + +const Legend = () => { + return ( + + + theme.palette.primary.main, + background: (theme) => theme.palette.primary.light, + }} + /> + در حال بررسی + + + theme.palette.success.main, + background: (theme) => theme.palette.success.light, + }} + /> + تایید شده + + + theme.palette.warning.main, + background: (theme) => theme.palette.warning.light, + }} + /> + عدم تایید + + + ); +}; +export default Legend; diff --git a/src/components/dashboard/roadItems/reports/Map/PointsOnMap/DialogInfoItem/ContentInfoItem.jsx b/src/components/dashboard/roadItems/reports/Map/PointsOnMap/DialogInfoItem/ContentInfoItem.jsx index a10a1aa..bbe49d2 100644 --- a/src/components/dashboard/roadItems/reports/Map/PointsOnMap/DialogInfoItem/ContentInfoItem.jsx +++ b/src/components/dashboard/roadItems/reports/Map/PointsOnMap/DialogInfoItem/ContentInfoItem.jsx @@ -1,104 +1,104 @@ -import { Box, Chip, Divider, Stack, Typography } from "@mui/material"; -import moment from "jalali-moment"; -import Image from "next/image"; - -const ContentInfoItem = ({ data }) => { - return ( - - - - - {data.id !== "" && data.id} - - - - - - {data.province_fa !== "" && data.province_fa} - - - - - - - {data.edarat_name !== "" && data.edarat_name} - - - - - - - {data.item_fa !== "" && data.item_fa} - - - - - - - {data.sub_item_fa !== "" && data.sub_item_fa} - - - - - - - - {(data.sub_item_data / 1).toLocaleString()} - - - {`(${data.unit_fa})`} - - - - - - - - {data.activity_date_time && - moment(data.activity_date_time).locale("fa").format("HH:mm | yyyy/MM/DD")} - - - - - - - {data.created_at && moment(data.created_at).locale("fa").format("HH:mm | yyyy/MM/DD")} - - - - - - - {data.status_fa !== "" && data.status_fa} - - - - - - - before_image - - - - - - before_image - - - - - ); -}; -export default ContentInfoItem; +import { Box, Chip, Divider, Stack, Typography } from "@mui/material"; +import moment from "jalali-moment"; +import Image from "next/image"; + +const ContentInfoItem = ({ data }) => { + return ( + + + + + {data.id !== "" && data.id} + + + + + + {data.province_fa !== "" && data.province_fa} + + + + + + + {data.edarat_name !== "" && data.edarat_name} + + + + + + + {data.item_fa !== "" && data.item_fa} + + + + + + + {data.sub_item_fa !== "" && data.sub_item_fa} + + + + + + + + {(data.sub_item_data / 1).toLocaleString()} + + + {`(${data.unit_fa})`} + + + + + + + + {data.activity_date_time && + moment(data.activity_date_time).locale("fa").format("HH:mm | yyyy/MM/DD")} + + + + + + + {data.created_at && moment(data.created_at).locale("fa").format("HH:mm | yyyy/MM/DD")} + + + + + + + {data.status_fa !== "" && data.status_fa} + + + + + + + before_image + + + + + + before_image + + + + + ); +}; +export default ContentInfoItem; diff --git a/src/components/dashboard/roadItems/reports/Map/PointsOnMap/DialogInfoItem/index.jsx b/src/components/dashboard/roadItems/reports/Map/PointsOnMap/DialogInfoItem/index.jsx index a3c9b23..02857bb 100644 --- a/src/components/dashboard/roadItems/reports/Map/PointsOnMap/DialogInfoItem/index.jsx +++ b/src/components/dashboard/roadItems/reports/Map/PointsOnMap/DialogInfoItem/index.jsx @@ -1,51 +1,51 @@ -import DialogLoading from "@/core/components/DialogLoading"; -import { GET_ROAD_ITEM } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { Button, DialogActions, DialogContent, DialogTitle } from "@mui/material"; -import { useEffect, useState } from "react"; -import ContentInfoItem from "./ContentInfoItem"; - -const DialogInfoItem = ({ selectedId, closeDialog }) => { - const request = useRequest(); - const [loading, setLoading] = useState(true); - const [data, setData] = useState(null); - - useEffect(() => { - const controller = new AbortController(); - - const fetchItem = async () => { - setLoading(true); - setData(null); - try { - const response = await request(`${GET_ROAD_ITEM}/${selectedId}`, "get", { - signal: controller.signal, - }); - setData(response.data.data); - } catch (error) { - } finally { - setLoading(false); - } - }; - - fetchItem(); - - return () => { - controller.abort(); - }; - }, [selectedId]); - - return ( - <> - جزئیات فعالیت - - {loading ? : data && } - - - - - - ); -}; -export default DialogInfoItem; +import DialogLoading from "@/core/components/DialogLoading"; +import { GET_ROAD_ITEM } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { Button, DialogActions, DialogContent, DialogTitle } from "@mui/material"; +import { useEffect, useState } from "react"; +import ContentInfoItem from "./ContentInfoItem"; + +const DialogInfoItem = ({ selectedId, closeDialog }) => { + const request = useRequest(); + const [loading, setLoading] = useState(true); + const [data, setData] = useState(null); + + useEffect(() => { + const controller = new AbortController(); + + const fetchItem = async () => { + setLoading(true); + setData(null); + try { + const response = await request(`${GET_ROAD_ITEM}/${selectedId}`, "get", { + signal: controller.signal, + }); + setData(response.data.data); + } catch (error) { + } finally { + setLoading(false); + } + }; + + fetchItem(); + + return () => { + controller.abort(); + }; + }, [selectedId]); + + return ( + <> + جزئیات فعالیت + + {loading ? : data && } + + + + + + ); +}; +export default DialogInfoItem; diff --git a/src/components/dashboard/roadItems/reports/Map/PointsOnMap/index.jsx b/src/components/dashboard/roadItems/reports/Map/PointsOnMap/index.jsx index 8599f3f..f7090aa 100644 --- a/src/components/dashboard/roadItems/reports/Map/PointsOnMap/index.jsx +++ b/src/components/dashboard/roadItems/reports/Map/PointsOnMap/index.jsx @@ -1,71 +1,71 @@ -import { Dialog, useTheme } from "@mui/material"; -import { useCallback, useEffect, useMemo, useState } from "react"; -import { CircleMarker, useMap } from "react-leaflet"; -import MarkerClusterGroup from "react-leaflet-markercluster"; -import DialogInfoItem from "./DialogInfoItem"; - -const PointsOnMap = ({ data, isCluster }) => { - const map = useMap(); - const theme = useTheme(); - const [selectedId, setSelectedId] = useState(null); - const [open, setOpen] = useState(false); - - const openDialog = useCallback(() => setOpen(true), []); - const closeDialog = useCallback(() => setOpen(false), []); - - const getMarkerColor = (status) => { - if (status === 0) return theme.palette.info.main; - if (status === 1) return theme.palette.success.main; - return theme.palette.warning.main; - }; - - const markers = useMemo(() => { - return data.map(({ i, l, g, status }) => ( - { - openDialog(); - setSelectedId(i); - }, - }} - key={i} - center={L.latLng(l, g)} - radius={8} - color={getMarkerColor(status)} - /> - )); - }, [data, theme]); - - useEffect(() => { - if (data.length === 0) return; - const bounds = L.latLngBounds(data.map(({ l, g }) => L.latLng(l, g))); - map.flyToBounds(bounds, { duration: 0.7 }); - }, [data]); - - const createClusterCustomIcon = (cluster) => { - const count = cluster.getChildCount(); - return L.divIcon({ - html: `
    ${count}
    `, - className: "custom-marker-cluster", - iconSize: L.point(40, 40, true), - }); - }; - - if (data.length === 0) return null; - - return ( - <> - {isCluster ? ( - - {markers} - - ) : ( - markers - )} - - {open && } - - - ); -}; -export default PointsOnMap; +import { Dialog, useTheme } from "@mui/material"; +import { useCallback, useEffect, useMemo, useState } from "react"; +import { CircleMarker, useMap } from "react-leaflet"; +import MarkerClusterGroup from "react-leaflet-markercluster"; +import DialogInfoItem from "./DialogInfoItem"; + +const PointsOnMap = ({ data, isCluster }) => { + const map = useMap(); + const theme = useTheme(); + const [selectedId, setSelectedId] = useState(null); + const [open, setOpen] = useState(false); + + const openDialog = useCallback(() => setOpen(true), []); + const closeDialog = useCallback(() => setOpen(false), []); + + const getMarkerColor = (status) => { + if (status === 0) return theme.palette.info.main; + if (status === 1) return theme.palette.success.main; + return theme.palette.warning.main; + }; + + const markers = useMemo(() => { + return data.map(({ i, l, g, status }) => ( + { + openDialog(); + setSelectedId(i); + }, + }} + key={i} + center={L.latLng(l, g)} + radius={8} + color={getMarkerColor(status)} + /> + )); + }, [data, theme]); + + useEffect(() => { + if (data.length === 0) return; + const bounds = L.latLngBounds(data.map(({ l, g }) => L.latLng(l, g))); + map.flyToBounds(bounds, { duration: 0.7 }); + }, [data]); + + const createClusterCustomIcon = (cluster) => { + const count = cluster.getChildCount(); + return L.divIcon({ + html: `
    ${count}
    `, + className: "custom-marker-cluster", + iconSize: L.point(40, 40, true), + }); + }; + + if (data.length === 0) return null; + + return ( + <> + {isCluster ? ( + + {markers} + + ) : ( + markers + )} + + {open && } + + + ); +}; +export default PointsOnMap; diff --git a/src/components/dashboard/roadItems/reports/Map/index.jsx b/src/components/dashboard/roadItems/reports/Map/index.jsx index 1daacfb..3209ade 100644 --- a/src/components/dashboard/roadItems/reports/Map/index.jsx +++ b/src/components/dashboard/roadItems/reports/Map/index.jsx @@ -1,127 +1,127 @@ -"use client"; -import LoadingHardPage from "@/core/components/LoadingHardPage"; -import MapLoading from "@/core/components/MapLayer/Loading"; -import { GET_ROAD_ITEMS_REPORT_MAP } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { Box, Stack } from "@mui/material"; -import dynamic from "next/dynamic"; -import { useCallback, useEffect, useState } from "react"; -import Filter from "./Filter"; -import PointsOnMap from "./PointsOnMap"; -import moment from "jalali-moment"; -import ClusterSwitch from "./ClusterSwitch"; -import Legend from "./Legend"; -const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { - loading: () => , - ssr: false, -}); - -const defaultValues = { - province_id: "", - edarat_id: "", - item_id: "", - sub_item_id: "", - status: "", - activity_date_time: [moment().locale("en").format("YYYY-MM-DD"), moment().locale("en").format("YYYY-MM-DD")], -}; - -const MAX_POINTS = 1000; - -const containerStyles = { - width: "100%", - height: "100%", - p: 1, - border: "1px dashed", - borderColor: "divider", - borderRadius: 1, -}; - -const controlBarStyles = { - p: 1, - background: "#fff", -}; - -const RoadItemsReportMap = () => { - const requestServer = useRequest(); - const [filterData, setFilterData] = useState(defaultValues); - const [isCluster, setCluster] = useState(false); - const [data, setData] = useState([]); - const [isLoading, setLoading] = useState(true); - - const buildQueryParams = useCallback(() => { - const params = new URLSearchParams(); - const { province_id, edarat_id, item_id, sub_item_id, activity_date_time, status } = filterData; - - if (province_id) params.set("province_id", province_id); - if (edarat_id) params.set("edarat_id", edarat_id); - if (item_id) params.set("item_id", item_id); - if (sub_item_id) params.set("sub_item_id", sub_item_id); - if (activity_date_time[0]) { - params.set("date_from", activity_date_time[0]); - params.set("date_to", activity_date_time[1]); - } - if (status) params.set("status", status); - - return params.toString(); - }, [filterData]); - - useEffect(() => { - const fetchData = async () => { - try { - setLoading(true); - const query = buildQueryParams(); - const response = await requestServer(`${GET_ROAD_ITEMS_REPORT_MAP}?${query}`); - const fetchedData = response?.data?.data || []; - - if (fetchedData.length > MAX_POINTS) { - setCluster(true); - } - setData(fetchedData); - } catch (error) { - } finally { - setLoading(false); - } - }; - - fetchData(); - }, [filterData, buildQueryParams]); - - return ( - - - - - MAX_POINTS} - max={MAX_POINTS} - /> - - - - - - - - - - - {isLoading && ( - - - - )} - - - - - ); -}; -export default RoadItemsReportMap; +"use client"; +import LoadingHardPage from "@/core/components/LoadingHardPage"; +import MapLoading from "@/core/components/MapLayer/Loading"; +import { GET_ROAD_ITEMS_REPORT_MAP } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { Box, Stack } from "@mui/material"; +import dynamic from "next/dynamic"; +import { useCallback, useEffect, useState } from "react"; +import Filter from "./Filter"; +import PointsOnMap from "./PointsOnMap"; +import moment from "jalali-moment"; +import ClusterSwitch from "./ClusterSwitch"; +import Legend from "./Legend"; +const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { + loading: () => , + ssr: false, +}); + +const defaultValues = { + province_id: "", + edarat_id: "", + item_id: "", + sub_item_id: "", + status: "", + activity_date_time: [moment().locale("en").format("YYYY-MM-DD"), moment().locale("en").format("YYYY-MM-DD")], +}; + +const MAX_POINTS = 1000; + +const containerStyles = { + width: "100%", + height: "100%", + p: 1, + border: "1px dashed", + borderColor: "divider", + borderRadius: 1, +}; + +const controlBarStyles = { + p: 1, + background: "#fff", +}; + +const RoadItemsReportMap = () => { + const requestServer = useRequest(); + const [filterData, setFilterData] = useState(defaultValues); + const [isCluster, setCluster] = useState(false); + const [data, setData] = useState([]); + const [isLoading, setLoading] = useState(true); + + const buildQueryParams = useCallback(() => { + const params = new URLSearchParams(); + const { province_id, edarat_id, item_id, sub_item_id, activity_date_time, status } = filterData; + + if (province_id) params.set("province_id", province_id); + if (edarat_id) params.set("edarat_id", edarat_id); + if (item_id) params.set("item_id", item_id); + if (sub_item_id) params.set("sub_item_id", sub_item_id); + if (activity_date_time[0]) { + params.set("date_from", activity_date_time[0]); + params.set("date_to", activity_date_time[1]); + } + if (status) params.set("status", status); + + return params.toString(); + }, [filterData]); + + useEffect(() => { + const fetchData = async () => { + try { + setLoading(true); + const query = buildQueryParams(); + const response = await requestServer(`${GET_ROAD_ITEMS_REPORT_MAP}?${query}`); + const fetchedData = response?.data?.data || []; + + if (fetchedData.length > MAX_POINTS) { + setCluster(true); + } + setData(fetchedData); + } catch (error) { + } finally { + setLoading(false); + } + }; + + fetchData(); + }, [filterData, buildQueryParams]); + + return ( + + + + + MAX_POINTS} + max={MAX_POINTS} + /> + + + + + + + + + + + {isLoading && ( + + + + )} + + + + + ); +}; +export default RoadItemsReportMap; diff --git a/src/components/dashboard/roadItems/reports/SubItemsReports/ExcelPrint/index.jsx b/src/components/dashboard/roadItems/reports/SubItemsReports/ExcelPrint/index.jsx index 443135b..6a5d3cb 100644 --- a/src/components/dashboard/roadItems/reports/SubItemsReports/ExcelPrint/index.jsx +++ b/src/components/dashboard/roadItems/reports/SubItemsReports/ExcelPrint/index.jsx @@ -1,77 +1,77 @@ -"use client"; -import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; -import { useMemo, useState } from "react"; -import moment from "jalali-moment"; -import FileSaver from "file-saver"; -import DescriptionIcon from "@mui/icons-material/Description"; -import useRequest from "@/lib/hooks/useRequest"; -import { useTheme } from "@emotion/react"; -import { - EXPORT_COUNTRY_ROAD_ITEM_REPORTS_PER_SUB_ITEM, - EXPORT_PROVINCE_ROAD_ITEM_REPORTS_PER_SUB_ITEM, -} from "@/core/utils/routes"; - -const PrintExcel = ({ table, filterData }) => { - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const [loading, setLoading] = useState(false); - const requestServer = useRequest({ notificationSuccess: true }); - const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { - if (filter.value) { - acc.push({ id: filter.id, value: filter.value }); - } - return acc; - }, []); - - const filterParams = useMemo(() => { - const params = new URLSearchParams(); - activeFilters.length > 0 && - activeFilters.map((filter, index) => { - params.set(`${filter.id}`, filter.value); - }); - return params; - }, [activeFilters]); - - const clickHandler = () => { - setLoading(true); - const CountryOrProvince = activeFilters.find((item) => item.id === "province_id"); - const requestUrl = - CountryOrProvince.value === "-1" - ? EXPORT_COUNTRY_ROAD_ITEM_REPORTS_PER_SUB_ITEM - : EXPORT_PROVINCE_ROAD_ITEM_REPORTS_PER_SUB_ITEM; - requestServer(`${requestUrl}?${filterParams}`, "get", { - requestOptions: { responseType: "blob" }, - }) - .then((response) => { - const filename = `خروجی کارتابل گزارشات فعالیت روزانه براساس موارد اقدام شده تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; - FileSaver.saveAs(response.data, filename); - }) - .catch(() => {}) - .finally(() => { - setLoading(false); - }); - }; - - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - - ); -}; -export default PrintExcel; +"use client"; +import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; +import { useMemo, useState } from "react"; +import moment from "jalali-moment"; +import FileSaver from "file-saver"; +import DescriptionIcon from "@mui/icons-material/Description"; +import useRequest from "@/lib/hooks/useRequest"; +import { useTheme } from "@emotion/react"; +import { + EXPORT_COUNTRY_ROAD_ITEM_REPORTS_PER_SUB_ITEM, + EXPORT_PROVINCE_ROAD_ITEM_REPORTS_PER_SUB_ITEM, +} from "@/core/utils/routes"; + +const PrintExcel = ({ table, filterData }) => { + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const [loading, setLoading] = useState(false); + const requestServer = useRequest({ notificationSuccess: true }); + const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { + if (filter.value) { + acc.push({ id: filter.id, value: filter.value }); + } + return acc; + }, []); + + const filterParams = useMemo(() => { + const params = new URLSearchParams(); + activeFilters.length > 0 && + activeFilters.map((filter, index) => { + params.set(`${filter.id}`, filter.value); + }); + return params; + }, [activeFilters]); + + const clickHandler = () => { + setLoading(true); + const CountryOrProvince = activeFilters.find((item) => item.id === "province_id"); + const requestUrl = + CountryOrProvince.value === "-1" + ? EXPORT_COUNTRY_ROAD_ITEM_REPORTS_PER_SUB_ITEM + : EXPORT_PROVINCE_ROAD_ITEM_REPORTS_PER_SUB_ITEM; + requestServer(`${requestUrl}?${filterParams}`, "get", { + requestOptions: { responseType: "blob" }, + }) + .then((response) => { + const filename = `خروجی کارتابل گزارشات فعالیت روزانه براساس موارد اقدام شده تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; + FileSaver.saveAs(response.data, filename); + }) + .catch(() => {}) + .finally(() => { + setLoading(false); + }); + }; + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + + ); +}; +export default PrintExcel; diff --git a/src/components/dashboard/roadItems/reports/SubItemsReports/Search/FromDateController.jsx b/src/components/dashboard/roadItems/reports/SubItemsReports/Search/FromDateController.jsx index 2e23def..562bf68 100644 --- a/src/components/dashboard/roadItems/reports/SubItemsReports/Search/FromDateController.jsx +++ b/src/components/dashboard/roadItems/reports/SubItemsReports/Search/FromDateController.jsx @@ -1,28 +1,28 @@ -import { Controller } from "react-hook-form"; -import MuiDatePicker from "@/core/components/MuiDatePicker"; -import React from "react"; -import moment from "jalali-moment"; - -const FromDateController = ({ control }) => { - return ( - ( - { - const formattedDate = moment(new Date(newValue)).locale("en").format("YYYY-MM-DD"); - onChange(formattedDate); // Update the field value in react-hook-form - }} - helperText={error ? error.message : null} - /> - )} - /> - ); -}; -export default FromDateController; +import { Controller } from "react-hook-form"; +import MuiDatePicker from "@/core/components/MuiDatePicker"; +import React from "react"; +import moment from "jalali-moment"; + +const FromDateController = ({ control }) => { + return ( + ( + { + const formattedDate = moment(new Date(newValue)).locale("en").format("YYYY-MM-DD"); + onChange(formattedDate); // Update the field value in react-hook-form + }} + helperText={error ? error.message : null} + /> + )} + /> + ); +}; +export default FromDateController; diff --git a/src/components/dashboard/roadItems/reports/SubItemsReports/Search/SearchReportField.jsx b/src/components/dashboard/roadItems/reports/SubItemsReports/Search/SearchReportField.jsx index 5487b7f..54399b5 100644 --- a/src/components/dashboard/roadItems/reports/SubItemsReports/Search/SearchReportField.jsx +++ b/src/components/dashboard/roadItems/reports/SubItemsReports/Search/SearchReportField.jsx @@ -1,48 +1,48 @@ -import { Button, Grid } from "@mui/material"; -import SearchIcon from "@mui/icons-material/Search"; -import React from "react"; -import FromDateController from "./FromDateController"; -import ToDateController from "./ToDateController"; -import SelectProvince from "./SelectProvince"; -import { Controller } from "react-hook-form"; -import SelectItems from "./SelectItems"; - -const SearchReportField = ({ control, hasProvincesPermission }) => { - return ( - - - - - - - - {hasProvincesPermission && ( - - - - )} - - - - - ( - - )} - /> - - - ); -}; -export default SearchReportField; +import { Button, Grid } from "@mui/material"; +import SearchIcon from "@mui/icons-material/Search"; +import React from "react"; +import FromDateController from "./FromDateController"; +import ToDateController from "./ToDateController"; +import SelectProvince from "./SelectProvince"; +import { Controller } from "react-hook-form"; +import SelectItems from "./SelectItems"; + +const SearchReportField = ({ control, hasProvincesPermission }) => { + return ( + + + + + + + + {hasProvincesPermission && ( + + + + )} + + + + + ( + + )} + /> + + + ); +}; +export default SearchReportField; diff --git a/src/components/dashboard/roadItems/reports/SubItemsReports/Search/SelectItems.jsx b/src/components/dashboard/roadItems/reports/SubItemsReports/Search/SelectItems.jsx index db71a8a..e5c0b6a 100644 --- a/src/components/dashboard/roadItems/reports/SubItemsReports/Search/SelectItems.jsx +++ b/src/components/dashboard/roadItems/reports/SubItemsReports/Search/SelectItems.jsx @@ -1,42 +1,42 @@ -import { Controller } from "react-hook-form"; -import MuiDatePicker from "@/core/components/MuiDatePicker"; -import React from "react"; -import { FormControl, FormHelperText, InputLabel, MenuItem, Select } from "@mui/material"; -import useRoadItemGetItems from "@/lib/hooks/useRoadItemGetItems"; - -const SelectProvince = ({ control }) => { - const { itemsList, loadingItemsList, errorItemsList } = useRoadItemGetItems(); - return ( - ( - - آیتم - - {error && {error.message}} - - )} - /> - ); -}; -export default SelectProvince; +import { Controller } from "react-hook-form"; +import MuiDatePicker from "@/core/components/MuiDatePicker"; +import React from "react"; +import { FormControl, FormHelperText, InputLabel, MenuItem, Select } from "@mui/material"; +import useRoadItemGetItems from "@/lib/hooks/useRoadItemGetItems"; + +const SelectProvince = ({ control }) => { + const { itemsList, loadingItemsList, errorItemsList } = useRoadItemGetItems(); + return ( + ( + + آیتم + + {error && {error.message}} + + )} + /> + ); +}; +export default SelectProvince; diff --git a/src/components/dashboard/roadItems/reports/SubItemsReports/Search/SelectProvince.jsx b/src/components/dashboard/roadItems/reports/SubItemsReports/Search/SelectProvince.jsx index b1d8a39..7f738bc 100644 --- a/src/components/dashboard/roadItems/reports/SubItemsReports/Search/SelectProvince.jsx +++ b/src/components/dashboard/roadItems/reports/SubItemsReports/Search/SelectProvince.jsx @@ -1,47 +1,47 @@ -import { Controller } from "react-hook-form"; -import MuiDatePicker from "@/core/components/MuiDatePicker"; -import React from "react"; -import { FormControl, FormHelperText, InputLabel, LinearProgress, MenuItem, Select, Typography } from "@mui/material"; -import useProvinces from "@/lib/hooks/useProvince"; - -const SelectProvince = ({ control }) => { - const { provinces, loadingProvinces, errorProvinces } = useProvinces(); - return ( - ( - - استان - - {error && {error.message}} - - )} - /> - ); -}; -export default SelectProvince; +import { Controller } from "react-hook-form"; +import MuiDatePicker from "@/core/components/MuiDatePicker"; +import React from "react"; +import { FormControl, FormHelperText, InputLabel, LinearProgress, MenuItem, Select, Typography } from "@mui/material"; +import useProvinces from "@/lib/hooks/useProvince"; + +const SelectProvince = ({ control }) => { + const { provinces, loadingProvinces, errorProvinces } = useProvinces(); + return ( + ( + + استان + + {error && {error.message}} + + )} + /> + ); +}; +export default SelectProvince; diff --git a/src/components/dashboard/roadItems/reports/SubItemsReports/Search/ToDateController.jsx b/src/components/dashboard/roadItems/reports/SubItemsReports/Search/ToDateController.jsx index 2b312c4..40e36cd 100644 --- a/src/components/dashboard/roadItems/reports/SubItemsReports/Search/ToDateController.jsx +++ b/src/components/dashboard/roadItems/reports/SubItemsReports/Search/ToDateController.jsx @@ -1,30 +1,30 @@ -import { Controller, useWatch } from "react-hook-form"; -import MuiDatePicker from "@/core/components/MuiDatePicker"; -import React from "react"; -import moment from "jalali-moment"; - -const ToDateController = ({ control }) => { - const minDate = useWatch({ control, name: "from_date" }); - return ( - ( - { - const formattedDate = moment(new Date(newValue)).locale("en").format("YYYY-MM-DD"); - onChange(formattedDate); - }} - helperText={error ? error.message : null} - /> - )} - /> - ); -}; -export default ToDateController; +import { Controller, useWatch } from "react-hook-form"; +import MuiDatePicker from "@/core/components/MuiDatePicker"; +import React from "react"; +import moment from "jalali-moment"; + +const ToDateController = ({ control }) => { + const minDate = useWatch({ control, name: "from_date" }); + return ( + ( + { + const formattedDate = moment(new Date(newValue)).locale("en").format("YYYY-MM-DD"); + onChange(formattedDate); + }} + helperText={error ? error.message : null} + /> + )} + /> + ); +}; +export default ToDateController; diff --git a/src/components/dashboard/roadItems/reports/SubItemsReports/Search/index.jsx b/src/components/dashboard/roadItems/reports/SubItemsReports/Search/index.jsx index 0ca7a3f..83713d6 100644 --- a/src/components/dashboard/roadItems/reports/SubItemsReports/Search/index.jsx +++ b/src/components/dashboard/roadItems/reports/SubItemsReports/Search/index.jsx @@ -1,12 +1,12 @@ -import StyledForm from "@/core/components/StyledForm"; -import SearchReportField from "./SearchReportField"; -const SearchReportList = ({ handleSubmit, onSearchSubmit, control, hasProvincesPermission }) => { - return ( - <> - - - - - ); -}; -export default SearchReportList; +import StyledForm from "@/core/components/StyledForm"; +import SearchReportField from "./SearchReportField"; +const SearchReportList = ({ handleSubmit, onSearchSubmit, control, hasProvincesPermission }) => { + return ( + <> + + + + + ); +}; +export default SearchReportList; diff --git a/src/components/dashboard/roadItems/reports/SubItemsReports/SubItemsList.jsx b/src/components/dashboard/roadItems/reports/SubItemsReports/SubItemsList.jsx index d92a366..95362e4 100644 --- a/src/components/dashboard/roadItems/reports/SubItemsReports/SubItemsList.jsx +++ b/src/components/dashboard/roadItems/reports/SubItemsReports/SubItemsList.jsx @@ -1,20 +1,20 @@ -import DataTableWithAuth from "@/core/components/DataTableWithAuth"; -import { Box } from "@mui/material"; -import Toolbar from "./TableToolbar"; - -const SubItemsList = ({ data, specialFilter }) => { - return ( - - - - ); -}; -export default SubItemsList; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import { Box } from "@mui/material"; +import Toolbar from "./TableToolbar"; + +const SubItemsList = ({ data, specialFilter }) => { + return ( + + + + ); +}; +export default SubItemsList; diff --git a/src/components/dashboard/roadItems/reports/SubItemsReports/TableToolbar.jsx b/src/components/dashboard/roadItems/reports/SubItemsReports/TableToolbar.jsx index 32c4395..b62f822 100644 --- a/src/components/dashboard/roadItems/reports/SubItemsReports/TableToolbar.jsx +++ b/src/components/dashboard/roadItems/reports/SubItemsReports/TableToolbar.jsx @@ -1,10 +1,10 @@ -import PrintExcel from "./ExcelPrint"; - -const Toolbar = ({ table, filterData }) => { - return ( - <> - - - ); -}; -export default Toolbar; +import PrintExcel from "./ExcelPrint"; + +const Toolbar = ({ table, filterData }) => { + return ( + <> + + + ); +}; +export default Toolbar; diff --git a/src/components/dashboard/roadItems/reports/SubItemsReports/index.jsx b/src/components/dashboard/roadItems/reports/SubItemsReports/index.jsx index 87f9bd5..15f7d85 100644 --- a/src/components/dashboard/roadItems/reports/SubItemsReports/index.jsx +++ b/src/components/dashboard/roadItems/reports/SubItemsReports/index.jsx @@ -1,256 +1,256 @@ -"use client"; -import SubItemsList from "./SubItemsList"; -import PageTitle from "@/core/components/PageTitle"; -import { LinearProgress, Stack } from "@mui/material"; -import SearchReportList from "./Search"; -import { useEffect, useState } from "react"; -import { usePermissions } from "@/lib/hooks/usePermissions"; -import { useAuth } from "@/lib/contexts/auth"; -import useRequest from "@/lib/hooks/useRequest"; -import moment from "jalali-moment"; -import { GET_CITY_ACTIVITY_PER_SUB_ITEM, GET_PROVINCE_ACTIVITY_PER_SUB_ITEM } from "@/core/utils/routes"; -import * as yup from "yup"; -import { useForm } from "react-hook-form"; -import { yupResolver } from "@hookform/resolvers/yup"; - -const createColumns = (sub_items) => { - const dynamicColumns = - sub_items?.map((sub_item) => ({ - accessorKey: `sub_item_${sub_item.sub_item}`, - header: `${sub_item.sub_item_str}`, - id: `sub_item_${sub_item.sub_item}`, - columns: [ - { - accessorKey: `sub_item_${sub_item.sub_item}_count`, - header: "تعداد اقدام", - id: `sub_item_${sub_item.sub_item}_count`, - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - size: 50, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - { - accessorKey: `sub_item_${sub_item.sub_item}_sum`, - header: `مجموع (${sub_item.sub_item_unit})`, - id: `sub_item_${sub_item.sub_item}_sum`, - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - grow: false, - size: 50, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - ], - })) || []; - - return [ - { - accessorKey: "edare_name", - header: "اداره", - id: "edare_name", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - }, - { - header: "موارد اقدام شده فعالیت روزانه", - enableColumnFilter: false, - id: "subItems", - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - columns: [...dynamicColumns], - }, - ]; -}; - -const SubItemsReports = () => { - const [data, setData] = useState(null); - const { data: userPermissions } = usePermissions(); - const { user } = useAuth(); - const requestServer = useRequest(); - const hasProvincesPermission = userPermissions?.includes("show-road-item-supervise-cartable"); - - const defaultValues = { - from_date: moment(new Date()).format("YYYY-MM-DD"), - date_to: moment(new Date()).format("YYYY-MM-DD"), - province_id: hasProvincesPermission ? "-1" : user.province_id, - item: 1, - }; - const defaultFilter = [ - { value: `${defaultValues.province_id}`, datatype: "numeric", id: "province_id", fn: "equals" }, - { value: `${defaultValues.item}`, datatype: "numeric", id: "item", fn: "equals" }, - { value: `${defaultValues.from_date}`, datatype: "date", id: "from_date", fn: "between" }, - { value: `${defaultValues.date_to}`, datatype: "date", id: "date_to", fn: "between" }, - ]; - const [specialFilter, setSpecialFilter] = useState(defaultFilter); - - const onSearchSubmit = async (data) => { - const params = new URLSearchParams(); - params.set("from_date", `${data.from_date}`); - params.set("date_to", `${data.date_to}`); - params.set("item", `${data.item}`); - setSpecialFilter([ - { value: `${data.province_id}`, datatype: "numeric", id: "province_id", fn: "equals" }, - { value: `${data.item}`, datatype: "numeric", id: "item", fn: "equals" }, - { value: `${data.from_date}`, datatype: "date", id: "from_date", fn: "between" }, - { value: `${data.date_to}`, datatype: "date", id: "date_to", fn: "between" }, - ]); - if (data.province_id === "-1") { - try { - const response = await requestServer(`${GET_PROVINCE_ACTIVITY_PER_SUB_ITEM}?${params}`); - const result = response.data.data; - const nationalReport = { - edare_name: "کل کشور", - }; - - result.sub_items.forEach((subItem) => { - const nationalReportForSubItem = result.activities.find( - (report) => report.p === -1 && report.t === subItem.sub_item - ); - nationalReport[`sub_item_${subItem.sub_item}_count`] = nationalReportForSubItem - ? nationalReportForSubItem.c - : 0; - nationalReport[`sub_item_${subItem.sub_item}_sum`] = nationalReportForSubItem - ? nationalReportForSubItem.s - : 0; - }); - - setData({ - data: [ - nationalReport, - ...result.provinces.map((province) => { - const filteredReports = result.activities.filter((report) => report.p === province.id); - const rowData = { - edare_name: province.name_fa, - }; - - result.sub_items.forEach((subItem) => { - const reportForItem = filteredReports.find((report) => report.t === subItem.sub_item); - rowData[`sub_item_${subItem.sub_item}_count`] = reportForItem ? reportForItem.c : 0; - rowData[`sub_item_${subItem.sub_item}_sum`] = reportForItem ? reportForItem.s : 0; - }); - - return rowData; - }), - ], - columns: createColumns(result.sub_items), - filters: data, - }); - } catch (e) {} - } else { - try { - params.set("province_id", `${data.province_id}`); - const response = await requestServer(`${GET_CITY_ACTIVITY_PER_SUB_ITEM}?${params}`); - const result = response.data.data; - const nationalReport = { - edare_name: "کل استان", - }; - - result.sub_items.forEach((subItem) => { - const nationalReportForSubItem = result.activities.find( - (report) => report.ci === -1 && report.t === subItem.sub_item - ); - nationalReport[`sub_item_${subItem.sub_item}_count`] = nationalReportForSubItem - ? nationalReportForSubItem.c - : 0; - nationalReport[`sub_item_${subItem.sub_item}_sum`] = nationalReportForSubItem - ? nationalReportForSubItem.s - : 0; - }); - - setData({ - data: [ - nationalReport, - ...result.edarateShahri.map((edare) => { - const filteredReports = result.activities.filter((report) => report.ci === edare.id); - const rowData = { - edare_name: edare.name_fa, - }; - - result.sub_items.forEach((subItem) => { - const reportForItem = filteredReports.find((report) => report.t === subItem.sub_item); - rowData[`sub_item_${subItem.sub_item}_count`] = reportForItem ? reportForItem.c : 0; - rowData[`sub_item_${subItem.sub_item}_sum`] = reportForItem ? reportForItem.s : 0; - }); - - return rowData; - }), - ], - columns: createColumns(result.sub_items), - filters: data, - }); - } catch (e) { - console.log(e); - } - } - }; - - useEffect(() => { - if (!userPermissions) return; - onSearchSubmit(defaultValues); - }, [userPermissions]); - - const validationSchema = yup.object().shape({ - from_date: yup - .string() - .required("تاریخ شروع الزامی است!") - .matches(/^\d{4}-\d{2}-\d{2}$/, "تاریخ شروع الزامی است!") - .test("is-valid-date", "تاریخ شروع معتبر نیست!", (value) => moment(value, "YYYY-MM-DD", true).isValid()), - date_to: yup - .string() - .required("تاریخ پایان الزامی است!") - .matches(/^\d{4}-\d{2}-\d{2}$/, "تاریخ پایان الزامی است!") - .test("is-valid-date", "تاریخ پایان معتبر نیست!", (value) => moment(value, "YYYY-MM-DD", true).isValid()), - province_id: yup.string().nullable(), - item: yup.number().required("آیتم مورد نظر را وارد کنید!!!"), - }); - - const { control, handleSubmit } = useForm({ - defaultValues, - resolver: yupResolver(validationSchema), - mode: "all", - }); - return ( - - - - {!data ? : } - - ); -}; -export default SubItemsReports; +"use client"; +import SubItemsList from "./SubItemsList"; +import PageTitle from "@/core/components/PageTitle"; +import { LinearProgress, Stack } from "@mui/material"; +import SearchReportList from "./Search"; +import { useEffect, useState } from "react"; +import { usePermissions } from "@/lib/hooks/usePermissions"; +import { useAuth } from "@/lib/contexts/auth"; +import useRequest from "@/lib/hooks/useRequest"; +import moment from "jalali-moment"; +import { GET_CITY_ACTIVITY_PER_SUB_ITEM, GET_PROVINCE_ACTIVITY_PER_SUB_ITEM } from "@/core/utils/routes"; +import * as yup from "yup"; +import { useForm } from "react-hook-form"; +import { yupResolver } from "@hookform/resolvers/yup"; + +const createColumns = (sub_items) => { + const dynamicColumns = + sub_items?.map((sub_item) => ({ + accessorKey: `sub_item_${sub_item.sub_item}`, + header: `${sub_item.sub_item_str}`, + id: `sub_item_${sub_item.sub_item}`, + columns: [ + { + accessorKey: `sub_item_${sub_item.sub_item}_count`, + header: "تعداد اقدام", + id: `sub_item_${sub_item.sub_item}_count`, + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + size: 50, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + { + accessorKey: `sub_item_${sub_item.sub_item}_sum`, + header: `مجموع (${sub_item.sub_item_unit})`, + id: `sub_item_${sub_item.sub_item}_sum`, + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + grow: false, + size: 50, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + ], + })) || []; + + return [ + { + accessorKey: "edare_name", + header: "اداره", + id: "edare_name", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + }, + { + header: "موارد اقدام شده فعالیت روزانه", + enableColumnFilter: false, + id: "subItems", + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + columns: [...dynamicColumns], + }, + ]; +}; + +const SubItemsReports = () => { + const [data, setData] = useState(null); + const { data: userPermissions } = usePermissions(); + const { user } = useAuth(); + const requestServer = useRequest(); + const hasProvincesPermission = userPermissions?.includes("show-road-item-supervise-cartable"); + + const defaultValues = { + from_date: moment(new Date()).format("YYYY-MM-DD"), + date_to: moment(new Date()).format("YYYY-MM-DD"), + province_id: hasProvincesPermission ? "-1" : user.province_id, + item: 1, + }; + const defaultFilter = [ + { value: `${defaultValues.province_id}`, datatype: "numeric", id: "province_id", fn: "equals" }, + { value: `${defaultValues.item}`, datatype: "numeric", id: "item", fn: "equals" }, + { value: `${defaultValues.from_date}`, datatype: "date", id: "from_date", fn: "between" }, + { value: `${defaultValues.date_to}`, datatype: "date", id: "date_to", fn: "between" }, + ]; + const [specialFilter, setSpecialFilter] = useState(defaultFilter); + + const onSearchSubmit = async (data) => { + const params = new URLSearchParams(); + params.set("from_date", `${data.from_date}`); + params.set("date_to", `${data.date_to}`); + params.set("item", `${data.item}`); + setSpecialFilter([ + { value: `${data.province_id}`, datatype: "numeric", id: "province_id", fn: "equals" }, + { value: `${data.item}`, datatype: "numeric", id: "item", fn: "equals" }, + { value: `${data.from_date}`, datatype: "date", id: "from_date", fn: "between" }, + { value: `${data.date_to}`, datatype: "date", id: "date_to", fn: "between" }, + ]); + if (data.province_id === "-1") { + try { + const response = await requestServer(`${GET_PROVINCE_ACTIVITY_PER_SUB_ITEM}?${params}`); + const result = response.data.data; + const nationalReport = { + edare_name: "کل کشور", + }; + + result.sub_items.forEach((subItem) => { + const nationalReportForSubItem = result.activities.find( + (report) => report.p === -1 && report.t === subItem.sub_item + ); + nationalReport[`sub_item_${subItem.sub_item}_count`] = nationalReportForSubItem + ? nationalReportForSubItem.c + : 0; + nationalReport[`sub_item_${subItem.sub_item}_sum`] = nationalReportForSubItem + ? nationalReportForSubItem.s + : 0; + }); + + setData({ + data: [ + nationalReport, + ...result.provinces.map((province) => { + const filteredReports = result.activities.filter((report) => report.p === province.id); + const rowData = { + edare_name: province.name_fa, + }; + + result.sub_items.forEach((subItem) => { + const reportForItem = filteredReports.find((report) => report.t === subItem.sub_item); + rowData[`sub_item_${subItem.sub_item}_count`] = reportForItem ? reportForItem.c : 0; + rowData[`sub_item_${subItem.sub_item}_sum`] = reportForItem ? reportForItem.s : 0; + }); + + return rowData; + }), + ], + columns: createColumns(result.sub_items), + filters: data, + }); + } catch (e) {} + } else { + try { + params.set("province_id", `${data.province_id}`); + const response = await requestServer(`${GET_CITY_ACTIVITY_PER_SUB_ITEM}?${params}`); + const result = response.data.data; + const nationalReport = { + edare_name: "کل استان", + }; + + result.sub_items.forEach((subItem) => { + const nationalReportForSubItem = result.activities.find( + (report) => report.ci === -1 && report.t === subItem.sub_item + ); + nationalReport[`sub_item_${subItem.sub_item}_count`] = nationalReportForSubItem + ? nationalReportForSubItem.c + : 0; + nationalReport[`sub_item_${subItem.sub_item}_sum`] = nationalReportForSubItem + ? nationalReportForSubItem.s + : 0; + }); + + setData({ + data: [ + nationalReport, + ...result.edarateShahri.map((edare) => { + const filteredReports = result.activities.filter((report) => report.ci === edare.id); + const rowData = { + edare_name: edare.name_fa, + }; + + result.sub_items.forEach((subItem) => { + const reportForItem = filteredReports.find((report) => report.t === subItem.sub_item); + rowData[`sub_item_${subItem.sub_item}_count`] = reportForItem ? reportForItem.c : 0; + rowData[`sub_item_${subItem.sub_item}_sum`] = reportForItem ? reportForItem.s : 0; + }); + + return rowData; + }), + ], + columns: createColumns(result.sub_items), + filters: data, + }); + } catch (e) { + console.log(e); + } + } + }; + + useEffect(() => { + if (!userPermissions) return; + onSearchSubmit(defaultValues); + }, [userPermissions]); + + const validationSchema = yup.object().shape({ + from_date: yup + .string() + .required("تاریخ شروع الزامی است!") + .matches(/^\d{4}-\d{2}-\d{2}$/, "تاریخ شروع الزامی است!") + .test("is-valid-date", "تاریخ شروع معتبر نیست!", (value) => moment(value, "YYYY-MM-DD", true).isValid()), + date_to: yup + .string() + .required("تاریخ پایان الزامی است!") + .matches(/^\d{4}-\d{2}-\d{2}$/, "تاریخ پایان الزامی است!") + .test("is-valid-date", "تاریخ پایان معتبر نیست!", (value) => moment(value, "YYYY-MM-DD", true).isValid()), + province_id: yup.string().nullable(), + item: yup.number().required("آیتم مورد نظر را وارد کنید!!!"), + }); + + const { control, handleSubmit } = useForm({ + defaultValues, + resolver: yupResolver(validationSchema), + mode: "all", + }); + return ( + + + + {!data ? : } + + ); +}; +export default SubItemsReports; diff --git a/src/components/dashboard/roadItems/supervisor/ExcelPrint/index.jsx b/src/components/dashboard/roadItems/supervisor/ExcelPrint/index.jsx index eca9fff..f1bbf5e 100644 --- a/src/components/dashboard/roadItems/supervisor/ExcelPrint/index.jsx +++ b/src/components/dashboard/roadItems/supervisor/ExcelPrint/index.jsx @@ -1,74 +1,74 @@ -import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; -import { useMemo, useState } from "react"; -import moment from "jalali-moment"; -import FileSaver from "file-saver"; -import DescriptionIcon from "@mui/icons-material/Description"; -import useRequest from "@/lib/hooks/useRequest"; -import { EXPORT_ROAD_ITEMS_SUPERVISOR_LIST } from "@/core/utils/routes"; -import { useTheme } from "@emotion/react"; -import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; -import isArrayEmpty from "@/core/utils/isArrayEmpty"; - -const PrintExcel = ({ table, filterData }) => { - const [loading, setLoading] = useState(false); - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const requestServer = useRequest(); - const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { - if (filter.value && (!Array.isArray(filter.value) || filter.value.some((item) => item.trim() !== ""))) { - acc.push({ id: key, value: filter.value }); - } - return acc; - }, []); - - const filterParams = useMemo(() => { - const params = new URLSearchParams(); - if (activeFilters.length > 0) { - activeFilters.map((filter, index) => { - const filteredFilterData = DataTableFilterDataStructure(filterData, isArrayEmpty); - params.set("filters", JSON.stringify(filteredFilterData.length === 0 ? [] : filteredFilterData)); - }); - } else { - params.set("filters", JSON.stringify([])); - } - return params; - }, [activeFilters]); - const clickHandler = () => { - setLoading(true); - requestServer(`${EXPORT_ROAD_ITEMS_SUPERVISOR_LIST}?${filterParams}`, "get", { - requestOptions: { responseType: "blob" }, - }) - .then((response) => { - const filename = `خروجی کارتابل ارزیابی فعالیت روزانه تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; - FileSaver.saveAs(response.data, filename); - }) - .catch(() => {}) - .finally(() => { - setLoading(false); - }); - }; - - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - - ); -}; - -export default PrintExcel; +import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; +import { useMemo, useState } from "react"; +import moment from "jalali-moment"; +import FileSaver from "file-saver"; +import DescriptionIcon from "@mui/icons-material/Description"; +import useRequest from "@/lib/hooks/useRequest"; +import { EXPORT_ROAD_ITEMS_SUPERVISOR_LIST } from "@/core/utils/routes"; +import { useTheme } from "@emotion/react"; +import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; +import isArrayEmpty from "@/core/utils/isArrayEmpty"; + +const PrintExcel = ({ table, filterData }) => { + const [loading, setLoading] = useState(false); + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const requestServer = useRequest(); + const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { + if (filter.value && (!Array.isArray(filter.value) || filter.value.some((item) => item.trim() !== ""))) { + acc.push({ id: key, value: filter.value }); + } + return acc; + }, []); + + const filterParams = useMemo(() => { + const params = new URLSearchParams(); + if (activeFilters.length > 0) { + activeFilters.map((filter, index) => { + const filteredFilterData = DataTableFilterDataStructure(filterData, isArrayEmpty); + params.set("filters", JSON.stringify(filteredFilterData.length === 0 ? [] : filteredFilterData)); + }); + } else { + params.set("filters", JSON.stringify([])); + } + return params; + }, [activeFilters]); + const clickHandler = () => { + setLoading(true); + requestServer(`${EXPORT_ROAD_ITEMS_SUPERVISOR_LIST}?${filterParams}`, "get", { + requestOptions: { responseType: "blob" }, + }) + .then((response) => { + const filename = `خروجی کارتابل ارزیابی فعالیت روزانه تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; + FileSaver.saveAs(response.data, filename); + }) + .catch(() => {}) + .finally(() => { + setLoading(false); + }); + }; + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + + ); +}; + +export default PrintExcel; diff --git a/src/components/dashboard/roadItems/supervisor/RowActions/ConfirmForm/ConfirmContent.jsx b/src/components/dashboard/roadItems/supervisor/RowActions/ConfirmForm/ConfirmContent.jsx index 4cba1f8..3ca369a 100644 --- a/src/components/dashboard/roadItems/supervisor/RowActions/ConfirmForm/ConfirmContent.jsx +++ b/src/components/dashboard/roadItems/supervisor/RowActions/ConfirmForm/ConfirmContent.jsx @@ -1,72 +1,72 @@ -import { Button, DialogActions, DialogContent, Stack, TextField } from "@mui/material"; -import { useForm } from "react-hook-form"; -import useRequest from "@/lib/hooks/useRequest"; -import { VERIFY_BY_SUPERVISOR } from "@/core/utils/routes"; - -const ConfirmContent = ({ rowId, mutate, setOpenConfirmDialog }) => { - const requestServer = useRequest({ notificationSuccess: true }); - - const { - register, - handleSubmit, - formState: { isSubmitting }, - reset, - } = useForm({ - defaultValues: { - description: "", - }, - }); - - const onSubmit = async (data) => { - const formData = new FormData(); - data.description !== "" && formData.append("description", data.description); - formData.append("verify", 1); - requestServer(`${VERIFY_BY_SUPERVISOR}/${rowId}`, "post", { - data: formData, - hasSidebarUpdate: true, - }) - .then(() => { - mutate(); - setOpenConfirmDialog(false); - }) - .catch(() => {}); - }; - - return ( - <> - - - - - - - - - - - - - ); -}; - -export default ConfirmContent; +import { Button, DialogActions, DialogContent, Stack, TextField } from "@mui/material"; +import { useForm } from "react-hook-form"; +import useRequest from "@/lib/hooks/useRequest"; +import { VERIFY_BY_SUPERVISOR } from "@/core/utils/routes"; + +const ConfirmContent = ({ rowId, mutate, setOpenConfirmDialog }) => { + const requestServer = useRequest({ notificationSuccess: true }); + + const { + register, + handleSubmit, + formState: { isSubmitting }, + reset, + } = useForm({ + defaultValues: { + description: "", + }, + }); + + const onSubmit = async (data) => { + const formData = new FormData(); + data.description !== "" && formData.append("description", data.description); + formData.append("verify", 1); + requestServer(`${VERIFY_BY_SUPERVISOR}/${rowId}`, "post", { + data: formData, + hasSidebarUpdate: true, + }) + .then(() => { + mutate(); + setOpenConfirmDialog(false); + }) + .catch(() => {}); + }; + + return ( + <> + + + + + + + + + + + + + ); +}; + +export default ConfirmContent; diff --git a/src/components/dashboard/roadItems/supervisor/RowActions/ConfirmForm/index.jsx b/src/components/dashboard/roadItems/supervisor/RowActions/ConfirmForm/index.jsx index d9aafa0..ba7b746 100644 --- a/src/components/dashboard/roadItems/supervisor/RowActions/ConfirmForm/index.jsx +++ b/src/components/dashboard/roadItems/supervisor/RowActions/ConfirmForm/index.jsx @@ -1,29 +1,29 @@ -import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import ConfirmContent from "./ConfirmContent"; -import DoneIcon from "@mui/icons-material/Done"; -const ConfirmForm = ({ rowId, mutate }) => { - const [openConfirmDialog, setOpenConfirmDialog] = useState(false); - return ( - <> - - setOpenConfirmDialog(true)}> - - - - - تایید فعالیت - - - - ); -}; -export default ConfirmForm; +import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import ConfirmContent from "./ConfirmContent"; +import DoneIcon from "@mui/icons-material/Done"; +const ConfirmForm = ({ rowId, mutate }) => { + const [openConfirmDialog, setOpenConfirmDialog] = useState(false); + return ( + <> + + setOpenConfirmDialog(true)}> + + + + + تایید فعالیت + + + + ); +}; +export default ConfirmForm; diff --git a/src/components/dashboard/roadItems/supervisor/RowActions/DeleteForm/DeleteContent.jsx b/src/components/dashboard/roadItems/supervisor/RowActions/DeleteForm/DeleteContent.jsx index 4bfb3ea..e45f68d 100644 --- a/src/components/dashboard/roadItems/supervisor/RowActions/DeleteForm/DeleteContent.jsx +++ b/src/components/dashboard/roadItems/supervisor/RowActions/DeleteForm/DeleteContent.jsx @@ -1,42 +1,42 @@ -import { Button, DialogActions, DialogContent, Stack, Typography } from "@mui/material"; -import React, { useState } from "react"; -import useRequest from "@/lib/hooks/useRequest"; -import { DELETE_BY_SUPERVISOR } from "@/core/utils/routes"; - -const DeleteContent = ({ rowId, mutate, setOpenDeleteDialog }) => { - const [submitting, setSubmitting] = useState(false); - const requestServer = useRequest({ notificationSuccess: true }); - const handleClick = () => { - setSubmitting(true); - requestServer(`${DELETE_BY_SUPERVISOR}/${rowId}`, "post", { - hasSidebarUpdate: true, - }) - .then(() => { - mutate(); - setOpenDeleteDialog(false); - setSubmitting(false); - }) - .catch(() => { - setSubmitting(false); - }); - }; - return ( - <> - - - آیا از حذف فعالیت اطمینان دارید؟ - - - - - - - - ); -}; - -export default DeleteContent; +import { Button, DialogActions, DialogContent, Stack, Typography } from "@mui/material"; +import React, { useState } from "react"; +import useRequest from "@/lib/hooks/useRequest"; +import { DELETE_BY_SUPERVISOR } from "@/core/utils/routes"; + +const DeleteContent = ({ rowId, mutate, setOpenDeleteDialog }) => { + const [submitting, setSubmitting] = useState(false); + const requestServer = useRequest({ notificationSuccess: true }); + const handleClick = () => { + setSubmitting(true); + requestServer(`${DELETE_BY_SUPERVISOR}/${rowId}`, "post", { + hasSidebarUpdate: true, + }) + .then(() => { + mutate(); + setOpenDeleteDialog(false); + setSubmitting(false); + }) + .catch(() => { + setSubmitting(false); + }); + }; + return ( + <> + + + آیا از حذف فعالیت اطمینان دارید؟ + + + + + + + + ); +}; + +export default DeleteContent; diff --git a/src/components/dashboard/roadItems/supervisor/RowActions/DeleteForm/index.jsx b/src/components/dashboard/roadItems/supervisor/RowActions/DeleteForm/index.jsx index 596cf9a..557c628 100644 --- a/src/components/dashboard/roadItems/supervisor/RowActions/DeleteForm/index.jsx +++ b/src/components/dashboard/roadItems/supervisor/RowActions/DeleteForm/index.jsx @@ -1,32 +1,32 @@ -import DeleteIcon from "@mui/icons-material/Delete"; -import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import DeleteContent from "./DeleteContent"; -const DeleteForm = ({ rowId, mutate }) => { - const [openDeleteDialog, setOpenDeleteDialog] = useState(false); - - return ( - <> - - setOpenDeleteDialog(true)}> - - - - setOpenDeleteDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - حذف فعالیت - - - - ); -}; -export default DeleteForm; +import DeleteIcon from "@mui/icons-material/Delete"; +import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import DeleteContent from "./DeleteContent"; +const DeleteForm = ({ rowId, mutate }) => { + const [openDeleteDialog, setOpenDeleteDialog] = useState(false); + + return ( + <> + + setOpenDeleteDialog(true)}> + + + + setOpenDeleteDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + حذف فعالیت + + + + ); +}; +export default DeleteForm; diff --git a/src/components/dashboard/roadItems/supervisor/RowActions/ImageForm/ImageFormContent.jsx b/src/components/dashboard/roadItems/supervisor/RowActions/ImageForm/ImageFormContent.jsx index 9ddb19b..2b52698 100644 --- a/src/components/dashboard/roadItems/supervisor/RowActions/ImageForm/ImageFormContent.jsx +++ b/src/components/dashboard/roadItems/supervisor/RowActions/ImageForm/ImageFormContent.jsx @@ -1,45 +1,45 @@ -import { Box, DialogContent, Paper, Stack, Typography, useTheme } from "@mui/material"; -import Image from "next/image"; - -const ImageFormContent = ({ image, title }) => { - const theme = useTheme(); - return ( - - - {title} - - - Image - - - ); -}; -export default ImageFormContent; +import { Box, DialogContent, Paper, Stack, Typography, useTheme } from "@mui/material"; +import Image from "next/image"; + +const ImageFormContent = ({ image, title }) => { + const theme = useTheme(); + return ( + + + {title} + + + Image + + + ); +}; +export default ImageFormContent; diff --git a/src/components/dashboard/roadItems/supervisor/RowActions/ImageForm/ImagesContent.jsx b/src/components/dashboard/roadItems/supervisor/RowActions/ImageForm/ImagesContent.jsx index 6414e24..7c88f12 100644 --- a/src/components/dashboard/roadItems/supervisor/RowActions/ImageForm/ImagesContent.jsx +++ b/src/components/dashboard/roadItems/supervisor/RowActions/ImageForm/ImagesContent.jsx @@ -1,43 +1,43 @@ -import { useEffect, useState } from "react"; -import ImageFormContent from "./ImageFormContent"; -import DialogLoading from "@/core/components/DialogLoading"; -import useRequest from "@/lib/hooks/useRequest"; -import { GET_IMAGES_ROAD_ITEM } from "@/core/utils/routes"; -import { Typography } from "@mui/material"; - -const ImagesContent = ({ rowId }) => { - const [loading, setLoading] = useState(true); - const [data, setData] = useState(null); - const request = useRequest(); - - useEffect(() => { - const fetchData = async () => { - try { - setLoading(true); - const response = await request(`${GET_IMAGES_ROAD_ITEM}/${rowId}`); - setData(response.data.data); - } catch (error) { - } finally { - setLoading(false); - } - }; - - fetchData(); - }, [rowId]); - - return ( - <> - {loading ? ( - - ) : data ? ( - <> - - - - ) : ( - تصویری در سامانه یافت نشد - )} - - ); -}; -export default ImagesContent; +import { useEffect, useState } from "react"; +import ImageFormContent from "./ImageFormContent"; +import DialogLoading from "@/core/components/DialogLoading"; +import useRequest from "@/lib/hooks/useRequest"; +import { GET_IMAGES_ROAD_ITEM } from "@/core/utils/routes"; +import { Typography } from "@mui/material"; + +const ImagesContent = ({ rowId }) => { + const [loading, setLoading] = useState(true); + const [data, setData] = useState(null); + const request = useRequest(); + + useEffect(() => { + const fetchData = async () => { + try { + setLoading(true); + const response = await request(`${GET_IMAGES_ROAD_ITEM}/${rowId}`); + setData(response.data.data); + } catch (error) { + } finally { + setLoading(false); + } + }; + + fetchData(); + }, [rowId]); + + return ( + <> + {loading ? ( + + ) : data ? ( + <> + + + + ) : ( + تصویری در سامانه یافت نشد + )} + + ); +}; +export default ImagesContent; diff --git a/src/components/dashboard/roadItems/supervisor/RowActions/ImageForm/index.jsx b/src/components/dashboard/roadItems/supervisor/RowActions/ImageForm/index.jsx index 08e9cd9..5080908 100644 --- a/src/components/dashboard/roadItems/supervisor/RowActions/ImageForm/index.jsx +++ b/src/components/dashboard/roadItems/supervisor/RowActions/ImageForm/index.jsx @@ -1,40 +1,40 @@ -import PhotoLibraryIcon from "@mui/icons-material/PhotoLibrary"; -import { Button, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import ImagesContent from "./ImagesContent"; - -const ImageDialog = ({ rowId }) => { - const [openImageDialog, setOpenImageDialog] = useState(false); - - return ( - <> - - setOpenImageDialog(true)}> - - - - setOpenImageDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - maxWidth={"sm"} - scroll="paper" - > - تصاویر - {openImageDialog && } - - - - - - ); -}; - -export default ImageDialog; +import PhotoLibraryIcon from "@mui/icons-material/PhotoLibrary"; +import { Button, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import ImagesContent from "./ImagesContent"; + +const ImageDialog = ({ rowId }) => { + const [openImageDialog, setOpenImageDialog] = useState(false); + + return ( + <> + + setOpenImageDialog(true)}> + + + + setOpenImageDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + maxWidth={"sm"} + scroll="paper" + > + تصاویر + {openImageDialog && } + + + + + + ); +}; + +export default ImageDialog; diff --git a/src/components/dashboard/roadItems/supervisor/RowActions/LocationForm/LocationFormContent.jsx b/src/components/dashboard/roadItems/supervisor/RowActions/LocationForm/LocationFormContent.jsx index 1e20921..e00ae19 100644 --- a/src/components/dashboard/roadItems/supervisor/RowActions/LocationForm/LocationFormContent.jsx +++ b/src/components/dashboard/roadItems/supervisor/RowActions/LocationForm/LocationFormContent.jsx @@ -1,36 +1,36 @@ -"use client"; -import { Box, Button, DialogActions, DialogContent, Stack } from "@mui/material"; -import React from "react"; -import dynamic from "next/dynamic"; -import MapLoading from "@/core/components/MapLayer/Loading"; -import ShowLocationMarker from "@/core/components/ShowLocationMarker"; -const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { - loading: () => , - ssr: false, -}); - -const LocationFormContent = ({ setOpenLocationDialog, start_lat, start_lng, end_lat, end_lng }) => { - return ( - <> - - - - - - - - - - - - ); -}; - -export default LocationFormContent; +"use client"; +import { Box, Button, DialogActions, DialogContent, Stack } from "@mui/material"; +import React from "react"; +import dynamic from "next/dynamic"; +import MapLoading from "@/core/components/MapLayer/Loading"; +import ShowLocationMarker from "@/core/components/ShowLocationMarker"; +const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { + loading: () => , + ssr: false, +}); + +const LocationFormContent = ({ setOpenLocationDialog, start_lat, start_lng, end_lat, end_lng }) => { + return ( + <> + + + + + + + + + + + + ); +}; + +export default LocationFormContent; diff --git a/src/components/dashboard/roadItems/supervisor/RowActions/LocationForm/index.jsx b/src/components/dashboard/roadItems/supervisor/RowActions/LocationForm/index.jsx index f578ca8..90a5cb4 100644 --- a/src/components/dashboard/roadItems/supervisor/RowActions/LocationForm/index.jsx +++ b/src/components/dashboard/roadItems/supervisor/RowActions/LocationForm/index.jsx @@ -1,38 +1,38 @@ -import React, { useState } from "react"; -import { Tooltip, IconButton, Dialog, DialogTitle } from "@mui/material"; -import ExploreIcon from "@mui/icons-material/Explore"; -import LocationFormContent from "./LocationFormContent"; -const LocationForm = ({ start_lat, start_lng, end_lat, end_lng }) => { - const [openLocationDialog, setOpenLocationDialog] = useState(false); - - return ( - <> - - setOpenLocationDialog(true)}> - - - - setOpenLocationDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - موقعیت - - - - ); -}; -export default LocationForm; +import React, { useState } from "react"; +import { Tooltip, IconButton, Dialog, DialogTitle } from "@mui/material"; +import ExploreIcon from "@mui/icons-material/Explore"; +import LocationFormContent from "./LocationFormContent"; +const LocationForm = ({ start_lat, start_lng, end_lat, end_lng }) => { + const [openLocationDialog, setOpenLocationDialog] = useState(false); + + return ( + <> + + setOpenLocationDialog(true)}> + + + + setOpenLocationDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + موقعیت + + + + ); +}; +export default LocationForm; diff --git a/src/components/dashboard/roadItems/supervisor/RowActions/MachinesCodeForm/MachinesCodeContent.jsx b/src/components/dashboard/roadItems/supervisor/RowActions/MachinesCodeForm/MachinesCodeContent.jsx index c71be76..3c627f9 100644 --- a/src/components/dashboard/roadItems/supervisor/RowActions/MachinesCodeForm/MachinesCodeContent.jsx +++ b/src/components/dashboard/roadItems/supervisor/RowActions/MachinesCodeForm/MachinesCodeContent.jsx @@ -1,79 +1,79 @@ -import DialogLoading from "@/core/components/DialogLoading"; -import ShowPlak from "@/core/components/ShowPlak"; -import { GET_CMMS_MACHINE_ROAD_ITEM } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { - DialogContent, - Table, - TableBody, - TableCell, - TableContainer, - TableHead, - TableRow, - Typography, -} from "@mui/material"; -import { useEffect, useState } from "react"; - -const MachinesCodeContent = ({ rowId }) => { - const [loading, setLoading] = useState(true); - const [data, setData] = useState(null); - const request = useRequest(); - - useEffect(() => { - const fetchData = async () => { - try { - setLoading(true); - const response = await request(`${GET_CMMS_MACHINE_ROAD_ITEM}/${rowId}`); - setData(response.data.data); - } catch (error) { - } finally { - setLoading(false); - } - }; - - fetchData(); - }, [rowId]); - - return ( - <> - - {loading ? ( - - ) : data ? ( - - - - - کد ماشین - نام خودرو - پلاک - - - - {data.map((machine) => { - return ( - - {machine.machine_code} - {machine.car_name} - - {machine.plak_number ? ( - - ) : null} - - - ); - })} - -
    -
    - ) : ( - اطلاعات خودرویی در سامانه یافت نشد - )} -
    - - ); -}; -export default MachinesCodeContent; +import DialogLoading from "@/core/components/DialogLoading"; +import ShowPlak from "@/core/components/ShowPlak"; +import { GET_CMMS_MACHINE_ROAD_ITEM } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { + DialogContent, + Table, + TableBody, + TableCell, + TableContainer, + TableHead, + TableRow, + Typography, +} from "@mui/material"; +import { useEffect, useState } from "react"; + +const MachinesCodeContent = ({ rowId }) => { + const [loading, setLoading] = useState(true); + const [data, setData] = useState(null); + const request = useRequest(); + + useEffect(() => { + const fetchData = async () => { + try { + setLoading(true); + const response = await request(`${GET_CMMS_MACHINE_ROAD_ITEM}/${rowId}`); + setData(response.data.data); + } catch (error) { + } finally { + setLoading(false); + } + }; + + fetchData(); + }, [rowId]); + + return ( + <> + + {loading ? ( + + ) : data ? ( + + + + + کد ماشین + نام خودرو + پلاک + + + + {data.map((machine) => { + return ( + + {machine.machine_code} + {machine.car_name} + + {machine.plak_number ? ( + + ) : null} + + + ); + })} + +
    +
    + ) : ( + اطلاعات خودرویی در سامانه یافت نشد + )} +
    + + ); +}; +export default MachinesCodeContent; diff --git a/src/components/dashboard/roadItems/supervisor/RowActions/MachinesCodeForm/index.jsx b/src/components/dashboard/roadItems/supervisor/RowActions/MachinesCodeForm/index.jsx index 685fd06..fc0ce01 100644 --- a/src/components/dashboard/roadItems/supervisor/RowActions/MachinesCodeForm/index.jsx +++ b/src/components/dashboard/roadItems/supervisor/RowActions/MachinesCodeForm/index.jsx @@ -1,43 +1,43 @@ -import { Button, Dialog, DialogActions, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import DirectionsCarIcon from "@mui/icons-material/DirectionsCar"; -import { useState } from "react"; -import MachinesCodeContent from "./MachinesCodeContent"; - -const MachinesCodeDialog = ({ rowId }) => { - const [openMachinesCodeDialog, setOpenMachinesCodeDialog] = useState(false); - return ( - <> - - setOpenMachinesCodeDialog(true)}> - - - - setOpenMachinesCodeDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - خودرو ها - {openMachinesCodeDialog && } - - - - - - ); -}; -export default MachinesCodeDialog; +import { Button, Dialog, DialogActions, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import DirectionsCarIcon from "@mui/icons-material/DirectionsCar"; +import { useState } from "react"; +import MachinesCodeContent from "./MachinesCodeContent"; + +const MachinesCodeDialog = ({ rowId }) => { + const [openMachinesCodeDialog, setOpenMachinesCodeDialog] = useState(false); + return ( + <> + + setOpenMachinesCodeDialog(true)}> + + + + setOpenMachinesCodeDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + خودرو ها + {openMachinesCodeDialog && } + + + + + + ); +}; +export default MachinesCodeDialog; diff --git a/src/components/dashboard/roadItems/supervisor/RowActions/RahdaranForm/RahdaranContent.jsx b/src/components/dashboard/roadItems/supervisor/RowActions/RahdaranForm/RahdaranContent.jsx index c4e562f..0706033 100644 --- a/src/components/dashboard/roadItems/supervisor/RowActions/RahdaranForm/RahdaranContent.jsx +++ b/src/components/dashboard/roadItems/supervisor/RowActions/RahdaranForm/RahdaranContent.jsx @@ -1,72 +1,72 @@ -import DialogLoading from "@/core/components/DialogLoading"; -import { GET_RAHDARAN_ROAD_ITEM } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { - DialogContent, - Table, - TableBody, - TableCell, - TableContainer, - TableHead, - TableRow, - Typography, -} from "@mui/material"; -import { useEffect, useState } from "react"; - -const RahdaranContent = ({ rowId }) => { - const [loading, setLoading] = useState(true); - const [data, setData] = useState(null); - const request = useRequest(); - - useEffect(() => { - const fetchData = async () => { - try { - setLoading(true); - const response = await request(`${GET_RAHDARAN_ROAD_ITEM}/${rowId}`); - setData(response.data.data); - } catch (error) { - } finally { - setLoading(false); - } - }; - - fetchData(); - }, [rowId]); - - return ( - <> - - {loading ? ( - - ) : data ? ( - - - - - کد راهدار - نام - - - - {data.map((rahdar) => { - return ( - - {rahdar.code} - {rahdar.name} - - ); - })} - -
    -
    - ) : ( - اطلاعات راهداران در سامانه یافت نشد - )} -
    - - ); -}; -export default RahdaranContent; +import DialogLoading from "@/core/components/DialogLoading"; +import { GET_RAHDARAN_ROAD_ITEM } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { + DialogContent, + Table, + TableBody, + TableCell, + TableContainer, + TableHead, + TableRow, + Typography, +} from "@mui/material"; +import { useEffect, useState } from "react"; + +const RahdaranContent = ({ rowId }) => { + const [loading, setLoading] = useState(true); + const [data, setData] = useState(null); + const request = useRequest(); + + useEffect(() => { + const fetchData = async () => { + try { + setLoading(true); + const response = await request(`${GET_RAHDARAN_ROAD_ITEM}/${rowId}`); + setData(response.data.data); + } catch (error) { + } finally { + setLoading(false); + } + }; + + fetchData(); + }, [rowId]); + + return ( + <> + + {loading ? ( + + ) : data ? ( + + + + + کد راهدار + نام + + + + {data.map((rahdar) => { + return ( + + {rahdar.code} + {rahdar.name} + + ); + })} + +
    +
    + ) : ( + اطلاعات راهداران در سامانه یافت نشد + )} +
    + + ); +}; +export default RahdaranContent; diff --git a/src/components/dashboard/roadItems/supervisor/RowActions/RahdaranForm/index.jsx b/src/components/dashboard/roadItems/supervisor/RowActions/RahdaranForm/index.jsx index e3a2efc..a051c23 100644 --- a/src/components/dashboard/roadItems/supervisor/RowActions/RahdaranForm/index.jsx +++ b/src/components/dashboard/roadItems/supervisor/RowActions/RahdaranForm/index.jsx @@ -1,38 +1,38 @@ -import { Button, Dialog, DialogActions, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import GroupsIcon from "@mui/icons-material/Groups"; -import { useState } from "react"; -import RahdaranContent from "./RahdaranContent"; - -const RahdaranDialog = ({ rowId }) => { - const [openRahdaranDialog, setOpenRahdaranDialog] = useState(false); - return ( - <> - - setOpenRahdaranDialog(true)}> - - - - setOpenRahdaranDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - لیست راهداران - {openRahdaranDialog && } - - - - - - ); -}; -export default RahdaranDialog; +import { Button, Dialog, DialogActions, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import GroupsIcon from "@mui/icons-material/Groups"; +import { useState } from "react"; +import RahdaranContent from "./RahdaranContent"; + +const RahdaranDialog = ({ rowId }) => { + const [openRahdaranDialog, setOpenRahdaranDialog] = useState(false); + return ( + <> + + setOpenRahdaranDialog(true)}> + + + + setOpenRahdaranDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + لیست راهداران + {openRahdaranDialog && } + + + + + + ); +}; +export default RahdaranDialog; diff --git a/src/components/dashboard/roadItems/supervisor/RowActions/RejectForm/RejectContent.jsx b/src/components/dashboard/roadItems/supervisor/RowActions/RejectForm/RejectContent.jsx index 8702ea4..f747e34 100644 --- a/src/components/dashboard/roadItems/supervisor/RowActions/RejectForm/RejectContent.jsx +++ b/src/components/dashboard/roadItems/supervisor/RowActions/RejectForm/RejectContent.jsx @@ -1,84 +1,84 @@ -import { Button, DialogActions, DialogContent, Stack, TextField } from "@mui/material"; -import { useForm } from "react-hook-form"; -import { yupResolver } from "@hookform/resolvers/yup"; -import * as Yup from "yup"; -import useRequest from "@/lib/hooks/useRequest"; -import { REJECT_BY_SUPERVISOR } from "@/core/utils/routes"; - -const RejectContent = ({ rowId, mutate, setOpenRejectDialog }) => { - const requestServer = useRequest({ notificationSuccess: true }); - - const validationSchema = Yup.object().shape({ - description: Yup.string().required("لطفاً توضیحات را وارد کنید."), - }); - - const { - register, - handleSubmit, - formState: { errors, isSubmitting }, - reset, - } = useForm({ - defaultValues: { - description: "", - }, - resolver: yupResolver(validationSchema), - mode: "all", - }); - - const onSubmit = async (data) => { - const formData = new FormData(); - formData.append("description", data.description); - formData.append("verify", 2); - await requestServer(`${REJECT_BY_SUPERVISOR}/${rowId}`, "post", { - data: formData, - hasSidebarUpdate: true, - }) - .then(() => { - mutate(); - setOpenRejectDialog(false); - }) - .catch(() => {}) - .finally(() => { - reset(); - }); - }; - - return ( - <> - - - - - - - - - - - - - ); -}; -export default RejectContent; +import { Button, DialogActions, DialogContent, Stack, TextField } from "@mui/material"; +import { useForm } from "react-hook-form"; +import { yupResolver } from "@hookform/resolvers/yup"; +import * as Yup from "yup"; +import useRequest from "@/lib/hooks/useRequest"; +import { REJECT_BY_SUPERVISOR } from "@/core/utils/routes"; + +const RejectContent = ({ rowId, mutate, setOpenRejectDialog }) => { + const requestServer = useRequest({ notificationSuccess: true }); + + const validationSchema = Yup.object().shape({ + description: Yup.string().required("لطفاً توضیحات را وارد کنید."), + }); + + const { + register, + handleSubmit, + formState: { errors, isSubmitting }, + reset, + } = useForm({ + defaultValues: { + description: "", + }, + resolver: yupResolver(validationSchema), + mode: "all", + }); + + const onSubmit = async (data) => { + const formData = new FormData(); + formData.append("description", data.description); + formData.append("verify", 2); + await requestServer(`${REJECT_BY_SUPERVISOR}/${rowId}`, "post", { + data: formData, + hasSidebarUpdate: true, + }) + .then(() => { + mutate(); + setOpenRejectDialog(false); + }) + .catch(() => {}) + .finally(() => { + reset(); + }); + }; + + return ( + <> + + + + + + + + + + + + + ); +}; +export default RejectContent; diff --git a/src/components/dashboard/roadItems/supervisor/RowActions/RejectForm/index.jsx b/src/components/dashboard/roadItems/supervisor/RowActions/RejectForm/index.jsx index 2f08152..94f78de 100644 --- a/src/components/dashboard/roadItems/supervisor/RowActions/RejectForm/index.jsx +++ b/src/components/dashboard/roadItems/supervisor/RowActions/RejectForm/index.jsx @@ -1,29 +1,29 @@ -import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import RejectContent from "./RejectContent"; -import ClearIcon from "@mui/icons-material/Clear"; -const RejectForm = ({ rowId, mutate }) => { - const [openRejectDialog, setOpenRejectDialog] = useState(false); - return ( - <> - - setOpenRejectDialog(true)}> - - - - - عدم تایید فعالیت - - - - ); -}; -export default RejectForm; +import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import RejectContent from "./RejectContent"; +import ClearIcon from "@mui/icons-material/Clear"; +const RejectForm = ({ rowId, mutate }) => { + const [openRejectDialog, setOpenRejectDialog] = useState(false); + return ( + <> + + setOpenRejectDialog(true)}> + + + + + عدم تایید فعالیت + + + + ); +}; +export default RejectForm; diff --git a/src/components/dashboard/roadItems/supervisor/RowActions/RestoreForm/RestoreContent.jsx b/src/components/dashboard/roadItems/supervisor/RowActions/RestoreForm/RestoreContent.jsx index 61192d7..fc6b70c 100644 --- a/src/components/dashboard/roadItems/supervisor/RowActions/RestoreForm/RestoreContent.jsx +++ b/src/components/dashboard/roadItems/supervisor/RowActions/RestoreForm/RestoreContent.jsx @@ -1,44 +1,44 @@ -import { Button, DialogActions, DialogContent, Stack, Typography } from "@mui/material"; -import React, { useState } from "react"; -import useRequest from "@/lib/hooks/useRequest"; -import { RESTORE_BY_SUPERVISOR } from "@/core/utils/routes"; - -const RestoreContent = ({ rowId, mutate, setOpenRestoreDialog }) => { - const [submitting, setSubmitting] = useState(false); - const requestServer = useRequest({ notificationSuccess: true }); - const handleClick = () => { - setSubmitting(true); - requestServer(`${RESTORE_BY_SUPERVISOR}/${rowId}`, "post", { - hasSidebarUpdate: true, - }) - .then(() => { - mutate(); - setOpenRestoreDialog(false); - setSubmitting(false); - }) - .catch(() => { - setSubmitting(false); - }); - }; - return ( - <> - - - - آیا از بازگردانی فعالیت اطمینان دارید؟ - - - - - - - - - ); -}; - -export default RestoreContent; +import { Button, DialogActions, DialogContent, Stack, Typography } from "@mui/material"; +import React, { useState } from "react"; +import useRequest from "@/lib/hooks/useRequest"; +import { RESTORE_BY_SUPERVISOR } from "@/core/utils/routes"; + +const RestoreContent = ({ rowId, mutate, setOpenRestoreDialog }) => { + const [submitting, setSubmitting] = useState(false); + const requestServer = useRequest({ notificationSuccess: true }); + const handleClick = () => { + setSubmitting(true); + requestServer(`${RESTORE_BY_SUPERVISOR}/${rowId}`, "post", { + hasSidebarUpdate: true, + }) + .then(() => { + mutate(); + setOpenRestoreDialog(false); + setSubmitting(false); + }) + .catch(() => { + setSubmitting(false); + }); + }; + return ( + <> + + + + آیا از بازگردانی فعالیت اطمینان دارید؟ + + + + + + + + + ); +}; + +export default RestoreContent; diff --git a/src/components/dashboard/roadItems/supervisor/RowActions/RestoreForm/index.jsx b/src/components/dashboard/roadItems/supervisor/RowActions/RestoreForm/index.jsx index 2632c20..08668c9 100644 --- a/src/components/dashboard/roadItems/supervisor/RowActions/RestoreForm/index.jsx +++ b/src/components/dashboard/roadItems/supervisor/RowActions/RestoreForm/index.jsx @@ -1,32 +1,32 @@ -import React, { useState } from "react"; -import { Tooltip, IconButton, Dialog, DialogTitle } from "@mui/material"; -import ReplyIcon from "@mui/icons-material/Reply"; -import RestoreContent from "./RestoreContent"; -const RestoreForm = ({ rowId, mutate }) => { - const [openRestoreDialog, setOpenRestoreDialog] = useState(false); - - return ( - <> - - setOpenRestoreDialog(true)}> - - - - setOpenRestoreDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - بازگردانی فعالیت - - - - ); -}; -export default RestoreForm; +import React, { useState } from "react"; +import { Tooltip, IconButton, Dialog, DialogTitle } from "@mui/material"; +import ReplyIcon from "@mui/icons-material/Reply"; +import RestoreContent from "./RestoreContent"; +const RestoreForm = ({ rowId, mutate }) => { + const [openRestoreDialog, setOpenRestoreDialog] = useState(false); + + return ( + <> + + setOpenRestoreDialog(true)}> + + + + setOpenRestoreDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + بازگردانی فعالیت + + + + ); +}; +export default RestoreForm; diff --git a/src/components/dashboard/roadItems/supervisor/RowActions/index.jsx b/src/components/dashboard/roadItems/supervisor/RowActions/index.jsx index 971ad37..5499006 100644 --- a/src/components/dashboard/roadItems/supervisor/RowActions/index.jsx +++ b/src/components/dashboard/roadItems/supervisor/RowActions/index.jsx @@ -1,27 +1,27 @@ -import { Box } from "@mui/material"; -import DeleteForm from "./DeleteForm"; -import RejectForm from "./RejectForm"; -import ConfirmForm from "./ConfirmForm"; -import RestoreForm from "./RestoreForm"; -import { usePermissions } from "@/lib/hooks/usePermissions"; - -const RowActions = ({ row, mutate }) => { - const { data: userPermissions } = usePermissions(); - const hasDeletePermission = userPermissions?.includes("delete-road-item"); - const hasRestorePermission = userPermissions?.includes("restore-road-item"); - return ( - - {row.original.status === 0 && row.original.can_supervise === 1 && ( - - )} - {row.original.status === 0 && row.original.can_supervise === 1 && ( - - )} - {hasRestorePermission && row.original.status !== 0 && ( - - )} - {hasDeletePermission && } - - ); -}; -export default RowActions; +import { Box } from "@mui/material"; +import DeleteForm from "./DeleteForm"; +import RejectForm from "./RejectForm"; +import ConfirmForm from "./ConfirmForm"; +import RestoreForm from "./RestoreForm"; +import { usePermissions } from "@/lib/hooks/usePermissions"; + +const RowActions = ({ row, mutate }) => { + const { data: userPermissions } = usePermissions(); + const hasDeletePermission = userPermissions?.includes("delete-road-item"); + const hasRestorePermission = userPermissions?.includes("restore-road-item"); + return ( + + {row.original.status === 0 && row.original.can_supervise === 1 && ( + + )} + {row.original.status === 0 && row.original.can_supervise === 1 && ( + + )} + {hasRestorePermission && row.original.status !== 0 && ( + + )} + {hasDeletePermission && } + + ); +}; +export default RowActions; diff --git a/src/components/dashboard/roadItems/supervisor/SupervisorList.jsx b/src/components/dashboard/roadItems/supervisor/SupervisorList.jsx index 2ba551c..807f417 100644 --- a/src/components/dashboard/roadItems/supervisor/SupervisorList.jsx +++ b/src/components/dashboard/roadItems/supervisor/SupervisorList.jsx @@ -1,438 +1,438 @@ -import BlinkingCell from "@/core/components/BlinkingCell"; -import CustomSelectByDependency from "@/core/components/DataTable/filter/fieldsType/CustomSelectByDependency"; -import DataTableWithAuth from "@/core/components/DataTableWithAuth"; -import { GET_ROAD_ITEMS_SUPERVISOR_LIST } from "@/core/utils/routes"; -import { useAuth } from "@/lib/contexts/auth"; -import useEdaratLists from "@/lib/hooks/useEdaratLists"; -import { usePermissions } from "@/lib/hooks/usePermissions"; -import useProvinces from "@/lib/hooks/useProvince"; -import useRoadItemGetSubItems from "@/lib/hooks/useRoadItemGetISubtems"; -import useRoadItemGetItems from "@/lib/hooks/useRoadItemGetItems"; -import { Box, Stack, Typography } from "@mui/material"; -import moment from "jalali-moment"; -import { useEffect, useMemo, useState } from "react"; -import ImageDialog from "../operator/RowActions/ImageForm"; -import MachinesCodeDialog from "../operator/RowActions/MachinesCodeForm"; -import RahdaranDialog from "../operator/RowActions/RahdaranForm"; -import RowActions from "./RowActions"; -import LocationForm from "./RowActions/LocationForm"; -import Toolbar from "./Toolbar"; - -const SupervisorList = () => { - const statusOptions = [ - { value: "", label: "همه وضعیت ها" }, - { value: 0, label: "درحال بررسی" }, - { value: 1, label: "تایید" }, - { value: 2, label: "عدم تایید" }, - ]; - const { data: userPermissions } = usePermissions(); - const hasCountryPermission = userPermissions?.includes("show-road-item-supervise-cartable"); - const { user } = useAuth(); - const columns = useMemo(() => { - const dynamicColumns = { - header: "استان", - id: "province_id", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - grow: false, - size: 130, - ColumnSelectComponent: (props) => { - const { provinces, errorProvinces, loadingProvinces } = useProvinces(); - const getColumnSelectOptions = useMemo(() => { - if (loadingProvinces) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorProvinces) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: "کل کشور" }, - ...provinces.map((province) => ({ - value: province.id, - label: province.name_fa, - })), - ]; - }, [provinces, errorProvinces, loadingProvinces]); - return ( - - ); - }, - Cell: ({ renderedCellValue, row }) => <>{row.original.province_fa}, - }; - return [ - { - // accessorKey: "id", - header: "کد یکتا", - id: "id", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - Cell: ({ row }) => , - }, - ...(hasCountryPermission ? [dynamicColumns] : []), - { - header: "اداره", - id: "edarat_id", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - dependencyId: hasCountryPermission ? "province_id" : null, - grow: false, - size: 120, - ColumnSelectComponent: (props) => { - const { edaratList, loadingEdaratList, errorEdaratList } = useEdaratLists( - hasCountryPermission ? props.dependencyFieldValue.value : user.province_id - ); - const [prevDependency, setPrevDependency] = useState( - hasCountryPermission ? props.dependencyFieldValue.value : user.province_id - ); - - const getColumnSelectOptions = useMemo(() => { - if (hasCountryPermission && props.dependencyFieldValue.value === "") { - return [{ value: "empty", label: "ابتدا استان را انتخاب کنید" }]; - } - if (loadingEdaratList) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorEdaratList) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: "کل ادارات" }, - ...edaratList.map((edare) => ({ - value: edare.id, - label: edare.name_fa, - })), - ]; - }, [edaratList, loadingEdaratList, errorEdaratList]); - useEffect(() => { - if (hasCountryPermission) return; - if (prevDependency === props.dependencyFieldValue?.value) return; - props.handleChange({ ...props.filterParameters, value: "" }); - setPrevDependency(props.dependencyFieldValue?.value); - }, [props.dependencyFieldValue?.value, hasCountryPermission]); - return ( - - ); - }, - Cell: ({ renderedCellValue, row }) => <>{row.original.edarat_name}, - }, - { - header: "اطلاعات فعالیت", - id: "info", - enableColumnFilter: false, - enableSorting: false, - grow: false, - size: 50, - columns: [ - { - header: "آیتم فعالیت", - id: "item", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - grow: false, - size: 100, - ColumnSelectComponent: (props) => { - const { itemsList, loadingItemsList, errorItemsList } = useRoadItemGetItems(); - - const getColumnSelectOptions = useMemo(() => { - if (loadingItemsList) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorItemsList) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: "همه آیتم ها" }, - ...itemsList.map((item) => ({ - value: item.id, - label: item.name, - })), - ]; - }, [itemsList, loadingItemsList, errorItemsList]); - - return ( - - ); - }, - Cell: ({ row }) => { - return row.original.item_fa; - }, - }, - { - header: "اقدام انجام شده", - id: "sub_item", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - dependencyId: "item", - ColumnSelectComponent: (props) => { - const { subItemsList, loadingSubItemsList, errorSubItemsList } = useRoadItemGetSubItems( - props.dependencyFieldValue.value - ); - const [prevDependency, setPrevDependency] = useState(props.dependencyFieldValue.value); - - const getColumnSelectOptions = useMemo(() => { - if (props.dependencyFieldValue.value === "") { - return [{ value: "empty", label: "ابتدا آیتم فعالیت را انتخاب کنید" }]; - } - if (loadingSubItemsList) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorSubItemsList) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: "همه اقدام ها" }, - ...subItemsList.map((item) => ({ - value: item.sub_item, - label: item.name, - })), - ]; - }, [subItemsList, loadingSubItemsList, errorSubItemsList]); - - useEffect(() => { - if (prevDependency === props.dependencyFieldValue.value) return; - props.handleChange({ ...props.filterParameters, value: "" }); - setPrevDependency(props.dependencyFieldValue.value); - }, [props.dependencyFieldValue.value]); - return ( - - ); - }, - Cell: ({ row }) => { - return row.original.sub_item_fa; - }, - }, - { - header: "مقدار", // Value - id: "value", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - filterMode: "equals", - grow: false, - size: 120, - columnFilterModeOptions: ["equals", "contains"], - Cell: ({ renderedCellValue, row }) => { - return ( - - - {(row.original.sub_item_data / 1).toLocaleString()} - - - {`(${row.original.unit_fa})`} - - - ); - }, - }, - { - header: "تصاویر", - id: "images", - enableColumnFilter: false, - enableSorting: false, - datatype: "array", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue, row }) => { - return ( - - - - ); - }, - }, - { - header: "موقعیت", // Location - id: "location", - enableColumnFilter: false, - enableSorting: false, - datatype: "array", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue, row }) => { - return ( - - - - ); - }, - }, - { - header: "خودرو ها", - id: "cmmsMachines__machine_code", - enableColumnFilter: true, - datatype: "text", - filterMode: "contains", - enableSorting: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue, row }) => { - return ( - - - - ); - }, - }, - { - header: "راهداران", - id: "rahdaran__code", - enableColumnFilter: true, - enableSorting: false, - datatype: "text", - filterMode: "contains", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue, row }) => { - return ( - - - - ); - }, - }, - { - accessorFn: (row) => moment(row.activity_date_time).locale("fa").format("HH:mm | yyyy/MM/DD"), - header: "تاریخ فعالیت", // Start Date - id: "activity_date_time", - enableColumnFilter: true, - datatype: "date", - filterMode: "between", - grow: false, - size: 100, - }, - ], - }, - { - accessorFn: (row) => moment(row.created_at).locale("fa").format("HH:mm | yyyy/MM/DD"), - header: "تاریخ ثبت", // Register Date - id: "created_at", - enableColumnFilter: true, - datatype: "date", - filterMode: "between", - grow: false, - size: 100, - }, - { - header: "وضعیت نظارت", - id: "status", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - sortDescFirst: true, - grow: false, - size: 100, - columnSelectOption: () => { - return statusOptions.map((status) => ({ - value: status.value, - label: status.label, - })); - }, - Cell: ({ renderedCellValue, row }) => <>{row.original.status_fa}, - }, - ]; - }, [hasCountryPermission]); - - return ( - <> - - - - - ); -}; - -export default SupervisorList; +import BlinkingCell from "@/core/components/BlinkingCell"; +import CustomSelectByDependency from "@/core/components/DataTable/filter/fieldsType/CustomSelectByDependency"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import { GET_ROAD_ITEMS_SUPERVISOR_LIST } from "@/core/utils/routes"; +import { useAuth } from "@/lib/contexts/auth"; +import useEdaratLists from "@/lib/hooks/useEdaratLists"; +import { usePermissions } from "@/lib/hooks/usePermissions"; +import useProvinces from "@/lib/hooks/useProvince"; +import useRoadItemGetSubItems from "@/lib/hooks/useRoadItemGetISubtems"; +import useRoadItemGetItems from "@/lib/hooks/useRoadItemGetItems"; +import { Box, Stack, Typography } from "@mui/material"; +import moment from "jalali-moment"; +import { useEffect, useMemo, useState } from "react"; +import ImageDialog from "../operator/RowActions/ImageForm"; +import MachinesCodeDialog from "../operator/RowActions/MachinesCodeForm"; +import RahdaranDialog from "../operator/RowActions/RahdaranForm"; +import RowActions from "./RowActions"; +import LocationForm from "./RowActions/LocationForm"; +import Toolbar from "./Toolbar"; + +const SupervisorList = () => { + const statusOptions = [ + { value: "", label: "همه وضعیت ها" }, + { value: 0, label: "درحال بررسی" }, + { value: 1, label: "تایید" }, + { value: 2, label: "عدم تایید" }, + ]; + const { data: userPermissions } = usePermissions(); + const hasCountryPermission = userPermissions?.includes("show-road-item-supervise-cartable"); + const { user } = useAuth(); + const columns = useMemo(() => { + const dynamicColumns = { + header: "استان", + id: "province_id", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 130, + ColumnSelectComponent: (props) => { + const { provinces, errorProvinces, loadingProvinces } = useProvinces(); + const getColumnSelectOptions = useMemo(() => { + if (loadingProvinces) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorProvinces) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: "کل کشور" }, + ...provinces.map((province) => ({ + value: province.id, + label: province.name_fa, + })), + ]; + }, [provinces, errorProvinces, loadingProvinces]); + return ( + + ); + }, + Cell: ({ renderedCellValue, row }) => <>{row.original.province_fa}, + }; + return [ + { + // accessorKey: "id", + header: "کد یکتا", + id: "id", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + Cell: ({ row }) => , + }, + ...(hasCountryPermission ? [dynamicColumns] : []), + { + header: "اداره", + id: "edarat_id", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + dependencyId: hasCountryPermission ? "province_id" : null, + grow: false, + size: 120, + ColumnSelectComponent: (props) => { + const { edaratList, loadingEdaratList, errorEdaratList } = useEdaratLists( + hasCountryPermission ? props.dependencyFieldValue.value : user.province_id + ); + const [prevDependency, setPrevDependency] = useState( + hasCountryPermission ? props.dependencyFieldValue.value : user.province_id + ); + + const getColumnSelectOptions = useMemo(() => { + if (hasCountryPermission && props.dependencyFieldValue.value === "") { + return [{ value: "empty", label: "ابتدا استان را انتخاب کنید" }]; + } + if (loadingEdaratList) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorEdaratList) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: "کل ادارات" }, + ...edaratList.map((edare) => ({ + value: edare.id, + label: edare.name_fa, + })), + ]; + }, [edaratList, loadingEdaratList, errorEdaratList]); + useEffect(() => { + if (hasCountryPermission) return; + if (prevDependency === props.dependencyFieldValue?.value) return; + props.handleChange({ ...props.filterParameters, value: "" }); + setPrevDependency(props.dependencyFieldValue?.value); + }, [props.dependencyFieldValue?.value, hasCountryPermission]); + return ( + + ); + }, + Cell: ({ renderedCellValue, row }) => <>{row.original.edarat_name}, + }, + { + header: "اطلاعات فعالیت", + id: "info", + enableColumnFilter: false, + enableSorting: false, + grow: false, + size: 50, + columns: [ + { + header: "آیتم فعالیت", + id: "item", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 100, + ColumnSelectComponent: (props) => { + const { itemsList, loadingItemsList, errorItemsList } = useRoadItemGetItems(); + + const getColumnSelectOptions = useMemo(() => { + if (loadingItemsList) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorItemsList) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: "همه آیتم ها" }, + ...itemsList.map((item) => ({ + value: item.id, + label: item.name, + })), + ]; + }, [itemsList, loadingItemsList, errorItemsList]); + + return ( + + ); + }, + Cell: ({ row }) => { + return row.original.item_fa; + }, + }, + { + header: "اقدام انجام شده", + id: "sub_item", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + dependencyId: "item", + ColumnSelectComponent: (props) => { + const { subItemsList, loadingSubItemsList, errorSubItemsList } = useRoadItemGetSubItems( + props.dependencyFieldValue.value + ); + const [prevDependency, setPrevDependency] = useState(props.dependencyFieldValue.value); + + const getColumnSelectOptions = useMemo(() => { + if (props.dependencyFieldValue.value === "") { + return [{ value: "empty", label: "ابتدا آیتم فعالیت را انتخاب کنید" }]; + } + if (loadingSubItemsList) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorSubItemsList) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: "همه اقدام ها" }, + ...subItemsList.map((item) => ({ + value: item.sub_item, + label: item.name, + })), + ]; + }, [subItemsList, loadingSubItemsList, errorSubItemsList]); + + useEffect(() => { + if (prevDependency === props.dependencyFieldValue.value) return; + props.handleChange({ ...props.filterParameters, value: "" }); + setPrevDependency(props.dependencyFieldValue.value); + }, [props.dependencyFieldValue.value]); + return ( + + ); + }, + Cell: ({ row }) => { + return row.original.sub_item_fa; + }, + }, + { + header: "مقدار", // Value + id: "value", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + filterMode: "equals", + grow: false, + size: 120, + columnFilterModeOptions: ["equals", "contains"], + Cell: ({ renderedCellValue, row }) => { + return ( + + + {(row.original.sub_item_data / 1).toLocaleString()} + + + {`(${row.original.unit_fa})`} + + + ); + }, + }, + { + header: "تصاویر", + id: "images", + enableColumnFilter: false, + enableSorting: false, + datatype: "array", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue, row }) => { + return ( + + + + ); + }, + }, + { + header: "موقعیت", // Location + id: "location", + enableColumnFilter: false, + enableSorting: false, + datatype: "array", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue, row }) => { + return ( + + + + ); + }, + }, + { + header: "خودرو ها", + id: "cmmsMachines__machine_code", + enableColumnFilter: true, + datatype: "text", + filterMode: "contains", + enableSorting: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue, row }) => { + return ( + + + + ); + }, + }, + { + header: "راهداران", + id: "rahdaran__code", + enableColumnFilter: true, + enableSorting: false, + datatype: "text", + filterMode: "contains", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue, row }) => { + return ( + + + + ); + }, + }, + { + accessorFn: (row) => moment(row.activity_date_time).locale("fa").format("HH:mm | yyyy/MM/DD"), + header: "تاریخ فعالیت", // Start Date + id: "activity_date_time", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + ], + }, + { + accessorFn: (row) => moment(row.created_at).locale("fa").format("HH:mm | yyyy/MM/DD"), + header: "تاریخ ثبت", // Register Date + id: "created_at", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + { + header: "وضعیت نظارت", + id: "status", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + sortDescFirst: true, + grow: false, + size: 100, + columnSelectOption: () => { + return statusOptions.map((status) => ({ + value: status.value, + label: status.label, + })); + }, + Cell: ({ renderedCellValue, row }) => <>{row.original.status_fa}, + }, + ]; + }, [hasCountryPermission]); + + return ( + <> + + + + + ); +}; + +export default SupervisorList; diff --git a/src/components/dashboard/roadItems/supervisor/Toolbar.jsx b/src/components/dashboard/roadItems/supervisor/Toolbar.jsx index 32c4395..b62f822 100644 --- a/src/components/dashboard/roadItems/supervisor/Toolbar.jsx +++ b/src/components/dashboard/roadItems/supervisor/Toolbar.jsx @@ -1,10 +1,10 @@ -import PrintExcel from "./ExcelPrint"; - -const Toolbar = ({ table, filterData }) => { - return ( - <> - - - ); -}; -export default Toolbar; +import PrintExcel from "./ExcelPrint"; + +const Toolbar = ({ table, filterData }) => { + return ( + <> + + + ); +}; +export default Toolbar; diff --git a/src/components/dashboard/roadItems/supervisor/index.jsx b/src/components/dashboard/roadItems/supervisor/index.jsx index 784a066..49583a7 100644 --- a/src/components/dashboard/roadItems/supervisor/index.jsx +++ b/src/components/dashboard/roadItems/supervisor/index.jsx @@ -1,14 +1,14 @@ -"use client"; -import PageTitle from "@/core/components/PageTitle"; -import { Stack } from "@mui/material"; -import SupervisorList from "./SupervisorList"; - -const SupervisorPage = () => { - return ( - - - - - ); -}; -export default SupervisorPage; +"use client"; +import PageTitle from "@/core/components/PageTitle"; +import { Stack } from "@mui/material"; +import SupervisorList from "./SupervisorList"; + +const SupervisorPage = () => { + return ( + + + + + ); +}; +export default SupervisorPage; diff --git a/src/components/dashboard/roadMissions/control/Actions/showArea/index.jsx b/src/components/dashboard/roadMissions/control/Actions/showArea/index.jsx new file mode 100644 index 0000000..4232c07 --- /dev/null +++ b/src/components/dashboard/roadMissions/control/Actions/showArea/index.jsx @@ -0,0 +1,55 @@ +import MapLayer from "@/core/components/MapLayer"; +import { Close, RemoveRedEye } from "@mui/icons-material"; +import { Box, Dialog, DialogContent, DialogTitle, IconButton, Tooltip, Typography } from "@mui/material"; +import { useMemo, useState } from "react"; +import ShowBound from "../showBound"; +import L from "leaflet"; + +const ShowArea = ({ area }) => { + const bound = useMemo(() => L.polygon([...area]), [area]); + const [openAreaDialog, setOpenAreaDialog] = useState(false); + + return ( + <> + + setOpenAreaDialog(true)}> + + + + setOpenAreaDialog(false)} + PaperProps={{ + sx: { + transition: "all .3s", + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + borderRadius: 2, + padding: 1, + }, + }} + maxWidth="sm" + fullWidth + dir="rtl" + > + + + محدوده + + setOpenAreaDialog(false)} size="small"> + + + + + + + + + + + + + + + ); +}; +export default ShowArea; diff --git a/src/components/dashboard/roadMissions/control/Actions/showBound/index.jsx b/src/components/dashboard/roadMissions/control/Actions/showBound/index.jsx new file mode 100644 index 0000000..43dd0b8 --- /dev/null +++ b/src/components/dashboard/roadMissions/control/Actions/showBound/index.jsx @@ -0,0 +1,29 @@ +import { useEffect, useRef } from "react"; +import { FeatureGroup, useMap } from "react-leaflet"; + +const ShowBound = ({ bound }) => { + const map = useMap(); + const featureRef = useRef(null); + + const safeFitBounds = (layer) => { + if (!layer || !map) return; + try { + const latLngs = layer.getLatLngs(); + map.fitBounds(latLngs, { + paddingTopLeft: [20, 20], + paddingBottomRight: [20, 20], + }); + } catch (e) { + console.warn("fitBounds failed:", e); + } + }; + + useEffect(() => { + bound?.editing?.disable(); + featureRef.current.addLayer(bound); + safeFitBounds(bound); + }, []); + + return ; +}; +export default ShowBound; diff --git a/src/components/dashboard/roadMissions/control/ControlList.jsx b/src/components/dashboard/roadMissions/control/ControlList.jsx new file mode 100644 index 0000000..45edcdf --- /dev/null +++ b/src/components/dashboard/roadMissions/control/ControlList.jsx @@ -0,0 +1,125 @@ +"use client"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import { GET_ROAD_MISSIONS_CONTROL_LIST } from "@/core/utils/routes"; +import { Box, Stack } from "@mui/material"; +import moment from "jalali-moment"; +import { useMemo } from "react"; +import ShowArea from "./Actions/showArea"; +import RowActions from "./RowActions"; + +const ControlList = () => { + const typeOptions = [ + { value: 1, label: "روزانه" }, + { value: 2, label: "ساعتی" }, + ]; + + const columns = useMemo( + () => [ + { + accessorKey: "id", + header: "کد یکتا", + id: "id", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "type", + header: "نوع", + id: "type", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + sortDescFirst: true, + grow: false, + size: 100, + columnSelectOption: () => { + return typeOptions.map((type) => ({ + value: type.value, + label: type.label, + })); + }, + Cell: ({ row }) => row.original.type_fa, + }, + { + accessorFn: (row) => moment(row.start_date).locale("fa").format("HH:mm | yyyy/MM/DD"), + header: "تاریخ شروع", + id: "start_date", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + { + accessorFn: (row) => moment(row.end_date).locale("fa").format("HH:mm | yyyy/MM/DD"), + header: "تاریخ پایان", + id: "end_date", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + { + accessorKey: "end_point", + header: "مقصد", + id: "end_point", + enableColumnFilter: false, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 100, + }, + { + header: "محدوده", + id: "area", + enableColumnFilter: false, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => + row.original.area ? ( + + + + ) : ( + "-" + ), + }, + ], + [] + ); + + return ( + <> + + + + + ); +}; +export default ControlList; diff --git a/src/components/dashboard/roadMissions/control/RowActions/FinishMission/FinishMissionContent.jsx b/src/components/dashboard/roadMissions/control/RowActions/FinishMission/FinishMissionContent.jsx new file mode 100644 index 0000000..243d6ab --- /dev/null +++ b/src/components/dashboard/roadMissions/control/RowActions/FinishMission/FinishMissionContent.jsx @@ -0,0 +1,42 @@ +import { FINISH_MISSION } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { Button, DialogActions, DialogContent, Stack, Typography } from "@mui/material"; +import { useState } from "react"; + +const FinishMissionContent = ({ rowId, mutate, setOpenFinishMissionDialog }) => { + const [submitting, setSubmitting] = useState(false); + const requestServer = useRequest({ notificationSuccess: true }); + const handleClick = () => { + setSubmitting(true); + requestServer(`${FINISH_MISSION}/${rowId}`, "post", { + hasSidebarUpdate: true, + }) + .then(() => { + mutate(); + setOpenFinishMissionDialog(false); + setSubmitting(false); + }) + .catch(() => { + setSubmitting(false); + }); + }; + return ( + <> + + + آیا از ورود خودرو و پایان ماموریت اطمینان دارید؟ + + + + + + + + ); +}; + +export default FinishMissionContent; diff --git a/src/components/dashboard/roadMissions/control/RowActions/FinishMission/index.jsx b/src/components/dashboard/roadMissions/control/RowActions/FinishMission/index.jsx new file mode 100644 index 0000000..0fce011 --- /dev/null +++ b/src/components/dashboard/roadMissions/control/RowActions/FinishMission/index.jsx @@ -0,0 +1,36 @@ +import { Login } from "@mui/icons-material"; +import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import FinishMissionContent from "./FinishMissionContent"; +const FinishMission = ({ rowId, mutate }) => { + const [openFinishMissionDialog, setOpenFinishMissionDialog] = useState(false); + + return ( + <> + + setOpenFinishMissionDialog(true)}> + + + + setOpenFinishMissionDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + ورود و پایان ماموریت + + + + ); +}; +export default FinishMission; diff --git a/src/components/dashboard/roadMissions/control/RowActions/StartMission/StartMissionContent.jsx b/src/components/dashboard/roadMissions/control/RowActions/StartMission/StartMissionContent.jsx new file mode 100644 index 0000000..6aa5e78 --- /dev/null +++ b/src/components/dashboard/roadMissions/control/RowActions/StartMission/StartMissionContent.jsx @@ -0,0 +1,42 @@ +import { START_MISSION } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { Button, DialogActions, DialogContent, Stack, Typography } from "@mui/material"; +import { useState } from "react"; + +const StartMissionContent = ({ rowId, mutate, setOpenStartMissionDialog }) => { + const [submitting, setSubmitting] = useState(false); + const requestServer = useRequest({ notificationSuccess: true }); + const handleClick = () => { + setSubmitting(true); + requestServer(`${START_MISSION}/${rowId}`, "post", { + hasSidebarUpdate: true, + }) + .then(() => { + mutate(); + setOpenStartMissionDialog(false); + setSubmitting(false); + }) + .catch(() => { + setSubmitting(false); + }); + }; + return ( + <> + + + آیا از خروج خودرو و شروع ماموریت اطمینان دارید؟ + + + + + + + + ); +}; + +export default StartMissionContent; diff --git a/src/components/dashboard/roadMissions/control/RowActions/StartMission/index.jsx b/src/components/dashboard/roadMissions/control/RowActions/StartMission/index.jsx new file mode 100644 index 0000000..a7ac9f1 --- /dev/null +++ b/src/components/dashboard/roadMissions/control/RowActions/StartMission/index.jsx @@ -0,0 +1,36 @@ +import { Logout } from "@mui/icons-material"; +import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import StartMissionContent from "./StartMissionContent"; +const StartMission = ({ rowId, mutate }) => { + const [openStartMissionDialog, setOpenStartMissionDialog] = useState(false); + + return ( + <> + + setOpenStartMissionDialog(true)}> + + + + setOpenStartMissionDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + خروج و شروع ماموریت + + + + ); +}; +export default StartMission; diff --git a/src/components/dashboard/roadMissions/control/RowActions/index.jsx b/src/components/dashboard/roadMissions/control/RowActions/index.jsx new file mode 100644 index 0000000..ae3cc36 --- /dev/null +++ b/src/components/dashboard/roadMissions/control/RowActions/index.jsx @@ -0,0 +1,13 @@ +import { Box } from "@mui/material"; +import FinishMission from "./FinishMission"; +import StartMission from "./StartMission"; + +const RowActions = ({ row, mutate }) => { + return ( + + {row.original.state_id == 2 && } + {row.original.state_id == 3 && } + + ); +}; +export default RowActions; diff --git a/src/components/dashboard/roadMissions/control/index.jsx b/src/components/dashboard/roadMissions/control/index.jsx new file mode 100644 index 0000000..ac96845 --- /dev/null +++ b/src/components/dashboard/roadMissions/control/index.jsx @@ -0,0 +1,13 @@ +import PageTitle from "@/core/components/PageTitle"; +import { Stack } from "@mui/material"; +import ControlList from "./ControlList"; + +const ControlPage = () => { + return ( + + + + + ); +}; +export default ControlPage; diff --git a/src/components/dashboard/roadMissions/operator/Actions/Create/Form/Area/MapControl/DrawBound/index.jsx b/src/components/dashboard/roadMissions/operator/Actions/Create/Form/Area/MapControl/DrawBound/index.jsx new file mode 100644 index 0000000..639f8fb --- /dev/null +++ b/src/components/dashboard/roadMissions/operator/Actions/Create/Form/Area/MapControl/DrawBound/index.jsx @@ -0,0 +1,116 @@ +import React, { useCallback, useEffect, useRef, useState } from "react"; +import L from "leaflet"; +import { FeatureGroup, useMap } from "react-leaflet"; +import "leaflet-draw"; + +const DrawBound = ({ control, controlDispach, bound, setBound }) => { + const map = useMap(); + const featureRef = useRef(null); + const [area, setArea] = useState(); + const drawControlRef = useRef(null); + + const safeFlyToBounds = (layer) => { + if (!layer || !map) return; + try { + const latLngs = layer.getLatLngs(); + map.flyToBounds(latLngs, { + paddingTopLeft: [20, 35], + paddingBottomRight: [20, 55], + }); + } catch (e) { + console.warn("flyToBounds failed:", e); + } + }; + + const bindEditEvent = (layer) => { + if (!layer) return; + layer.on("edit", function (e) { + const editedLayer = e.target; + setArea(editedLayer); + setBound(editedLayer); + safeFlyToBounds(editedLayer); + }); + }; + + const handlerCreatedBound = useCallback((event) => { + const { layer } = event; + layer.editing.enable(); + featureRef.current.addLayer(layer); // 🟢 اول اضافه به نقشه + setArea(layer); + setBound(layer); + safeFlyToBounds(layer); + bindEditEvent(layer); + controlDispach({ type: "SET_STATUS", status: 2 }); + }, []); + + useEffect(() => { + if ( + control.status === 1 && + drawControlRef.current && + drawControlRef.current._toolbars?.draw?._modes?.polygon?.handler + ) { + drawControlRef.current._toolbars.draw._modes.polygon.handler.enable(); + } + }, [control.status]); + + useEffect(() => { + if (control.status === 0 && area && featureRef.current) { + featureRef.current.removeLayer(area); + setArea(null); + setBound(null); + } + }, [control.status, area]); + + useEffect(() => { + if (control.status === 2 && bound && featureRef.current) { + setArea(bound); + featureRef.current.addLayer(bound); + bound.editing.enable(); + safeFlyToBounds(bound); + bindEditEvent(bound); + } + }, [control.status, bound]); + + useEffect(() => { + if (!featureRef.current) return; + + L.drawLocal.draw.handlers.polygon.tooltip.start = "برای شروع ترسیم محدوده، روی نقشه کلیک کنید"; + L.drawLocal.draw.handlers.polygon.tooltip.cont = "برای ادامه ترسیم، نقاط بعدی را کلیک کنید"; + L.drawLocal.draw.handlers.polygon.tooltip.end = "برای بستن محدوده، روی نقطه‌ی شروع کلیک کنید"; + + const drawControl = new L.Control.Draw({ + draw: { + polygon: { + shapeOptions: { + color: "#3388ff", + weight: 3, + clickable: true, + }, + }, + polyline: false, + rectangle: false, + circle: false, + marker: false, + circlemarker: false, + }, + edit: { + featureGroup: featureRef.current, + edit: true, + remove: false, + }, + }); + + drawControlRef.current = drawControl; + map.addControl(drawControl); + map.on(L.Draw.Event.CREATED, handlerCreatedBound); + + return () => { + map.off(L.Draw.Event.CREATED, handlerCreatedBound); + map.removeControl(drawControl); + }; + }, [map, handlerCreatedBound]); + + return ; +}; + +export default DrawBound; diff --git a/src/components/dashboard/roadMissions/operator/Actions/Create/Form/Area/MapControl/index.jsx b/src/components/dashboard/roadMissions/operator/Actions/Create/Form/Area/MapControl/index.jsx new file mode 100644 index 0000000..bdd1c97 --- /dev/null +++ b/src/components/dashboard/roadMissions/operator/Actions/Create/Form/Area/MapControl/index.jsx @@ -0,0 +1,116 @@ +import { Box, Button, Stack, Typography } from "@mui/material"; +import DrawBound from "./DrawBound"; +import { Delete, Edit, Route } from "@mui/icons-material"; +import { useReducer } from "react"; + +const statusType = [ + { + id: 0, + message: "برای آغاز ترسیم محدوده، کلیک کنید!", + buttons: [ + { + label: "شروع ترسیم محدوده", + key: "start", + color: "primary", + icon: , + onclick: (controlDispach) => { + controlDispach({ type: "SET_STATUS", status: 1 }); + }, + }, + ], + }, + { + id: 1, + message: "محدوده‌ی موردنظر را با کلیک روی نقشه مشخص کنید. برای اتمام، روی نقطه‌ی ابتدایی کلیک کنید!", + buttons: [], + }, + { + id: 2, + message: "برای اصلاح محدوده، گوشه‌ها را بکشید. برای ترسیم دوباره، آن را حذف کنید", + buttons: [ + { + label: "حذف", + key: "end", + color: "error", + icon: , + onclick: (controlDispach) => { + controlDispach({ type: "SET_STATUS", status: 0 }); + }, + }, + ], + }, +]; + +const createInitialState = (bound) => { + if (bound) { + return { status: 2 }; + } + return { status: 0 }; +}; + +const reducer = (state, action) => { + switch (action.type) { + case "SET_STATUS": + return { ...state, status: action.status }; + default: + return state; + } +}; + +const MapControl = ({ bound, setBound }) => { + const [control, controlDispach] = useReducer(reducer, bound, createInitialState); + + return ( + <> + + + theme.palette.info.main, + borderBottomLeftRadius: 8, + borderBottomRightRadius: 8, + py: 0.5, + px: 2, + }} + > + + {statusType.find((st) => st.id == control.status).message} + + + + + + {statusType + .find((st) => st.id == control.status) + .buttons.map((button) => ( + + ))} + + + + ); +}; +export default MapControl; diff --git a/src/components/dashboard/roadMissions/operator/Actions/Create/Form/Area/index.jsx b/src/components/dashboard/roadMissions/operator/Actions/Create/Form/Area/index.jsx new file mode 100644 index 0000000..aaa229c --- /dev/null +++ b/src/components/dashboard/roadMissions/operator/Actions/Create/Form/Area/index.jsx @@ -0,0 +1,39 @@ +import MapLoading from "@/core/components/MapLayer/Loading"; +import { Box, Button, DialogActions, DialogContent } from "@mui/material"; +import dynamic from "next/dynamic"; +import MapControl from "./MapControl"; +import { useCallback, useState } from "react"; +const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { + loading: () => , + ssr: false, +}); + +const Area = ({ allData, setAllData, handlePrev, setTabState }) => { + const [bound, setBound] = useState(allData.bound); + + const handleNext = useCallback(() => { + setAllData({ bound: bound }); + setTabState((s) => s + 1); + }, [bound]); + + return ( + <> + + + + + + + + + + + + + ); +}; +export default Area; diff --git a/src/components/dashboard/roadMissions/operator/Actions/Create/Form/GetItemInfo/MissionDates/index.jsx b/src/components/dashboard/roadMissions/operator/Actions/Create/Form/GetItemInfo/MissionDates/index.jsx new file mode 100644 index 0000000..5e6717f --- /dev/null +++ b/src/components/dashboard/roadMissions/operator/Actions/Create/Form/GetItemInfo/MissionDates/index.jsx @@ -0,0 +1,93 @@ +import MuiDatePicker from "@/core/components/MuiDatePicker"; +import MuiTimePicker from "@/core/components/MuiTimePicker"; +import { Grid } from "@mui/material"; +import { Controller, useWatch } from "react-hook-form"; + +const MissionDates = ({ control }) => { + const type = useWatch({ control, name: "type" }); + return ( + <> + + { + return ( + field.onChange(value || [])} + helperText={error ? error.message : null} + /> + ); + }} + /> + + {type == 2 && ( + + { + return ( + field.onChange(value || null)} + helperText={error ? error.message : null} + /> + ); + }} + /> + + )} + + { + return ( + field.onChange(value || [])} + helperText={error ? error.message : null} + /> + ); + }} + /> + + {type == 2 && ( + + { + return ( + field.onChange(value || null)} + helperText={error ? error.message : null} + /> + ); + }} + /> + + )} + + ); +}; +export default MissionDates; diff --git a/src/components/dashboard/roadMissions/operator/Actions/Create/Form/GetItemInfo/index.jsx b/src/components/dashboard/roadMissions/operator/Actions/Create/Form/GetItemInfo/index.jsx new file mode 100644 index 0000000..66c340c --- /dev/null +++ b/src/components/dashboard/roadMissions/operator/Actions/Create/Form/GetItemInfo/index.jsx @@ -0,0 +1,137 @@ +import PersianTextField from "@/core/components/PersianTextField"; +import SelectBox from "@/core/components/SelectBox"; +import StyledForm from "@/core/components/StyledForm"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { ExitToApp } from "@mui/icons-material"; +import { Box, Button, DialogActions, DialogContent, Grid, Stack } from "@mui/material"; +import { Controller, useForm } from "react-hook-form"; +import { object, string } from "yup"; +import MissionDates from "./MissionDates"; +import moment from "jalali-moment"; + +const validationSchema = object({ + type: string().required("نوع ماموریت را مشخص کنید!"), + start_date: string().required("تاریخ شروع ماموریت را مشخص کنید!"), + start_time: string().when("type", { + is: "2", + then: (schema) => schema.required("زمان شروع ماموریت را مشخص کنید!"), + otherwise: (schema) => schema.notRequired(), + }), + end_date: string().required("تاریخ پایان ماموریت را مشخص کنید!"), + end_time: string().when("type", { + is: "2", + then: (schema) => schema.required("زمان شروع ماموریت را مشخص کنید!"), + otherwise: (schema) => schema.notRequired(), + }), + end_point: string().required("مقصد را مشخص کنید!"), + region: string().required("محور ماموریت را مشخص کنید!"), +}); + +const GetItemInfo = ({ types, regions, allData, setAllData, handlePrev, setTabState }) => { + const defaultValues = { + type: allData.type, + start_date: allData.start_date, + start_time: allData.start_time ? moment(allData.start_time).toDate() : null, + end_date: allData.end_date, + end_time: allData.end_time ? moment(allData.end_time).toDate() : null, + end_point: allData.end_point, + region: allData.region, + }; + + const { control, handleSubmit } = useForm({ + defaultValues, + resolver: yupResolver(validationSchema), + mode: "all", + }); + + const handleNext = (data) => { + setAllData(data); + setTabState((s) => s + 1); + }; + + return ( + + + + + + + ( + + )} + /> + + + ( + + )} + /> + + + + { + return ( + + ); + }} + /> + + + + + + + + + + + ); +}; +export default GetItemInfo; diff --git a/src/components/dashboard/roadMissions/operator/Actions/Create/Form/Rahdaran/Form/index.jsx b/src/components/dashboard/roadMissions/operator/Actions/Create/Form/Rahdaran/Form/index.jsx new file mode 100644 index 0000000..83c23af --- /dev/null +++ b/src/components/dashboard/roadMissions/operator/Actions/Create/Form/Rahdaran/Form/index.jsx @@ -0,0 +1,63 @@ +import RahdarCode from "@/core/components/RahdarCode"; +import StyledForm from "@/core/components/StyledForm"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { Button, Stack } from "@mui/material"; +import { Controller, useForm } from "react-hook-form"; +import { object } from "yup"; + +const schema = object().shape({ + rahdar: object().required("راهدار الزامی است."), +}); +const RahdaranForm = ({ setRahdaran }) => { + const defaultValues = { + rahdar: null, + }; + + const { + control, + handleSubmit, + reset, + formState: { isSubmitting, isValid }, + } = useForm({ defaultValues, resolver: yupResolver(schema), mode: "all" }); + + const submit = (data) => { + setRahdaran((prev) => { + const alreadyExists = prev.some((r) => r.id === data.rahdar.id); + if (alreadyExists) return prev; + return [...prev, data.rahdar]; + }); + reset(); + }; + + return ( + + + + { + return ( + field.onChange(value)} + error={error} + multiple={false} + /> + ); + }} + name={"rahdar"} + /> + + + + + ); +}; +export default RahdaranForm; diff --git a/src/components/dashboard/roadMissions/operator/Actions/Create/Form/Rahdaran/List/index.jsx b/src/components/dashboard/roadMissions/operator/Actions/Create/Form/Rahdaran/List/index.jsx new file mode 100644 index 0000000..133b82c --- /dev/null +++ b/src/components/dashboard/roadMissions/operator/Actions/Create/Form/Rahdaran/List/index.jsx @@ -0,0 +1,56 @@ +import { AccountCircle, Delete } from "@mui/icons-material"; +import { Card, Collapse, IconButton, Stack, Typography } from "@mui/material"; +import { TransitionGroup } from "react-transition-group"; + +const RahdaranList = ({ rahdaran, setRahdaran }) => { + const handleRemove = (index) => { + setRahdaran((prev) => prev.filter((_, i) => i !== index)); + }; + + return ( + + + {rahdaran.map((rahdar, index) => ( + + + + + + + نام و نام خانوادگی: + {rahdar.name} + + + کد راهدار: + {rahdar.code} + + + + handleRemove(index)}> + + + + + ))} + {rahdaran.length == 0 && ( + + راهداری ثبت نشده است + + )} + + + ); +}; +export default RahdaranList; diff --git a/src/components/dashboard/roadMissions/operator/Actions/Create/Form/Rahdaran/index.jsx b/src/components/dashboard/roadMissions/operator/Actions/Create/Form/Rahdaran/index.jsx new file mode 100644 index 0000000..5e1221a --- /dev/null +++ b/src/components/dashboard/roadMissions/operator/Actions/Create/Form/Rahdaran/index.jsx @@ -0,0 +1,36 @@ +import { Box, Button, Chip, DialogActions, DialogContent, Divider } from "@mui/material"; +import { useCallback, useState } from "react"; +import RahdaranForm from "./Form"; +import RahdaranList from "./List"; + +const Rahdaran = ({ allData, setAllData, setTabState, handlePrev }) => { + const [rahdaran, setRahdaran] = useState(allData.rahdaran); + + const handleNext = useCallback(() => { + setAllData({ rahdaran: rahdaran }); + setTabState((s) => s + 1); + }, [rahdaran]); + + return ( + <> + + + + + + + + + + + + + + + ); +}; +export default Rahdaran; diff --git a/src/components/dashboard/roadMissions/operator/Actions/Create/Form/RequestMachines/Form/index.jsx b/src/components/dashboard/roadMissions/operator/Actions/Create/Form/RequestMachines/Form/index.jsx new file mode 100644 index 0000000..b6682a8 --- /dev/null +++ b/src/components/dashboard/roadMissions/operator/Actions/Create/Form/RequestMachines/Form/index.jsx @@ -0,0 +1,89 @@ +import LtrTextField from "@/core/components/LtrTextField"; +import SelectBox from "@/core/components/SelectBox"; +import StyledForm from "@/core/components/StyledForm"; +import { machineType } from "@/core/utils/machineTypes"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { Add } from "@mui/icons-material"; +import { Button, Grid, Stack } from "@mui/material"; +import moment from "jalali-moment"; +import { Controller, useForm } from "react-hook-form"; +import { object, string } from "yup"; + +const validationSchema = object({ + type: string().required("نوع خودرو را مشخص کنید!"), + count: string().required("تعداد خودرو را مشخص کنید!"), +}); + +const RequestMachinesForm = ({ requests, setRequests }) => { + const usedTypeIds = requests.map((r) => r.type); + const filteredMachineTypes = machineType.filter((mt) => !usedTypeIds.includes(mt.id)); + + const defaultValues = { + type: "", + count: "", + }; + + const { control, handleSubmit, reset } = useForm({ + defaultValues, + resolver: yupResolver(validationSchema), + mode: "all", + }); + + const submit = (data) => { + setRequests((r) => [...r, { id: moment().valueOf(), ...data }]); + reset(); + }; + return ( + + + + + ( + + )} + /> + + + ( + { + if (isNaN(Number(e.target.value))) return; + field.onChange(e.target.value); + }} + size="small" + error={!!error} + helperText={!!error && error.message} + type="tel" + label="تعداد خودرو" + /> + )} + /> + + + + + + + + ); +}; +export default RequestMachinesForm; diff --git a/src/components/dashboard/roadMissions/operator/Actions/Create/Form/RequestMachines/List/index.jsx b/src/components/dashboard/roadMissions/operator/Actions/Create/Form/RequestMachines/List/index.jsx new file mode 100644 index 0000000..44ce785 --- /dev/null +++ b/src/components/dashboard/roadMissions/operator/Actions/Create/Form/RequestMachines/List/index.jsx @@ -0,0 +1,59 @@ +import { machineType } from "@/core/utils/machineTypes"; +import { Delete, FireTruck } from "@mui/icons-material"; +import { Card, Collapse, IconButton, Stack, Typography } from "@mui/material"; +import { TransitionGroup } from "react-transition-group"; + +const RequestMachinesList = ({ requests, setRequests }) => { + const handleRemove = (index) => { + setRequests((prev) => prev.filter((_, i) => i !== index)); + }; + + return ( + + + {requests.map((request, index) => ( + + + + + + + نوع خودرو: + + {machineType.find((t) => t.id == request.type)?.name_fa || ""} + + + + تعداد: + {request.count} + + + + handleRemove(index)}> + + + + + ))} + {requests.length == 0 && ( + + درخواستی ثبت نشده است + + )} + + + ); +}; +export default RequestMachinesList; diff --git a/src/components/dashboard/roadMissions/operator/Actions/Create/Form/RequestMachines/index.jsx b/src/components/dashboard/roadMissions/operator/Actions/Create/Form/RequestMachines/index.jsx new file mode 100644 index 0000000..28f6ed0 --- /dev/null +++ b/src/components/dashboard/roadMissions/operator/Actions/Create/Form/RequestMachines/index.jsx @@ -0,0 +1,36 @@ +import { Box, Button, Chip, DialogActions, DialogContent, Divider } from "@mui/material"; +import { useCallback, useState } from "react"; +import RequestMachinesForm from "./Form"; +import RequestMachinesList from "./List"; + +const RequestMachines = ({ allData, setAllData, handlePrev, setTabState }) => { + const [requests, setRequests] = useState(allData.requested_machines); + + const handleNext = useCallback(() => { + setAllData({ requested_machines: requests }); + setTabState((s) => s + 1); + }, [requests]); + + return ( + <> + + + + + + + + + + + + + + + ); +}; +export default RequestMachines; diff --git a/src/components/dashboard/roadMissions/operator/Actions/Create/Form/Verify/index.jsx b/src/components/dashboard/roadMissions/operator/Actions/Create/Form/Verify/index.jsx new file mode 100644 index 0000000..c131573 --- /dev/null +++ b/src/components/dashboard/roadMissions/operator/Actions/Create/Form/Verify/index.jsx @@ -0,0 +1,118 @@ +import MapLoading from "@/core/components/MapLayer/Loading"; +import { Box, Button, Chip, DialogActions, DialogContent, Divider, Stack, Typography } from "@mui/material"; +import dynamic from "next/dynamic"; +import { useCallback } from "react"; +import moment from "jalali-moment"; +import ShowBound from "../../../showBound"; +import { machineType } from "@/core/utils/machineTypes"; +const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { + loading: () => , + ssr: false, +}); + +const Verify = ({ types, regions, allData, handlePrev, submitForm, submitting }) => { + const handleNext = useCallback(() => { + submitForm(allData); + }, [allData]); + + return ( + <> + + + + + + + + + + + + + + نوع ماموریت + + t.id == allData.type).name_fa} /> + + + محدوده ماموریت + + r.id == allData.region).name_fa} /> + + + تاریخ شروع ماموریت + + {allData.type == 2 ? ( + + ) : ( + + )} + + + تاریخ پایان ماموریت + + {allData.type == 2 ? ( + + ) : ( + + )} + + + مقصد + + + + + + + + + {allData.requested_machines.map((request) => ( + + + {machineType.find((mt) => mt.id == request.type).name_fa} + + + + + ))} + + + + + + {allData.rahdaran.map((rahdar) => ( + + {rahdar.name} + + + + ))} + + + + + + + + + + ); +}; +export default Verify; diff --git a/src/components/dashboard/roadMissions/operator/Actions/Create/Form/index.jsx b/src/components/dashboard/roadMissions/operator/Actions/Create/Form/index.jsx new file mode 100644 index 0000000..d26f870 --- /dev/null +++ b/src/components/dashboard/roadMissions/operator/Actions/Create/Form/index.jsx @@ -0,0 +1,133 @@ +import { Engineering, InsertDriveFile, Route, TaxiAlert, Verified } from "@mui/icons-material"; +import { Box, Tab, Tabs } from "@mui/material"; +import { useReducer, useState } from "react"; +import GetItemInfo from "./GetItemInfo"; +import RequestMachines from "./RequestMachines"; +import Rahdaran from "./Rahdaran"; +import Area from "./Area"; +import Verify from "./Verify"; + +const types = [ + { id: 1, name_fa: "روزانه" }, + { id: 2, name_fa: "ساعتی" }, +]; + +const regions = [ + { id: 1, name_fa: "داخل شهر" }, + { id: 2, name_fa: "بیرون شهر - داخل محدوده" }, + { id: 3, name_fa: "بیرون شهر - خارج محدوده" }, +]; + +function TabPanel(props) { + const { children, value, index } = props; + return ( + + ); +} + +const reducer = (state, action) => { + switch (action.type) { + case "changeData": + return { ...state, ...action.data }; + default: + return state; + } +}; + +const CreateForm = ({ defaultValues, submitForm, setOpen, submitting }) => { + const [allData, dispatch] = useReducer(reducer, defaultValues); + const [tabState, setTabState] = useState(0); + const handleClose = () => { + setOpen(false); + }; + const handleChangeTab = (event, newValue) => { + setTabState(newValue); + }; + + const handlePrev = () => { + if (tabState === 0) { + handleClose(); + } else { + setTabState((t) => t - 1); + } + }; + + return ( + <> + + } label="مشخصات" /> + } label="محدوده" /> + } label="خودرو ها" /> + } label="راهداران" /> + } label="بررسی نهایی" /> + + + { + dispatch({ type: "changeData", data }); + }} + handlePrev={handlePrev} + setTabState={setTabState} + /> + + + { + dispatch({ type: "changeData", data }); + }} + handlePrev={handlePrev} + setTabState={setTabState} + /> + + + { + dispatch({ type: "changeData", data }); + }} + handlePrev={handlePrev} + setTabState={setTabState} + /> + + + { + dispatch({ type: "changeData", data }); + }} + handlePrev={handlePrev} + setTabState={setTabState} + /> + + + + + + ); +}; +export default CreateForm; diff --git a/src/components/dashboard/roadMissions/operator/Actions/Create/index.jsx b/src/components/dashboard/roadMissions/operator/Actions/Create/index.jsx new file mode 100644 index 0000000..07a2e1d --- /dev/null +++ b/src/components/dashboard/roadMissions/operator/Actions/Create/index.jsx @@ -0,0 +1,111 @@ +import { AddCircle, Close } from "@mui/icons-material"; +import { Button, Dialog, IconButton, useMediaQuery, useTheme } from "@mui/material"; +import { useState } from "react"; +import CreateForm from "./Form"; +import useRequest from "@/lib/hooks/useRequest"; +import { REQUEST_MISSION } from "@/core/utils/routes"; +import moment from "jalali-moment"; + +const Create = ({ mutate }) => { + const [submitting, setSubmitting] = useState(false); + const requestServer = useRequest({ notificationSuccess: true }); + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const [open, setOpen] = useState(false); + + const handleOpen = () => { + setOpen(true); + }; + + const submitForm = async (result) => { + setSubmitting(true); + const bound = result.bound.getLatLngs(); + let area = bound.map((ring) => ring.map((latlng) => [latlng.lat, latlng.lng])); + + await requestServer(REQUEST_MISSION, "post", { + data: { + area: area[0], + rahdaran: result.rahdaran.map((r) => r.id), + requested_machines: result.requested_machines, + type: result.type, + zone: result.region, + end_point: result.end_point, + ...(result.type == 2 + ? { + start_date: `${result.start_date} ${moment(result.start_time).format("HH:mm")}`, + end_date: `${result.end_date} ${moment(result.end_time).format("HH:mm")}`, + } + : { + start_date: result.start_date, + end_date: result.end_date, + }), + }, + hasSidebarUpdate: true, + }) + .then((response) => { + mutate(); + setOpen(false); + }) + .catch((error) => {}) + .finally(() => { + setSubmitting(false); + }); + }; + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + + setOpen(false)} + sx={(theme) => ({ + position: "absolute", + right: 8, + top: 8, + zIndex: 50, + color: theme.palette.grey[500], + })} + > + + + {open && ( + + )} + + + ); +}; +export default Create; diff --git a/src/components/dashboard/roadMissions/operator/Actions/showArea/index.jsx b/src/components/dashboard/roadMissions/operator/Actions/showArea/index.jsx new file mode 100644 index 0000000..4232c07 --- /dev/null +++ b/src/components/dashboard/roadMissions/operator/Actions/showArea/index.jsx @@ -0,0 +1,55 @@ +import MapLayer from "@/core/components/MapLayer"; +import { Close, RemoveRedEye } from "@mui/icons-material"; +import { Box, Dialog, DialogContent, DialogTitle, IconButton, Tooltip, Typography } from "@mui/material"; +import { useMemo, useState } from "react"; +import ShowBound from "../showBound"; +import L from "leaflet"; + +const ShowArea = ({ area }) => { + const bound = useMemo(() => L.polygon([...area]), [area]); + const [openAreaDialog, setOpenAreaDialog] = useState(false); + + return ( + <> + + setOpenAreaDialog(true)}> + + + + setOpenAreaDialog(false)} + PaperProps={{ + sx: { + transition: "all .3s", + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + borderRadius: 2, + padding: 1, + }, + }} + maxWidth="sm" + fullWidth + dir="rtl" + > + + + محدوده + + setOpenAreaDialog(false)} size="small"> + + + + + + + + + + + + + + + ); +}; +export default ShowArea; diff --git a/src/components/dashboard/roadMissions/operator/Actions/showBound/index.jsx b/src/components/dashboard/roadMissions/operator/Actions/showBound/index.jsx new file mode 100644 index 0000000..43dd0b8 --- /dev/null +++ b/src/components/dashboard/roadMissions/operator/Actions/showBound/index.jsx @@ -0,0 +1,29 @@ +import { useEffect, useRef } from "react"; +import { FeatureGroup, useMap } from "react-leaflet"; + +const ShowBound = ({ bound }) => { + const map = useMap(); + const featureRef = useRef(null); + + const safeFitBounds = (layer) => { + if (!layer || !map) return; + try { + const latLngs = layer.getLatLngs(); + map.fitBounds(latLngs, { + paddingTopLeft: [20, 20], + paddingBottomRight: [20, 20], + }); + } catch (e) { + console.warn("fitBounds failed:", e); + } + }; + + useEffect(() => { + bound?.editing?.disable(); + featureRef.current.addLayer(bound); + safeFitBounds(bound); + }, []); + + return ; +}; +export default ShowBound; diff --git a/src/components/dashboard/roadMissions/operator/OperatorList.jsx b/src/components/dashboard/roadMissions/operator/OperatorList.jsx new file mode 100644 index 0000000..ae85aca --- /dev/null +++ b/src/components/dashboard/roadMissions/operator/OperatorList.jsx @@ -0,0 +1,136 @@ +"use client"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import { GET_ROAD_MISSIONS_OPERATOR_LIST } from "@/core/utils/routes"; +import { Box, Stack } from "@mui/material"; +import moment from "jalali-moment"; +import { useMemo } from "react"; +import ShowArea from "./Actions/showArea"; +import RowActions from "./RowActions"; +import Toolbar from "./Toolbar"; + +const typeOptions = [ + { value: 1, label: "روزانه" }, + { value: 2, label: "ساعتی" }, +]; +const OperatorList = () => { + const columns = useMemo( + () => [ + { + accessorKey: "id", + header: "کد یکتا", + id: "id", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "type", + header: "نوع", + id: "type", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + sortDescFirst: true, + grow: false, + size: 100, + columnSelectOption: () => { + return typeOptions.map((type) => ({ + value: type.value, + label: type.label, + })); + }, + Cell: ({ row }) => row.original.type_fa, + }, + { + accessorFn: (row) => moment(row.start_date).locale("fa").format("HH:mm | yyyy/MM/DD"), + header: "تاریخ شروع", + id: "start_date", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + { + accessorFn: (row) => moment(row.end_date).locale("fa").format("HH:mm | yyyy/MM/DD"), + header: "تاریخ پایان", + id: "end_date", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + { + accessorKey: "end_point", + header: "مقصد", + id: "end_point", + enableColumnFilter: false, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 100, + }, + { + header: "محدوده", + id: "area", + enableColumnFilter: false, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => + row.original.area ? ( + + + + ) : ( + "-" + ), + }, + { + accessorKey: "state_name", + header: "وضعیت", + id: "state_name", + enableColumnFilter: false, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 100, + }, + ], + [] + ); + + return ( + <> + + + + + ); +}; +export default OperatorList; diff --git a/src/components/dashboard/roadMissions/operator/RowActions/Delete/DeleteContent.jsx b/src/components/dashboard/roadMissions/operator/RowActions/Delete/DeleteContent.jsx new file mode 100644 index 0000000..c30ac85 --- /dev/null +++ b/src/components/dashboard/roadMissions/operator/RowActions/Delete/DeleteContent.jsx @@ -0,0 +1,39 @@ +import { DELETE_REQUEST_MISSION } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { Button, DialogActions, DialogContent, Stack, Typography } from "@mui/material"; +import { useState } from "react"; + +const DeleteContent = ({ rowId, mutate, setOpenDeleteDialog }) => { + const [submitting, setSubmitting] = useState(false); + const requestServer = useRequest({ notificationSuccess: true }); + const handleClick = () => { + setSubmitting(true); + requestServer(`${DELETE_REQUEST_MISSION}/${rowId}`, "delete") + .then(() => { + mutate(); + setOpenDeleteDialog(false); + setSubmitting(false); + }) + .catch(() => { + setSubmitting(false); + }); + }; + return ( + <> + + + آیا از حذف ماموریت اطمینان دارید؟ + + + + + + + + ); +}; +export default DeleteContent; diff --git a/src/components/dashboard/roadMissions/operator/RowActions/Delete/index.jsx b/src/components/dashboard/roadMissions/operator/RowActions/Delete/index.jsx new file mode 100644 index 0000000..472756d --- /dev/null +++ b/src/components/dashboard/roadMissions/operator/RowActions/Delete/index.jsx @@ -0,0 +1,34 @@ +import DeleteIcon from "@mui/icons-material/Delete"; +import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import DeleteContent from "./DeleteContent"; +const Delete = ({ rowId, mutate }) => { + const [openDeleteDialog, setOpenDeleteDialog] = useState(false); + + return ( + <> + + setOpenDeleteDialog(true)}> + + + + setOpenDeleteDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + حذف ماموریت + {openDeleteDialog && ( + + )} + + + ); +}; +export default Delete; diff --git a/src/components/dashboard/roadMissions/operator/RowActions/Edit/EditController/index.jsx b/src/components/dashboard/roadMissions/operator/RowActions/Edit/EditController/index.jsx new file mode 100644 index 0000000..40adcc5 --- /dev/null +++ b/src/components/dashboard/roadMissions/operator/RowActions/Edit/EditController/index.jsx @@ -0,0 +1,92 @@ +import { useEffect, useMemo, useState } from "react"; +import useRequest from "@/lib/hooks/useRequest"; +import DialogLoading from "@/core/components/DialogLoading"; +import CreateForm from "../../../Actions/Create/Form"; +import moment from "jalali-moment"; +import L from "leaflet"; +import { GET_RAHDARAN_BY_ID, UPDATE_REQUEST_MISSION } from "@/core/utils/routes"; + +const EditController = ({ row, mutate, openEditDialog, setOpenEditDialog }) => { + const bound = useMemo(() => L.polygon([...row.original.area]), [row.original.area]); + const [submitting, setSubmitting] = useState(false); + const [rahdaran, setRahdaran] = useState(null); + const [rahdaranLoading, setRahdaranLoading] = useState(false); + const requestServer = useRequest(); + + useEffect(() => { + setRahdaranLoading(true); + requestServer(`${GET_RAHDARAN_BY_ID}/${row.original.id}`, "get") + .then((response) => { + setRahdaran(response.data.data); + setRahdaranLoading(false); + }) + .catch((e) => { + setRahdaranLoading(false); + }); + }, [row.original.id]); + + const submitForm = async (result) => { + setSubmitting(true); + const bound = result.bound.getLatLngs(); + let area = bound.map((ring) => ring.map((latlng) => [latlng.lat, latlng.lng])); + + await requestServer(`${UPDATE_REQUEST_MISSION}/${row.original.id}`, "post", { + data: { + area: area[0], + rahdaran: result.rahdaran.map((r) => r.id), + requested_machines: result.requested_machines, + type: result.type, + zone: result.region, + end_point: result.end_point, + ...(result.type == 2 + ? { + start_date: `${result.start_date} ${moment(result.start_time).format("HH:mm")}`, + end_date: `${result.end_date} ${moment(result.end_time).format("HH:mm")}`, + } + : { + start_date: result.start_date, + end_date: result.end_date, + }), + }, + hasSidebarUpdate: true, + notificationSuccess: true, + }) + .then((response) => { + mutate(); + setOpenEditDialog(false); + }) + .catch((error) => {}) + .finally(() => { + setSubmitting(false); + }); + }; + + return ( + <> + {rahdaranLoading ? ( + + ) : ( + + )} + + ); +}; +export default EditController; diff --git a/src/components/dashboard/roadMissions/operator/RowActions/Edit/index.jsx b/src/components/dashboard/roadMissions/operator/RowActions/Edit/index.jsx new file mode 100644 index 0000000..11abb1c --- /dev/null +++ b/src/components/dashboard/roadMissions/operator/RowActions/Edit/index.jsx @@ -0,0 +1,48 @@ +import { BorderColor, Close } from "@mui/icons-material"; +import { Dialog, IconButton, Tooltip } from "@mui/material"; +import EditController from "./EditController"; +import { useState } from "react"; + +const Edit = ({ row, mutate }) => { + const [openEditDialog, setOpenEditDialog] = useState(false); + + return ( + <> + + { + setOpenEditDialog(true); + }} + > + + + + + setOpenEditDialog(false)} + sx={(theme) => ({ + position: "absolute", + right: 8, + top: 8, + zIndex: 50, + color: theme.palette.grey[500], + })} + > + + + {openEditDialog && ( + + )} + + + ); +}; +export default Edit; diff --git a/src/components/dashboard/roadMissions/operator/RowActions/index.jsx b/src/components/dashboard/roadMissions/operator/RowActions/index.jsx new file mode 100644 index 0000000..a4c3c39 --- /dev/null +++ b/src/components/dashboard/roadMissions/operator/RowActions/index.jsx @@ -0,0 +1,17 @@ +import { Box } from "@mui/material"; +import Edit from "./Edit"; +import Delete from "./Delete"; + +const RowActions = ({ row, mutate }) => { + return ( + + {row.original.state_id == 5 && ( + <> + + + + )} + + ); +}; +export default RowActions; diff --git a/src/components/dashboard/roadMissions/operator/Toolbar.jsx b/src/components/dashboard/roadMissions/operator/Toolbar.jsx new file mode 100644 index 0000000..5f49db7 --- /dev/null +++ b/src/components/dashboard/roadMissions/operator/Toolbar.jsx @@ -0,0 +1,11 @@ +import { Stack } from "@mui/material"; +import Create from "./Actions/Create"; + +const Toolbar = ({ table, filterData, mutate }) => { + return ( + + + + ); +}; +export default Toolbar; diff --git a/src/components/dashboard/roadMissions/operator/index.jsx b/src/components/dashboard/roadMissions/operator/index.jsx new file mode 100644 index 0000000..148167b --- /dev/null +++ b/src/components/dashboard/roadMissions/operator/index.jsx @@ -0,0 +1,14 @@ +"use client"; +import PageTitle from "@/core/components/PageTitle"; +import { Stack } from "@mui/material"; +import OperatorList from "./OperatorList"; + +const OperatorPage = () => { + return ( + + + + + ); +}; +export default OperatorPage; diff --git a/src/components/dashboard/roadMissions/transportation/Actions/showArea/index.jsx b/src/components/dashboard/roadMissions/transportation/Actions/showArea/index.jsx new file mode 100644 index 0000000..4232c07 --- /dev/null +++ b/src/components/dashboard/roadMissions/transportation/Actions/showArea/index.jsx @@ -0,0 +1,55 @@ +import MapLayer from "@/core/components/MapLayer"; +import { Close, RemoveRedEye } from "@mui/icons-material"; +import { Box, Dialog, DialogContent, DialogTitle, IconButton, Tooltip, Typography } from "@mui/material"; +import { useMemo, useState } from "react"; +import ShowBound from "../showBound"; +import L from "leaflet"; + +const ShowArea = ({ area }) => { + const bound = useMemo(() => L.polygon([...area]), [area]); + const [openAreaDialog, setOpenAreaDialog] = useState(false); + + return ( + <> + + setOpenAreaDialog(true)}> + + + + setOpenAreaDialog(false)} + PaperProps={{ + sx: { + transition: "all .3s", + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + borderRadius: 2, + padding: 1, + }, + }} + maxWidth="sm" + fullWidth + dir="rtl" + > + + + محدوده + + setOpenAreaDialog(false)} size="small"> + + + + + + + + + + + + + + + ); +}; +export default ShowArea; diff --git a/src/components/dashboard/roadMissions/transportation/Actions/showBound/index.jsx b/src/components/dashboard/roadMissions/transportation/Actions/showBound/index.jsx new file mode 100644 index 0000000..43dd0b8 --- /dev/null +++ b/src/components/dashboard/roadMissions/transportation/Actions/showBound/index.jsx @@ -0,0 +1,29 @@ +import { useEffect, useRef } from "react"; +import { FeatureGroup, useMap } from "react-leaflet"; + +const ShowBound = ({ bound }) => { + const map = useMap(); + const featureRef = useRef(null); + + const safeFitBounds = (layer) => { + if (!layer || !map) return; + try { + const latLngs = layer.getLatLngs(); + map.fitBounds(latLngs, { + paddingTopLeft: [20, 20], + paddingBottomRight: [20, 20], + }); + } catch (e) { + console.warn("fitBounds failed:", e); + } + }; + + useEffect(() => { + bound?.editing?.disable(); + featureRef.current.addLayer(bound); + safeFitBounds(bound); + }, []); + + return ; +}; +export default ShowBound; diff --git a/src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/MachinesDialog/MachineList/RowActions/Allocate/index.jsx b/src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/MachinesDialog/MachineList/RowActions/Allocate/index.jsx new file mode 100644 index 0000000..e26344e --- /dev/null +++ b/src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/MachinesDialog/MachineList/RowActions/Allocate/index.jsx @@ -0,0 +1,24 @@ +import { Done } from "@mui/icons-material"; +import { IconButton, Tooltip } from "@mui/material"; + +const Allocate = ({ row, request, dispatch, setOpenMachinesDialog }) => { + const handleClick = () => { + dispatch({ + type: "CHANGE_MACHINE", + id: request.id, + machine: row.original, + }); + setOpenMachinesDialog(false); + }; + + return ( + <> + + + + + + + ); +}; +export default Allocate; diff --git a/src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/MachinesDialog/MachineList/RowActions/index.jsx b/src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/MachinesDialog/MachineList/RowActions/index.jsx new file mode 100644 index 0000000..ee1b9d2 --- /dev/null +++ b/src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/MachinesDialog/MachineList/RowActions/index.jsx @@ -0,0 +1,6 @@ +import Allocate from "./Allocate"; + +const RowActions = ({ row, request, dispatch, setOpenMachinesDialog }) => { + return ; +}; +export default RowActions; diff --git a/src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/MachinesDialog/MachineList/index.jsx b/src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/MachinesDialog/MachineList/index.jsx new file mode 100644 index 0000000..3e48a20 --- /dev/null +++ b/src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/MachinesDialog/MachineList/index.jsx @@ -0,0 +1,61 @@ +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import { Box } from "@mui/material"; +import { useMemo } from "react"; +import RowActions from "./RowActions"; +import { GET_MACHINES_TABLE_LIST } from "@/core/utils/routes"; + +const MachinesList = ({ request, dispatch, setOpenMachinesDialog }) => { + const columns = useMemo( + () => [ + { + accessorKey: "machine_code", + header: "کد خودرو", + id: "machine_code", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "car_name", + header: "نام خودرو", + id: "car_name", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + ], + [] + ); + + return ( + <> + + ( + + )} + /> + + + ); +}; +export default MachinesList; diff --git a/src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/MachinesDialog/index.jsx b/src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/MachinesDialog/index.jsx new file mode 100644 index 0000000..5bdd6d8 --- /dev/null +++ b/src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/MachinesDialog/index.jsx @@ -0,0 +1,40 @@ +import { Close, Edit } from "@mui/icons-material"; +import { Button, Dialog, IconButton } from "@mui/material"; +import { useState } from "react"; +import MachinesList from "./MachineList"; + +const MachinesDialog = ({ request, dispatch, mode }) => { + const [openMachinesDialog, setOpenMachinesDialog] = useState(false); + return ( + <> + {mode == "edit" ? ( + setOpenMachinesDialog(true)} size="small"> + + + ) : ( + + )} + + setOpenMachinesDialog(false)} + sx={(theme) => ({ + position: "absolute", + right: 8, + top: 8, + zIndex: 50, + color: theme.palette.grey[500], + })} + > + + + {openMachinesDialog && ( + + )} + + + ); +}; +export default MachinesDialog; diff --git a/src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/Reject/Form/index.jsx b/src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/Reject/Form/index.jsx new file mode 100644 index 0000000..887867c --- /dev/null +++ b/src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/Reject/Form/index.jsx @@ -0,0 +1,84 @@ +import { DEALLOCATE_REQUEST_MISSION } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { Button, DialogActions, DialogContent, Stack, TextField } from "@mui/material"; +import { useForm } from "react-hook-form"; +import { object, string } from "yup"; + +const RejectForm = ({ rowId, mutate, setOpenAllocationDialog, setOpenRejectDialog }) => { + const requestServer = useRequest({ notificationSuccess: true }); + + const validationSchema = object().shape({ + description: string().required("لطفاً توضیحات را وارد کنید."), + }); + + const { + register, + handleSubmit, + formState: { errors, isSubmitting }, + reset, + } = useForm({ + defaultValues: { + description: "", + }, + resolver: yupResolver(validationSchema), + mode: "all", + }); + + const onSubmit = async (data) => { + const formData = new FormData(); + formData.append("description", data.description); + await requestServer(`${DEALLOCATE_REQUEST_MISSION}/${rowId}`, "post", { + data: formData, + hasSidebarUpdate: true, + }) + .then(() => { + mutate(); + setOpenRejectDialog(false); + setOpenAllocationDialog(false); + }) + .catch(() => {}) + .finally(() => { + reset(); + }); + }; + + return ( + <> + + + + + + + + + + + + + ); +}; +export default RejectForm; diff --git a/src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/Reject/index.jsx b/src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/Reject/index.jsx new file mode 100644 index 0000000..ee48c0a --- /dev/null +++ b/src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/Reject/index.jsx @@ -0,0 +1,40 @@ +import { Close } from "@mui/icons-material"; +import { Button, Dialog, DialogTitle, IconButton } from "@mui/material"; +import { useState } from "react"; +import RejectForm from "./Form"; + +const Reject = ({ isSubmitting, rowId, mutate, setOpenAllocationDialog }) => { + const [openRejectDialog, setOpenRejectDialog] = useState(false); + return ( + <> + + + setOpenRejectDialog(false)} + sx={(theme) => ({ + position: "absolute", + right: 8, + top: 8, + zIndex: 50, + color: theme.palette.grey[500], + })} + > + + + رد درخواست + {openRejectDialog && ( + + )} + + + ); +}; +export default Reject; diff --git a/src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/index.jsx b/src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/index.jsx new file mode 100644 index 0000000..929b43c --- /dev/null +++ b/src/components/dashboard/roadMissions/transportation/RowActions/Allocation/Form/index.jsx @@ -0,0 +1,121 @@ +import { machineType } from "@/core/utils/machineTypes"; +import { Alert, Box, Button, Chip, DialogActions, DialogContent, Divider, Typography } from "@mui/material"; +import { Stack } from "@mui/system"; +import { useReducer, useState } from "react"; +import MachinesDialog from "./MachinesDialog"; +import useRequest from "@/lib/hooks/useRequest"; +import { ALLOCATE_REQUEST_MISSION } from "@/core/utils/routes"; +import Reject from "./Reject"; + +const initValue = (requested_machines) => { + let arr = []; + let counter = 0; + for (let i = 0; i < requested_machines.length; i++) { + const request = requested_machines[i]; + for (let j = 0; j < request.count; j++) { + counter++; + arr.push({ id: counter, type: request.type, machine: null, position: j + 1 }); + } + } + return arr; +}; + +const reducer = (state, action) => { + switch (action.type) { + case "CHANGE_MACHINE": + return state.map((s) => (s.id == action.id ? { ...s, machine: action.machine } : s)); + default: + return state; + } +}; + +const AllocationForm = ({ rowId, mutate, setOpenAllocationDialog, requested_machines }) => { + const requestServer = useRequest({ notificationSuccess: true }); + const [requests, dispatch] = useReducer(reducer, requested_machines, initValue); + const [isSubmitting, setIsSubmitting] = useState(false); + + const handleSubmit = async (_requests) => { + setIsSubmitting(true); + await requestServer(`${ALLOCATE_REQUEST_MISSION}/${rowId}`, "post", { + data: { + machines: _requests.map((r) => r.machine.id), + }, + hasSidebarUpdate: true, + }) + .then((response) => { + mutate(); + setOpenAllocationDialog(false); + }) + .catch((error) => {}) + .finally(() => { + setIsSubmitting(false); + }); + }; + + return ( + <> + + + {requests.map((request) => ( + + + {machineType.find((mt) => mt.id == request.type).name_fa} {request.position} + + + {!request.machine && ( + + )} + + {request.machine ? ( + <> + + + + ) : ( + + )} + + ))} + {requests.some((r) => !r.machine) && ( + + برای تایید و تخصیص باید همه خودرو ها انتخاب شده باشند! + + )} + + + + + + + + + + + + + ); +}; +export default AllocationForm; diff --git a/src/components/dashboard/roadMissions/transportation/RowActions/Allocation/index.jsx b/src/components/dashboard/roadMissions/transportation/RowActions/Allocation/index.jsx new file mode 100644 index 0000000..58c9ae8 --- /dev/null +++ b/src/components/dashboard/roadMissions/transportation/RowActions/Allocation/index.jsx @@ -0,0 +1,49 @@ +import { Close, LocalShipping } from "@mui/icons-material"; +import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import AllocationForm from "./Form"; + +const Allocation = ({ row, mutate }) => { + const [openAllocationDialog, setOpenAllocationDialog] = useState(false); + + return ( + <> + + { + setOpenAllocationDialog(true); + }} + > + + + + + setOpenAllocationDialog(false)} + sx={(theme) => ({ + position: "absolute", + right: 8, + top: 8, + zIndex: 50, + color: theme.palette.grey[500], + })} + > + + + لیست خودرو های درخواستی + {openAllocationDialog && ( + + )} + + + ); +}; +export default Allocation; diff --git a/src/components/dashboard/roadMissions/transportation/RowActions/index.jsx b/src/components/dashboard/roadMissions/transportation/RowActions/index.jsx new file mode 100644 index 0000000..6d99797 --- /dev/null +++ b/src/components/dashboard/roadMissions/transportation/RowActions/index.jsx @@ -0,0 +1,10 @@ +import Allocation from "./Allocation"; + +const RowActions = ({ row, mutate }) => { + return ( + <> + + + ); +}; +export default RowActions; diff --git a/src/components/dashboard/roadMissions/transportation/TransportationList.jsx b/src/components/dashboard/roadMissions/transportation/TransportationList.jsx new file mode 100644 index 0000000..eb1f935 --- /dev/null +++ b/src/components/dashboard/roadMissions/transportation/TransportationList.jsx @@ -0,0 +1,125 @@ +"use client"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import { GET_ROAD_MISSIONS_TRANSPORTATION_LIST } from "@/core/utils/routes"; +import { Box, Stack } from "@mui/material"; +import moment from "jalali-moment"; +import { useMemo } from "react"; +import ShowArea from "./Actions/showArea"; +import RowActions from "./RowActions"; + +const TransportationList = () => { + const typeOptions = [ + { value: 1, label: "روزانه" }, + { value: 2, label: "ساعتی" }, + ]; + + const columns = useMemo( + () => [ + { + accessorKey: "id", + header: "کد یکتا", + id: "id", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "type", + header: "نوع", + id: "type", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + sortDescFirst: true, + grow: false, + size: 100, + columnSelectOption: () => { + return typeOptions.map((type) => ({ + value: type.value, + label: type.label, + })); + }, + Cell: ({ row }) => row.original.type_fa, + }, + { + accessorFn: (row) => moment(row.start_date).locale("fa").format("HH:mm | yyyy/MM/DD"), + header: "تاریخ شروع", + id: "start_date", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + { + accessorFn: (row) => moment(row.end_date).locale("fa").format("HH:mm | yyyy/MM/DD"), + header: "تاریخ پایان", + id: "end_date", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + { + accessorKey: "end_point", + header: "مقصد", + id: "end_point", + enableColumnFilter: false, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 100, + }, + { + header: "محدوده", + id: "area", + enableColumnFilter: false, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => + row.original.area ? ( + + + + ) : ( + "-" + ), + }, + ], + [] + ); + + return ( + <> + + + + + ); +}; +export default TransportationList; diff --git a/src/components/dashboard/roadMissions/transportation/index.jsx b/src/components/dashboard/roadMissions/transportation/index.jsx new file mode 100644 index 0000000..ca0db36 --- /dev/null +++ b/src/components/dashboard/roadMissions/transportation/index.jsx @@ -0,0 +1,14 @@ +"use client"; +import PageTitle from "@/core/components/PageTitle"; +import { Stack } from "@mui/material"; +import TransportationList from "./TransportationList"; + +const TransportationPage = () => { + return ( + + + + + ); +}; +export default TransportationPage; diff --git a/src/components/dashboard/roadPatrols/operator/Actions/Create/index.jsx b/src/components/dashboard/roadPatrols/operator/Actions/Create/index.jsx index 97ce660..aad2f77 100644 --- a/src/components/dashboard/roadPatrols/operator/Actions/Create/index.jsx +++ b/src/components/dashboard/roadPatrols/operator/Actions/Create/index.jsx @@ -1,33 +1,33 @@ -"use client"; - -import { Button, IconButton, useMediaQuery } from "@mui/material"; -import { useTheme } from "@emotion/react"; -import { useState } from "react"; -import { AddCircle } from "@mui/icons-material"; -import CreatePatrol from "../../Forms/CreatePatrol"; - -const OperatorCreate = ({ mutate }) => { - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const [open, setOpen] = useState(false); - - const handleOpen = () => { - setOpen(true); - }; - - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - - - ); -}; -export default OperatorCreate; +"use client"; + +import { Button, IconButton, useMediaQuery } from "@mui/material"; +import { useTheme } from "@emotion/react"; +import { useState } from "react"; +import { AddCircle } from "@mui/icons-material"; +import CreatePatrol from "../../Forms/CreatePatrol"; + +const OperatorCreate = ({ mutate }) => { + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const [open, setOpen] = useState(false); + + const handleOpen = () => { + setOpen(true); + }; + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + + + ); +}; +export default OperatorCreate; diff --git a/src/components/dashboard/roadPatrols/operator/ExcelPrint/index.jsx b/src/components/dashboard/roadPatrols/operator/ExcelPrint/index.jsx index a5fb3b4..5d9fb0d 100644 --- a/src/components/dashboard/roadPatrols/operator/ExcelPrint/index.jsx +++ b/src/components/dashboard/roadPatrols/operator/ExcelPrint/index.jsx @@ -1,75 +1,75 @@ -import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; -import { useMemo, useState } from "react"; -import moment from "jalali-moment"; -import FileSaver from "file-saver"; -import DescriptionIcon from "@mui/icons-material/Description"; -import useRequest from "@/lib/hooks/useRequest"; -import { EXPORT_ROAD_PATROL_OPERATOR_LIST } from "@/core/utils/routes"; -import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; -import isArrayEmpty from "@/core/utils/isArrayEmpty"; -import { useTheme } from "@emotion/react"; - -const PrintExcel = ({ table, filterData }) => { - const [loading, setLoading] = useState(false); - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const requestServer = useRequest(); - const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { - if (filter.value && (!Array.isArray(filter.value) || filter.value.some((item) => item.trim() !== ""))) { - acc.push({ id: key, value: filter.value }); - } - return acc; - }, []); - - const filterParams = useMemo(() => { - const params = new URLSearchParams(); - if (activeFilters.length > 0) { - activeFilters.map((filter, index) => { - const filteredFilterData = DataTableFilterDataStructure(filterData, isArrayEmpty); - params.set("filters", JSON.stringify(filteredFilterData.length === 0 ? [] : filteredFilterData)); - }); - } else { - params.set("filters", JSON.stringify([])); - } - return params; - }, [activeFilters]); - - const clickHandler = () => { - setLoading(true); - requestServer(`${EXPORT_ROAD_PATROL_OPERATOR_LIST}?${filterParams}`, "get", { - requestOptions: { responseType: "blob" }, - }) - .then((response) => { - const filename = `خروجی کارتابل عملیات گشت راهداری تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; - FileSaver.saveAs(response.data, filename); - }) - .catch(() => {}) - .finally(() => { - setLoading(false); - }); - }; - - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - - ); -}; - -export default PrintExcel; +import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; +import { useMemo, useState } from "react"; +import moment from "jalali-moment"; +import FileSaver from "file-saver"; +import DescriptionIcon from "@mui/icons-material/Description"; +import useRequest from "@/lib/hooks/useRequest"; +import { EXPORT_ROAD_PATROL_OPERATOR_LIST } from "@/core/utils/routes"; +import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; +import isArrayEmpty from "@/core/utils/isArrayEmpty"; +import { useTheme } from "@emotion/react"; + +const PrintExcel = ({ table, filterData }) => { + const [loading, setLoading] = useState(false); + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const requestServer = useRequest(); + const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { + if (filter.value && (!Array.isArray(filter.value) || filter.value.some((item) => item.trim() !== ""))) { + acc.push({ id: key, value: filter.value }); + } + return acc; + }, []); + + const filterParams = useMemo(() => { + const params = new URLSearchParams(); + if (activeFilters.length > 0) { + activeFilters.map((filter, index) => { + const filteredFilterData = DataTableFilterDataStructure(filterData, isArrayEmpty); + params.set("filters", JSON.stringify(filteredFilterData.length === 0 ? [] : filteredFilterData)); + }); + } else { + params.set("filters", JSON.stringify([])); + } + return params; + }, [activeFilters]); + + const clickHandler = () => { + setLoading(true); + requestServer(`${EXPORT_ROAD_PATROL_OPERATOR_LIST}?${filterParams}`, "get", { + requestOptions: { responseType: "blob" }, + }) + .then((response) => { + const filename = `خروجی کارتابل عملیات گشت راهداری تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; + FileSaver.saveAs(response.data, filename); + }) + .catch(() => {}) + .finally(() => { + setLoading(false); + }); + }; + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + + ); +}; + +export default PrintExcel; diff --git a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/ActionInfo.jsx b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/ActionInfo.jsx index 8ad27a7..c377e40 100644 --- a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/ActionInfo.jsx +++ b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/ActionInfo.jsx @@ -1,39 +1,39 @@ -"use client"; - -import DeleteIcon from "@mui/icons-material/Delete"; -import HandymanIcon from "@mui/icons-material/Handyman"; -import { Box, Card, CardActions, CardHeader, Chip, IconButton, Typography } from "@mui/material"; -import EditActionDuringPatrol from "./EditActionDuringPatrol"; - -const ActionInfo = ({ action, setActionsList, index, deleteAction }) => { - return ( - - } - title={ - - {action.data.item_name} - - } - subheader={action.data.sub_item_name} - /> - - - - - - - - - - ); -}; - -export default ActionInfo; +"use client"; + +import DeleteIcon from "@mui/icons-material/Delete"; +import HandymanIcon from "@mui/icons-material/Handyman"; +import { Box, Card, CardActions, CardHeader, Chip, IconButton, Typography } from "@mui/material"; +import EditActionDuringPatrol from "./EditActionDuringPatrol"; + +const ActionInfo = ({ action, setActionsList, index, deleteAction }) => { + return ( + + } + title={ + + {action.data.item_name} + + } + subheader={action.data.sub_item_name} + /> + + + + + + + + + + ); +}; + +export default ActionInfo; diff --git a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/ActionsDurigPatrol.jsx b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/ActionsDurigPatrol.jsx index 8028103..7a664c0 100644 --- a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/ActionsDurigPatrol.jsx +++ b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/ActionsDurigPatrol.jsx @@ -1,124 +1,124 @@ -"use client"; - -import AddCircleIcon from "@mui/icons-material/AddCircle"; -import ExitToAppIcon from "@mui/icons-material/ExitToApp"; -import { Box, Button, Chip, DialogActions, DialogContent, Divider, Grid, Stack, Typography } from "@mui/material"; -import { useState } from "react"; -import ActionInfo from "./ActionInfo"; -import ModalActionsDuringPatrol from "./ModalActionsDuringPatrol"; -import ModalObservedItemPatrol from "./ModalObservedItemPatrol"; -import ObservedInfo from "./ObservedInfo"; - -const ActionsDuringPatrol = ({ allData, setAllData, handlePrev, setTabState }) => { - const [actionsList, setActionsList] = useState(allData.observed_items); - const [openAction, setOpenAction] = useState(false); - const [openObserved, setOpenObseved] = useState(false); - const handleOpenAction = () => { - setOpenAction(true); - }; - - const handleOpenObserved = () => { - setOpenObseved(true); - }; - - const deleteAction = (indexToRemove) => { - setActionsList((prev) => prev.filter((_, index) => index !== indexToRemove)); - }; - - const handleNext = (data) => { - setAllData({ observed_items: data }); - setTabState((s) => s + 1); - }; - - return ( - <> - - - - - - - - - - - - {actionsList.length !== 0 ? ( - - {actionsList.map((action, index) => ( - - {action.instant_action == 1 ? ( - deleteAction(index)} - /> - ) : ( - deleteAction(index)} - /> - )} - - ))} - - ) : ( - - - فعالیتی ثبت نکرده اید - - - )} - - - - - - - - ); -}; - -export default ActionsDuringPatrol; +"use client"; + +import AddCircleIcon from "@mui/icons-material/AddCircle"; +import ExitToAppIcon from "@mui/icons-material/ExitToApp"; +import { Box, Button, Chip, DialogActions, DialogContent, Divider, Grid, Stack, Typography } from "@mui/material"; +import { useState } from "react"; +import ActionInfo from "./ActionInfo"; +import ModalActionsDuringPatrol from "./ModalActionsDuringPatrol"; +import ModalObservedItemPatrol from "./ModalObservedItemPatrol"; +import ObservedInfo from "./ObservedInfo"; + +const ActionsDuringPatrol = ({ allData, setAllData, handlePrev, setTabState }) => { + const [actionsList, setActionsList] = useState(allData.observed_items); + const [openAction, setOpenAction] = useState(false); + const [openObserved, setOpenObseved] = useState(false); + const handleOpenAction = () => { + setOpenAction(true); + }; + + const handleOpenObserved = () => { + setOpenObseved(true); + }; + + const deleteAction = (indexToRemove) => { + setActionsList((prev) => prev.filter((_, index) => index !== indexToRemove)); + }; + + const handleNext = (data) => { + setAllData({ observed_items: data }); + setTabState((s) => s + 1); + }; + + return ( + <> + + + + + + + + + + + + {actionsList.length !== 0 ? ( + + {actionsList.map((action, index) => ( + + {action.instant_action == 1 ? ( + deleteAction(index)} + /> + ) : ( + deleteAction(index)} + /> + )} + + ))} + + ) : ( + + + فعالیتی ثبت نکرده اید + + + )} + + + + + + + + ); +}; + +export default ActionsDuringPatrol; diff --git a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/CompeleteRequest.jsx b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/CompeleteRequest.jsx index 5402d42..f3b40f6 100644 --- a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/CompeleteRequest.jsx +++ b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/CompeleteRequest.jsx @@ -1,369 +1,369 @@ -"use client"; - -import ShowPlak from "@/core/components/ShowPlak"; -import StyledForm from "@/core/components/StyledForm"; -import { formatCounter } from "@/core/utils/formatCounter"; -import { formatSecondsToHHMMSS } from "@/core/utils/formatSecondsToHHMMSS"; -import { CREATE_PATROL, GET_OTP_TOKEN } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { yupResolver } from "@hookform/resolvers/yup"; -import ExitToAppIcon from "@mui/icons-material/ExitToApp"; -import ForwardToInboxIcon from "@mui/icons-material/ForwardToInbox"; -import { - Box, - Button, - Chip, - DialogActions, - DialogContent, - Divider, - FormControl, - Grid, - InputLabel, - OutlinedInput, - Slide, - Stack, - Typography, -} from "@mui/material"; -import moment from "jalali-moment"; -import { useCallback, useEffect, useState } from "react"; -import { useForm } from "react-hook-form"; -import * as yup from "yup"; - -const schemaOtp = yup.object().shape({ - phoneNumber: yup - .string() - .matches(/^09\d{9}$/, "شماره تماس باید با 09 شروع شود و 11 رقم باشد.") - .required("شماره تماس الزامی است."), -}); - -const schemaSend = yup.object().shape({ - phoneNumber: yup - .string() - .matches(/^09\d{9}$/, "شماره تماس باید با 09 شروع شود و 11 رقم باشد.") - .required("شماره تماس الزامی است."), - code: yup.string().length(6).required("شماره تماس الزامی است."), -}); - -const CompeleteRequest = ({ allData, handlePrev, mutate, setOpen }) => { - const requestServer = useRequest(); - const [delayPerRequest, setDelayPerRequest] = useState(false); - const [counter, setCounter] = useState(120); - const [otpSended, setOtpSended] = useState(false); - - const defaultValuesOtp = { - phoneNumber: "", - }; - - const defaultValuesSend = { - phoneNumber: "", - code: "", - }; - - const { - handleSubmit: handleSubmitOtp, - register: registerOtp, - formState: { isSubmitting: isSubmittingOtp, isValid: isValidOtp }, - } = useForm({ defaultValues: defaultValuesOtp, resolver: yupResolver(schemaOtp), mode: "all" }); - - const { - handleSubmit: handleSubmitSend, - setValue: setValueSend, - register: registerSend, - formState: { isSubmitting: isSubmittingSend, isValid: isValidSend }, - } = useForm({ defaultValues: defaultValuesSend, resolver: yupResolver(schemaSend), mode: "all" }); - - useEffect(() => { - if (counter === 0) { - setDelayPerRequest(false); - return; - } - if (delayPerRequest && counter > 0) { - const timer = setInterval(() => { - setCounter((prevCounter) => prevCounter - 1); - }, 1000); - - return () => clearInterval(timer); - } - }, [counter, delayPerRequest]); - - const sendOtp = async (data) => { - try { - await requestServer(GET_OTP_TOKEN, "post", { - data: { - phone_number: data.phoneNumber, - }, - }); - setOtpSended(true); - setDelayPerRequest(true); - setValueSend("phoneNumber", data.phoneNumber); - } catch (error) {} - }; - - const sendData = useCallback( - async (data) => { - const formData = new FormData(); - allData.road_patrol_rahdaran_id.forEach((rahdar, index) => - formData.append(`road_patrol_rahdaran_id[${index}]`, rahdar.id) - ); - formData.append(`road_patrol_machines_id[0]`, allData.roadPatrolMachinesId.id); - allData.stopPoints.forEach((stop_point, index) => { - formData.append(`stop_points[${index}][duration]`, stop_point.duration); - formData.append(`stop_points[${index}][latitude]`, stop_point.latitude); - formData.append(`stop_points[${index}][longitude]`, stop_point.longitude); - formData.append(`stop_points[${index}][startDT]`, stop_point.startDT); - }); - allData.observed_items.forEach((observed_item, index) => { - if (observed_item.instant_action == 1) { - formData.append(`observed_items[${index}][instant_action]`, observed_item.instant_action); - formData.append(`observed_items[${index}][local_name]`, ""); - formData.append(`observed_items[${index}][start_point]`, observed_item.result.start_point); - if (observed_item.result.end_point) - formData.append(`observed_items[${index}][end_point]`, observed_item.result.end_point); - formData.append(`observed_items[${index}][amount]`, observed_item.result.amount); - formData.append(`observed_items[${index}][before_image]`, observed_item.result.before_image); - formData.append(`observed_items[${index}][after_image]`, observed_item.result.after_image); - formData.append(`observed_items[${index}][item_id]`, observed_item.result.item_id); - formData.append(`observed_items[${index}][sub_item_id]`, observed_item.result.sub_item_id); - formData.append( - `observed_items[${index}][road_item_machines_id][]`, - allData.roadPatrolMachinesId.id - ); - allData.road_patrol_rahdaran_id.forEach((rahdar, i) => - formData.append(`observed_items[${index}][road_item_rahdaran_id][]`, rahdar.id) - ); - } else { - formData.append(`observed_items[${index}][instant_action]`, observed_item.instant_action); - formData.append(`observed_items[${index}][local_name]`, observed_item.result.local_name); - formData.append(`observed_items[${index}][priority]`, observed_item.result.priority); - formData.append(`observed_items[${index}][start_point]`, observed_item.result.start_point); - if (observed_item.result.end_point) - formData.append(`observed_items[${index}][end_point]`, observed_item.result.end_point); - formData.append(`observed_items[${index}][item_id]`, observed_item.result.item_id); - formData.append(`observed_items[${index}][sub_item_id]`, observed_item.result.sub_item_id); - } - }); - formData.append("start_time", allData.start_time); - formData.append("end_time", allData.end_time); - formData.append("vehicle_runtime", allData.accOnDuration); - formData.append("fuel_consumption", +allData.fuelConsumption); - formData.append("distance", allData.mileage); - // formData.append("description", ""); - formData.append("phone_number", data.phoneNumber); - formData.append("verification_code", data.code); - try { - await requestServer(CREATE_PATROL, "post", { - data: formData, - }); - mutate(); - setOpen(false); - } catch (error) { - console.log(error); - } - }, - [allData] - ); - - return ( - <> - - - - - - - - - - - - {allData.start_time !== "" && - moment(allData.start_time).locale("fa").format("HH:mm | YYYY/MM/DD")} - - - - - - - {allData.start_time !== "" && - moment(allData.start_time).locale("fa").format("HH:mm | YYYY/MM/DD")} - - - - - - - - {allData.accOnDuration && formatSecondsToHHMMSS(allData.accOnDuration)} - - - - - - - {allData.fuelConsumption && Math.round(allData.fuelConsumption * 10) / 10} لیتر - - - - - - {allData.stopPoints && allData.stopPoints.length} نقطه - - - - - - {allData.mileage && (allData.mileage / 1000).toFixed(1)} کیلومتر - - - - - - {allData.observed_items && allData.observed_items.length} مورد - - - - - - - - - - - - {allData.roadPatrolMachinesId && allData.roadPatrolMachinesId.machine_code} - - - - - - - {allData.roadPatrolMachinesId && allData.roadPatrolMachinesId.car_name} - - - - - - - {allData.roadPatrolMachinesId.plak_number && - ShowPlak({ plak_number: allData.roadPatrolMachinesId.plak_number })} - - - - - - - - {allData.road_patrol_rahdaran_id.map((rahdar, index) => ( - - - - - - {rahdar.name} | {rahdar.code} - - - - ))} - - - - - - - - - - شماره تلفن مامور گشت - - - - - - - - - - کد تایید پیامک شده - - - - - - - - - - - - - - - ); -}; - -export default CompeleteRequest; +"use client"; + +import ShowPlak from "@/core/components/ShowPlak"; +import StyledForm from "@/core/components/StyledForm"; +import { formatCounter } from "@/core/utils/formatCounter"; +import { formatSecondsToHHMMSS } from "@/core/utils/formatSecondsToHHMMSS"; +import { CREATE_PATROL, GET_OTP_TOKEN } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { yupResolver } from "@hookform/resolvers/yup"; +import ExitToAppIcon from "@mui/icons-material/ExitToApp"; +import ForwardToInboxIcon from "@mui/icons-material/ForwardToInbox"; +import { + Box, + Button, + Chip, + DialogActions, + DialogContent, + Divider, + FormControl, + Grid, + InputLabel, + OutlinedInput, + Slide, + Stack, + Typography, +} from "@mui/material"; +import moment from "jalali-moment"; +import { useCallback, useEffect, useState } from "react"; +import { useForm } from "react-hook-form"; +import * as yup from "yup"; + +const schemaOtp = yup.object().shape({ + phoneNumber: yup + .string() + .matches(/^09\d{9}$/, "شماره تماس باید با 09 شروع شود و 11 رقم باشد.") + .required("شماره تماس الزامی است."), +}); + +const schemaSend = yup.object().shape({ + phoneNumber: yup + .string() + .matches(/^09\d{9}$/, "شماره تماس باید با 09 شروع شود و 11 رقم باشد.") + .required("شماره تماس الزامی است."), + code: yup.string().length(6).required("شماره تماس الزامی است."), +}); + +const CompeleteRequest = ({ allData, handlePrev, mutate, setOpen }) => { + const requestServer = useRequest(); + const [delayPerRequest, setDelayPerRequest] = useState(false); + const [counter, setCounter] = useState(120); + const [otpSended, setOtpSended] = useState(false); + + const defaultValuesOtp = { + phoneNumber: "", + }; + + const defaultValuesSend = { + phoneNumber: "", + code: "", + }; + + const { + handleSubmit: handleSubmitOtp, + register: registerOtp, + formState: { isSubmitting: isSubmittingOtp, isValid: isValidOtp }, + } = useForm({ defaultValues: defaultValuesOtp, resolver: yupResolver(schemaOtp), mode: "all" }); + + const { + handleSubmit: handleSubmitSend, + setValue: setValueSend, + register: registerSend, + formState: { isSubmitting: isSubmittingSend, isValid: isValidSend }, + } = useForm({ defaultValues: defaultValuesSend, resolver: yupResolver(schemaSend), mode: "all" }); + + useEffect(() => { + if (counter === 0) { + setDelayPerRequest(false); + return; + } + if (delayPerRequest && counter > 0) { + const timer = setInterval(() => { + setCounter((prevCounter) => prevCounter - 1); + }, 1000); + + return () => clearInterval(timer); + } + }, [counter, delayPerRequest]); + + const sendOtp = async (data) => { + try { + await requestServer(GET_OTP_TOKEN, "post", { + data: { + phone_number: data.phoneNumber, + }, + }); + setOtpSended(true); + setDelayPerRequest(true); + setValueSend("phoneNumber", data.phoneNumber); + } catch (error) {} + }; + + const sendData = useCallback( + async (data) => { + const formData = new FormData(); + allData.road_patrol_rahdaran_id.forEach((rahdar, index) => + formData.append(`road_patrol_rahdaran_id[${index}]`, rahdar.id) + ); + formData.append(`road_patrol_machines_id[0]`, allData.roadPatrolMachinesId.id); + allData.stopPoints.forEach((stop_point, index) => { + formData.append(`stop_points[${index}][duration]`, stop_point.duration); + formData.append(`stop_points[${index}][latitude]`, stop_point.latitude); + formData.append(`stop_points[${index}][longitude]`, stop_point.longitude); + formData.append(`stop_points[${index}][startDT]`, stop_point.startDT); + }); + allData.observed_items.forEach((observed_item, index) => { + if (observed_item.instant_action == 1) { + formData.append(`observed_items[${index}][instant_action]`, observed_item.instant_action); + formData.append(`observed_items[${index}][local_name]`, ""); + formData.append(`observed_items[${index}][start_point]`, observed_item.result.start_point); + if (observed_item.result.end_point) + formData.append(`observed_items[${index}][end_point]`, observed_item.result.end_point); + formData.append(`observed_items[${index}][amount]`, observed_item.result.amount); + formData.append(`observed_items[${index}][before_image]`, observed_item.result.before_image); + formData.append(`observed_items[${index}][after_image]`, observed_item.result.after_image); + formData.append(`observed_items[${index}][item_id]`, observed_item.result.item_id); + formData.append(`observed_items[${index}][sub_item_id]`, observed_item.result.sub_item_id); + formData.append( + `observed_items[${index}][road_item_machines_id][]`, + allData.roadPatrolMachinesId.id + ); + allData.road_patrol_rahdaran_id.forEach((rahdar, i) => + formData.append(`observed_items[${index}][road_item_rahdaran_id][]`, rahdar.id) + ); + } else { + formData.append(`observed_items[${index}][instant_action]`, observed_item.instant_action); + formData.append(`observed_items[${index}][local_name]`, observed_item.result.local_name); + formData.append(`observed_items[${index}][priority]`, observed_item.result.priority); + formData.append(`observed_items[${index}][start_point]`, observed_item.result.start_point); + if (observed_item.result.end_point) + formData.append(`observed_items[${index}][end_point]`, observed_item.result.end_point); + formData.append(`observed_items[${index}][item_id]`, observed_item.result.item_id); + formData.append(`observed_items[${index}][sub_item_id]`, observed_item.result.sub_item_id); + } + }); + formData.append("start_time", allData.start_time); + formData.append("end_time", allData.end_time); + formData.append("vehicle_runtime", allData.accOnDuration); + formData.append("fuel_consumption", +allData.fuelConsumption); + formData.append("distance", allData.mileage); + // formData.append("description", ""); + formData.append("phone_number", data.phoneNumber); + formData.append("verification_code", data.code); + try { + await requestServer(CREATE_PATROL, "post", { + data: formData, + }); + mutate(); + setOpen(false); + } catch (error) { + console.log(error); + } + }, + [allData] + ); + + return ( + <> + + + + + + + + + + + + {allData.start_time !== "" && + moment(allData.start_time).locale("fa").format("HH:mm | YYYY/MM/DD")} + + + + + + + {allData.start_time !== "" && + moment(allData.start_time).locale("fa").format("HH:mm | YYYY/MM/DD")} + + + + + + + + {allData.accOnDuration && formatSecondsToHHMMSS(allData.accOnDuration)} + + + + + + + {allData.fuelConsumption && Math.round(allData.fuelConsumption * 10) / 10} لیتر + + + + + + {allData.stopPoints && allData.stopPoints.length} نقطه + + + + + + {allData.mileage && (allData.mileage / 1000).toFixed(1)} کیلومتر + + + + + + {allData.observed_items && allData.observed_items.length} مورد + + + + + + + + + + + + {allData.roadPatrolMachinesId && allData.roadPatrolMachinesId.machine_code} + + + + + + + {allData.roadPatrolMachinesId && allData.roadPatrolMachinesId.car_name} + + + + + + + {allData.roadPatrolMachinesId.plak_number && + ShowPlak({ plak_number: allData.roadPatrolMachinesId.plak_number })} + + + + + + + + {allData.road_patrol_rahdaran_id.map((rahdar, index) => ( + + + + + + {rahdar.name} | {rahdar.code} + + + + ))} + + + + + + + + + + شماره تلفن مامور گشت + + + + + + + + + + کد تایید پیامک شده + + + + + + + + + + + + + + + ); +}; + +export default CompeleteRequest; diff --git a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/CreateFormContentObservedItem.jsx b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/CreateFormContentObservedItem.jsx index 216cdfe..559f0c0 100644 --- a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/CreateFormContentObservedItem.jsx +++ b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/CreateFormContentObservedItem.jsx @@ -1,203 +1,203 @@ -import GetItemsForm from "@/components/dashboard/roadItems/operator/Actions/Create/Forms/GetItemsForm"; -import GetSubItemsForm from "@/components/dashboard/roadItems/operator/Actions/Create/Forms/GetSubItemsForm"; -import StyledForm from "@/core/components/StyledForm"; -import { useTheme } from "@emotion/react"; -import { yupResolver } from "@hookform/resolvers/yup"; -import BeenhereIcon from "@mui/icons-material/Beenhere"; -import ExitToAppIcon from "@mui/icons-material/ExitToApp"; -import FileCopyIcon from "@mui/icons-material/FileCopy"; -import InfoIcon from "@mui/icons-material/Info"; -import InsertDriveFileIcon from "@mui/icons-material/InsertDriveFile"; -import KeyboardDoubleArrowRightIcon from "@mui/icons-material/KeyboardDoubleArrowRight"; -import { Box, Button, DialogActions, DialogContent, Tab, Tabs, useMediaQuery } from "@mui/material"; -import { useState } from "react"; -import { useForm } from "react-hook-form"; -import { mixed, number, object, string } from "yup"; -import GetObservedItemInfo from "./GetObservedItemInfo"; - -function TabPanel(props) { - const { children, value, index } = props; - return ( - - ); -} - -const validationSchema = object({ - item_id: number().required("نوع آیتم را مشخص کنید!"), - sub_item_id: number().required("اقدام انجام شده را مشخص کنید!"), - local_name: string().required("نام محلی را مشخص کنید!"), - priority: string().required("اولویت را مشخص کنید!"), - start_point: mixed() - .test("start-point-required", "لطفاً نقطه شروع را مشخص کنید!", function (value) { - return !!value; // چک می‌کند که مقدار موجود است - }) - .required("لطفاً نقطه شروع را مشخص کنید!"), - end_point: mixed().test("end-point-required", "لطفاً نقطه پایان را مشخص کنید!", function (value) { - const { subItemsList } = this.options.context; - const needsEndPoint = subItemsList?.needs_end_point === 1; - if (needsEndPoint) { - return !!value; // چک می‌کند که مقدار موجود است - } - return true; - }), -}); - -const CreateFormContentObservedItem = ({ setOpen, onSubmit }) => { - const defaultValues = { - item_id: null, - sub_item_id: null, - local_name: "", - priority: "1", - start_point: "", - end_point: "", - }; - - const [tabState, setTabState] = useState(0); - const [itemsList, setItemsList] = useState(); - const [subItemsList, setSubItemsList] = useState([]); - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - - const handleClose = () => { - setOpen(false); - }; - - const handleChangeTab = (event, newValue) => { - setTabState(newValue); - }; - - const handlePrev = () => { - if (tabState === 2) { - const fieldsToReset = ["local_name", "priority", "start_point", "end_point"]; - fieldsToReset.forEach((field) => resetField(field)); - } - if (tabState === 0) { - handleClose(); - } else { - setTabState(tabState - 1); - } - }; - const { - control, - watch, - getValues, - register, - handleSubmit, - setValue, - resetField, - formState: { errors, isSubmitting }, - } = useForm({ - defaultValues, - resolver: yupResolver(validationSchema), - mode: "all", - context: { subItemsList }, - }); - const onSubmitBase = async (data) => { - let result = { ...data }; - - if (result.end_point === "") { - delete result.end_point; - delete data.end_point; - } else { - result.end_point = `${result.end_point.lat},${result.end_point.lng}`; - } - - if (result.start_point === "") { - delete result.start_point; - delete data.start_point; - } else { - result.start_point = `${result.start_point.lat},${result.start_point.lng}`; - } - - await onSubmit({ - result, - data: { - ...data, - item_name: itemsList.name, - sub_item_name: subItemsList.name, - unit_fa: subItemsList.unit, - }, - }); - }; - - return ( - - - } label="انتخاب آیتم" /> - } label="انتخاب اقدام مشاهده شده" /> - } label="اطلاعات فعالیت" /> - - - - - - - - - - - - - - - - - {tabState === 2 && ( - - )} - - - ); -}; -export default CreateFormContentObservedItem; +import GetItemsForm from "@/components/dashboard/roadItems/operator/Actions/Create/Forms/GetItemsForm"; +import GetSubItemsForm from "@/components/dashboard/roadItems/operator/Actions/Create/Forms/GetSubItemsForm"; +import StyledForm from "@/core/components/StyledForm"; +import { useTheme } from "@emotion/react"; +import { yupResolver } from "@hookform/resolvers/yup"; +import BeenhereIcon from "@mui/icons-material/Beenhere"; +import ExitToAppIcon from "@mui/icons-material/ExitToApp"; +import FileCopyIcon from "@mui/icons-material/FileCopy"; +import InfoIcon from "@mui/icons-material/Info"; +import InsertDriveFileIcon from "@mui/icons-material/InsertDriveFile"; +import KeyboardDoubleArrowRightIcon from "@mui/icons-material/KeyboardDoubleArrowRight"; +import { Box, Button, DialogActions, DialogContent, Tab, Tabs, useMediaQuery } from "@mui/material"; +import { useState } from "react"; +import { useForm } from "react-hook-form"; +import { mixed, number, object, string } from "yup"; +import GetObservedItemInfo from "./GetObservedItemInfo"; + +function TabPanel(props) { + const { children, value, index } = props; + return ( + + ); +} + +const validationSchema = object({ + item_id: number().required("نوع آیتم را مشخص کنید!"), + sub_item_id: number().required("اقدام انجام شده را مشخص کنید!"), + local_name: string().required("نام محلی را مشخص کنید!"), + priority: string().required("اولویت را مشخص کنید!"), + start_point: mixed() + .test("start-point-required", "لطفاً نقطه شروع را مشخص کنید!", function (value) { + return !!value; // چک می‌کند که مقدار موجود است + }) + .required("لطفاً نقطه شروع را مشخص کنید!"), + end_point: mixed().test("end-point-required", "لطفاً نقطه پایان را مشخص کنید!", function (value) { + const { subItemsList } = this.options.context; + const needsEndPoint = subItemsList?.needs_end_point === 1; + if (needsEndPoint) { + return !!value; // چک می‌کند که مقدار موجود است + } + return true; + }), +}); + +const CreateFormContentObservedItem = ({ setOpen, onSubmit }) => { + const defaultValues = { + item_id: null, + sub_item_id: null, + local_name: "", + priority: "1", + start_point: "", + end_point: "", + }; + + const [tabState, setTabState] = useState(0); + const [itemsList, setItemsList] = useState(); + const [subItemsList, setSubItemsList] = useState([]); + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + + const handleClose = () => { + setOpen(false); + }; + + const handleChangeTab = (event, newValue) => { + setTabState(newValue); + }; + + const handlePrev = () => { + if (tabState === 2) { + const fieldsToReset = ["local_name", "priority", "start_point", "end_point"]; + fieldsToReset.forEach((field) => resetField(field)); + } + if (tabState === 0) { + handleClose(); + } else { + setTabState(tabState - 1); + } + }; + const { + control, + watch, + getValues, + register, + handleSubmit, + setValue, + resetField, + formState: { errors, isSubmitting }, + } = useForm({ + defaultValues, + resolver: yupResolver(validationSchema), + mode: "all", + context: { subItemsList }, + }); + const onSubmitBase = async (data) => { + let result = { ...data }; + + if (result.end_point === "") { + delete result.end_point; + delete data.end_point; + } else { + result.end_point = `${result.end_point.lat},${result.end_point.lng}`; + } + + if (result.start_point === "") { + delete result.start_point; + delete data.start_point; + } else { + result.start_point = `${result.start_point.lat},${result.start_point.lng}`; + } + + await onSubmit({ + result, + data: { + ...data, + item_name: itemsList.name, + sub_item_name: subItemsList.name, + unit_fa: subItemsList.unit, + }, + }); + }; + + return ( + + + } label="انتخاب آیتم" /> + } label="انتخاب اقدام مشاهده شده" /> + } label="اطلاعات فعالیت" /> + + + + + + + + + + + + + + + + + {tabState === 2 && ( + + )} + + + ); +}; +export default CreateFormContentObservedItem; diff --git a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/DatePickerForEndTime.jsx b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/DatePickerForEndTime.jsx index 10e1526..141baeb 100644 --- a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/DatePickerForEndTime.jsx +++ b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/DatePickerForEndTime.jsx @@ -1,54 +1,54 @@ -import { IconButton, InputAdornment } from "@mui/material"; -import { ClearIcon, MobileDateTimePicker } from "@mui/x-date-pickers"; -import moment from "jalali-moment"; -import { useWatch } from "react-hook-form"; - -const DatePickerForEndTime = ({ field, fieldState: { error }, control }) => { - const startTime = useWatch({ control, name: "start_time" }); - return ( - { - const date = new Date(end_time); - const formattedDate = moment(date).locale("en").format("YYYY-MM-DD HH:mm"); - field.onChange(formattedDate); - }} - slotProps={{ - textField: { - size: "small", - placeholder: "تاریخ و ساعت وارد کنید", - InputLabelProps: { shrink: true }, - sx: { width: { xs: "100%", md: 200 } }, - InputProps: { - endAdornment: ( - - { - event.stopPropagation(); - field.onChange(""); - }} - sx={{ - color: "#bfbfbf", - "&:hover": { - backgroundColor: "rgba(189, 189, 189, 0.1)", - color: "#363434", - }, - }} - > - - - - ), - }, - }, - }} - label="تاریخ و ساعت پایان گشت" - /> - ); -}; -export default DatePickerForEndTime; +import { IconButton, InputAdornment } from "@mui/material"; +import { ClearIcon, MobileDateTimePicker } from "@mui/x-date-pickers"; +import moment from "jalali-moment"; +import { useWatch } from "react-hook-form"; + +const DatePickerForEndTime = ({ field, fieldState: { error }, control }) => { + const startTime = useWatch({ control, name: "start_time" }); + return ( + { + const date = new Date(end_time); + const formattedDate = moment(date).locale("en").format("YYYY-MM-DD HH:mm"); + field.onChange(formattedDate); + }} + slotProps={{ + textField: { + size: "small", + placeholder: "تاریخ و ساعت وارد کنید", + InputLabelProps: { shrink: true }, + sx: { width: { xs: "100%", md: 200 } }, + InputProps: { + endAdornment: ( + + { + event.stopPropagation(); + field.onChange(""); + }} + sx={{ + color: "#bfbfbf", + "&:hover": { + backgroundColor: "rgba(189, 189, 189, 0.1)", + color: "#363434", + }, + }} + > + + + + ), + }, + }, + }} + label="تاریخ و ساعت پایان گشت" + /> + ); +}; +export default DatePickerForEndTime; diff --git a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/DatePickerForStartTime.jsx b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/DatePickerForStartTime.jsx index 927ad13..ef5663f 100644 --- a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/DatePickerForStartTime.jsx +++ b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/DatePickerForStartTime.jsx @@ -1,54 +1,54 @@ -import { IconButton, InputAdornment } from "@mui/material"; -import { ClearIcon, MobileDateTimePicker } from "@mui/x-date-pickers"; -import moment from "jalali-moment"; -import { useWatch } from "react-hook-form"; - -const DatePickerForStartTime = ({ field, fieldState: { error }, control }) => { - const endTime = useWatch({ control, name: "end_time" }); - return ( - { - const date = new Date(start_time); - const formattedDate = moment(date).locale("en").format("YYYY-MM-DD HH:mm"); - field.onChange(formattedDate); - }} - slotProps={{ - textField: { - size: "small", - placeholder: "تاریخ و ساعت وارد کنید", - InputLabelProps: { shrink: true }, - sx: { width: { xs: "100%", md: 200 } }, - InputProps: { - endAdornment: ( - - { - event.stopPropagation(); - field.onChange(""); - }} - sx={{ - color: "#bfbfbf", - "&:hover": { - backgroundColor: "rgba(189, 189, 189, 0.1)", - color: "#363434", - }, - }} - > - - - - ), - }, - }, - }} - label="تاریخ و ساعت شروع گشت" - /> - ); -}; -export default DatePickerForStartTime; +import { IconButton, InputAdornment } from "@mui/material"; +import { ClearIcon, MobileDateTimePicker } from "@mui/x-date-pickers"; +import moment from "jalali-moment"; +import { useWatch } from "react-hook-form"; + +const DatePickerForStartTime = ({ field, fieldState: { error }, control }) => { + const endTime = useWatch({ control, name: "end_time" }); + return ( + { + const date = new Date(start_time); + const formattedDate = moment(date).locale("en").format("YYYY-MM-DD HH:mm"); + field.onChange(formattedDate); + }} + slotProps={{ + textField: { + size: "small", + placeholder: "تاریخ و ساعت وارد کنید", + InputLabelProps: { shrink: true }, + sx: { width: { xs: "100%", md: 200 } }, + InputProps: { + endAdornment: ( + + { + event.stopPropagation(); + field.onChange(""); + }} + sx={{ + color: "#bfbfbf", + "&:hover": { + backgroundColor: "rgba(189, 189, 189, 0.1)", + color: "#363434", + }, + }} + > + + + + ), + }, + }, + }} + label="تاریخ و ساعت شروع گشت" + /> + ); +}; +export default DatePickerForStartTime; diff --git a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/EditActionDuringPatrol.jsx b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/EditActionDuringPatrol.jsx index 46875ce..282fee6 100644 --- a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/EditActionDuringPatrol.jsx +++ b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/EditActionDuringPatrol.jsx @@ -1,62 +1,62 @@ -"use client"; - -import React, { useState } from "react"; -import dynamic from "next/dynamic"; -import MapLoading from "@/core/components/MapLayer/Loading"; -import { Dialog, DialogTitle, IconButton } from "@mui/material"; -import EditIcon from "@mui/icons-material/Edit"; -import EditFormContent from "@/components/dashboard/roadItems/operator/RowActions/EditForm/EditFormContent"; - -const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { - loading: () => , - ssr: false, -}); - -const EditActionDuringPatrol = ({ action, index, setActionsList }) => { - const [open, setOpen] = useState(false); - - const handleOpen = () => { - setOpen(true); - }; - - const HandleSubmit = async (newData) => { - setActionsList((prev) => { - const updatedList = [...prev]; - updatedList[index] = { - ...updatedList[index], - data: newData.data, - result: newData.result, - }; - return updatedList; - }); - setOpen(false); - }; - - return ( - <> - - - - - ویرایش اطلاعات - - - - ); -}; - -export default EditActionDuringPatrol; +"use client"; + +import React, { useState } from "react"; +import dynamic from "next/dynamic"; +import MapLoading from "@/core/components/MapLayer/Loading"; +import { Dialog, DialogTitle, IconButton } from "@mui/material"; +import EditIcon from "@mui/icons-material/Edit"; +import EditFormContent from "@/components/dashboard/roadItems/operator/RowActions/EditForm/EditFormContent"; + +const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { + loading: () => , + ssr: false, +}); + +const EditActionDuringPatrol = ({ action, index, setActionsList }) => { + const [open, setOpen] = useState(false); + + const handleOpen = () => { + setOpen(true); + }; + + const HandleSubmit = async (newData) => { + setActionsList((prev) => { + const updatedList = [...prev]; + updatedList[index] = { + ...updatedList[index], + data: newData.data, + result: newData.result, + }; + return updatedList; + }); + setOpen(false); + }; + + return ( + <> + + + + + ویرایش اطلاعات + + + + ); +}; + +export default EditActionDuringPatrol; diff --git a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/GetObservedItemInfo.jsx b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/GetObservedItemInfo.jsx index 63a1953..245b1ab 100644 --- a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/GetObservedItemInfo.jsx +++ b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/GetObservedItemInfo.jsx @@ -1,55 +1,55 @@ -import MapInfoOneMarker from "@/core/components/MapInfoOneMarker"; -import MapInfoTwoMarker from "@/core/components/MapInfoTwoMarker"; -import { FormControl, InputLabel, MenuItem, OutlinedInput, Select, Stack, TextField } from "@mui/material"; -import PreviousStatesInfoInObservedItem from "./PreviousStatesInfoInObservedItem"; - -const GetObservedItemInfo = ({ register, itemsList, subItemsList, control, setValue, errors, watch, getValues }) => { - return ( - - - - - - - - - - - اولویت - - - - - - {subItemsList?.needs_end_point === 1 ? ( - - ) : ( - - )} - - - ); -}; -export default GetObservedItemInfo; +import MapInfoOneMarker from "@/core/components/MapInfoOneMarker"; +import MapInfoTwoMarker from "@/core/components/MapInfoTwoMarker"; +import { FormControl, InputLabel, MenuItem, OutlinedInput, Select, Stack, TextField } from "@mui/material"; +import PreviousStatesInfoInObservedItem from "./PreviousStatesInfoInObservedItem"; + +const GetObservedItemInfo = ({ register, itemsList, subItemsList, control, setValue, errors, watch, getValues }) => { + return ( + + + + + + + + + + + اولویت + + + + + + {subItemsList?.needs_end_point === 1 ? ( + + ) : ( + + )} + + + ); +}; +export default GetObservedItemInfo; diff --git a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/ModalActionsDuringPatrol.jsx b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/ModalActionsDuringPatrol.jsx index 97be471..56becc9 100644 --- a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/ModalActionsDuringPatrol.jsx +++ b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/ModalActionsDuringPatrol.jsx @@ -1,16 +1,16 @@ -import CreateFormContent from "@/components/dashboard/roadItems/operator/Actions/Create/Forms/CreateFormContent"; -import { Dialog } from "@mui/material"; - -const ModalActionsDuringPatrol = ({ open, setOpen, setActionsList }) => { - const HandleSubmit = async (data) => { - setActionsList((prev) => [...prev, { ...data, instant_action: 1 }]); - setOpen(false); - }; - - return ( - - - - ); -}; -export default ModalActionsDuringPatrol; +import CreateFormContent from "@/components/dashboard/roadItems/operator/Actions/Create/Forms/CreateFormContent"; +import { Dialog } from "@mui/material"; + +const ModalActionsDuringPatrol = ({ open, setOpen, setActionsList }) => { + const HandleSubmit = async (data) => { + setActionsList((prev) => [...prev, { ...data, instant_action: 1 }]); + setOpen(false); + }; + + return ( + + + + ); +}; +export default ModalActionsDuringPatrol; diff --git a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/ModalObservedItemPatrol.jsx b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/ModalObservedItemPatrol.jsx index 9a6c0fc..c9a400a 100644 --- a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/ModalObservedItemPatrol.jsx +++ b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/ModalObservedItemPatrol.jsx @@ -1,16 +1,16 @@ -import { Dialog } from "@mui/material"; -import CreateFormContentObservedItem from "./CreateFormContentObservedItem"; - -const ModalObservedItemPatrol = ({ open, setOpen, setActionsList }) => { - const HandleSubmit = async (data) => { - setActionsList((prev) => [...prev, { ...data, instant_action: 0 }]); - setOpen(false); - }; - - return ( - - - - ); -}; -export default ModalObservedItemPatrol; +import { Dialog } from "@mui/material"; +import CreateFormContentObservedItem from "./CreateFormContentObservedItem"; + +const ModalObservedItemPatrol = ({ open, setOpen, setActionsList }) => { + const HandleSubmit = async (data) => { + setActionsList((prev) => [...prev, { ...data, instant_action: 0 }]); + setOpen(false); + }; + + return ( + + + + ); +}; +export default ModalObservedItemPatrol; diff --git a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/ObservedInfo.jsx b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/ObservedInfo.jsx index 16b9953..8911547 100644 --- a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/ObservedInfo.jsx +++ b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/ObservedInfo.jsx @@ -1,37 +1,37 @@ -"use client"; - -import DeleteIcon from "@mui/icons-material/Delete"; -import VisibilityIcon from "@mui/icons-material/Visibility"; -import { Box, Card, CardActions, CardHeader, Chip, IconButton, Typography } from "@mui/material"; - -const ObservedInfo = ({ action, deleteAction }) => { - return ( - - } - title={ - - {action.data.item_name} - - } - subheader={action.data.sub_item_name} - /> - - - - - - - - - ); -}; - -export default ObservedInfo; +"use client"; + +import DeleteIcon from "@mui/icons-material/Delete"; +import VisibilityIcon from "@mui/icons-material/Visibility"; +import { Box, Card, CardActions, CardHeader, Chip, IconButton, Typography } from "@mui/material"; + +const ObservedInfo = ({ action, deleteAction }) => { + return ( + + } + title={ + + {action.data.item_name} + + } + subheader={action.data.sub_item_name} + /> + + + + + + + + + ); +}; + +export default ObservedInfo; diff --git a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PatrolDetail.jsx b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PatrolDetail.jsx index 6202bb6..3ec6fd4 100644 --- a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PatrolDetail.jsx +++ b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PatrolDetail.jsx @@ -1,180 +1,180 @@ -"use client"; - -import CarCode from "@/core/components/CarCode"; -import StyledForm from "@/core/components/StyledForm"; -import { GET_FMS_DATA as GET_VAHICLE_OPRATION } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { yupResolver } from "@hookform/resolvers/yup"; -import ExitToAppIcon from "@mui/icons-material/ExitToApp"; -import SearchIcon from "@mui/icons-material/Search"; -import { Box, Button, Chip, DialogActions, DialogContent, Divider, Stack } from "@mui/material"; -import { LocalizationProvider } from "@mui/x-date-pickers"; -import { AdapterDateFnsJalali } from "@mui/x-date-pickers/AdapterDateFnsJalali"; -import { faIR } from "@mui/x-date-pickers/locales"; -import moment from "jalali-moment"; -import { useState } from "react"; -import { Controller, useForm } from "react-hook-form"; -import * as yup from "yup"; -import DatePickerForEndTime from "./DatePickerForEndTime"; -import DatePickerForStartTime from "./DatePickerForStartTime"; -import PatrolDetailInfo from "./PatrolDetailInfo"; -import PatrolResultCodeErrors from "./PatrolResultCodeErrors"; - -const schema = yup.object().shape({ - roadPatrolMachinesId: yup.object().required("خودرو الزامی است."), - start_time: yup.string().required("زمان شروع الزامی است."), - end_time: yup.string().required("زمان پایان الزامی است."), -}); - -const PatrolDetail = ({ allData, setAllData, handlePrev, setTabState }) => { - const defaultValues = { - has_vehicle_operation: allData.has_vehicle_operation, - roadPatrolMachinesId: allData.roadPatrolMachinesId, - start_time: allData.start_time, - end_time: allData.end_time, - stopPoints: allData.stopPoints, - accOnDuration: allData.accOnDuration, - fuelConsumption: allData.fuelConsumption, - mileage: allData.mileage, - }; - const requestServer = useRequest(); - const [patrolResultStatus, setPatrolResultStatus] = useState(allData.resultCode); - const [patrolData, setPatrolData] = useState(defaultValues); - - const { - control, - handleSubmit, - setValue, - formState: { isSubmitting, isValid }, - } = useForm({ defaultValues, resolver: yupResolver(schema), mode: "all" }); - - const requestPatrolInfo = async (data) => { - setPatrolResultStatus(1); - setPatrolData((pd) => ({ ...pd, has_vehicle_operation: false })); - const formData = new FormData(); - formData.append("machineCode", data.roadPatrolMachinesId.machine_code); - formData.append("startDT", moment(data.start_time).format("YYYY-MM-DDTHH:mm")); - formData.append("endDT", moment(data.end_time).format("YYYY-MM-DDTHH:mm")); - try { - const response = await requestServer(GET_VAHICLE_OPRATION, "post", { - data: formData, - }); - const result = response.data.data; - setPatrolData({ - ...result, - roadPatrolMachinesId: data.roadPatrolMachinesId, - start_time: data.start_time, - end_time: data.end_time, - has_vehicle_operation: result.resultCode == 0, - }); - - setValue("stopPoints", result.stopPoints); - setValue("accOnDuration", result.accOnDuration); - setValue("fuelConsumption", result.fuelConsumption); - setValue("mileage", result.mileage); - setValue("has_vehicle_operation", true); - setPatrolResultStatus(result.resultCode); - } catch (error) {} - }; - - const handleNext = (data) => { - setAllData(data); - setTabState((s) => s + 1); - }; - - return ( - <> - - - - - - - { - return ( - field.onChange(value)} - error={error} - /> - ); - }} - name={"roadPatrolMachinesId"} - /> - - - - } - name={"start_time"} - /> - } - name={"end_time"} - /> - - - - - - - - - {patrolResultStatus !== 0 && } - - - - - - - - - - ); -}; - -export default PatrolDetail; +"use client"; + +import CarCode from "@/core/components/CarCode"; +import StyledForm from "@/core/components/StyledForm"; +import { GET_FMS_DATA as GET_VAHICLE_OPRATION } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { yupResolver } from "@hookform/resolvers/yup"; +import ExitToAppIcon from "@mui/icons-material/ExitToApp"; +import SearchIcon from "@mui/icons-material/Search"; +import { Box, Button, Chip, DialogActions, DialogContent, Divider, Stack } from "@mui/material"; +import { LocalizationProvider } from "@mui/x-date-pickers"; +import { AdapterDateFnsJalali } from "@mui/x-date-pickers/AdapterDateFnsJalali"; +import { faIR } from "@mui/x-date-pickers/locales"; +import moment from "jalali-moment"; +import { useState } from "react"; +import { Controller, useForm } from "react-hook-form"; +import * as yup from "yup"; +import DatePickerForEndTime from "./DatePickerForEndTime"; +import DatePickerForStartTime from "./DatePickerForStartTime"; +import PatrolDetailInfo from "./PatrolDetailInfo"; +import PatrolResultCodeErrors from "./PatrolResultCodeErrors"; + +const schema = yup.object().shape({ + roadPatrolMachinesId: yup.object().required("خودرو الزامی است."), + start_time: yup.string().required("زمان شروع الزامی است."), + end_time: yup.string().required("زمان پایان الزامی است."), +}); + +const PatrolDetail = ({ allData, setAllData, handlePrev, setTabState }) => { + const defaultValues = { + has_vehicle_operation: allData.has_vehicle_operation, + roadPatrolMachinesId: allData.roadPatrolMachinesId, + start_time: allData.start_time, + end_time: allData.end_time, + stopPoints: allData.stopPoints, + accOnDuration: allData.accOnDuration, + fuelConsumption: allData.fuelConsumption, + mileage: allData.mileage, + }; + const requestServer = useRequest(); + const [patrolResultStatus, setPatrolResultStatus] = useState(allData.resultCode); + const [patrolData, setPatrolData] = useState(defaultValues); + + const { + control, + handleSubmit, + setValue, + formState: { isSubmitting, isValid }, + } = useForm({ defaultValues, resolver: yupResolver(schema), mode: "all" }); + + const requestPatrolInfo = async (data) => { + setPatrolResultStatus(1); + setPatrolData((pd) => ({ ...pd, has_vehicle_operation: false })); + const formData = new FormData(); + formData.append("machineCode", data.roadPatrolMachinesId.machine_code); + formData.append("startDT", moment(data.start_time).format("YYYY-MM-DDTHH:mm")); + formData.append("endDT", moment(data.end_time).format("YYYY-MM-DDTHH:mm")); + try { + const response = await requestServer(GET_VAHICLE_OPRATION, "post", { + data: formData, + }); + const result = response.data.data; + setPatrolData({ + ...result, + roadPatrolMachinesId: data.roadPatrolMachinesId, + start_time: data.start_time, + end_time: data.end_time, + has_vehicle_operation: result.resultCode == 0, + }); + + setValue("stopPoints", result.stopPoints); + setValue("accOnDuration", result.accOnDuration); + setValue("fuelConsumption", result.fuelConsumption); + setValue("mileage", result.mileage); + setValue("has_vehicle_operation", true); + setPatrolResultStatus(result.resultCode); + } catch (error) {} + }; + + const handleNext = (data) => { + setAllData(data); + setTabState((s) => s + 1); + }; + + return ( + <> + + + + + + + { + return ( + field.onChange(value)} + error={error} + /> + ); + }} + name={"roadPatrolMachinesId"} + /> + + + + } + name={"start_time"} + /> + } + name={"end_time"} + /> + + + + + + + + + {patrolResultStatus !== 0 && } + + + + + + + + + + ); +}; + +export default PatrolDetail; diff --git a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PatrolDetailInfo.jsx b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PatrolDetailInfo.jsx index 14fd172..6e5109d 100644 --- a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PatrolDetailInfo.jsx +++ b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PatrolDetailInfo.jsx @@ -1,166 +1,166 @@ -"use client"; - -import MapLoading from "@/core/components/MapLayer/Loading"; -import ShowPlak from "@/core/components/ShowPlak"; -import { formatSecondsToHHMMSS } from "@/core/utils/formatSecondsToHHMMSS"; -import AddRoadIcon from "@mui/icons-material/AddRoad"; -import BadgeIcon from "@mui/icons-material/Badge"; -import DirectionsCarFilledIcon from "@mui/icons-material/DirectionsCarFilled"; -import ElectricCarIcon from "@mui/icons-material/ElectricCar"; -import LocalGasStationIcon from "@mui/icons-material/LocalGasStation"; -import QrCode2Icon from "@mui/icons-material/QrCode2"; -import QueryBuilderIcon from "@mui/icons-material/QueryBuilder"; -import ShareLocationIcon from "@mui/icons-material/ShareLocation"; -import WatchLaterIcon from "@mui/icons-material/WatchLater"; -import { Box, Card, CardContent, Chip, Divider, Fade, Stack, Typography } from "@mui/material"; -import moment from "jalali-moment"; -import dynamic from "next/dynamic"; -import React, { useEffect } from "react"; -import { useMap } from "react-leaflet"; -import PatrolMapFeatures from "./PatrolMapFeatures"; - -const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { - loading: () => , - ssr: false, -}); - -const MapItemViewBound = ({ patrolData, bound }) => { - const map = useMap(); - - useEffect(() => { - if (bound.length !== 0) { - map.fitBounds(bound, { paddingTopLeft: [64, 64], paddingBottomRight: [64, 64] }); - } - }, [bound]); - - return ( - <> - {patrolData?.stopPoints && - patrolData.stopPoints.map((stopPoint, index) => ( - - - - ))} - - ); -}; - -const PatrolDetailInfo = ({ patrolData }) => { - const bound = patrolData?.stopPoints - ? patrolData?.stopPoints.map((point) => [point.latitude, point.longitude]) - : []; - - return ( - - - - - - } /> - - - {patrolData?.start_time !== "" && - moment(patrolData?.start_time).locale("fa").format("HH:mm | YYYY/MM/DD")} - - - - } /> - - - {patrolData?.end_time !== "" && - moment(patrolData?.end_time).locale("fa").format("HH:mm | YYYY/MM/DD")} - - - - } /> - - - {patrolData?.roadPatrolMachinesId?.machine_code} - - - - } /> - - - {patrolData?.roadPatrolMachinesId?.car_name} - - - - } /> - - - {patrolData?.roadPatrolMachinesId?.plak_number && - ShowPlak({ plak_number: patrolData?.roadPatrolMachinesId?.plak_number })} - - - - } /> - - - {formatSecondsToHHMMSS(patrolData?.accOnDuration)} - - - - } /> - - - {(patrolData?.mileage / 1000).toFixed(1)} کیلومتر - - - - } /> - - - {Math.round(patrolData?.fuelConsumption * 10) / 10} لیتر - - - - } /> - - - {patrolData?.stopPoints?.length} نقطه - - - - - - - - {bound.length > 0 && ( - - - - )} - - - - - - - ); -}; - -export default PatrolDetailInfo; +"use client"; + +import MapLoading from "@/core/components/MapLayer/Loading"; +import ShowPlak from "@/core/components/ShowPlak"; +import { formatSecondsToHHMMSS } from "@/core/utils/formatSecondsToHHMMSS"; +import AddRoadIcon from "@mui/icons-material/AddRoad"; +import BadgeIcon from "@mui/icons-material/Badge"; +import DirectionsCarFilledIcon from "@mui/icons-material/DirectionsCarFilled"; +import ElectricCarIcon from "@mui/icons-material/ElectricCar"; +import LocalGasStationIcon from "@mui/icons-material/LocalGasStation"; +import QrCode2Icon from "@mui/icons-material/QrCode2"; +import QueryBuilderIcon from "@mui/icons-material/QueryBuilder"; +import ShareLocationIcon from "@mui/icons-material/ShareLocation"; +import WatchLaterIcon from "@mui/icons-material/WatchLater"; +import { Box, Card, CardContent, Chip, Divider, Fade, Stack, Typography } from "@mui/material"; +import moment from "jalali-moment"; +import dynamic from "next/dynamic"; +import React, { useEffect } from "react"; +import { useMap } from "react-leaflet"; +import PatrolMapFeatures from "./PatrolMapFeatures"; + +const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { + loading: () => , + ssr: false, +}); + +const MapItemViewBound = ({ patrolData, bound }) => { + const map = useMap(); + + useEffect(() => { + if (bound.length !== 0) { + map.fitBounds(bound, { paddingTopLeft: [64, 64], paddingBottomRight: [64, 64] }); + } + }, [bound]); + + return ( + <> + {patrolData?.stopPoints && + patrolData.stopPoints.map((stopPoint, index) => ( + + + + ))} + + ); +}; + +const PatrolDetailInfo = ({ patrolData }) => { + const bound = patrolData?.stopPoints + ? patrolData?.stopPoints.map((point) => [point.latitude, point.longitude]) + : []; + + return ( + + + + + + } /> + + + {patrolData?.start_time !== "" && + moment(patrolData?.start_time).locale("fa").format("HH:mm | YYYY/MM/DD")} + + + + } /> + + + {patrolData?.end_time !== "" && + moment(patrolData?.end_time).locale("fa").format("HH:mm | YYYY/MM/DD")} + + + + } /> + + + {patrolData?.roadPatrolMachinesId?.machine_code} + + + + } /> + + + {patrolData?.roadPatrolMachinesId?.car_name} + + + + } /> + + + {patrolData?.roadPatrolMachinesId?.plak_number && + ShowPlak({ plak_number: patrolData?.roadPatrolMachinesId?.plak_number })} + + + + } /> + + + {formatSecondsToHHMMSS(patrolData?.accOnDuration)} + + + + } /> + + + {(patrolData?.mileage / 1000).toFixed(1)} کیلومتر + + + + } /> + + + {Math.round(patrolData?.fuelConsumption * 10) / 10} لیتر + + + + } /> + + + {patrolData?.stopPoints?.length} نقطه + + + + + + + + {bound.length > 0 && ( + + + + )} + + + + + + + ); +}; + +export default PatrolDetailInfo; diff --git a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PatrolForms.jsx b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PatrolForms.jsx index 63b877c..e123cf5 100644 --- a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PatrolForms.jsx +++ b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PatrolForms.jsx @@ -1,132 +1,132 @@ -"use client"; - -import { useTheme } from "@emotion/react"; -import EngineeringIcon from "@mui/icons-material/Engineering"; -import HandymanIcon from "@mui/icons-material/Handyman"; -import TaxiAlertIcon from "@mui/icons-material/TaxiAlert"; -import VerifiedIcon from "@mui/icons-material/Verified"; -import { Box, Tab, Tabs, useMediaQuery } from "@mui/material"; -import { DialogHeader } from "next/dist/client/components/react-dev-overlay/internal/components/Dialog"; -import { useCallback, useEffect, useReducer, useState } from "react"; -import ActionsDuringPatrol from "./ActionsDurigPatrol"; -import CompeleteRequest from "./CompeleteRequest"; -import PatrolDetail from "./PatrolDetail"; -import SuperVisorsDetail from "./SuperVisorsDetail"; - -function TabPanel(props) { - const { children, value, index } = props; - - return ( - - ); -} - -const defaultValues = { - has_vehicle_operation: false, - road_patrol_rahdaran_id: [], - roadPatrolMachinesId: null, - start_time: "", - end_time: "", - stopPoints: null, - accOnDuration: "", - fuelConsumption: "", - mileage: "", - observed_items: [], - phone_number: "", - otp_token: "", - resultCode: null, -}; - -const reducer = (state, action) => { - switch (action.type) { - case "changeData": - return { ...state, ...action.data }; - default: - return state; - } -}; - -const PatrolForms = ({ mutate, setOpen }) => { - const [allData, dispatch] = useReducer(reducer, defaultValues); - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("md")); - const [tabState, setTabState] = useState(0); - const [activeUpTo, setActiveUpTo] = useState(0); - - const handleChangeTab = (event, newValue) => { - setTabState(newValue); - }; - - useEffect(() => { - if (activeUpTo < tabState) { - setActiveUpTo(tabState); - } - }, [tabState]); - - const handlePrev = useCallback(() => { - if (tabState == 0) { - setOpen(false); - } - setTabState((s) => s - 1); - }, [tabState]); - - return ( - <> - - - = 0)} icon={} label="مشخصات گشت"> - = 1)} icon={} label="مشخصات راهداران"> - = 2)} icon={} label="اقدامات حین گشت"> - = 3)} icon={} label="بررسی نهایی و ثبت"> - - - - { - dispatch({ type: "changeData", data }); - }} - handlePrev={handlePrev} - setTabState={setTabState} - /> - - - { - dispatch({ type: "changeData", data }); - }} - handlePrev={handlePrev} - setTabState={setTabState} - /> - - - { - dispatch({ type: "changeData", data }); - }} - handlePrev={handlePrev} - setTabState={setTabState} - /> - - - - - - ); -}; -export default PatrolForms; +"use client"; + +import { useTheme } from "@emotion/react"; +import EngineeringIcon from "@mui/icons-material/Engineering"; +import HandymanIcon from "@mui/icons-material/Handyman"; +import TaxiAlertIcon from "@mui/icons-material/TaxiAlert"; +import VerifiedIcon from "@mui/icons-material/Verified"; +import { Box, Tab, Tabs, useMediaQuery } from "@mui/material"; +import { DialogHeader } from "next/dist/client/components/react-dev-overlay/internal/components/Dialog"; +import { useCallback, useEffect, useReducer, useState } from "react"; +import ActionsDuringPatrol from "./ActionsDurigPatrol"; +import CompeleteRequest from "./CompeleteRequest"; +import PatrolDetail from "./PatrolDetail"; +import SuperVisorsDetail from "./SuperVisorsDetail"; + +function TabPanel(props) { + const { children, value, index } = props; + + return ( + + ); +} + +const defaultValues = { + has_vehicle_operation: false, + road_patrol_rahdaran_id: [], + roadPatrolMachinesId: null, + start_time: "", + end_time: "", + stopPoints: null, + accOnDuration: "", + fuelConsumption: "", + mileage: "", + observed_items: [], + phone_number: "", + otp_token: "", + resultCode: null, +}; + +const reducer = (state, action) => { + switch (action.type) { + case "changeData": + return { ...state, ...action.data }; + default: + return state; + } +}; + +const PatrolForms = ({ mutate, setOpen }) => { + const [allData, dispatch] = useReducer(reducer, defaultValues); + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("md")); + const [tabState, setTabState] = useState(0); + const [activeUpTo, setActiveUpTo] = useState(0); + + const handleChangeTab = (event, newValue) => { + setTabState(newValue); + }; + + useEffect(() => { + if (activeUpTo < tabState) { + setActiveUpTo(tabState); + } + }, [tabState]); + + const handlePrev = useCallback(() => { + if (tabState == 0) { + setOpen(false); + } + setTabState((s) => s - 1); + }, [tabState]); + + return ( + <> + + + = 0)} icon={} label="مشخصات گشت"> + = 1)} icon={} label="مشخصات راهداران"> + = 2)} icon={} label="اقدامات حین گشت"> + = 3)} icon={} label="بررسی نهایی و ثبت"> + + + + { + dispatch({ type: "changeData", data }); + }} + handlePrev={handlePrev} + setTabState={setTabState} + /> + + + { + dispatch({ type: "changeData", data }); + }} + handlePrev={handlePrev} + setTabState={setTabState} + /> + + + { + dispatch({ type: "changeData", data }); + }} + handlePrev={handlePrev} + setTabState={setTabState} + /> + + + + + + ); +}; +export default PatrolForms; diff --git a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PatrolMapFeatures.jsx b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PatrolMapFeatures.jsx index 8779132..a74ceb3 100644 --- a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PatrolMapFeatures.jsx +++ b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PatrolMapFeatures.jsx @@ -1,39 +1,39 @@ -"use client"; - -import { Typography } from "@mui/material"; -import React, { useRef } from "react"; -import { Marker, Popup } from "react-leaflet"; -import AzmayeshIcon from "@/assets/images/examine_marker.png"; -import { formatSecondsToHHMMSS } from "@/core/utils/formatSecondsToHHMMSS"; - -const PatrolMapFeatures = ({ stopPoint }) => { - const position = [stopPoint.latitude, stopPoint.longitude]; - const mapPatrolMarker = useRef(); - const createCustomIcon = (size, iconUrl) => { - return L.icon({ - iconUrl: iconUrl, - iconSize: size, - iconAnchor: [size[0] / 2, size[1]], - popupAnchor: [0, -size[1]], - }); - }; - - return ( - - - مدت زمان توقف: {formatSecondsToHHMMSS(stopPoint.duration)} - - - ); -}; - -export default PatrolMapFeatures; +"use client"; + +import { Typography } from "@mui/material"; +import React, { useRef } from "react"; +import { Marker, Popup } from "react-leaflet"; +import AzmayeshIcon from "@/assets/images/examine_marker.png"; +import { formatSecondsToHHMMSS } from "@/core/utils/formatSecondsToHHMMSS"; + +const PatrolMapFeatures = ({ stopPoint }) => { + const position = [stopPoint.latitude, stopPoint.longitude]; + const mapPatrolMarker = useRef(); + const createCustomIcon = (size, iconUrl) => { + return L.icon({ + iconUrl: iconUrl, + iconSize: size, + iconAnchor: [size[0] / 2, size[1]], + popupAnchor: [0, -size[1]], + }); + }; + + return ( + + + مدت زمان توقف: {formatSecondsToHHMMSS(stopPoint.duration)} + + + ); +}; + +export default PatrolMapFeatures; diff --git a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PatrolResultCodeErrors.jsx b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PatrolResultCodeErrors.jsx index e079d0e..ae9e1ac 100644 --- a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PatrolResultCodeErrors.jsx +++ b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PatrolResultCodeErrors.jsx @@ -1,29 +1,29 @@ -"use client"; - -import { Box, Typography } from "@mui/material"; -import React from "react"; - -const PatrolResultCodeErrors = ({ ResultCode }) => { - const errorMessages = { - [1]: "درحال دریافت عملکرد خودرو ...", - [-1]: "نام کاربری یا کلمه عبور صحیح نمیباشد", - [-2]: "ردیاب به خودرو انتخابی متصل نیست", - [-3]: "کاربر دسترسی لازم به اطلاعات خودرو انتخابی را ندارد", - [-4]: "خطای درخواست مکرر", - }; - - const message = errorMessages[ResultCode] || "ابتدا اطلاعات بالا را تکمیل نمایید"; - - return ( - - - {message} - - - ); -}; - -export default PatrolResultCodeErrors; +"use client"; + +import { Box, Typography } from "@mui/material"; +import React from "react"; + +const PatrolResultCodeErrors = ({ ResultCode }) => { + const errorMessages = { + [1]: "درحال دریافت عملکرد خودرو ...", + [-1]: "نام کاربری یا کلمه عبور صحیح نمیباشد", + [-2]: "ردیاب به خودرو انتخابی متصل نیست", + [-3]: "کاربر دسترسی لازم به اطلاعات خودرو انتخابی را ندارد", + [-4]: "خطای درخواست مکرر", + }; + + const message = errorMessages[ResultCode] || "ابتدا اطلاعات بالا را تکمیل نمایید"; + + return ( + + + {message} + + + ); +}; + +export default PatrolResultCodeErrors; diff --git a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PatrolTimeLine.jsx b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PatrolTimeLine.jsx index 4edaa2f..09f577d 100644 --- a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PatrolTimeLine.jsx +++ b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PatrolTimeLine.jsx @@ -1,119 +1,119 @@ -"use client"; - -import { Box, CircularProgress, Typography } from "@mui/material"; -import TaxiAlertIcon from "@mui/icons-material/TaxiAlert"; -import EngineeringIcon from "@mui/icons-material/Engineering"; -import HandymanIcon from "@mui/icons-material/Handyman"; -import VerifiedIcon from "@mui/icons-material/Verified"; -import { - Timeline, - TimelineConnector, - TimelineContent, - TimelineDot, - TimelineItem, - timelineItemClasses, - TimelineSeparator, -} from "@mui/lab"; - -const PatrolTimeLine = ({ tabState }) => { - return ( - - - - - - - {tabState === 0 ? ( - - ) : ( - 0 ? "success" : "error"} - sx={{ width: "1.5rem", height: "1.5rem" }} - /> - )} - - - - - مشخصات گشت - - تایید اطلاعات اولیه گشت - - - - - - - - {tabState === 1 ? ( - - ) : ( - 1 ? "success" : "error"} - sx={{ width: "1.5rem", height: "1.5rem" }} - /> - )} - - - - - مشخصات راهداران - - راهدار / راهداران حاضر در گشت - - - - - - - - {tabState === 2 ? ( - - ) : ( - 2 ? "success" : "error"} - sx={{ width: "1.5rem", height: "1.5rem" }} - /> - )} - - - - - اقدامات حین گشت - - ثبت فعالیت های صورت گرفته حین گشت - - - - - - - - {tabState === 3 ? ( - - ) : ( - 3 ? "success" : "error"} - sx={{ width: "1.5rem", height: "1.5rem" }} - /> - )} - - - - - تکمیل درخواست - - تکمیل درخواست و ثبت نهایی - - - - - - ); -}; -export default PatrolTimeLine; +"use client"; + +import { Box, CircularProgress, Typography } from "@mui/material"; +import TaxiAlertIcon from "@mui/icons-material/TaxiAlert"; +import EngineeringIcon from "@mui/icons-material/Engineering"; +import HandymanIcon from "@mui/icons-material/Handyman"; +import VerifiedIcon from "@mui/icons-material/Verified"; +import { + Timeline, + TimelineConnector, + TimelineContent, + TimelineDot, + TimelineItem, + timelineItemClasses, + TimelineSeparator, +} from "@mui/lab"; + +const PatrolTimeLine = ({ tabState }) => { + return ( + + + + + + + {tabState === 0 ? ( + + ) : ( + 0 ? "success" : "error"} + sx={{ width: "1.5rem", height: "1.5rem" }} + /> + )} + + + + + مشخصات گشت + + تایید اطلاعات اولیه گشت + + + + + + + + {tabState === 1 ? ( + + ) : ( + 1 ? "success" : "error"} + sx={{ width: "1.5rem", height: "1.5rem" }} + /> + )} + + + + + مشخصات راهداران + + راهدار / راهداران حاضر در گشت + + + + + + + + {tabState === 2 ? ( + + ) : ( + 2 ? "success" : "error"} + sx={{ width: "1.5rem", height: "1.5rem" }} + /> + )} + + + + + اقدامات حین گشت + + ثبت فعالیت های صورت گرفته حین گشت + + + + + + + + {tabState === 3 ? ( + + ) : ( + 3 ? "success" : "error"} + sx={{ width: "1.5rem", height: "1.5rem" }} + /> + )} + + + + + تکمیل درخواست + + تکمیل درخواست و ثبت نهایی + + + + + + ); +}; +export default PatrolTimeLine; diff --git a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PreviousStatesInfoInObservedItem.jsx b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PreviousStatesInfoInObservedItem.jsx index 7476631..70f9f1a 100644 --- a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PreviousStatesInfoInObservedItem.jsx +++ b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/PreviousStatesInfoInObservedItem.jsx @@ -1,43 +1,43 @@ -import { Box, Chip, Divider, Grid, Typography } from "@mui/material"; -import InsertDriveFileIcon from "@mui/icons-material/InsertDriveFile"; -import FileCopyIcon from "@mui/icons-material/FileCopy"; - -const PreviousStatesInfoInObservedItem = ({ itemsList, subItemsList }) => { - return ( - - - - } - label={ - - آیتم انتخاب ‌شده - - } - /> - - - - {itemsList.name || "هیچ آیتمی انتخاب نشده است"} - - - - - } - label={ - - اقدام مشاهده شده - - } - /> - - - - {subItemsList?.name || "هیچ اقدامی انتخاب نشده است"} - - - - ); -}; -export default PreviousStatesInfoInObservedItem; +import { Box, Chip, Divider, Grid, Typography } from "@mui/material"; +import InsertDriveFileIcon from "@mui/icons-material/InsertDriveFile"; +import FileCopyIcon from "@mui/icons-material/FileCopy"; + +const PreviousStatesInfoInObservedItem = ({ itemsList, subItemsList }) => { + return ( + + + + } + label={ + + آیتم انتخاب ‌شده + + } + /> + + + + {itemsList.name || "هیچ آیتمی انتخاب نشده است"} + + + + + } + label={ + + اقدام مشاهده شده + + } + /> + + + + {subItemsList?.name || "هیچ اقدامی انتخاب نشده است"} + + + + ); +}; +export default PreviousStatesInfoInObservedItem; diff --git a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/SuperVisorInfo.jsx b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/SuperVisorInfo.jsx index d9ffef6..c186520 100644 --- a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/SuperVisorInfo.jsx +++ b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/SuperVisorInfo.jsx @@ -1,40 +1,40 @@ -"use client"; - -import { Box, Card, IconButton, Stack, Typography } from "@mui/material"; -import AccountCircleIcon from "@mui/icons-material/AccountCircle"; -import DeleteIcon from "@mui/icons-material/Delete"; -import React from "react"; - -const SuperVisorInfo = ({ superVisor, deleteSuperVisor }) => { - return ( - - - - - - {superVisor.name} - - کد راهدار: {superVisor.code} - - - - deleteSuperVisor(superVisor.id)}> - - - - - ); -}; - -export default SuperVisorInfo; +"use client"; + +import { Box, Card, IconButton, Stack, Typography } from "@mui/material"; +import AccountCircleIcon from "@mui/icons-material/AccountCircle"; +import DeleteIcon from "@mui/icons-material/Delete"; +import React from "react"; + +const SuperVisorInfo = ({ superVisor, deleteSuperVisor }) => { + return ( + + + + + + {superVisor.name} + + کد راهدار: {superVisor.code} + + + + deleteSuperVisor(superVisor.id)}> + + + + + ); +}; + +export default SuperVisorInfo; diff --git a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/SuperVisorsDetail.jsx b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/SuperVisorsDetail.jsx index 34adc2e..521d0d3 100644 --- a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/SuperVisorsDetail.jsx +++ b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/SuperVisorsDetail.jsx @@ -1,145 +1,145 @@ -"use client"; - -import SuperVisorInfo from "@/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/SuperVisorInfo"; -import RahdarCode from "@/core/components/RahdarCode"; -import StyledForm from "@/core/components/StyledForm"; -import { yupResolver } from "@hookform/resolvers/yup"; -import ExitToAppIcon from "@mui/icons-material/ExitToApp"; -import { Box, Button, Chip, DialogActions, DialogContent, Divider, Fade, Grid, Stack, Typography } from "@mui/material"; -import { useState } from "react"; -import { Controller, useForm } from "react-hook-form"; -import * as yup from "yup"; - -const schema = yup.object().shape({ - road_patrol_rahdaran_id: yup.object().required("راهدار الزامی است."), -}); - -const SuperVisorsDetail = ({ allData, setAllData, handlePrev, setTabState }) => { - const [SuperVisorList, setSuperVisorList] = useState(allData.road_patrol_rahdaran_id); - - const defaultValues = { - road_patrol_rahdaran_id: null, - }; - - const { - control, - handleSubmit, - reset, - setValue, - formState: { isSubmitting, isValid }, - } = useForm({ defaultValues, resolver: yupResolver(schema), mode: "all" }); - - const requestPatrolInfo = (data) => { - setSuperVisorList((prev) => [...prev, data.road_patrol_rahdaran_id]); - reset(); - }; - - const deleteSuperVisor = (id) => { - setSuperVisorList((prev) => prev.filter((superVisor) => superVisor.id !== id)); - }; - - const handleNext = (data) => { - setAllData({ road_patrol_rahdaran_id: data }); - setTabState((s) => s + 1); - }; - - return ( - <> - - - - - - - { - return ( - field.onChange(value)} - error={error} - multiple={false} - /> - ); - }} - name={"road_patrol_rahdaran_id"} - /> - - - - - - - - {SuperVisorList.length === 0 && ( - - - ابتدا اطلاعات بالا را تکمیل نمایید - - - )} - - - {SuperVisorList.length !== 0 && - SuperVisorList.map((superVisor) => ( - - - - ))} - - - - - - - - - - - ); -}; - -export default SuperVisorsDetail; +"use client"; + +import SuperVisorInfo from "@/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/SuperVisorInfo"; +import RahdarCode from "@/core/components/RahdarCode"; +import StyledForm from "@/core/components/StyledForm"; +import { yupResolver } from "@hookform/resolvers/yup"; +import ExitToAppIcon from "@mui/icons-material/ExitToApp"; +import { Box, Button, Chip, DialogActions, DialogContent, Divider, Fade, Grid, Stack, Typography } from "@mui/material"; +import { useState } from "react"; +import { Controller, useForm } from "react-hook-form"; +import * as yup from "yup"; + +const schema = yup.object().shape({ + road_patrol_rahdaran_id: yup.object().required("راهدار الزامی است."), +}); + +const SuperVisorsDetail = ({ allData, setAllData, handlePrev, setTabState }) => { + const [SuperVisorList, setSuperVisorList] = useState(allData.road_patrol_rahdaran_id); + + const defaultValues = { + road_patrol_rahdaran_id: null, + }; + + const { + control, + handleSubmit, + reset, + setValue, + formState: { isSubmitting, isValid }, + } = useForm({ defaultValues, resolver: yupResolver(schema), mode: "all" }); + + const requestPatrolInfo = (data) => { + setSuperVisorList((prev) => [...prev, data.road_patrol_rahdaran_id]); + reset(); + }; + + const deleteSuperVisor = (id) => { + setSuperVisorList((prev) => prev.filter((superVisor) => superVisor.id !== id)); + }; + + const handleNext = (data) => { + setAllData({ road_patrol_rahdaran_id: data }); + setTabState((s) => s + 1); + }; + + return ( + <> + + + + + + + { + return ( + field.onChange(value)} + error={error} + multiple={false} + /> + ); + }} + name={"road_patrol_rahdaran_id"} + /> + + + + + + + + {SuperVisorList.length === 0 && ( + + + ابتدا اطلاعات بالا را تکمیل نمایید + + + )} + + + {SuperVisorList.length !== 0 && + SuperVisorList.map((superVisor) => ( + + + + ))} + + + + + + + + + + + ); +}; + +export default SuperVisorsDetail; diff --git a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/index.jsx b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/index.jsx index c19d1e1..661d655 100644 --- a/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/index.jsx +++ b/src/components/dashboard/roadPatrols/operator/Forms/CreatePatrol/index.jsx @@ -1,27 +1,27 @@ -"use client"; - -import { Dialog, IconButton } from "@mui/material"; -import PatrolForms from "./PatrolForms"; -import CloseIcon from "@mui/icons-material/Close"; - -const CreatePatrol = ({ open, setOpen, mutate }) => { - return ( - - setOpen(false)} - sx={(theme) => ({ - position: "absolute", - right: 8, - top: 8, - zIndex: 50, - color: theme.palette.grey[500], - })} - > - - - {open && } - - ); -}; -export default CreatePatrol; +"use client"; + +import { Dialog, IconButton } from "@mui/material"; +import PatrolForms from "./PatrolForms"; +import CloseIcon from "@mui/icons-material/Close"; + +const CreatePatrol = ({ open, setOpen, mutate }) => { + return ( + + setOpen(false)} + sx={(theme) => ({ + position: "absolute", + right: 8, + top: 8, + zIndex: 50, + color: theme.palette.grey[500], + })} + > + + + {open && } + + ); +}; +export default CreatePatrol; diff --git a/src/components/dashboard/roadPatrols/operator/OperatorList.jsx b/src/components/dashboard/roadPatrols/operator/OperatorList.jsx index 2de63a8..71357d6 100644 --- a/src/components/dashboard/roadPatrols/operator/OperatorList.jsx +++ b/src/components/dashboard/roadPatrols/operator/OperatorList.jsx @@ -1,158 +1,158 @@ -"use client"; -import { useMemo } from "react"; -import { Box, Stack, Typography } from "@mui/material"; -import DataTableWithAuth from "@/core/components/DataTableWithAuth"; -import Toolbar from "./Toolbar"; -import { GET_ROAD_PATROL_OPERATOR_LIST } from "@/core/utils/routes"; -import moment from "jalali-moment"; -import RowActions from "./RowActions"; -import ReportForm from "./RowActions/ReportForm"; -import RahdaranDialog from "./RowActions/RahdaranForm"; -import MachinePerformanceForm from "./RowActions/MachinePerformanceForm"; - -const OperatorList = () => { - const columns = useMemo( - () => [ - { - accessorKey: "id", - header: "کد یکتا", - id: "id", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - header: "عملکرد خودرو", // Car ID - enableColumnFilter: true, - id: "cmmsMachines__machine_code", - datatype: "text", - filterMode: "contains", - columnFilterModeOptions: ["equals", "contains"], - enableSorting: false, - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue, row }) => { - return ( - - - - ); - }, - }, - { - accessorKey: "rahdaran", - header: "راهداران", - id: "rahdaran__code", - enableColumnFilter: true, - enableSorting: false, - datatype: "text", - filterMode: "contains", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue, row }) => { - return ( - - - - ); - }, - }, - { - accessorFn: (row) => moment(row.start_time).locale("fa").format("HH:mm | yyyy/MM/DD"), - header: "تاریخ شروع", - id: "start_time", - enableColumnFilter: true, - datatype: "date", - filterMode: "between", - grow: false, - size: 100, - }, - { - accessorFn: (row) => moment(row.end_time).locale("fa").format("HH:mm | yyyy/MM/DD"), - header: "تاریخ پایان", - id: "end_time", - enableColumnFilter: true, - datatype: "date", - filterMode: "between", - grow: false, - size: 100, - }, - { - accessorFn: (row) => moment(row.created_at).locale("fa").format("HH:mm | yyyy/MM/DD"), - header: "تاریخ ثبت", - id: "created_at", - enableColumnFilter: true, - datatype: "date", - filterMode: "between", - grow: false, - size: 100, - }, - { - header: "گزارش مامور", - enableColumnFilter: false, - datatype: "text", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue, row }) => { - return ( - - - - ); - }, - }, - ], - [] - ); - - return ( - <> - - - - - ); -}; -export default OperatorList; +"use client"; +import { useMemo } from "react"; +import { Box, Stack, Typography } from "@mui/material"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import Toolbar from "./Toolbar"; +import { GET_ROAD_PATROL_OPERATOR_LIST } from "@/core/utils/routes"; +import moment from "jalali-moment"; +import RowActions from "./RowActions"; +import ReportForm from "./RowActions/ReportForm"; +import RahdaranDialog from "./RowActions/RahdaranForm"; +import MachinePerformanceForm from "./RowActions/MachinePerformanceForm"; + +const OperatorList = () => { + const columns = useMemo( + () => [ + { + accessorKey: "id", + header: "کد یکتا", + id: "id", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + header: "عملکرد خودرو", // Car ID + enableColumnFilter: true, + id: "cmmsMachines__machine_code", + datatype: "text", + filterMode: "contains", + columnFilterModeOptions: ["equals", "contains"], + enableSorting: false, + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue, row }) => { + return ( + + + + ); + }, + }, + { + accessorKey: "rahdaran", + header: "راهداران", + id: "rahdaran__code", + enableColumnFilter: true, + enableSorting: false, + datatype: "text", + filterMode: "contains", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue, row }) => { + return ( + + + + ); + }, + }, + { + accessorFn: (row) => moment(row.start_time).locale("fa").format("HH:mm | yyyy/MM/DD"), + header: "تاریخ شروع", + id: "start_time", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + { + accessorFn: (row) => moment(row.end_time).locale("fa").format("HH:mm | yyyy/MM/DD"), + header: "تاریخ پایان", + id: "end_time", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + { + accessorFn: (row) => moment(row.created_at).locale("fa").format("HH:mm | yyyy/MM/DD"), + header: "تاریخ ثبت", + id: "created_at", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + { + header: "گزارش مامور", + enableColumnFilter: false, + datatype: "text", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue, row }) => { + return ( + + + + ); + }, + }, + ], + [] + ); + + return ( + <> + + + + + ); +}; +export default OperatorList; diff --git a/src/components/dashboard/roadPatrols/operator/RowActions/MachinePerformanceForm/MachinePerformanceContent.jsx b/src/components/dashboard/roadPatrols/operator/RowActions/MachinePerformanceForm/MachinePerformanceContent.jsx index ead48ff..d37d1d3 100644 --- a/src/components/dashboard/roadPatrols/operator/RowActions/MachinePerformanceForm/MachinePerformanceContent.jsx +++ b/src/components/dashboard/roadPatrols/operator/RowActions/MachinePerformanceForm/MachinePerformanceContent.jsx @@ -1,155 +1,155 @@ -import { Box, Chip, DialogContent, Divider, Grid, Stack, Typography } from "@mui/material"; -import React, { useEffect, useState, useRef } from "react"; -import { Marker, useMap } from "react-leaflet"; -import AzmayeshActiveIcon from "@/assets/images/examine_marker_active.png"; -import MapLayer from "@/core/components/MapLayer"; -import PinDropIcon from "@mui/icons-material/PinDrop"; -import AccessAlarmsIcon from "@mui/icons-material/AccessAlarms"; -import { formatSecondsToHHMMSS } from "@/core/utils/formatSecondsToHHMMSS"; -import StopsInfo from "./StopsInfo"; -const defaultIconSize = [35, 35]; -const MachinePerformanceContent = ({ machinesLists }) => { - const [selectedPoint, setSelectedPoint] = useState(null); - const mapRef = useRef(null); - const isFirstRender = useRef(true); - const createCustomIcon = (size, iconUrl) => { - return L.icon({ - iconUrl: iconUrl, - iconSize: size, - iconAnchor: [size[0] / 2, size[1]], - popupAnchor: [0, -size[1]], - }); - }; - const MapWithBounds = () => { - const map = useMap(); - useEffect(() => { - if (machinesLists.stopPoints.length > 0) { - const bounds = machinesLists.stopPoints.map((point) => [point.latitude, point.longitude]); - if (isFirstRender.current) { - map.fitBounds(bounds, { - padding: [50, 50], - }); - isFirstRender.current = false; - } else if (mapRef.current) { - mapRef.current.setView(map.getCenter(), map.getZoom()); - } - } - }, [machinesLists.stopPoints, map]); - return null; - }; - const handleMarkerClick = (point) => { - setSelectedPoint(point); - }; - - return ( - <> - - - - - - - - - - - {machinesLists.stopPoints.map((point, index) => ( - handleMarkerClick(point), - }} - > - ))} - - - - - - - - } - label={ - - طول جغرافیایی - - } - /> - - - - {selectedPoint ? selectedPoint.longitude : "نقطه مورد نظر را انتخاب کنید"} - - - - - } - label={ - - عرض جغرافیایی - - } - /> - - - - {selectedPoint ? selectedPoint.latitude : "نقطه مورد نظر را انتخاب کنید"} - - - - - } - label={ - - مدت زمان توقف - - } - /> - - - - {selectedPoint - ? `${formatSecondsToHHMMSS(selectedPoint.duration)}` - : "نقطه مورد نظر را انتخاب کنید"} - - - - - - - - ); -}; -export default MachinePerformanceContent; +import { Box, Chip, DialogContent, Divider, Grid, Stack, Typography } from "@mui/material"; +import React, { useEffect, useState, useRef } from "react"; +import { Marker, useMap } from "react-leaflet"; +import AzmayeshActiveIcon from "@/assets/images/examine_marker_active.png"; +import MapLayer from "@/core/components/MapLayer"; +import PinDropIcon from "@mui/icons-material/PinDrop"; +import AccessAlarmsIcon from "@mui/icons-material/AccessAlarms"; +import { formatSecondsToHHMMSS } from "@/core/utils/formatSecondsToHHMMSS"; +import StopsInfo from "./StopsInfo"; +const defaultIconSize = [35, 35]; +const MachinePerformanceContent = ({ machinesLists }) => { + const [selectedPoint, setSelectedPoint] = useState(null); + const mapRef = useRef(null); + const isFirstRender = useRef(true); + const createCustomIcon = (size, iconUrl) => { + return L.icon({ + iconUrl: iconUrl, + iconSize: size, + iconAnchor: [size[0] / 2, size[1]], + popupAnchor: [0, -size[1]], + }); + }; + const MapWithBounds = () => { + const map = useMap(); + useEffect(() => { + if (machinesLists.stopPoints.length > 0) { + const bounds = machinesLists.stopPoints.map((point) => [point.latitude, point.longitude]); + if (isFirstRender.current) { + map.fitBounds(bounds, { + padding: [50, 50], + }); + isFirstRender.current = false; + } else if (mapRef.current) { + mapRef.current.setView(map.getCenter(), map.getZoom()); + } + } + }, [machinesLists.stopPoints, map]); + return null; + }; + const handleMarkerClick = (point) => { + setSelectedPoint(point); + }; + + return ( + <> + + + + + + + + + + + {machinesLists.stopPoints.map((point, index) => ( + handleMarkerClick(point), + }} + > + ))} + + + + + + + + } + label={ + + طول جغرافیایی + + } + /> + + + + {selectedPoint ? selectedPoint.longitude : "نقطه مورد نظر را انتخاب کنید"} + + + + + } + label={ + + عرض جغرافیایی + + } + /> + + + + {selectedPoint ? selectedPoint.latitude : "نقطه مورد نظر را انتخاب کنید"} + + + + + } + label={ + + مدت زمان توقف + + } + /> + + + + {selectedPoint + ? `${formatSecondsToHHMMSS(selectedPoint.duration)}` + : "نقطه مورد نظر را انتخاب کنید"} + + + + + + + + ); +}; +export default MachinePerformanceContent; diff --git a/src/components/dashboard/roadPatrols/operator/RowActions/MachinePerformanceForm/MachinesCodeFetch.jsx b/src/components/dashboard/roadPatrols/operator/RowActions/MachinePerformanceForm/MachinesCodeFetch.jsx index 0da7b28..3824bd0 100644 --- a/src/components/dashboard/roadPatrols/operator/RowActions/MachinePerformanceForm/MachinesCodeFetch.jsx +++ b/src/components/dashboard/roadPatrols/operator/RowActions/MachinePerformanceForm/MachinesCodeFetch.jsx @@ -1,50 +1,50 @@ -import DialogLoading from "@/core/components/DialogLoading"; -import { GET_CMMS_MACHINE_ROAD_PATROL } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { DialogContent, Typography } from "@mui/material"; -import { useEffect, useState } from "react"; -import MachinePerformanceContent from "./MachinePerformanceContent"; - -const MachinePerformanceFetch = ({ row }) => { - const [loading, setLoading] = useState(true); - const [data, setData] = useState(null); - const request = useRequest(); - - useEffect(() => { - const fetchData = async () => { - try { - setLoading(true); - const response = await request(`${GET_CMMS_MACHINE_ROAD_PATROL}/${row.getValue("id")}`); - setData(response.data.data); - } catch (error) { - } finally { - setLoading(false); - } - }; - - fetchData(); - }, []); - - return ( - <> - - {loading ? ( - - ) : data && row.original?.stop_points?.length > 0 ? ( - - ) : ( - عملکرد خودرویی در سامانه یافت نشد - )} - - - ); -}; -export default MachinePerformanceFetch; +import DialogLoading from "@/core/components/DialogLoading"; +import { GET_CMMS_MACHINE_ROAD_PATROL } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { DialogContent, Typography } from "@mui/material"; +import { useEffect, useState } from "react"; +import MachinePerformanceContent from "./MachinePerformanceContent"; + +const MachinePerformanceFetch = ({ row }) => { + const [loading, setLoading] = useState(true); + const [data, setData] = useState(null); + const request = useRequest(); + + useEffect(() => { + const fetchData = async () => { + try { + setLoading(true); + const response = await request(`${GET_CMMS_MACHINE_ROAD_PATROL}/${row.getValue("id")}`); + setData(response.data.data); + } catch (error) { + } finally { + setLoading(false); + } + }; + + fetchData(); + }, []); + + return ( + <> + + {loading ? ( + + ) : data && row.original?.stop_points?.length > 0 ? ( + + ) : ( + عملکرد خودرویی در سامانه یافت نشد + )} + + + ); +}; +export default MachinePerformanceFetch; diff --git a/src/components/dashboard/roadPatrols/operator/RowActions/MachinePerformanceForm/StopsInfo.jsx b/src/components/dashboard/roadPatrols/operator/RowActions/MachinePerformanceForm/StopsInfo.jsx index d8e44cb..67ae090 100644 --- a/src/components/dashboard/roadPatrols/operator/RowActions/MachinePerformanceForm/StopsInfo.jsx +++ b/src/components/dashboard/roadPatrols/operator/RowActions/MachinePerformanceForm/StopsInfo.jsx @@ -1,120 +1,120 @@ -import { Box, Chip, Divider, Grid, Typography } from "@mui/material"; -import AccessAlarmsIcon from "@mui/icons-material/AccessAlarms"; - -import LocalGasStationIcon from "@mui/icons-material/LocalGasStation"; -import QrCode2Icon from "@mui/icons-material/QrCode2"; -import AddRoadIcon from "@mui/icons-material/AddRoad"; -import DirectionsCarFilledIcon from "@mui/icons-material/DirectionsCarFilled"; -import BadgeIcon from "@mui/icons-material/Badge"; -import { formatSecondsToHHMMSS } from "@/core/utils/formatSecondsToHHMMSS"; -import ShowPlak from "@/core/components/ShowPlak"; - -const StopsInfo = ({ staticData }) => { - return ( - - - - } - label={ - - کد خودرو - - } - /> - - - - {staticData.cmmsMachineCode.machine_code || ""} - - - - - } - label={ - - نام خودرو - - } - /> - - - - {staticData.cmmsMachineCode.car_name || ""} - - - - - } - label={ - - پلاک خودرو - - } - /> - - - - {staticData.cmmsMachineCode.plak_number && - ShowPlak({ plak_number: staticData.cmmsMachineCode.plak_number })} - - - - - } - label={ - - میزان سوخت مصرفی - - } - /> - - - - {Math.round(staticData?.fuelConsumption * 10) / 10} لیتر - - - - - } - label={ - - مسافت پیموده شده - - } - /> - - - - {(staticData?.mileage / 1000).toFixed(1)} کیلومتر - - - - - } - label={ - - مدت زمان روشن بودن خودرو - - } - /> - - - - {formatSecondsToHHMMSS(staticData?.accOnDuration)} - - - - ); -}; -export default StopsInfo; +import { Box, Chip, Divider, Grid, Typography } from "@mui/material"; +import AccessAlarmsIcon from "@mui/icons-material/AccessAlarms"; + +import LocalGasStationIcon from "@mui/icons-material/LocalGasStation"; +import QrCode2Icon from "@mui/icons-material/QrCode2"; +import AddRoadIcon from "@mui/icons-material/AddRoad"; +import DirectionsCarFilledIcon from "@mui/icons-material/DirectionsCarFilled"; +import BadgeIcon from "@mui/icons-material/Badge"; +import { formatSecondsToHHMMSS } from "@/core/utils/formatSecondsToHHMMSS"; +import ShowPlak from "@/core/components/ShowPlak"; + +const StopsInfo = ({ staticData }) => { + return ( + + + + } + label={ + + کد خودرو + + } + /> + + + + {staticData.cmmsMachineCode.machine_code || ""} + + + + + } + label={ + + نام خودرو + + } + /> + + + + {staticData.cmmsMachineCode.car_name || ""} + + + + + } + label={ + + پلاک خودرو + + } + /> + + + + {staticData.cmmsMachineCode.plak_number && + ShowPlak({ plak_number: staticData.cmmsMachineCode.plak_number })} + + + + + } + label={ + + میزان سوخت مصرفی + + } + /> + + + + {Math.round(staticData?.fuelConsumption * 10) / 10} لیتر + + + + + } + label={ + + مسافت پیموده شده + + } + /> + + + + {(staticData?.mileage / 1000).toFixed(1)} کیلومتر + + + + + } + label={ + + مدت زمان روشن بودن خودرو + + } + /> + + + + {formatSecondsToHHMMSS(staticData?.accOnDuration)} + + + + ); +}; +export default StopsInfo; diff --git a/src/components/dashboard/roadPatrols/operator/RowActions/MachinePerformanceForm/index.jsx b/src/components/dashboard/roadPatrols/operator/RowActions/MachinePerformanceForm/index.jsx index 168936e..e9a161b 100644 --- a/src/components/dashboard/roadPatrols/operator/RowActions/MachinePerformanceForm/index.jsx +++ b/src/components/dashboard/roadPatrols/operator/RowActions/MachinePerformanceForm/index.jsx @@ -1,43 +1,43 @@ -import DirectionsCarIcon from "@mui/icons-material/DirectionsCar"; -import { Button, Dialog, DialogActions, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import MachinePerformanceFetch from "./MachinesCodeFetch"; - -const MachinePerformanceForm = ({ row }) => { - const [openMachinesCodeDialog, setOpenMachinesCodeDialog] = useState(false); - return ( - <> - - setOpenMachinesCodeDialog(true)}> - - - - setOpenMachinesCodeDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - عملکرد خودرو - {openMachinesCodeDialog && } - - - - - - ); -}; -export default MachinePerformanceForm; +import DirectionsCarIcon from "@mui/icons-material/DirectionsCar"; +import { Button, Dialog, DialogActions, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import MachinePerformanceFetch from "./MachinesCodeFetch"; + +const MachinePerformanceForm = ({ row }) => { + const [openMachinesCodeDialog, setOpenMachinesCodeDialog] = useState(false); + return ( + <> + + setOpenMachinesCodeDialog(true)}> + + + + setOpenMachinesCodeDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + عملکرد خودرو + {openMachinesCodeDialog && } + + + + + + ); +}; +export default MachinePerformanceForm; diff --git a/src/components/dashboard/roadPatrols/operator/RowActions/MachinesCodeForm/MachinesCodeContent.jsx b/src/components/dashboard/roadPatrols/operator/RowActions/MachinesCodeForm/MachinesCodeContent.jsx index 1eef774..c98f48d 100644 --- a/src/components/dashboard/roadPatrols/operator/RowActions/MachinesCodeForm/MachinesCodeContent.jsx +++ b/src/components/dashboard/roadPatrols/operator/RowActions/MachinesCodeForm/MachinesCodeContent.jsx @@ -1,55 +1,55 @@ -import { DialogContent, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow } from "@mui/material"; -import ShowPlak from "@/core/components/ShowPlak"; - -const MachinesCodeContent = ({ machinesLists }) => { - return ( - <> - - - - - - - کد ماشین - نام خودرو - پلاک - - - - {machinesLists.map((machine) => { - return ( - - {machine.machine_code} - {machine.car_name} - - {machine.plak_number ? ( - - ) : null} - - - ); - })} - -
    -
    -
    -
    - - ); -}; -export default MachinesCodeContent; +import { DialogContent, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow } from "@mui/material"; +import ShowPlak from "@/core/components/ShowPlak"; + +const MachinesCodeContent = ({ machinesLists }) => { + return ( + <> + + + + + + + کد ماشین + نام خودرو + پلاک + + + + {machinesLists.map((machine) => { + return ( + + {machine.machine_code} + {machine.car_name} + + {machine.plak_number ? ( + + ) : null} + + + ); + })} + +
    +
    +
    +
    + + ); +}; +export default MachinesCodeContent; diff --git a/src/components/dashboard/roadPatrols/operator/RowActions/MachinesCodeForm/index.jsx b/src/components/dashboard/roadPatrols/operator/RowActions/MachinesCodeForm/index.jsx index d8e8754..b60e021 100644 --- a/src/components/dashboard/roadPatrols/operator/RowActions/MachinesCodeForm/index.jsx +++ b/src/components/dashboard/roadPatrols/operator/RowActions/MachinesCodeForm/index.jsx @@ -1,43 +1,43 @@ -import { Button, Dialog, DialogActions, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import DirectionsCarIcon from "@mui/icons-material/DirectionsCar"; -import { useState } from "react"; -import MachinesCodeContent from "./MachinesCodeContent"; - -const MachinesCodeDialog = ({ machinesLists }) => { - const [openMachinesCodeDialog, setOpenMachinesCodeDialog] = useState(false); - return ( - <> - - setOpenMachinesCodeDialog(true)}> - - - - setOpenMachinesCodeDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - کد خودرو - - - - - - - ); -}; -export default MachinesCodeDialog; +import { Button, Dialog, DialogActions, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import DirectionsCarIcon from "@mui/icons-material/DirectionsCar"; +import { useState } from "react"; +import MachinesCodeContent from "./MachinesCodeContent"; + +const MachinesCodeDialog = ({ machinesLists }) => { + const [openMachinesCodeDialog, setOpenMachinesCodeDialog] = useState(false); + return ( + <> + + setOpenMachinesCodeDialog(true)}> + + + + setOpenMachinesCodeDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + کد خودرو + + + + + + + ); +}; +export default MachinesCodeDialog; diff --git a/src/components/dashboard/roadPatrols/operator/RowActions/RahdaranForm/RahdaranContent.jsx b/src/components/dashboard/roadPatrols/operator/RowActions/RahdaranForm/RahdaranContent.jsx index 1a31ce8..8e14863 100644 --- a/src/components/dashboard/roadPatrols/operator/RowActions/RahdaranForm/RahdaranContent.jsx +++ b/src/components/dashboard/roadPatrols/operator/RowActions/RahdaranForm/RahdaranContent.jsx @@ -1,72 +1,72 @@ -import DialogLoading from "@/core/components/DialogLoading"; -import { GET_RAHDARAN_ROAD_POTROL } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { - DialogContent, - Table, - TableBody, - TableCell, - TableContainer, - TableHead, - TableRow, - Typography, -} from "@mui/material"; -import { useEffect, useState } from "react"; - -const RahdaranContent = ({ rowId }) => { - const [loading, setLoading] = useState(true); - const [data, setData] = useState(null); - const request = useRequest(); - - useEffect(() => { - const fetchData = async () => { - try { - setLoading(true); - const response = await request(`${GET_RAHDARAN_ROAD_POTROL}/${rowId}`); - setData(response.data.data); - } catch (error) { - } finally { - setLoading(false); - } - }; - - fetchData(); - }, [rowId]); - - return ( - <> - - {loading ? ( - - ) : data ? ( - - - - - کد راهدار - نام - - - - {data.map((rahdar) => { - return ( - - {rahdar.code} - {rahdar.name} - - ); - })} - -
    -
    - ) : ( - اطلاعات راهداران در سامانه یافت نشد - )} -
    - - ); -}; -export default RahdaranContent; +import DialogLoading from "@/core/components/DialogLoading"; +import { GET_RAHDARAN_ROAD_POTROL } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { + DialogContent, + Table, + TableBody, + TableCell, + TableContainer, + TableHead, + TableRow, + Typography, +} from "@mui/material"; +import { useEffect, useState } from "react"; + +const RahdaranContent = ({ rowId }) => { + const [loading, setLoading] = useState(true); + const [data, setData] = useState(null); + const request = useRequest(); + + useEffect(() => { + const fetchData = async () => { + try { + setLoading(true); + const response = await request(`${GET_RAHDARAN_ROAD_POTROL}/${rowId}`); + setData(response.data.data); + } catch (error) { + } finally { + setLoading(false); + } + }; + + fetchData(); + }, [rowId]); + + return ( + <> + + {loading ? ( + + ) : data ? ( + + + + + کد راهدار + نام + + + + {data.map((rahdar) => { + return ( + + {rahdar.code} + {rahdar.name} + + ); + })} + +
    +
    + ) : ( + اطلاعات راهداران در سامانه یافت نشد + )} +
    + + ); +}; +export default RahdaranContent; diff --git a/src/components/dashboard/roadPatrols/operator/RowActions/RahdaranForm/index.jsx b/src/components/dashboard/roadPatrols/operator/RowActions/RahdaranForm/index.jsx index e3a2efc..a051c23 100644 --- a/src/components/dashboard/roadPatrols/operator/RowActions/RahdaranForm/index.jsx +++ b/src/components/dashboard/roadPatrols/operator/RowActions/RahdaranForm/index.jsx @@ -1,38 +1,38 @@ -import { Button, Dialog, DialogActions, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import GroupsIcon from "@mui/icons-material/Groups"; -import { useState } from "react"; -import RahdaranContent from "./RahdaranContent"; - -const RahdaranDialog = ({ rowId }) => { - const [openRahdaranDialog, setOpenRahdaranDialog] = useState(false); - return ( - <> - - setOpenRahdaranDialog(true)}> - - - - setOpenRahdaranDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - لیست راهداران - {openRahdaranDialog && } - - - - - - ); -}; -export default RahdaranDialog; +import { Button, Dialog, DialogActions, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import GroupsIcon from "@mui/icons-material/Groups"; +import { useState } from "react"; +import RahdaranContent from "./RahdaranContent"; + +const RahdaranDialog = ({ rowId }) => { + const [openRahdaranDialog, setOpenRahdaranDialog] = useState(false); + return ( + <> + + setOpenRahdaranDialog(true)}> + + + + setOpenRahdaranDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + لیست راهداران + {openRahdaranDialog && } + + + + + + ); +}; +export default RahdaranDialog; diff --git a/src/components/dashboard/roadPatrols/operator/RowActions/ReportForm/index.jsx b/src/components/dashboard/roadPatrols/operator/RowActions/ReportForm/index.jsx index 4c834ca..8f5aabc 100644 --- a/src/components/dashboard/roadPatrols/operator/RowActions/ReportForm/index.jsx +++ b/src/components/dashboard/roadPatrols/operator/RowActions/ReportForm/index.jsx @@ -1,22 +1,22 @@ -import { GET_ROAD_PATROL_OPERATOR_REPORT } from "@/core/utils/routes"; -import PrintIcon from "@mui/icons-material/Print"; -import { IconButton, Tooltip } from "@mui/material"; - -const ReportForm = ({ rowId }) => { - return ( - - - - - - ); -}; - -export default ReportForm; +import { GET_ROAD_PATROL_OPERATOR_REPORT } from "@/core/utils/routes"; +import PrintIcon from "@mui/icons-material/Print"; +import { IconButton, Tooltip } from "@mui/material"; + +const ReportForm = ({ rowId }) => { + return ( + + + + + + ); +}; + +export default ReportForm; diff --git a/src/components/dashboard/roadPatrols/operator/RowActions/index.jsx b/src/components/dashboard/roadPatrols/operator/RowActions/index.jsx index c9e69ef..6a1c0d6 100644 --- a/src/components/dashboard/roadPatrols/operator/RowActions/index.jsx +++ b/src/components/dashboard/roadPatrols/operator/RowActions/index.jsx @@ -1,6 +1,6 @@ -import { Box } from "@mui/material"; - -const RowActions = ({ row }) => { - return ; -}; -export default RowActions; +import { Box } from "@mui/material"; + +const RowActions = ({ row }) => { + return ; +}; +export default RowActions; diff --git a/src/components/dashboard/roadPatrols/operator/Toolbar.jsx b/src/components/dashboard/roadPatrols/operator/Toolbar.jsx index f4e6d6f..a799c26 100644 --- a/src/components/dashboard/roadPatrols/operator/Toolbar.jsx +++ b/src/components/dashboard/roadPatrols/operator/Toolbar.jsx @@ -1,13 +1,13 @@ -import { Stack } from "@mui/material"; -import OperatorCreate from "./Actions/Create"; -import PrintExcel from "./ExcelPrint"; - -const Toolbar = ({ table, filterData, mutate }) => { - return ( - - - - - ); -}; -export default Toolbar; +import { Stack } from "@mui/material"; +import OperatorCreate from "./Actions/Create"; +import PrintExcel from "./ExcelPrint"; + +const Toolbar = ({ table, filterData, mutate }) => { + return ( + + + + + ); +}; +export default Toolbar; diff --git a/src/components/dashboard/roadPatrols/operator/index.jsx b/src/components/dashboard/roadPatrols/operator/index.jsx index f30536c..e26b46e 100644 --- a/src/components/dashboard/roadPatrols/operator/index.jsx +++ b/src/components/dashboard/roadPatrols/operator/index.jsx @@ -1,14 +1,14 @@ -"use client"; -import PageTitle from "@/core/components/PageTitle"; -import { Stack } from "@mui/material"; -import OperatorList from "./OperatorList"; - -const OperatorPage = () => { - return ( - - - - - ); -}; -export default OperatorPage; +"use client"; +import PageTitle from "@/core/components/PageTitle"; +import { Stack } from "@mui/material"; +import OperatorList from "./OperatorList"; + +const OperatorPage = () => { + return ( + + + + + ); +}; +export default OperatorPage; diff --git a/src/components/dashboard/roadPatrols/reports/ExcelPrint/index.jsx b/src/components/dashboard/roadPatrols/reports/ExcelPrint/index.jsx index 192d4fb..2e3f683 100644 --- a/src/components/dashboard/roadPatrols/reports/ExcelPrint/index.jsx +++ b/src/components/dashboard/roadPatrols/reports/ExcelPrint/index.jsx @@ -1,72 +1,72 @@ -"use client"; -import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; -import { useMemo, useState } from "react"; -import moment from "jalali-moment"; -import FileSaver from "file-saver"; -import DescriptionIcon from "@mui/icons-material/Description"; -import useRequest from "@/lib/hooks/useRequest"; -import { useTheme } from "@emotion/react"; -import { EXPORT_COUNTRY_ROAD_PATROL_REPORTS, EXPORT_PROVINCE_ROAD_PATROL_REPORTS } from "@/core/utils/routes"; - -const PrintExcel = ({ table, filterData }) => { - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const [loading, setLoading] = useState(false); - const requestServer = useRequest({ notificationSuccess: true }); - const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { - if (filter.value) { - acc.push({ id: filter.id, value: filter.value }); - } - return acc; - }, []); - - const filterParams = useMemo(() => { - const params = new URLSearchParams(); - activeFilters.length > 0 && - activeFilters.map((filter, index) => { - params.set(`${filter.id}`, filter.value); - }); - return params; - }, [activeFilters]); - - const clickHandler = () => { - setLoading(true); - const CountryOrProvince = activeFilters.find((item) => item.id === "province_id"); - const requestUrl = - CountryOrProvince.value === "-1" ? EXPORT_COUNTRY_ROAD_PATROL_REPORTS : EXPORT_PROVINCE_ROAD_PATROL_REPORTS; - requestServer(`${requestUrl}?${filterParams}`, "get", { - requestOptions: { responseType: "blob" }, - }) - .then((response) => { - const filename = `خروجی کارتابل گزارشات گشت راهداری تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; - FileSaver.saveAs(response.data, filename); - }) - .catch(() => {}) - .finally(() => { - setLoading(false); - }); - }; - - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - - ); -}; -export default PrintExcel; +"use client"; +import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; +import { useMemo, useState } from "react"; +import moment from "jalali-moment"; +import FileSaver from "file-saver"; +import DescriptionIcon from "@mui/icons-material/Description"; +import useRequest from "@/lib/hooks/useRequest"; +import { useTheme } from "@emotion/react"; +import { EXPORT_COUNTRY_ROAD_PATROL_REPORTS, EXPORT_PROVINCE_ROAD_PATROL_REPORTS } from "@/core/utils/routes"; + +const PrintExcel = ({ table, filterData }) => { + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const [loading, setLoading] = useState(false); + const requestServer = useRequest({ notificationSuccess: true }); + const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { + if (filter.value) { + acc.push({ id: filter.id, value: filter.value }); + } + return acc; + }, []); + + const filterParams = useMemo(() => { + const params = new URLSearchParams(); + activeFilters.length > 0 && + activeFilters.map((filter, index) => { + params.set(`${filter.id}`, filter.value); + }); + return params; + }, [activeFilters]); + + const clickHandler = () => { + setLoading(true); + const CountryOrProvince = activeFilters.find((item) => item.id === "province_id"); + const requestUrl = + CountryOrProvince.value === "-1" ? EXPORT_COUNTRY_ROAD_PATROL_REPORTS : EXPORT_PROVINCE_ROAD_PATROL_REPORTS; + requestServer(`${requestUrl}?${filterParams}`, "get", { + requestOptions: { responseType: "blob" }, + }) + .then((response) => { + const filename = `خروجی کارتابل گزارشات گشت راهداری تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; + FileSaver.saveAs(response.data, filename); + }) + .catch(() => {}) + .finally(() => { + setLoading(false); + }); + }; + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + + ); +}; +export default PrintExcel; diff --git a/src/components/dashboard/roadPatrols/reports/ReportLists.jsx b/src/components/dashboard/roadPatrols/reports/ReportLists.jsx index f683177..5a67f5a 100644 --- a/src/components/dashboard/roadPatrols/reports/ReportLists.jsx +++ b/src/components/dashboard/roadPatrols/reports/ReportLists.jsx @@ -1,210 +1,210 @@ -"use client"; -import DataTableWithAuth from "@/core/components/DataTableWithAuth"; -import { Box } from "@mui/material"; -import { useMemo } from "react"; -import Toolbar from "./Toolbar"; - -const ReportLists = ({ data, specialFilter }) => { - const columns = useMemo(() => { - return [ - { - accessorKey: "edare_name", - header: "اداره کل", - id: "edare_name", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - }, - - { - accessorKey: "tedade", - header: "تعداد کل", - id: "tedade", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - { - header: "اقدامات لازم جهت رسیدگی آتی", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - columns: [ - { - accessorKey: "tedad_mavarede_moshede_shode_adi", - header: "عادی", - id: "tedad_mavarede_moshede_shode_adi", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - { - accessorKey: "tedad_mavarede_moshede_shode_fori", - header: "فوری", - id: "tedad_mavarede_moshede_shode_fori", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - { - accessorKey: "tedad_mavarede_moshede_shode_ani", - header: "آنی", - id: "tedad_mavarede_moshede_shode_ani", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - ], - }, - { - accessorKey: "tedad_mavarede_peygiri_shode", - header: "اقدامات رسیدگی شده", - id: "tedad_mavarede_peygiri_shode", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - { - accessorKey: "masafat_tey_shode", - header: "مجموع مسافت پیمایش شده", - id: "masafat_tey_shode", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - { - accessorKey: "tedad_faliyat_sabt_shode", - header: "تعداد فعالیت صورت گرفته حین گشت", - id: "tedad_faliyat_sabt_shode", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - ]; - }, []); - - return ( - - - - ); -}; - -export default ReportLists; +"use client"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import { Box } from "@mui/material"; +import { useMemo } from "react"; +import Toolbar from "./Toolbar"; + +const ReportLists = ({ data, specialFilter }) => { + const columns = useMemo(() => { + return [ + { + accessorKey: "edare_name", + header: "اداره کل", + id: "edare_name", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + }, + + { + accessorKey: "tedade", + header: "تعداد کل", + id: "tedade", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + { + header: "اقدامات لازم جهت رسیدگی آتی", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + columns: [ + { + accessorKey: "tedad_mavarede_moshede_shode_adi", + header: "عادی", + id: "tedad_mavarede_moshede_shode_adi", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + { + accessorKey: "tedad_mavarede_moshede_shode_fori", + header: "فوری", + id: "tedad_mavarede_moshede_shode_fori", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + { + accessorKey: "tedad_mavarede_moshede_shode_ani", + header: "آنی", + id: "tedad_mavarede_moshede_shode_ani", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + ], + }, + { + accessorKey: "tedad_mavarede_peygiri_shode", + header: "اقدامات رسیدگی شده", + id: "tedad_mavarede_peygiri_shode", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + { + accessorKey: "masafat_tey_shode", + header: "مجموع مسافت پیمایش شده", + id: "masafat_tey_shode", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + { + accessorKey: "tedad_faliyat_sabt_shode", + header: "تعداد فعالیت صورت گرفته حین گشت", + id: "tedad_faliyat_sabt_shode", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + ]; + }, []); + + return ( + + + + ); +}; + +export default ReportLists; diff --git a/src/components/dashboard/roadPatrols/reports/Search/FromDateController.jsx b/src/components/dashboard/roadPatrols/reports/Search/FromDateController.jsx index 73b095f..45002e1 100644 --- a/src/components/dashboard/roadPatrols/reports/Search/FromDateController.jsx +++ b/src/components/dashboard/roadPatrols/reports/Search/FromDateController.jsx @@ -1,28 +1,28 @@ -import { Controller } from "react-hook-form"; -import MuiDatePicker from "@/core/components/MuiDatePicker"; -import React from "react"; -import moment from "jalali-moment"; - -const FromDateController = ({ control }) => { - return ( - ( - { - const formattedDate = moment(new Date(newValue)).locale("en").format("YYYY-MM-DD"); - onChange(formattedDate); // Update the field value in react-hook-form - }} - helperText={error ? error.message : null} - /> - )} - /> - ); -}; -export default FromDateController; +import { Controller } from "react-hook-form"; +import MuiDatePicker from "@/core/components/MuiDatePicker"; +import React from "react"; +import moment from "jalali-moment"; + +const FromDateController = ({ control }) => { + return ( + ( + { + const formattedDate = moment(new Date(newValue)).locale("en").format("YYYY-MM-DD"); + onChange(formattedDate); // Update the field value in react-hook-form + }} + helperText={error ? error.message : null} + /> + )} + /> + ); +}; +export default FromDateController; diff --git a/src/components/dashboard/roadPatrols/reports/Search/SearchReportField.jsx b/src/components/dashboard/roadPatrols/reports/Search/SearchReportField.jsx index ab8442c..5c6aa23 100644 --- a/src/components/dashboard/roadPatrols/reports/Search/SearchReportField.jsx +++ b/src/components/dashboard/roadPatrols/reports/Search/SearchReportField.jsx @@ -1,45 +1,45 @@ -import { Button, Grid, LinearProgress, Typography } from "@mui/material"; -import SearchIcon from "@mui/icons-material/Search"; -import React from "react"; -import FromDateController from "./FromDateController"; -import ToDateController from "./ToDateController"; -import SelectProvince from "./SelectProvince"; -import { Controller } from "react-hook-form"; - -const SearchReportField = ({ control, hasProvincesPermission }) => { - return ( - - - - - - - - {hasProvincesPermission && ( - - - - )} - - ( - - )} - /> - - - ); -}; - -export default SearchReportField; +import { Button, Grid, LinearProgress, Typography } from "@mui/material"; +import SearchIcon from "@mui/icons-material/Search"; +import React from "react"; +import FromDateController from "./FromDateController"; +import ToDateController from "./ToDateController"; +import SelectProvince from "./SelectProvince"; +import { Controller } from "react-hook-form"; + +const SearchReportField = ({ control, hasProvincesPermission }) => { + return ( + + + + + + + + {hasProvincesPermission && ( + + + + )} + + ( + + )} + /> + + + ); +}; + +export default SearchReportField; diff --git a/src/components/dashboard/roadPatrols/reports/Search/SelectProvince.jsx b/src/components/dashboard/roadPatrols/reports/Search/SelectProvince.jsx index b1d8a39..7f738bc 100644 --- a/src/components/dashboard/roadPatrols/reports/Search/SelectProvince.jsx +++ b/src/components/dashboard/roadPatrols/reports/Search/SelectProvince.jsx @@ -1,47 +1,47 @@ -import { Controller } from "react-hook-form"; -import MuiDatePicker from "@/core/components/MuiDatePicker"; -import React from "react"; -import { FormControl, FormHelperText, InputLabel, LinearProgress, MenuItem, Select, Typography } from "@mui/material"; -import useProvinces from "@/lib/hooks/useProvince"; - -const SelectProvince = ({ control }) => { - const { provinces, loadingProvinces, errorProvinces } = useProvinces(); - return ( - ( - - استان - - {error && {error.message}} - - )} - /> - ); -}; -export default SelectProvince; +import { Controller } from "react-hook-form"; +import MuiDatePicker from "@/core/components/MuiDatePicker"; +import React from "react"; +import { FormControl, FormHelperText, InputLabel, LinearProgress, MenuItem, Select, Typography } from "@mui/material"; +import useProvinces from "@/lib/hooks/useProvince"; + +const SelectProvince = ({ control }) => { + const { provinces, loadingProvinces, errorProvinces } = useProvinces(); + return ( + ( + + استان + + {error && {error.message}} + + )} + /> + ); +}; +export default SelectProvince; diff --git a/src/components/dashboard/roadPatrols/reports/Search/ToDateController.jsx b/src/components/dashboard/roadPatrols/reports/Search/ToDateController.jsx index d102c13..4b5f2a8 100644 --- a/src/components/dashboard/roadPatrols/reports/Search/ToDateController.jsx +++ b/src/components/dashboard/roadPatrols/reports/Search/ToDateController.jsx @@ -1,30 +1,30 @@ -import { Controller, useWatch } from "react-hook-form"; -import MuiDatePicker from "@/core/components/MuiDatePicker"; -import React from "react"; -import moment from "jalali-moment"; - -const ToDateController = ({ control }) => { - const minDate = useWatch({ control, name: "from_date" }); - return ( - ( - { - const formattedDate = moment(new Date(newValue)).locale("en").format("YYYY-MM-DD"); - onChange(formattedDate); // Update the field value in react-hook-form - }} - helperText={error ? error.message : null} - /> - )} - /> - ); -}; -export default ToDateController; +import { Controller, useWatch } from "react-hook-form"; +import MuiDatePicker from "@/core/components/MuiDatePicker"; +import React from "react"; +import moment from "jalali-moment"; + +const ToDateController = ({ control }) => { + const minDate = useWatch({ control, name: "from_date" }); + return ( + ( + { + const formattedDate = moment(new Date(newValue)).locale("en").format("YYYY-MM-DD"); + onChange(formattedDate); // Update the field value in react-hook-form + }} + helperText={error ? error.message : null} + /> + )} + /> + ); +}; +export default ToDateController; diff --git a/src/components/dashboard/roadPatrols/reports/Search/index.jsx b/src/components/dashboard/roadPatrols/reports/Search/index.jsx index f29d302..9d504f2 100644 --- a/src/components/dashboard/roadPatrols/reports/Search/index.jsx +++ b/src/components/dashboard/roadPatrols/reports/Search/index.jsx @@ -1,13 +1,13 @@ -import StyledForm from "@/core/components/StyledForm"; -import SearchReportField from "./SearchReportField"; - -const SearchReportList = ({ handleSubmit, onSearchSubmit, control, hasProvincesPermission }) => { - return ( - <> - - - - - ); -}; -export default SearchReportList; +import StyledForm from "@/core/components/StyledForm"; +import SearchReportField from "./SearchReportField"; + +const SearchReportList = ({ handleSubmit, onSearchSubmit, control, hasProvincesPermission }) => { + return ( + <> + + + + + ); +}; +export default SearchReportList; diff --git a/src/components/dashboard/roadPatrols/reports/Toolbar.jsx b/src/components/dashboard/roadPatrols/reports/Toolbar.jsx index 7dd930f..3e5ab8c 100644 --- a/src/components/dashboard/roadPatrols/reports/Toolbar.jsx +++ b/src/components/dashboard/roadPatrols/reports/Toolbar.jsx @@ -1,11 +1,11 @@ -import PrintExcel from "./ExcelPrint"; -import { Box } from "@mui/material"; - -const Toolbar = ({ table, filterData, mutate }) => { - return ( - - - - ); -}; -export default Toolbar; +import PrintExcel from "./ExcelPrint"; +import { Box } from "@mui/material"; + +const Toolbar = ({ table, filterData, mutate }) => { + return ( + + + + ); +}; +export default Toolbar; diff --git a/src/components/dashboard/roadPatrols/reports/index.jsx b/src/components/dashboard/roadPatrols/reports/index.jsx index d3b7679..a77efac 100644 --- a/src/components/dashboard/roadPatrols/reports/index.jsx +++ b/src/components/dashboard/roadPatrols/reports/index.jsx @@ -1,134 +1,134 @@ -"use client"; -import PageTitle from "@/core/components/PageTitle"; -import { LinearProgress, Stack } from "@mui/material"; -import SearchReportList from "./Search"; -import { useEffect, useState } from "react"; -import ReportLists from "./ReportLists"; -import useRequest from "@/lib/hooks/useRequest"; -import { GET_CITY_ACTIVITY_REPORT, GET_PROVINCE_ACTIVITY_REPORT } from "@/core/utils/routes"; -import moment from "jalali-moment"; -import * as yup from "yup"; -import { useForm } from "react-hook-form"; -import { yupResolver } from "@hookform/resolvers/yup"; -import { usePermissions } from "@/lib/hooks/usePermissions"; -import { useAuth } from "@/lib/contexts/auth"; - -const ReportPage = () => { - const [data, setData] = useState(null); - const { data: userPermissions } = usePermissions(); - const { user } = useAuth(); - const requestServer = useRequest(); - const hasProvincesPermission = userPermissions?.includes("show-road-patrol-supervise-cartable"); - - const defaultValues = { - from_date: moment(new Date()).format("YYYY-MM-DD"), - date_to: moment(new Date()).format("YYYY-MM-DD"), - province_id: hasProvincesPermission ? "-1" : user.province_id, - }; - const defaultFilter = [ - { value: `${defaultValues.province_id}`, datatype: "numeric", id: "province_id", fn: "equals" }, - { value: `${defaultValues.from_date}`, datatype: "date", id: "from_date", fn: "between" }, - { value: `${defaultValues.date_to}`, datatype: "date", id: "date_to", fn: "between" }, - ]; - const [specialFilter, setSpecialFilter] = useState(defaultFilter); - - const onSearchSubmit = async (data) => { - const params = new URLSearchParams(); - params.set("from_date", `${data.from_date}`); - params.set("date_to", `${data.date_to}`); - setSpecialFilter([ - { value: `${data.province_id}`, datatype: "numeric", id: "province_id", fn: "equals" }, - { value: `${data.from_date}`, datatype: "date", id: "from_date", fn: "between" }, - { value: `${data.date_to}`, datatype: "date", id: "date_to", fn: "between" }, - ]); - if (data.province_id === "-1") { - try { - const response = await requestServer(`${GET_PROVINCE_ACTIVITY_REPORT}?${params}`); - const result = response.data.data; - const nationalReportForItem = result.activities.find((report) => report.province_id === -1); - const nationalReport = { - edare_name: "کل کشور", - ...nationalReportForItem, - }; - - setData({ - data: [ - nationalReport, - ...result.provinces.map((province) => { - const filteredReports = result.activities.find( - (report) => report.province_id === province.id - ); - return { - ...filteredReports, - edare_name: province.name_fa, - }; - }), - ], - filters: data, - }); - } catch (e) {} - } else { - try { - params.set("province_id", `${data.province_id}`); - const response = await requestServer(`${GET_CITY_ACTIVITY_REPORT}?${params}`); - const result = response.data.data; - const nationalReportForItem = result.activities.find((report) => report.edare_id === "-1"); - const nationalReport = { - ...nationalReportForItem, - edare_name: "کل استان", - }; - setData({ - data: [ - nationalReport, - ...result.edarateShahri.map((edare) => { - const filteredReports = result.activities.find((report) => report.edare_id == edare.id); - return { - edare_name: edare.name_fa, - ...filteredReports, - }; - }), - ], - filters: data, - }); - } catch (e) {} - } - }; - - useEffect(() => { - if (!userPermissions) return; - onSearchSubmit(defaultValues); - }, [userPermissions]); - - const validationSchema = yup.object().shape({ - from_date: yup - .string() - .required("تاریخ شروع الزامی است!") - .matches(/^\d{4}-\d{2}-\d{2}$/, "تاریخ شروع الزامی است!") - .test("is-valid-date", "تاریخ شروع معتبر نیست!", (value) => moment(value, "YYYY-MM-DD", true).isValid()), - date_to: yup - .string() - .required("تاریخ پایان الزامی است!") - .matches(/^\d{4}-\d{2}-\d{2}$/, "تاریخ پایان الزامی است!") - .test("is-valid-date", "تاریخ پایان معتبر نیست!", (value) => moment(value, "YYYY-MM-DD", true).isValid()), - province_id: yup.string().nullable(), - }); - - const { control, handleSubmit } = useForm({ - defaultValues, - resolver: yupResolver(validationSchema), - mode: "all", - }); - return ( - - - - {!data ? : } - - ); -}; -export default ReportPage; +"use client"; +import PageTitle from "@/core/components/PageTitle"; +import { LinearProgress, Stack } from "@mui/material"; +import SearchReportList from "./Search"; +import { useEffect, useState } from "react"; +import ReportLists from "./ReportLists"; +import useRequest from "@/lib/hooks/useRequest"; +import { GET_CITY_ACTIVITY_REPORT, GET_PROVINCE_ACTIVITY_REPORT } from "@/core/utils/routes"; +import moment from "jalali-moment"; +import * as yup from "yup"; +import { useForm } from "react-hook-form"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { usePermissions } from "@/lib/hooks/usePermissions"; +import { useAuth } from "@/lib/contexts/auth"; + +const ReportPage = () => { + const [data, setData] = useState(null); + const { data: userPermissions } = usePermissions(); + const { user } = useAuth(); + const requestServer = useRequest(); + const hasProvincesPermission = userPermissions?.includes("show-road-patrol-supervise-cartable"); + + const defaultValues = { + from_date: moment(new Date()).format("YYYY-MM-DD"), + date_to: moment(new Date()).format("YYYY-MM-DD"), + province_id: hasProvincesPermission ? "-1" : user.province_id, + }; + const defaultFilter = [ + { value: `${defaultValues.province_id}`, datatype: "numeric", id: "province_id", fn: "equals" }, + { value: `${defaultValues.from_date}`, datatype: "date", id: "from_date", fn: "between" }, + { value: `${defaultValues.date_to}`, datatype: "date", id: "date_to", fn: "between" }, + ]; + const [specialFilter, setSpecialFilter] = useState(defaultFilter); + + const onSearchSubmit = async (data) => { + const params = new URLSearchParams(); + params.set("from_date", `${data.from_date}`); + params.set("date_to", `${data.date_to}`); + setSpecialFilter([ + { value: `${data.province_id}`, datatype: "numeric", id: "province_id", fn: "equals" }, + { value: `${data.from_date}`, datatype: "date", id: "from_date", fn: "between" }, + { value: `${data.date_to}`, datatype: "date", id: "date_to", fn: "between" }, + ]); + if (data.province_id === "-1") { + try { + const response = await requestServer(`${GET_PROVINCE_ACTIVITY_REPORT}?${params}`); + const result = response.data.data; + const nationalReportForItem = result.activities.find((report) => report.province_id === -1); + const nationalReport = { + edare_name: "کل کشور", + ...nationalReportForItem, + }; + + setData({ + data: [ + nationalReport, + ...result.provinces.map((province) => { + const filteredReports = result.activities.find( + (report) => report.province_id === province.id + ); + return { + ...filteredReports, + edare_name: province.name_fa, + }; + }), + ], + filters: data, + }); + } catch (e) {} + } else { + try { + params.set("province_id", `${data.province_id}`); + const response = await requestServer(`${GET_CITY_ACTIVITY_REPORT}?${params}`); + const result = response.data.data; + const nationalReportForItem = result.activities.find((report) => report.edare_id === "-1"); + const nationalReport = { + ...nationalReportForItem, + edare_name: "کل استان", + }; + setData({ + data: [ + nationalReport, + ...result.edarateShahri.map((edare) => { + const filteredReports = result.activities.find((report) => report.edare_id == edare.id); + return { + edare_name: edare.name_fa, + ...filteredReports, + }; + }), + ], + filters: data, + }); + } catch (e) {} + } + }; + + useEffect(() => { + if (!userPermissions) return; + onSearchSubmit(defaultValues); + }, [userPermissions]); + + const validationSchema = yup.object().shape({ + from_date: yup + .string() + .required("تاریخ شروع الزامی است!") + .matches(/^\d{4}-\d{2}-\d{2}$/, "تاریخ شروع الزامی است!") + .test("is-valid-date", "تاریخ شروع معتبر نیست!", (value) => moment(value, "YYYY-MM-DD", true).isValid()), + date_to: yup + .string() + .required("تاریخ پایان الزامی است!") + .matches(/^\d{4}-\d{2}-\d{2}$/, "تاریخ پایان الزامی است!") + .test("is-valid-date", "تاریخ پایان معتبر نیست!", (value) => moment(value, "YYYY-MM-DD", true).isValid()), + province_id: yup.string().nullable(), + }); + + const { control, handleSubmit } = useForm({ + defaultValues, + resolver: yupResolver(validationSchema), + mode: "all", + }); + return ( + + + + {!data ? : } + + ); +}; +export default ReportPage; diff --git a/src/components/dashboard/roadPatrols/supervisor/ExcelPrint/index.jsx b/src/components/dashboard/roadPatrols/supervisor/ExcelPrint/index.jsx index ba176bb..b583c0d 100644 --- a/src/components/dashboard/roadPatrols/supervisor/ExcelPrint/index.jsx +++ b/src/components/dashboard/roadPatrols/supervisor/ExcelPrint/index.jsx @@ -1,75 +1,75 @@ -import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; -import { useMemo, useState } from "react"; -import moment from "jalali-moment"; -import FileSaver from "file-saver"; -import DescriptionIcon from "@mui/icons-material/Description"; -import useRequest from "@/lib/hooks/useRequest"; -import { EXPORT_ROAD_PATROL_SUPERVISOR_LIST } from "@/core/utils/routes"; -import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; -import isArrayEmpty from "@/core/utils/isArrayEmpty"; -import { useTheme } from "@emotion/react"; - -const PrintExcel = ({ table, filterData }) => { - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const [loading, setLoading] = useState(false); - const requestServer = useRequest(); - const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { - if (filter.value && (!Array.isArray(filter.value) || filter.value.some((item) => item.trim() !== ""))) { - acc.push({ id: key, value: filter.value }); - } - return acc; - }, []); - - const filterParams = useMemo(() => { - const params = new URLSearchParams(); - if (activeFilters.length > 0) { - activeFilters.map((filter, index) => { - const filteredFilterData = DataTableFilterDataStructure(filterData, isArrayEmpty); - params.set("filters", JSON.stringify(filteredFilterData.length === 0 ? [] : filteredFilterData)); - }); - } else { - params.set("filters", JSON.stringify([])); - } - return params; - }, [activeFilters]); - - const clickHandler = () => { - setLoading(true); - requestServer(`${EXPORT_ROAD_PATROL_SUPERVISOR_LIST}?${filterParams}`, "get", { - requestOptions: { responseType: "blob" }, - }) - .then((response) => { - const filename = `خروجی کارتابل ارزیابی گشت راهداری تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; - FileSaver.saveAs(response.data, filename); - }) - .catch(() => {}) - .finally(() => { - setLoading(false); - }); - }; - - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - - ); -}; - -export default PrintExcel; +import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; +import { useMemo, useState } from "react"; +import moment from "jalali-moment"; +import FileSaver from "file-saver"; +import DescriptionIcon from "@mui/icons-material/Description"; +import useRequest from "@/lib/hooks/useRequest"; +import { EXPORT_ROAD_PATROL_SUPERVISOR_LIST } from "@/core/utils/routes"; +import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; +import isArrayEmpty from "@/core/utils/isArrayEmpty"; +import { useTheme } from "@emotion/react"; + +const PrintExcel = ({ table, filterData }) => { + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const [loading, setLoading] = useState(false); + const requestServer = useRequest(); + const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { + if (filter.value && (!Array.isArray(filter.value) || filter.value.some((item) => item.trim() !== ""))) { + acc.push({ id: key, value: filter.value }); + } + return acc; + }, []); + + const filterParams = useMemo(() => { + const params = new URLSearchParams(); + if (activeFilters.length > 0) { + activeFilters.map((filter, index) => { + const filteredFilterData = DataTableFilterDataStructure(filterData, isArrayEmpty); + params.set("filters", JSON.stringify(filteredFilterData.length === 0 ? [] : filteredFilterData)); + }); + } else { + params.set("filters", JSON.stringify([])); + } + return params; + }, [activeFilters]); + + const clickHandler = () => { + setLoading(true); + requestServer(`${EXPORT_ROAD_PATROL_SUPERVISOR_LIST}?${filterParams}`, "get", { + requestOptions: { responseType: "blob" }, + }) + .then((response) => { + const filename = `خروجی کارتابل ارزیابی گشت راهداری تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; + FileSaver.saveAs(response.data, filename); + }) + .catch(() => {}) + .finally(() => { + setLoading(false); + }); + }; + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + + ); +}; + +export default PrintExcel; diff --git a/src/components/dashboard/roadPatrols/supervisor/RowActions/DeleteForm/DeleteContent.jsx b/src/components/dashboard/roadPatrols/supervisor/RowActions/DeleteForm/DeleteContent.jsx index 3e6386f..e2735a7 100644 --- a/src/components/dashboard/roadPatrols/supervisor/RowActions/DeleteForm/DeleteContent.jsx +++ b/src/components/dashboard/roadPatrols/supervisor/RowActions/DeleteForm/DeleteContent.jsx @@ -1,116 +1,116 @@ -import { Button, DialogActions, DialogContent, Stack, Typography, List, ListItem } from "@mui/material"; -import useRequest from "@/lib/hooks/useRequest"; -import React, { useState } from "react"; -import { DELETE_ROAD_PATROL_SUPERVISOR } from "@/core/utils/routes"; - -const DeleteContent = ({ - rowId, - mutate, - setOpenDeleteDialog, - hasCompleteDeletePermission, - hasPartialDeletePermission, -}) => { - const requestServer = useRequest({ notificationSuccess: true }); - const [submittingPartial, setSubmittingPartial] = useState(false); - const [submittingGeneral, setSubmittingGeneral] = useState(false); - const handleGeneralDelete = () => { - setSubmittingGeneral(true); - requestServer(`${DELETE_ROAD_PATROL_SUPERVISOR}/${rowId}`, "post", { - data: { - type: 2, - }, - }) - .then(() => { - mutate(); - setOpenDeleteDialog(false); - setSubmittingGeneral(false); - }) - .catch(() => { - setSubmittingGeneral(false); - }); - }; - - const handlePartialDelete = () => { - setSubmittingPartial(true); - requestServer(`${DELETE_ROAD_PATROL_SUPERVISOR}/${rowId}`, "post", { - data: { - type: 1, - }, - }) - .then(() => { - mutate(); - setOpenDeleteDialog(false); - setSubmittingPartial(false); - }) - .catch(() => { - setSubmittingPartial(false); - }); - }; - - return ( - <> - - - - لطفاً نوع حذف مورد نظر را انتخاب کنید. - - - {hasPartialDeletePermission && ( - - حذف جزئی : حذف گشت بدون اقدامات انجام شده. - - )} - {hasCompleteDeletePermission && ( - - حذف کلی : حذف گشت با اقدامات انجام شده. - - )} - - - - - - {hasPartialDeletePermission && ( - - )} - {hasCompleteDeletePermission && ( - - )} - - - ); -}; - -export default DeleteContent; +import { Button, DialogActions, DialogContent, Stack, Typography, List, ListItem } from "@mui/material"; +import useRequest from "@/lib/hooks/useRequest"; +import React, { useState } from "react"; +import { DELETE_ROAD_PATROL_SUPERVISOR } from "@/core/utils/routes"; + +const DeleteContent = ({ + rowId, + mutate, + setOpenDeleteDialog, + hasCompleteDeletePermission, + hasPartialDeletePermission, +}) => { + const requestServer = useRequest({ notificationSuccess: true }); + const [submittingPartial, setSubmittingPartial] = useState(false); + const [submittingGeneral, setSubmittingGeneral] = useState(false); + const handleGeneralDelete = () => { + setSubmittingGeneral(true); + requestServer(`${DELETE_ROAD_PATROL_SUPERVISOR}/${rowId}`, "post", { + data: { + type: 2, + }, + }) + .then(() => { + mutate(); + setOpenDeleteDialog(false); + setSubmittingGeneral(false); + }) + .catch(() => { + setSubmittingGeneral(false); + }); + }; + + const handlePartialDelete = () => { + setSubmittingPartial(true); + requestServer(`${DELETE_ROAD_PATROL_SUPERVISOR}/${rowId}`, "post", { + data: { + type: 1, + }, + }) + .then(() => { + mutate(); + setOpenDeleteDialog(false); + setSubmittingPartial(false); + }) + .catch(() => { + setSubmittingPartial(false); + }); + }; + + return ( + <> + + + + لطفاً نوع حذف مورد نظر را انتخاب کنید. + + + {hasPartialDeletePermission && ( + + حذف جزئی : حذف گشت بدون اقدامات انجام شده. + + )} + {hasCompleteDeletePermission && ( + + حذف کلی : حذف گشت با اقدامات انجام شده. + + )} + + + + + + {hasPartialDeletePermission && ( + + )} + {hasCompleteDeletePermission && ( + + )} + + + ); +}; + +export default DeleteContent; diff --git a/src/components/dashboard/roadPatrols/supervisor/RowActions/DeleteForm/index.jsx b/src/components/dashboard/roadPatrols/supervisor/RowActions/DeleteForm/index.jsx index 07a903f..aeb7939 100644 --- a/src/components/dashboard/roadPatrols/supervisor/RowActions/DeleteForm/index.jsx +++ b/src/components/dashboard/roadPatrols/supervisor/RowActions/DeleteForm/index.jsx @@ -1,38 +1,38 @@ -import React, { useState } from "react"; -import { Tooltip, IconButton, Dialog, DialogTitle } from "@mui/material"; -import DeleteIcon from "@mui/icons-material/Delete"; -import DeleteContent from "./DeleteContent"; -const DeleteForm = ({ rowId, mutate, hasCompleteDeletePermission, hasPartialDeletePermission }) => { - const [openDeleteDialog, setOpenDeleteDialog] = useState(false); - - return ( - <> - - setOpenDeleteDialog(true)}> - - - - setOpenDeleteDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - حذف گشت - - - - ); -}; -export default DeleteForm; +import React, { useState } from "react"; +import { Tooltip, IconButton, Dialog, DialogTitle } from "@mui/material"; +import DeleteIcon from "@mui/icons-material/Delete"; +import DeleteContent from "./DeleteContent"; +const DeleteForm = ({ rowId, mutate, hasCompleteDeletePermission, hasPartialDeletePermission }) => { + const [openDeleteDialog, setOpenDeleteDialog] = useState(false); + + return ( + <> + + setOpenDeleteDialog(true)}> + + + + setOpenDeleteDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + حذف گشت + + + + ); +}; +export default DeleteForm; diff --git a/src/components/dashboard/roadPatrols/supervisor/RowActions/MachinePerformanceForm/MachinePerformanceContent.jsx b/src/components/dashboard/roadPatrols/supervisor/RowActions/MachinePerformanceForm/MachinePerformanceContent.jsx index ead48ff..d37d1d3 100644 --- a/src/components/dashboard/roadPatrols/supervisor/RowActions/MachinePerformanceForm/MachinePerformanceContent.jsx +++ b/src/components/dashboard/roadPatrols/supervisor/RowActions/MachinePerformanceForm/MachinePerformanceContent.jsx @@ -1,155 +1,155 @@ -import { Box, Chip, DialogContent, Divider, Grid, Stack, Typography } from "@mui/material"; -import React, { useEffect, useState, useRef } from "react"; -import { Marker, useMap } from "react-leaflet"; -import AzmayeshActiveIcon from "@/assets/images/examine_marker_active.png"; -import MapLayer from "@/core/components/MapLayer"; -import PinDropIcon from "@mui/icons-material/PinDrop"; -import AccessAlarmsIcon from "@mui/icons-material/AccessAlarms"; -import { formatSecondsToHHMMSS } from "@/core/utils/formatSecondsToHHMMSS"; -import StopsInfo from "./StopsInfo"; -const defaultIconSize = [35, 35]; -const MachinePerformanceContent = ({ machinesLists }) => { - const [selectedPoint, setSelectedPoint] = useState(null); - const mapRef = useRef(null); - const isFirstRender = useRef(true); - const createCustomIcon = (size, iconUrl) => { - return L.icon({ - iconUrl: iconUrl, - iconSize: size, - iconAnchor: [size[0] / 2, size[1]], - popupAnchor: [0, -size[1]], - }); - }; - const MapWithBounds = () => { - const map = useMap(); - useEffect(() => { - if (machinesLists.stopPoints.length > 0) { - const bounds = machinesLists.stopPoints.map((point) => [point.latitude, point.longitude]); - if (isFirstRender.current) { - map.fitBounds(bounds, { - padding: [50, 50], - }); - isFirstRender.current = false; - } else if (mapRef.current) { - mapRef.current.setView(map.getCenter(), map.getZoom()); - } - } - }, [machinesLists.stopPoints, map]); - return null; - }; - const handleMarkerClick = (point) => { - setSelectedPoint(point); - }; - - return ( - <> - - - - - - - - - - - {machinesLists.stopPoints.map((point, index) => ( - handleMarkerClick(point), - }} - > - ))} - - - - - - - - } - label={ - - طول جغرافیایی - - } - /> - - - - {selectedPoint ? selectedPoint.longitude : "نقطه مورد نظر را انتخاب کنید"} - - - - - } - label={ - - عرض جغرافیایی - - } - /> - - - - {selectedPoint ? selectedPoint.latitude : "نقطه مورد نظر را انتخاب کنید"} - - - - - } - label={ - - مدت زمان توقف - - } - /> - - - - {selectedPoint - ? `${formatSecondsToHHMMSS(selectedPoint.duration)}` - : "نقطه مورد نظر را انتخاب کنید"} - - - - - - - - ); -}; -export default MachinePerformanceContent; +import { Box, Chip, DialogContent, Divider, Grid, Stack, Typography } from "@mui/material"; +import React, { useEffect, useState, useRef } from "react"; +import { Marker, useMap } from "react-leaflet"; +import AzmayeshActiveIcon from "@/assets/images/examine_marker_active.png"; +import MapLayer from "@/core/components/MapLayer"; +import PinDropIcon from "@mui/icons-material/PinDrop"; +import AccessAlarmsIcon from "@mui/icons-material/AccessAlarms"; +import { formatSecondsToHHMMSS } from "@/core/utils/formatSecondsToHHMMSS"; +import StopsInfo from "./StopsInfo"; +const defaultIconSize = [35, 35]; +const MachinePerformanceContent = ({ machinesLists }) => { + const [selectedPoint, setSelectedPoint] = useState(null); + const mapRef = useRef(null); + const isFirstRender = useRef(true); + const createCustomIcon = (size, iconUrl) => { + return L.icon({ + iconUrl: iconUrl, + iconSize: size, + iconAnchor: [size[0] / 2, size[1]], + popupAnchor: [0, -size[1]], + }); + }; + const MapWithBounds = () => { + const map = useMap(); + useEffect(() => { + if (machinesLists.stopPoints.length > 0) { + const bounds = machinesLists.stopPoints.map((point) => [point.latitude, point.longitude]); + if (isFirstRender.current) { + map.fitBounds(bounds, { + padding: [50, 50], + }); + isFirstRender.current = false; + } else if (mapRef.current) { + mapRef.current.setView(map.getCenter(), map.getZoom()); + } + } + }, [machinesLists.stopPoints, map]); + return null; + }; + const handleMarkerClick = (point) => { + setSelectedPoint(point); + }; + + return ( + <> + + + + + + + + + + + {machinesLists.stopPoints.map((point, index) => ( + handleMarkerClick(point), + }} + > + ))} + + + + + + + + } + label={ + + طول جغرافیایی + + } + /> + + + + {selectedPoint ? selectedPoint.longitude : "نقطه مورد نظر را انتخاب کنید"} + + + + + } + label={ + + عرض جغرافیایی + + } + /> + + + + {selectedPoint ? selectedPoint.latitude : "نقطه مورد نظر را انتخاب کنید"} + + + + + } + label={ + + مدت زمان توقف + + } + /> + + + + {selectedPoint + ? `${formatSecondsToHHMMSS(selectedPoint.duration)}` + : "نقطه مورد نظر را انتخاب کنید"} + + + + + + + + ); +}; +export default MachinePerformanceContent; diff --git a/src/components/dashboard/roadPatrols/supervisor/RowActions/MachinePerformanceForm/MachinesCodeFetch.jsx b/src/components/dashboard/roadPatrols/supervisor/RowActions/MachinePerformanceForm/MachinesCodeFetch.jsx index 0da7b28..3824bd0 100644 --- a/src/components/dashboard/roadPatrols/supervisor/RowActions/MachinePerformanceForm/MachinesCodeFetch.jsx +++ b/src/components/dashboard/roadPatrols/supervisor/RowActions/MachinePerformanceForm/MachinesCodeFetch.jsx @@ -1,50 +1,50 @@ -import DialogLoading from "@/core/components/DialogLoading"; -import { GET_CMMS_MACHINE_ROAD_PATROL } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { DialogContent, Typography } from "@mui/material"; -import { useEffect, useState } from "react"; -import MachinePerformanceContent from "./MachinePerformanceContent"; - -const MachinePerformanceFetch = ({ row }) => { - const [loading, setLoading] = useState(true); - const [data, setData] = useState(null); - const request = useRequest(); - - useEffect(() => { - const fetchData = async () => { - try { - setLoading(true); - const response = await request(`${GET_CMMS_MACHINE_ROAD_PATROL}/${row.getValue("id")}`); - setData(response.data.data); - } catch (error) { - } finally { - setLoading(false); - } - }; - - fetchData(); - }, []); - - return ( - <> - - {loading ? ( - - ) : data && row.original?.stop_points?.length > 0 ? ( - - ) : ( - عملکرد خودرویی در سامانه یافت نشد - )} - - - ); -}; -export default MachinePerformanceFetch; +import DialogLoading from "@/core/components/DialogLoading"; +import { GET_CMMS_MACHINE_ROAD_PATROL } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { DialogContent, Typography } from "@mui/material"; +import { useEffect, useState } from "react"; +import MachinePerformanceContent from "./MachinePerformanceContent"; + +const MachinePerformanceFetch = ({ row }) => { + const [loading, setLoading] = useState(true); + const [data, setData] = useState(null); + const request = useRequest(); + + useEffect(() => { + const fetchData = async () => { + try { + setLoading(true); + const response = await request(`${GET_CMMS_MACHINE_ROAD_PATROL}/${row.getValue("id")}`); + setData(response.data.data); + } catch (error) { + } finally { + setLoading(false); + } + }; + + fetchData(); + }, []); + + return ( + <> + + {loading ? ( + + ) : data && row.original?.stop_points?.length > 0 ? ( + + ) : ( + عملکرد خودرویی در سامانه یافت نشد + )} + + + ); +}; +export default MachinePerformanceFetch; diff --git a/src/components/dashboard/roadPatrols/supervisor/RowActions/MachinePerformanceForm/StopsInfo.jsx b/src/components/dashboard/roadPatrols/supervisor/RowActions/MachinePerformanceForm/StopsInfo.jsx index d8e44cb..67ae090 100644 --- a/src/components/dashboard/roadPatrols/supervisor/RowActions/MachinePerformanceForm/StopsInfo.jsx +++ b/src/components/dashboard/roadPatrols/supervisor/RowActions/MachinePerformanceForm/StopsInfo.jsx @@ -1,120 +1,120 @@ -import { Box, Chip, Divider, Grid, Typography } from "@mui/material"; -import AccessAlarmsIcon from "@mui/icons-material/AccessAlarms"; - -import LocalGasStationIcon from "@mui/icons-material/LocalGasStation"; -import QrCode2Icon from "@mui/icons-material/QrCode2"; -import AddRoadIcon from "@mui/icons-material/AddRoad"; -import DirectionsCarFilledIcon from "@mui/icons-material/DirectionsCarFilled"; -import BadgeIcon from "@mui/icons-material/Badge"; -import { formatSecondsToHHMMSS } from "@/core/utils/formatSecondsToHHMMSS"; -import ShowPlak from "@/core/components/ShowPlak"; - -const StopsInfo = ({ staticData }) => { - return ( - - - - } - label={ - - کد خودرو - - } - /> - - - - {staticData.cmmsMachineCode.machine_code || ""} - - - - - } - label={ - - نام خودرو - - } - /> - - - - {staticData.cmmsMachineCode.car_name || ""} - - - - - } - label={ - - پلاک خودرو - - } - /> - - - - {staticData.cmmsMachineCode.plak_number && - ShowPlak({ plak_number: staticData.cmmsMachineCode.plak_number })} - - - - - } - label={ - - میزان سوخت مصرفی - - } - /> - - - - {Math.round(staticData?.fuelConsumption * 10) / 10} لیتر - - - - - } - label={ - - مسافت پیموده شده - - } - /> - - - - {(staticData?.mileage / 1000).toFixed(1)} کیلومتر - - - - - } - label={ - - مدت زمان روشن بودن خودرو - - } - /> - - - - {formatSecondsToHHMMSS(staticData?.accOnDuration)} - - - - ); -}; -export default StopsInfo; +import { Box, Chip, Divider, Grid, Typography } from "@mui/material"; +import AccessAlarmsIcon from "@mui/icons-material/AccessAlarms"; + +import LocalGasStationIcon from "@mui/icons-material/LocalGasStation"; +import QrCode2Icon from "@mui/icons-material/QrCode2"; +import AddRoadIcon from "@mui/icons-material/AddRoad"; +import DirectionsCarFilledIcon from "@mui/icons-material/DirectionsCarFilled"; +import BadgeIcon from "@mui/icons-material/Badge"; +import { formatSecondsToHHMMSS } from "@/core/utils/formatSecondsToHHMMSS"; +import ShowPlak from "@/core/components/ShowPlak"; + +const StopsInfo = ({ staticData }) => { + return ( + + + + } + label={ + + کد خودرو + + } + /> + + + + {staticData.cmmsMachineCode.machine_code || ""} + + + + + } + label={ + + نام خودرو + + } + /> + + + + {staticData.cmmsMachineCode.car_name || ""} + + + + + } + label={ + + پلاک خودرو + + } + /> + + + + {staticData.cmmsMachineCode.plak_number && + ShowPlak({ plak_number: staticData.cmmsMachineCode.plak_number })} + + + + + } + label={ + + میزان سوخت مصرفی + + } + /> + + + + {Math.round(staticData?.fuelConsumption * 10) / 10} لیتر + + + + + } + label={ + + مسافت پیموده شده + + } + /> + + + + {(staticData?.mileage / 1000).toFixed(1)} کیلومتر + + + + + } + label={ + + مدت زمان روشن بودن خودرو + + } + /> + + + + {formatSecondsToHHMMSS(staticData?.accOnDuration)} + + + + ); +}; +export default StopsInfo; diff --git a/src/components/dashboard/roadPatrols/supervisor/RowActions/MachinePerformanceForm/index.jsx b/src/components/dashboard/roadPatrols/supervisor/RowActions/MachinePerformanceForm/index.jsx index 168936e..e9a161b 100644 --- a/src/components/dashboard/roadPatrols/supervisor/RowActions/MachinePerformanceForm/index.jsx +++ b/src/components/dashboard/roadPatrols/supervisor/RowActions/MachinePerformanceForm/index.jsx @@ -1,43 +1,43 @@ -import DirectionsCarIcon from "@mui/icons-material/DirectionsCar"; -import { Button, Dialog, DialogActions, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import MachinePerformanceFetch from "./MachinesCodeFetch"; - -const MachinePerformanceForm = ({ row }) => { - const [openMachinesCodeDialog, setOpenMachinesCodeDialog] = useState(false); - return ( - <> - - setOpenMachinesCodeDialog(true)}> - - - - setOpenMachinesCodeDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - عملکرد خودرو - {openMachinesCodeDialog && } - - - - - - ); -}; -export default MachinePerformanceForm; +import DirectionsCarIcon from "@mui/icons-material/DirectionsCar"; +import { Button, Dialog, DialogActions, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import MachinePerformanceFetch from "./MachinesCodeFetch"; + +const MachinePerformanceForm = ({ row }) => { + const [openMachinesCodeDialog, setOpenMachinesCodeDialog] = useState(false); + return ( + <> + + setOpenMachinesCodeDialog(true)}> + + + + setOpenMachinesCodeDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + عملکرد خودرو + {openMachinesCodeDialog && } + + + + + + ); +}; +export default MachinePerformanceForm; diff --git a/src/components/dashboard/roadPatrols/supervisor/RowActions/OfficerDescription/index.jsx b/src/components/dashboard/roadPatrols/supervisor/RowActions/OfficerDescription/index.jsx index 1ba3991..fd4caed 100644 --- a/src/components/dashboard/roadPatrols/supervisor/RowActions/OfficerDescription/index.jsx +++ b/src/components/dashboard/roadPatrols/supervisor/RowActions/OfficerDescription/index.jsx @@ -1,50 +1,50 @@ -import { Dialog, DialogContent, DialogTitle, IconButton, Tooltip, Typography, Card, CardContent } from "@mui/material"; -import { useState } from "react"; -import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye"; -import CloseIcon from "@mui/icons-material/Close"; - -const OfficerDescriptionForm = ({ description }) => { - const [openOfficerDescriptionDialog, setOpenOfficerDescriptionDialog] = useState(false); - - return ( - <> - - setOpenOfficerDescriptionDialog(true)}> - - - - setOpenOfficerDescriptionDialog(false)} - PaperProps={{ - sx: { - transition: "all .3s", - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - borderRadius: 2, - padding: 1, - }, - }} - maxWidth="sm" - fullWidth - dir="rtl" - > - - - توضیحات مامور - - setOpenOfficerDescriptionDialog(false)} size="small"> - - - - - - - {description || "هیچ توضیحی موجود نیست"} - - - - - - ); -}; -export default OfficerDescriptionForm; +import { Dialog, DialogContent, DialogTitle, IconButton, Tooltip, Typography, Card, CardContent } from "@mui/material"; +import { useState } from "react"; +import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye"; +import CloseIcon from "@mui/icons-material/Close"; + +const OfficerDescriptionForm = ({ description }) => { + const [openOfficerDescriptionDialog, setOpenOfficerDescriptionDialog] = useState(false); + + return ( + <> + + setOpenOfficerDescriptionDialog(true)}> + + + + setOpenOfficerDescriptionDialog(false)} + PaperProps={{ + sx: { + transition: "all .3s", + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + borderRadius: 2, + padding: 1, + }, + }} + maxWidth="sm" + fullWidth + dir="rtl" + > + + + توضیحات مامور + + setOpenOfficerDescriptionDialog(false)} size="small"> + + + + + + + {description || "هیچ توضیحی موجود نیست"} + + + + + + ); +}; +export default OfficerDescriptionForm; diff --git a/src/components/dashboard/roadPatrols/supervisor/RowActions/RahdaranForm/RahdaranContent.jsx b/src/components/dashboard/roadPatrols/supervisor/RowActions/RahdaranForm/RahdaranContent.jsx index d1e9b15..dd7ded9 100644 --- a/src/components/dashboard/roadPatrols/supervisor/RowActions/RahdaranForm/RahdaranContent.jsx +++ b/src/components/dashboard/roadPatrols/supervisor/RowActions/RahdaranForm/RahdaranContent.jsx @@ -1,48 +1,48 @@ -import { DialogContent, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow } from "@mui/material"; - -const RahdaranContent = ({ rahdarLists }) => { - return ( - <> - - - - - - - کد راهدار - نام - - - - {rahdarLists.map((rahdar) => { - return ( - - {rahdar.code} - {rahdar.name} - - ); - })} - -
    -
    -
    -
    - - ); -}; -export default RahdaranContent; +import { DialogContent, Paper, Table, TableBody, TableCell, TableContainer, TableHead, TableRow } from "@mui/material"; + +const RahdaranContent = ({ rahdarLists }) => { + return ( + <> + + + + + + + کد راهدار + نام + + + + {rahdarLists.map((rahdar) => { + return ( + + {rahdar.code} + {rahdar.name} + + ); + })} + +
    +
    +
    +
    + + ); +}; +export default RahdaranContent; diff --git a/src/components/dashboard/roadPatrols/supervisor/RowActions/RahdaranForm/index.jsx b/src/components/dashboard/roadPatrols/supervisor/RowActions/RahdaranForm/index.jsx index 2c73d80..82b1440 100644 --- a/src/components/dashboard/roadPatrols/supervisor/RowActions/RahdaranForm/index.jsx +++ b/src/components/dashboard/roadPatrols/supervisor/RowActions/RahdaranForm/index.jsx @@ -1,38 +1,38 @@ -import { Button, Dialog, DialogActions, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import GroupsIcon from "@mui/icons-material/Groups"; -import { useState } from "react"; -import RahdaranContent from "./RahdaranContent"; - -const RahdaranDialog = ({ rahdarLists }) => { - const [openRahdaranDialog, setOpenRahdaranDialog] = useState(false); - return ( - <> - - setOpenRahdaranDialog(true)}> - - - - setOpenRahdaranDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - لیست راهداران - - - - - - - ); -}; -export default RahdaranDialog; +import { Button, Dialog, DialogActions, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import GroupsIcon from "@mui/icons-material/Groups"; +import { useState } from "react"; +import RahdaranContent from "./RahdaranContent"; + +const RahdaranDialog = ({ rahdarLists }) => { + const [openRahdaranDialog, setOpenRahdaranDialog] = useState(false); + return ( + <> + + setOpenRahdaranDialog(true)}> + + + + setOpenRahdaranDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + لیست راهداران + + + + + + + ); +}; +export default RahdaranDialog; diff --git a/src/components/dashboard/roadPatrols/supervisor/RowActions/ReportForm/index.jsx b/src/components/dashboard/roadPatrols/supervisor/RowActions/ReportForm/index.jsx index c33aa7b..20daa69 100644 --- a/src/components/dashboard/roadPatrols/supervisor/RowActions/ReportForm/index.jsx +++ b/src/components/dashboard/roadPatrols/supervisor/RowActions/ReportForm/index.jsx @@ -1,22 +1,22 @@ -import { GET_ROAD_PATROL_SUPERVISOR_REPORT } from "@/core/utils/routes"; -import PrintIcon from "@mui/icons-material/Print"; -import { IconButton, Tooltip } from "@mui/material"; - -const ReportForm = ({ rowId }) => { - return ( - - - - - - ); -}; - -export default ReportForm; +import { GET_ROAD_PATROL_SUPERVISOR_REPORT } from "@/core/utils/routes"; +import PrintIcon from "@mui/icons-material/Print"; +import { IconButton, Tooltip } from "@mui/material"; + +const ReportForm = ({ rowId }) => { + return ( + + + + + + ); +}; + +export default ReportForm; diff --git a/src/components/dashboard/roadPatrols/supervisor/RowActions/index.jsx b/src/components/dashboard/roadPatrols/supervisor/RowActions/index.jsx index 6672411..591166b 100644 --- a/src/components/dashboard/roadPatrols/supervisor/RowActions/index.jsx +++ b/src/components/dashboard/roadPatrols/supervisor/RowActions/index.jsx @@ -1,22 +1,22 @@ -import { Box } from "@mui/material"; -import DeleteForm from "./DeleteForm"; -import { usePermissions } from "@/lib/hooks/usePermissions"; - -const RowActions = ({ row, mutate }) => { - const { data: userPermissions } = usePermissions(); - const hasPartialDeletePermission = userPermissions?.includes("partial-delete-road-patrol"); - const hasCompleteDeletePermission = userPermissions?.includes("complete-delete-road-patrol"); - return ( - - {hasPartialDeletePermission | hasCompleteDeletePermission && ( - - )} - - ); -}; -export default RowActions; +import { Box } from "@mui/material"; +import DeleteForm from "./DeleteForm"; +import { usePermissions } from "@/lib/hooks/usePermissions"; + +const RowActions = ({ row, mutate }) => { + const { data: userPermissions } = usePermissions(); + const hasPartialDeletePermission = userPermissions?.includes("partial-delete-road-patrol"); + const hasCompleteDeletePermission = userPermissions?.includes("complete-delete-road-patrol"); + return ( + + {hasPartialDeletePermission | hasCompleteDeletePermission && ( + + )} + + ); +}; +export default RowActions; diff --git a/src/components/dashboard/roadPatrols/supervisor/SupervisorList.jsx b/src/components/dashboard/roadPatrols/supervisor/SupervisorList.jsx index 723e4da..1a5224e 100644 --- a/src/components/dashboard/roadPatrols/supervisor/SupervisorList.jsx +++ b/src/components/dashboard/roadPatrols/supervisor/SupervisorList.jsx @@ -1,281 +1,281 @@ -"use client"; -import { useEffect, useMemo, useState } from "react"; -import { Box, Stack, Typography } from "@mui/material"; -import DataTableWithAuth from "@/core/components/DataTableWithAuth"; -import Toolbar from "./Toolbar"; -import { GET_ROAD_PATROL_SUPERVISOR_LIST } from "@/core/utils/routes"; -import moment from "jalali-moment"; -import RowActions from "./RowActions"; -import useProvinces from "@/lib/hooks/useProvince"; -import CustomSelectByDependency from "@/core/components/DataTable/filter/fieldsType/CustomSelectByDependency"; -import useEdaratLists from "@/lib/hooks/useEdaratLists"; -import OfficerDescriptionForm from "./RowActions/OfficerDescription"; -import ReportForm from "./RowActions/ReportForm"; -import RahdaranDialog from "./RowActions/RahdaranForm"; -import { usePermissions } from "@/lib/hooks/usePermissions"; -import { useAuth } from "@/lib/contexts/auth"; -import MachinePerformanceForm from "./RowActions/MachinePerformanceForm"; - -const SupervisorList = () => { - const { data: userPermissions } = usePermissions(); - const hasCountryPermission = userPermissions?.includes("show-road-patrol-supervise-cartable"); - const { user } = useAuth(); - const columns = useMemo(() => { - const dynamicColumns = { - accessorKey: "province_id", - header: "استان", // Province - id: "province_id", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - grow: false, - size: 130, - ColumnSelectComponent: (props) => { - const { provinces, errorProvinces, loadingProvinces } = useProvinces(); - const getColumnSelectOptions = useMemo(() => { - if (loadingProvinces) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorProvinces) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: props.column.header }, - ...provinces.map((province) => ({ - value: province.id, - label: province.name_fa, - })), - ]; - }, [provinces, errorProvinces, loadingProvinces]); - return ( - - ); - }, - Cell: ({ renderedCellValue, row }) => <>{row.original.province_fa}, - }; - return [ - { - accessorKey: "id", - header: "کد یکتا", - id: "id", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - ...(hasCountryPermission ? [dynamicColumns] : []), - { - accessorKey: "edare_id", - header: "اداره", - id: "edare_id", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - dependencyId: hasCountryPermission ? "province_id" : null, - grow: false, - size: 120, - ColumnSelectComponent: (props) => { - const { edaratList, loadingEdaratList, errorEdaratList } = useEdaratLists( - hasCountryPermission ? props.dependencyFieldValue.value : user.province_id - ); - const [prevDependency, setPrevDependency] = useState( - hasCountryPermission ? props.dependencyFieldValue.value : user.province_id - ); - - const getColumnSelectOptions = useMemo(() => { - if (hasCountryPermission && props.dependencyFieldValue.value === "") { - return [{ value: "empty", label: "ابتدا استان را انتخاب کنید" }]; - } - if (loadingEdaratList) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorEdaratList) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: props.column.header }, - ...edaratList.map((edare) => ({ - value: edare.id, - label: edare.name_fa, - })), - ]; - }, [edaratList, loadingEdaratList, errorEdaratList]); - useEffect(() => { - if (hasCountryPermission) return; - if (prevDependency === props.dependencyFieldValue?.value) return; - props.handleChange({ ...props.filterParameters, value: "" }); - setPrevDependency(props.dependencyFieldValue?.value); - }, [props.dependencyFieldValue?.value, hasCountryPermission]); - return ( - - ); - }, - Cell: ({ renderedCellValue, row }) => <>{row.original.edare_name}, - }, - { - header: "عملکرد خودرو", - enableColumnFilter: true, - id: "cmmsMachines__machine_code", - datatype: "text", - filterMode: "contains", - columnFilterModeOptions: ["equals", "contains"], - enableSorting: false, - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ row }) => ( - - - - ), - }, - { - accessorKey: "rahdaran", - header: "راهداران", - id: "rahdaran__code", - enableColumnFilter: true, - enableSorting: false, - datatype: "text", - filterMode: "contains", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => - renderedCellValue ? ( - - - - ) : ( - - - ), - }, - { - accessorFn: (row) => moment(row.start_time).locale("fa").format("HH:mm | yyyy/MM/DD"), - header: "تاریخ شروع", - id: "start_time", - enableColumnFilter: true, - datatype: "date", - filterMode: "between", - grow: false, - size: 100, - }, - { - accessorFn: (row) => moment(row.end_time).locale("fa").format("HH:mm | yyyy/MM/DD"), - header: "تاریخ پایان", - id: "end_time", - enableColumnFilter: true, - datatype: "date", - filterMode: "between", - grow: false, - size: 100, - }, - { - accessorFn: (row) => moment(row.created_at).locale("fa").format("HH:mm | yyyy/MM/DD"), - header: "تاریخ ثبت", - id: "created_at", - enableColumnFilter: true, - datatype: "date", - filterMode: "between", - grow: false, - size: 100, - }, - { - accessorKey: "description", - header: "توضیحات مامور", - id: "description", - enableColumnFilter: false, - datatype: "text", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => ( - - - - ), - }, - { - header: "گزارش مامور", - enableColumnFilter: false, - datatype: "text", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ row }) => ( - - - - ), - }, - ]; - }, [hasCountryPermission]); - - return ( - <> - - - - - ); -}; -export default SupervisorList; +"use client"; +import { useEffect, useMemo, useState } from "react"; +import { Box, Stack, Typography } from "@mui/material"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import Toolbar from "./Toolbar"; +import { GET_ROAD_PATROL_SUPERVISOR_LIST } from "@/core/utils/routes"; +import moment from "jalali-moment"; +import RowActions from "./RowActions"; +import useProvinces from "@/lib/hooks/useProvince"; +import CustomSelectByDependency from "@/core/components/DataTable/filter/fieldsType/CustomSelectByDependency"; +import useEdaratLists from "@/lib/hooks/useEdaratLists"; +import OfficerDescriptionForm from "./RowActions/OfficerDescription"; +import ReportForm from "./RowActions/ReportForm"; +import RahdaranDialog from "./RowActions/RahdaranForm"; +import { usePermissions } from "@/lib/hooks/usePermissions"; +import { useAuth } from "@/lib/contexts/auth"; +import MachinePerformanceForm from "./RowActions/MachinePerformanceForm"; + +const SupervisorList = () => { + const { data: userPermissions } = usePermissions(); + const hasCountryPermission = userPermissions?.includes("show-road-patrol-supervise-cartable"); + const { user } = useAuth(); + const columns = useMemo(() => { + const dynamicColumns = { + accessorKey: "province_id", + header: "استان", // Province + id: "province_id", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 130, + ColumnSelectComponent: (props) => { + const { provinces, errorProvinces, loadingProvinces } = useProvinces(); + const getColumnSelectOptions = useMemo(() => { + if (loadingProvinces) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorProvinces) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: props.column.header }, + ...provinces.map((province) => ({ + value: province.id, + label: province.name_fa, + })), + ]; + }, [provinces, errorProvinces, loadingProvinces]); + return ( + + ); + }, + Cell: ({ renderedCellValue, row }) => <>{row.original.province_fa}, + }; + return [ + { + accessorKey: "id", + header: "کد یکتا", + id: "id", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + ...(hasCountryPermission ? [dynamicColumns] : []), + { + accessorKey: "edare_id", + header: "اداره", + id: "edare_id", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + dependencyId: hasCountryPermission ? "province_id" : null, + grow: false, + size: 120, + ColumnSelectComponent: (props) => { + const { edaratList, loadingEdaratList, errorEdaratList } = useEdaratLists( + hasCountryPermission ? props.dependencyFieldValue.value : user.province_id + ); + const [prevDependency, setPrevDependency] = useState( + hasCountryPermission ? props.dependencyFieldValue.value : user.province_id + ); + + const getColumnSelectOptions = useMemo(() => { + if (hasCountryPermission && props.dependencyFieldValue.value === "") { + return [{ value: "empty", label: "ابتدا استان را انتخاب کنید" }]; + } + if (loadingEdaratList) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorEdaratList) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: props.column.header }, + ...edaratList.map((edare) => ({ + value: edare.id, + label: edare.name_fa, + })), + ]; + }, [edaratList, loadingEdaratList, errorEdaratList]); + useEffect(() => { + if (hasCountryPermission) return; + if (prevDependency === props.dependencyFieldValue?.value) return; + props.handleChange({ ...props.filterParameters, value: "" }); + setPrevDependency(props.dependencyFieldValue?.value); + }, [props.dependencyFieldValue?.value, hasCountryPermission]); + return ( + + ); + }, + Cell: ({ renderedCellValue, row }) => <>{row.original.edare_name}, + }, + { + header: "عملکرد خودرو", + enableColumnFilter: true, + id: "cmmsMachines__machine_code", + datatype: "text", + filterMode: "contains", + columnFilterModeOptions: ["equals", "contains"], + enableSorting: false, + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => ( + + + + ), + }, + { + accessorKey: "rahdaran", + header: "راهداران", + id: "rahdaran__code", + enableColumnFilter: true, + enableSorting: false, + datatype: "text", + filterMode: "contains", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => + renderedCellValue ? ( + + + + ) : ( + - + ), + }, + { + accessorFn: (row) => moment(row.start_time).locale("fa").format("HH:mm | yyyy/MM/DD"), + header: "تاریخ شروع", + id: "start_time", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + { + accessorFn: (row) => moment(row.end_time).locale("fa").format("HH:mm | yyyy/MM/DD"), + header: "تاریخ پایان", + id: "end_time", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + { + accessorFn: (row) => moment(row.created_at).locale("fa").format("HH:mm | yyyy/MM/DD"), + header: "تاریخ ثبت", + id: "created_at", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + { + accessorKey: "description", + header: "توضیحات مامور", + id: "description", + enableColumnFilter: false, + datatype: "text", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => ( + + + + ), + }, + { + header: "گزارش مامور", + enableColumnFilter: false, + datatype: "text", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => ( + + + + ), + }, + ]; + }, [hasCountryPermission]); + + return ( + <> + + + + + ); +}; +export default SupervisorList; diff --git a/src/components/dashboard/roadPatrols/supervisor/Toolbar.jsx b/src/components/dashboard/roadPatrols/supervisor/Toolbar.jsx index 32c4395..b62f822 100644 --- a/src/components/dashboard/roadPatrols/supervisor/Toolbar.jsx +++ b/src/components/dashboard/roadPatrols/supervisor/Toolbar.jsx @@ -1,10 +1,10 @@ -import PrintExcel from "./ExcelPrint"; - -const Toolbar = ({ table, filterData }) => { - return ( - <> - - - ); -}; -export default Toolbar; +import PrintExcel from "./ExcelPrint"; + +const Toolbar = ({ table, filterData }) => { + return ( + <> + + + ); +}; +export default Toolbar; diff --git a/src/components/dashboard/roadPatrols/supervisor/index.jsx b/src/components/dashboard/roadPatrols/supervisor/index.jsx index db6a291..5171d6e 100644 --- a/src/components/dashboard/roadPatrols/supervisor/index.jsx +++ b/src/components/dashboard/roadPatrols/supervisor/index.jsx @@ -1,14 +1,14 @@ -"use client"; -import PageTitle from "@/core/components/PageTitle"; -import { Stack } from "@mui/material"; -import SupervisorList from "./SupervisorList"; - -const SupervisorPage = () => { - return ( - - - - - ); -}; -export default SupervisorPage; +"use client"; +import PageTitle from "@/core/components/PageTitle"; +import { Stack } from "@mui/material"; +import SupervisorList from "./SupervisorList"; + +const SupervisorPage = () => { + return ( + + + + + ); +}; +export default SupervisorPage; diff --git a/src/components/dashboard/roadSafety/operator/ExcelPrint/index.jsx b/src/components/dashboard/roadSafety/operator/ExcelPrint/index.jsx index 2970e57..be9ac57 100644 --- a/src/components/dashboard/roadSafety/operator/ExcelPrint/index.jsx +++ b/src/components/dashboard/roadSafety/operator/ExcelPrint/index.jsx @@ -1,74 +1,74 @@ -import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; -import { useMemo, useState } from "react"; -import moment from "jalali-moment"; -import FileSaver from "file-saver"; -import DescriptionIcon from "@mui/icons-material/Description"; -import useRequest from "@/lib/hooks/useRequest"; -import { useTheme } from "@emotion/react"; -import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; -import isArrayEmpty from "@/core/utils/isArrayEmpty"; -import { EXPORT_OPERATOR_ROAD_SAFETY } from "@/core/utils/routes"; - -const PrintExcel = ({ table, filterData }) => { - const [loading, setLoading] = useState(false); - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const requestServer = useRequest(); - const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { - if (filter.value && (!Array.isArray(filter.value) || filter.value.some((item) => item.trim() !== ""))) { - acc.push({ id: key, value: filter.value }); - } - return acc; - }, []); - - const filterParams = useMemo(() => { - const params = new URLSearchParams(); - if (activeFilters.length > 0) { - activeFilters.map((filter, index) => { - const filteredFilterData = DataTableFilterDataStructure(filterData, isArrayEmpty); - params.set("filters", JSON.stringify(filteredFilterData.length === 0 ? [] : filteredFilterData)); - }); - } else { - params.set("filters", JSON.stringify([])); - } - return params; - }, [activeFilters]); - - const clickHandler = () => { - setLoading(true); - requestServer(`${EXPORT_OPERATOR_ROAD_SAFETY}?${filterParams}`, "get", { - requestOptions: { responseType: "blob" }, - }) - .then((response) => { - const filename = `خروجی کارتابل عملیات نگهداری حریم تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; - FileSaver.saveAs(response.data, filename); - }) - .catch(() => {}) - .finally(() => { - setLoading(false); - }); - }; - - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - - ); -}; -export default PrintExcel; +import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; +import { useMemo, useState } from "react"; +import moment from "jalali-moment"; +import FileSaver from "file-saver"; +import DescriptionIcon from "@mui/icons-material/Description"; +import useRequest from "@/lib/hooks/useRequest"; +import { useTheme } from "@emotion/react"; +import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; +import isArrayEmpty from "@/core/utils/isArrayEmpty"; +import { EXPORT_OPERATOR_ROAD_SAFETY } from "@/core/utils/routes"; + +const PrintExcel = ({ table, filterData }) => { + const [loading, setLoading] = useState(false); + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const requestServer = useRequest(); + const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { + if (filter.value && (!Array.isArray(filter.value) || filter.value.some((item) => item.trim() !== ""))) { + acc.push({ id: key, value: filter.value }); + } + return acc; + }, []); + + const filterParams = useMemo(() => { + const params = new URLSearchParams(); + if (activeFilters.length > 0) { + activeFilters.map((filter, index) => { + const filteredFilterData = DataTableFilterDataStructure(filterData, isArrayEmpty); + params.set("filters", JSON.stringify(filteredFilterData.length === 0 ? [] : filteredFilterData)); + }); + } else { + params.set("filters", JSON.stringify([])); + } + return params; + }, [activeFilters]); + + const clickHandler = () => { + setLoading(true); + requestServer(`${EXPORT_OPERATOR_ROAD_SAFETY}?${filterParams}`, "get", { + requestOptions: { responseType: "blob" }, + }) + .then((response) => { + const filename = `خروجی کارتابل عملیات نگهداری حریم تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; + FileSaver.saveAs(response.data, filename); + }) + .catch(() => {}) + .finally(() => { + setLoading(false); + }); + }; + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + + ); +}; +export default PrintExcel; diff --git a/src/components/dashboard/roadSafety/operator/Form/EditAxisType/EditFormContent.jsx b/src/components/dashboard/roadSafety/operator/Form/EditAxisType/EditFormContent.jsx index b42d741..b3c1f0d 100644 --- a/src/components/dashboard/roadSafety/operator/Form/EditAxisType/EditFormContent.jsx +++ b/src/components/dashboard/roadSafety/operator/Form/EditAxisType/EditFormContent.jsx @@ -1,102 +1,102 @@ -import SelectBox from "@/core/components/SelectBox"; -import StyledForm from "@/core/components/StyledForm"; -import { UPDATE_SAFETY_AND_PRIVACY } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { yupResolver } from "@hookform/resolvers/yup"; -import BeenhereIcon from "@mui/icons-material/Beenhere"; -import ExitToAppIcon from "@mui/icons-material/ExitToApp"; -import { Button, DialogActions, DialogContent, Grid, Stack } from "@mui/material"; -import { Controller, useForm } from "react-hook-form"; -import { object, string } from "yup"; - -const validationSchema = object({ - axis_type_id: string().required("نوع محور را مشخص کنید!"), -}); - -const EditFormContent = ({ setOpen, mutate, row }) => { - const requestServer = useRequest({ notificationSuccess: true }); - const defaultValues = { - axis_type_id: row.original.axis_type_id || "", - }; - - const handleClose = () => { - setOpen(false); - }; - - const { - control, - handleSubmit, - formState: { isSubmitting }, - } = useForm({ - defaultValues, - resolver: yupResolver(validationSchema), - mode: "all", - }); - const onSubmitBase = async (data) => { - const formData = new FormData(); - formData.append("axis_type_id", data.axis_type_id); - await requestServer(`${UPDATE_SAFETY_AND_PRIVACY}/${row.original.id}`, "post", { - data: formData, - }) - .then((response) => { - mutate(); - setOpen(false); - }) - .catch((error) => {}); - }; - - return ( - - - - - - ( - - )} - /> - - - - - - - - - - ); -}; -export default EditFormContent; +import SelectBox from "@/core/components/SelectBox"; +import StyledForm from "@/core/components/StyledForm"; +import { UPDATE_SAFETY_AND_PRIVACY } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { yupResolver } from "@hookform/resolvers/yup"; +import BeenhereIcon from "@mui/icons-material/Beenhere"; +import ExitToAppIcon from "@mui/icons-material/ExitToApp"; +import { Button, DialogActions, DialogContent, Grid, Stack } from "@mui/material"; +import { Controller, useForm } from "react-hook-form"; +import { object, string } from "yup"; + +const validationSchema = object({ + axis_type_id: string().required("نوع محور را مشخص کنید!"), +}); + +const EditFormContent = ({ setOpen, mutate, row }) => { + const requestServer = useRequest({ notificationSuccess: true }); + const defaultValues = { + axis_type_id: row.original.axis_type_id || "", + }; + + const handleClose = () => { + setOpen(false); + }; + + const { + control, + handleSubmit, + formState: { isSubmitting }, + } = useForm({ + defaultValues, + resolver: yupResolver(validationSchema), + mode: "all", + }); + const onSubmitBase = async (data) => { + const formData = new FormData(); + formData.append("axis_type_id", data.axis_type_id); + await requestServer(`${UPDATE_SAFETY_AND_PRIVACY}/${row.original.id}`, "post", { + data: formData, + }) + .then((response) => { + mutate(); + setOpen(false); + }) + .catch((error) => {}); + }; + + return ( + + + + + + ( + + )} + /> + + + + + + + + + + ); +}; +export default EditFormContent; diff --git a/src/components/dashboard/roadSafety/operator/Form/EditAxisType/OperatorEditForm.jsx b/src/components/dashboard/roadSafety/operator/Form/EditAxisType/OperatorEditForm.jsx index 34e66e3..2898a36 100644 --- a/src/components/dashboard/roadSafety/operator/Form/EditAxisType/OperatorEditForm.jsx +++ b/src/components/dashboard/roadSafety/operator/Form/EditAxisType/OperatorEditForm.jsx @@ -1,26 +1,26 @@ -import { Dialog, DialogTitle, IconButton } from "@mui/material"; -import CloseIcon from "@mui/icons-material/Close"; -import EditFormContent from "./EditFormContent"; - -const OperatorEditForm = ({ open, setOpen, mutate, row }) => { - return ( - - setOpen(false)} - sx={(theme) => ({ - position: "absolute", - right: 8, - top: 8, - zIndex: 50, - color: theme.palette.grey[500], - })} - > - - - ویرایش محور - {open && } - - ); -}; -export default OperatorEditForm; +import { Dialog, DialogTitle, IconButton } from "@mui/material"; +import CloseIcon from "@mui/icons-material/Close"; +import EditFormContent from "./EditFormContent"; + +const OperatorEditForm = ({ open, setOpen, mutate, row }) => { + return ( + + setOpen(false)} + sx={(theme) => ({ + position: "absolute", + right: 8, + top: 8, + zIndex: 50, + color: theme.palette.grey[500], + })} + > + + + ویرایش محور + {open && } + + ); +}; +export default OperatorEditForm; diff --git a/src/components/dashboard/roadSafety/operator/Form/EditAxisType/index.jsx b/src/components/dashboard/roadSafety/operator/Form/EditAxisType/index.jsx index 7e99d16..5398def 100644 --- a/src/components/dashboard/roadSafety/operator/Form/EditAxisType/index.jsx +++ b/src/components/dashboard/roadSafety/operator/Form/EditAxisType/index.jsx @@ -1,19 +1,19 @@ -import { Dialog, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import EditIcon from "@mui/icons-material/Edit"; -import OperatorEditForm from "./OperatorEditForm"; - -const EditAxisType = ({ row, mutate }) => { - const [openEditDialog, setOpenEditDialog] = useState(false); - return ( - <> - - setOpenEditDialog(true)}> - - - - - - ); -}; -export default EditAxisType; +import { Dialog, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import EditIcon from "@mui/icons-material/Edit"; +import OperatorEditForm from "./OperatorEditForm"; + +const EditAxisType = ({ row, mutate }) => { + const [openEditDialog, setOpenEditDialog] = useState(false); + return ( + <> + + setOpenEditDialog(true)}> + + + + + + ); +}; +export default EditAxisType; diff --git a/src/components/dashboard/roadSafety/operator/Form/StepOne/CreateFormContent.jsx b/src/components/dashboard/roadSafety/operator/Form/StepOne/CreateFormContent.jsx index 69fb689..5d197df 100644 --- a/src/components/dashboard/roadSafety/operator/Form/StepOne/CreateFormContent.jsx +++ b/src/components/dashboard/roadSafety/operator/Form/StepOne/CreateFormContent.jsx @@ -1,155 +1,155 @@ -import React, { useState } from "react"; -import { useForm } from "react-hook-form"; -import { yupResolver } from "@hookform/resolvers/yup"; -import { mixed, number, object, string } from "yup"; -import { Box, Button, DialogActions, DialogContent, Tab, Tabs } from "@mui/material"; -import StyledForm from "@/core/components/StyledForm"; -import InsertDriveFileIcon from "@mui/icons-material/InsertDriveFile"; -import FileCopyIcon from "@mui/icons-material/FileCopy"; -import ExitToAppIcon from "@mui/icons-material/ExitToApp"; -import KeyboardDoubleArrowRightIcon from "@mui/icons-material/KeyboardDoubleArrowRight"; -import BeenhereIcon from "@mui/icons-material/Beenhere"; -import useRequest from "@/lib/hooks/useRequest"; -import GetItemInfo from "./GetItemInfo"; -import GetSubItemInfo from "./GetSubItemInfo"; -import { format } from "date-fns"; -import { FIRST_STEP_STORE } from "@/core/utils/routes"; - -function TabPanel(props) { - const { children, value, index } = props; - return ( - - ); -} - -const validationSchema = object({ - recognize_picture: mixed().nullable().required("لطفا عکس فعالیت را بارگذاری کنید!"), - info_id: number().required("نوع آیتم را مشخص کنید!"), - axis_type_id: string().required("نوع محور را مشخص کنید!"), - start_point: mixed() - .test("start-point-required", "لطفاً نقطه شروع را مشخص کنید!", function (value) { - return !!value; // چک می‌کند که مقدار موجود است - }) - .required("لطفاً نقطه فعالیت را مشخص کنید!"), - activity_time: string().required("لطفا زمان فعالیت را انتخاب کنید!"), - activity_date: string().required("لطفا تاریخ فعالیت را انتخاب کنید!"), -}); - -const CreateFormContent = ({ setOpen, mutate }) => { - const requestServer = useRequest({ notificationSuccess: true }); - const [itemsList, setItemsList] = useState(); - const defaultValues = { - info_id: null, - axis_type_id: "", - recognize_picture: null, - activity_date: "", - activity_time: "", - start_point: "", - }; - - const [tabState, setTabState] = useState(0); - const handleClose = () => { - setOpen(false); - }; - const handleChangeTab = (event, newValue) => { - setTabState(newValue); - }; - - const handlePrev = () => { - if (tabState === 2) { - const fieldsToReset = ["recognize_picture", "activity_time", "activity_date", "start_point"]; - fieldsToReset.forEach((field) => resetField(field)); - } - if (tabState === 0) { - handleClose(); - } else { - setTabState(tabState - 1); - } - }; - const { - control, - handleSubmit, - resetField, - setValue, - formState: { errors, isSubmitting }, - } = useForm({ - defaultValues, - resolver: yupResolver(validationSchema), - mode: "all", - }); - const onSubmitBase = async (data) => { - const startPoint = `${data.start_point.lat},${data.start_point.lng}`; - const formData = new FormData(); - formData.append("activity_date", data.activity_date); - formData.append("activity_time", `${data.activity_time.toString().padStart(2, "0")}:00`); - formData.append("info_id", data.info_id); - formData.append("axis_type_id", data.axis_type_id); - formData.append("recognize_picture", data.recognize_picture); - formData.append("point", startPoint); - await requestServer(FIRST_STEP_STORE, "post", { - data: formData, - hasSidebarUpdate: true, - }) - .then((response) => { - mutate(); - setOpen(false); - }) - .catch((error) => {}); - }; - - return ( - - - } label="انتخاب مورد" /> - } label="اطلاعات مورد مشاهده شده" /> - - - - - - - - - - - - - - {tabState === 1 && ( - - )} - - - ); -}; -export default CreateFormContent; +import React, { useState } from "react"; +import { useForm } from "react-hook-form"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { mixed, number, object, string } from "yup"; +import { Box, Button, DialogActions, DialogContent, Tab, Tabs } from "@mui/material"; +import StyledForm from "@/core/components/StyledForm"; +import InsertDriveFileIcon from "@mui/icons-material/InsertDriveFile"; +import FileCopyIcon from "@mui/icons-material/FileCopy"; +import ExitToAppIcon from "@mui/icons-material/ExitToApp"; +import KeyboardDoubleArrowRightIcon from "@mui/icons-material/KeyboardDoubleArrowRight"; +import BeenhereIcon from "@mui/icons-material/Beenhere"; +import useRequest from "@/lib/hooks/useRequest"; +import GetItemInfo from "./GetItemInfo"; +import GetSubItemInfo from "./GetSubItemInfo"; +import { format } from "date-fns"; +import { FIRST_STEP_STORE } from "@/core/utils/routes"; + +function TabPanel(props) { + const { children, value, index } = props; + return ( + + ); +} + +const validationSchema = object({ + recognize_picture: mixed().nullable().required("لطفا عکس فعالیت را بارگذاری کنید!"), + info_id: number().required("نوع آیتم را مشخص کنید!"), + axis_type_id: string().required("نوع محور را مشخص کنید!"), + start_point: mixed() + .test("start-point-required", "لطفاً نقطه شروع را مشخص کنید!", function (value) { + return !!value; // چک می‌کند که مقدار موجود است + }) + .required("لطفاً نقطه فعالیت را مشخص کنید!"), + activity_time: string().required("لطفا زمان فعالیت را انتخاب کنید!"), + activity_date: string().required("لطفا تاریخ فعالیت را انتخاب کنید!"), +}); + +const CreateFormContent = ({ setOpen, mutate }) => { + const requestServer = useRequest({ notificationSuccess: true }); + const [itemsList, setItemsList] = useState(); + const defaultValues = { + info_id: null, + axis_type_id: "", + recognize_picture: null, + activity_date: "", + activity_time: "", + start_point: "", + }; + + const [tabState, setTabState] = useState(0); + const handleClose = () => { + setOpen(false); + }; + const handleChangeTab = (event, newValue) => { + setTabState(newValue); + }; + + const handlePrev = () => { + if (tabState === 2) { + const fieldsToReset = ["recognize_picture", "activity_time", "activity_date", "start_point"]; + fieldsToReset.forEach((field) => resetField(field)); + } + if (tabState === 0) { + handleClose(); + } else { + setTabState(tabState - 1); + } + }; + const { + control, + handleSubmit, + resetField, + setValue, + formState: { errors, isSubmitting }, + } = useForm({ + defaultValues, + resolver: yupResolver(validationSchema), + mode: "all", + }); + const onSubmitBase = async (data) => { + const startPoint = `${data.start_point.lat},${data.start_point.lng}`; + const formData = new FormData(); + formData.append("activity_date", data.activity_date); + formData.append("activity_time", `${data.activity_time.toString().padStart(2, "0")}:00`); + formData.append("info_id", data.info_id); + formData.append("axis_type_id", data.axis_type_id); + formData.append("recognize_picture", data.recognize_picture); + formData.append("point", startPoint); + await requestServer(FIRST_STEP_STORE, "post", { + data: formData, + hasSidebarUpdate: true, + }) + .then((response) => { + mutate(); + setOpen(false); + }) + .catch((error) => {}); + }; + + return ( + + + } label="انتخاب مورد" /> + } label="اطلاعات مورد مشاهده شده" /> + + + + + + + + + + + + + + {tabState === 1 && ( + + )} + + + ); +}; +export default CreateFormContent; diff --git a/src/components/dashboard/roadSafety/operator/Form/StepOne/GetItemInfo.jsx b/src/components/dashboard/roadSafety/operator/Form/StepOne/GetItemInfo.jsx index ad9ef36..689b726 100644 --- a/src/components/dashboard/roadSafety/operator/Form/StepOne/GetItemInfo.jsx +++ b/src/components/dashboard/roadSafety/operator/Form/StepOne/GetItemInfo.jsx @@ -1,62 +1,62 @@ -import DialogLoading from "@/core/components/DialogLoading"; -import useSafetyAndPrivacyGetItems from "@/lib/hooks/useSafetyAndPrivacyGetItems"; -import { Card, CardActionArea, Grid, Typography } from "@mui/material"; -import { Controller } from "react-hook-form"; - -const GetItemInfo = ({ setItemsList, setTabState, control }) => { - const { itemsList, loadingItemsList, errorItemsList } = useSafetyAndPrivacyGetItems(); - - return ( - <> - {errorItemsList ? ( - - خطا در دریافت لیست آیتم ها - - ) : loadingItemsList ? ( - - ) : ( - - ( - <> - {itemsList.map((item) => ( - - { - field.onChange(item.id); - setItemsList(item); - setTabState(1); - }} - > - - {item.name} - - - - ))} - - )} - /> - - )} - - ); -}; -export default GetItemInfo; +import DialogLoading from "@/core/components/DialogLoading"; +import useSafetyAndPrivacyGetItems from "@/lib/hooks/useSafetyAndPrivacyGetItems"; +import { Card, CardActionArea, Grid, Typography } from "@mui/material"; +import { Controller } from "react-hook-form"; + +const GetItemInfo = ({ setItemsList, setTabState, control }) => { + const { itemsList, loadingItemsList, errorItemsList } = useSafetyAndPrivacyGetItems(); + + return ( + <> + {errorItemsList ? ( + + خطا در دریافت لیست آیتم ها + + ) : loadingItemsList ? ( + + ) : ( + + ( + <> + {itemsList.map((item) => ( + + { + field.onChange(item.id); + setItemsList(item); + setTabState(1); + }} + > + + {item.name} + + + + ))} + + )} + /> + + )} + + ); +}; +export default GetItemInfo; diff --git a/src/components/dashboard/roadSafety/operator/Form/StepOne/GetSubItemInfo.jsx b/src/components/dashboard/roadSafety/operator/Form/StepOne/GetSubItemInfo.jsx index a54b027..1433bcc 100644 --- a/src/components/dashboard/roadSafety/operator/Form/StepOne/GetSubItemInfo.jsx +++ b/src/components/dashboard/roadSafety/operator/Form/StepOne/GetSubItemInfo.jsx @@ -1,126 +1,126 @@ -import HourSelect from "@/core/components/HourSelect"; -import MapInfoOneMarker from "@/core/components/MapInfoOneMarker"; -import MuiDatePicker from "@/core/components/MuiDatePicker"; -import SelectBox from "@/core/components/SelectBox"; -import InsertDriveFileIcon from "@mui/icons-material/InsertDriveFile"; -import { Box, Chip, Divider, Grid, Stack, Typography } from "@mui/material"; -import { Controller, useWatch } from "react-hook-form"; -import ImageUpload from "./ImageUpload"; - -const GetSubItemInfo = ({ itemsList, control, setValue, errors }) => { - const StartPoint = useWatch({ control, name: "start_point" }); - return ( - - - - - - } - label={ - - مورد انتخاب ‌شده - - } - /> - - - - {itemsList?.name || "هیچ آیتمی انتخاب نشده است"} - - - - - - - - ( - - )} - /> - - - - - - - { - return ( - field.onChange(value || [])} - helperText={error ? error.message : null} - /> - ); - }} - name={"activity_date"} - /> - - - { - return ( - - ); - }} - name={"activity_time"} - /> - - - ( - - )} - /> - - - - - - - - ); -}; -export default GetSubItemInfo; +import HourSelect from "@/core/components/HourSelect"; +import MapInfoOneMarker from "@/core/components/MapInfoOneMarker"; +import MuiDatePicker from "@/core/components/MuiDatePicker"; +import SelectBox from "@/core/components/SelectBox"; +import InsertDriveFileIcon from "@mui/icons-material/InsertDriveFile"; +import { Box, Chip, Divider, Grid, Stack, Typography } from "@mui/material"; +import { Controller, useWatch } from "react-hook-form"; +import ImageUpload from "./ImageUpload"; + +const GetSubItemInfo = ({ itemsList, control, setValue, errors }) => { + const StartPoint = useWatch({ control, name: "start_point" }); + return ( + + + + + + } + label={ + + مورد انتخاب ‌شده + + } + /> + + + + {itemsList?.name || "هیچ آیتمی انتخاب نشده است"} + + + + + + + + ( + + )} + /> + + + + + + + { + return ( + field.onChange(value || [])} + helperText={error ? error.message : null} + /> + ); + }} + name={"activity_date"} + /> + + + { + return ( + + ); + }} + name={"activity_time"} + /> + + + ( + + )} + /> + + + + + + + + ); +}; +export default GetSubItemInfo; diff --git a/src/components/dashboard/roadSafety/operator/Form/StepOne/ImageUpload.jsx b/src/components/dashboard/roadSafety/operator/Form/StepOne/ImageUpload.jsx index 5186a4b..7697cfb 100644 --- a/src/components/dashboard/roadSafety/operator/Form/StepOne/ImageUpload.jsx +++ b/src/components/dashboard/roadSafety/operator/Form/StepOne/ImageUpload.jsx @@ -1,77 +1,77 @@ -import { FormControl, FormHelperText } from "@mui/material"; -import UploadSystem from "@/core/components/UploadSystem"; -import React, { useEffect, useState } from "react"; - -const ImageUpload = ({ name, value, onChange, error, title }) => { - const [beforeImg, setBeforeImg] = useState(value ? value : null); - const [beforeFileType, setBeforeFileType] = useState(value ? "image/" : null); - const [beforeFileName, setBeforeFileName] = useState(null); - const [showBeforeImage, setShowBeforeImage] = useState(!value); - - useEffect(() => { - if (value) { - setShowBeforeImage(false); - if (typeof value === "string") { - setBeforeImg(value); - setBeforeFileType("image/"); - } else if (value instanceof File) { - setBeforeImg(URL.createObjectURL(value)); - setBeforeFileType(value.type); - } - } - }, [value]); - - const handleFileChange = (event) => { - const uploadedFile = event.target?.files?.[0]; - if (uploadedFile) { - const fileType = event.target?.files?.[0].type; - const fileName = event.target?.files?.[0].name; - setBeforeImg(URL.createObjectURL(uploadedFile)); - setBeforeFileType(fileType); - setBeforeFileName(fileName); - onChange(uploadedFile); - setShowBeforeImage(false); - } - }; - - return ( - - - {title} - - - {error ? error.message : null} - - ); -}; -export default ImageUpload; +import { FormControl, FormHelperText } from "@mui/material"; +import UploadSystem from "@/core/components/UploadSystem"; +import React, { useEffect, useState } from "react"; + +const ImageUpload = ({ name, value, onChange, error, title }) => { + const [beforeImg, setBeforeImg] = useState(value ? value : null); + const [beforeFileType, setBeforeFileType] = useState(value ? "image/" : null); + const [beforeFileName, setBeforeFileName] = useState(null); + const [showBeforeImage, setShowBeforeImage] = useState(!value); + + useEffect(() => { + if (value) { + setShowBeforeImage(false); + if (typeof value === "string") { + setBeforeImg(value); + setBeforeFileType("image/"); + } else if (value instanceof File) { + setBeforeImg(URL.createObjectURL(value)); + setBeforeFileType(value.type); + } + } + }, [value]); + + const handleFileChange = (event) => { + const uploadedFile = event.target?.files?.[0]; + if (uploadedFile) { + const fileType = event.target?.files?.[0].type; + const fileName = event.target?.files?.[0].name; + setBeforeImg(URL.createObjectURL(uploadedFile)); + setBeforeFileType(fileType); + setBeforeFileName(fileName); + onChange(uploadedFile); + setShowBeforeImage(false); + } + }; + + return ( + + + {title} + + + {error ? error.message : null} + + ); +}; +export default ImageUpload; diff --git a/src/components/dashboard/roadSafety/operator/Form/StepOne/OperatorCreateForm.jsx b/src/components/dashboard/roadSafety/operator/Form/StepOne/OperatorCreateForm.jsx index 44b2828..39cfd2f 100644 --- a/src/components/dashboard/roadSafety/operator/Form/StepOne/OperatorCreateForm.jsx +++ b/src/components/dashboard/roadSafety/operator/Form/StepOne/OperatorCreateForm.jsx @@ -1,26 +1,26 @@ -"use client"; -import { Dialog, IconButton } from "@mui/material"; -import CreateFormContent from "./CreateFormContent"; -import CloseIcon from "@mui/icons-material/Close"; - -const OperatorCreateForm = ({ open, setOpen, mutate }) => { - return ( - - setOpen(false)} - sx={(theme) => ({ - position: "absolute", - right: 8, - top: 8, - zIndex: 50, - color: theme.palette.grey[500], - })} - > - - - {open && } - - ); -}; -export default OperatorCreateForm; +"use client"; +import { Dialog, IconButton } from "@mui/material"; +import CreateFormContent from "./CreateFormContent"; +import CloseIcon from "@mui/icons-material/Close"; + +const OperatorCreateForm = ({ open, setOpen, mutate }) => { + return ( + + setOpen(false)} + sx={(theme) => ({ + position: "absolute", + right: 8, + top: 8, + zIndex: 50, + color: theme.palette.grey[500], + })} + > + + + {open && } + + ); +}; +export default OperatorCreateForm; diff --git a/src/components/dashboard/roadSafety/operator/Form/StepOne/index.jsx b/src/components/dashboard/roadSafety/operator/Form/StepOne/index.jsx index e390936..fbbf7fb 100644 --- a/src/components/dashboard/roadSafety/operator/Form/StepOne/index.jsx +++ b/src/components/dashboard/roadSafety/operator/Form/StepOne/index.jsx @@ -1,36 +1,36 @@ -import { Button, IconButton, useMediaQuery } from "@mui/material"; -import { AddCircle } from "@mui/icons-material"; -import { useTheme } from "@emotion/react"; -import { useState } from "react"; -import OperatorCreateForm from "./OperatorCreateForm"; - -const StepOne = ({ mutate }) => { - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const [open, setOpen] = useState(false); - - const handleOpen = () => { - setOpen(true); - }; - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - - - ); -}; -export default StepOne; +import { Button, IconButton, useMediaQuery } from "@mui/material"; +import { AddCircle } from "@mui/icons-material"; +import { useTheme } from "@emotion/react"; +import { useState } from "react"; +import OperatorCreateForm from "./OperatorCreateForm"; + +const StepOne = ({ mutate }) => { + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const [open, setOpen] = useState(false); + + const handleOpen = () => { + setOpen(true); + }; + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + + + ); +}; +export default StepOne; diff --git a/src/components/dashboard/roadSafety/operator/Form/StepThree/ImageUpload.jsx b/src/components/dashboard/roadSafety/operator/Form/StepThree/ImageUpload.jsx index 5186a4b..7697cfb 100644 --- a/src/components/dashboard/roadSafety/operator/Form/StepThree/ImageUpload.jsx +++ b/src/components/dashboard/roadSafety/operator/Form/StepThree/ImageUpload.jsx @@ -1,77 +1,77 @@ -import { FormControl, FormHelperText } from "@mui/material"; -import UploadSystem from "@/core/components/UploadSystem"; -import React, { useEffect, useState } from "react"; - -const ImageUpload = ({ name, value, onChange, error, title }) => { - const [beforeImg, setBeforeImg] = useState(value ? value : null); - const [beforeFileType, setBeforeFileType] = useState(value ? "image/" : null); - const [beforeFileName, setBeforeFileName] = useState(null); - const [showBeforeImage, setShowBeforeImage] = useState(!value); - - useEffect(() => { - if (value) { - setShowBeforeImage(false); - if (typeof value === "string") { - setBeforeImg(value); - setBeforeFileType("image/"); - } else if (value instanceof File) { - setBeforeImg(URL.createObjectURL(value)); - setBeforeFileType(value.type); - } - } - }, [value]); - - const handleFileChange = (event) => { - const uploadedFile = event.target?.files?.[0]; - if (uploadedFile) { - const fileType = event.target?.files?.[0].type; - const fileName = event.target?.files?.[0].name; - setBeforeImg(URL.createObjectURL(uploadedFile)); - setBeforeFileType(fileType); - setBeforeFileName(fileName); - onChange(uploadedFile); - setShowBeforeImage(false); - } - }; - - return ( - - - {title} - - - {error ? error.message : null} - - ); -}; -export default ImageUpload; +import { FormControl, FormHelperText } from "@mui/material"; +import UploadSystem from "@/core/components/UploadSystem"; +import React, { useEffect, useState } from "react"; + +const ImageUpload = ({ name, value, onChange, error, title }) => { + const [beforeImg, setBeforeImg] = useState(value ? value : null); + const [beforeFileType, setBeforeFileType] = useState(value ? "image/" : null); + const [beforeFileName, setBeforeFileName] = useState(null); + const [showBeforeImage, setShowBeforeImage] = useState(!value); + + useEffect(() => { + if (value) { + setShowBeforeImage(false); + if (typeof value === "string") { + setBeforeImg(value); + setBeforeFileType("image/"); + } else if (value instanceof File) { + setBeforeImg(URL.createObjectURL(value)); + setBeforeFileType(value.type); + } + } + }, [value]); + + const handleFileChange = (event) => { + const uploadedFile = event.target?.files?.[0]; + if (uploadedFile) { + const fileType = event.target?.files?.[0].type; + const fileName = event.target?.files?.[0].name; + setBeforeImg(URL.createObjectURL(uploadedFile)); + setBeforeFileType(fileType); + setBeforeFileName(fileName); + onChange(uploadedFile); + setShowBeforeImage(false); + } + }; + + return ( + + + {title} + + + {error ? error.message : null} + + ); +}; +export default ImageUpload; diff --git a/src/components/dashboard/roadSafety/operator/Form/StepThree/StepThreeContent.jsx b/src/components/dashboard/roadSafety/operator/Form/StepThree/StepThreeContent.jsx index 278d8ca..06cb7ef 100644 --- a/src/components/dashboard/roadSafety/operator/Form/StepThree/StepThreeContent.jsx +++ b/src/components/dashboard/roadSafety/operator/Form/StepThree/StepThreeContent.jsx @@ -1,114 +1,114 @@ -import HourSelect from "@/core/components/HourSelect"; -import MuiDatePicker from "@/core/components/MuiDatePicker"; -import StyledForm from "@/core/components/StyledForm"; -import { THIRD_STEP_STORE } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { yupResolver } from "@hookform/resolvers/yup"; -import { Button, DialogActions, DialogContent, Grid, Stack } from "@mui/material"; -import { Controller, useForm } from "react-hook-form"; -import { mixed, object, string } from "yup"; -import ImageUpload from "./ImageUpload"; - -const StepThreeContent = ({ setOpen, mutate, rowId }) => { - const requestServer = useRequest({ notificationSuccess: true }); - const defaultValues = { - action_date: "", - action_time: "", - action_picture: null, - }; - const validationSchema = object({ - action_date: string().required("لطفا تاریخ اقدام را انتخاب کنید!"), - action_time: string().required("لطفا ساعت اقدام را انتخاب کنید!"), - action_picture: mixed().nullable().required("لطفا عکس اقدام را بارگذاری کنید!"), - }); - const { - control, - handleSubmit, - formState: { isSubmitting }, - } = useForm({ - defaultValues, - resolver: yupResolver(validationSchema), - mode: "all", - }); - const onSubmit = async (data) => { - const formData = new FormData(); - formData.append("action_date", `${data.action_date} ${data.action_time.toString().padStart(2, "0")}:00`); - formData.append("action_picture", data.action_picture); - await requestServer(`${THIRD_STEP_STORE}/${rowId}`, "post", { - data: formData, - hasSidebarUpdate: true, - }) - .then((response) => { - mutate(); - setOpen(false); - }) - .catch((error) => {}); - }; - return ( - - - - - - { - return ( - field.onChange(value || [])} - helperText={error ? error.message : null} - /> - ); - }} - name={"action_date"} - /> - - - { - return ( - - ); - }} - name={"action_time"} - /> - - - ( - - )} - /> - - - - - - - - ); -}; -export default StepThreeContent; +import HourSelect from "@/core/components/HourSelect"; +import MuiDatePicker from "@/core/components/MuiDatePicker"; +import StyledForm from "@/core/components/StyledForm"; +import { THIRD_STEP_STORE } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { Button, DialogActions, DialogContent, Grid, Stack } from "@mui/material"; +import { Controller, useForm } from "react-hook-form"; +import { mixed, object, string } from "yup"; +import ImageUpload from "./ImageUpload"; + +const StepThreeContent = ({ setOpen, mutate, rowId }) => { + const requestServer = useRequest({ notificationSuccess: true }); + const defaultValues = { + action_date: "", + action_time: "", + action_picture: null, + }; + const validationSchema = object({ + action_date: string().required("لطفا تاریخ اقدام را انتخاب کنید!"), + action_time: string().required("لطفا ساعت اقدام را انتخاب کنید!"), + action_picture: mixed().nullable().required("لطفا عکس اقدام را بارگذاری کنید!"), + }); + const { + control, + handleSubmit, + formState: { isSubmitting }, + } = useForm({ + defaultValues, + resolver: yupResolver(validationSchema), + mode: "all", + }); + const onSubmit = async (data) => { + const formData = new FormData(); + formData.append("action_date", `${data.action_date} ${data.action_time.toString().padStart(2, "0")}:00`); + formData.append("action_picture", data.action_picture); + await requestServer(`${THIRD_STEP_STORE}/${rowId}`, "post", { + data: formData, + hasSidebarUpdate: true, + }) + .then((response) => { + mutate(); + setOpen(false); + }) + .catch((error) => {}); + }; + return ( + + + + + + { + return ( + field.onChange(value || [])} + helperText={error ? error.message : null} + /> + ); + }} + name={"action_date"} + /> + + + { + return ( + + ); + }} + name={"action_time"} + /> + + + ( + + )} + /> + + + + + + + + ); +}; +export default StepThreeContent; diff --git a/src/components/dashboard/roadSafety/operator/Form/StepThree/index.jsx b/src/components/dashboard/roadSafety/operator/Form/StepThree/index.jsx index 025222d..8b868c1 100644 --- a/src/components/dashboard/roadSafety/operator/Form/StepThree/index.jsx +++ b/src/components/dashboard/roadSafety/operator/Form/StepThree/index.jsx @@ -1,32 +1,32 @@ -import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import StepThreeContent from "./StepThreeContent"; -import AddPhotoAlternateIcon from "@mui/icons-material/AddPhotoAlternate"; -const StepThree = ({ mutate, rowId }) => { - const [open, setOpen] = useState(false); - return ( - <> - - setOpen(true)}> - - - - setOpen(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"xs"} - fullWidth - > - ثبت اقدام - - - - ); -}; -export default StepThree; +import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import StepThreeContent from "./StepThreeContent"; +import AddPhotoAlternateIcon from "@mui/icons-material/AddPhotoAlternate"; +const StepThree = ({ mutate, rowId }) => { + const [open, setOpen] = useState(false); + return ( + <> + + setOpen(true)}> + + + + setOpen(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"xs"} + fullWidth + > + ثبت اقدام + + + + ); +}; +export default StepThree; diff --git a/src/components/dashboard/roadSafety/operator/Form/StepTwo/ShowDocuments.jsx b/src/components/dashboard/roadSafety/operator/Form/StepTwo/ShowDocuments.jsx index 93958c8..8a68095 100644 --- a/src/components/dashboard/roadSafety/operator/Form/StepTwo/ShowDocuments.jsx +++ b/src/components/dashboard/roadSafety/operator/Form/StepTwo/ShowDocuments.jsx @@ -1,37 +1,37 @@ -import { Box, Card, IconButton, Stack, Typography } from "@mui/material"; -import DeleteIcon from "@mui/icons-material/Delete"; -import React from "react"; -import MinorCrashIcon from "@mui/icons-material/MinorCrash"; - -const ShowDocuments = ({ deleteDamageItem, selectedDamageItem }) => { - return ( - - - - - - {selectedDamageItem.name} - - - - - - deleteDamageItem(selectedDamageItem.name)}> - - - - - ); -}; -export default ShowDocuments; +import { Box, Card, IconButton, Stack, Typography } from "@mui/material"; +import DeleteIcon from "@mui/icons-material/Delete"; +import React from "react"; +import MinorCrashIcon from "@mui/icons-material/MinorCrash"; + +const ShowDocuments = ({ deleteDamageItem, selectedDamageItem }) => { + return ( + + + + + + {selectedDamageItem.name} + + + + + + deleteDamageItem(selectedDamageItem.name)}> + + + + + ); +}; +export default ShowDocuments; diff --git a/src/components/dashboard/roadSafety/operator/Form/StepTwo/StepTwoContent.jsx b/src/components/dashboard/roadSafety/operator/Form/StepTwo/StepTwoContent.jsx index e9d5a6e..bb873ec 100644 --- a/src/components/dashboard/roadSafety/operator/Form/StepTwo/StepTwoContent.jsx +++ b/src/components/dashboard/roadSafety/operator/Form/StepTwo/StepTwoContent.jsx @@ -1,208 +1,208 @@ -import { - Box, - Button, - Chip, - DialogActions, - DialogContent, - Divider, - Fade, - FormControlLabel, - Grid, - Radio, - RadioGroup, - Stack, - TextField, - Typography, -} from "@mui/material"; -import { useEffect, useState } from "react"; -import { Controller, useForm, useWatch } from "react-hook-form"; -import { yupResolver } from "@hookform/resolvers/yup"; -import { mixed, object, string } from "yup"; -import ShowDocuments from "./ShowDocuments"; -import StyledForm from "@/core/components/StyledForm"; -import { SECOND_STEP_STORE } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; - -const StepTwoContent = ({ setOpenStepTwoDialog, mutate, rowId }) => { - const requestServer = useRequest({ notificationSuccess: true }); - const [selectedDamageItemList, setSelectedDamageItemList] = useState([]); - const defaultValues = { - need_judiciary: "0", - operator_description: "", - judiciary_document: null, - }; - const validationSchema = object({ - judiciary_document: mixed().when("need_judiciary", { - is: "1", - then: (schema) => - schema.test("is-array", "لطفا حداقل یک فایل بارگذاری کنید!", (value) => { - return Array.isArray(value) && value.length > 0; - }), - otherwise: (schema) => schema.notRequired(), - }), - operator_description: string().when("need_judiciary", { - is: "0", - then: (schema) => schema.required("لطفا توضیحات را وارد کنید!"), - otherwise: (schema) => schema.notRequired(), - }), - }); - const { - control, - handleSubmit, - setValue, - formState: { isSubmitting }, - } = useForm({ - defaultValues, - resolver: yupResolver(validationSchema), - mode: "all", - }); - const handleCreateDamage = (files) => { - setSelectedDamageItemList((prev) => { - const newFiles = files.filter((file) => !prev.some((item) => item.name === file.name)); - return [...prev, ...newFiles]; - }); - }; - useEffect(() => { - setValue("judiciary_document", selectedDamageItemList); - }, [selectedDamageItemList]); - - const need_judiciary = useWatch({ control, name: "need_judiciary" }); - - const deleteDamageItem = (name) => { - setSelectedDamageItemList((prev) => prev.filter((documentItem) => documentItem.name !== name)); - }; - const onSubmit = async (data) => { - const formData = new FormData(); - formData.append(`need_judiciary`, data.need_judiciary); - if (data.need_judiciary == 1) { - data.judiciary_document.map((item, index) => formData.append(`judiciary_document[${index}]`, item)); - } else { - formData.append(`operator_description`, data.operator_description); - } - await requestServer(`${SECOND_STEP_STORE}/${rowId}`, "post", { - data: formData, - hasSidebarUpdate: true, - }) - .then((response) => { - mutate(); - setOpenStepTwoDialog(false); - }) - .catch((error) => {}); - }; - return ( - - - ( - <> - - } label="بدون مستندات قضایی" /> - } label="دارای مستندات قضایی" /> - - - )} - /> - {need_judiciary == 1 ? ( - <> - - ( - <> - - {error && {error.message}} - - )} - /> - - - - - {selectedDamageItemList.length === 0 && ( - - - فایل موردنظر را بارگذاری کنید. - - - )} - - - {selectedDamageItemList.length !== 0 && - selectedDamageItemList.map((selectedDamageItem, index) => ( - - - - ))} - - - - ) : ( - - ( - - )} - /> - - )} - - - - - - - ); -}; -export default StepTwoContent; +import { + Box, + Button, + Chip, + DialogActions, + DialogContent, + Divider, + Fade, + FormControlLabel, + Grid, + Radio, + RadioGroup, + Stack, + TextField, + Typography, +} from "@mui/material"; +import { useEffect, useState } from "react"; +import { Controller, useForm, useWatch } from "react-hook-form"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { mixed, object, string } from "yup"; +import ShowDocuments from "./ShowDocuments"; +import StyledForm from "@/core/components/StyledForm"; +import { SECOND_STEP_STORE } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; + +const StepTwoContent = ({ setOpenStepTwoDialog, mutate, rowId }) => { + const requestServer = useRequest({ notificationSuccess: true }); + const [selectedDamageItemList, setSelectedDamageItemList] = useState([]); + const defaultValues = { + need_judiciary: "0", + operator_description: "", + judiciary_document: null, + }; + const validationSchema = object({ + judiciary_document: mixed().when("need_judiciary", { + is: "1", + then: (schema) => + schema.test("is-array", "لطفا حداقل یک فایل بارگذاری کنید!", (value) => { + return Array.isArray(value) && value.length > 0; + }), + otherwise: (schema) => schema.notRequired(), + }), + operator_description: string().when("need_judiciary", { + is: "0", + then: (schema) => schema.required("لطفا توضیحات را وارد کنید!"), + otherwise: (schema) => schema.notRequired(), + }), + }); + const { + control, + handleSubmit, + setValue, + formState: { isSubmitting }, + } = useForm({ + defaultValues, + resolver: yupResolver(validationSchema), + mode: "all", + }); + const handleCreateDamage = (files) => { + setSelectedDamageItemList((prev) => { + const newFiles = files.filter((file) => !prev.some((item) => item.name === file.name)); + return [...prev, ...newFiles]; + }); + }; + useEffect(() => { + setValue("judiciary_document", selectedDamageItemList); + }, [selectedDamageItemList]); + + const need_judiciary = useWatch({ control, name: "need_judiciary" }); + + const deleteDamageItem = (name) => { + setSelectedDamageItemList((prev) => prev.filter((documentItem) => documentItem.name !== name)); + }; + const onSubmit = async (data) => { + const formData = new FormData(); + formData.append(`need_judiciary`, data.need_judiciary); + if (data.need_judiciary == 1) { + data.judiciary_document.map((item, index) => formData.append(`judiciary_document[${index}]`, item)); + } else { + formData.append(`operator_description`, data.operator_description); + } + await requestServer(`${SECOND_STEP_STORE}/${rowId}`, "post", { + data: formData, + hasSidebarUpdate: true, + }) + .then((response) => { + mutate(); + setOpenStepTwoDialog(false); + }) + .catch((error) => {}); + }; + return ( + + + ( + <> + + } label="بدون مستندات قضایی" /> + } label="دارای مستندات قضایی" /> + + + )} + /> + {need_judiciary == 1 ? ( + <> + + ( + <> + + {error && {error.message}} + + )} + /> + + + + + {selectedDamageItemList.length === 0 && ( + + + فایل موردنظر را بارگذاری کنید. + + + )} + + + {selectedDamageItemList.length !== 0 && + selectedDamageItemList.map((selectedDamageItem, index) => ( + + + + ))} + + + + ) : ( + + ( + + )} + /> + + )} + + + + + + + ); +}; +export default StepTwoContent; diff --git a/src/components/dashboard/roadSafety/operator/Form/StepTwo/index.jsx b/src/components/dashboard/roadSafety/operator/Form/StepTwo/index.jsx index 5bdfe20..ea06846 100644 --- a/src/components/dashboard/roadSafety/operator/Form/StepTwo/index.jsx +++ b/src/components/dashboard/roadSafety/operator/Form/StepTwo/index.jsx @@ -1,33 +1,33 @@ -import UploadFileIcon from "@mui/icons-material/UploadFile"; -import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import StepTwoContent from "./StepTwoContent"; - -const StepTwo = ({ mutate, rowId }) => { - const [openStepTwoDialog, setOpenStepTwoDialog] = useState(false); - return ( - <> - - setOpenStepTwoDialog(true)}> - - - - setOpenStepTwoDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"sm"} - fullWidth - > - بارگذاری مستندات قضایی - - - - ); -}; -export default StepTwo; +import UploadFileIcon from "@mui/icons-material/UploadFile"; +import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import StepTwoContent from "./StepTwoContent"; + +const StepTwo = ({ mutate, rowId }) => { + const [openStepTwoDialog, setOpenStepTwoDialog] = useState(false); + return ( + <> + + setOpenStepTwoDialog(true)}> + + + + setOpenStepTwoDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"sm"} + fullWidth + > + بارگذاری مستندات قضایی + + + + ); +}; +export default StepTwo; diff --git a/src/components/dashboard/roadSafety/operator/Learn/index.jsx b/src/components/dashboard/roadSafety/operator/Learn/index.jsx index 8db03e7..1c7988b 100644 --- a/src/components/dashboard/roadSafety/operator/Learn/index.jsx +++ b/src/components/dashboard/roadSafety/operator/Learn/index.jsx @@ -1,39 +1,39 @@ -"use client"; -import { useTheme } from "@emotion/react"; -import { OndemandVideo } from "@mui/icons-material"; -import { Button, IconButton, useMediaQuery } from "@mui/material"; - -const Learn = () => { - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - - const handleClick = () => { - const link = document.createElement("a"); - link.href = `/v3/learn-road-safety.mp4`; - link.download = "آموزش بخش نگهداری حریم راه - سامانه جامع راهداری.mp4"; - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - }; - - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - - ); -}; -export default Learn; +"use client"; +import { useTheme } from "@emotion/react"; +import { OndemandVideo } from "@mui/icons-material"; +import { Button, IconButton, useMediaQuery } from "@mui/material"; + +const Learn = () => { + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + + const handleClick = () => { + const link = document.createElement("a"); + link.href = `/v3/learn-road-safety.mp4`; + link.download = "آموزش بخش نگهداری حریم راه - سامانه جامع راهداری.mp4"; + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + }; + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + + ); +}; +export default Learn; diff --git a/src/components/dashboard/roadSafety/operator/OperatorList.jsx b/src/components/dashboard/roadSafety/operator/OperatorList.jsx index 7498e32..27ab825 100644 --- a/src/components/dashboard/roadSafety/operator/OperatorList.jsx +++ b/src/components/dashboard/roadSafety/operator/OperatorList.jsx @@ -1,500 +1,500 @@ -"use client"; -import CustomSelectByDependency from "@/core/components/DataTable/filter/fieldsType/CustomSelectByDependency"; -import DataTableWithAuth from "@/core/components/DataTableWithAuth"; -import { GET_SAFETY_AND_PRIVACY_OPERATOR } from "@/core/utils/routes"; -import useSafetyAndPrivacyGetItems from "@/lib/hooks/useSafetyAndPrivacyGetItems"; -import { Box, Stack } from "@mui/material"; -import moment from "jalali-moment"; -import { useMemo } from "react"; -import RowActions from "./RowActions"; -import ActionPictureDialog from "./RowActions/ActionPictureDialog"; -import DescriptionForm from "./RowActions/DescriptionForm"; -import FinishDescriptionForm from "./RowActions/FinishDescriptionForm"; -import JudiciaryDocumentDialog from "./RowActions/JudiciaryDocumentDialog"; -import LocationForm from "./RowActions/LocationForm"; -import RecognizePictureDialog from "./RowActions/RecognizePictureDialog"; -import Toolbar from "./Toolbar"; -import OperatorDescriptionForm from "./RowActions/OperatorDescriptionForm"; - -const OperatorList = () => { - const stepOptions = [ - { value: "", label: "همه گام ها" }, - { value: 1, label: "گام اول (شناسایی)" }, - { value: 2, label: "گام دوم (مستندات قضایی)" }, - { value: 3, label: "گام سوم (برخورد)" }, - ]; - const statusOptions = [ - { value: "", label: "همه وضعیت ها" }, - { value: 0, label: "درحال بررسی" }, - { value: 1, label: "تایید" }, - { value: 2, label: "عدم تایید" }, - ]; - const finishOptions = [ - { value: "", label: "همه موارد" }, - { value: 0, label: "در جریان" }, - { value: 1, label: "خاتمه یافته" }, - ]; - const axisOptions = [ - { value: "", label: "همه محور ها" }, - { value: 1, label: "آزادراه" }, - { value: 2, label: "بزرگراه" }, - { value: 3, label: "اصلی" }, - { value: 4, label: "فرعی" }, - { value: 5, label: "روستایی" }, - ]; - - const columns = useMemo( - () => [ - { - accessorKey: "id", - header: "کد یکتا", - id: "id", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - header: "اطلاعات فعالیت", - id: "info", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - columns: [ - { - accessorKey: "info_id", - header: "مورد مشاهده شده", - id: "info_id", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - grow: false, - size: 100, - ColumnSelectComponent: (props) => { - const { itemsList, loadingItemsList, errorItemsList } = useSafetyAndPrivacyGetItems(); - - const getColumnSelectOptions = useMemo(() => { - if (loadingItemsList) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorItemsList) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: "همه موارد" }, - ...itemsList.map((item) => ({ - value: item.id, - label: item.name, - })), - ]; - }, [itemsList, loadingItemsList, errorItemsList]); - - return ( - - ); - }, - Cell: ({ row }) => <>{row.original.info_fa}, - }, - { - accessorKey: "axis_type_id", - header: "نوع محور", - id: "axis_type_id", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - sortDescFirst: true, - grow: false, - size: 100, - columnSelectOption: () => { - return axisOptions.map((status) => ({ - value: status.value, - label: status.label, - })); - }, - Cell: ({ row }) => (row.original?.axis_type_name ? <>{row.original.axis_type_name} : <>-), - }, - { - accessorKey: "location", - header: "موقعیت", - id: "location", - enableColumnFilter: false, - enableSorting: false, - datatype: "array", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ row }) => { - return ( - - - - ); - }, - }, - { - accessorFn: (row) => moment(row.created_at).locale("fa").format("HH:mm | yyyy/MM/DD"), - header: "تاریخ ثبت", - id: "created_at", - enableColumnFilter: true, - datatype: "date", - filterMode: "between", - grow: false, - size: 100, - }, - ], - }, - { - header: "وضعیت فعالیت", - id: "allstatus", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - columns: [ - { - header: "وضعیت گام ها", - id: "step", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - sortDescFirst: true, - grow: false, - size: 100, - columnSelectOption: () => { - return stepOptions.map((status) => ({ - value: status.value, - label: status.label, - })); - }, - Cell: ({ row }) => <>{row.original.step_fa}, - }, - { - header: "وضعیت فرایند", - id: "is_finished", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - sortDescFirst: true, - grow: false, - size: 100, - columnSelectOption: () => { - return finishOptions.map((status) => ({ - value: status.value, - label: status.label, - })); - }, - Cell: ({ row }) => ( - <> - {row.original.is_finished == 1 - ? "خاتمه یافته" - : row.original.is_finished == 0 - ? "در جریان" - : "-"} - - ), - }, - { - header: "علت خاتمه فرایند", - id: "finished_description", - enableColumnFilter: false, - datatype: "numeric", - filterMode: "equals", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ row }) => - row.original.final_description ? ( - - - - ) : ( - "-" - ), - }, - { - header: "وضعیت نظارت", - id: "status", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - sortDescFirst: true, - grow: false, - size: 100, - columnSelectOption: () => { - return statusOptions.map((status) => ({ - value: status.value, - label: status.label, - })); - }, - Cell: ({ row }) => <>{row.original.status_fa || "-"}, - }, - { - header: "توضیحات ناظر", - id: "supervisor_description", - enableColumnFilter: false, - datatype: "numeric", - filterMode: "equals", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ row }) => - row.original.supervisor_description ? ( - - - - ) : ( - "-" - ), - }, - ], - }, - { - header: "گام اول (شناسایی)", - id: "stepOne", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - columns: [ - { - accessorKey: "recognize_picture", - header: "تصویر بازدید", - id: "recognize_picture", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return renderedCellValue ? ( - - - - ) : ( - <>- - ); - }, - }, - { - accessorFn: (row) => - row.activity_date_time ? ( - moment(row.activity_date_time).locale("fa").format("HH:mm | yyyy/MM/DD") - ) : ( - <>- - ), - header: "تاریخ بازدید", - id: "activity_date_time", - enableColumnFilter: true, - datatype: "date", - filterMode: "between", - grow: false, - size: 100, - }, - ], - }, - { - header: "گام دوم (مستندات قضایی)", - id: "stepTwo", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - columns: [ - { - header: "مستندات قضایی", - id: "judiciary_document", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ row }) => { - return ( - - {row.original.judiciary_document_upload_date !== "0000-00-00 00:00:00" && - row.original.judiciary_document_upload_date ? ( - - ) : ( - <>- - )} - - ); - }, - }, - { - accessorFn: (row) => { - const date = row.judiciary_document_upload_date; - if (!date || date === "0000-00-00 00:00:00") { - return <>-; - } - return moment(date, "YYYY-MM-DD HH:mm:ss").locale("fa").format("HH:mm | yyyy/MM/DD"); - }, - - header: "تاریخ بارگذاری مستندات", - id: "judiciary_document_upload_date", - enableColumnFilter: true, - datatype: "date", - filterMode: "between", - grow: false, - size: 100, - }, - { - header: "توضیحات کارشناس", - id: "operator_description", - enableColumnFilter: false, - datatype: "numeric", - filterMode: "equals", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ row }) => - row.original.operator_description ? ( - - - - ) : ( - "-" - ), - }, - ], - }, - { - header: "گام سوم (برخورد)", - id: "stepThree", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - columns: [ - { - accessorKey: "action_picture", - header: "تصویر اقدام", - id: "action_picture", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return renderedCellValue ? ( - - - - ) : ( - <>- - ); - }, - }, - { - accessorFn: (row) => - row.action_date ? ( - moment(row.action_date).locale("fa").format("HH:mm | yyyy/MM/DD") - ) : ( - <>- - ), - header: "تاریخ اقدام", - id: "action_date", - enableColumnFilter: true, - datatype: "date", - filterMode: "between", - grow: false, - size: 100, - }, - ], - }, - ], - [] - ); - - return ( - <> - - - - - ); -}; -export default OperatorList; +"use client"; +import CustomSelectByDependency from "@/core/components/DataTable/filter/fieldsType/CustomSelectByDependency"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import { GET_SAFETY_AND_PRIVACY_OPERATOR } from "@/core/utils/routes"; +import useSafetyAndPrivacyGetItems from "@/lib/hooks/useSafetyAndPrivacyGetItems"; +import { Box, Stack } from "@mui/material"; +import moment from "jalali-moment"; +import { useMemo } from "react"; +import RowActions from "./RowActions"; +import ActionPictureDialog from "./RowActions/ActionPictureDialog"; +import DescriptionForm from "./RowActions/DescriptionForm"; +import FinishDescriptionForm from "./RowActions/FinishDescriptionForm"; +import JudiciaryDocumentDialog from "./RowActions/JudiciaryDocumentDialog"; +import LocationForm from "./RowActions/LocationForm"; +import RecognizePictureDialog from "./RowActions/RecognizePictureDialog"; +import Toolbar from "./Toolbar"; +import OperatorDescriptionForm from "./RowActions/OperatorDescriptionForm"; + +const OperatorList = () => { + const stepOptions = [ + { value: "", label: "همه گام ها" }, + { value: 1, label: "گام اول (شناسایی)" }, + { value: 2, label: "گام دوم (مستندات قضایی)" }, + { value: 3, label: "گام سوم (برخورد)" }, + ]; + const statusOptions = [ + { value: "", label: "همه وضعیت ها" }, + { value: 0, label: "درحال بررسی" }, + { value: 1, label: "تایید" }, + { value: 2, label: "عدم تایید" }, + ]; + const finishOptions = [ + { value: "", label: "همه موارد" }, + { value: 0, label: "در جریان" }, + { value: 1, label: "خاتمه یافته" }, + ]; + const axisOptions = [ + { value: "", label: "همه محور ها" }, + { value: 1, label: "آزادراه" }, + { value: 2, label: "بزرگراه" }, + { value: 3, label: "اصلی" }, + { value: 4, label: "فرعی" }, + { value: 5, label: "روستایی" }, + ]; + + const columns = useMemo( + () => [ + { + accessorKey: "id", + header: "کد یکتا", + id: "id", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + header: "اطلاعات فعالیت", + id: "info", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + columns: [ + { + accessorKey: "info_id", + header: "مورد مشاهده شده", + id: "info_id", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 100, + ColumnSelectComponent: (props) => { + const { itemsList, loadingItemsList, errorItemsList } = useSafetyAndPrivacyGetItems(); + + const getColumnSelectOptions = useMemo(() => { + if (loadingItemsList) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorItemsList) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: "همه موارد" }, + ...itemsList.map((item) => ({ + value: item.id, + label: item.name, + })), + ]; + }, [itemsList, loadingItemsList, errorItemsList]); + + return ( + + ); + }, + Cell: ({ row }) => <>{row.original.info_fa}, + }, + { + accessorKey: "axis_type_id", + header: "نوع محور", + id: "axis_type_id", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + sortDescFirst: true, + grow: false, + size: 100, + columnSelectOption: () => { + return axisOptions.map((status) => ({ + value: status.value, + label: status.label, + })); + }, + Cell: ({ row }) => (row.original?.axis_type_name ? <>{row.original.axis_type_name} : <>-), + }, + { + accessorKey: "location", + header: "موقعیت", + id: "location", + enableColumnFilter: false, + enableSorting: false, + datatype: "array", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => { + return ( + + + + ); + }, + }, + { + accessorFn: (row) => moment(row.created_at).locale("fa").format("HH:mm | yyyy/MM/DD"), + header: "تاریخ ثبت", + id: "created_at", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + ], + }, + { + header: "وضعیت فعالیت", + id: "allstatus", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + columns: [ + { + header: "وضعیت گام ها", + id: "step", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + sortDescFirst: true, + grow: false, + size: 100, + columnSelectOption: () => { + return stepOptions.map((status) => ({ + value: status.value, + label: status.label, + })); + }, + Cell: ({ row }) => <>{row.original.step_fa}, + }, + { + header: "وضعیت فرایند", + id: "is_finished", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + sortDescFirst: true, + grow: false, + size: 100, + columnSelectOption: () => { + return finishOptions.map((status) => ({ + value: status.value, + label: status.label, + })); + }, + Cell: ({ row }) => ( + <> + {row.original.is_finished == 1 + ? "خاتمه یافته" + : row.original.is_finished == 0 + ? "در جریان" + : "-"} + + ), + }, + { + header: "علت خاتمه فرایند", + id: "finished_description", + enableColumnFilter: false, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => + row.original.final_description ? ( + + + + ) : ( + "-" + ), + }, + { + header: "وضعیت نظارت", + id: "status", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + sortDescFirst: true, + grow: false, + size: 100, + columnSelectOption: () => { + return statusOptions.map((status) => ({ + value: status.value, + label: status.label, + })); + }, + Cell: ({ row }) => <>{row.original.status_fa || "-"}, + }, + { + header: "توضیحات ناظر", + id: "supervisor_description", + enableColumnFilter: false, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => + row.original.supervisor_description ? ( + + + + ) : ( + "-" + ), + }, + ], + }, + { + header: "گام اول (شناسایی)", + id: "stepOne", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + columns: [ + { + accessorKey: "recognize_picture", + header: "تصویر بازدید", + id: "recognize_picture", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return renderedCellValue ? ( + + + + ) : ( + <>- + ); + }, + }, + { + accessorFn: (row) => + row.activity_date_time ? ( + moment(row.activity_date_time).locale("fa").format("HH:mm | yyyy/MM/DD") + ) : ( + <>- + ), + header: "تاریخ بازدید", + id: "activity_date_time", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + ], + }, + { + header: "گام دوم (مستندات قضایی)", + id: "stepTwo", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + columns: [ + { + header: "مستندات قضایی", + id: "judiciary_document", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => { + return ( + + {row.original.judiciary_document_upload_date !== "0000-00-00 00:00:00" && + row.original.judiciary_document_upload_date ? ( + + ) : ( + <>- + )} + + ); + }, + }, + { + accessorFn: (row) => { + const date = row.judiciary_document_upload_date; + if (!date || date === "0000-00-00 00:00:00") { + return <>-; + } + return moment(date, "YYYY-MM-DD HH:mm:ss").locale("fa").format("HH:mm | yyyy/MM/DD"); + }, + + header: "تاریخ بارگذاری مستندات", + id: "judiciary_document_upload_date", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + { + header: "توضیحات کارشناس", + id: "operator_description", + enableColumnFilter: false, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => + row.original.operator_description ? ( + + + + ) : ( + "-" + ), + }, + ], + }, + { + header: "گام سوم (برخورد)", + id: "stepThree", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + columns: [ + { + accessorKey: "action_picture", + header: "تصویر اقدام", + id: "action_picture", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return renderedCellValue ? ( + + + + ) : ( + <>- + ); + }, + }, + { + accessorFn: (row) => + row.action_date ? ( + moment(row.action_date).locale("fa").format("HH:mm | yyyy/MM/DD") + ) : ( + <>- + ), + header: "تاریخ اقدام", + id: "action_date", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + ], + }, + ], + [] + ); + + return ( + <> + + + + + ); +}; +export default OperatorList; diff --git a/src/components/dashboard/roadSafety/operator/RowActions/ActionPictureDialog/ActionPictureContent.jsx b/src/components/dashboard/roadSafety/operator/RowActions/ActionPictureDialog/ActionPictureContent.jsx index f27255b..26c8143 100644 --- a/src/components/dashboard/roadSafety/operator/RowActions/ActionPictureDialog/ActionPictureContent.jsx +++ b/src/components/dashboard/roadSafety/operator/RowActions/ActionPictureDialog/ActionPictureContent.jsx @@ -1,44 +1,44 @@ -import { Box, Stack, Typography, useTheme } from "@mui/material"; -import Image from "next/image"; - -const ActionPictureContent = ({ image, title }) => { - const theme = useTheme(); - return ( - - - {title} - - - Image - - - ); -}; -export default ActionPictureContent; +import { Box, Stack, Typography, useTheme } from "@mui/material"; +import Image from "next/image"; + +const ActionPictureContent = ({ image, title }) => { + const theme = useTheme(); + return ( + + + {title} + + + Image + + + ); +}; +export default ActionPictureContent; diff --git a/src/components/dashboard/roadSafety/operator/RowActions/ActionPictureDialog/index.jsx b/src/components/dashboard/roadSafety/operator/RowActions/ActionPictureDialog/index.jsx index 4c2911c..79736f4 100644 --- a/src/components/dashboard/roadSafety/operator/RowActions/ActionPictureDialog/index.jsx +++ b/src/components/dashboard/roadSafety/operator/RowActions/ActionPictureDialog/index.jsx @@ -1,40 +1,40 @@ -import PhotoLibraryIcon from "@mui/icons-material/PhotoLibrary"; -import { Button, Dialog, DialogActions, DialogContent, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import ActionPictureContent from "./ActionPictureContent"; - -const ActionPictureDialog = ({ image }) => { - const [openImageDialog, setOpenImageDialog] = useState(false); - - return ( - <> - - setOpenImageDialog(true)}> - - - - setOpenImageDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - maxWidth={"sm"} - scroll="paper" - > - - - - - - - - - ); -}; -export default ActionPictureDialog; +import PhotoLibraryIcon from "@mui/icons-material/PhotoLibrary"; +import { Button, Dialog, DialogActions, DialogContent, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import ActionPictureContent from "./ActionPictureContent"; + +const ActionPictureDialog = ({ image }) => { + const [openImageDialog, setOpenImageDialog] = useState(false); + + return ( + <> + + setOpenImageDialog(true)}> + + + + setOpenImageDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + maxWidth={"sm"} + scroll="paper" + > + + + + + + + + + ); +}; +export default ActionPictureDialog; diff --git a/src/components/dashboard/roadSafety/operator/RowActions/DeleteDialog/DeleteContent.jsx b/src/components/dashboard/roadSafety/operator/RowActions/DeleteDialog/DeleteContent.jsx index bb88f78..ce102ee 100644 --- a/src/components/dashboard/roadSafety/operator/RowActions/DeleteDialog/DeleteContent.jsx +++ b/src/components/dashboard/roadSafety/operator/RowActions/DeleteDialog/DeleteContent.jsx @@ -1,42 +1,42 @@ -import { Button, DialogActions, DialogContent, Stack, Typography } from "@mui/material"; -import React, { useState } from "react"; -import useRequest from "@/lib/hooks/useRequest"; -import { DELETE_SAFETY_AND_PRIVACY } from "@/core/utils/routes"; - -const DeleteContent = ({ rowId, mutate, setOpenDeleteDialog }) => { - const [submitting, setSubmitting] = useState(false); - const requestServer = useRequest({ notificationSuccess: true }); - const handleClick = () => { - setSubmitting(true); - requestServer(`${DELETE_SAFETY_AND_PRIVACY}/${rowId}`, "delete", { - hasSidebarUpdate: true, - }) - .then(() => { - mutate(); - setOpenDeleteDialog(false); - setSubmitting(false); - }) - .catch(() => { - setSubmitting(false); - }); - }; - return ( - <> - - - آیا از حذف فعالیت اطمینان دارید؟ - - - - - - - - ); -}; - -export default DeleteContent; +import { Button, DialogActions, DialogContent, Stack, Typography } from "@mui/material"; +import React, { useState } from "react"; +import useRequest from "@/lib/hooks/useRequest"; +import { DELETE_SAFETY_AND_PRIVACY } from "@/core/utils/routes"; + +const DeleteContent = ({ rowId, mutate, setOpenDeleteDialog }) => { + const [submitting, setSubmitting] = useState(false); + const requestServer = useRequest({ notificationSuccess: true }); + const handleClick = () => { + setSubmitting(true); + requestServer(`${DELETE_SAFETY_AND_PRIVACY}/${rowId}`, "delete", { + hasSidebarUpdate: true, + }) + .then(() => { + mutate(); + setOpenDeleteDialog(false); + setSubmitting(false); + }) + .catch(() => { + setSubmitting(false); + }); + }; + return ( + <> + + + آیا از حذف فعالیت اطمینان دارید؟ + + + + + + + + ); +}; + +export default DeleteContent; diff --git a/src/components/dashboard/roadSafety/operator/RowActions/DeleteDialog/index.jsx b/src/components/dashboard/roadSafety/operator/RowActions/DeleteDialog/index.jsx index 596cf9a..557c628 100644 --- a/src/components/dashboard/roadSafety/operator/RowActions/DeleteDialog/index.jsx +++ b/src/components/dashboard/roadSafety/operator/RowActions/DeleteDialog/index.jsx @@ -1,32 +1,32 @@ -import DeleteIcon from "@mui/icons-material/Delete"; -import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import DeleteContent from "./DeleteContent"; -const DeleteForm = ({ rowId, mutate }) => { - const [openDeleteDialog, setOpenDeleteDialog] = useState(false); - - return ( - <> - - setOpenDeleteDialog(true)}> - - - - setOpenDeleteDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - حذف فعالیت - - - - ); -}; -export default DeleteForm; +import DeleteIcon from "@mui/icons-material/Delete"; +import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import DeleteContent from "./DeleteContent"; +const DeleteForm = ({ rowId, mutate }) => { + const [openDeleteDialog, setOpenDeleteDialog] = useState(false); + + return ( + <> + + setOpenDeleteDialog(true)}> + + + + setOpenDeleteDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + حذف فعالیت + + + + ); +}; +export default DeleteForm; diff --git a/src/components/dashboard/roadSafety/operator/RowActions/DescriptionForm/index.jsx b/src/components/dashboard/roadSafety/operator/RowActions/DescriptionForm/index.jsx index 91b135a..efae7b0 100644 --- a/src/components/dashboard/roadSafety/operator/RowActions/DescriptionForm/index.jsx +++ b/src/components/dashboard/roadSafety/operator/RowActions/DescriptionForm/index.jsx @@ -1,51 +1,51 @@ -import { Dialog, DialogContent, DialogTitle, IconButton, Tooltip, Typography, Card, CardContent } from "@mui/material"; -import { useState } from "react"; -import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye"; -import CloseIcon from "@mui/icons-material/Close"; - -const DescriptionForm = ({ description }) => { - const [openOfficerDescriptionDialog, setOpenOfficerDescriptionDialog] = useState(false); - - return ( - <> - - setOpenOfficerDescriptionDialog(true)}> - - - - setOpenOfficerDescriptionDialog(false)} - PaperProps={{ - sx: { - transition: "all .3s", - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - borderRadius: 2, - padding: 1, - }, - }} - maxWidth="sm" - fullWidth - dir="rtl" - > - - - توضیحات ناظر - - setOpenOfficerDescriptionDialog(false)} size="small"> - - - - - - - {description || "هیچ توضیحی موجود نیست"} - - - - - - ); -}; - -export default DescriptionForm; +import { Dialog, DialogContent, DialogTitle, IconButton, Tooltip, Typography, Card, CardContent } from "@mui/material"; +import { useState } from "react"; +import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye"; +import CloseIcon from "@mui/icons-material/Close"; + +const DescriptionForm = ({ description }) => { + const [openOfficerDescriptionDialog, setOpenOfficerDescriptionDialog] = useState(false); + + return ( + <> + + setOpenOfficerDescriptionDialog(true)}> + + + + setOpenOfficerDescriptionDialog(false)} + PaperProps={{ + sx: { + transition: "all .3s", + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + borderRadius: 2, + padding: 1, + }, + }} + maxWidth="sm" + fullWidth + dir="rtl" + > + + + توضیحات ناظر + + setOpenOfficerDescriptionDialog(false)} size="small"> + + + + + + + {description || "هیچ توضیحی موجود نیست"} + + + + + + ); +}; + +export default DescriptionForm; diff --git a/src/components/dashboard/roadSafety/operator/RowActions/FinishDescriptionForm/index.jsx b/src/components/dashboard/roadSafety/operator/RowActions/FinishDescriptionForm/index.jsx index 6178ae8..a8d63d6 100644 --- a/src/components/dashboard/roadSafety/operator/RowActions/FinishDescriptionForm/index.jsx +++ b/src/components/dashboard/roadSafety/operator/RowActions/FinishDescriptionForm/index.jsx @@ -1,51 +1,51 @@ -import { Dialog, DialogContent, DialogTitle, IconButton, Tooltip, Typography, Card, CardContent } from "@mui/material"; -import { useState } from "react"; -import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye"; -import CloseIcon from "@mui/icons-material/Close"; - -const FinishDescriptionForm = ({ description }) => { - const [openOfficerDescriptionDialog, setOpenOfficerDescriptionDialog] = useState(false); - - return ( - <> - - setOpenOfficerDescriptionDialog(true)}> - - - - setOpenOfficerDescriptionDialog(false)} - PaperProps={{ - sx: { - transition: "all .3s", - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - borderRadius: 2, - padding: 1, - }, - }} - maxWidth="sm" - fullWidth - dir="rtl" - > - - - علت خاتمه فرایند - - setOpenOfficerDescriptionDialog(false)} size="small"> - - - - - - - {description || "هیچ توضیحی موجود نیست"} - - - - - - ); -}; - -export default FinishDescriptionForm; +import { Dialog, DialogContent, DialogTitle, IconButton, Tooltip, Typography, Card, CardContent } from "@mui/material"; +import { useState } from "react"; +import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye"; +import CloseIcon from "@mui/icons-material/Close"; + +const FinishDescriptionForm = ({ description }) => { + const [openOfficerDescriptionDialog, setOpenOfficerDescriptionDialog] = useState(false); + + return ( + <> + + setOpenOfficerDescriptionDialog(true)}> + + + + setOpenOfficerDescriptionDialog(false)} + PaperProps={{ + sx: { + transition: "all .3s", + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + borderRadius: 2, + padding: 1, + }, + }} + maxWidth="sm" + fullWidth + dir="rtl" + > + + + علت خاتمه فرایند + + setOpenOfficerDescriptionDialog(false)} size="small"> + + + + + + + {description || "هیچ توضیحی موجود نیست"} + + + + + + ); +}; + +export default FinishDescriptionForm; diff --git a/src/components/dashboard/roadSafety/operator/RowActions/FinishForm/FinishContent.jsx b/src/components/dashboard/roadSafety/operator/RowActions/FinishForm/FinishContent.jsx index 56e21ea..6a593ad 100644 --- a/src/components/dashboard/roadSafety/operator/RowActions/FinishForm/FinishContent.jsx +++ b/src/components/dashboard/roadSafety/operator/RowActions/FinishForm/FinishContent.jsx @@ -1,80 +1,80 @@ -import { FINISH_ROAD_SAFETY_BY_SUPERVISOR } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { yupResolver } from "@hookform/resolvers/yup"; -import { Button, DialogActions, DialogContent, Stack, TextField } from "@mui/material"; -import { useForm } from "react-hook-form"; -import * as Yup from "yup"; - -const FinishContent = ({ rowId, mutate, setOpenFinishDialog }) => { - const requestServer = useRequest({ notificationSuccess: true }); - - const validationSchema = Yup.object().shape({ - description: Yup.string().required("لطفاً توضیحات را وارد کنید."), - }); - - const { - register, - handleSubmit, - formState: { errors, isSubmitting }, - } = useForm({ - defaultValues: { - description: "", - }, - resolver: yupResolver(validationSchema), - mode: "all", - }); - - const onSubmit = async (data) => { - const formData = new FormData(); - formData.append("final_description", data.description); - requestServer(`${FINISH_ROAD_SAFETY_BY_SUPERVISOR}/${rowId}`, "post", { - data: formData, - hasSidebarUpdate: true, - }) - .then(() => { - mutate(); - setOpenFinishDialog(false); - }) - .catch(() => {}); - }; - - return ( - <> - - - - - - - - - - - - - ); -}; - -export default FinishContent; +import { FINISH_ROAD_SAFETY_BY_SUPERVISOR } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { Button, DialogActions, DialogContent, Stack, TextField } from "@mui/material"; +import { useForm } from "react-hook-form"; +import * as Yup from "yup"; + +const FinishContent = ({ rowId, mutate, setOpenFinishDialog }) => { + const requestServer = useRequest({ notificationSuccess: true }); + + const validationSchema = Yup.object().shape({ + description: Yup.string().required("لطفاً توضیحات را وارد کنید."), + }); + + const { + register, + handleSubmit, + formState: { errors, isSubmitting }, + } = useForm({ + defaultValues: { + description: "", + }, + resolver: yupResolver(validationSchema), + mode: "all", + }); + + const onSubmit = async (data) => { + const formData = new FormData(); + formData.append("final_description", data.description); + requestServer(`${FINISH_ROAD_SAFETY_BY_SUPERVISOR}/${rowId}`, "post", { + data: formData, + hasSidebarUpdate: true, + }) + .then(() => { + mutate(); + setOpenFinishDialog(false); + }) + .catch(() => {}); + }; + + return ( + <> + + + + + + + + + + + + + ); +}; + +export default FinishContent; diff --git a/src/components/dashboard/roadSafety/operator/RowActions/FinishForm/index.jsx b/src/components/dashboard/roadSafety/operator/RowActions/FinishForm/index.jsx index a4340d7..9b5dd8e 100644 --- a/src/components/dashboard/roadSafety/operator/RowActions/FinishForm/index.jsx +++ b/src/components/dashboard/roadSafety/operator/RowActions/FinishForm/index.jsx @@ -1,29 +1,29 @@ -import DoneAllIcon from "@mui/icons-material/DoneAll"; -import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import FinishContent from "./FinishContent"; -const FinishForm = ({ rowId, mutate }) => { - const [openFinishDialog, setOpenFinishDialog] = useState(false); - return ( - <> - - setOpenFinishDialog(true)}> - - - - - خاتمه فرایند - - - - ); -}; -export default FinishForm; +import DoneAllIcon from "@mui/icons-material/DoneAll"; +import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import FinishContent from "./FinishContent"; +const FinishForm = ({ rowId, mutate }) => { + const [openFinishDialog, setOpenFinishDialog] = useState(false); + return ( + <> + + setOpenFinishDialog(true)}> + + + + + خاتمه فرایند + + + + ); +}; +export default FinishForm; diff --git a/src/components/dashboard/roadSafety/operator/RowActions/JudiciaryDocumentDialog/JudiciaryDocumentContent.jsx b/src/components/dashboard/roadSafety/operator/RowActions/JudiciaryDocumentDialog/JudiciaryDocumentContent.jsx index 95a3f1e..8127ada 100644 --- a/src/components/dashboard/roadSafety/operator/RowActions/JudiciaryDocumentDialog/JudiciaryDocumentContent.jsx +++ b/src/components/dashboard/roadSafety/operator/RowActions/JudiciaryDocumentDialog/JudiciaryDocumentContent.jsx @@ -1,43 +1,43 @@ -import { Box, Button, Chip, Divider, Grid, Typography } from "@mui/material"; -import DownloadIcon from "@mui/icons-material/Download"; -import ArticleIcon from "@mui/icons-material/Article"; - -const JudiciaryDocumentContent = ({ judiciaryDocumentDetails }) => { - return ( - - {judiciaryDocumentDetails.map((judiciaryDocument, index) => { - return ( - - - } - label={ - - مستندات قضایی {index + 1} - - } - /> - - - - - ); - })} - - ); -}; -export default JudiciaryDocumentContent; +import { Box, Button, Chip, Divider, Grid, Typography } from "@mui/material"; +import DownloadIcon from "@mui/icons-material/Download"; +import ArticleIcon from "@mui/icons-material/Article"; + +const JudiciaryDocumentContent = ({ judiciaryDocumentDetails }) => { + return ( + + {judiciaryDocumentDetails.map((judiciaryDocument, index) => { + return ( + + + } + label={ + + مستندات قضایی {index + 1} + + } + /> + + + + + ); + })} + + ); +}; +export default JudiciaryDocumentContent; diff --git a/src/components/dashboard/roadSafety/operator/RowActions/JudiciaryDocumentDialog/JudiciaryDocumentController.jsx b/src/components/dashboard/roadSafety/operator/RowActions/JudiciaryDocumentDialog/JudiciaryDocumentController.jsx index 0773130..0d4c245 100644 --- a/src/components/dashboard/roadSafety/operator/RowActions/JudiciaryDocumentDialog/JudiciaryDocumentController.jsx +++ b/src/components/dashboard/roadSafety/operator/RowActions/JudiciaryDocumentDialog/JudiciaryDocumentController.jsx @@ -1,35 +1,35 @@ -import { useEffect, useState } from "react"; -import useRequest from "@/lib/hooks/useRequest"; -import DialogLoading from "@/core/components/DialogLoading"; -import JudiciaryDocumentContent from "./JudiciaryDocumentContent"; -import { DESERIALIZE_JUDICIARY_DOCUMENT } from "@/core/utils/routes"; -import { Typography } from "@mui/material"; - -const JudiciaryDocumentController = ({ rowId }) => { - const requestServer = useRequest(); - const [judiciaryDocumentDetails, setJudiciaryDocumentDetails] = useState([]); - const [judiciaryDocumentDetailsLoading, setJudiciaryDocumentDetailsLoading] = useState(false); - useEffect(() => { - setJudiciaryDocumentDetailsLoading(true); - requestServer(`${DESERIALIZE_JUDICIARY_DOCUMENT}/${rowId}`, "get") - .then((response) => { - setJudiciaryDocumentDetails(response.data.data); - setJudiciaryDocumentDetailsLoading(false); - }) - .catch((e) => { - setJudiciaryDocumentDetailsLoading(false); - }); - }, [rowId]); - return ( - <> - {judiciaryDocumentDetailsLoading ? ( - - ) : judiciaryDocumentDetails.length > 0 ? ( - - ) : ( - بدون مستندات - )} - - ); -}; -export default JudiciaryDocumentController; +import { useEffect, useState } from "react"; +import useRequest from "@/lib/hooks/useRequest"; +import DialogLoading from "@/core/components/DialogLoading"; +import JudiciaryDocumentContent from "./JudiciaryDocumentContent"; +import { DESERIALIZE_JUDICIARY_DOCUMENT } from "@/core/utils/routes"; +import { Typography } from "@mui/material"; + +const JudiciaryDocumentController = ({ rowId }) => { + const requestServer = useRequest(); + const [judiciaryDocumentDetails, setJudiciaryDocumentDetails] = useState([]); + const [judiciaryDocumentDetailsLoading, setJudiciaryDocumentDetailsLoading] = useState(false); + useEffect(() => { + setJudiciaryDocumentDetailsLoading(true); + requestServer(`${DESERIALIZE_JUDICIARY_DOCUMENT}/${rowId}`, "get") + .then((response) => { + setJudiciaryDocumentDetails(response.data.data); + setJudiciaryDocumentDetailsLoading(false); + }) + .catch((e) => { + setJudiciaryDocumentDetailsLoading(false); + }); + }, [rowId]); + return ( + <> + {judiciaryDocumentDetailsLoading ? ( + + ) : judiciaryDocumentDetails.length > 0 ? ( + + ) : ( + بدون مستندات + )} + + ); +}; +export default JudiciaryDocumentController; diff --git a/src/components/dashboard/roadSafety/operator/RowActions/JudiciaryDocumentDialog/index.jsx b/src/components/dashboard/roadSafety/operator/RowActions/JudiciaryDocumentDialog/index.jsx index 575d4c5..d6bbd16 100644 --- a/src/components/dashboard/roadSafety/operator/RowActions/JudiciaryDocumentDialog/index.jsx +++ b/src/components/dashboard/roadSafety/operator/RowActions/JudiciaryDocumentDialog/index.jsx @@ -1,40 +1,40 @@ -import { Button, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import ArticleIcon from "@mui/icons-material/Article"; -import React, { useState } from "react"; -import JudiciaryDocumentController from "./JudiciaryDocumentController"; - -const JudiciaryDocumentDialog = ({ rowId }) => { - const [openJudiciaryDocumentDialog, setOpenJudiciaryDocumentDialog] = useState(false); - return ( - <> - - setOpenJudiciaryDocumentDialog(true)}> - - - - setOpenJudiciaryDocumentDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"sm"} - fullWidth - > - مشاهده مستندات قضایی - - - - - - - - - ); -}; -export default JudiciaryDocumentDialog; +import { Button, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import ArticleIcon from "@mui/icons-material/Article"; +import React, { useState } from "react"; +import JudiciaryDocumentController from "./JudiciaryDocumentController"; + +const JudiciaryDocumentDialog = ({ rowId }) => { + const [openJudiciaryDocumentDialog, setOpenJudiciaryDocumentDialog] = useState(false); + return ( + <> + + setOpenJudiciaryDocumentDialog(true)}> + + + + setOpenJudiciaryDocumentDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"sm"} + fullWidth + > + مشاهده مستندات قضایی + + + + + + + + + ); +}; +export default JudiciaryDocumentDialog; diff --git a/src/components/dashboard/roadSafety/operator/RowActions/LocationForm/LocationFormContent.jsx b/src/components/dashboard/roadSafety/operator/RowActions/LocationForm/LocationFormContent.jsx index 14b3db3..08e4730 100644 --- a/src/components/dashboard/roadSafety/operator/RowActions/LocationForm/LocationFormContent.jsx +++ b/src/components/dashboard/roadSafety/operator/RowActions/LocationForm/LocationFormContent.jsx @@ -1,35 +1,35 @@ -"use client"; -import { Box, Button, DialogActions, DialogContent, Stack } from "@mui/material"; -import React from "react"; -import dynamic from "next/dynamic"; -import MapLoading from "@/core/components/MapLayer/Loading"; -import ShowLocationMarker from "@/core/components/ShowLocationMarker"; -const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { - loading: () => , - ssr: false, -}); - -const LocationFormContent = ({ setOpenLocationDialog, start_lat, start_lng, end_lat, end_lng }) => { - return ( - <> - - - - - - - - - - - - ); -}; -export default LocationFormContent; +"use client"; +import { Box, Button, DialogActions, DialogContent, Stack } from "@mui/material"; +import React from "react"; +import dynamic from "next/dynamic"; +import MapLoading from "@/core/components/MapLayer/Loading"; +import ShowLocationMarker from "@/core/components/ShowLocationMarker"; +const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { + loading: () => , + ssr: false, +}); + +const LocationFormContent = ({ setOpenLocationDialog, start_lat, start_lng, end_lat, end_lng }) => { + return ( + <> + + + + + + + + + + + + ); +}; +export default LocationFormContent; diff --git a/src/components/dashboard/roadSafety/operator/RowActions/LocationForm/index.jsx b/src/components/dashboard/roadSafety/operator/RowActions/LocationForm/index.jsx index d614215..6c90746 100644 --- a/src/components/dashboard/roadSafety/operator/RowActions/LocationForm/index.jsx +++ b/src/components/dashboard/roadSafety/operator/RowActions/LocationForm/index.jsx @@ -1,40 +1,40 @@ -import React, { useState } from "react"; -import { Tooltip, IconButton, Dialog, DialogTitle } from "@mui/material"; -import ExploreIcon from "@mui/icons-material/Explore"; -import LocationFormContent from "./LocationFormContent"; -const LocationForm = ({ start_lat, start_lng, end_lat, end_lng }) => { - const [openLocationDialog, setOpenLocationDialog] = useState(false); - - return ( - <> - - setOpenLocationDialog(true)}> - - - - setOpenLocationDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - موقعیت - {openLocationDialog && ( - - )} - - - ); -}; -export default LocationForm; +import React, { useState } from "react"; +import { Tooltip, IconButton, Dialog, DialogTitle } from "@mui/material"; +import ExploreIcon from "@mui/icons-material/Explore"; +import LocationFormContent from "./LocationFormContent"; +const LocationForm = ({ start_lat, start_lng, end_lat, end_lng }) => { + const [openLocationDialog, setOpenLocationDialog] = useState(false); + + return ( + <> + + setOpenLocationDialog(true)}> + + + + setOpenLocationDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + موقعیت + {openLocationDialog && ( + + )} + + + ); +}; +export default LocationForm; diff --git a/src/components/dashboard/roadSafety/operator/RowActions/OperatorDescriptionForm/index.jsx b/src/components/dashboard/roadSafety/operator/RowActions/OperatorDescriptionForm/index.jsx index 9a59745..f446b9d 100644 --- a/src/components/dashboard/roadSafety/operator/RowActions/OperatorDescriptionForm/index.jsx +++ b/src/components/dashboard/roadSafety/operator/RowActions/OperatorDescriptionForm/index.jsx @@ -1,51 +1,51 @@ -import { Dialog, DialogContent, DialogTitle, IconButton, Tooltip, Typography, Card, CardContent } from "@mui/material"; -import { useState } from "react"; -import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye"; -import CloseIcon from "@mui/icons-material/Close"; - -const OperatorDescriptionForm = ({ description }) => { - const [openOfficerDescriptionDialog, setOpenOfficerDescriptionDialog] = useState(false); - - return ( - <> - - setOpenOfficerDescriptionDialog(true)}> - - - - setOpenOfficerDescriptionDialog(false)} - PaperProps={{ - sx: { - transition: "all .3s", - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - borderRadius: 2, - padding: 1, - }, - }} - maxWidth="sm" - fullWidth - dir="rtl" - > - - - توضیحات کارشناس - - setOpenOfficerDescriptionDialog(false)} size="small"> - - - - - - - {description || "هیچ توضیحی موجود نیست"} - - - - - - ); -}; - -export default OperatorDescriptionForm; +import { Dialog, DialogContent, DialogTitle, IconButton, Tooltip, Typography, Card, CardContent } from "@mui/material"; +import { useState } from "react"; +import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye"; +import CloseIcon from "@mui/icons-material/Close"; + +const OperatorDescriptionForm = ({ description }) => { + const [openOfficerDescriptionDialog, setOpenOfficerDescriptionDialog] = useState(false); + + return ( + <> + + setOpenOfficerDescriptionDialog(true)}> + + + + setOpenOfficerDescriptionDialog(false)} + PaperProps={{ + sx: { + transition: "all .3s", + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + borderRadius: 2, + padding: 1, + }, + }} + maxWidth="sm" + fullWidth + dir="rtl" + > + + + توضیحات کارشناس + + setOpenOfficerDescriptionDialog(false)} size="small"> + + + + + + + {description || "هیچ توضیحی موجود نیست"} + + + + + + ); +}; + +export default OperatorDescriptionForm; diff --git a/src/components/dashboard/roadSafety/operator/RowActions/RecognizePictureDialog/RecognizePictureContent.jsx b/src/components/dashboard/roadSafety/operator/RowActions/RecognizePictureDialog/RecognizePictureContent.jsx index 39dbdcf..a50191f 100644 --- a/src/components/dashboard/roadSafety/operator/RowActions/RecognizePictureDialog/RecognizePictureContent.jsx +++ b/src/components/dashboard/roadSafety/operator/RowActions/RecognizePictureDialog/RecognizePictureContent.jsx @@ -1,44 +1,44 @@ -import { Box, Stack, Typography, useTheme } from "@mui/material"; -import Image from "next/image"; - -const RecognizePictureContent = ({ image, title }) => { - const theme = useTheme(); - return ( - - - {title} - - - Image - - - ); -}; -export default RecognizePictureContent; +import { Box, Stack, Typography, useTheme } from "@mui/material"; +import Image from "next/image"; + +const RecognizePictureContent = ({ image, title }) => { + const theme = useTheme(); + return ( + + + {title} + + + Image + + + ); +}; +export default RecognizePictureContent; diff --git a/src/components/dashboard/roadSafety/operator/RowActions/RecognizePictureDialog/index.jsx b/src/components/dashboard/roadSafety/operator/RowActions/RecognizePictureDialog/index.jsx index 72ef4ea..f51e501 100644 --- a/src/components/dashboard/roadSafety/operator/RowActions/RecognizePictureDialog/index.jsx +++ b/src/components/dashboard/roadSafety/operator/RowActions/RecognizePictureDialog/index.jsx @@ -1,40 +1,40 @@ -import PhotoLibraryIcon from "@mui/icons-material/PhotoLibrary"; -import { Button, Dialog, DialogActions, DialogContent, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import RecognizePictureContent from "./RecognizePictureContent"; - -const RecognizePictureDialog = ({ image }) => { - const [openImageDialog, setOpenImageDialog] = useState(false); - - return ( - <> - - setOpenImageDialog(true)}> - - - - setOpenImageDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - maxWidth={"sm"} - scroll="paper" - > - - - - - - - - - ); -}; -export default RecognizePictureDialog; +import PhotoLibraryIcon from "@mui/icons-material/PhotoLibrary"; +import { Button, Dialog, DialogActions, DialogContent, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import RecognizePictureContent from "./RecognizePictureContent"; + +const RecognizePictureDialog = ({ image }) => { + const [openImageDialog, setOpenImageDialog] = useState(false); + + return ( + <> + + setOpenImageDialog(true)}> + + + + setOpenImageDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + maxWidth={"sm"} + scroll="paper" + > + + + + + + + + + ); +}; +export default RecognizePictureDialog; diff --git a/src/components/dashboard/roadSafety/operator/RowActions/index.jsx b/src/components/dashboard/roadSafety/operator/RowActions/index.jsx index 8b3344b..0ccc2bb 100644 --- a/src/components/dashboard/roadSafety/operator/RowActions/index.jsx +++ b/src/components/dashboard/roadSafety/operator/RowActions/index.jsx @@ -1,27 +1,27 @@ -import { usePermissions } from "@/lib/hooks/usePermissions"; -import { Box } from "@mui/material"; -import EditAxisType from "../Form/EditAxisType"; -import StepThree from "../Form/StepThree"; -import StepTwo from "../Form/StepTwo"; -import DeleteForm from "./DeleteDialog"; -import FinishForm from "./FinishForm"; - -const RowActions = ({ row, mutate }) => { - const { data: userPermissions } = usePermissions(); - const hasDeletePermission = userPermissions?.includes("delete-safety-and-privacy"); - const hasUpdatePermission = userPermissions?.includes("update-safety-and-privacy"); - return ( - - {hasUpdatePermission && row.original?.axis_type_id == null && } - {!row.original.is_finished && ( - <> - {row.original?.step === 1 && } - {row.original?.step === 2 && } - - - )} - {hasDeletePermission && } - - ); -}; -export default RowActions; +import { usePermissions } from "@/lib/hooks/usePermissions"; +import { Box } from "@mui/material"; +import EditAxisType from "../Form/EditAxisType"; +import StepThree from "../Form/StepThree"; +import StepTwo from "../Form/StepTwo"; +import DeleteForm from "./DeleteDialog"; +import FinishForm from "./FinishForm"; + +const RowActions = ({ row, mutate }) => { + const { data: userPermissions } = usePermissions(); + const hasDeletePermission = userPermissions?.includes("delete-safety-and-privacy"); + const hasUpdatePermission = userPermissions?.includes("update-safety-and-privacy"); + return ( + + {hasUpdatePermission && row.original?.axis_type_id == null && } + {!row.original.is_finished && ( + <> + {row.original?.step === 1 && } + {row.original?.step === 2 && } + + + )} + {hasDeletePermission && } + + ); +}; +export default RowActions; diff --git a/src/components/dashboard/roadSafety/operator/Toolbar.jsx b/src/components/dashboard/roadSafety/operator/Toolbar.jsx index 0f96d53..a3504ce 100644 --- a/src/components/dashboard/roadSafety/operator/Toolbar.jsx +++ b/src/components/dashboard/roadSafety/operator/Toolbar.jsx @@ -1,18 +1,18 @@ -import { Stack } from "@mui/material"; -import StepOne from "./Form/StepOne"; -import PrintExcel from "./ExcelPrint"; -import { usePermissions } from "@/lib/hooks/usePermissions"; -import Learn from "./Learn"; - -const Toolbar = ({ table, filterData, mutate }) => { - const { data: userPermissions } = usePermissions(); - const hasCreatePermission = userPermissions?.includes("add-safety-and-privacy"); - return ( - - - {hasCreatePermission && } - - - ); -}; -export default Toolbar; +import { Stack } from "@mui/material"; +import StepOne from "./Form/StepOne"; +import PrintExcel from "./ExcelPrint"; +import { usePermissions } from "@/lib/hooks/usePermissions"; +import Learn from "./Learn"; + +const Toolbar = ({ table, filterData, mutate }) => { + const { data: userPermissions } = usePermissions(); + const hasCreatePermission = userPermissions?.includes("add-safety-and-privacy"); + return ( + + + {hasCreatePermission && } + + + ); +}; +export default Toolbar; diff --git a/src/components/dashboard/roadSafety/operator/index.jsx b/src/components/dashboard/roadSafety/operator/index.jsx index 74badaf..7522933 100644 --- a/src/components/dashboard/roadSafety/operator/index.jsx +++ b/src/components/dashboard/roadSafety/operator/index.jsx @@ -1,14 +1,14 @@ -"use client"; -import PageTitle from "@/core/components/PageTitle"; -import { Stack } from "@mui/material"; -import OperatorList from "./OperatorList"; - -const OperatorPage = () => { - return ( - - - - - ); -}; -export default OperatorPage; +"use client"; +import PageTitle from "@/core/components/PageTitle"; +import { Stack } from "@mui/material"; +import OperatorList from "./OperatorList"; + +const OperatorPage = () => { + return ( + + + + + ); +}; +export default OperatorPage; diff --git a/src/components/dashboard/roadSafety/reports/map/ClusterSwitch/index.jsx b/src/components/dashboard/roadSafety/reports/map/ClusterSwitch/index.jsx index e8fac87..29312eb 100644 --- a/src/components/dashboard/roadSafety/reports/map/ClusterSwitch/index.jsx +++ b/src/components/dashboard/roadSafety/reports/map/ClusterSwitch/index.jsx @@ -1,25 +1,25 @@ -import DoneIcon from "@mui/icons-material/Done"; -import { Chip, Tooltip, Zoom } from "@mui/material"; - -const ClusterSwitch = ({ isCluster, setCluster, disabled, max }) => { - return ( - - - setCluster((c) => !c)} - sx={{ borderRadius: 1 }} - icon={ - - - - } - /> - - - ); -}; -export default ClusterSwitch; +import DoneIcon from "@mui/icons-material/Done"; +import { Chip, Tooltip, Zoom } from "@mui/material"; + +const ClusterSwitch = ({ isCluster, setCluster, disabled, max }) => { + return ( + + + setCluster((c) => !c)} + sx={{ borderRadius: 1 }} + icon={ + + + + } + /> + + + ); +}; +export default ClusterSwitch; diff --git a/src/components/dashboard/roadSafety/reports/map/Filter/index.jsx b/src/components/dashboard/roadSafety/reports/map/Filter/index.jsx index 3cbbe5d..7fdcacb 100644 --- a/src/components/dashboard/roadSafety/reports/map/Filter/index.jsx +++ b/src/components/dashboard/roadSafety/reports/map/Filter/index.jsx @@ -1,44 +1,44 @@ -"use client"; -import { Box, Button, Drawer } from "@mui/material"; -import FilterListIcon from "@mui/icons-material/FilterList"; -import { useCallback, useState } from "react"; -import FilterDrawer from "@/core/components/FilterDrawer"; - -const drawerSx = { - overflowY: "hidden", - display: "flex", - flexDirection: "column", - height: "100%", - zIndex: "1300", -}; - -const boxSx = { - width: { xs: 300, sm: 450 }, -}; - -const Filter = ({ filterData, setFilterData }) => { - const [open, setOpen] = useState(false); - - const openDrawer = useCallback(() => setOpen(true), []); - const closeDrawer = useCallback(() => setOpen(false), []); - - return ( - <> - - - - {open && ( - - )} - - - - ); -}; -export default Filter; +"use client"; +import { Box, Button, Drawer } from "@mui/material"; +import FilterListIcon from "@mui/icons-material/FilterList"; +import { useCallback, useState } from "react"; +import FilterDrawer from "@/core/components/FilterDrawer"; + +const drawerSx = { + overflowY: "hidden", + display: "flex", + flexDirection: "column", + height: "100%", + zIndex: "1300", +}; + +const boxSx = { + width: { xs: 300, sm: 450 }, +}; + +const Filter = ({ filterData, setFilterData }) => { + const [open, setOpen] = useState(false); + + const openDrawer = useCallback(() => setOpen(true), []); + const closeDrawer = useCallback(() => setOpen(false), []); + + return ( + <> + + + + {open && ( + + )} + + + + ); +}; +export default Filter; diff --git a/src/components/dashboard/roadSafety/reports/map/Legend/index.jsx b/src/components/dashboard/roadSafety/reports/map/Legend/index.jsx index 91bc710..3ce26d8 100644 --- a/src/components/dashboard/roadSafety/reports/map/Legend/index.jsx +++ b/src/components/dashboard/roadSafety/reports/map/Legend/index.jsx @@ -1,48 +1,48 @@ -import { Box, Stack, Typography } from "@mui/material"; - -const Legend = () => { - return ( - - - theme.palette.warning.main, - background: (theme) => theme.palette.warning.light, - }} - /> - گام اول (شناسایی) - - - theme.palette.error.main, - background: (theme) => theme.palette.error.light, - }} - /> - گام دوم (مستندات قضایی) - - - theme.palette.success.main, - background: (theme) => theme.palette.success.light, - }} - /> - گام سوم (برخورد) - - - ); -}; -export default Legend; +import { Box, Stack, Typography } from "@mui/material"; + +const Legend = () => { + return ( + + + theme.palette.warning.main, + background: (theme) => theme.palette.warning.light, + }} + /> + گام اول (شناسایی) + + + theme.palette.error.main, + background: (theme) => theme.palette.error.light, + }} + /> + گام دوم (مستندات قضایی) + + + theme.palette.success.main, + background: (theme) => theme.palette.success.light, + }} + /> + گام سوم (برخورد) + + + ); +}; +export default Legend; diff --git a/src/components/dashboard/roadSafety/reports/map/PointsOnMap/DialogInfoItem/ContentInfoItem.jsx b/src/components/dashboard/roadSafety/reports/map/PointsOnMap/DialogInfoItem/ContentInfoItem.jsx index 58064a2..eca6f82 100644 --- a/src/components/dashboard/roadSafety/reports/map/PointsOnMap/DialogInfoItem/ContentInfoItem.jsx +++ b/src/components/dashboard/roadSafety/reports/map/PointsOnMap/DialogInfoItem/ContentInfoItem.jsx @@ -1,104 +1,104 @@ -import { Box, Chip, Divider, Stack, Typography } from "@mui/material"; -import moment from "jalali-moment"; -import Image from "next/image"; - -const ContentInfoItem = ({ data }) => { - return ( - - - - - {data.id !== "" && data.id} - - - - - - {data.province_fa !== "" && data.province_fa} - - - - - - - {data.edare_shahri_name !== "" && data.edare_shahri_name} - - - - - - - {data.info_fa !== "" && data.info_fa} - - - - - - - {data.axis_type_name !== "" && data.axis_type_name} - - - - - - - {data.step_fa !== "" && data.step_fa} - - - - - - - {data.activity_date_time && - moment(data.activity_date_time).locale("fa").format("HH:mm | yyyy/MM/DD")} - - - {data.step == 3 && ( - - - - - {data.action_date && moment(data.action_date).locale("fa").format("HH:mm | yyyy/MM/DD")} - - - )} - - - - - recognize_picture - - - {data.step == 3 && ( - - - - action_picture - - - )} - - - ); -}; -export default ContentInfoItem; +import { Box, Chip, Divider, Stack, Typography } from "@mui/material"; +import moment from "jalali-moment"; +import Image from "next/image"; + +const ContentInfoItem = ({ data }) => { + return ( + + + + + {data.id !== "" && data.id} + + + + + + {data.province_fa !== "" && data.province_fa} + + + + + + + {data.edare_shahri_name !== "" && data.edare_shahri_name} + + + + + + + {data.info_fa !== "" && data.info_fa} + + + + + + + {data.axis_type_name !== "" && data.axis_type_name} + + + + + + + {data.step_fa !== "" && data.step_fa} + + + + + + + {data.activity_date_time && + moment(data.activity_date_time).locale("fa").format("HH:mm | yyyy/MM/DD")} + + + {data.step == 3 && ( + + + + + {data.action_date && moment(data.action_date).locale("fa").format("HH:mm | yyyy/MM/DD")} + + + )} + + + + + recognize_picture + + + {data.step == 3 && ( + + + + action_picture + + + )} + + + ); +}; +export default ContentInfoItem; diff --git a/src/components/dashboard/roadSafety/reports/map/PointsOnMap/DialogInfoItem/index.jsx b/src/components/dashboard/roadSafety/reports/map/PointsOnMap/DialogInfoItem/index.jsx index 3107c53..758cb8c 100644 --- a/src/components/dashboard/roadSafety/reports/map/PointsOnMap/DialogInfoItem/index.jsx +++ b/src/components/dashboard/roadSafety/reports/map/PointsOnMap/DialogInfoItem/index.jsx @@ -1,51 +1,51 @@ -import DialogLoading from "@/core/components/DialogLoading"; -import { GET_ROAD_SAFETY_DETAILS } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { Button, DialogActions, DialogContent, DialogTitle } from "@mui/material"; -import { useEffect, useState } from "react"; -import ContentInfoItem from "./ContentInfoItem"; - -const DialogInfoItem = ({ selectedId, closeDialog }) => { - const request = useRequest(); - const [loading, setLoading] = useState(true); - const [data, setData] = useState(null); - - useEffect(() => { - const controller = new AbortController(); - - const fetchItem = async () => { - setLoading(true); - setData(null); - try { - const response = await request(`${GET_ROAD_SAFETY_DETAILS}/${selectedId}`, "get", { - signal: controller.signal, - }); - setData(response.data.data); - } catch (error) { - } finally { - setLoading(false); - } - }; - - fetchItem(); - - return () => { - controller.abort(); - }; - }, [selectedId]); - - return ( - <> - جزئیات فعالیت - - {loading ? : data && } - - - - - - ); -}; -export default DialogInfoItem; +import DialogLoading from "@/core/components/DialogLoading"; +import { GET_ROAD_SAFETY_DETAILS } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { Button, DialogActions, DialogContent, DialogTitle } from "@mui/material"; +import { useEffect, useState } from "react"; +import ContentInfoItem from "./ContentInfoItem"; + +const DialogInfoItem = ({ selectedId, closeDialog }) => { + const request = useRequest(); + const [loading, setLoading] = useState(true); + const [data, setData] = useState(null); + + useEffect(() => { + const controller = new AbortController(); + + const fetchItem = async () => { + setLoading(true); + setData(null); + try { + const response = await request(`${GET_ROAD_SAFETY_DETAILS}/${selectedId}`, "get", { + signal: controller.signal, + }); + setData(response.data.data); + } catch (error) { + } finally { + setLoading(false); + } + }; + + fetchItem(); + + return () => { + controller.abort(); + }; + }, [selectedId]); + + return ( + <> + جزئیات فعالیت + + {loading ? : data && } + + + + + + ); +}; +export default DialogInfoItem; diff --git a/src/components/dashboard/roadSafety/reports/map/PointsOnMap/index.jsx b/src/components/dashboard/roadSafety/reports/map/PointsOnMap/index.jsx index b965bda..d016ff7 100644 --- a/src/components/dashboard/roadSafety/reports/map/PointsOnMap/index.jsx +++ b/src/components/dashboard/roadSafety/reports/map/PointsOnMap/index.jsx @@ -1,71 +1,71 @@ -import { Dialog, useTheme } from "@mui/material"; -import { useCallback, useEffect, useMemo, useState } from "react"; -import { CircleMarker, useMap } from "react-leaflet"; -import MarkerClusterGroup from "react-leaflet-markercluster"; -import DialogInfoItem from "./DialogInfoItem"; - -const PointsOnMap = ({ data, isCluster }) => { - const map = useMap(); - const theme = useTheme(); - const [selectedId, setSelectedId] = useState(null); - const [open, setOpen] = useState(false); - - const openDialog = useCallback(() => setOpen(true), []); - const closeDialog = useCallback(() => setOpen(false), []); - - const getMarkerColor = (status) => { - if (status === 1) return theme.palette.warning.main; - if (status === 2) return theme.palette.error.main; - return theme.palette.success.main; - }; - - const markers = useMemo(() => { - return data.map(({ id, lat, lon, step }) => ( - { - openDialog(); - setSelectedId(id); - }, - }} - key={id} - center={L.latLng(lat, lon)} - radius={8} - color={getMarkerColor(step)} - /> - )); - }, [data, theme]); - - useEffect(() => { - if (data.length === 0) return; - const bounds = L.latLngBounds(data.map(({ lat, lon }) => L.latLng(lat, lon))); - map.flyToBounds(bounds, { duration: 0.7 }); - }, [data]); - - const createClusterCustomIcon = (cluster) => { - const count = cluster.getChildCount(); - return L.divIcon({ - html: `
    ${count}
    `, - className: "custom-marker-cluster", - iconSize: L.point(40, 40, true), - }); - }; - - if (data.length === 0) return null; - - return ( - <> - {isCluster ? ( - - {markers} - - ) : ( - markers - )} - - {open && } - - - ); -}; -export default PointsOnMap; +import { Dialog, useTheme } from "@mui/material"; +import { useCallback, useEffect, useMemo, useState } from "react"; +import { CircleMarker, useMap } from "react-leaflet"; +import MarkerClusterGroup from "react-leaflet-markercluster"; +import DialogInfoItem from "./DialogInfoItem"; + +const PointsOnMap = ({ data, isCluster }) => { + const map = useMap(); + const theme = useTheme(); + const [selectedId, setSelectedId] = useState(null); + const [open, setOpen] = useState(false); + + const openDialog = useCallback(() => setOpen(true), []); + const closeDialog = useCallback(() => setOpen(false), []); + + const getMarkerColor = (status) => { + if (status === 1) return theme.palette.warning.main; + if (status === 2) return theme.palette.error.main; + return theme.palette.success.main; + }; + + const markers = useMemo(() => { + return data.map(({ id, lat, lon, step }) => ( + { + openDialog(); + setSelectedId(id); + }, + }} + key={id} + center={L.latLng(lat, lon)} + radius={8} + color={getMarkerColor(step)} + /> + )); + }, [data, theme]); + + useEffect(() => { + if (data.length === 0) return; + const bounds = L.latLngBounds(data.map(({ lat, lon }) => L.latLng(lat, lon))); + map.flyToBounds(bounds, { duration: 0.7 }); + }, [data]); + + const createClusterCustomIcon = (cluster) => { + const count = cluster.getChildCount(); + return L.divIcon({ + html: `
    ${count}
    `, + className: "custom-marker-cluster", + iconSize: L.point(40, 40, true), + }); + }; + + if (data.length === 0) return null; + + return ( + <> + {isCluster ? ( + + {markers} + + ) : ( + markers + )} + + {open && } + + + ); +}; +export default PointsOnMap; diff --git a/src/components/dashboard/roadSafety/reports/map/index.jsx b/src/components/dashboard/roadSafety/reports/map/index.jsx index 91c0979..a623052 100644 --- a/src/components/dashboard/roadSafety/reports/map/index.jsx +++ b/src/components/dashboard/roadSafety/reports/map/index.jsx @@ -1,322 +1,322 @@ -"use client"; -import LoadingHardPage from "@/core/components/LoadingHardPage"; -import MapLoading from "@/core/components/MapLayer/Loading"; -import isArrayEmpty from "@/core/utils/isArrayEmpty"; -import { GET_ROAD_SAFETY_REPORT_MAP } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { Box, Stack } from "@mui/material"; -import dynamic from "next/dynamic"; -import { useCallback, useEffect, useMemo, useState } from "react"; -import ClusterSwitch from "./ClusterSwitch"; -import Filter from "./Filter"; -import Legend from "./Legend"; -import PointsOnMap from "./PointsOnMap"; -import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; -import useProvinces from "@/lib/hooks/useProvince"; -import CustomSelectByDependency from "@/core/components/FilterDrawer/fieldsType/CustomSelectByDependency"; -import useEdaratLists from "@/lib/hooks/useEdaratLists"; -import useSafetyAndPrivacyGetItems from "@/lib/hooks/useSafetyAndPrivacyGetItems"; -const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { - loading: () => , - ssr: false, -}); - -const statusOptions = [ - { value: "", label: "همه وضعیت ها" }, - { value: 1, label: "گام اول (شناسایی)" }, - { value: 2, label: "گام دوم (مستندات قضایی)" }, - { value: 3, label: "گام سوم (برخورد)" }, -]; -const axisOptions = [ - { value: "", label: "همه محور ها" }, - { value: 1, label: "آزادراه" }, - { value: 2, label: "بزرگراه" }, - { value: 3, label: "اصلی" }, - { value: 4, label: "فرعی" }, - { value: 5, label: "روستایی" }, -]; - -const MAX_POINTS = 1000; - -const containerStyles = { - width: "100%", - height: "100%", - p: 1, - border: "1px dashed", - borderColor: "divider", - borderRadius: 1, -}; - -const controlBarStyles = { - p: 1, - background: "#fff", -}; - -const RoadSafetyReportMap = () => { - const defaultValues = useMemo( - () => [ - { - header: "استان", - id: "province_id", - filterMode: "equals", - datatype: "numeric", - value: "", - enable: true, - SelectComponent: (props) => { - const { provinces, errorProvinces, loadingProvinces } = useProvinces(); - const getSelectOptions = useMemo(() => { - if (loadingProvinces) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorProvinces) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: "کل کشور" }, - ...provinces.map((province) => ({ - value: province.id, - label: province.name_fa, - })), - ]; - }, [provinces, errorProvinces, loadingProvinces]); - return ( - - ); - }, - }, - { - eader: "اداره", - id: "edare_shahri_id", - filterMode: "equals", - datatype: "numeric", - dependencyId: "province_id", - value: "", - enable: true, - SelectComponent: (props) => { - const { edaratList, loadingEdaratList, errorEdaratList } = useEdaratLists( - props.dependencyFieldValue.value - ); - const [prevDependency, setPrevDependency] = useState(props.dependencyFieldValue.value); - - const getSelectOptions = useMemo(() => { - if (props.dependencyFieldValue.value === "") { - return [{ value: "empty", label: "ابتدا استان را انتخاب کنید" }]; - } - if (loadingEdaratList) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorEdaratList) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: "کل ادارات" }, - ...edaratList.map((edare) => ({ - value: edare.id, - label: edare.name_fa, - })), - ]; - }, [edaratList, loadingEdaratList, errorEdaratList]); - useEffect(() => { - if (prevDependency === props.dependencyFieldValue?.value) return; - props.handleChange({ ...props.filterParameters, value: "" }); - setPrevDependency(props.dependencyFieldValue?.value); - }, [props.dependencyFieldValue?.value]); - return ( - - ); - }, - }, - { - header: "مورد مشاهده شده", - id: "info_id", - filterMode: "equals", - datatype: "numeric", - value: "", - enable: true, - SelectComponent: (props) => { - const { itemsList, loadingItemsList, errorItemsList } = useSafetyAndPrivacyGetItems(); - - const getSelectOptions = useMemo(() => { - if (loadingItemsList) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorItemsList) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: "همه موارد" }, - ...itemsList.map((item) => ({ - value: item.id, - label: item.name, - })), - ]; - }, [itemsList, loadingItemsList, errorItemsList]); - - return ( - - ); - }, - }, - { - header: "نوع محور", - id: "axis_type_id", - filterMode: "equals", - datatype: "numeric", - value: "", - enable: true, - selectOption: () => { - return axisOptions.map((status) => ({ - value: status.value, - label: status.label, - })); - }, - }, - { - header: "وضعیت", - id: "step", - filterMode: "equals", - datatype: "numeric", - value: "", - enable: true, - selectOption: () => { - return statusOptions.map((status) => ({ - value: status.value, - label: status.label, - })); - }, - }, - { - header: "تاریخ ثبت", - id: "created_at", - filterMode: "between", - datatype: "date", - value: ["", ""], - enable: true, - }, - { - header: "تاریخ بازدید", - id: "activity_date_time", - filterMode: "between", - datatype: "date", - value: ["", ""], - enable: true, - }, - { - header: "تاریخ بارگذاری مستندات", - id: "judiciary_document_upload_date", - filterMode: "between", - datatype: "date", - value: ["", ""], - enable: true, - }, - { - header: "تاریخ اقدام", - id: "action_date", - filterMode: "between", - datatype: "date", - value: ["", ""], - enable: true, - }, - ], - [] - ); - const requestServer = useRequest(); - const [filterData, setFilterData] = useState( - defaultValues.reduce((acc, item) => { - acc[item.id] = item; - return acc; - }, {}) - ); - const [isCluster, setCluster] = useState(false); - const [data, setData] = useState([]); - const [isLoading, setLoading] = useState(true); - - const buildQueryParams = useCallback(() => { - const params = new URLSearchParams(); - const filters = DataTableFilterDataStructure(filterData, isArrayEmpty); - params.set("filters", JSON.stringify(filters || [])); - return params.toString(); - }, [filterData]); - - useEffect(() => { - const fetchData = async () => { - try { - setLoading(true); - const params = new URLSearchParams(); - const filters = DataTableFilterDataStructure(filterData, isArrayEmpty); - params.set("filters", JSON.stringify(filters || [])); - const query = params.toString(); - const response = await requestServer(`${GET_ROAD_SAFETY_REPORT_MAP}?${query}`); - const fetchedData = response?.data?.data || []; - - if (fetchedData.length > MAX_POINTS) { - setCluster(true); - } - setData(fetchedData); - } catch (error) { - console.log(error); - } finally { - setLoading(false); - } - }; - - fetchData(); - }, [filterData, buildQueryParams]); - - return ( - - - - - MAX_POINTS} - max={MAX_POINTS} - /> - - - - - - - - - - - {isLoading && ( - - - - )} - - - - - ); -}; -export default RoadSafetyReportMap; +"use client"; +import LoadingHardPage from "@/core/components/LoadingHardPage"; +import MapLoading from "@/core/components/MapLayer/Loading"; +import isArrayEmpty from "@/core/utils/isArrayEmpty"; +import { GET_ROAD_SAFETY_REPORT_MAP } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { Box, Stack } from "@mui/material"; +import dynamic from "next/dynamic"; +import { useCallback, useEffect, useMemo, useState } from "react"; +import ClusterSwitch from "./ClusterSwitch"; +import Filter from "./Filter"; +import Legend from "./Legend"; +import PointsOnMap from "./PointsOnMap"; +import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; +import useProvinces from "@/lib/hooks/useProvince"; +import CustomSelectByDependency from "@/core/components/FilterDrawer/fieldsType/CustomSelectByDependency"; +import useEdaratLists from "@/lib/hooks/useEdaratLists"; +import useSafetyAndPrivacyGetItems from "@/lib/hooks/useSafetyAndPrivacyGetItems"; +const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { + loading: () => , + ssr: false, +}); + +const statusOptions = [ + { value: "", label: "همه وضعیت ها" }, + { value: 1, label: "گام اول (شناسایی)" }, + { value: 2, label: "گام دوم (مستندات قضایی)" }, + { value: 3, label: "گام سوم (برخورد)" }, +]; +const axisOptions = [ + { value: "", label: "همه محور ها" }, + { value: 1, label: "آزادراه" }, + { value: 2, label: "بزرگراه" }, + { value: 3, label: "اصلی" }, + { value: 4, label: "فرعی" }, + { value: 5, label: "روستایی" }, +]; + +const MAX_POINTS = 1000; + +const containerStyles = { + width: "100%", + height: "100%", + p: 1, + border: "1px dashed", + borderColor: "divider", + borderRadius: 1, +}; + +const controlBarStyles = { + p: 1, + background: "#fff", +}; + +const RoadSafetyReportMap = () => { + const defaultValues = useMemo( + () => [ + { + header: "استان", + id: "province_id", + filterMode: "equals", + datatype: "numeric", + value: "", + enable: true, + SelectComponent: (props) => { + const { provinces, errorProvinces, loadingProvinces } = useProvinces(); + const getSelectOptions = useMemo(() => { + if (loadingProvinces) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorProvinces) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: "کل کشور" }, + ...provinces.map((province) => ({ + value: province.id, + label: province.name_fa, + })), + ]; + }, [provinces, errorProvinces, loadingProvinces]); + return ( + + ); + }, + }, + { + eader: "اداره", + id: "edare_shahri_id", + filterMode: "equals", + datatype: "numeric", + dependencyId: "province_id", + value: "", + enable: true, + SelectComponent: (props) => { + const { edaratList, loadingEdaratList, errorEdaratList } = useEdaratLists( + props.dependencyFieldValue.value + ); + const [prevDependency, setPrevDependency] = useState(props.dependencyFieldValue.value); + + const getSelectOptions = useMemo(() => { + if (props.dependencyFieldValue.value === "") { + return [{ value: "empty", label: "ابتدا استان را انتخاب کنید" }]; + } + if (loadingEdaratList) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorEdaratList) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: "کل ادارات" }, + ...edaratList.map((edare) => ({ + value: edare.id, + label: edare.name_fa, + })), + ]; + }, [edaratList, loadingEdaratList, errorEdaratList]); + useEffect(() => { + if (prevDependency === props.dependencyFieldValue?.value) return; + props.handleChange({ ...props.filterParameters, value: "" }); + setPrevDependency(props.dependencyFieldValue?.value); + }, [props.dependencyFieldValue?.value]); + return ( + + ); + }, + }, + { + header: "مورد مشاهده شده", + id: "info_id", + filterMode: "equals", + datatype: "numeric", + value: "", + enable: true, + SelectComponent: (props) => { + const { itemsList, loadingItemsList, errorItemsList } = useSafetyAndPrivacyGetItems(); + + const getSelectOptions = useMemo(() => { + if (loadingItemsList) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorItemsList) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: "همه موارد" }, + ...itemsList.map((item) => ({ + value: item.id, + label: item.name, + })), + ]; + }, [itemsList, loadingItemsList, errorItemsList]); + + return ( + + ); + }, + }, + { + header: "نوع محور", + id: "axis_type_id", + filterMode: "equals", + datatype: "numeric", + value: "", + enable: true, + selectOption: () => { + return axisOptions.map((status) => ({ + value: status.value, + label: status.label, + })); + }, + }, + { + header: "وضعیت", + id: "step", + filterMode: "equals", + datatype: "numeric", + value: "", + enable: true, + selectOption: () => { + return statusOptions.map((status) => ({ + value: status.value, + label: status.label, + })); + }, + }, + { + header: "تاریخ ثبت", + id: "created_at", + filterMode: "between", + datatype: "date", + value: ["", ""], + enable: true, + }, + { + header: "تاریخ بازدید", + id: "activity_date_time", + filterMode: "between", + datatype: "date", + value: ["", ""], + enable: true, + }, + { + header: "تاریخ بارگذاری مستندات", + id: "judiciary_document_upload_date", + filterMode: "between", + datatype: "date", + value: ["", ""], + enable: true, + }, + { + header: "تاریخ اقدام", + id: "action_date", + filterMode: "between", + datatype: "date", + value: ["", ""], + enable: true, + }, + ], + [] + ); + const requestServer = useRequest(); + const [filterData, setFilterData] = useState( + defaultValues.reduce((acc, item) => { + acc[item.id] = item; + return acc; + }, {}) + ); + const [isCluster, setCluster] = useState(false); + const [data, setData] = useState([]); + const [isLoading, setLoading] = useState(true); + + const buildQueryParams = useCallback(() => { + const params = new URLSearchParams(); + const filters = DataTableFilterDataStructure(filterData, isArrayEmpty); + params.set("filters", JSON.stringify(filters || [])); + return params.toString(); + }, [filterData]); + + useEffect(() => { + const fetchData = async () => { + try { + setLoading(true); + const params = new URLSearchParams(); + const filters = DataTableFilterDataStructure(filterData, isArrayEmpty); + params.set("filters", JSON.stringify(filters || [])); + const query = params.toString(); + const response = await requestServer(`${GET_ROAD_SAFETY_REPORT_MAP}?${query}`); + const fetchedData = response?.data?.data || []; + + if (fetchedData.length > MAX_POINTS) { + setCluster(true); + } + setData(fetchedData); + } catch (error) { + console.log(error); + } finally { + setLoading(false); + } + }; + + fetchData(); + }, [filterData, buildQueryParams]); + + return ( + + + + + MAX_POINTS} + max={MAX_POINTS} + /> + + + + + + + + + + + {isLoading && ( + + + + )} + + + + + ); +}; +export default RoadSafetyReportMap; diff --git a/src/components/dashboard/roadSafety/reports/reportPage/ExcelPrint/index.jsx b/src/components/dashboard/roadSafety/reports/reportPage/ExcelPrint/index.jsx index 25ccefa..a924431 100644 --- a/src/components/dashboard/roadSafety/reports/reportPage/ExcelPrint/index.jsx +++ b/src/components/dashboard/roadSafety/reports/reportPage/ExcelPrint/index.jsx @@ -1,67 +1,67 @@ -"use client"; -import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; -import isArrayEmpty from "@/core/utils/isArrayEmpty"; -import { EXPORT_COUNTRY_ROAD_SAFETY_REPORT, EXPORT_PROVINCE_ROAD_SAFETY_REPORT } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { useTheme } from "@emotion/react"; -import DescriptionIcon from "@mui/icons-material/Description"; -import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; -import FileSaver from "file-saver"; -import moment from "jalali-moment"; -import { useState } from "react"; - -const PrintExcel = ({ table, filterData }) => { - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const [loading, setLoading] = useState(false); - const requestServer = useRequest({ notificationSuccess: true }); - - const clickHandler = () => { - setLoading(true); - const filters = DataTableFilterDataStructure(filterData, isArrayEmpty); - const filterParams = new URLSearchParams(); - let requestUrl; - filterParams.set("filters", JSON.stringify(filters || [])); - if (filterData.province_id.value === "") { - requestUrl = EXPORT_COUNTRY_ROAD_SAFETY_REPORT; - } else { - filterParams.set("province_id", filterData.province_id.value); - requestUrl = EXPORT_PROVINCE_ROAD_SAFETY_REPORT; - } - - requestServer(`${requestUrl}?${filterParams}`, "get", { - requestOptions: { responseType: "blob" }, - }) - .then((response) => { - const filename = `خروجی کارتابل نگهداری حریم راه تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; - FileSaver.saveAs(response.data, filename); - }) - .catch(() => {}) - .finally(() => { - setLoading(false); - }); - }; - - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - - ); -}; -export default PrintExcel; +"use client"; +import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; +import isArrayEmpty from "@/core/utils/isArrayEmpty"; +import { EXPORT_COUNTRY_ROAD_SAFETY_REPORT, EXPORT_PROVINCE_ROAD_SAFETY_REPORT } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { useTheme } from "@emotion/react"; +import DescriptionIcon from "@mui/icons-material/Description"; +import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; +import FileSaver from "file-saver"; +import moment from "jalali-moment"; +import { useState } from "react"; + +const PrintExcel = ({ table, filterData }) => { + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const [loading, setLoading] = useState(false); + const requestServer = useRequest({ notificationSuccess: true }); + + const clickHandler = () => { + setLoading(true); + const filters = DataTableFilterDataStructure(filterData, isArrayEmpty); + const filterParams = new URLSearchParams(); + let requestUrl; + filterParams.set("filters", JSON.stringify(filters || [])); + if (filterData.province_id.value === "") { + requestUrl = EXPORT_COUNTRY_ROAD_SAFETY_REPORT; + } else { + filterParams.set("province_id", filterData.province_id.value); + requestUrl = EXPORT_PROVINCE_ROAD_SAFETY_REPORT; + } + + requestServer(`${requestUrl}?${filterParams}`, "get", { + requestOptions: { responseType: "blob" }, + }) + .then((response) => { + const filename = `خروجی کارتابل نگهداری حریم راه تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; + FileSaver.saveAs(response.data, filename); + }) + .catch(() => {}) + .finally(() => { + setLoading(false); + }); + }; + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + + ); +}; +export default PrintExcel; diff --git a/src/components/dashboard/roadSafety/reports/reportPage/ReportLists.jsx b/src/components/dashboard/roadSafety/reports/reportPage/ReportLists.jsx index cb0e8b7..e406ea5 100644 --- a/src/components/dashboard/roadSafety/reports/reportPage/ReportLists.jsx +++ b/src/components/dashboard/roadSafety/reports/reportPage/ReportLists.jsx @@ -1,304 +1,304 @@ -"use client"; -import DataTableWithAuth from "@/core/components/DataTableWithAuth"; -import { Box } from "@mui/material"; -import { useMemo } from "react"; -import Toolbar from "./Toolbar"; - -const ReportLists = ({ data, filterData, setFilterData, isLoading }) => { - const columns = useMemo(() => { - return [ - { - accessorKey: "edare_name", - header: "اداره کل", - id: "edare_name", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - }, - - { - accessorKey: "sum", - header: "تعداد کل", - id: "sum", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - { - header: "ساخت و ساز غیر مجاز", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - id: "id_89", - grow: false, - size: 50, - columns: [ - { - accessorFn: (row) => (row["89"] ? row["89"]["1"] : 0), - header: "گام اول (شناسایی)", - id: "id_89.1", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - { - accessorFn: (row) => (row["89"] ? row["89"]["2"] : 0), - header: "گام دوم (مستندات قضایی)", - id: "id_89.2", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - { - accessorFn: (row) => (row["89"] ? row["89"]["3"] : 0), - header: "گام سوم (برخورد)", - id: "id_89.3", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - ], - }, - { - header: "راه دسترسی غیر مجاز", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - id: "id_90", - grow: false, - size: 50, - columns: [ - { - accessorFn: (row) => (row["90"] ? row["90"]["1"] : 0), - header: "گام اول (شناسایی)", - id: "id_90.1", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - { - accessorFn: (row) => (row["90"] ? row["90"]["2"] : 0), - header: "گام دوم (مستندات قضایی)", - id: "id_90.2", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - { - accessorFn: (row) => (row["90"] ? row["90"]["3"] : 0), - header: "گام سوم (برخورد)", - id: "id_90.3", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - ], - }, - { - header: "عبور تاسیسات زیربنایی غیر مجاز", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - id: "id_91", - grow: false, - size: 50, - columns: [ - { - accessorFn: (row) => (row["91"] ? row["91"]["1"] : 0), - header: "گام اول (شناسایی)", - id: "id_91.1", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - { - accessorFn: (row) => (row["91"] ? row["91"]["2"] : 0), - header: "گام دوم (مستندات قضایی)", - id: "id_91.2", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - { - accessorFn: (row) => (row["91"] ? row["91"]["3"] : 0), - header: "گام سوم (برخورد)", - id: "id_91.3", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - muiTableBodyCellProps: { - sx: { - textAlign: "center", - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return (renderedCellValue / 1).toLocaleString(); - }, - }, - ], - }, - ]; - }, []); - - return ( - - - - ); -}; - -export default ReportLists; +"use client"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import { Box } from "@mui/material"; +import { useMemo } from "react"; +import Toolbar from "./Toolbar"; + +const ReportLists = ({ data, filterData, setFilterData, isLoading }) => { + const columns = useMemo(() => { + return [ + { + accessorKey: "edare_name", + header: "اداره کل", + id: "edare_name", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + }, + + { + accessorKey: "sum", + header: "تعداد کل", + id: "sum", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + { + header: "ساخت و ساز غیر مجاز", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + id: "id_89", + grow: false, + size: 50, + columns: [ + { + accessorFn: (row) => (row["89"] ? row["89"]["1"] : 0), + header: "گام اول (شناسایی)", + id: "id_89.1", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + { + accessorFn: (row) => (row["89"] ? row["89"]["2"] : 0), + header: "گام دوم (مستندات قضایی)", + id: "id_89.2", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + { + accessorFn: (row) => (row["89"] ? row["89"]["3"] : 0), + header: "گام سوم (برخورد)", + id: "id_89.3", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + ], + }, + { + header: "راه دسترسی غیر مجاز", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + id: "id_90", + grow: false, + size: 50, + columns: [ + { + accessorFn: (row) => (row["90"] ? row["90"]["1"] : 0), + header: "گام اول (شناسایی)", + id: "id_90.1", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + { + accessorFn: (row) => (row["90"] ? row["90"]["2"] : 0), + header: "گام دوم (مستندات قضایی)", + id: "id_90.2", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + { + accessorFn: (row) => (row["90"] ? row["90"]["3"] : 0), + header: "گام سوم (برخورد)", + id: "id_90.3", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + ], + }, + { + header: "عبور تاسیسات زیربنایی غیر مجاز", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + id: "id_91", + grow: false, + size: 50, + columns: [ + { + accessorFn: (row) => (row["91"] ? row["91"]["1"] : 0), + header: "گام اول (شناسایی)", + id: "id_91.1", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + { + accessorFn: (row) => (row["91"] ? row["91"]["2"] : 0), + header: "گام دوم (مستندات قضایی)", + id: "id_91.2", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + { + accessorFn: (row) => (row["91"] ? row["91"]["3"] : 0), + header: "گام سوم (برخورد)", + id: "id_91.3", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + muiTableBodyCellProps: { + sx: { + textAlign: "center", + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return (renderedCellValue / 1).toLocaleString(); + }, + }, + ], + }, + ]; + }, []); + + return ( + + + + ); +}; + +export default ReportLists; diff --git a/src/components/dashboard/roadSafety/reports/reportPage/Search/FromDateController.jsx b/src/components/dashboard/roadSafety/reports/reportPage/Search/FromDateController.jsx index cc6226a..7f3f0f4 100644 --- a/src/components/dashboard/roadSafety/reports/reportPage/Search/FromDateController.jsx +++ b/src/components/dashboard/roadSafety/reports/reportPage/Search/FromDateController.jsx @@ -1,28 +1,28 @@ -import { Controller } from "react-hook-form"; -import MuiDatePicker from "@/core/components/MuiDatePicker"; -import React from "react"; -import moment from "jalali-moment"; - -const FromDateController = ({ control }) => { - return ( - ( - { - const formattedDate = moment(new Date(newValue)).locale("en").format("YYYY-MM-DD"); - onChange(formattedDate); // Update the field value in react-hook-form - }} - helperText={error ? error.message : null} - /> - )} - /> - ); -}; -export default FromDateController; +import { Controller } from "react-hook-form"; +import MuiDatePicker from "@/core/components/MuiDatePicker"; +import React from "react"; +import moment from "jalali-moment"; + +const FromDateController = ({ control }) => { + return ( + ( + { + const formattedDate = moment(new Date(newValue)).locale("en").format("YYYY-MM-DD"); + onChange(formattedDate); // Update the field value in react-hook-form + }} + helperText={error ? error.message : null} + /> + )} + /> + ); +}; +export default FromDateController; diff --git a/src/components/dashboard/roadSafety/reports/reportPage/Search/SearchReportField.jsx b/src/components/dashboard/roadSafety/reports/reportPage/Search/SearchReportField.jsx index 606e08c..2ec69aa 100644 --- a/src/components/dashboard/roadSafety/reports/reportPage/Search/SearchReportField.jsx +++ b/src/components/dashboard/roadSafety/reports/reportPage/Search/SearchReportField.jsx @@ -1,49 +1,49 @@ -import { Button, Grid, LinearProgress, Typography } from "@mui/material"; -import SearchIcon from "@mui/icons-material/Search"; -import React from "react"; -import FromDateController from "./FromDateController"; -import ToDateController from "./ToDateController"; -import SelectProvince from "./SelectProvince"; -import { Controller } from "react-hook-form"; -import SelectAxisType from "./SelectAxisType"; - -const SearchReportField = ({ control, hasProvincesPermission }) => { - return ( - - - - - - - - {hasProvincesPermission && ( - - - - )} - - - - - ( - - )} - /> - - - ); -}; - -export default SearchReportField; +import { Button, Grid, LinearProgress, Typography } from "@mui/material"; +import SearchIcon from "@mui/icons-material/Search"; +import React from "react"; +import FromDateController from "./FromDateController"; +import ToDateController from "./ToDateController"; +import SelectProvince from "./SelectProvince"; +import { Controller } from "react-hook-form"; +import SelectAxisType from "./SelectAxisType"; + +const SearchReportField = ({ control, hasProvincesPermission }) => { + return ( + + + + + + + + {hasProvincesPermission && ( + + + + )} + + + + + ( + + )} + /> + + + ); +}; + +export default SearchReportField; diff --git a/src/components/dashboard/roadSafety/reports/reportPage/Search/SelectAxisType.jsx b/src/components/dashboard/roadSafety/reports/reportPage/Search/SelectAxisType.jsx index 217143e..65b5062 100644 --- a/src/components/dashboard/roadSafety/reports/reportPage/Search/SelectAxisType.jsx +++ b/src/components/dashboard/roadSafety/reports/reportPage/Search/SelectAxisType.jsx @@ -1,45 +1,45 @@ -import { FormControl, FormHelperText, InputLabel, MenuItem, Select } from "@mui/material"; -import { Controller } from "react-hook-form"; - -const axisOptions = [ - { value: 1, label: "آزادراه" }, - { value: 2, label: "بزرگراه" }, - { value: 3, label: "اصلی" }, - { value: 4, label: "فرعی" }, - { value: 5, label: "روستایی" }, -]; - -const SelectAxisType = ({ control }) => { - return ( - ( - - نوع محور - - {error && {error.message}} - - )} - /> - ); -}; -export default SelectAxisType; +import { FormControl, FormHelperText, InputLabel, MenuItem, Select } from "@mui/material"; +import { Controller } from "react-hook-form"; + +const axisOptions = [ + { value: 1, label: "آزادراه" }, + { value: 2, label: "بزرگراه" }, + { value: 3, label: "اصلی" }, + { value: 4, label: "فرعی" }, + { value: 5, label: "روستایی" }, +]; + +const SelectAxisType = ({ control }) => { + return ( + ( + + نوع محور + + {error && {error.message}} + + )} + /> + ); +}; +export default SelectAxisType; diff --git a/src/components/dashboard/roadSafety/reports/reportPage/Search/SelectProvince.jsx b/src/components/dashboard/roadSafety/reports/reportPage/Search/SelectProvince.jsx index 2b24d67..89395f0 100644 --- a/src/components/dashboard/roadSafety/reports/reportPage/Search/SelectProvince.jsx +++ b/src/components/dashboard/roadSafety/reports/reportPage/Search/SelectProvince.jsx @@ -1,45 +1,45 @@ -import useProvinces from "@/lib/hooks/useProvince"; -import { FormControl, FormHelperText, InputLabel, MenuItem, Select } from "@mui/material"; -import { Controller } from "react-hook-form"; - -const SelectProvince = ({ control }) => { - const { provinces, loadingProvinces, errorProvinces } = useProvinces(); - return ( - ( - - استان - - {error && {error.message}} - - )} - /> - ); -}; -export default SelectProvince; +import useProvinces from "@/lib/hooks/useProvince"; +import { FormControl, FormHelperText, InputLabel, MenuItem, Select } from "@mui/material"; +import { Controller } from "react-hook-form"; + +const SelectProvince = ({ control }) => { + const { provinces, loadingProvinces, errorProvinces } = useProvinces(); + return ( + ( + + استان + + {error && {error.message}} + + )} + /> + ); +}; +export default SelectProvince; diff --git a/src/components/dashboard/roadSafety/reports/reportPage/Search/ToDateController.jsx b/src/components/dashboard/roadSafety/reports/reportPage/Search/ToDateController.jsx index ad7690a..e9c66e4 100644 --- a/src/components/dashboard/roadSafety/reports/reportPage/Search/ToDateController.jsx +++ b/src/components/dashboard/roadSafety/reports/reportPage/Search/ToDateController.jsx @@ -1,30 +1,30 @@ -import { Controller, useWatch } from "react-hook-form"; -import MuiDatePicker from "@/core/components/MuiDatePicker"; -import React from "react"; -import moment from "jalali-moment"; - -const ToDateController = ({ control }) => { - const minDate = useWatch({ control, name: "from_date" }); - return ( - ( - { - const formattedDate = moment(new Date(newValue)).locale("en").format("YYYY-MM-DD"); - onChange(formattedDate); // Update the field value in react-hook-form - }} - helperText={error ? error.message : null} - /> - )} - /> - ); -}; -export default ToDateController; +import { Controller, useWatch } from "react-hook-form"; +import MuiDatePicker from "@/core/components/MuiDatePicker"; +import React from "react"; +import moment from "jalali-moment"; + +const ToDateController = ({ control }) => { + const minDate = useWatch({ control, name: "from_date" }); + return ( + ( + { + const formattedDate = moment(new Date(newValue)).locale("en").format("YYYY-MM-DD"); + onChange(formattedDate); // Update the field value in react-hook-form + }} + helperText={error ? error.message : null} + /> + )} + /> + ); +}; +export default ToDateController; diff --git a/src/components/dashboard/roadSafety/reports/reportPage/Search/index.jsx b/src/components/dashboard/roadSafety/reports/reportPage/Search/index.jsx index f29d302..9d504f2 100644 --- a/src/components/dashboard/roadSafety/reports/reportPage/Search/index.jsx +++ b/src/components/dashboard/roadSafety/reports/reportPage/Search/index.jsx @@ -1,13 +1,13 @@ -import StyledForm from "@/core/components/StyledForm"; -import SearchReportField from "./SearchReportField"; - -const SearchReportList = ({ handleSubmit, onSearchSubmit, control, hasProvincesPermission }) => { - return ( - <> - - - - - ); -}; -export default SearchReportList; +import StyledForm from "@/core/components/StyledForm"; +import SearchReportField from "./SearchReportField"; + +const SearchReportList = ({ handleSubmit, onSearchSubmit, control, hasProvincesPermission }) => { + return ( + <> + + + + + ); +}; +export default SearchReportList; diff --git a/src/components/dashboard/roadSafety/reports/reportPage/Toolbar.jsx b/src/components/dashboard/roadSafety/reports/reportPage/Toolbar.jsx index 7dd930f..3e5ab8c 100644 --- a/src/components/dashboard/roadSafety/reports/reportPage/Toolbar.jsx +++ b/src/components/dashboard/roadSafety/reports/reportPage/Toolbar.jsx @@ -1,11 +1,11 @@ -import PrintExcel from "./ExcelPrint"; -import { Box } from "@mui/material"; - -const Toolbar = ({ table, filterData, mutate }) => { - return ( - - - - ); -}; -export default Toolbar; +import PrintExcel from "./ExcelPrint"; +import { Box } from "@mui/material"; + +const Toolbar = ({ table, filterData, mutate }) => { + return ( + + + + ); +}; +export default Toolbar; diff --git a/src/components/dashboard/roadSafety/reports/reportPage/index.jsx b/src/components/dashboard/roadSafety/reports/reportPage/index.jsx index a8f8998..5d7a2cd 100644 --- a/src/components/dashboard/roadSafety/reports/reportPage/index.jsx +++ b/src/components/dashboard/roadSafety/reports/reportPage/index.jsx @@ -1,264 +1,264 @@ -"use client"; -import CustomSelectByDependency from "@/core/components/FilterDrawer/fieldsType/CustomSelectByDependency"; -import PageTitle from "@/core/components/PageTitle"; -import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; -import isArrayEmpty from "@/core/utils/isArrayEmpty"; -import { GET_ROAD_SAFETY_CITY_ACTIVITY_REPORT, GET_ROAD_SAFETY_PROVINCE_ACTIVITY_REPORT } from "@/core/utils/routes"; -import { useAuth } from "@/lib/contexts/auth"; -import { usePermissions } from "@/lib/hooks/usePermissions"; -import useProvinces from "@/lib/hooks/useProvince"; -import useRequest from "@/lib/hooks/useRequest"; -import useSafetyAndPrivacyGetItems from "@/lib/hooks/useSafetyAndPrivacyGetItems"; -import { LinearProgress, Stack } from "@mui/material"; -import { useEffect, useMemo, useState } from "react"; -import ReportLists from "./ReportLists"; - -const statusOptions = [ - { value: "", label: "همه وضعیت ها" }, - { value: 1, label: "گام اول (شناسایی)" }, - { value: 2, label: "گام دوم (مستندات قضایی)" }, - { value: 3, label: "گام سوم (برخورد)" }, -]; -const axisOptions = [ - { value: "", label: "همه محور ها" }, - { value: 1, label: "آزادراه" }, - { value: 2, label: "بزرگراه" }, - { value: 3, label: "اصلی" }, - { value: 4, label: "فرعی" }, - { value: 5, label: "روستایی" }, -]; - -const ReportPage = () => { - const { data: userPermissions } = usePermissions(); - const hasProvincesPermission = userPermissions.includes("show-safety-and-privacy-operator-cartable"); - const { user } = useAuth(); - const requestServer = useRequest(); - const [data, setData] = useState(null); - const [isLoading, setLoading] = useState(true); - const defaultValues = useMemo( - () => [ - { - header: "استان", - id: "province_id", - filterMode: "equals", - datatype: "numeric", - value: hasProvincesPermission ? "" : user.province_id, - enable: hasProvincesPermission, - SelectComponent: (props) => { - const { provinces, errorProvinces, loadingProvinces } = useProvinces(); - const getSelectOptions = useMemo(() => { - if (loadingProvinces) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorProvinces) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: "کل کشور" }, - ...provinces.map((province) => ({ - value: province.id, - label: province.name_fa, - })), - ]; - }, [provinces, errorProvinces, loadingProvinces]); - return ( - - ); - }, - }, - { - header: "مورد مشاهده شده", - id: "info_id", - filterMode: "equals", - datatype: "numeric", - value: "", - enable: true, - SelectComponent: (props) => { - const { itemsList, loadingItemsList, errorItemsList } = useSafetyAndPrivacyGetItems(); - - const getSelectOptions = useMemo(() => { - if (loadingItemsList) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorItemsList) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: "همه موارد" }, - ...itemsList.map((item) => ({ - value: item.id, - label: item.name, - })), - ]; - }, [itemsList, loadingItemsList, errorItemsList]); - - return ( - - ); - }, - }, - { - header: "نوع محور", - id: "axis_type_id", - filterMode: "equals", - datatype: "numeric", - value: "", - enable: true, - selectOption: () => { - return axisOptions.map((status) => ({ - value: status.value, - label: status.label, - })); - }, - }, - { - header: "وضعیت", - id: "step", - filterMode: "equals", - datatype: "numeric", - value: "", - enable: true, - selectOption: () => { - return statusOptions.map((status) => ({ - value: status.value, - label: status.label, - })); - }, - }, - { - header: "تاریخ ثبت", - id: "created_at", - filterMode: "between", - datatype: "date", - value: ["", ""], - enable: true, - }, - { - header: "تاریخ بازدید", - id: "activity_date_time", - filterMode: "between", - datatype: "date", - value: ["", ""], - enable: true, - }, - { - header: "تاریخ بارگذاری مستندات", - id: "judiciary_document_upload_date", - filterMode: "between", - datatype: "date", - value: ["", ""], - enable: true, - }, - { - header: "تاریخ اقدام", - id: "action_date", - filterMode: "between", - datatype: "date", - value: ["", ""], - enable: true, - }, - ], - [hasProvincesPermission, user.province_id] - ); - - const [filterData, setFilterData] = useState( - defaultValues.reduce((acc, item) => { - acc[item.id] = item; - return acc; - }, {}) - ); - - useEffect(() => { - const fetchData = async () => { - try { - setLoading(true); - const filters = DataTableFilterDataStructure(filterData, isArrayEmpty); - const params = new URLSearchParams(); - params.set("filters", JSON.stringify(filters || [])); - if (filterData.province_id.value === "") { - try { - const response = await requestServer( - `${GET_ROAD_SAFETY_PROVINCE_ACTIVITY_REPORT}?${params.toString()}` - ); - const result = response.data.data; - const nationalReportForItem = result.activities.find((report) => report.province_id === -1); - const nationalReport = { - edare_name: "کل کشور", - ...nationalReportForItem, - }; - - setData([ - nationalReport, - ...result.provinces.map((province) => { - const filteredReports = result.activities.find( - (report) => report.province_id === province.id - ); - return { - ...filteredReports, - edare_name: province.name_fa, - }; - }), - ]); - } catch (e) { - console.log(e); - } - } else { - params.set("province_id", filterData.province_id.value); - try { - const response = await requestServer( - `${GET_ROAD_SAFETY_CITY_ACTIVITY_REPORT}?${params.toString()}` - ); - const result = response.data.data; - const nationalReportForItem = result.activities.find( - (report) => report.edare_shahri_id == "-1" - ); - const nationalReport = { - ...nationalReportForItem, - edare_name: "کل استان", - }; - setData([ - nationalReport, - ...result.edarateShahri.map((edare) => { - const filteredReports = result.activities.find( - (report) => report.edare_shahri_id == edare.id - ); - return { - edare_name: edare.name_fa, - ...filteredReports, - }; - }), - ]); - } catch (e) { - console.log(e); - } - } - } catch (error) { - console.log(error); - } finally { - setLoading(false); - } - }; - - fetchData(); - }, [filterData]); - - return ( - - - {!data ? ( - - ) : ( - - )} - - ); -}; -export default ReportPage; +"use client"; +import CustomSelectByDependency from "@/core/components/FilterDrawer/fieldsType/CustomSelectByDependency"; +import PageTitle from "@/core/components/PageTitle"; +import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; +import isArrayEmpty from "@/core/utils/isArrayEmpty"; +import { GET_ROAD_SAFETY_CITY_ACTIVITY_REPORT, GET_ROAD_SAFETY_PROVINCE_ACTIVITY_REPORT } from "@/core/utils/routes"; +import { useAuth } from "@/lib/contexts/auth"; +import { usePermissions } from "@/lib/hooks/usePermissions"; +import useProvinces from "@/lib/hooks/useProvince"; +import useRequest from "@/lib/hooks/useRequest"; +import useSafetyAndPrivacyGetItems from "@/lib/hooks/useSafetyAndPrivacyGetItems"; +import { LinearProgress, Stack } from "@mui/material"; +import { useEffect, useMemo, useState } from "react"; +import ReportLists from "./ReportLists"; + +const statusOptions = [ + { value: "", label: "همه وضعیت ها" }, + { value: 1, label: "گام اول (شناسایی)" }, + { value: 2, label: "گام دوم (مستندات قضایی)" }, + { value: 3, label: "گام سوم (برخورد)" }, +]; +const axisOptions = [ + { value: "", label: "همه محور ها" }, + { value: 1, label: "آزادراه" }, + { value: 2, label: "بزرگراه" }, + { value: 3, label: "اصلی" }, + { value: 4, label: "فرعی" }, + { value: 5, label: "روستایی" }, +]; + +const ReportPage = () => { + const { data: userPermissions } = usePermissions(); + const hasProvincesPermission = userPermissions.includes("show-safety-and-privacy-operator-cartable"); + const { user } = useAuth(); + const requestServer = useRequest(); + const [data, setData] = useState(null); + const [isLoading, setLoading] = useState(true); + const defaultValues = useMemo( + () => [ + { + header: "استان", + id: "province_id", + filterMode: "equals", + datatype: "numeric", + value: hasProvincesPermission ? "" : user.province_id, + enable: hasProvincesPermission, + SelectComponent: (props) => { + const { provinces, errorProvinces, loadingProvinces } = useProvinces(); + const getSelectOptions = useMemo(() => { + if (loadingProvinces) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorProvinces) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: "کل کشور" }, + ...provinces.map((province) => ({ + value: province.id, + label: province.name_fa, + })), + ]; + }, [provinces, errorProvinces, loadingProvinces]); + return ( + + ); + }, + }, + { + header: "مورد مشاهده شده", + id: "info_id", + filterMode: "equals", + datatype: "numeric", + value: "", + enable: true, + SelectComponent: (props) => { + const { itemsList, loadingItemsList, errorItemsList } = useSafetyAndPrivacyGetItems(); + + const getSelectOptions = useMemo(() => { + if (loadingItemsList) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorItemsList) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: "همه موارد" }, + ...itemsList.map((item) => ({ + value: item.id, + label: item.name, + })), + ]; + }, [itemsList, loadingItemsList, errorItemsList]); + + return ( + + ); + }, + }, + { + header: "نوع محور", + id: "axis_type_id", + filterMode: "equals", + datatype: "numeric", + value: "", + enable: true, + selectOption: () => { + return axisOptions.map((status) => ({ + value: status.value, + label: status.label, + })); + }, + }, + { + header: "وضعیت", + id: "step", + filterMode: "equals", + datatype: "numeric", + value: "", + enable: true, + selectOption: () => { + return statusOptions.map((status) => ({ + value: status.value, + label: status.label, + })); + }, + }, + { + header: "تاریخ ثبت", + id: "created_at", + filterMode: "between", + datatype: "date", + value: ["", ""], + enable: true, + }, + { + header: "تاریخ بازدید", + id: "activity_date_time", + filterMode: "between", + datatype: "date", + value: ["", ""], + enable: true, + }, + { + header: "تاریخ بارگذاری مستندات", + id: "judiciary_document_upload_date", + filterMode: "between", + datatype: "date", + value: ["", ""], + enable: true, + }, + { + header: "تاریخ اقدام", + id: "action_date", + filterMode: "between", + datatype: "date", + value: ["", ""], + enable: true, + }, + ], + [hasProvincesPermission, user.province_id] + ); + + const [filterData, setFilterData] = useState( + defaultValues.reduce((acc, item) => { + acc[item.id] = item; + return acc; + }, {}) + ); + + useEffect(() => { + const fetchData = async () => { + try { + setLoading(true); + const filters = DataTableFilterDataStructure(filterData, isArrayEmpty); + const params = new URLSearchParams(); + params.set("filters", JSON.stringify(filters || [])); + if (filterData.province_id.value === "") { + try { + const response = await requestServer( + `${GET_ROAD_SAFETY_PROVINCE_ACTIVITY_REPORT}?${params.toString()}` + ); + const result = response.data.data; + const nationalReportForItem = result.activities.find((report) => report.province_id === -1); + const nationalReport = { + edare_name: "کل کشور", + ...nationalReportForItem, + }; + + setData([ + nationalReport, + ...result.provinces.map((province) => { + const filteredReports = result.activities.find( + (report) => report.province_id === province.id + ); + return { + ...filteredReports, + edare_name: province.name_fa, + }; + }), + ]); + } catch (e) { + console.log(e); + } + } else { + params.set("province_id", filterData.province_id.value); + try { + const response = await requestServer( + `${GET_ROAD_SAFETY_CITY_ACTIVITY_REPORT}?${params.toString()}` + ); + const result = response.data.data; + const nationalReportForItem = result.activities.find( + (report) => report.edare_shahri_id == "-1" + ); + const nationalReport = { + ...nationalReportForItem, + edare_name: "کل استان", + }; + setData([ + nationalReport, + ...result.edarateShahri.map((edare) => { + const filteredReports = result.activities.find( + (report) => report.edare_shahri_id == edare.id + ); + return { + edare_name: edare.name_fa, + ...filteredReports, + }; + }), + ]); + } catch (e) { + console.log(e); + } + } + } catch (error) { + console.log(error); + } finally { + setLoading(false); + } + }; + + fetchData(); + }, [filterData]); + + return ( + + + {!data ? ( + + ) : ( + + )} + + ); +}; +export default ReportPage; diff --git a/src/components/dashboard/roadSafety/supervisor/ExcelPrint/index.jsx b/src/components/dashboard/roadSafety/supervisor/ExcelPrint/index.jsx index d66215e..9e1926c 100644 --- a/src/components/dashboard/roadSafety/supervisor/ExcelPrint/index.jsx +++ b/src/components/dashboard/roadSafety/supervisor/ExcelPrint/index.jsx @@ -1,74 +1,74 @@ -import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; -import isArrayEmpty from "@/core/utils/isArrayEmpty"; -import { EXPORT_SUPERVISOR_ROAD_SAFETY } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { useTheme } from "@emotion/react"; -import DescriptionIcon from "@mui/icons-material/Description"; -import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; -import FileSaver from "file-saver"; -import moment from "jalali-moment"; -import { useMemo, useState } from "react"; - -const PrintExcel = ({ table, filterData }) => { - const [loading, setLoading] = useState(false); - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const requestServer = useRequest(); - const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { - if (filter.value && (!Array.isArray(filter.value) || filter.value.some((item) => item.trim() !== ""))) { - acc.push({ id: key, value: filter.value }); - } - return acc; - }, []); - - const filterParams = useMemo(() => { - const params = new URLSearchParams(); - if (activeFilters.length > 0) { - activeFilters.map((filter, index) => { - const filteredFilterData = DataTableFilterDataStructure(filterData, isArrayEmpty); - params.set("filters", JSON.stringify(filteredFilterData.length === 0 ? [] : filteredFilterData)); - }); - } else { - params.set("filters", JSON.stringify([])); - } - return params; - }, [activeFilters]); - - const clickHandler = () => { - setLoading(true); - requestServer(`${EXPORT_SUPERVISOR_ROAD_SAFETY}?${filterParams}`, "get", { - requestOptions: { responseType: "blob" }, - }) - .then((response) => { - const filename = `خروجی کارتابل ارزیابی نگهداری حریم تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; - FileSaver.saveAs(response.data, filename); - }) - .catch(() => {}) - .finally(() => { - setLoading(false); - }); - }; - - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - - ); -}; -export default PrintExcel; +import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; +import isArrayEmpty from "@/core/utils/isArrayEmpty"; +import { EXPORT_SUPERVISOR_ROAD_SAFETY } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { useTheme } from "@emotion/react"; +import DescriptionIcon from "@mui/icons-material/Description"; +import { Button, CircularProgress, IconButton, useMediaQuery } from "@mui/material"; +import FileSaver from "file-saver"; +import moment from "jalali-moment"; +import { useMemo, useState } from "react"; + +const PrintExcel = ({ table, filterData }) => { + const [loading, setLoading] = useState(false); + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const requestServer = useRequest(); + const activeFilters = Object.entries(filterData).reduce((acc, [key, filter]) => { + if (filter.value && (!Array.isArray(filter.value) || filter.value.some((item) => item.trim() !== ""))) { + acc.push({ id: key, value: filter.value }); + } + return acc; + }, []); + + const filterParams = useMemo(() => { + const params = new URLSearchParams(); + if (activeFilters.length > 0) { + activeFilters.map((filter, index) => { + const filteredFilterData = DataTableFilterDataStructure(filterData, isArrayEmpty); + params.set("filters", JSON.stringify(filteredFilterData.length === 0 ? [] : filteredFilterData)); + }); + } else { + params.set("filters", JSON.stringify([])); + } + return params; + }, [activeFilters]); + + const clickHandler = () => { + setLoading(true); + requestServer(`${EXPORT_SUPERVISOR_ROAD_SAFETY}?${filterParams}`, "get", { + requestOptions: { responseType: "blob" }, + }) + .then((response) => { + const filename = `خروجی کارتابل ارزیابی نگهداری حریم تاریخ_${moment().format("jYYYY_jMM_jDD")}.xlsx`; + FileSaver.saveAs(response.data, filename); + }) + .catch(() => {}) + .finally(() => { + setLoading(false); + }); + }; + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + + ); +}; +export default PrintExcel; diff --git a/src/components/dashboard/roadSafety/supervisor/Learn/index.jsx b/src/components/dashboard/roadSafety/supervisor/Learn/index.jsx index 8db03e7..1c7988b 100644 --- a/src/components/dashboard/roadSafety/supervisor/Learn/index.jsx +++ b/src/components/dashboard/roadSafety/supervisor/Learn/index.jsx @@ -1,39 +1,39 @@ -"use client"; -import { useTheme } from "@emotion/react"; -import { OndemandVideo } from "@mui/icons-material"; -import { Button, IconButton, useMediaQuery } from "@mui/material"; - -const Learn = () => { - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - - const handleClick = () => { - const link = document.createElement("a"); - link.href = `/v3/learn-road-safety.mp4`; - link.download = "آموزش بخش نگهداری حریم راه - سامانه جامع راهداری.mp4"; - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - }; - - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - - ); -}; -export default Learn; +"use client"; +import { useTheme } from "@emotion/react"; +import { OndemandVideo } from "@mui/icons-material"; +import { Button, IconButton, useMediaQuery } from "@mui/material"; + +const Learn = () => { + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + + const handleClick = () => { + const link = document.createElement("a"); + link.href = `/v3/learn-road-safety.mp4`; + link.download = "آموزش بخش نگهداری حریم راه - سامانه جامع راهداری.mp4"; + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + }; + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + + ); +}; +export default Learn; diff --git a/src/components/dashboard/roadSafety/supervisor/RowActions/ActionPictureDialog/ActionPictureContent.jsx b/src/components/dashboard/roadSafety/supervisor/RowActions/ActionPictureDialog/ActionPictureContent.jsx index f27255b..26c8143 100644 --- a/src/components/dashboard/roadSafety/supervisor/RowActions/ActionPictureDialog/ActionPictureContent.jsx +++ b/src/components/dashboard/roadSafety/supervisor/RowActions/ActionPictureDialog/ActionPictureContent.jsx @@ -1,44 +1,44 @@ -import { Box, Stack, Typography, useTheme } from "@mui/material"; -import Image from "next/image"; - -const ActionPictureContent = ({ image, title }) => { - const theme = useTheme(); - return ( - - - {title} - - - Image - - - ); -}; -export default ActionPictureContent; +import { Box, Stack, Typography, useTheme } from "@mui/material"; +import Image from "next/image"; + +const ActionPictureContent = ({ image, title }) => { + const theme = useTheme(); + return ( + + + {title} + + + Image + + + ); +}; +export default ActionPictureContent; diff --git a/src/components/dashboard/roadSafety/supervisor/RowActions/ActionPictureDialog/index.jsx b/src/components/dashboard/roadSafety/supervisor/RowActions/ActionPictureDialog/index.jsx index 4c2911c..79736f4 100644 --- a/src/components/dashboard/roadSafety/supervisor/RowActions/ActionPictureDialog/index.jsx +++ b/src/components/dashboard/roadSafety/supervisor/RowActions/ActionPictureDialog/index.jsx @@ -1,40 +1,40 @@ -import PhotoLibraryIcon from "@mui/icons-material/PhotoLibrary"; -import { Button, Dialog, DialogActions, DialogContent, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import ActionPictureContent from "./ActionPictureContent"; - -const ActionPictureDialog = ({ image }) => { - const [openImageDialog, setOpenImageDialog] = useState(false); - - return ( - <> - - setOpenImageDialog(true)}> - - - - setOpenImageDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - maxWidth={"sm"} - scroll="paper" - > - - - - - - - - - ); -}; -export default ActionPictureDialog; +import PhotoLibraryIcon from "@mui/icons-material/PhotoLibrary"; +import { Button, Dialog, DialogActions, DialogContent, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import ActionPictureContent from "./ActionPictureContent"; + +const ActionPictureDialog = ({ image }) => { + const [openImageDialog, setOpenImageDialog] = useState(false); + + return ( + <> + + setOpenImageDialog(true)}> + + + + setOpenImageDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + maxWidth={"sm"} + scroll="paper" + > + + + + + + + + + ); +}; +export default ActionPictureDialog; diff --git a/src/components/dashboard/roadSafety/supervisor/RowActions/ConfirmForm/ConfirmContent.jsx b/src/components/dashboard/roadSafety/supervisor/RowActions/ConfirmForm/ConfirmContent.jsx index 847e242..6a40761 100644 --- a/src/components/dashboard/roadSafety/supervisor/RowActions/ConfirmForm/ConfirmContent.jsx +++ b/src/components/dashboard/roadSafety/supervisor/RowActions/ConfirmForm/ConfirmContent.jsx @@ -1,70 +1,70 @@ -import { CONFIRM_ROAD_SAFETY_BY_SUPERVISOR } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { Button, DialogActions, DialogContent, Stack, TextField } from "@mui/material"; -import { useForm } from "react-hook-form"; - -const ConfirmContent = ({ rowId, mutate, setOpenConfirmDialog }) => { - const requestServer = useRequest({ notificationSuccess: true }); - - const { - register, - handleSubmit, - formState: { isSubmitting }, - } = useForm({ - defaultValues: { - supervisor_description: "", - }, - }); - - const onSubmit = async (data) => { - const formData = new FormData(); - data.supervisor_description !== "" && formData.append("supervisor_description", data.supervisor_description); - requestServer(`${CONFIRM_ROAD_SAFETY_BY_SUPERVISOR}/${rowId}`, "post", { - data: formData, - hasSidebarUpdate: true, - }) - .then(() => { - mutate(); - setOpenConfirmDialog(false); - }) - .catch(() => {}); - }; - - return ( - <> - - - - - - - - - - - - - ); -}; - -export default ConfirmContent; +import { CONFIRM_ROAD_SAFETY_BY_SUPERVISOR } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { Button, DialogActions, DialogContent, Stack, TextField } from "@mui/material"; +import { useForm } from "react-hook-form"; + +const ConfirmContent = ({ rowId, mutate, setOpenConfirmDialog }) => { + const requestServer = useRequest({ notificationSuccess: true }); + + const { + register, + handleSubmit, + formState: { isSubmitting }, + } = useForm({ + defaultValues: { + supervisor_description: "", + }, + }); + + const onSubmit = async (data) => { + const formData = new FormData(); + data.supervisor_description !== "" && formData.append("supervisor_description", data.supervisor_description); + requestServer(`${CONFIRM_ROAD_SAFETY_BY_SUPERVISOR}/${rowId}`, "post", { + data: formData, + hasSidebarUpdate: true, + }) + .then(() => { + mutate(); + setOpenConfirmDialog(false); + }) + .catch(() => {}); + }; + + return ( + <> + + + + + + + + + + + + + ); +}; + +export default ConfirmContent; diff --git a/src/components/dashboard/roadSafety/supervisor/RowActions/ConfirmForm/index.jsx b/src/components/dashboard/roadSafety/supervisor/RowActions/ConfirmForm/index.jsx index d9aafa0..ba7b746 100644 --- a/src/components/dashboard/roadSafety/supervisor/RowActions/ConfirmForm/index.jsx +++ b/src/components/dashboard/roadSafety/supervisor/RowActions/ConfirmForm/index.jsx @@ -1,29 +1,29 @@ -import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import ConfirmContent from "./ConfirmContent"; -import DoneIcon from "@mui/icons-material/Done"; -const ConfirmForm = ({ rowId, mutate }) => { - const [openConfirmDialog, setOpenConfirmDialog] = useState(false); - return ( - <> - - setOpenConfirmDialog(true)}> - - - - - تایید فعالیت - - - - ); -}; -export default ConfirmForm; +import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import ConfirmContent from "./ConfirmContent"; +import DoneIcon from "@mui/icons-material/Done"; +const ConfirmForm = ({ rowId, mutate }) => { + const [openConfirmDialog, setOpenConfirmDialog] = useState(false); + return ( + <> + + setOpenConfirmDialog(true)}> + + + + + تایید فعالیت + + + + ); +}; +export default ConfirmForm; diff --git a/src/components/dashboard/roadSafety/supervisor/RowActions/DeleteDialog/DeleteContent.jsx b/src/components/dashboard/roadSafety/supervisor/RowActions/DeleteDialog/DeleteContent.jsx index bb88f78..ce102ee 100644 --- a/src/components/dashboard/roadSafety/supervisor/RowActions/DeleteDialog/DeleteContent.jsx +++ b/src/components/dashboard/roadSafety/supervisor/RowActions/DeleteDialog/DeleteContent.jsx @@ -1,42 +1,42 @@ -import { Button, DialogActions, DialogContent, Stack, Typography } from "@mui/material"; -import React, { useState } from "react"; -import useRequest from "@/lib/hooks/useRequest"; -import { DELETE_SAFETY_AND_PRIVACY } from "@/core/utils/routes"; - -const DeleteContent = ({ rowId, mutate, setOpenDeleteDialog }) => { - const [submitting, setSubmitting] = useState(false); - const requestServer = useRequest({ notificationSuccess: true }); - const handleClick = () => { - setSubmitting(true); - requestServer(`${DELETE_SAFETY_AND_PRIVACY}/${rowId}`, "delete", { - hasSidebarUpdate: true, - }) - .then(() => { - mutate(); - setOpenDeleteDialog(false); - setSubmitting(false); - }) - .catch(() => { - setSubmitting(false); - }); - }; - return ( - <> - - - آیا از حذف فعالیت اطمینان دارید؟ - - - - - - - - ); -}; - -export default DeleteContent; +import { Button, DialogActions, DialogContent, Stack, Typography } from "@mui/material"; +import React, { useState } from "react"; +import useRequest from "@/lib/hooks/useRequest"; +import { DELETE_SAFETY_AND_PRIVACY } from "@/core/utils/routes"; + +const DeleteContent = ({ rowId, mutate, setOpenDeleteDialog }) => { + const [submitting, setSubmitting] = useState(false); + const requestServer = useRequest({ notificationSuccess: true }); + const handleClick = () => { + setSubmitting(true); + requestServer(`${DELETE_SAFETY_AND_PRIVACY}/${rowId}`, "delete", { + hasSidebarUpdate: true, + }) + .then(() => { + mutate(); + setOpenDeleteDialog(false); + setSubmitting(false); + }) + .catch(() => { + setSubmitting(false); + }); + }; + return ( + <> + + + آیا از حذف فعالیت اطمینان دارید؟ + + + + + + + + ); +}; + +export default DeleteContent; diff --git a/src/components/dashboard/roadSafety/supervisor/RowActions/DeleteDialog/index.jsx b/src/components/dashboard/roadSafety/supervisor/RowActions/DeleteDialog/index.jsx index 596cf9a..557c628 100644 --- a/src/components/dashboard/roadSafety/supervisor/RowActions/DeleteDialog/index.jsx +++ b/src/components/dashboard/roadSafety/supervisor/RowActions/DeleteDialog/index.jsx @@ -1,32 +1,32 @@ -import DeleteIcon from "@mui/icons-material/Delete"; -import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import DeleteContent from "./DeleteContent"; -const DeleteForm = ({ rowId, mutate }) => { - const [openDeleteDialog, setOpenDeleteDialog] = useState(false); - - return ( - <> - - setOpenDeleteDialog(true)}> - - - - setOpenDeleteDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - حذف فعالیت - - - - ); -}; -export default DeleteForm; +import DeleteIcon from "@mui/icons-material/Delete"; +import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import DeleteContent from "./DeleteContent"; +const DeleteForm = ({ rowId, mutate }) => { + const [openDeleteDialog, setOpenDeleteDialog] = useState(false); + + return ( + <> + + setOpenDeleteDialog(true)}> + + + + setOpenDeleteDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + حذف فعالیت + + + + ); +}; +export default DeleteForm; diff --git a/src/components/dashboard/roadSafety/supervisor/RowActions/DescriptionForm/index.jsx b/src/components/dashboard/roadSafety/supervisor/RowActions/DescriptionForm/index.jsx index 91b135a..efae7b0 100644 --- a/src/components/dashboard/roadSafety/supervisor/RowActions/DescriptionForm/index.jsx +++ b/src/components/dashboard/roadSafety/supervisor/RowActions/DescriptionForm/index.jsx @@ -1,51 +1,51 @@ -import { Dialog, DialogContent, DialogTitle, IconButton, Tooltip, Typography, Card, CardContent } from "@mui/material"; -import { useState } from "react"; -import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye"; -import CloseIcon from "@mui/icons-material/Close"; - -const DescriptionForm = ({ description }) => { - const [openOfficerDescriptionDialog, setOpenOfficerDescriptionDialog] = useState(false); - - return ( - <> - - setOpenOfficerDescriptionDialog(true)}> - - - - setOpenOfficerDescriptionDialog(false)} - PaperProps={{ - sx: { - transition: "all .3s", - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - borderRadius: 2, - padding: 1, - }, - }} - maxWidth="sm" - fullWidth - dir="rtl" - > - - - توضیحات ناظر - - setOpenOfficerDescriptionDialog(false)} size="small"> - - - - - - - {description || "هیچ توضیحی موجود نیست"} - - - - - - ); -}; - -export default DescriptionForm; +import { Dialog, DialogContent, DialogTitle, IconButton, Tooltip, Typography, Card, CardContent } from "@mui/material"; +import { useState } from "react"; +import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye"; +import CloseIcon from "@mui/icons-material/Close"; + +const DescriptionForm = ({ description }) => { + const [openOfficerDescriptionDialog, setOpenOfficerDescriptionDialog] = useState(false); + + return ( + <> + + setOpenOfficerDescriptionDialog(true)}> + + + + setOpenOfficerDescriptionDialog(false)} + PaperProps={{ + sx: { + transition: "all .3s", + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + borderRadius: 2, + padding: 1, + }, + }} + maxWidth="sm" + fullWidth + dir="rtl" + > + + + توضیحات ناظر + + setOpenOfficerDescriptionDialog(false)} size="small"> + + + + + + + {description || "هیچ توضیحی موجود نیست"} + + + + + + ); +}; + +export default DescriptionForm; diff --git a/src/components/dashboard/roadSafety/supervisor/RowActions/FinishDescriptionForm/index.jsx b/src/components/dashboard/roadSafety/supervisor/RowActions/FinishDescriptionForm/index.jsx index 6178ae8..a8d63d6 100644 --- a/src/components/dashboard/roadSafety/supervisor/RowActions/FinishDescriptionForm/index.jsx +++ b/src/components/dashboard/roadSafety/supervisor/RowActions/FinishDescriptionForm/index.jsx @@ -1,51 +1,51 @@ -import { Dialog, DialogContent, DialogTitle, IconButton, Tooltip, Typography, Card, CardContent } from "@mui/material"; -import { useState } from "react"; -import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye"; -import CloseIcon from "@mui/icons-material/Close"; - -const FinishDescriptionForm = ({ description }) => { - const [openOfficerDescriptionDialog, setOpenOfficerDescriptionDialog] = useState(false); - - return ( - <> - - setOpenOfficerDescriptionDialog(true)}> - - - - setOpenOfficerDescriptionDialog(false)} - PaperProps={{ - sx: { - transition: "all .3s", - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - borderRadius: 2, - padding: 1, - }, - }} - maxWidth="sm" - fullWidth - dir="rtl" - > - - - علت خاتمه فرایند - - setOpenOfficerDescriptionDialog(false)} size="small"> - - - - - - - {description || "هیچ توضیحی موجود نیست"} - - - - - - ); -}; - -export default FinishDescriptionForm; +import { Dialog, DialogContent, DialogTitle, IconButton, Tooltip, Typography, Card, CardContent } from "@mui/material"; +import { useState } from "react"; +import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye"; +import CloseIcon from "@mui/icons-material/Close"; + +const FinishDescriptionForm = ({ description }) => { + const [openOfficerDescriptionDialog, setOpenOfficerDescriptionDialog] = useState(false); + + return ( + <> + + setOpenOfficerDescriptionDialog(true)}> + + + + setOpenOfficerDescriptionDialog(false)} + PaperProps={{ + sx: { + transition: "all .3s", + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + borderRadius: 2, + padding: 1, + }, + }} + maxWidth="sm" + fullWidth + dir="rtl" + > + + + علت خاتمه فرایند + + setOpenOfficerDescriptionDialog(false)} size="small"> + + + + + + + {description || "هیچ توضیحی موجود نیست"} + + + + + + ); +}; + +export default FinishDescriptionForm; diff --git a/src/components/dashboard/roadSafety/supervisor/RowActions/JudiciaryDocumentDialog/JudiciaryDocumentContent.jsx b/src/components/dashboard/roadSafety/supervisor/RowActions/JudiciaryDocumentDialog/JudiciaryDocumentContent.jsx index 95a3f1e..8127ada 100644 --- a/src/components/dashboard/roadSafety/supervisor/RowActions/JudiciaryDocumentDialog/JudiciaryDocumentContent.jsx +++ b/src/components/dashboard/roadSafety/supervisor/RowActions/JudiciaryDocumentDialog/JudiciaryDocumentContent.jsx @@ -1,43 +1,43 @@ -import { Box, Button, Chip, Divider, Grid, Typography } from "@mui/material"; -import DownloadIcon from "@mui/icons-material/Download"; -import ArticleIcon from "@mui/icons-material/Article"; - -const JudiciaryDocumentContent = ({ judiciaryDocumentDetails }) => { - return ( - - {judiciaryDocumentDetails.map((judiciaryDocument, index) => { - return ( - - - } - label={ - - مستندات قضایی {index + 1} - - } - /> - - - - - ); - })} - - ); -}; -export default JudiciaryDocumentContent; +import { Box, Button, Chip, Divider, Grid, Typography } from "@mui/material"; +import DownloadIcon from "@mui/icons-material/Download"; +import ArticleIcon from "@mui/icons-material/Article"; + +const JudiciaryDocumentContent = ({ judiciaryDocumentDetails }) => { + return ( + + {judiciaryDocumentDetails.map((judiciaryDocument, index) => { + return ( + + + } + label={ + + مستندات قضایی {index + 1} + + } + /> + + + + + ); + })} + + ); +}; +export default JudiciaryDocumentContent; diff --git a/src/components/dashboard/roadSafety/supervisor/RowActions/JudiciaryDocumentDialog/JudiciaryDocumentController.jsx b/src/components/dashboard/roadSafety/supervisor/RowActions/JudiciaryDocumentDialog/JudiciaryDocumentController.jsx index 0773130..0d4c245 100644 --- a/src/components/dashboard/roadSafety/supervisor/RowActions/JudiciaryDocumentDialog/JudiciaryDocumentController.jsx +++ b/src/components/dashboard/roadSafety/supervisor/RowActions/JudiciaryDocumentDialog/JudiciaryDocumentController.jsx @@ -1,35 +1,35 @@ -import { useEffect, useState } from "react"; -import useRequest from "@/lib/hooks/useRequest"; -import DialogLoading from "@/core/components/DialogLoading"; -import JudiciaryDocumentContent from "./JudiciaryDocumentContent"; -import { DESERIALIZE_JUDICIARY_DOCUMENT } from "@/core/utils/routes"; -import { Typography } from "@mui/material"; - -const JudiciaryDocumentController = ({ rowId }) => { - const requestServer = useRequest(); - const [judiciaryDocumentDetails, setJudiciaryDocumentDetails] = useState([]); - const [judiciaryDocumentDetailsLoading, setJudiciaryDocumentDetailsLoading] = useState(false); - useEffect(() => { - setJudiciaryDocumentDetailsLoading(true); - requestServer(`${DESERIALIZE_JUDICIARY_DOCUMENT}/${rowId}`, "get") - .then((response) => { - setJudiciaryDocumentDetails(response.data.data); - setJudiciaryDocumentDetailsLoading(false); - }) - .catch((e) => { - setJudiciaryDocumentDetailsLoading(false); - }); - }, [rowId]); - return ( - <> - {judiciaryDocumentDetailsLoading ? ( - - ) : judiciaryDocumentDetails.length > 0 ? ( - - ) : ( - بدون مستندات - )} - - ); -}; -export default JudiciaryDocumentController; +import { useEffect, useState } from "react"; +import useRequest from "@/lib/hooks/useRequest"; +import DialogLoading from "@/core/components/DialogLoading"; +import JudiciaryDocumentContent from "./JudiciaryDocumentContent"; +import { DESERIALIZE_JUDICIARY_DOCUMENT } from "@/core/utils/routes"; +import { Typography } from "@mui/material"; + +const JudiciaryDocumentController = ({ rowId }) => { + const requestServer = useRequest(); + const [judiciaryDocumentDetails, setJudiciaryDocumentDetails] = useState([]); + const [judiciaryDocumentDetailsLoading, setJudiciaryDocumentDetailsLoading] = useState(false); + useEffect(() => { + setJudiciaryDocumentDetailsLoading(true); + requestServer(`${DESERIALIZE_JUDICIARY_DOCUMENT}/${rowId}`, "get") + .then((response) => { + setJudiciaryDocumentDetails(response.data.data); + setJudiciaryDocumentDetailsLoading(false); + }) + .catch((e) => { + setJudiciaryDocumentDetailsLoading(false); + }); + }, [rowId]); + return ( + <> + {judiciaryDocumentDetailsLoading ? ( + + ) : judiciaryDocumentDetails.length > 0 ? ( + + ) : ( + بدون مستندات + )} + + ); +}; +export default JudiciaryDocumentController; diff --git a/src/components/dashboard/roadSafety/supervisor/RowActions/JudiciaryDocumentDialog/index.jsx b/src/components/dashboard/roadSafety/supervisor/RowActions/JudiciaryDocumentDialog/index.jsx index 575d4c5..d6bbd16 100644 --- a/src/components/dashboard/roadSafety/supervisor/RowActions/JudiciaryDocumentDialog/index.jsx +++ b/src/components/dashboard/roadSafety/supervisor/RowActions/JudiciaryDocumentDialog/index.jsx @@ -1,40 +1,40 @@ -import { Button, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import ArticleIcon from "@mui/icons-material/Article"; -import React, { useState } from "react"; -import JudiciaryDocumentController from "./JudiciaryDocumentController"; - -const JudiciaryDocumentDialog = ({ rowId }) => { - const [openJudiciaryDocumentDialog, setOpenJudiciaryDocumentDialog] = useState(false); - return ( - <> - - setOpenJudiciaryDocumentDialog(true)}> - - - - setOpenJudiciaryDocumentDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"sm"} - fullWidth - > - مشاهده مستندات قضایی - - - - - - - - - ); -}; -export default JudiciaryDocumentDialog; +import { Button, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import ArticleIcon from "@mui/icons-material/Article"; +import React, { useState } from "react"; +import JudiciaryDocumentController from "./JudiciaryDocumentController"; + +const JudiciaryDocumentDialog = ({ rowId }) => { + const [openJudiciaryDocumentDialog, setOpenJudiciaryDocumentDialog] = useState(false); + return ( + <> + + setOpenJudiciaryDocumentDialog(true)}> + + + + setOpenJudiciaryDocumentDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"sm"} + fullWidth + > + مشاهده مستندات قضایی + + + + + + + + + ); +}; +export default JudiciaryDocumentDialog; diff --git a/src/components/dashboard/roadSafety/supervisor/RowActions/LocationForm/LocationFormContent.jsx b/src/components/dashboard/roadSafety/supervisor/RowActions/LocationForm/LocationFormContent.jsx index 14b3db3..08e4730 100644 --- a/src/components/dashboard/roadSafety/supervisor/RowActions/LocationForm/LocationFormContent.jsx +++ b/src/components/dashboard/roadSafety/supervisor/RowActions/LocationForm/LocationFormContent.jsx @@ -1,35 +1,35 @@ -"use client"; -import { Box, Button, DialogActions, DialogContent, Stack } from "@mui/material"; -import React from "react"; -import dynamic from "next/dynamic"; -import MapLoading from "@/core/components/MapLayer/Loading"; -import ShowLocationMarker from "@/core/components/ShowLocationMarker"; -const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { - loading: () => , - ssr: false, -}); - -const LocationFormContent = ({ setOpenLocationDialog, start_lat, start_lng, end_lat, end_lng }) => { - return ( - <> - - - - - - - - - - - - ); -}; -export default LocationFormContent; +"use client"; +import { Box, Button, DialogActions, DialogContent, Stack } from "@mui/material"; +import React from "react"; +import dynamic from "next/dynamic"; +import MapLoading from "@/core/components/MapLayer/Loading"; +import ShowLocationMarker from "@/core/components/ShowLocationMarker"; +const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { + loading: () => , + ssr: false, +}); + +const LocationFormContent = ({ setOpenLocationDialog, start_lat, start_lng, end_lat, end_lng }) => { + return ( + <> + + + + + + + + + + + + ); +}; +export default LocationFormContent; diff --git a/src/components/dashboard/roadSafety/supervisor/RowActions/LocationForm/index.jsx b/src/components/dashboard/roadSafety/supervisor/RowActions/LocationForm/index.jsx index d614215..6c90746 100644 --- a/src/components/dashboard/roadSafety/supervisor/RowActions/LocationForm/index.jsx +++ b/src/components/dashboard/roadSafety/supervisor/RowActions/LocationForm/index.jsx @@ -1,40 +1,40 @@ -import React, { useState } from "react"; -import { Tooltip, IconButton, Dialog, DialogTitle } from "@mui/material"; -import ExploreIcon from "@mui/icons-material/Explore"; -import LocationFormContent from "./LocationFormContent"; -const LocationForm = ({ start_lat, start_lng, end_lat, end_lng }) => { - const [openLocationDialog, setOpenLocationDialog] = useState(false); - - return ( - <> - - setOpenLocationDialog(true)}> - - - - setOpenLocationDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - موقعیت - {openLocationDialog && ( - - )} - - - ); -}; -export default LocationForm; +import React, { useState } from "react"; +import { Tooltip, IconButton, Dialog, DialogTitle } from "@mui/material"; +import ExploreIcon from "@mui/icons-material/Explore"; +import LocationFormContent from "./LocationFormContent"; +const LocationForm = ({ start_lat, start_lng, end_lat, end_lng }) => { + const [openLocationDialog, setOpenLocationDialog] = useState(false); + + return ( + <> + + setOpenLocationDialog(true)}> + + + + setOpenLocationDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + موقعیت + {openLocationDialog && ( + + )} + + + ); +}; +export default LocationForm; diff --git a/src/components/dashboard/roadSafety/supervisor/RowActions/OperatorDescriptionForm/index.jsx b/src/components/dashboard/roadSafety/supervisor/RowActions/OperatorDescriptionForm/index.jsx index 9a59745..f446b9d 100644 --- a/src/components/dashboard/roadSafety/supervisor/RowActions/OperatorDescriptionForm/index.jsx +++ b/src/components/dashboard/roadSafety/supervisor/RowActions/OperatorDescriptionForm/index.jsx @@ -1,51 +1,51 @@ -import { Dialog, DialogContent, DialogTitle, IconButton, Tooltip, Typography, Card, CardContent } from "@mui/material"; -import { useState } from "react"; -import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye"; -import CloseIcon from "@mui/icons-material/Close"; - -const OperatorDescriptionForm = ({ description }) => { - const [openOfficerDescriptionDialog, setOpenOfficerDescriptionDialog] = useState(false); - - return ( - <> - - setOpenOfficerDescriptionDialog(true)}> - - - - setOpenOfficerDescriptionDialog(false)} - PaperProps={{ - sx: { - transition: "all .3s", - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - borderRadius: 2, - padding: 1, - }, - }} - maxWidth="sm" - fullWidth - dir="rtl" - > - - - توضیحات کارشناس - - setOpenOfficerDescriptionDialog(false)} size="small"> - - - - - - - {description || "هیچ توضیحی موجود نیست"} - - - - - - ); -}; - -export default OperatorDescriptionForm; +import { Dialog, DialogContent, DialogTitle, IconButton, Tooltip, Typography, Card, CardContent } from "@mui/material"; +import { useState } from "react"; +import RemoveRedEyeIcon from "@mui/icons-material/RemoveRedEye"; +import CloseIcon from "@mui/icons-material/Close"; + +const OperatorDescriptionForm = ({ description }) => { + const [openOfficerDescriptionDialog, setOpenOfficerDescriptionDialog] = useState(false); + + return ( + <> + + setOpenOfficerDescriptionDialog(true)}> + + + + setOpenOfficerDescriptionDialog(false)} + PaperProps={{ + sx: { + transition: "all .3s", + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + borderRadius: 2, + padding: 1, + }, + }} + maxWidth="sm" + fullWidth + dir="rtl" + > + + + توضیحات کارشناس + + setOpenOfficerDescriptionDialog(false)} size="small"> + + + + + + + {description || "هیچ توضیحی موجود نیست"} + + + + + + ); +}; + +export default OperatorDescriptionForm; diff --git a/src/components/dashboard/roadSafety/supervisor/RowActions/RecognizePictureDialog/RecognizePictureContent.jsx b/src/components/dashboard/roadSafety/supervisor/RowActions/RecognizePictureDialog/RecognizePictureContent.jsx index 39dbdcf..a50191f 100644 --- a/src/components/dashboard/roadSafety/supervisor/RowActions/RecognizePictureDialog/RecognizePictureContent.jsx +++ b/src/components/dashboard/roadSafety/supervisor/RowActions/RecognizePictureDialog/RecognizePictureContent.jsx @@ -1,44 +1,44 @@ -import { Box, Stack, Typography, useTheme } from "@mui/material"; -import Image from "next/image"; - -const RecognizePictureContent = ({ image, title }) => { - const theme = useTheme(); - return ( - - - {title} - - - Image - - - ); -}; -export default RecognizePictureContent; +import { Box, Stack, Typography, useTheme } from "@mui/material"; +import Image from "next/image"; + +const RecognizePictureContent = ({ image, title }) => { + const theme = useTheme(); + return ( + + + {title} + + + Image + + + ); +}; +export default RecognizePictureContent; diff --git a/src/components/dashboard/roadSafety/supervisor/RowActions/RecognizePictureDialog/index.jsx b/src/components/dashboard/roadSafety/supervisor/RowActions/RecognizePictureDialog/index.jsx index 72ef4ea..f51e501 100644 --- a/src/components/dashboard/roadSafety/supervisor/RowActions/RecognizePictureDialog/index.jsx +++ b/src/components/dashboard/roadSafety/supervisor/RowActions/RecognizePictureDialog/index.jsx @@ -1,40 +1,40 @@ -import PhotoLibraryIcon from "@mui/icons-material/PhotoLibrary"; -import { Button, Dialog, DialogActions, DialogContent, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import RecognizePictureContent from "./RecognizePictureContent"; - -const RecognizePictureDialog = ({ image }) => { - const [openImageDialog, setOpenImageDialog] = useState(false); - - return ( - <> - - setOpenImageDialog(true)}> - - - - setOpenImageDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - maxWidth={"sm"} - scroll="paper" - > - - - - - - - - - ); -}; -export default RecognizePictureDialog; +import PhotoLibraryIcon from "@mui/icons-material/PhotoLibrary"; +import { Button, Dialog, DialogActions, DialogContent, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import RecognizePictureContent from "./RecognizePictureContent"; + +const RecognizePictureDialog = ({ image }) => { + const [openImageDialog, setOpenImageDialog] = useState(false); + + return ( + <> + + setOpenImageDialog(true)}> + + + + setOpenImageDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + maxWidth={"sm"} + scroll="paper" + > + + + + + + + + + ); +}; +export default RecognizePictureDialog; diff --git a/src/components/dashboard/roadSafety/supervisor/RowActions/RejectForm/RejectContent.jsx b/src/components/dashboard/roadSafety/supervisor/RowActions/RejectForm/RejectContent.jsx index bed259d..65c8d24 100644 --- a/src/components/dashboard/roadSafety/supervisor/RowActions/RejectForm/RejectContent.jsx +++ b/src/components/dashboard/roadSafety/supervisor/RowActions/RejectForm/RejectContent.jsx @@ -1,83 +1,83 @@ -import { REJECT_ROAD_SAFETY_BY_SUPERVISOR } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import { yupResolver } from "@hookform/resolvers/yup"; -import { Button, DialogActions, DialogContent, Stack, TextField } from "@mui/material"; -import { useForm } from "react-hook-form"; -import * as Yup from "yup"; - -const RejectContent = ({ rowId, mutate, setOpenRejectDialog }) => { - const requestServer = useRequest({ notificationSuccess: true }); - - const validationSchema = Yup.object().shape({ - supervisor_description: Yup.string().required("لطفاً توضیحات را وارد کنید."), - }); - - const { - register, - handleSubmit, - formState: { errors, isSubmitting }, - reset, - } = useForm({ - defaultValues: { - supervisor_description: "", - }, - resolver: yupResolver(validationSchema), - mode: "all", - }); - - const onSubmit = async (data) => { - const formData = new FormData(); - formData.append("supervisor_description", data.supervisor_description); - await requestServer(`${REJECT_ROAD_SAFETY_BY_SUPERVISOR}/${rowId}`, "post", { - data: formData, - hasSidebarUpdate: true, - }) - .then(() => { - mutate(); - setOpenRejectDialog(false); - }) - .catch(() => {}) - .finally(() => { - reset(); - }); - }; - - return ( - <> - - - - - - - - - - - - - ); -}; -export default RejectContent; +import { REJECT_ROAD_SAFETY_BY_SUPERVISOR } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { Button, DialogActions, DialogContent, Stack, TextField } from "@mui/material"; +import { useForm } from "react-hook-form"; +import * as Yup from "yup"; + +const RejectContent = ({ rowId, mutate, setOpenRejectDialog }) => { + const requestServer = useRequest({ notificationSuccess: true }); + + const validationSchema = Yup.object().shape({ + supervisor_description: Yup.string().required("لطفاً توضیحات را وارد کنید."), + }); + + const { + register, + handleSubmit, + formState: { errors, isSubmitting }, + reset, + } = useForm({ + defaultValues: { + supervisor_description: "", + }, + resolver: yupResolver(validationSchema), + mode: "all", + }); + + const onSubmit = async (data) => { + const formData = new FormData(); + formData.append("supervisor_description", data.supervisor_description); + await requestServer(`${REJECT_ROAD_SAFETY_BY_SUPERVISOR}/${rowId}`, "post", { + data: formData, + hasSidebarUpdate: true, + }) + .then(() => { + mutate(); + setOpenRejectDialog(false); + }) + .catch(() => {}) + .finally(() => { + reset(); + }); + }; + + return ( + <> + + + + + + + + + + + + + ); +}; +export default RejectContent; diff --git a/src/components/dashboard/roadSafety/supervisor/RowActions/RejectForm/index.jsx b/src/components/dashboard/roadSafety/supervisor/RowActions/RejectForm/index.jsx index 2f08152..94f78de 100644 --- a/src/components/dashboard/roadSafety/supervisor/RowActions/RejectForm/index.jsx +++ b/src/components/dashboard/roadSafety/supervisor/RowActions/RejectForm/index.jsx @@ -1,29 +1,29 @@ -import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import RejectContent from "./RejectContent"; -import ClearIcon from "@mui/icons-material/Clear"; -const RejectForm = ({ rowId, mutate }) => { - const [openRejectDialog, setOpenRejectDialog] = useState(false); - return ( - <> - - setOpenRejectDialog(true)}> - - - - - عدم تایید فعالیت - - - - ); -}; -export default RejectForm; +import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import RejectContent from "./RejectContent"; +import ClearIcon from "@mui/icons-material/Clear"; +const RejectForm = ({ rowId, mutate }) => { + const [openRejectDialog, setOpenRejectDialog] = useState(false); + return ( + <> + + setOpenRejectDialog(true)}> + + + + + عدم تایید فعالیت + + + + ); +}; +export default RejectForm; diff --git a/src/components/dashboard/roadSafety/supervisor/RowActions/index.jsx b/src/components/dashboard/roadSafety/supervisor/RowActions/index.jsx index 1deca9d..09c9d2e 100644 --- a/src/components/dashboard/roadSafety/supervisor/RowActions/index.jsx +++ b/src/components/dashboard/roadSafety/supervisor/RowActions/index.jsx @@ -1,22 +1,22 @@ -import { usePermissions } from "@/lib/hooks/usePermissions"; -import { Box } from "@mui/material"; -import ConfirmForm from "./ConfirmForm"; -import DeleteForm from "./DeleteDialog"; -import RejectForm from "./RejectForm"; - -const RowActions = ({ row, mutate }) => { - const { data: userPermissions } = usePermissions(); - const hasDeletePermission = userPermissions?.includes("delete-safety-and-privacy"); - return ( - - {row.original.is_finished == 1 && row.original.status === 0 && ( - <> - - - - )} - {hasDeletePermission && } - - ); -}; -export default RowActions; +import { usePermissions } from "@/lib/hooks/usePermissions"; +import { Box } from "@mui/material"; +import ConfirmForm from "./ConfirmForm"; +import DeleteForm from "./DeleteDialog"; +import RejectForm from "./RejectForm"; + +const RowActions = ({ row, mutate }) => { + const { data: userPermissions } = usePermissions(); + const hasDeletePermission = userPermissions?.includes("delete-safety-and-privacy"); + return ( + + {row.original.is_finished == 1 && row.original.status === 0 && ( + <> + + + + )} + {hasDeletePermission && } + + ); +}; +export default RowActions; diff --git a/src/components/dashboard/roadSafety/supervisor/SupervisorList.jsx b/src/components/dashboard/roadSafety/supervisor/SupervisorList.jsx index 93271f9..cd79cc2 100644 --- a/src/components/dashboard/roadSafety/supervisor/SupervisorList.jsx +++ b/src/components/dashboard/roadSafety/supervisor/SupervisorList.jsx @@ -1,606 +1,606 @@ -"use client"; -import CustomSelectByDependency from "@/core/components/DataTable/filter/fieldsType/CustomSelectByDependency"; -import DataTableWithAuth from "@/core/components/DataTableWithAuth"; -import { GET_SAFETY_AND_PRIVACY_SUPERVISOR } from "@/core/utils/routes"; -import useSafetyAndPrivacyGetItems from "@/lib/hooks/useSafetyAndPrivacyGetItems"; -import { Box, Stack } from "@mui/material"; -import moment from "jalali-moment"; -import { useEffect, useMemo, useState } from "react"; -import RowActions from "./RowActions"; -import ActionPictureDialog from "./RowActions/ActionPictureDialog"; -import DescriptionForm from "./RowActions/DescriptionForm"; -import FinishDescriptionForm from "./RowActions/FinishDescriptionForm"; -import JudiciaryDocumentDialog from "./RowActions/JudiciaryDocumentDialog"; -import LocationForm from "./RowActions/LocationForm"; -import OperatorDescriptionForm from "./RowActions/OperatorDescriptionForm"; -import RecognizePictureDialog from "./RowActions/RecognizePictureDialog"; -import Toolbar from "./Toolbar"; -import { usePermissions } from "@/lib/hooks/usePermissions"; -import { useAuth } from "@/lib/contexts/auth"; -import useProvinces from "@/lib/hooks/useProvince"; -import useEdaratLists from "@/lib/hooks/useEdaratLists"; -import BlinkingCell from "@/core/components/BlinkingCell"; - -const stepOptions = [ - { value: "", label: "همه گام ها" }, - { value: 1, label: "گام اول (شناسایی)" }, - { value: 2, label: "گام دوم (مستندات قضایی)" }, - { value: 3, label: "گام سوم (برخورد)" }, -]; -const statusOptions = [ - { value: "", label: "همه وضعیت ها" }, - { value: 0, label: "درحال بررسی" }, - { value: 1, label: "تایید" }, - { value: 2, label: "عدم تایید" }, -]; -const finishOptions = [ - { value: "", label: "همه موارد" }, - { value: 0, label: "در جریان" }, - { value: 1, label: "خاتمه یافته" }, -]; -const axisOptions = [ - { value: "", label: "همه محور ها" }, - { value: 1, label: "آزادراه" }, - { value: 2, label: "بزرگراه" }, - { value: 3, label: "اصلی" }, - { value: 4, label: "فرعی" }, - { value: 5, label: "روستایی" }, -]; -const SupervisorList = () => { - const { data: userPermissions } = usePermissions(); - const hasCountryPermission = userPermissions?.includes("show-safety-and-privacy-operator-cartable"); - const { user } = useAuth(); - - const columns = useMemo(() => { - const provinceColumn = { - header: "استان", - id: "province_id", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - grow: false, - size: 130, - ColumnSelectComponent: (props) => { - const { provinces, errorProvinces, loadingProvinces } = useProvinces(); - const getColumnSelectOptions = useMemo(() => { - if (loadingProvinces) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorProvinces) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: "کل کشور" }, - ...provinces.map((province) => ({ - value: province.id, - label: province.name_fa, - })), - ]; - }, [provinces, errorProvinces, loadingProvinces]); - return ( - - ); - }, - Cell: ({ renderedCellValue, row }) => <>{row.original.province_fa}, - }; - return [ - { - accessorKey: "id", - header: "کد یکتا", - id: "id", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - Cell: ({ row }) => ( - - ), - }, - ...(hasCountryPermission ? [provinceColumn] : []), - { - header: "اداره", - id: "edare_shahri_id", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - dependencyId: hasCountryPermission ? "province_id" : null, - grow: false, - size: 120, - ColumnSelectComponent: (props) => { - const { edaratList, loadingEdaratList, errorEdaratList } = useEdaratLists( - hasCountryPermission ? props.dependencyFieldValue.value : user.province_id - ); - const [prevDependency, setPrevDependency] = useState( - hasCountryPermission ? props.dependencyFieldValue.value : user.province_id - ); - - const getColumnSelectOptions = useMemo(() => { - if (hasCountryPermission && props.dependencyFieldValue.value === "") { - return [{ value: "empty", label: "ابتدا استان را انتخاب کنید" }]; - } - if (loadingEdaratList) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorEdaratList) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: "کل ادارات" }, - ...edaratList.map((edare) => ({ - value: edare.id, - label: edare.name_fa, - })), - ]; - }, [edaratList, loadingEdaratList, errorEdaratList]); - useEffect(() => { - if (hasCountryPermission) return; - if (prevDependency === props.dependencyFieldValue?.value) return; - props.handleChange({ ...props.filterParameters, value: "" }); - setPrevDependency(props.dependencyFieldValue?.value); - }, [props.dependencyFieldValue?.value, hasCountryPermission]); - return ( - - ); - }, - Cell: ({ renderedCellValue, row }) => <>{row.original.edare_shahri_name}, - }, - { - header: "اطلاعات فعالیت", - id: "info", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - columns: [ - { - accessorKey: "info_id", - header: "مورد مشاهده شده", - id: "info_id", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - grow: false, - size: 100, - ColumnSelectComponent: (props) => { - const { itemsList, loadingItemsList, errorItemsList } = useSafetyAndPrivacyGetItems(); - - const getColumnSelectOptions = useMemo(() => { - if (loadingItemsList) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorItemsList) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: "همه موارد" }, - ...itemsList.map((item) => ({ - value: item.id, - label: item.name, - })), - ]; - }, [itemsList, loadingItemsList, errorItemsList]); - - return ( - - ); - }, - Cell: ({ row }) => <>{row.original.info_fa}, - }, - { - accessorKey: "axis_type_id", - header: "نوع محور", - id: "axis_type_id", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - sortDescFirst: true, - grow: false, - size: 100, - columnSelectOption: () => { - return axisOptions.map((status) => ({ - value: status.value, - label: status.label, - })); - }, - Cell: ({ row }) => (row.original?.axis_type_name ? <>{row.original.axis_type_name} : <>-), - }, - { - accessorKey: "location", - header: "موقعیت", - id: "location", - enableColumnFilter: false, - enableSorting: false, - datatype: "array", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ row }) => { - return ( - - - - ); - }, - }, - { - accessorFn: (row) => moment(row.created_at).locale("fa").format("HH:mm | yyyy/MM/DD"), - header: "تاریخ ثبت", - id: "created_at", - enableColumnFilter: true, - datatype: "date", - filterMode: "between", - grow: false, - size: 100, - }, - ], - }, - { - header: "وضعیت فعالیت", - id: "allstatus", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - columns: [ - { - header: "وضعیت گام ها", - id: "step", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - sortDescFirst: true, - grow: false, - size: 100, - columnSelectOption: () => { - return stepOptions.map((status) => ({ - value: status.value, - label: status.label, - })); - }, - Cell: ({ row }) => <>{row.original.step_fa}, - }, - { - header: "وضعیت فرایند", - id: "is_finished", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - sortDescFirst: true, - grow: false, - size: 100, - columnSelectOption: () => { - return finishOptions.map((status) => ({ - value: status.value, - label: status.label, - })); - }, - Cell: ({ row }) => ( - <> - {row.original.is_finished == 1 - ? "خاتمه یافته" - : row.original.is_finished == 0 - ? "در جریان" - : "-"} - - ), - }, - { - header: "علت خاتمه فرایند", - id: "finished_description", - enableColumnFilter: false, - datatype: "numeric", - filterMode: "equals", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ row }) => - row.original.final_description ? ( - - - - ) : ( - "-" - ), - }, - { - header: "وضعیت نظارت", - id: "status", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - sortDescFirst: true, - grow: false, - size: 100, - columnSelectOption: () => { - return statusOptions.map((status) => ({ - value: status.value, - label: status.label, - })); - }, - Cell: ({ row }) => <>{row.original.status_fa || "-"}, - }, - { - header: "توضیحات ناظر", - id: "supervisor_description", - enableColumnFilter: false, - datatype: "numeric", - filterMode: "equals", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ row }) => - row.original.supervisor_description ? ( - - - - ) : ( - "-" - ), - }, - ], - }, - { - header: "گام اول (شناسایی)", - id: "stepOne", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - columns: [ - { - accessorKey: "recognize_picture", - header: "تصویر بازدید", - id: "recognize_picture", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return renderedCellValue ? ( - - - - ) : ( - <>- - ); - }, - }, - { - accessorFn: (row) => - row.activity_date_time ? ( - moment(row.activity_date_time).locale("fa").format("HH:mm | yyyy/MM/DD") - ) : ( - <>- - ), - header: "تاریخ بازدید", - id: "activity_date_time", - enableColumnFilter: true, - datatype: "date", - filterMode: "between", - grow: false, - size: 100, - }, - ], - }, - { - header: "گام دوم (مستندات قضایی)", - id: "stepTwo", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - columns: [ - { - header: "مستندات قضایی", - id: "judiciary_document", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ row }) => { - return ( - - {row.original.judiciary_document_upload_date !== "0000-00-00 00:00:00" && - row.original.judiciary_document_upload_date ? ( - - ) : ( - <>- - )} - - ); - }, - }, - { - accessorFn: (row) => { - const date = row.judiciary_document_upload_date; - if (!date || date === "0000-00-00 00:00:00") { - return <>-; - } - return moment(date, "YYYY-MM-DD HH:mm:ss").locale("fa").format("HH:mm | yyyy/MM/DD"); - }, - - header: "تاریخ بارگذاری مستندات", - id: "judiciary_document_upload_date", - enableColumnFilter: true, - datatype: "date", - filterMode: "between", - grow: false, - size: 100, - }, - { - header: "توضیحات کارشناس", - id: "operator_description", - enableColumnFilter: false, - datatype: "numeric", - filterMode: "equals", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ row }) => - row.original.operator_description ? ( - - - - ) : ( - "-" - ), - }, - ], - }, - { - header: "گام سوم (برخورد)", - id: "stepThree", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - columns: [ - { - accessorKey: "action_picture", - header: "تصویر اقدام", - id: "action_picture", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue }) => { - return renderedCellValue ? ( - - - - ) : ( - <>- - ); - }, - }, - { - accessorFn: (row) => - row.action_date ? ( - moment(row.action_date).locale("fa").format("HH:mm | yyyy/MM/DD") - ) : ( - <>- - ), - header: "تاریخ اقدام", - id: "action_date", - enableColumnFilter: true, - datatype: "date", - filterMode: "between", - grow: false, - size: 100, - }, - ], - }, - ]; - }, []); - - return ( - <> - - - - - ); -}; -export default SupervisorList; +"use client"; +import CustomSelectByDependency from "@/core/components/DataTable/filter/fieldsType/CustomSelectByDependency"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import { GET_SAFETY_AND_PRIVACY_SUPERVISOR } from "@/core/utils/routes"; +import useSafetyAndPrivacyGetItems from "@/lib/hooks/useSafetyAndPrivacyGetItems"; +import { Box, Stack } from "@mui/material"; +import moment from "jalali-moment"; +import { useEffect, useMemo, useState } from "react"; +import RowActions from "./RowActions"; +import ActionPictureDialog from "./RowActions/ActionPictureDialog"; +import DescriptionForm from "./RowActions/DescriptionForm"; +import FinishDescriptionForm from "./RowActions/FinishDescriptionForm"; +import JudiciaryDocumentDialog from "./RowActions/JudiciaryDocumentDialog"; +import LocationForm from "./RowActions/LocationForm"; +import OperatorDescriptionForm from "./RowActions/OperatorDescriptionForm"; +import RecognizePictureDialog from "./RowActions/RecognizePictureDialog"; +import Toolbar from "./Toolbar"; +import { usePermissions } from "@/lib/hooks/usePermissions"; +import { useAuth } from "@/lib/contexts/auth"; +import useProvinces from "@/lib/hooks/useProvince"; +import useEdaratLists from "@/lib/hooks/useEdaratLists"; +import BlinkingCell from "@/core/components/BlinkingCell"; + +const stepOptions = [ + { value: "", label: "همه گام ها" }, + { value: 1, label: "گام اول (شناسایی)" }, + { value: 2, label: "گام دوم (مستندات قضایی)" }, + { value: 3, label: "گام سوم (برخورد)" }, +]; +const statusOptions = [ + { value: "", label: "همه وضعیت ها" }, + { value: 0, label: "درحال بررسی" }, + { value: 1, label: "تایید" }, + { value: 2, label: "عدم تایید" }, +]; +const finishOptions = [ + { value: "", label: "همه موارد" }, + { value: 0, label: "در جریان" }, + { value: 1, label: "خاتمه یافته" }, +]; +const axisOptions = [ + { value: "", label: "همه محور ها" }, + { value: 1, label: "آزادراه" }, + { value: 2, label: "بزرگراه" }, + { value: 3, label: "اصلی" }, + { value: 4, label: "فرعی" }, + { value: 5, label: "روستایی" }, +]; +const SupervisorList = () => { + const { data: userPermissions } = usePermissions(); + const hasCountryPermission = userPermissions?.includes("show-safety-and-privacy-operator-cartable"); + const { user } = useAuth(); + + const columns = useMemo(() => { + const provinceColumn = { + header: "استان", + id: "province_id", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 130, + ColumnSelectComponent: (props) => { + const { provinces, errorProvinces, loadingProvinces } = useProvinces(); + const getColumnSelectOptions = useMemo(() => { + if (loadingProvinces) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorProvinces) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: "کل کشور" }, + ...provinces.map((province) => ({ + value: province.id, + label: province.name_fa, + })), + ]; + }, [provinces, errorProvinces, loadingProvinces]); + return ( + + ); + }, + Cell: ({ renderedCellValue, row }) => <>{row.original.province_fa}, + }; + return [ + { + accessorKey: "id", + header: "کد یکتا", + id: "id", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + Cell: ({ row }) => ( + + ), + }, + ...(hasCountryPermission ? [provinceColumn] : []), + { + header: "اداره", + id: "edare_shahri_id", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + dependencyId: hasCountryPermission ? "province_id" : null, + grow: false, + size: 120, + ColumnSelectComponent: (props) => { + const { edaratList, loadingEdaratList, errorEdaratList } = useEdaratLists( + hasCountryPermission ? props.dependencyFieldValue.value : user.province_id + ); + const [prevDependency, setPrevDependency] = useState( + hasCountryPermission ? props.dependencyFieldValue.value : user.province_id + ); + + const getColumnSelectOptions = useMemo(() => { + if (hasCountryPermission && props.dependencyFieldValue.value === "") { + return [{ value: "empty", label: "ابتدا استان را انتخاب کنید" }]; + } + if (loadingEdaratList) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorEdaratList) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: "کل ادارات" }, + ...edaratList.map((edare) => ({ + value: edare.id, + label: edare.name_fa, + })), + ]; + }, [edaratList, loadingEdaratList, errorEdaratList]); + useEffect(() => { + if (hasCountryPermission) return; + if (prevDependency === props.dependencyFieldValue?.value) return; + props.handleChange({ ...props.filterParameters, value: "" }); + setPrevDependency(props.dependencyFieldValue?.value); + }, [props.dependencyFieldValue?.value, hasCountryPermission]); + return ( + + ); + }, + Cell: ({ renderedCellValue, row }) => <>{row.original.edare_shahri_name}, + }, + { + header: "اطلاعات فعالیت", + id: "info", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + columns: [ + { + accessorKey: "info_id", + header: "مورد مشاهده شده", + id: "info_id", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 100, + ColumnSelectComponent: (props) => { + const { itemsList, loadingItemsList, errorItemsList } = useSafetyAndPrivacyGetItems(); + + const getColumnSelectOptions = useMemo(() => { + if (loadingItemsList) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorItemsList) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: "همه موارد" }, + ...itemsList.map((item) => ({ + value: item.id, + label: item.name, + })), + ]; + }, [itemsList, loadingItemsList, errorItemsList]); + + return ( + + ); + }, + Cell: ({ row }) => <>{row.original.info_fa}, + }, + { + accessorKey: "axis_type_id", + header: "نوع محور", + id: "axis_type_id", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + sortDescFirst: true, + grow: false, + size: 100, + columnSelectOption: () => { + return axisOptions.map((status) => ({ + value: status.value, + label: status.label, + })); + }, + Cell: ({ row }) => (row.original?.axis_type_name ? <>{row.original.axis_type_name} : <>-), + }, + { + accessorKey: "location", + header: "موقعیت", + id: "location", + enableColumnFilter: false, + enableSorting: false, + datatype: "array", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => { + return ( + + + + ); + }, + }, + { + accessorFn: (row) => moment(row.created_at).locale("fa").format("HH:mm | yyyy/MM/DD"), + header: "تاریخ ثبت", + id: "created_at", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + ], + }, + { + header: "وضعیت فعالیت", + id: "allstatus", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + columns: [ + { + header: "وضعیت گام ها", + id: "step", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + sortDescFirst: true, + grow: false, + size: 100, + columnSelectOption: () => { + return stepOptions.map((status) => ({ + value: status.value, + label: status.label, + })); + }, + Cell: ({ row }) => <>{row.original.step_fa}, + }, + { + header: "وضعیت فرایند", + id: "is_finished", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + sortDescFirst: true, + grow: false, + size: 100, + columnSelectOption: () => { + return finishOptions.map((status) => ({ + value: status.value, + label: status.label, + })); + }, + Cell: ({ row }) => ( + <> + {row.original.is_finished == 1 + ? "خاتمه یافته" + : row.original.is_finished == 0 + ? "در جریان" + : "-"} + + ), + }, + { + header: "علت خاتمه فرایند", + id: "finished_description", + enableColumnFilter: false, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => + row.original.final_description ? ( + + + + ) : ( + "-" + ), + }, + { + header: "وضعیت نظارت", + id: "status", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + sortDescFirst: true, + grow: false, + size: 100, + columnSelectOption: () => { + return statusOptions.map((status) => ({ + value: status.value, + label: status.label, + })); + }, + Cell: ({ row }) => <>{row.original.status_fa || "-"}, + }, + { + header: "توضیحات ناظر", + id: "supervisor_description", + enableColumnFilter: false, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => + row.original.supervisor_description ? ( + + + + ) : ( + "-" + ), + }, + ], + }, + { + header: "گام اول (شناسایی)", + id: "stepOne", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + columns: [ + { + accessorKey: "recognize_picture", + header: "تصویر بازدید", + id: "recognize_picture", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return renderedCellValue ? ( + + + + ) : ( + <>- + ); + }, + }, + { + accessorFn: (row) => + row.activity_date_time ? ( + moment(row.activity_date_time).locale("fa").format("HH:mm | yyyy/MM/DD") + ) : ( + <>- + ), + header: "تاریخ بازدید", + id: "activity_date_time", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + ], + }, + { + header: "گام دوم (مستندات قضایی)", + id: "stepTwo", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + columns: [ + { + header: "مستندات قضایی", + id: "judiciary_document", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => { + return ( + + {row.original.judiciary_document_upload_date !== "0000-00-00 00:00:00" && + row.original.judiciary_document_upload_date ? ( + + ) : ( + <>- + )} + + ); + }, + }, + { + accessorFn: (row) => { + const date = row.judiciary_document_upload_date; + if (!date || date === "0000-00-00 00:00:00") { + return <>-; + } + return moment(date, "YYYY-MM-DD HH:mm:ss").locale("fa").format("HH:mm | yyyy/MM/DD"); + }, + + header: "تاریخ بارگذاری مستندات", + id: "judiciary_document_upload_date", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + { + header: "توضیحات کارشناس", + id: "operator_description", + enableColumnFilter: false, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ row }) => + row.original.operator_description ? ( + + + + ) : ( + "-" + ), + }, + ], + }, + { + header: "گام سوم (برخورد)", + id: "stepThree", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + columns: [ + { + accessorKey: "action_picture", + header: "تصویر اقدام", + id: "action_picture", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue }) => { + return renderedCellValue ? ( + + + + ) : ( + <>- + ); + }, + }, + { + accessorFn: (row) => + row.action_date ? ( + moment(row.action_date).locale("fa").format("HH:mm | yyyy/MM/DD") + ) : ( + <>- + ), + header: "تاریخ اقدام", + id: "action_date", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + ], + }, + ]; + }, []); + + return ( + <> + + + + + ); +}; +export default SupervisorList; diff --git a/src/components/dashboard/roadSafety/supervisor/Toolbar.jsx b/src/components/dashboard/roadSafety/supervisor/Toolbar.jsx index 0ea09ad..db507b8 100644 --- a/src/components/dashboard/roadSafety/supervisor/Toolbar.jsx +++ b/src/components/dashboard/roadSafety/supervisor/Toolbar.jsx @@ -1,13 +1,13 @@ -import { Stack } from "@mui/material"; -import PrintExcel from "./ExcelPrint"; -import Learn from "./Learn"; - -const Toolbar = ({ table, filterData, mutate }) => { - return ( - - - - - ); -}; -export default Toolbar; +import { Stack } from "@mui/material"; +import PrintExcel from "./ExcelPrint"; +import Learn from "./Learn"; + +const Toolbar = ({ table, filterData, mutate }) => { + return ( + + + + + ); +}; +export default Toolbar; diff --git a/src/components/dashboard/roadSafety/supervisor/index.jsx b/src/components/dashboard/roadSafety/supervisor/index.jsx index 356487f..c207666 100644 --- a/src/components/dashboard/roadSafety/supervisor/index.jsx +++ b/src/components/dashboard/roadSafety/supervisor/index.jsx @@ -1,14 +1,14 @@ -"use client"; -import PageTitle from "@/core/components/PageTitle"; -import { Stack } from "@mui/material"; -import SupervisorList from "./SupervisorList"; - -const SupervisorPage = () => { - return ( - - - - - ); -}; -export default SupervisorPage; +"use client"; +import PageTitle from "@/core/components/PageTitle"; +import { Stack } from "@mui/material"; +import SupervisorList from "./SupervisorList"; + +const SupervisorPage = () => { + return ( + + + + + ); +}; +export default SupervisorPage; diff --git a/src/components/dashboard/userActivities/Actions/Create/Form/ActionTypeList.jsx b/src/components/dashboard/userActivities/Actions/Create/Form/ActionTypeList.jsx index 0732896..b7aad63 100644 --- a/src/components/dashboard/userActivities/Actions/Create/Form/ActionTypeList.jsx +++ b/src/components/dashboard/userActivities/Actions/Create/Form/ActionTypeList.jsx @@ -1,38 +1,38 @@ -import { FormControl, FormHelperText, InputLabel, MenuItem, OutlinedInput, Select } from "@mui/material"; - -const ActionTypeList = ({ value, onChange, error }) => { - const statusOptions = [ - { value: "show", label: "show" }, - { value: "add", label: "add" }, - { value: "edit", label: "edit" }, - { value: "delete", label: "delete" }, - { value: "report", label: "report" }, - { value: "action", label: "action" }, - ]; - - return ( - - - نوع فعالیت - - - {error && {error.message}} - - ); -}; -export default ActionTypeList; +import { FormControl, FormHelperText, InputLabel, MenuItem, OutlinedInput, Select } from "@mui/material"; + +const ActionTypeList = ({ value, onChange, error }) => { + const statusOptions = [ + { value: "show", label: "show" }, + { value: "add", label: "add" }, + { value: "edit", label: "edit" }, + { value: "delete", label: "delete" }, + { value: "report", label: "report" }, + { value: "action", label: "action" }, + ]; + + return ( + + + نوع فعالیت + + + {error && {error.message}} + + ); +}; +export default ActionTypeList; diff --git a/src/components/dashboard/userActivities/Actions/Create/Form/CreateFormContent.jsx b/src/components/dashboard/userActivities/Actions/Create/Form/CreateFormContent.jsx index ff2f25f..c0b00ef 100644 --- a/src/components/dashboard/userActivities/Actions/Create/Form/CreateFormContent.jsx +++ b/src/components/dashboard/userActivities/Actions/Create/Form/CreateFormContent.jsx @@ -1,98 +1,98 @@ -import PersianTextField from "@/core/components/PersianTextField"; -import StyledForm from "@/core/components/StyledForm"; -import { yupResolver } from "@hookform/resolvers/yup"; -import { Beenhere, ExitToApp } from "@mui/icons-material"; -import { Button, DialogActions, DialogContent, Stack, TextField } from "@mui/material"; -import { Controller, useForm } from "react-hook-form"; -import { object, string } from "yup"; -import ActionTypeList from "./ActionTypeList"; - -const validationSchema = object({ - title: string().required("وارد کردن عنوان الزامیست!"), - log_unique_code: string().required("وارد کردن کد الزامیست!"), - action_type: string().required("وارد کردن نوع فعالیت الزامیست!"), -}); - -const CreateFormContent = ({ setOpen, defaultValues, onSubmitBase }) => { - const { - control, - handleSubmit, - formState: { isSubmitting }, - } = useForm({ - defaultValues, - resolver: yupResolver(validationSchema), - mode: "all", - }); - const handleOnSubmit = async (data) => { - await onSubmitBase(data); - }; - - return ( - <> - - - - ( - - )} - /> - ( - - )} - /> - ( - - )} - /> - - - - - - - - - ); -}; -export default CreateFormContent; +import PersianTextField from "@/core/components/PersianTextField"; +import StyledForm from "@/core/components/StyledForm"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { Beenhere, ExitToApp } from "@mui/icons-material"; +import { Button, DialogActions, DialogContent, Stack, TextField } from "@mui/material"; +import { Controller, useForm } from "react-hook-form"; +import { object, string } from "yup"; +import ActionTypeList from "./ActionTypeList"; + +const validationSchema = object({ + title: string().required("وارد کردن عنوان الزامیست!"), + log_unique_code: string().required("وارد کردن کد الزامیست!"), + action_type: string().required("وارد کردن نوع فعالیت الزامیست!"), +}); + +const CreateFormContent = ({ setOpen, defaultValues, onSubmitBase }) => { + const { + control, + handleSubmit, + formState: { isSubmitting }, + } = useForm({ + defaultValues, + resolver: yupResolver(validationSchema), + mode: "all", + }); + const handleOnSubmit = async (data) => { + await onSubmitBase(data); + }; + + return ( + <> + + + + ( + + )} + /> + ( + + )} + /> + ( + + )} + /> + + + + + + + + + ); +}; +export default CreateFormContent; diff --git a/src/components/dashboard/userActivities/Actions/Create/Form/index.jsx b/src/components/dashboard/userActivities/Actions/Create/Form/index.jsx index 5275391..948078e 100644 --- a/src/components/dashboard/userActivities/Actions/Create/Form/index.jsx +++ b/src/components/dashboard/userActivities/Actions/Create/Form/index.jsx @@ -1,58 +1,58 @@ -import { Dialog, DialogTitle, IconButton } from "@mui/material"; -import CreateFormContent from "./CreateFormContent"; -import CloseIcon from "@mui/icons-material/Close"; -import useRequest from "@/lib/hooks/useRequest"; -import { CREATE_USER_ACTIVITY } from "@/core/utils/routes"; -import { DialogHeader } from "next/dist/client/components/react-dev-overlay/internal/components/Dialog"; - -const CreateForm = ({ open, setOpen, mutate }) => { - const requestServer = useRequest({ notificationSuccess: true }); - const defaultValues = { - title: "", - log_unique_code: "", - action_type: "", - }; - const onSubmit = async (result) => { - const formData = new FormData(); - formData.append("description", result.title); - formData.append("log_unique_code", result.log_unique_code); - formData.append("action_type", result.action_type); - await requestServer(CREATE_USER_ACTIVITY, "post", { - data: formData, - }) - .then(() => { - mutate(); - setOpen(false); - }) - .catch(() => {}); - }; - return ( - - setOpen(false)} - sx={(theme) => ({ - position: "absolute", - right: 8, - top: 8, - zIndex: 50, - color: theme.palette.grey[500], - })} - > - - - - ثبت فعالیت کاربران - - {open && ( - - )} - - ); -}; -export default CreateForm; +import { Dialog, DialogTitle, IconButton } from "@mui/material"; +import CreateFormContent from "./CreateFormContent"; +import CloseIcon from "@mui/icons-material/Close"; +import useRequest from "@/lib/hooks/useRequest"; +import { CREATE_USER_ACTIVITY } from "@/core/utils/routes"; +import { DialogHeader } from "next/dist/client/components/react-dev-overlay/internal/components/Dialog"; + +const CreateForm = ({ open, setOpen, mutate }) => { + const requestServer = useRequest({ notificationSuccess: true }); + const defaultValues = { + title: "", + log_unique_code: "", + action_type: "", + }; + const onSubmit = async (result) => { + const formData = new FormData(); + formData.append("description", result.title); + formData.append("log_unique_code", result.log_unique_code); + formData.append("action_type", result.action_type); + await requestServer(CREATE_USER_ACTIVITY, "post", { + data: formData, + }) + .then(() => { + mutate(); + setOpen(false); + }) + .catch(() => {}); + }; + return ( + + setOpen(false)} + sx={(theme) => ({ + position: "absolute", + right: 8, + top: 8, + zIndex: 50, + color: theme.palette.grey[500], + })} + > + + + + ثبت فعالیت کاربران + + {open && ( + + )} + + ); +}; +export default CreateForm; diff --git a/src/components/dashboard/userActivities/Actions/Create/index.jsx b/src/components/dashboard/userActivities/Actions/Create/index.jsx index b26543a..40ce3ca 100644 --- a/src/components/dashboard/userActivities/Actions/Create/index.jsx +++ b/src/components/dashboard/userActivities/Actions/Create/index.jsx @@ -1,36 +1,36 @@ -import { AddCircle } from "@mui/icons-material"; -import { Button, IconButton, useMediaQuery, useTheme } from "@mui/material"; -import CreateForm from "./Form"; -import { useState } from "react"; - -const CreateUserActivity = ({ mutate }) => { - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const [open, setOpen] = useState(false); - - const handleOpen = () => { - setOpen(true); - }; - - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - - - ); -}; -export default CreateUserActivity; +import { AddCircle } from "@mui/icons-material"; +import { Button, IconButton, useMediaQuery, useTheme } from "@mui/material"; +import CreateForm from "./Form"; +import { useState } from "react"; + +const CreateUserActivity = ({ mutate }) => { + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const [open, setOpen] = useState(false); + + const handleOpen = () => { + setOpen(true); + }; + + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + + + ); +}; +export default CreateUserActivity; diff --git a/src/components/dashboard/userActivities/Actions/Edit/EditController.jsx b/src/components/dashboard/userActivities/Actions/Edit/EditController.jsx index 0486691..c2dc78e 100644 --- a/src/components/dashboard/userActivities/Actions/Edit/EditController.jsx +++ b/src/components/dashboard/userActivities/Actions/Edit/EditController.jsx @@ -1,38 +1,38 @@ -import useRequest from "@/lib/hooks/useRequest"; -import CreateFormContent from "../Create/Form/CreateFormContent"; -import { UPDATE_USER_ACTIVITY } from "@/core/utils/routes"; -import { DialogTitle } from "@mui/material"; -import { DialogHeader } from "next/dist/client/components/react-dev-overlay/internal/components/Dialog"; - -const EditController = ({ rowId, mutate, setOpen, row }) => { - const requestServer = useRequest({ notificationSuccess: true }); - - const defaultData = { - title: row.original?.description || "", - log_unique_code: row.original?.log_unique_code || "", - action_type: row.original?.action_type || "", - }; - const handleSubmit = async (result) => { - const formData = new FormData(); - formData.append("description", result.title); - formData.append("log_unique_code", result.log_unique_code); - formData.append("action_type", result.action_type); - await requestServer(`${UPDATE_USER_ACTIVITY}/${rowId}`, "post", { - data: formData, - }) - .then(() => { - mutate(); - setOpen(false); - }) - .catch(() => {}); - }; - return ( - <> - - ویرایش فعالیت کاربران - - - - ); -}; -export default EditController; +import useRequest from "@/lib/hooks/useRequest"; +import CreateFormContent from "../Create/Form/CreateFormContent"; +import { UPDATE_USER_ACTIVITY } from "@/core/utils/routes"; +import { DialogTitle } from "@mui/material"; +import { DialogHeader } from "next/dist/client/components/react-dev-overlay/internal/components/Dialog"; + +const EditController = ({ rowId, mutate, setOpen, row }) => { + const requestServer = useRequest({ notificationSuccess: true }); + + const defaultData = { + title: row.original?.description || "", + log_unique_code: row.original?.log_unique_code || "", + action_type: row.original?.action_type || "", + }; + const handleSubmit = async (result) => { + const formData = new FormData(); + formData.append("description", result.title); + formData.append("log_unique_code", result.log_unique_code); + formData.append("action_type", result.action_type); + await requestServer(`${UPDATE_USER_ACTIVITY}/${rowId}`, "post", { + data: formData, + }) + .then(() => { + mutate(); + setOpen(false); + }) + .catch(() => {}); + }; + return ( + <> + + ویرایش فعالیت کاربران + + + + ); +}; +export default EditController; diff --git a/src/components/dashboard/userActivities/Actions/Edit/index.jsx b/src/components/dashboard/userActivities/Actions/Edit/index.jsx index ca5f622..d203ac7 100644 --- a/src/components/dashboard/userActivities/Actions/Edit/index.jsx +++ b/src/components/dashboard/userActivities/Actions/Edit/index.jsx @@ -1,51 +1,51 @@ -import { useState } from "react"; -import { Dialog, IconButton, Tooltip } from "@mui/material"; -import BorderColorIcon from "@mui/icons-material/BorderColor"; -import CloseIcon from "@mui/icons-material/Close"; -import EditController from "./EditController"; - -const EditUserActivity = ({ mutate, row, rowId }) => { - const [open, setOpen] = useState(false); - - return ( - <> - - { - setOpen(true); - }} - > - - - - - setOpen(false)} - sx={(theme) => ({ - position: "absolute", - right: 8, - top: 8, - zIndex: 50, - color: theme.palette.grey[500], - })} - > - - - {open && } - - - ); -}; -export default EditUserActivity; +import { useState } from "react"; +import { Dialog, IconButton, Tooltip } from "@mui/material"; +import BorderColorIcon from "@mui/icons-material/BorderColor"; +import CloseIcon from "@mui/icons-material/Close"; +import EditController from "./EditController"; + +const EditUserActivity = ({ mutate, row, rowId }) => { + const [open, setOpen] = useState(false); + + return ( + <> + + { + setOpen(true); + }} + > + + + + + setOpen(false)} + sx={(theme) => ({ + position: "absolute", + right: 8, + top: 8, + zIndex: 50, + color: theme.palette.grey[500], + })} + > + + + {open && } + + + ); +}; +export default EditUserActivity; diff --git a/src/components/dashboard/userActivities/RowActions/DeleteDialog/DeleteContent.jsx b/src/components/dashboard/userActivities/RowActions/DeleteDialog/DeleteContent.jsx index 159746a..4d1b34c 100644 --- a/src/components/dashboard/userActivities/RowActions/DeleteDialog/DeleteContent.jsx +++ b/src/components/dashboard/userActivities/RowActions/DeleteDialog/DeleteContent.jsx @@ -1,39 +1,39 @@ -import { Button, DialogActions, DialogContent, Stack, Typography } from "@mui/material"; -import React, { useState } from "react"; -import useRequest from "@/lib/hooks/useRequest"; -import { DELETE_USER_ACTIVITIES } from "@/core/utils/routes"; - -const DeleteContent = ({ rowId, mutate, setOpenDeleteDialog }) => { - const [submitting, setSubmitting] = useState(false); - const requestServer = useRequest({ notificationSuccess: true }); - const handleClick = () => { - setSubmitting(true); - requestServer(`${DELETE_USER_ACTIVITIES}/${rowId}`, "delete") - .then(() => { - mutate(); - setSubmitting(false); - setOpenDeleteDialog(false); - }) - .catch(() => { - setSubmitting(false); - }); - }; - return ( - <> - - - آیا از حذف این فعالیت کاربران اطمینان دارید؟ - - - - - - - - ); -}; -export default DeleteContent; +import { Button, DialogActions, DialogContent, Stack, Typography } from "@mui/material"; +import React, { useState } from "react"; +import useRequest from "@/lib/hooks/useRequest"; +import { DELETE_USER_ACTIVITIES } from "@/core/utils/routes"; + +const DeleteContent = ({ rowId, mutate, setOpenDeleteDialog }) => { + const [submitting, setSubmitting] = useState(false); + const requestServer = useRequest({ notificationSuccess: true }); + const handleClick = () => { + setSubmitting(true); + requestServer(`${DELETE_USER_ACTIVITIES}/${rowId}`, "delete") + .then(() => { + mutate(); + setSubmitting(false); + setOpenDeleteDialog(false); + }) + .catch(() => { + setSubmitting(false); + }); + }; + return ( + <> + + + آیا از حذف این فعالیت کاربران اطمینان دارید؟ + + + + + + + + ); +}; +export default DeleteContent; diff --git a/src/components/dashboard/userActivities/RowActions/DeleteDialog/index.jsx b/src/components/dashboard/userActivities/RowActions/DeleteDialog/index.jsx index 7cbd3a1..6876b53 100644 --- a/src/components/dashboard/userActivities/RowActions/DeleteDialog/index.jsx +++ b/src/components/dashboard/userActivities/RowActions/DeleteDialog/index.jsx @@ -1,34 +1,34 @@ -import DeleteIcon from "@mui/icons-material/Delete"; -import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import DeleteContent from "./DeleteContent"; -const DeleteDialog = ({ rowId, mutate }) => { - const [openDeleteDialog, setOpenDeleteDialog] = useState(false); - - return ( - <> - - setOpenDeleteDialog(true)}> - - - - setOpenDeleteDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - حذف فعالیت کاربران - {openDeleteDialog && ( - - )} - - - ); -}; -export default DeleteDialog; +import DeleteIcon from "@mui/icons-material/Delete"; +import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import DeleteContent from "./DeleteContent"; +const DeleteDialog = ({ rowId, mutate }) => { + const [openDeleteDialog, setOpenDeleteDialog] = useState(false); + + return ( + <> + + setOpenDeleteDialog(true)}> + + + + setOpenDeleteDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + حذف فعالیت کاربران + {openDeleteDialog && ( + + )} + + + ); +}; +export default DeleteDialog; diff --git a/src/components/dashboard/userActivities/RowActions/index.jsx b/src/components/dashboard/userActivities/RowActions/index.jsx index 2f7f578..b9cea16 100644 --- a/src/components/dashboard/userActivities/RowActions/index.jsx +++ b/src/components/dashboard/userActivities/RowActions/index.jsx @@ -1,12 +1,12 @@ -import { Box } from "@mui/material"; -import EditUserActivity from "../Actions/Edit"; -import DeleteDialog from "./DeleteDialog"; -const RowActions = ({ row, mutate }) => { - return ( - - - - - ); -}; -export default RowActions; +import { Box } from "@mui/material"; +import EditUserActivity from "../Actions/Edit"; +import DeleteDialog from "./DeleteDialog"; +const RowActions = ({ row, mutate }) => { + return ( + + + + + ); +}; +export default RowActions; diff --git a/src/components/dashboard/userActivities/Toolbar.jsx b/src/components/dashboard/userActivities/Toolbar.jsx index 7d3ce90..2c53818 100644 --- a/src/components/dashboard/userActivities/Toolbar.jsx +++ b/src/components/dashboard/userActivities/Toolbar.jsx @@ -1,9 +1,9 @@ -import CreateUserActivity from "./Actions/Create"; -const Toolbar = ({ mutate }) => { - return ( - <> - - - ); -}; -export default Toolbar; +import CreateUserActivity from "./Actions/Create"; +const Toolbar = ({ mutate }) => { + return ( + <> + + + ); +}; +export default Toolbar; diff --git a/src/components/dashboard/userActivities/UserActivitiesList.jsx b/src/components/dashboard/userActivities/UserActivitiesList.jsx index cbdad72..f71f1d2 100644 --- a/src/components/dashboard/userActivities/UserActivitiesList.jsx +++ b/src/components/dashboard/userActivities/UserActivitiesList.jsx @@ -1,83 +1,83 @@ -"use client"; -import DataTableWithAuth from "@/core/components/DataTableWithAuth"; -import { GET_USER_ACTIVITIES_LIST } from "@/core/utils/routes"; -import { Box } from "@mui/material"; -import { useMemo } from "react"; -import RowActions from "./RowActions"; -import Toolbar from "./Toolbar"; - -const UserActivitiesList = () => { - const columns = useMemo( - () => [ - { - accessorKey: "id", - header: "کد یکتا", - id: "id", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorKey: "description", - header: "عنوان", - id: "description", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorKey: "log_unique_code", - header: "کد", - id: "log_unique_code", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals"], - grow: false, - size: 100, - }, - { - accessorKey: "action_type", - header: "نوع فعالیت", - id: "action_type", - enableColumnFilter: false, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals"], - grow: false, - size: 100, - }, - ], - [] - ); - - return ( - <> - - - - - ); -}; -export default UserActivitiesList; +"use client"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import { GET_USER_ACTIVITIES_LIST } from "@/core/utils/routes"; +import { Box } from "@mui/material"; +import { useMemo } from "react"; +import RowActions from "./RowActions"; +import Toolbar from "./Toolbar"; + +const UserActivitiesList = () => { + const columns = useMemo( + () => [ + { + accessorKey: "id", + header: "کد یکتا", + id: "id", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "description", + header: "عنوان", + id: "description", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "log_unique_code", + header: "کد", + id: "log_unique_code", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals"], + grow: false, + size: 100, + }, + { + accessorKey: "action_type", + header: "نوع فعالیت", + id: "action_type", + enableColumnFilter: false, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals"], + grow: false, + size: 100, + }, + ], + [] + ); + + return ( + <> + + + + + ); +}; +export default UserActivitiesList; diff --git a/src/components/dashboard/userActivities/index.jsx b/src/components/dashboard/userActivities/index.jsx index 321001d..2f2f254 100644 --- a/src/components/dashboard/userActivities/index.jsx +++ b/src/components/dashboard/userActivities/index.jsx @@ -1,13 +1,13 @@ -import PageTitle from "@/core/components/PageTitle"; -import { Stack } from "@mui/material"; -import UserActivitiesList from "./UserActivitiesList"; - -const UserActivitiesPage = () => { - return ( - - - - - ); -}; -export default UserActivitiesPage; +import PageTitle from "@/core/components/PageTitle"; +import { Stack } from "@mui/material"; +import UserActivitiesList from "./UserActivitiesList"; + +const UserActivitiesPage = () => { + return ( + + + + + ); +}; +export default UserActivitiesPage; diff --git a/src/components/infrastructure/tollHouse/Form/CreateTollHouse/CityContent.jsx b/src/components/infrastructure/tollHouse/Form/CreateTollHouse/CityContent.jsx index 3069208..348e946 100644 --- a/src/components/infrastructure/tollHouse/Form/CreateTollHouse/CityContent.jsx +++ b/src/components/infrastructure/tollHouse/Form/CreateTollHouse/CityContent.jsx @@ -1,33 +1,33 @@ -import SelectBox from "@/core/components/SelectBox"; -import { useEffect, useState } from "react"; -import useCities from "@/lib/hooks/useCities"; - -const CityContent = ({ provinceID, field, fieldState: { error } }) => { - const { cityList, loadingCityList, errorCityList } = useCities(provinceID); - const [prevDependency, setPrevDependency] = useState(provinceID); - - useEffect(() => { - if (prevDependency === provinceID) return; - field.onChange(null); - setPrevDependency(provinceID); - }, [provinceID]); - - return ( - - ); -}; -export default CityContent; +import SelectBox from "@/core/components/SelectBox"; +import { useEffect, useState } from "react"; +import useCities from "@/lib/hooks/useCities"; + +const CityContent = ({ provinceID, field, fieldState: { error } }) => { + const { cityList, loadingCityList, errorCityList } = useCities(provinceID); + const [prevDependency, setPrevDependency] = useState(provinceID); + + useEffect(() => { + if (prevDependency === provinceID) return; + field.onChange(null); + setPrevDependency(provinceID); + }, [provinceID]); + + return ( + + ); +}; +export default CityContent; diff --git a/src/components/infrastructure/tollHouse/Form/CreateTollHouse/CityController.jsx b/src/components/infrastructure/tollHouse/Form/CreateTollHouse/CityController.jsx index 72de542..13bfe9f 100644 --- a/src/components/infrastructure/tollHouse/Form/CreateTollHouse/CityController.jsx +++ b/src/components/infrastructure/tollHouse/Form/CreateTollHouse/CityController.jsx @@ -1,14 +1,14 @@ -import { Controller, useWatch } from "react-hook-form"; -import CityContent from "./CityContent"; - -const CityController = ({ control }) => { - const provinceID = useWatch({ control, name: "province_id" }); - return ( - } - /> - ); -}; -export default CityController; +import { Controller, useWatch } from "react-hook-form"; +import CityContent from "./CityContent"; + +const CityController = ({ control }) => { + const provinceID = useWatch({ control, name: "province_id" }); + return ( + } + /> + ); +}; +export default CityController; diff --git a/src/components/infrastructure/tollHouse/Form/CreateTollHouse/CreateTollHouseContent.jsx b/src/components/infrastructure/tollHouse/Form/CreateTollHouse/CreateTollHouseContent.jsx index ef2e51d..bb3cb1b 100644 --- a/src/components/infrastructure/tollHouse/Form/CreateTollHouse/CreateTollHouseContent.jsx +++ b/src/components/infrastructure/tollHouse/Form/CreateTollHouse/CreateTollHouseContent.jsx @@ -1,192 +1,192 @@ -import StyledForm from "@/core/components/StyledForm"; -import { Box, Button, DialogActions, DialogContent, Tab, Tabs } from "@mui/material"; -import ExitToAppIcon from "@mui/icons-material/ExitToApp"; -import KeyboardDoubleArrowRightIcon from "@mui/icons-material/KeyboardDoubleArrowRight"; -import BeenhereIcon from "@mui/icons-material/Beenhere"; -import OtherHousesIcon from "@mui/icons-material/OtherHouses"; -import LocalShippingIcon from "@mui/icons-material/LocalShipping"; -import EditLocationAltIcon from "@mui/icons-material/EditLocationAlt"; -import React, { useState } from "react"; -import { useForm } from "react-hook-form"; -import { yupResolver } from "@hookform/resolvers/yup"; -import { mixed, number, object, string } from "yup"; -import TollHouseInfo from "./TollHouseInfo"; -import KeyboardDoubleArrowLeftIcon from "@mui/icons-material/KeyboardDoubleArrowLeft"; -import MachineInfo from "@/components/infrastructure/tollHouse/Form/CreateTollHouse/MachineInfo"; -import TollHouseLocation from "@/components/infrastructure/tollHouse/Form/CreateTollHouse/TollHouseLocation"; - -function TabPanel(props) { - const { children, value, index } = props; - return ( - - ); -} - -const validationSchema = object({ - name: string().required("وارد کردن نام راهدارخانه الزامیست!"), - status: string().required("وارد کردن وضعیت الزامیست!"), - type: string().required("وارد کردن نوع الزامیست!"), - phone: string().required("وارد کردن تلفن راهدارخانه الزامیست!"), - team_num: string().required("وارد کردن تعداد اکیپ الزامیست!"), - staff_num: string().required("وارد کردن تعداد پرسنل الزامیست!"), - responsible_name: string().required("وارد کردن نام مسئول الزامیست!"), - responsible_mobile: string() - .required("وارد کردن تلفن مسئول الزامیست!") - .matches(/^09\d{9}$/, "شماره تلفن مسئول باید با ۰۹ شروع شده و ۱۱ رقم باشد!"), - successor_name: string().required("وارد کردن نام جانشین الزامیست!"), - successor_mobile: string() - .required("وارد کردن تلفن جانشین الزامیست!") - .matches(/^09\d{9}$/, "شماره تلفن جانشین باید با ۰۹ شروع شده و ۱۱ رقم باشد!"), - province_id: number().required("وارد کردن استان الزامیست!"), - city_id: number().required("وارد کردن شهرستان الزامیست!"), - machines_light: string().required("وارد کردن ماشین آلات سبک الزامیست!"), - machines_sheavy: string().required("وارد کردن ماشین آلات نیمه سنگین الزامیست!"), - machines_heavy: string().required("وارد کردن ماشین آلات سنگین الزامیست!"), - overview_files_1: mixed().nullable().required("لطفا نمای کلی از راهداری را بارگذاری کنید!"), - overview_files_2: mixed().nullable().required("لطفا آشیانه ماشین آلات را بارگذاری کنید!"), - overview_files_3: mixed().nullable().required("لطفا انباری شن و ماسه را بارگذاری کنید!"), - overview_files_4: mixed().nullable().required("لطفا محیط کاری را بارگذاری کنید!"), - overview_files_5: mixed().nullable().required("لطفا سایر تصاویر را بارگذاری کنید!"), - start_point: mixed() - .test("start-point-required", "لطفاً محل پروژه را مشخص کنید!", function (value) { - return !!value; - }) - .required("لطفاً محل پروژه را مشخص کنید!"), -}); -const CreateTollHouseContent = ({ setOpen, SubmitCreateTollHouse, defaultValues }) => { - const [tabState, setTabState] = useState(0); - const handleClose = () => { - setOpen(false); - }; - - const handleChangeTab = (event, newValue) => { - setTabState(newValue); - }; - const handleNext = async () => { - let fieldsToValidate = []; - if (tabState === 0) { - fieldsToValidate = [ - "name", - "province_id", - "city_id", - "status", - "type", - "phone", - "team_num", - "staff_num", - "responsible_name", - "responsible_mobile", - "successor_name", - "successor_mobile", - ]; - } else if (tabState === 1) { - fieldsToValidate = [ - "machines_light", - "machines_sheavy", - "machines_heavy", - "overview_files_1", - "overview_files_2", - "overview_files_3", - "overview_files_4", - "overview_files_5", - ]; - } else if (tabState === 2) { - fieldsToValidate = ["start_point"]; - } - const isValid = await trigger(fieldsToValidate); - if (isValid) { - setTabState(tabState + 1); - } - }; - const handlePrev = () => { - if (tabState === 0) { - handleClose(); - } else { - setTabState(tabState - 1); - } - }; - const { - control, - handleSubmit, - trigger, - setValue, - formState: { isSubmitting, errors }, - } = useForm({ - defaultValues, - resolver: yupResolver(validationSchema), - mode: "all", - }); - const onSubmitBase = async (data) => { - await SubmitCreateTollHouse(data); - }; - return ( - - - } label="اطلاعات راهدارخانه" /> - } label="ماشین آلات" /> - } label="موقعیت" /> - - - - - - - - - - - - - - - - - {tabState !== 2 && ( - - )} - {tabState === 2 && ( - - )} - - - ); -}; -export default CreateTollHouseContent; +import StyledForm from "@/core/components/StyledForm"; +import { Box, Button, DialogActions, DialogContent, Tab, Tabs } from "@mui/material"; +import ExitToAppIcon from "@mui/icons-material/ExitToApp"; +import KeyboardDoubleArrowRightIcon from "@mui/icons-material/KeyboardDoubleArrowRight"; +import BeenhereIcon from "@mui/icons-material/Beenhere"; +import OtherHousesIcon from "@mui/icons-material/OtherHouses"; +import LocalShippingIcon from "@mui/icons-material/LocalShipping"; +import EditLocationAltIcon from "@mui/icons-material/EditLocationAlt"; +import React, { useState } from "react"; +import { useForm } from "react-hook-form"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { mixed, number, object, string } from "yup"; +import TollHouseInfo from "./TollHouseInfo"; +import KeyboardDoubleArrowLeftIcon from "@mui/icons-material/KeyboardDoubleArrowLeft"; +import MachineInfo from "@/components/infrastructure/tollHouse/Form/CreateTollHouse/MachineInfo"; +import TollHouseLocation from "@/components/infrastructure/tollHouse/Form/CreateTollHouse/TollHouseLocation"; + +function TabPanel(props) { + const { children, value, index } = props; + return ( + + ); +} + +const validationSchema = object({ + name: string().required("وارد کردن نام راهدارخانه الزامیست!"), + status: string().required("وارد کردن وضعیت الزامیست!"), + type: string().required("وارد کردن نوع الزامیست!"), + phone: string().required("وارد کردن تلفن راهدارخانه الزامیست!"), + team_num: string().required("وارد کردن تعداد اکیپ الزامیست!"), + staff_num: string().required("وارد کردن تعداد پرسنل الزامیست!"), + responsible_name: string().required("وارد کردن نام مسئول الزامیست!"), + responsible_mobile: string() + .required("وارد کردن تلفن مسئول الزامیست!") + .matches(/^09\d{9}$/, "شماره تلفن مسئول باید با ۰۹ شروع شده و ۱۱ رقم باشد!"), + successor_name: string().required("وارد کردن نام جانشین الزامیست!"), + successor_mobile: string() + .required("وارد کردن تلفن جانشین الزامیست!") + .matches(/^09\d{9}$/, "شماره تلفن جانشین باید با ۰۹ شروع شده و ۱۱ رقم باشد!"), + province_id: number().required("وارد کردن استان الزامیست!"), + city_id: number().required("وارد کردن شهرستان الزامیست!"), + machines_light: string().required("وارد کردن ماشین آلات سبک الزامیست!"), + machines_sheavy: string().required("وارد کردن ماشین آلات نیمه سنگین الزامیست!"), + machines_heavy: string().required("وارد کردن ماشین آلات سنگین الزامیست!"), + overview_files_1: mixed().nullable().required("لطفا نمای کلی از راهداری را بارگذاری کنید!"), + overview_files_2: mixed().nullable().required("لطفا آشیانه ماشین آلات را بارگذاری کنید!"), + overview_files_3: mixed().nullable().required("لطفا انباری شن و ماسه را بارگذاری کنید!"), + overview_files_4: mixed().nullable().required("لطفا محیط کاری را بارگذاری کنید!"), + overview_files_5: mixed().nullable().required("لطفا سایر تصاویر را بارگذاری کنید!"), + start_point: mixed() + .test("start-point-required", "لطفاً محل پروژه را مشخص کنید!", function (value) { + return !!value; + }) + .required("لطفاً محل پروژه را مشخص کنید!"), +}); +const CreateTollHouseContent = ({ setOpen, SubmitCreateTollHouse, defaultValues }) => { + const [tabState, setTabState] = useState(0); + const handleClose = () => { + setOpen(false); + }; + + const handleChangeTab = (event, newValue) => { + setTabState(newValue); + }; + const handleNext = async () => { + let fieldsToValidate = []; + if (tabState === 0) { + fieldsToValidate = [ + "name", + "province_id", + "city_id", + "status", + "type", + "phone", + "team_num", + "staff_num", + "responsible_name", + "responsible_mobile", + "successor_name", + "successor_mobile", + ]; + } else if (tabState === 1) { + fieldsToValidate = [ + "machines_light", + "machines_sheavy", + "machines_heavy", + "overview_files_1", + "overview_files_2", + "overview_files_3", + "overview_files_4", + "overview_files_5", + ]; + } else if (tabState === 2) { + fieldsToValidate = ["start_point"]; + } + const isValid = await trigger(fieldsToValidate); + if (isValid) { + setTabState(tabState + 1); + } + }; + const handlePrev = () => { + if (tabState === 0) { + handleClose(); + } else { + setTabState(tabState - 1); + } + }; + const { + control, + handleSubmit, + trigger, + setValue, + formState: { isSubmitting, errors }, + } = useForm({ + defaultValues, + resolver: yupResolver(validationSchema), + mode: "all", + }); + const onSubmitBase = async (data) => { + await SubmitCreateTollHouse(data); + }; + return ( + + + } label="اطلاعات راهدارخانه" /> + } label="ماشین آلات" /> + } label="موقعیت" /> + + + + + + + + + + + + + + + + + {tabState !== 2 && ( + + )} + {tabState === 2 && ( + + )} + + + ); +}; +export default CreateTollHouseContent; diff --git a/src/components/infrastructure/tollHouse/Form/CreateTollHouse/ImageUpload.jsx b/src/components/infrastructure/tollHouse/Form/CreateTollHouse/ImageUpload.jsx index 5186a4b..7697cfb 100644 --- a/src/components/infrastructure/tollHouse/Form/CreateTollHouse/ImageUpload.jsx +++ b/src/components/infrastructure/tollHouse/Form/CreateTollHouse/ImageUpload.jsx @@ -1,77 +1,77 @@ -import { FormControl, FormHelperText } from "@mui/material"; -import UploadSystem from "@/core/components/UploadSystem"; -import React, { useEffect, useState } from "react"; - -const ImageUpload = ({ name, value, onChange, error, title }) => { - const [beforeImg, setBeforeImg] = useState(value ? value : null); - const [beforeFileType, setBeforeFileType] = useState(value ? "image/" : null); - const [beforeFileName, setBeforeFileName] = useState(null); - const [showBeforeImage, setShowBeforeImage] = useState(!value); - - useEffect(() => { - if (value) { - setShowBeforeImage(false); - if (typeof value === "string") { - setBeforeImg(value); - setBeforeFileType("image/"); - } else if (value instanceof File) { - setBeforeImg(URL.createObjectURL(value)); - setBeforeFileType(value.type); - } - } - }, [value]); - - const handleFileChange = (event) => { - const uploadedFile = event.target?.files?.[0]; - if (uploadedFile) { - const fileType = event.target?.files?.[0].type; - const fileName = event.target?.files?.[0].name; - setBeforeImg(URL.createObjectURL(uploadedFile)); - setBeforeFileType(fileType); - setBeforeFileName(fileName); - onChange(uploadedFile); - setShowBeforeImage(false); - } - }; - - return ( - - - {title} - - - {error ? error.message : null} - - ); -}; -export default ImageUpload; +import { FormControl, FormHelperText } from "@mui/material"; +import UploadSystem from "@/core/components/UploadSystem"; +import React, { useEffect, useState } from "react"; + +const ImageUpload = ({ name, value, onChange, error, title }) => { + const [beforeImg, setBeforeImg] = useState(value ? value : null); + const [beforeFileType, setBeforeFileType] = useState(value ? "image/" : null); + const [beforeFileName, setBeforeFileName] = useState(null); + const [showBeforeImage, setShowBeforeImage] = useState(!value); + + useEffect(() => { + if (value) { + setShowBeforeImage(false); + if (typeof value === "string") { + setBeforeImg(value); + setBeforeFileType("image/"); + } else if (value instanceof File) { + setBeforeImg(URL.createObjectURL(value)); + setBeforeFileType(value.type); + } + } + }, [value]); + + const handleFileChange = (event) => { + const uploadedFile = event.target?.files?.[0]; + if (uploadedFile) { + const fileType = event.target?.files?.[0].type; + const fileName = event.target?.files?.[0].name; + setBeforeImg(URL.createObjectURL(uploadedFile)); + setBeforeFileType(fileType); + setBeforeFileName(fileName); + onChange(uploadedFile); + setShowBeforeImage(false); + } + }; + + return ( + + + {title} + + + {error ? error.message : null} + + ); +}; +export default ImageUpload; diff --git a/src/components/infrastructure/tollHouse/Form/CreateTollHouse/LogesticController.jsx b/src/components/infrastructure/tollHouse/Form/CreateTollHouse/LogesticController.jsx index 513abbf..4304c8b 100644 --- a/src/components/infrastructure/tollHouse/Form/CreateTollHouse/LogesticController.jsx +++ b/src/components/infrastructure/tollHouse/Form/CreateTollHouse/LogesticController.jsx @@ -1,42 +1,42 @@ -import { Controller, useWatch } from "react-hook-form"; -import SelectBox from "@/core/components/SelectBox"; -import useProvinces from "@/lib/hooks/useProvince"; -import { Grid } from "@mui/material"; -import CityController from "./CityController"; - -const LogesticController = ({ control }) => { - const { provinces, errorProvinces, loadingProvinces } = useProvinces(); - const isProvince = useWatch({ control, name: "is_province" }); - return ( - - {!isProvince ? ( - - { - return ( - - ); - }} - /> - - ) : null} - - - - - ); -}; -export default LogesticController; +import { Controller, useWatch } from "react-hook-form"; +import SelectBox from "@/core/components/SelectBox"; +import useProvinces from "@/lib/hooks/useProvince"; +import { Grid } from "@mui/material"; +import CityController from "./CityController"; + +const LogesticController = ({ control }) => { + const { provinces, errorProvinces, loadingProvinces } = useProvinces(); + const isProvince = useWatch({ control, name: "is_province" }); + return ( + + {!isProvince ? ( + + { + return ( + + ); + }} + /> + + ) : null} + + + + + ); +}; +export default LogesticController; diff --git a/src/components/infrastructure/tollHouse/Form/CreateTollHouse/MachineInfo.jsx b/src/components/infrastructure/tollHouse/Form/CreateTollHouse/MachineInfo.jsx index 44d3fea..3b05a3d 100644 --- a/src/components/infrastructure/tollHouse/Form/CreateTollHouse/MachineInfo.jsx +++ b/src/components/infrastructure/tollHouse/Form/CreateTollHouse/MachineInfo.jsx @@ -1,199 +1,199 @@ -import { Grid, Stack, TextField } from "@mui/material"; -import { Controller } from "react-hook-form"; -import PersianTextField from "@/core/components/PersianTextField"; -import ImageUpload from "@/components/dashboard/damages/operator/Actions/create/Forms/ImageUpload"; - -const MachineInfo = ({ control }) => { - return ( - - - - - ( - { - const inputValue = event.target.value; - if (isNaN(Number(inputValue))) { - return; - } - onChange(inputValue); - }} - /> - )} - /> - - - ( - { - const inputValue = event.target.value; - if (isNaN(Number(inputValue))) { - return; - } - onChange(inputValue); - }} - /> - )} - /> - - - ( - { - const inputValue = event.target.value; - if (isNaN(Number(inputValue))) { - return; - } - onChange(inputValue); - }} - /> - )} - /> - - - - - - - ( - - )} - /> - - - ( - - )} - /> - - - - - - - ( - - )} - /> - - - ( - - )} - /> - - - - - - - ( - - )} - /> - - - - - ); -}; -export default MachineInfo; +import { Grid, Stack, TextField } from "@mui/material"; +import { Controller } from "react-hook-form"; +import PersianTextField from "@/core/components/PersianTextField"; +import ImageUpload from "@/components/dashboard/damages/operator/Actions/create/Forms/ImageUpload"; + +const MachineInfo = ({ control }) => { + return ( + + + + + ( + { + const inputValue = event.target.value; + if (isNaN(Number(inputValue))) { + return; + } + onChange(inputValue); + }} + /> + )} + /> + + + ( + { + const inputValue = event.target.value; + if (isNaN(Number(inputValue))) { + return; + } + onChange(inputValue); + }} + /> + )} + /> + + + ( + { + const inputValue = event.target.value; + if (isNaN(Number(inputValue))) { + return; + } + onChange(inputValue); + }} + /> + )} + /> + + + + + + + ( + + )} + /> + + + ( + + )} + /> + + + + + + + ( + + )} + /> + + + ( + + )} + /> + + + + + + + ( + + )} + /> + + + + + ); +}; +export default MachineInfo; diff --git a/src/components/infrastructure/tollHouse/Form/CreateTollHouse/TollHouseInfo.jsx b/src/components/infrastructure/tollHouse/Form/CreateTollHouse/TollHouseInfo.jsx index d06a823..22e3fdc 100644 --- a/src/components/infrastructure/tollHouse/Form/CreateTollHouse/TollHouseInfo.jsx +++ b/src/components/infrastructure/tollHouse/Form/CreateTollHouse/TollHouseInfo.jsx @@ -1,311 +1,311 @@ -import { Grid, Stack, TextField } from "@mui/material"; -import { Controller } from "react-hook-form"; -import SelectBox from "@/core/components/SelectBox"; -import useProvince from "@/lib/hooks/useProvince"; -import PersianTextField from "@/core/components/PersianTextField"; -import CityController from "./CityController"; -import LogesticController from "./LogesticController"; - -const TollHouseInfo = ({ control }) => { - const { provinces, loadingProvinces, errorProvinces } = useProvince(); - return ( - - - - - ( - - )} - /> - - - ( - { - const inputValue = event.target.value; - if (isNaN(Number(inputValue))) { - return; - } - onChange(inputValue); - }} - /> - )} - /> - - - - - - - - - - { - return ( - - ); - }} - /> - - - { - return ( - - ); - }} - /> - - - - - - - ( - { - const inputValue = event.target.value; - if (isNaN(Number(inputValue))) { - return; - } - onChange(inputValue); - }} - /> - )} - /> - - - ( - { - const inputValue = event.target.value; - if (isNaN(Number(inputValue))) { - return; - } - onChange(inputValue); - }} - /> - )} - /> - - - - - - - ( - - )} - /> - - - ( - { - const inputValue = event.target.value; - if (isNaN(Number(inputValue))) { - return; - } - onChange(inputValue); - }} - /> - )} - /> - - - - - - - ( - - )} - /> - - - ( - { - const inputValue = event.target.value; - if (isNaN(Number(inputValue))) { - return; - } - onChange(inputValue); - }} - /> - )} - /> - - - - - ); -}; -export default TollHouseInfo; +import { Grid, Stack, TextField } from "@mui/material"; +import { Controller } from "react-hook-form"; +import SelectBox from "@/core/components/SelectBox"; +import useProvince from "@/lib/hooks/useProvince"; +import PersianTextField from "@/core/components/PersianTextField"; +import CityController from "./CityController"; +import LogesticController from "./LogesticController"; + +const TollHouseInfo = ({ control }) => { + const { provinces, loadingProvinces, errorProvinces } = useProvince(); + return ( + + + + + ( + + )} + /> + + + ( + { + const inputValue = event.target.value; + if (isNaN(Number(inputValue))) { + return; + } + onChange(inputValue); + }} + /> + )} + /> + + + + + + + + + + { + return ( + + ); + }} + /> + + + { + return ( + + ); + }} + /> + + + + + + + ( + { + const inputValue = event.target.value; + if (isNaN(Number(inputValue))) { + return; + } + onChange(inputValue); + }} + /> + )} + /> + + + ( + { + const inputValue = event.target.value; + if (isNaN(Number(inputValue))) { + return; + } + onChange(inputValue); + }} + /> + )} + /> + + + + + + + ( + + )} + /> + + + ( + { + const inputValue = event.target.value; + if (isNaN(Number(inputValue))) { + return; + } + onChange(inputValue); + }} + /> + )} + /> + + + + + + + ( + + )} + /> + + + ( + { + const inputValue = event.target.value; + if (isNaN(Number(inputValue))) { + return; + } + onChange(inputValue); + }} + /> + )} + /> + + + + + ); +}; +export default TollHouseInfo; diff --git a/src/components/infrastructure/tollHouse/Form/CreateTollHouse/TollHouseLocation.jsx b/src/components/infrastructure/tollHouse/Form/CreateTollHouse/TollHouseLocation.jsx index 98d36a7..2f9f168 100644 --- a/src/components/infrastructure/tollHouse/Form/CreateTollHouse/TollHouseLocation.jsx +++ b/src/components/infrastructure/tollHouse/Form/CreateTollHouse/TollHouseLocation.jsx @@ -1,20 +1,20 @@ -import MapInfoOneMarker from "@/core/components/MapInfoOneMarker"; -import { Stack } from "@mui/material"; -import { useWatch } from "react-hook-form"; - -const TollHouseLocation = ({ setValue, errors, control }) => { - const StartPoint = useWatch({ control, name: "start_point" }); - return ( - <> - - - - - ); -}; -export default TollHouseLocation; +import MapInfoOneMarker from "@/core/components/MapInfoOneMarker"; +import { Stack } from "@mui/material"; +import { useWatch } from "react-hook-form"; + +const TollHouseLocation = ({ setValue, errors, control }) => { + const StartPoint = useWatch({ control, name: "start_point" }); + return ( + <> + + + + + ); +}; +export default TollHouseLocation; diff --git a/src/components/infrastructure/tollHouse/Form/CreateTollHouse/index.jsx b/src/components/infrastructure/tollHouse/Form/CreateTollHouse/index.jsx index 621f4e6..7dbe3d5 100644 --- a/src/components/infrastructure/tollHouse/Form/CreateTollHouse/index.jsx +++ b/src/components/infrastructure/tollHouse/Form/CreateTollHouse/index.jsx @@ -1,140 +1,140 @@ -import { Button, Dialog, IconButton, useMediaQuery } from "@mui/material"; -import { useState } from "react"; -import CreateTollHouseContent from "./CreateTollHouseContent"; -import { AddCircle } from "@mui/icons-material"; -import { useTheme } from "@emotion/react"; -import { CREATE_TOLL_HOUSE } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -import CloseIcon from "@mui/icons-material/Close"; -import { useAuth } from "@/lib/contexts/auth"; -import { usePermissions } from "@/lib/hooks/usePermissions"; - -const CreateTollHouse = ({ mutate }) => { - const requestServer = useRequest({ notificationSuccess: true }); - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - const [open, setOpen] = useState(false); - const { user } = useAuth(); - const { data: userPermissions } = usePermissions(); - const hasCreateProvincePermission = userPermissions.some((item) => ["add-tollhouse"].includes(item)); - const handleOpen = () => { - setOpen(true); - }; - const SubmitCreateTollHouse = async (result) => { - const fields = [ - "province_id", - "city_id", - "name", - "status", - "type", - "team_num", - "staff_num", - "phone", - "responsible_name", - "responsible_mobile", - "successor_name", - "successor_mobile", - "machines_light", - "machines_sheavy", - "machines_heavy", - "overview_files_1", - "overview_files_2", - "overview_files_3", - "overview_files_4", - "overview_files_5", - ]; - const formData = new FormData(); - fields.forEach((field) => { - if (result[field] !== undefined && result[field] !== null) { - formData.append(field, result[field]); - } - }); - formData.append("lat", result.start_point.lat); - formData.append("lng", result.start_point.lng); - await requestServer(`${CREATE_TOLL_HOUSE}`, "post", { - data: formData, - }) - .then(() => { - mutate(); - setOpen(false); - }) - .catch(() => {}); - }; - const defaultValues = { - name: "", - is_province: !hasCreateProvincePermission, - province_id: !hasCreateProvincePermission ? user.province_id : null, - city_id: null, - status: "", - type: "", - phone: "", - team_num: "", - staff_num: "", - responsible_name: "", - responsible_mobile: "", - successor_name: "", - successor_mobile: "", - machines_light: "", - machines_sheavy: "", - machines_heavy: "", - overview_files_1: null, - overview_files_2: null, - overview_files_3: null, - overview_files_4: null, - overview_files_5: null, - start_point: "", - }; - return ( - <> - {isMobile ? ( - - - - ) : ( - - )} - setOpen(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - maxWidth={"md"} - scroll="paper" - > - setOpen(false)} - sx={(theme) => ({ - position: "absolute", - right: 8, - top: 8, - zIndex: 50, - color: theme.palette.grey[500], - })} - > - - - {open && ( - - )} - - - ); -}; -export default CreateTollHouse; +import { Button, Dialog, IconButton, useMediaQuery } from "@mui/material"; +import { useState } from "react"; +import CreateTollHouseContent from "./CreateTollHouseContent"; +import { AddCircle } from "@mui/icons-material"; +import { useTheme } from "@emotion/react"; +import { CREATE_TOLL_HOUSE } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +import CloseIcon from "@mui/icons-material/Close"; +import { useAuth } from "@/lib/contexts/auth"; +import { usePermissions } from "@/lib/hooks/usePermissions"; + +const CreateTollHouse = ({ mutate }) => { + const requestServer = useRequest({ notificationSuccess: true }); + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + const [open, setOpen] = useState(false); + const { user } = useAuth(); + const { data: userPermissions } = usePermissions(); + const hasCreateProvincePermission = userPermissions.some((item) => ["add-tollhouse"].includes(item)); + const handleOpen = () => { + setOpen(true); + }; + const SubmitCreateTollHouse = async (result) => { + const fields = [ + "province_id", + "city_id", + "name", + "status", + "type", + "team_num", + "staff_num", + "phone", + "responsible_name", + "responsible_mobile", + "successor_name", + "successor_mobile", + "machines_light", + "machines_sheavy", + "machines_heavy", + "overview_files_1", + "overview_files_2", + "overview_files_3", + "overview_files_4", + "overview_files_5", + ]; + const formData = new FormData(); + fields.forEach((field) => { + if (result[field] !== undefined && result[field] !== null) { + formData.append(field, result[field]); + } + }); + formData.append("lat", result.start_point.lat); + formData.append("lng", result.start_point.lng); + await requestServer(`${CREATE_TOLL_HOUSE}`, "post", { + data: formData, + }) + .then(() => { + mutate(); + setOpen(false); + }) + .catch(() => {}); + }; + const defaultValues = { + name: "", + is_province: !hasCreateProvincePermission, + province_id: !hasCreateProvincePermission ? user.province_id : null, + city_id: null, + status: "", + type: "", + phone: "", + team_num: "", + staff_num: "", + responsible_name: "", + responsible_mobile: "", + successor_name: "", + successor_mobile: "", + machines_light: "", + machines_sheavy: "", + machines_heavy: "", + overview_files_1: null, + overview_files_2: null, + overview_files_3: null, + overview_files_4: null, + overview_files_5: null, + start_point: "", + }; + return ( + <> + {isMobile ? ( + + + + ) : ( + + )} + setOpen(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + maxWidth={"md"} + scroll="paper" + > + setOpen(false)} + sx={(theme) => ({ + position: "absolute", + right: 8, + top: 8, + zIndex: 50, + color: theme.palette.grey[500], + })} + > + + + {open && ( + + )} + + + ); +}; +export default CreateTollHouse; diff --git a/src/components/infrastructure/tollHouse/Form/Edit/EditController.jsx b/src/components/infrastructure/tollHouse/Form/Edit/EditController.jsx index 774e5cb..a9d4281 100644 --- a/src/components/infrastructure/tollHouse/Form/Edit/EditController.jsx +++ b/src/components/infrastructure/tollHouse/Form/Edit/EditController.jsx @@ -1,107 +1,107 @@ -import useRequest from "@/lib/hooks/useRequest"; -import { useEffect, useState } from "react"; -import { GET_TOLL_HOUSE_DETAILS, UPDATE_TOLL_HOUSE_ITEM } from "@/core/utils/routes"; -import DialogLoading from "@/core/components/DialogLoading"; -import CreateTollHouseContent from "../CreateTollHouse/CreateTollHouseContent"; -import { usePermissions } from "@/lib/hooks/usePermissions"; - -const EditController = ({ rowId, mutate, setOpenEditDialog }) => { - const { data: userPermissions } = usePermissions(); - const hasCreateProvincePermission = userPermissions.some((item) => ["add-receipt"].includes(item)); - const requestServer = useRequest(); - const [tollHouseItemDetails, setTollHouseItemDetails] = useState(null); - const [tollHouseItemDetailsLoading, setTollHouseItemDetailsLoading] = useState(false); - - useEffect(() => { - setTollHouseItemDetailsLoading(true); - requestServer(`${GET_TOLL_HOUSE_DETAILS}/${rowId}`, "get") - .then((response) => { - setTollHouseItemDetails(response.data.data); - setTollHouseItemDetailsLoading(false); - }) - .catch((e) => { - setTollHouseItemDetailsLoading(false); - }); - }, [rowId]); - - const defaultData = { - phone: tollHouseItemDetails?.phone || "", - is_province: !hasCreateProvincePermission, - province_id: tollHouseItemDetails?.province_id || null, - city_id: tollHouseItemDetails?.city_id || null, - start_point: { lat: tollHouseItemDetails?.lat || "", lng: tollHouseItemDetails?.lng || "" }, - name: tollHouseItemDetails?.name || "", - status: tollHouseItemDetails?.status || "", - type: tollHouseItemDetails?.type || "", - team_num: tollHouseItemDetails?.team_num || "", - staff_num: tollHouseItemDetails?.staff_num || "", - responsible_name: tollHouseItemDetails?.responsible_name || "", - responsible_mobile: tollHouseItemDetails?.responsible_mobile || "", - successor_name: tollHouseItemDetails?.successor_name || "", - successor_mobile: tollHouseItemDetails?.successor_mobile || "", - machines_light: tollHouseItemDetails?.machines_light || "", - machines_sheavy: tollHouseItemDetails?.machines_sheavy || "", - machines_heavy: tollHouseItemDetails?.machines_heavy || "", - overview_files_1: tollHouseItemDetails?.files[0]?.path || null, - overview_files_2: tollHouseItemDetails?.files[1]?.path || null, - overview_files_3: tollHouseItemDetails?.files[2]?.path || null, - overview_files_4: tollHouseItemDetails?.files[3]?.path || null, - overview_files_5: tollHouseItemDetails?.files[4]?.path || null, - }; - const HandleSubmit = async (result) => { - const fields = [ - "province_id", - "city_id", - "name", - "status", - "type", - "team_num", - "staff_num", - "phone", - "responsible_name", - "responsible_mobile", - "successor_name", - "successor_mobile", - "machines_light", - "machines_sheavy", - "machines_heavy", - ]; - const formData = new FormData(); - fields.forEach((field) => { - if (result[field] !== undefined && result[field] !== null) { - formData.append(field, result[field]); - } - }); - for (let i = 1; i <= 5; i++) { - if (result[`overview_files_${i}`] !== defaultData[`overview_files_${i}`]) { - formData.append(`overview_files_${i}`, result[`overview_files_${i}`]); - } - } - formData.append("lat", result.start_point.lat); - formData.append("lng", result.start_point.lng); - - await requestServer(`${UPDATE_TOLL_HOUSE_ITEM}/${rowId}`, "post", { - data: formData, - notificationSuccess: true, - }) - .then(() => { - mutate(); - setOpenEditDialog(false); - }) - .catch(() => {}); - }; - return ( - <> - {tollHouseItemDetailsLoading ? ( - - ) : ( - - )} - - ); -}; -export default EditController; +import useRequest from "@/lib/hooks/useRequest"; +import { useEffect, useState } from "react"; +import { GET_TOLL_HOUSE_DETAILS, UPDATE_TOLL_HOUSE_ITEM } from "@/core/utils/routes"; +import DialogLoading from "@/core/components/DialogLoading"; +import CreateTollHouseContent from "../CreateTollHouse/CreateTollHouseContent"; +import { usePermissions } from "@/lib/hooks/usePermissions"; + +const EditController = ({ rowId, mutate, setOpenEditDialog }) => { + const { data: userPermissions } = usePermissions(); + const hasCreateProvincePermission = userPermissions.some((item) => ["add-receipt"].includes(item)); + const requestServer = useRequest(); + const [tollHouseItemDetails, setTollHouseItemDetails] = useState(null); + const [tollHouseItemDetailsLoading, setTollHouseItemDetailsLoading] = useState(false); + + useEffect(() => { + setTollHouseItemDetailsLoading(true); + requestServer(`${GET_TOLL_HOUSE_DETAILS}/${rowId}`, "get") + .then((response) => { + setTollHouseItemDetails(response.data.data); + setTollHouseItemDetailsLoading(false); + }) + .catch((e) => { + setTollHouseItemDetailsLoading(false); + }); + }, [rowId]); + + const defaultData = { + phone: tollHouseItemDetails?.phone || "", + is_province: !hasCreateProvincePermission, + province_id: tollHouseItemDetails?.province_id || null, + city_id: tollHouseItemDetails?.city_id || null, + start_point: { lat: tollHouseItemDetails?.lat || "", lng: tollHouseItemDetails?.lng || "" }, + name: tollHouseItemDetails?.name || "", + status: tollHouseItemDetails?.status || "", + type: tollHouseItemDetails?.type || "", + team_num: tollHouseItemDetails?.team_num || "", + staff_num: tollHouseItemDetails?.staff_num || "", + responsible_name: tollHouseItemDetails?.responsible_name || "", + responsible_mobile: tollHouseItemDetails?.responsible_mobile || "", + successor_name: tollHouseItemDetails?.successor_name || "", + successor_mobile: tollHouseItemDetails?.successor_mobile || "", + machines_light: tollHouseItemDetails?.machines_light || "", + machines_sheavy: tollHouseItemDetails?.machines_sheavy || "", + machines_heavy: tollHouseItemDetails?.machines_heavy || "", + overview_files_1: tollHouseItemDetails?.files[0]?.path || null, + overview_files_2: tollHouseItemDetails?.files[1]?.path || null, + overview_files_3: tollHouseItemDetails?.files[2]?.path || null, + overview_files_4: tollHouseItemDetails?.files[3]?.path || null, + overview_files_5: tollHouseItemDetails?.files[4]?.path || null, + }; + const HandleSubmit = async (result) => { + const fields = [ + "province_id", + "city_id", + "name", + "status", + "type", + "team_num", + "staff_num", + "phone", + "responsible_name", + "responsible_mobile", + "successor_name", + "successor_mobile", + "machines_light", + "machines_sheavy", + "machines_heavy", + ]; + const formData = new FormData(); + fields.forEach((field) => { + if (result[field] !== undefined && result[field] !== null) { + formData.append(field, result[field]); + } + }); + for (let i = 1; i <= 5; i++) { + if (result[`overview_files_${i}`] !== defaultData[`overview_files_${i}`]) { + formData.append(`overview_files_${i}`, result[`overview_files_${i}`]); + } + } + formData.append("lat", result.start_point.lat); + formData.append("lng", result.start_point.lng); + + await requestServer(`${UPDATE_TOLL_HOUSE_ITEM}/${rowId}`, "post", { + data: formData, + notificationSuccess: true, + }) + .then(() => { + mutate(); + setOpenEditDialog(false); + }) + .catch(() => {}); + }; + return ( + <> + {tollHouseItemDetailsLoading ? ( + + ) : ( + + )} + + ); +}; +export default EditController; diff --git a/src/components/infrastructure/tollHouse/Form/Edit/index.jsx b/src/components/infrastructure/tollHouse/Form/Edit/index.jsx index 53be78c..16ec8a4 100644 --- a/src/components/infrastructure/tollHouse/Form/Edit/index.jsx +++ b/src/components/infrastructure/tollHouse/Form/Edit/index.jsx @@ -1,59 +1,59 @@ -import { Dialog, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import BorderColorIcon from "@mui/icons-material/BorderColor"; -import EditController from "./EditController"; -import CloseIcon from "@mui/icons-material/Close"; - -const EditForm = ({ row, mutate, rowId }) => { - const [openEditDialog, setOpenEditDialog] = useState(false); - - return ( - <> - - { - setOpenEditDialog(true); - }} - > - - - - - setOpenEditDialog(false)} - sx={(theme) => ({ - position: "absolute", - right: 8, - top: 8, - zIndex: 50, - color: theme.palette.grey[500], - })} - > - - - {openEditDialog && ( - - )} - - - ); -}; -export default EditForm; +import { Dialog, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import BorderColorIcon from "@mui/icons-material/BorderColor"; +import EditController from "./EditController"; +import CloseIcon from "@mui/icons-material/Close"; + +const EditForm = ({ row, mutate, rowId }) => { + const [openEditDialog, setOpenEditDialog] = useState(false); + + return ( + <> + + { + setOpenEditDialog(true); + }} + > + + + + + setOpenEditDialog(false)} + sx={(theme) => ({ + position: "absolute", + right: 8, + top: 8, + zIndex: 50, + color: theme.palette.grey[500], + })} + > + + + {openEditDialog && ( + + )} + + + ); +}; +export default EditForm; diff --git a/src/components/infrastructure/tollHouse/RowActions/DeleteDialog/DeleteContent.jsx b/src/components/infrastructure/tollHouse/RowActions/DeleteDialog/DeleteContent.jsx index 3f3095a..bf0a3c5 100644 --- a/src/components/infrastructure/tollHouse/RowActions/DeleteDialog/DeleteContent.jsx +++ b/src/components/infrastructure/tollHouse/RowActions/DeleteDialog/DeleteContent.jsx @@ -1,39 +1,39 @@ -import { Button, DialogActions, DialogContent, Stack, Typography } from "@mui/material"; -import React, { useState } from "react"; -import useRequest from "@/lib/hooks/useRequest"; -import { DELETE_TOLL_HOUSE_ITEM } from "@/core/utils/routes"; - -const DeleteContent = ({ rowId, mutate, setOpenDeleteDialog }) => { - const [submitting, setSubmitting] = useState(false); - const requestServer = useRequest({ notificationSuccess: true }); - const handleClick = () => { - setSubmitting(true); - requestServer(`${DELETE_TOLL_HOUSE_ITEM}/${rowId}`, "delete") - .then(() => { - mutate(); - setOpenDeleteDialog(false); - setSubmitting(false); - }) - .catch(() => { - setSubmitting(false); - }); - }; - return ( - <> - - - آیا از حذف راهدارخانه اطمینان دارید؟ - - - - - - - - ); -}; -export default DeleteContent; +import { Button, DialogActions, DialogContent, Stack, Typography } from "@mui/material"; +import React, { useState } from "react"; +import useRequest from "@/lib/hooks/useRequest"; +import { DELETE_TOLL_HOUSE_ITEM } from "@/core/utils/routes"; + +const DeleteContent = ({ rowId, mutate, setOpenDeleteDialog }) => { + const [submitting, setSubmitting] = useState(false); + const requestServer = useRequest({ notificationSuccess: true }); + const handleClick = () => { + setSubmitting(true); + requestServer(`${DELETE_TOLL_HOUSE_ITEM}/${rowId}`, "delete") + .then(() => { + mutate(); + setOpenDeleteDialog(false); + setSubmitting(false); + }) + .catch(() => { + setSubmitting(false); + }); + }; + return ( + <> + + + آیا از حذف راهدارخانه اطمینان دارید؟ + + + + + + + + ); +}; +export default DeleteContent; diff --git a/src/components/infrastructure/tollHouse/RowActions/DeleteDialog/index.jsx b/src/components/infrastructure/tollHouse/RowActions/DeleteDialog/index.jsx index 54278bd..37eefdf 100644 --- a/src/components/infrastructure/tollHouse/RowActions/DeleteDialog/index.jsx +++ b/src/components/infrastructure/tollHouse/RowActions/DeleteDialog/index.jsx @@ -1,34 +1,34 @@ -import DeleteIcon from "@mui/icons-material/Delete"; -import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useState } from "react"; -import DeleteContent from "./DeleteContent"; -const DeleteDialog = ({ rowId, mutate }) => { - const [openDeleteDialog, setOpenDeleteDialog] = useState(false); - - return ( - <> - - setOpenDeleteDialog(true)}> - - - - setOpenDeleteDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - حذف راهدارخانه - {openDeleteDialog && ( - - )} - - - ); -}; -export default DeleteDialog; +import DeleteIcon from "@mui/icons-material/Delete"; +import { Dialog, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useState } from "react"; +import DeleteContent from "./DeleteContent"; +const DeleteDialog = ({ rowId, mutate }) => { + const [openDeleteDialog, setOpenDeleteDialog] = useState(false); + + return ( + <> + + setOpenDeleteDialog(true)}> + + + + setOpenDeleteDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + حذف راهدارخانه + {openDeleteDialog && ( + + )} + + + ); +}; +export default DeleteDialog; diff --git a/src/components/infrastructure/tollHouse/RowActions/ImageForm/ImageFormContent.jsx b/src/components/infrastructure/tollHouse/RowActions/ImageForm/ImageFormContent.jsx index c8f22d0..f8fd088 100644 --- a/src/components/infrastructure/tollHouse/RowActions/ImageForm/ImageFormContent.jsx +++ b/src/components/infrastructure/tollHouse/RowActions/ImageForm/ImageFormContent.jsx @@ -1,45 +1,45 @@ -import { Box, Stack, Typography, useTheme } from "@mui/material"; -import Image from "next/image"; - -const ImageFormContent = ({ image, title }) => { - const theme = useTheme(); - return ( - - - {title} - - - Image - - - ); -}; -export default ImageFormContent; +import { Box, Stack, Typography, useTheme } from "@mui/material"; +import Image from "next/image"; + +const ImageFormContent = ({ image, title }) => { + const theme = useTheme(); + return ( + + + {title} + + + Image + + + ); +}; +export default ImageFormContent; diff --git a/src/components/infrastructure/tollHouse/RowActions/ImageForm/ImagesContent.jsx b/src/components/infrastructure/tollHouse/RowActions/ImageForm/ImagesContent.jsx index 6e22c9a..f46e2d4 100644 --- a/src/components/infrastructure/tollHouse/RowActions/ImageForm/ImagesContent.jsx +++ b/src/components/infrastructure/tollHouse/RowActions/ImageForm/ImagesContent.jsx @@ -1,39 +1,39 @@ -import { useEffect, useState } from "react"; -import ImageFormContent from "./ImageFormContent"; -import DialogLoading from "@/core/components/DialogLoading"; -import useRequest from "@/lib/hooks/useRequest"; -import { GET_TOLL_HOUSE_IMAGES } from "@/core/utils/routes"; -import { Typography } from "@mui/material"; -const titles = ["نمای کلی از راهداری", "آشیانه ماشین آلات", "انباری شن و ماسه", "محیط کاری", "سایر تصاویر"]; - -const ImagesContent = ({ rowId }) => { - const requestServer = useRequest(); - const [tollHouseImages, setTollHouseImages] = useState(null); - const [tollHouseImagesLoading, setTollHouseImagesLoading] = useState(false); - useEffect(() => { - setTollHouseImagesLoading(true); - requestServer(`${GET_TOLL_HOUSE_IMAGES}/${rowId}`, "get") - .then((response) => { - setTollHouseImages(response.data.data); - setTollHouseImagesLoading(false); - }) - .catch((e) => { - setTollHouseImagesLoading(false); - }); - }, [rowId]); - - return ( - <> - {tollHouseImagesLoading ? ( - - ) : tollHouseImages ? ( - tollHouseImages.map((image, index) => { - return ; - }) - ) : ( - تصویری در سامانه یافت نشد - )} - - ); -}; -export default ImagesContent; +import { useEffect, useState } from "react"; +import ImageFormContent from "./ImageFormContent"; +import DialogLoading from "@/core/components/DialogLoading"; +import useRequest from "@/lib/hooks/useRequest"; +import { GET_TOLL_HOUSE_IMAGES } from "@/core/utils/routes"; +import { Typography } from "@mui/material"; +const titles = ["نمای کلی از راهداری", "آشیانه ماشین آلات", "انباری شن و ماسه", "محیط کاری", "سایر تصاویر"]; + +const ImagesContent = ({ rowId }) => { + const requestServer = useRequest(); + const [tollHouseImages, setTollHouseImages] = useState(null); + const [tollHouseImagesLoading, setTollHouseImagesLoading] = useState(false); + useEffect(() => { + setTollHouseImagesLoading(true); + requestServer(`${GET_TOLL_HOUSE_IMAGES}/${rowId}`, "get") + .then((response) => { + setTollHouseImages(response.data.data); + setTollHouseImagesLoading(false); + }) + .catch((e) => { + setTollHouseImagesLoading(false); + }); + }, [rowId]); + + return ( + <> + {tollHouseImagesLoading ? ( + + ) : tollHouseImages ? ( + tollHouseImages.map((image, index) => { + return ; + }) + ) : ( + تصویری در سامانه یافت نشد + )} + + ); +}; +export default ImagesContent; diff --git a/src/components/infrastructure/tollHouse/RowActions/ImageForm/index.jsx b/src/components/infrastructure/tollHouse/RowActions/ImageForm/index.jsx index 6ac8d25..4749109 100644 --- a/src/components/infrastructure/tollHouse/RowActions/ImageForm/index.jsx +++ b/src/components/infrastructure/tollHouse/RowActions/ImageForm/index.jsx @@ -1,43 +1,43 @@ -import PhotoLibraryIcon from "@mui/icons-material/PhotoLibrary"; -import { Button, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, Tooltip } from "@mui/material"; -import { useEffect, useState } from "react"; -import ImagesContent from "./ImagesContent"; -import useRequest from "@/lib/hooks/useRequest"; -import { GET_TOLL_HOUSE_IMAGES } from "@/core/utils/routes"; -import DialogLoading from "@/core/components/DialogLoading"; - -const ImageDialog = ({ rowId }) => { - const [openImageDialog, setOpenImageDialog] = useState(false); - - return ( - <> - - setOpenImageDialog(true)}> - - - - setOpenImageDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - maxWidth={"sm"} - scroll="paper" - > - تصاویر - {openImageDialog && } - - - - - - ); -}; - -export default ImageDialog; +import PhotoLibraryIcon from "@mui/icons-material/PhotoLibrary"; +import { Button, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, Tooltip } from "@mui/material"; +import { useEffect, useState } from "react"; +import ImagesContent from "./ImagesContent"; +import useRequest from "@/lib/hooks/useRequest"; +import { GET_TOLL_HOUSE_IMAGES } from "@/core/utils/routes"; +import DialogLoading from "@/core/components/DialogLoading"; + +const ImageDialog = ({ rowId }) => { + const [openImageDialog, setOpenImageDialog] = useState(false); + + return ( + <> + + setOpenImageDialog(true)}> + + + + setOpenImageDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + maxWidth={"sm"} + scroll="paper" + > + تصاویر + {openImageDialog && } + + + + + + ); +}; + +export default ImageDialog; diff --git a/src/components/infrastructure/tollHouse/RowActions/LocationForm/LocationFormContent.jsx b/src/components/infrastructure/tollHouse/RowActions/LocationForm/LocationFormContent.jsx index 14b3db3..08e4730 100644 --- a/src/components/infrastructure/tollHouse/RowActions/LocationForm/LocationFormContent.jsx +++ b/src/components/infrastructure/tollHouse/RowActions/LocationForm/LocationFormContent.jsx @@ -1,35 +1,35 @@ -"use client"; -import { Box, Button, DialogActions, DialogContent, Stack } from "@mui/material"; -import React from "react"; -import dynamic from "next/dynamic"; -import MapLoading from "@/core/components/MapLayer/Loading"; -import ShowLocationMarker from "@/core/components/ShowLocationMarker"; -const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { - loading: () => , - ssr: false, -}); - -const LocationFormContent = ({ setOpenLocationDialog, start_lat, start_lng, end_lat, end_lng }) => { - return ( - <> - - - - - - - - - - - - ); -}; -export default LocationFormContent; +"use client"; +import { Box, Button, DialogActions, DialogContent, Stack } from "@mui/material"; +import React from "react"; +import dynamic from "next/dynamic"; +import MapLoading from "@/core/components/MapLayer/Loading"; +import ShowLocationMarker from "@/core/components/ShowLocationMarker"; +const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { + loading: () => , + ssr: false, +}); + +const LocationFormContent = ({ setOpenLocationDialog, start_lat, start_lng, end_lat, end_lng }) => { + return ( + <> + + + + + + + + + + + + ); +}; +export default LocationFormContent; diff --git a/src/components/infrastructure/tollHouse/RowActions/LocationForm/index.jsx b/src/components/infrastructure/tollHouse/RowActions/LocationForm/index.jsx index f578ca8..90a5cb4 100644 --- a/src/components/infrastructure/tollHouse/RowActions/LocationForm/index.jsx +++ b/src/components/infrastructure/tollHouse/RowActions/LocationForm/index.jsx @@ -1,38 +1,38 @@ -import React, { useState } from "react"; -import { Tooltip, IconButton, Dialog, DialogTitle } from "@mui/material"; -import ExploreIcon from "@mui/icons-material/Explore"; -import LocationFormContent from "./LocationFormContent"; -const LocationForm = ({ start_lat, start_lng, end_lat, end_lng }) => { - const [openLocationDialog, setOpenLocationDialog] = useState(false); - - return ( - <> - - setOpenLocationDialog(true)}> - - - - setOpenLocationDialog(false)} - PaperProps={{ - sx: { - boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", - }, - }} - dir="rtl" - maxWidth={"md"} - > - موقعیت - - - - ); -}; -export default LocationForm; +import React, { useState } from "react"; +import { Tooltip, IconButton, Dialog, DialogTitle } from "@mui/material"; +import ExploreIcon from "@mui/icons-material/Explore"; +import LocationFormContent from "./LocationFormContent"; +const LocationForm = ({ start_lat, start_lng, end_lat, end_lng }) => { + const [openLocationDialog, setOpenLocationDialog] = useState(false); + + return ( + <> + + setOpenLocationDialog(true)}> + + + + setOpenLocationDialog(false)} + PaperProps={{ + sx: { + boxShadow: "rgba(60, 64, 67, 0.3) 0px 1px 16px 0px, rgba(60, 64, 67, 0.15) 0px 1px 10px 0px", + }, + }} + dir="rtl" + maxWidth={"md"} + > + موقعیت + + + + ); +}; +export default LocationForm; diff --git a/src/components/infrastructure/tollHouse/RowActions/index.jsx b/src/components/infrastructure/tollHouse/RowActions/index.jsx index 8801bda..80b1396 100644 --- a/src/components/infrastructure/tollHouse/RowActions/index.jsx +++ b/src/components/infrastructure/tollHouse/RowActions/index.jsx @@ -1,21 +1,21 @@ -import { Box } from "@mui/material"; -import EditForm from "../Form/Edit"; -import DeleteDialog from "./DeleteDialog"; -import { usePermissions } from "@/lib/hooks/usePermissions"; - -const RowActions = ({ row, mutate }) => { - const { data: userPermissions } = usePermissions(); - const hasEditPermission = userPermissions.some((item) => - ["edit-tollhouse", "edit-tollhouse-province"].includes(item) - ); - const hasDeletePermission = userPermissions.some((item) => - ["delete-tollhouse", "delete-tollhouse-province"].includes(item) - ); - return ( - - {hasEditPermission && } - {hasDeletePermission && } - - ); -}; -export default RowActions; +import { Box } from "@mui/material"; +import EditForm from "../Form/Edit"; +import DeleteDialog from "./DeleteDialog"; +import { usePermissions } from "@/lib/hooks/usePermissions"; + +const RowActions = ({ row, mutate }) => { + const { data: userPermissions } = usePermissions(); + const hasEditPermission = userPermissions.some((item) => + ["edit-tollhouse", "edit-tollhouse-province"].includes(item) + ); + const hasDeletePermission = userPermissions.some((item) => + ["delete-tollhouse", "delete-tollhouse-province"].includes(item) + ); + return ( + + {hasEditPermission && } + {hasDeletePermission && } + + ); +}; +export default RowActions; diff --git a/src/components/infrastructure/tollHouse/TollHouseList.jsx b/src/components/infrastructure/tollHouse/TollHouseList.jsx index 2b0a39c..113dcbc 100644 --- a/src/components/infrastructure/tollHouse/TollHouseList.jsx +++ b/src/components/infrastructure/tollHouse/TollHouseList.jsx @@ -1,412 +1,412 @@ -"use client"; -import { useEffect, useMemo, useState } from "react"; -import { Box, Stack, Typography } from "@mui/material"; -import DataTableWithAuth from "@/core/components/DataTableWithAuth"; -import Toolbar from "./Toolbar"; -import { GET_TOLL_HOUSE_LIST } from "@/core/utils/routes"; -import moment from "jalali-moment"; -import RowActions from "./RowActions"; -import useProvinces from "@/lib/hooks/useProvince"; -import CustomSelectByDependency from "@/core/components/DataTable/filter/fieldsType/CustomSelectByDependency"; -import useEdaratLists from "@/lib/hooks/useEdaratLists"; -import { usePermissions } from "@/lib/hooks/usePermissions"; -import LocationForm from "./RowActions/LocationForm"; -import ImageDialog from "./RowActions/ImageForm"; - -const statusOptions = [ - { value: "", label: "همه وضعیت ها" }, - { value: 0, label: "غیرفعال" }, - { value: 1, label: "فعال" }, -]; -const typeOptions = [ - { value: "", label: "همه نوع ها" }, - { value: 0, label: "فصلی" }, - { value: 1, label: "داعمی" }, - { value: 2, label: "موقت" }, -]; -const TollHouseList = () => { - const { data: userPermissions } = usePermissions(); - const hasProvincePermission = userPermissions.some((item) => ["add-tollhouse"].includes(item)); - - const columns = useMemo(() => { - return [ - { - accessorKey: "id", - header: "کد یکتا", // Unique Code - id: "id", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - - { - header: "اطلاعات راهدارخانه", - id: "tollHouseInfo", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - columns: [ - { - accessorKey: "name", - header: "نام راهدارخانه", - id: "name", - enableColumnFilter: true, - datatype: "text", - filterMode: "equals", - sortDescFirst: false, - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorKey: "province_id", - header: "استان", - id: "province_id", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - grow: false, - size: 130, - ColumnSelectComponent: (props) => { - const { provinces, errorProvinces, loadingProvinces } = useProvinces(); - const getColumnSelectOptions = useMemo(() => { - if (loadingProvinces) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorProvinces) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: "کل کشور" }, - ...provinces.map((province) => ({ - value: province.id, - label: province.name_fa, - })), - ]; - }, [provinces, errorProvinces, loadingProvinces]); - return ( - - ); - }, - Cell: ({ row }) => <>{row.original.province_name}, - }, - { - accessorKey: "city_id", - header: "شهرستان", // Office - id: "city_id", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - dependencyId: "province_id", - grow: false, - size: 120, - ColumnSelectComponent: (props) => { - const { edaratList, loadingEdaratList, errorEdaratList } = useEdaratLists( - props.dependencyFieldValue.value - ); - const [prevDependency, setPrevDependency] = useState(props.dependencyFieldValue.value); - - const getColumnSelectOptions = useMemo(() => { - if (props.dependencyFieldValue.value === "") { - return [{ value: "empty", label: "ابتدا استان را انتخاب کنید" }]; - } - if (loadingEdaratList) { - return [{ value: "loading", label: "در حال بارگذاری..." }]; - } - if (errorEdaratList) { - return [{ value: "error", label: "خطا در بارگذاری" }]; - } - return [ - { value: "", label: "کل شهر ها" }, - ...edaratList.map((edare) => ({ - value: edare.id, - label: edare.name_fa, - })), - ]; - }, [edaratList, loadingEdaratList, errorEdaratList]); - useEffect(() => { - if (prevDependency === props.dependencyFieldValue?.value) return; - props.handleChange({ ...props.filterParameters, value: "" }); - setPrevDependency(props.dependencyFieldValue?.value); - }, [props.dependencyFieldValue?.value]); - return ( - - ); - }, - Cell: ({ row }) => <>{row.original.city_name}, - }, - { - accessorKey: "status", - header: "وضعیت", - id: "status", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - grow: false, - size: 100, - columnSelectOption: () => { - return statusOptions.map((status) => ({ - value: status.value, - label: status.label, - })); - }, - Cell: ({ row }) => { - const status = statusOptions.find((option) => option.value == row.original.status); - return {status?.label || ""}; - }, - }, - { - accessorKey: "type", - header: "نوع", - id: "type", - enableColumnFilter: true, - datatype: "numeric", - filterMode: "equals", - grow: false, - size: 100, - columnSelectOption: () => { - return typeOptions.map((type) => ({ - value: type.value, - label: type.label, - })); - }, - Cell: ({ row }) => { - return {row.original.type_fa}; - }, - }, - { - accessorKey: "phone", - header: "تلفن راهدارخانه", - id: "phone", - enableColumnFilter: false, - enableSorting: true, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 120, - }, - { - accessorKey: "team_num", - header: "تعداد اکیپ", - id: "team_num", - enableColumnFilter: false, - enableSorting: true, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 120, - }, - { - accessorKey: "staff_num", - header: "تعداد پرسنل", - id: "staff_num", - enableColumnFilter: false, - enableSorting: true, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 120, - }, - { - accessorKey: "responsible_name", - header: "مسئول", - id: "responsible_name", - enableColumnFilter: false, - enableSorting: true, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 120, - }, - { - accessorKey: "responsible_mobile", - header: "شماره مسئول", - id: "responsible_mobile", - enableColumnFilter: false, - enableSorting: true, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 120, - }, - { - accessorKey: "successor_name", - header: "جانشین", - id: "successor_name", - enableColumnFilter: false, - enableSorting: true, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 120, - }, - { - accessorKey: "successor_mobile", - header: "شماره جانشین", - id: "successor_mobile", - enableColumnFilter: false, - enableSorting: true, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 120, - }, - ], - }, - { - header: "ماشین آلات", - id: "machines", - enableColumnFilter: false, - enableSorting: false, - datatype: "text", - grow: false, - size: 50, - columns: [ - { - accessorKey: "machines_light", - header: "ماشین آلات سبک", - id: "machines_light", - enableColumnFilter: false, - enableSorting: true, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorKey: "machines_sheavy", - header: "ماشین آلات نیمه سنگین", - id: "machines_sheavy", - enableColumnFilter: false, - enableSorting: true, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - accessorKey: "machines_heavy", - header: "ماشین آلات سنگین", - id: "machines_heavy", - enableColumnFilter: false, - enableSorting: true, - datatype: "text", - filterMode: "equals", - columnFilterModeOptions: ["equals", "contains"], - grow: false, - size: 100, - }, - { - header: "تصاویر", - id: "images", - enableColumnFilter: false, - enableSorting: false, - datatype: "array", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue, row }) => { - return ( - - - - ); - }, - }, - ], - }, - { - header: "موقعیت", // Location - id: "location", - enableColumnFilter: false, - enableSorting: false, - datatype: "array", - grow: false, - size: 100, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - py: 0, - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - Cell: ({ renderedCellValue, row }) => { - return ( - - - - ); - }, - }, - { - accessorFn: (row) => moment(row.created_at).locale("fa").format("HH:mm | yyyy/MM/DD"), - header: "تاریخ ثبت", - id: "created_at", - enableColumnFilter: true, - datatype: "date", - filterMode: "between", - grow: false, - size: 100, - }, - ]; - }, []); - - return ( - <> - - - - - ); -}; -export default TollHouseList; +"use client"; +import { useEffect, useMemo, useState } from "react"; +import { Box, Stack, Typography } from "@mui/material"; +import DataTableWithAuth from "@/core/components/DataTableWithAuth"; +import Toolbar from "./Toolbar"; +import { GET_TOLL_HOUSE_LIST } from "@/core/utils/routes"; +import moment from "jalali-moment"; +import RowActions from "./RowActions"; +import useProvinces from "@/lib/hooks/useProvince"; +import CustomSelectByDependency from "@/core/components/DataTable/filter/fieldsType/CustomSelectByDependency"; +import useEdaratLists from "@/lib/hooks/useEdaratLists"; +import { usePermissions } from "@/lib/hooks/usePermissions"; +import LocationForm from "./RowActions/LocationForm"; +import ImageDialog from "./RowActions/ImageForm"; + +const statusOptions = [ + { value: "", label: "همه وضعیت ها" }, + { value: 0, label: "غیرفعال" }, + { value: 1, label: "فعال" }, +]; +const typeOptions = [ + { value: "", label: "همه نوع ها" }, + { value: 0, label: "فصلی" }, + { value: 1, label: "داعمی" }, + { value: 2, label: "موقت" }, +]; +const TollHouseList = () => { + const { data: userPermissions } = usePermissions(); + const hasProvincePermission = userPermissions.some((item) => ["add-tollhouse"].includes(item)); + + const columns = useMemo(() => { + return [ + { + accessorKey: "id", + header: "کد یکتا", // Unique Code + id: "id", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + + { + header: "اطلاعات راهدارخانه", + id: "tollHouseInfo", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + columns: [ + { + accessorKey: "name", + header: "نام راهدارخانه", + id: "name", + enableColumnFilter: true, + datatype: "text", + filterMode: "equals", + sortDescFirst: false, + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "province_id", + header: "استان", + id: "province_id", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 130, + ColumnSelectComponent: (props) => { + const { provinces, errorProvinces, loadingProvinces } = useProvinces(); + const getColumnSelectOptions = useMemo(() => { + if (loadingProvinces) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorProvinces) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: "کل کشور" }, + ...provinces.map((province) => ({ + value: province.id, + label: province.name_fa, + })), + ]; + }, [provinces, errorProvinces, loadingProvinces]); + return ( + + ); + }, + Cell: ({ row }) => <>{row.original.province_name}, + }, + { + accessorKey: "city_id", + header: "شهرستان", // Office + id: "city_id", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + dependencyId: "province_id", + grow: false, + size: 120, + ColumnSelectComponent: (props) => { + const { edaratList, loadingEdaratList, errorEdaratList } = useEdaratLists( + props.dependencyFieldValue.value + ); + const [prevDependency, setPrevDependency] = useState(props.dependencyFieldValue.value); + + const getColumnSelectOptions = useMemo(() => { + if (props.dependencyFieldValue.value === "") { + return [{ value: "empty", label: "ابتدا استان را انتخاب کنید" }]; + } + if (loadingEdaratList) { + return [{ value: "loading", label: "در حال بارگذاری..." }]; + } + if (errorEdaratList) { + return [{ value: "error", label: "خطا در بارگذاری" }]; + } + return [ + { value: "", label: "کل شهر ها" }, + ...edaratList.map((edare) => ({ + value: edare.id, + label: edare.name_fa, + })), + ]; + }, [edaratList, loadingEdaratList, errorEdaratList]); + useEffect(() => { + if (prevDependency === props.dependencyFieldValue?.value) return; + props.handleChange({ ...props.filterParameters, value: "" }); + setPrevDependency(props.dependencyFieldValue?.value); + }, [props.dependencyFieldValue?.value]); + return ( + + ); + }, + Cell: ({ row }) => <>{row.original.city_name}, + }, + { + accessorKey: "status", + header: "وضعیت", + id: "status", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 100, + columnSelectOption: () => { + return statusOptions.map((status) => ({ + value: status.value, + label: status.label, + })); + }, + Cell: ({ row }) => { + const status = statusOptions.find((option) => option.value == row.original.status); + return {status?.label || ""}; + }, + }, + { + accessorKey: "type", + header: "نوع", + id: "type", + enableColumnFilter: true, + datatype: "numeric", + filterMode: "equals", + grow: false, + size: 100, + columnSelectOption: () => { + return typeOptions.map((type) => ({ + value: type.value, + label: type.label, + })); + }, + Cell: ({ row }) => { + return {row.original.type_fa}; + }, + }, + { + accessorKey: "phone", + header: "تلفن راهدارخانه", + id: "phone", + enableColumnFilter: false, + enableSorting: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 120, + }, + { + accessorKey: "team_num", + header: "تعداد اکیپ", + id: "team_num", + enableColumnFilter: false, + enableSorting: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 120, + }, + { + accessorKey: "staff_num", + header: "تعداد پرسنل", + id: "staff_num", + enableColumnFilter: false, + enableSorting: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 120, + }, + { + accessorKey: "responsible_name", + header: "مسئول", + id: "responsible_name", + enableColumnFilter: false, + enableSorting: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 120, + }, + { + accessorKey: "responsible_mobile", + header: "شماره مسئول", + id: "responsible_mobile", + enableColumnFilter: false, + enableSorting: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 120, + }, + { + accessorKey: "successor_name", + header: "جانشین", + id: "successor_name", + enableColumnFilter: false, + enableSorting: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 120, + }, + { + accessorKey: "successor_mobile", + header: "شماره جانشین", + id: "successor_mobile", + enableColumnFilter: false, + enableSorting: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 120, + }, + ], + }, + { + header: "ماشین آلات", + id: "machines", + enableColumnFilter: false, + enableSorting: false, + datatype: "text", + grow: false, + size: 50, + columns: [ + { + accessorKey: "machines_light", + header: "ماشین آلات سبک", + id: "machines_light", + enableColumnFilter: false, + enableSorting: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "machines_sheavy", + header: "ماشین آلات نیمه سنگین", + id: "machines_sheavy", + enableColumnFilter: false, + enableSorting: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + accessorKey: "machines_heavy", + header: "ماشین آلات سنگین", + id: "machines_heavy", + enableColumnFilter: false, + enableSorting: true, + datatype: "text", + filterMode: "equals", + columnFilterModeOptions: ["equals", "contains"], + grow: false, + size: 100, + }, + { + header: "تصاویر", + id: "images", + enableColumnFilter: false, + enableSorting: false, + datatype: "array", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue, row }) => { + return ( + + + + ); + }, + }, + ], + }, + { + header: "موقعیت", // Location + id: "location", + enableColumnFilter: false, + enableSorting: false, + datatype: "array", + grow: false, + size: 100, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + py: 0, + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + Cell: ({ renderedCellValue, row }) => { + return ( + + + + ); + }, + }, + { + accessorFn: (row) => moment(row.created_at).locale("fa").format("HH:mm | yyyy/MM/DD"), + header: "تاریخ ثبت", + id: "created_at", + enableColumnFilter: true, + datatype: "date", + filterMode: "between", + grow: false, + size: 100, + }, + ]; + }, []); + + return ( + <> + + + + + ); +}; +export default TollHouseList; diff --git a/src/components/infrastructure/tollHouse/Toolbar.jsx b/src/components/infrastructure/tollHouse/Toolbar.jsx index d8ada27..20d24fc 100644 --- a/src/components/infrastructure/tollHouse/Toolbar.jsx +++ b/src/components/infrastructure/tollHouse/Toolbar.jsx @@ -1,10 +1,10 @@ -import { Box } from "@mui/material"; -import CreateTollHouse from "./Form/CreateTollHouse"; -import { usePermissions } from "@/lib/hooks/usePermissions"; - -const Toolbar = ({ table, filterData, mutate }) => { - const { data: userPermissions } = usePermissions(); - const hasAddPermission = userPermissions.some((item) => ["add-tollhouse", "add-tollhouse-province"].includes(item)); - return {hasAddPermission && }; -}; -export default Toolbar; +import { Box } from "@mui/material"; +import CreateTollHouse from "./Form/CreateTollHouse"; +import { usePermissions } from "@/lib/hooks/usePermissions"; + +const Toolbar = ({ table, filterData, mutate }) => { + const { data: userPermissions } = usePermissions(); + const hasAddPermission = userPermissions.some((item) => ["add-tollhouse", "add-tollhouse-province"].includes(item)); + return {hasAddPermission && }; +}; +export default Toolbar; diff --git a/src/components/infrastructure/tollHouse/index.jsx b/src/components/infrastructure/tollHouse/index.jsx index 9089a83..b85dc7c 100644 --- a/src/components/infrastructure/tollHouse/index.jsx +++ b/src/components/infrastructure/tollHouse/index.jsx @@ -1,14 +1,14 @@ -"use client"; -import PageTitle from "@/core/components/PageTitle"; -import { Stack } from "@mui/material"; -import TollHouseList from "./TollHouseList"; - -const TollHousePage = () => { - return ( - - - - - ); -}; -export default TollHousePage; +"use client"; +import PageTitle from "@/core/components/PageTitle"; +import { Stack } from "@mui/material"; +import TollHouseList from "./TollHouseList"; + +const TollHousePage = () => { + return ( + + + + + ); +}; +export default TollHousePage; diff --git a/src/components/layouts/dashboard/headerWithLogo/HaederBottom/index.jsx b/src/components/layouts/dashboard/headerWithLogo/HaederBottom/index.jsx index 1599d86..b0f8685 100644 --- a/src/components/layouts/dashboard/headerWithLogo/HaederBottom/index.jsx +++ b/src/components/layouts/dashboard/headerWithLogo/HaederBottom/index.jsx @@ -1,45 +1,45 @@ -"use client"; -import { Box, Stack, Typography } from "@mui/material"; -import Image from "next/image"; -import RmsLogo from "@/assets/images/rmsLogo.png"; -import HeaderLogo from "@/assets/images/headerLogo.png"; - -const HeaderBottom = () => { - return ( - theme.palette.primary2.main, - }} - spacing={2} - > - - - - theme.palette.primary2.contrastText }}> - سامانه جامع راهداری - - theme.palette.primary2.contrastText }}>rms.rmto.ir - - - - theme.palette.primary.main, - borderRadius: 2, - borderStyle: "dashed", - }} - > - - - - - ); -}; -export default HeaderBottom; +"use client"; +import { Box, Stack, Typography } from "@mui/material"; +import Image from "next/image"; +import RmsLogo from "@/assets/images/rmsLogo.png"; +import HeaderLogo from "@/assets/images/headerLogo.png"; + +const HeaderBottom = () => { + return ( + theme.palette.primary2.main, + }} + spacing={2} + > + + + + theme.palette.primary2.contrastText }}> + سامانه جامع راهداری + + theme.palette.primary2.contrastText }}>rms.rmto.ir + + + + theme.palette.primary.main, + borderRadius: 2, + borderStyle: "dashed", + }} + > + + + + + ); +}; +export default HeaderBottom; diff --git a/src/components/layouts/dashboard/headerWithLogo/index.jsx b/src/components/layouts/dashboard/headerWithLogo/index.jsx index af23434..acd5b63 100644 --- a/src/components/layouts/dashboard/headerWithLogo/index.jsx +++ b/src/components/layouts/dashboard/headerWithLogo/index.jsx @@ -1,11 +1,11 @@ -import { Stack } from "@mui/material"; -import HeaderBottom from "./HaederBottom"; - -const HeaderWithLogo = () => { - return ( - - - - ); -}; -export default HeaderWithLogo; +import { Stack } from "@mui/material"; +import HeaderBottom from "./HaederBottom"; + +const HeaderWithLogo = () => { + return ( + + + + ); +}; +export default HeaderWithLogo; diff --git a/src/components/layouts/dashboard/headerWithSidebar/HeaderMenu/index.jsx b/src/components/layouts/dashboard/headerWithSidebar/HeaderMenu/index.jsx index 92c9553..ce5edb9 100644 --- a/src/components/layouts/dashboard/headerWithSidebar/HeaderMenu/index.jsx +++ b/src/components/layouts/dashboard/headerWithSidebar/HeaderMenu/index.jsx @@ -1,45 +1,45 @@ -import { ExpandLess, ExpandMore, Link } from "@mui/icons-material"; -import { Button, Divider, ListItemIcon, ListItemText, Menu, MenuItem, Stack } from "@mui/material"; -import NextLink from "next/link"; -import { useState } from "react"; - -const HeaderMenu = ({ menu }) => { - const [anchorEl, setAnchorEl] = useState(null); - const open = Boolean(anchorEl); - - const handleClick = (event) => { - setAnchorEl(event.currentTarget); - }; - const handleClose = () => { - setAnchorEl(null); - }; - - return ( - - - - {menu.subMenu.flatMap((subMenu, index) => [ - ...subMenu.map((sub) => ( - - - - - {sub.title} - - )), - index < menu.subMenu.length - 1 && , - ])} - - - ); -}; - -export default HeaderMenu; +import { ExpandLess, ExpandMore, Link } from "@mui/icons-material"; +import { Button, Divider, ListItemIcon, ListItemText, Menu, MenuItem, Stack } from "@mui/material"; +import NextLink from "next/link"; +import { useState } from "react"; + +const HeaderMenu = ({ menu }) => { + const [anchorEl, setAnchorEl] = useState(null); + const open = Boolean(anchorEl); + + const handleClick = (event) => { + setAnchorEl(event.currentTarget); + }; + const handleClose = () => { + setAnchorEl(null); + }; + + return ( + + + + {menu.subMenu.flatMap((subMenu, index) => [ + ...subMenu.map((sub) => ( + + + + + {sub.title} + + )), + index < menu.subMenu.length - 1 && , + ])} + + + ); +}; + +export default HeaderMenu; diff --git a/src/components/layouts/dashboard/headerWithSidebar/Sidebar/SidebarBadge.jsx b/src/components/layouts/dashboard/headerWithSidebar/Sidebar/SidebarBadge.jsx index 5f0fa7a..2e94c13 100644 --- a/src/components/layouts/dashboard/headerWithSidebar/Sidebar/SidebarBadge.jsx +++ b/src/components/layouts/dashboard/headerWithSidebar/Sidebar/SidebarBadge.jsx @@ -1,19 +1,19 @@ -import { getValueByPath } from "@/core/utils/getValueByPath"; -import { useSidebarBadge } from "@/lib/hooks/useSidebarBadge"; -import { Chip } from "@mui/material"; -import { useEffect, useState } from "react"; - -const SidebarBadge = ({ badge, chipProps = {} }) => { - const { data } = useSidebarBadge(); - const [value, setValue] = useState(); - - useEffect(() => { - setValue(getValueByPath(data, badge)); - }, [data, badge]); - - if (!data) return null; - if (!value) return null; - - return ; -}; -export default SidebarBadge; +import { getValueByPath } from "@/core/utils/getValueByPath"; +import { useSidebarBadge } from "@/lib/hooks/useSidebarBadge"; +import { Chip } from "@mui/material"; +import { useEffect, useState } from "react"; + +const SidebarBadge = ({ badge, chipProps = {} }) => { + const { data } = useSidebarBadge(); + const [value, setValue] = useState(); + + useEffect(() => { + setValue(getValueByPath(data, badge)); + }, [data, badge]); + + if (!data) return null; + if (!value) return null; + + return ; +}; +export default SidebarBadge; diff --git a/src/components/layouts/dashboard/headerWithSidebar/Sidebar/SidebarListItems.jsx b/src/components/layouts/dashboard/headerWithSidebar/Sidebar/SidebarListItems.jsx index 092ac1c..b75f491 100644 --- a/src/components/layouts/dashboard/headerWithSidebar/Sidebar/SidebarListItems.jsx +++ b/src/components/layouts/dashboard/headerWithSidebar/Sidebar/SidebarListItems.jsx @@ -1,90 +1,90 @@ -import { ExpandLess, ExpandMore } from "@mui/icons-material"; -import { - Collapse, - List, - ListItem, - ListItemButton, - ListItemIcon, - ListItemText, - Stack, - useMediaQuery, - useTheme, -} from "@mui/material"; -import Link from "next/link"; -import SidebarBadge from "./SidebarBadge"; -import SidebarSubitems from "./SidebarSubitems"; - -const SidebarListItems = ({ menuItem, dispatch, handleDrawerClose }) => { - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("md")); - return ( - <> - - { - if (menuItem.type !== "page") { - dispatch({ type: "COLLAPSE_MENU", id: menuItem.id }); - } else { - if (isMobile) { - handleDrawerClose(); - } - } - }} - > - - {menuItem.icon} - - - {menuItem.badges && ( - - {menuItem.badges.map((badge, i) => ( - - ))} - - )} - {menuItem.hasSubitems ? menuItem.showSubitems ? : : null} - - - - {menuItem.hasSubitems ? ( - - {menuItem.Subitems.map((subitem, index) => { - return ( - - ); - })} - - ) : null} - - - ); -}; -export default SidebarListItems; +import { ExpandLess, ExpandMore } from "@mui/icons-material"; +import { + Collapse, + List, + ListItem, + ListItemButton, + ListItemIcon, + ListItemText, + Stack, + useMediaQuery, + useTheme, +} from "@mui/material"; +import Link from "next/link"; +import SidebarBadge from "./SidebarBadge"; +import SidebarSubitems from "./SidebarSubitems"; + +const SidebarListItems = ({ menuItem, dispatch, handleDrawerClose }) => { + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("md")); + return ( + <> + + { + if (menuItem.type !== "page") { + dispatch({ type: "COLLAPSE_MENU", id: menuItem.id }); + } else { + if (isMobile) { + handleDrawerClose(); + } + } + }} + > + + {menuItem.icon} + + + {menuItem.badges && ( + + {menuItem.badges.map((badge, i) => ( + + ))} + + )} + {menuItem.hasSubitems ? menuItem.showSubitems ? : : null} + + + + {menuItem.hasSubitems ? ( + + {menuItem.Subitems.map((subitem, index) => { + return ( + + ); + })} + + ) : null} + + + ); +}; +export default SidebarListItems; diff --git a/src/components/layouts/dashboard/headerWithSidebar/Sidebar/SidebarMenu.jsx b/src/components/layouts/dashboard/headerWithSidebar/Sidebar/SidebarMenu.jsx index f27005e..7c3f16b 100644 --- a/src/components/layouts/dashboard/headerWithSidebar/Sidebar/SidebarMenu.jsx +++ b/src/components/layouts/dashboard/headerWithSidebar/Sidebar/SidebarMenu.jsx @@ -1,122 +1,122 @@ -"use client"; -import { usePermissions } from "@/lib/hooks/usePermissions"; -import { List } from "@mui/material"; -import { usePathname } from "next/navigation"; -import { useEffect, useReducer, useState } from "react"; -import Profile from "@/core/components/Profile"; -import { filterMenuItems } from "@/core/utils/filterMenuItems"; -import { pageMenu } from "@/core/utils/pageMenu"; -import SidebarListItems from "./SidebarListItems"; -import { pageMenuDev } from "@/core/utils/pageMenuDev"; - -function selectPage(item, route) { - if (item.type === "page") { - return { - ...item, - selected: item.route === route, - showSubitems: item.route === route, - }; - } else if (item.Subitems && Array.isArray(item.Subitems)) { - const updatedSubitems = item.Subitems.map((subitem) => selectPage(subitem, route)); - return { - ...item, - Subitems: updatedSubitems, - showSubitems: updatedSubitems.some((subitem) => subitem.showSubitems || subitem.route === route), - }; - } - return item; -} - -function toggleSubitems(items, actionId) { - return items.map((item) => - actionId === item.id ? { ...item, showSubitems: !item.showSubitems } : { ...item, showSubitems: false } - ); -} - -function reducer(state, action) { - switch (action.type) { - case "UPDATE_MENU": - const _permissions = action.permissions || []; - return filterMenuItems(state, ["all", ..._permissions]); - - case "COLLAPSE_MENU": - return state.map((item) => ({ - ...item, - showSubitems: item.id === action.id ? !item.showSubitems : false, - })); - - case "COLLAPSE_SUB_ITEMS": - return state.map((item) => - item.hasSubitems ? { ...item, Subitems: toggleSubitems(item.Subitems, action.id) } : item - ); - - case "COLLAPSE_SUB_SECOND_ITEMS": - return state.map((item) => - item.hasSubitems - ? { - ...item, - Subitems: item.Subitems.map((subitem) => - subitem.hasSubitems - ? { - ...subitem, - Subitems: toggleSubitems(subitem.Subitems, action.id), - } - : subitem - ), - } - : item - ); - - case "SELECTED": - return state.map((item) => selectPage(item, action.route)); - - default: - throw new Error(); - } -} - -const SidebarMenu = ({ handleDrawerClose }) => { - const { data: userPermissions } = usePermissions(); - const [menuItems, dispatch] = useReducer(reducer, process.env.NODE_ENV == "production" ? pageMenu : pageMenuDev); - const pathname = usePathname(); - const [selectedKey, setSelectedKey] = useState(null); - - useEffect(() => { - dispatch({ type: "SELECTED", route: pathname }); - setSelectedKey(pathname); - }, [userPermissions, pathname]); - - useEffect(() => { - if (!userPermissions) return; - dispatch({ type: "UPDATE_MENU", permissions: userPermissions }); - }, [userPermissions]); - - useEffect(() => { - selectedKey && - document.querySelector(`[data-route="${selectedKey}"]`)?.scrollIntoView({ - behavior: "smooth", - block: "center", - }); - }, [selectedKey]); - - return ( - <> - - {userPermissions && ( - - {menuItems.map((menuItem) => { - return ( - - ); - })} - - )} - - ); -}; -export default SidebarMenu; +"use client"; +import { usePermissions } from "@/lib/hooks/usePermissions"; +import { List } from "@mui/material"; +import { usePathname } from "next/navigation"; +import { useEffect, useReducer, useState } from "react"; +import Profile from "@/core/components/Profile"; +import { filterMenuItems } from "@/core/utils/filterMenuItems"; +import { pageMenu } from "@/core/utils/pageMenu"; +import SidebarListItems from "./SidebarListItems"; +import { pageMenuDev } from "@/core/utils/pageMenuDev"; + +function selectPage(item, route) { + if (item.type === "page") { + return { + ...item, + selected: item.route === route, + showSubitems: item.route === route, + }; + } else if (item.Subitems && Array.isArray(item.Subitems)) { + const updatedSubitems = item.Subitems.map((subitem) => selectPage(subitem, route)); + return { + ...item, + Subitems: updatedSubitems, + showSubitems: updatedSubitems.some((subitem) => subitem.showSubitems || subitem.route === route), + }; + } + return item; +} + +function toggleSubitems(items, actionId) { + return items.map((item) => + actionId === item.id ? { ...item, showSubitems: !item.showSubitems } : { ...item, showSubitems: false } + ); +} + +function reducer(state, action) { + switch (action.type) { + case "UPDATE_MENU": + const _permissions = action.permissions || []; + return filterMenuItems(state, ["all", ..._permissions]); + + case "COLLAPSE_MENU": + return state.map((item) => ({ + ...item, + showSubitems: item.id === action.id ? !item.showSubitems : false, + })); + + case "COLLAPSE_SUB_ITEMS": + return state.map((item) => + item.hasSubitems ? { ...item, Subitems: toggleSubitems(item.Subitems, action.id) } : item + ); + + case "COLLAPSE_SUB_SECOND_ITEMS": + return state.map((item) => + item.hasSubitems + ? { + ...item, + Subitems: item.Subitems.map((subitem) => + subitem.hasSubitems + ? { + ...subitem, + Subitems: toggleSubitems(subitem.Subitems, action.id), + } + : subitem + ), + } + : item + ); + + case "SELECTED": + return state.map((item) => selectPage(item, action.route)); + + default: + throw new Error(); + } +} + +const SidebarMenu = ({ handleDrawerClose }) => { + const { data: userPermissions } = usePermissions(); + const [menuItems, dispatch] = useReducer(reducer, process.env.NODE_ENV == "production" ? pageMenu : pageMenuDev); + const pathname = usePathname(); + const [selectedKey, setSelectedKey] = useState(null); + + useEffect(() => { + dispatch({ type: "SELECTED", route: pathname }); + setSelectedKey(pathname); + }, [userPermissions, pathname]); + + useEffect(() => { + if (!userPermissions) return; + dispatch({ type: "UPDATE_MENU", permissions: userPermissions }); + }, [userPermissions]); + + useEffect(() => { + selectedKey && + document.querySelector(`[data-route="${selectedKey}"]`)?.scrollIntoView({ + behavior: "smooth", + block: "center", + }); + }, [selectedKey]); + + return ( + <> + + {userPermissions && ( + + {menuItems.map((menuItem) => { + return ( + + ); + })} + + )} + + ); +}; +export default SidebarMenu; diff --git a/src/components/layouts/dashboard/headerWithSidebar/Sidebar/SidebarSubitems.jsx b/src/components/layouts/dashboard/headerWithSidebar/Sidebar/SidebarSubitems.jsx index 0e5267c..d14e838 100644 --- a/src/components/layouts/dashboard/headerWithSidebar/Sidebar/SidebarSubitems.jsx +++ b/src/components/layouts/dashboard/headerWithSidebar/Sidebar/SidebarSubitems.jsx @@ -1,100 +1,100 @@ -import { ExpandLess, ExpandMore } from "@mui/icons-material"; -import { - Box, - Collapse, - List, - ListItem, - ListItemButton, - ListItemIcon, - ListItemText, - Stack, - useMediaQuery, - useTheme, -} from "@mui/material"; -import Link from "next/link"; -import SidebarBadge from "./SidebarBadge"; - -const SidebarSubitems = ({ subitem, dispatch, handleDrawerClose }) => { - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("md")); - return ( - <> - - { - if (subitem.type !== "page") { - dispatch({ type: "COLLAPSE_SUB_ITEMS", id: subitem.id }); - } else { - if (isMobile) { - handleDrawerClose(); - } - } - }} - > - - {subitem.icon} - - - {subitem.badges && ( - - {subitem.badges.map((badge, i) => ( - - ))} - - )} - {subitem.hasSubitems ? ( - subitem.showSubitems ? ( - - ) : ( - - ) - ) : ( - - )} - - - - {subitem.hasSubitems ? ( - - {subitem.Subitems.map((subSubitem, index) => { - return ( - - ); - })} - - ) : null} - - - ); -}; -export default SidebarSubitems; +import { ExpandLess, ExpandMore } from "@mui/icons-material"; +import { + Box, + Collapse, + List, + ListItem, + ListItemButton, + ListItemIcon, + ListItemText, + Stack, + useMediaQuery, + useTheme, +} from "@mui/material"; +import Link from "next/link"; +import SidebarBadge from "./SidebarBadge"; + +const SidebarSubitems = ({ subitem, dispatch, handleDrawerClose }) => { + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("md")); + return ( + <> + + { + if (subitem.type !== "page") { + dispatch({ type: "COLLAPSE_SUB_ITEMS", id: subitem.id }); + } else { + if (isMobile) { + handleDrawerClose(); + } + } + }} + > + + {subitem.icon} + + + {subitem.badges && ( + + {subitem.badges.map((badge, i) => ( + + ))} + + )} + {subitem.hasSubitems ? ( + subitem.showSubitems ? ( + + ) : ( + + ) + ) : ( + + )} + + + + {subitem.hasSubitems ? ( + + {subitem.Subitems.map((subSubitem, index) => { + return ( + + ); + })} + + ) : null} + + + ); +}; +export default SidebarSubitems; diff --git a/src/components/layouts/dashboard/headerWithSidebar/index.jsx b/src/components/layouts/dashboard/headerWithSidebar/index.jsx index 3ef1f41..d7d289f 100644 --- a/src/components/layouts/dashboard/headerWithSidebar/index.jsx +++ b/src/components/layouts/dashboard/headerWithSidebar/index.jsx @@ -1,155 +1,155 @@ -"use client"; -import ChevronRightIcon from "@mui/icons-material/ChevronRight"; -import MenuIcon from "@mui/icons-material/Menu"; -import { Box, Drawer, IconButton, Stack, styled, Toolbar, Typography, useMediaQuery, useTheme } from "@mui/material"; -import MuiAppBar from "@mui/material/AppBar"; -import { useState, useEffect } from "react"; -import HeaderMenu from "./HeaderMenu"; -import moment from "jalali-moment"; -import { headerMenu } from "@/core/utils/headerMenu"; -import SidebarMenu from "./Sidebar/SidebarMenu"; - -const drawerWidth = 300; -const headersHeight = 72; - -const Main = styled(Stack, { shouldForwardProp: (prop) => prop !== "open" })(({ theme, open }) => ({ - flexGrow: 1, - height: "100%", - transition: theme.transitions.create("margin", { - easing: theme.transitions.easing.sharp, - duration: theme.transitions.duration.leavingScreen, - }), - marginLeft: `-${drawerWidth}px`, - ...(open && { - transition: theme.transitions.create("margin", { - easing: theme.transitions.easing.easeOut, - duration: theme.transitions.duration.enteringScreen, - }), - marginLeft: 0, - }), -})); - -const AppBar = styled(MuiAppBar, { - shouldForwardProp: (prop) => prop !== "open", -})(({ theme, open }) => ({ - transition: theme.transitions.create(["margin", "width"], { - easing: theme.transitions.easing.sharp, - duration: theme.transitions.duration.leavingScreen, - }), - ...(open && { - width: `calc(100% - ${drawerWidth}px)`, - marginLeft: `${drawerWidth}px`, - transition: theme.transitions.create(["margin", "width"], { - easing: theme.transitions.easing.easeOut, - duration: theme.transitions.duration.enteringScreen, - }), - }), -})); - -const DrawerHeader = styled("div")(({ theme }) => ({ - display: "flex", - alignItems: "center", - padding: theme.spacing(0, 1), - ...theme.mixins.toolbar, - minHeight: "40px !important", - justifyContent: "flex-end", -})); - -const HeaderWithSidebar = ({ children }) => { - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("md")); // Detect mobile/tablet screen - const [open, setOpen] = useState(!isMobile); // Initial state based on screen size - - useEffect(() => { - setOpen(!isMobile); // Toggle state when screen size changes - }, [isMobile]); - - const now = moment().locale("fa").format("dddd YYYY/MM/DD"); - - const handleDrawerOpen = () => { - setOpen(true); - }; - const handleDrawerClose = () => { - setOpen(false); - }; - - return ( - - - - - - - - {headerMenu.map((menu) => ( - - ))} - - - - - - - تاریخ امروز: {now} - - - - - - - - v{process.env.NEXT_PUBLIC_VERSION} - - -
    - - - {children} - -
    -
    - ); -}; - -export default HeaderWithSidebar; +"use client"; +import ChevronRightIcon from "@mui/icons-material/ChevronRight"; +import MenuIcon from "@mui/icons-material/Menu"; +import { Box, Drawer, IconButton, Stack, styled, Toolbar, Typography, useMediaQuery, useTheme } from "@mui/material"; +import MuiAppBar from "@mui/material/AppBar"; +import { useState, useEffect } from "react"; +import HeaderMenu from "./HeaderMenu"; +import moment from "jalali-moment"; +import { headerMenu } from "@/core/utils/headerMenu"; +import SidebarMenu from "./Sidebar/SidebarMenu"; + +const drawerWidth = 300; +const headersHeight = 72; + +const Main = styled(Stack, { shouldForwardProp: (prop) => prop !== "open" })(({ theme, open }) => ({ + flexGrow: 1, + height: "100%", + transition: theme.transitions.create("margin", { + easing: theme.transitions.easing.sharp, + duration: theme.transitions.duration.leavingScreen, + }), + marginLeft: `-${drawerWidth}px`, + ...(open && { + transition: theme.transitions.create("margin", { + easing: theme.transitions.easing.easeOut, + duration: theme.transitions.duration.enteringScreen, + }), + marginLeft: 0, + }), +})); + +const AppBar = styled(MuiAppBar, { + shouldForwardProp: (prop) => prop !== "open", +})(({ theme, open }) => ({ + transition: theme.transitions.create(["margin", "width"], { + easing: theme.transitions.easing.sharp, + duration: theme.transitions.duration.leavingScreen, + }), + ...(open && { + width: `calc(100% - ${drawerWidth}px)`, + marginLeft: `${drawerWidth}px`, + transition: theme.transitions.create(["margin", "width"], { + easing: theme.transitions.easing.easeOut, + duration: theme.transitions.duration.enteringScreen, + }), + }), +})); + +const DrawerHeader = styled("div")(({ theme }) => ({ + display: "flex", + alignItems: "center", + padding: theme.spacing(0, 1), + ...theme.mixins.toolbar, + minHeight: "40px !important", + justifyContent: "flex-end", +})); + +const HeaderWithSidebar = ({ children }) => { + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("md")); // Detect mobile/tablet screen + const [open, setOpen] = useState(!isMobile); // Initial state based on screen size + + useEffect(() => { + setOpen(!isMobile); // Toggle state when screen size changes + }, [isMobile]); + + const now = moment().locale("fa").format("dddd YYYY/MM/DD"); + + const handleDrawerOpen = () => { + setOpen(true); + }; + const handleDrawerClose = () => { + setOpen(false); + }; + + return ( + + + + + + + + {headerMenu.map((menu) => ( + + ))} + + + + + + + تاریخ امروز: {now} + + + + + + + + v{process.env.NEXT_PUBLIC_VERSION} + + +
    + + + {children} + +
    +
    + ); +}; + +export default HeaderWithSidebar; diff --git a/src/core/components/ActivityCodeLog.jsx b/src/core/components/ActivityCodeLog.jsx index 762920b..6a04696 100644 --- a/src/core/components/ActivityCodeLog.jsx +++ b/src/core/components/ActivityCodeLog.jsx @@ -1,39 +1,39 @@ -"use client"; - -import { useEffect, useState, memo } from "react"; -import useRequest from "@/lib/hooks/useRequest"; -import { ACTIVITY_LOG } from "@/core/utils/routes"; -import NumberField from "@/core/components/NumberField"; - -const ActivityCodeLog = memo(({ activity_code }) => { - const requestServer = useRequest({ notificationShow: false }); - const [hasLogged, setHasLogged] = useState(false); - - useEffect(() => { - if (!activity_code || hasLogged) return; - - const controller = new AbortController(); - - const fetchActivityLog = async () => { - try { - await requestServer(ACTIVITY_LOG, "post", { - data: { activityCode: activity_code }, - signal: controller.signal, - }); - setHasLogged(true); - } catch (error) {} - }; - - fetchActivityLog(); - - return () => { - controller.abort(); - }; - }, [activity_code, hasLogged, requestServer]); - - return null; -}); -ActivityCodeLog.displayName = "ActivityCodeLog"; - -ActivityCodeLog.displayName = "ActivityCodeLog"; -export default ActivityCodeLog; +"use client"; + +import { useEffect, useState, memo } from "react"; +import useRequest from "@/lib/hooks/useRequest"; +import { ACTIVITY_LOG } from "@/core/utils/routes"; +import NumberField from "@/core/components/NumberField"; + +const ActivityCodeLog = memo(({ activity_code }) => { + const requestServer = useRequest({ notificationShow: false }); + const [hasLogged, setHasLogged] = useState(false); + + useEffect(() => { + if (!activity_code || hasLogged) return; + + const controller = new AbortController(); + + const fetchActivityLog = async () => { + try { + await requestServer(ACTIVITY_LOG, "post", { + data: { activityCode: activity_code }, + signal: controller.signal, + }); + setHasLogged(true); + } catch (error) {} + }; + + fetchActivityLog(); + + return () => { + controller.abort(); + }; + }, [activity_code, hasLogged, requestServer]); + + return null; +}); +ActivityCodeLog.displayName = "ActivityCodeLog"; + +ActivityCodeLog.displayName = "ActivityCodeLog"; +export default ActivityCodeLog; diff --git a/src/core/components/ApplicantRequestDetail/DetailItem.jsx b/src/core/components/ApplicantRequestDetail/DetailItem.jsx index 099e955..34aac21 100644 --- a/src/core/components/ApplicantRequestDetail/DetailItem.jsx +++ b/src/core/components/ApplicantRequestDetail/DetailItem.jsx @@ -1,52 +1,52 @@ -"use client"; - -import { Box, Chip, Divider, Grid, Typography } from "@mui/material"; -import QrCode2Icon from "@mui/icons-material/QrCode2"; -import HomeWorkIcon from "@mui/icons-material/HomeWork"; -import DomainIcon from "@mui/icons-material/Domain"; -import CottageIcon from "@mui/icons-material/Cottage"; -import AccountTreeIcon from "@mui/icons-material/AccountTree"; -import HolidayVillageIcon from "@mui/icons-material/HolidayVillage"; -import CalendarMonthIcon from "@mui/icons-material/CalendarMonth"; -import FaxIcon from "@mui/icons-material/Fax"; -import FullscreenIcon from "@mui/icons-material/Fullscreen"; -import ArchitectureIcon from "@mui/icons-material/Architecture"; -import Diversity2Icon from "@mui/icons-material/Diversity2"; -import SubtitlesIcon from "@mui/icons-material/Subtitles"; -import FingerprintIcon from "@mui/icons-material/Fingerprint"; - -const findItem = { - id: { title: "کد یکتا", icon: }, - shomareh_darkhast: { title: "شماره درخواست", icon: }, - ostan: { title: "استان", icon: }, - shahr: { title: "شهر", icon: }, - shahrestan: { title: "شهرستان", icon: }, - bakhsh: { title: "بخش", icon: }, - roosta: { title: "روستا", icon: }, - tarikh_darkhast: { title: "تاریخ درخواست", icon: }, - sazman: { title: "سازمان", icon: }, - masahat_zamin: { title: "مساحت زمین", icon: }, - masahat_tarh: { title: "مساحت طرح", icon: }, - gorooh_tarh: { title: "گروه طرح", icon: }, - onvane_tarh: { title: "عنوان طرح", icon: }, -}; - -const DetailItem = ({ item }) => { - const currentItem = findItem[item.key]; - if (!currentItem) return null; - - return ( - - - - - {item.value} - - - ); -}; -export default DetailItem; +"use client"; + +import { Box, Chip, Divider, Grid, Typography } from "@mui/material"; +import QrCode2Icon from "@mui/icons-material/QrCode2"; +import HomeWorkIcon from "@mui/icons-material/HomeWork"; +import DomainIcon from "@mui/icons-material/Domain"; +import CottageIcon from "@mui/icons-material/Cottage"; +import AccountTreeIcon from "@mui/icons-material/AccountTree"; +import HolidayVillageIcon from "@mui/icons-material/HolidayVillage"; +import CalendarMonthIcon from "@mui/icons-material/CalendarMonth"; +import FaxIcon from "@mui/icons-material/Fax"; +import FullscreenIcon from "@mui/icons-material/Fullscreen"; +import ArchitectureIcon from "@mui/icons-material/Architecture"; +import Diversity2Icon from "@mui/icons-material/Diversity2"; +import SubtitlesIcon from "@mui/icons-material/Subtitles"; +import FingerprintIcon from "@mui/icons-material/Fingerprint"; + +const findItem = { + id: { title: "کد یکتا", icon: }, + shomareh_darkhast: { title: "شماره درخواست", icon: }, + ostan: { title: "استان", icon: }, + shahr: { title: "شهر", icon: }, + shahrestan: { title: "شهرستان", icon: }, + bakhsh: { title: "بخش", icon: }, + roosta: { title: "روستا", icon: }, + tarikh_darkhast: { title: "تاریخ درخواست", icon: }, + sazman: { title: "سازمان", icon: }, + masahat_zamin: { title: "مساحت زمین", icon: }, + masahat_tarh: { title: "مساحت طرح", icon: }, + gorooh_tarh: { title: "گروه طرح", icon: }, + onvane_tarh: { title: "عنوان طرح", icon: }, +}; + +const DetailItem = ({ item }) => { + const currentItem = findItem[item.key]; + if (!currentItem) return null; + + return ( + + + + + {item.value} + + + ); +}; +export default DetailItem; diff --git a/src/core/components/ApplicantRequestDetail/DetailMap.jsx b/src/core/components/ApplicantRequestDetail/DetailMap.jsx index 902ec3a..9021505 100644 --- a/src/core/components/ApplicantRequestDetail/DetailMap.jsx +++ b/src/core/components/ApplicantRequestDetail/DetailMap.jsx @@ -1,39 +1,39 @@ -"use client"; - -import { Box } from "@mui/material"; -import dynamic from "next/dynamic"; -import MapLoading from "@/core/components/MapLayer/Loading"; -import FlyToPolyGon from "./FlyToPolygon"; - -const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { - loading: () => , - ssr: false, -}); - -const DetailMap = ({ data }) => { - return ( - - - - - - - - ); -}; -export default DetailMap; +"use client"; + +import { Box } from "@mui/material"; +import dynamic from "next/dynamic"; +import MapLoading from "@/core/components/MapLayer/Loading"; +import FlyToPolyGon from "./FlyToPolygon"; + +const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { + loading: () => , + ssr: false, +}); + +const DetailMap = ({ data }) => { + return ( + + + + + + + + ); +}; +export default DetailMap; diff --git a/src/core/components/ApplicantRequestDetail/FlyToPolygon.jsx b/src/core/components/ApplicantRequestDetail/FlyToPolygon.jsx index 4a39edd..13cb92f 100644 --- a/src/core/components/ApplicantRequestDetail/FlyToPolygon.jsx +++ b/src/core/components/ApplicantRequestDetail/FlyToPolygon.jsx @@ -1,22 +1,22 @@ -"use client"; - -import { Polygon, useMap } from "react-leaflet"; -import { useEffect } from "react"; - -const purpleOptions = { color: "purple" }; - -const FlyToPolygon = ({ polygon }) => { - const map = useMap(); - - useEffect(() => { - if (map) { - const leafletPolygon = L.polygon(polygon); - const bounds = leafletPolygon.getBounds(); - map.flyToBounds(bounds, { padding: [50, 50] }); - } - }, [map, polygon]); - - return ; -}; - -export default FlyToPolygon; +"use client"; + +import { Polygon, useMap } from "react-leaflet"; +import { useEffect } from "react"; + +const purpleOptions = { color: "purple" }; + +const FlyToPolygon = ({ polygon }) => { + const map = useMap(); + + useEffect(() => { + if (map) { + const leafletPolygon = L.polygon(polygon); + const bounds = leafletPolygon.getBounds(); + map.flyToBounds(bounds, { padding: [50, 50] }); + } + }, [map, polygon]); + + return ; +}; + +export default FlyToPolygon; diff --git a/src/core/components/ApplicantRequestDetail/FlyToPolyline.jsx b/src/core/components/ApplicantRequestDetail/FlyToPolyline.jsx index c26ddd6..0c11336 100644 --- a/src/core/components/ApplicantRequestDetail/FlyToPolyline.jsx +++ b/src/core/components/ApplicantRequestDetail/FlyToPolyline.jsx @@ -1,21 +1,21 @@ -"use client"; - -import { Polyline, useMap } from "react-leaflet"; -import { useEffect } from "react"; -const purpleOptions = { color: "purple" }; - -const FlyToPolyline = ({ polyline }) => { - const map = useMap(); - - useEffect(() => { - if (map) { - const leafletPolyline = L.polyline(polyline); // Create a Leaflet polyline - const bounds = leafletPolyline.getBounds(); // Get bounds from the polyline - map.flyToBounds(bounds, { padding: [50, 50] }); // Fly to the polyline bounds - } - }, [map, polyline]); - - return ; // Render the polyline -}; - -export default FlyToPolyline; +"use client"; + +import { Polyline, useMap } from "react-leaflet"; +import { useEffect } from "react"; +const purpleOptions = { color: "purple" }; + +const FlyToPolyline = ({ polyline }) => { + const map = useMap(); + + useEffect(() => { + if (map) { + const leafletPolyline = L.polyline(polyline); // Create a Leaflet polyline + const bounds = leafletPolyline.getBounds(); // Get bounds from the polyline + map.flyToBounds(bounds, { padding: [50, 50] }); // Fly to the polyline bounds + } + }, [map, polyline]); + + return ; // Render the polyline +}; + +export default FlyToPolyline; diff --git a/src/core/components/ApplicantRequestDetail/index.jsx b/src/core/components/ApplicantRequestDetail/index.jsx index bfdbf35..669a852 100644 --- a/src/core/components/ApplicantRequestDetail/index.jsx +++ b/src/core/components/ApplicantRequestDetail/index.jsx @@ -1,57 +1,57 @@ -"use client"; - -import { Box, Button, Chip, Divider, Grid, Typography } from "@mui/material"; -import AttachFileIcon from "@mui/icons-material/AttachFile"; -import DownloadingIcon from "@mui/icons-material/Downloading"; -import DetailItem from "./DetailItem"; -import DetailMap from "./DetailMap"; -import ContactMailIcon from "@mui/icons-material/ContactMail"; - -const ApplicantRequestDetail = ({ data }) => { - return ( - <> - - - - - {Object.entries(data).map(([key, value]) => ( - - ))} - - - } - sx={{ fontSize: "12px", fontWeight: 500, pl: "5px" }} - label="فایل مصوب" - /> - - - - - - - - - } - label="آدرس" - /> - - - {data.address} - - - - - - ); -}; -export default ApplicantRequestDetail; +"use client"; + +import { Box, Button, Chip, Divider, Grid, Typography } from "@mui/material"; +import AttachFileIcon from "@mui/icons-material/AttachFile"; +import DownloadingIcon from "@mui/icons-material/Downloading"; +import DetailItem from "./DetailItem"; +import DetailMap from "./DetailMap"; +import ContactMailIcon from "@mui/icons-material/ContactMail"; + +const ApplicantRequestDetail = ({ data }) => { + return ( + <> + + + + + {Object.entries(data).map(([key, value]) => ( + + ))} + + + } + sx={{ fontSize: "12px", fontWeight: 500, pl: "5px" }} + label="فایل مصوب" + /> + + + + + + + + + } + label="آدرس" + /> + + + {data.address} + + + + + + ); +}; +export default ApplicantRequestDetail; diff --git a/src/core/components/BlinkingCell.jsx b/src/core/components/BlinkingCell.jsx index 3b1eed2..e912bfe 100644 --- a/src/core/components/BlinkingCell.jsx +++ b/src/core/components/BlinkingCell.jsx @@ -1,12 +1,12 @@ -import { Box, Stack } from "@mui/material"; -import BlinkingCircle from "./BlinkingCircle"; - -const BlinkingCell = ({ visible = false, value }) => { - return ( - - {value} - {visible && } - - ); -}; -export default BlinkingCell; +import { Box, Stack } from "@mui/material"; +import BlinkingCircle from "./BlinkingCircle"; + +const BlinkingCell = ({ visible = false, value }) => { + return ( + + {value} + {visible && } + + ); +}; +export default BlinkingCell; diff --git a/src/core/components/BlinkingCircle.jsx b/src/core/components/BlinkingCircle.jsx index 0d377e1..209e7f4 100644 --- a/src/core/components/BlinkingCircle.jsx +++ b/src/core/components/BlinkingCircle.jsx @@ -1,24 +1,24 @@ -import { keyframes } from "@emotion/react"; -import { Box } from "@mui/material"; - -const blink = keyframes` - 0% { opacity: 1; } - 50% { opacity: 0.3; } - 100% { opacity: 1; } -`; - -const BlinkingCircle = () => { - return ( - theme.palette.warning.main, - animation: `${blink} 1.3s infinite ease-in-out`, - }} - /> - ); -}; - -export default BlinkingCircle; +import { keyframes } from "@emotion/react"; +import { Box } from "@mui/material"; + +const blink = keyframes` + 0% { opacity: 1; } + 50% { opacity: 0.3; } + 100% { opacity: 1; } +`; + +const BlinkingCircle = () => { + return ( + theme.palette.warning.main, + animation: `${blink} 1.3s infinite ease-in-out`, + }} + /> + ); +}; + +export default BlinkingCircle; diff --git a/src/core/components/CarCode.jsx b/src/core/components/CarCode.jsx index ec23995..935ab94 100644 --- a/src/core/components/CarCode.jsx +++ b/src/core/components/CarCode.jsx @@ -1,103 +1,103 @@ -import { Autocomplete, CircularProgress, TextField } from "@mui/material"; -import { useEffect, useState } from "react"; -import useRequest from "@/lib/hooks/useRequest"; -import { debounce } from "@mui/material/utils"; -import { GET_CAR_LIST_SEARCH } from "@/core/utils/routes"; - -const CarCode = ({ carCode, setCarCode, inputValueDefault = "", error, multiple = false }) => { - const [inputValue, setInputValue] = useState(inputValueDefault); - const [options, setOptions] = useState([]); - const [loading, setLoading] = useState(false); - const requestServer = useRequest(); - - useEffect(() => { - const fetchCarCodes = (inputValue, controller) => { - const debouncer = debounce((query) => { - if (!query || query?.length < 3) { - setOptions([]); - return; - } - setLoading(true); - requestServer(`${GET_CAR_LIST_SEARCH}?machine_code=${query}`, "get", { - requestOptions: { signal: controller.signal }, - }) - .then((response) => { - const combinedArray = carCode ? [...carCode, ...response.data.data] : [...response.data.data]; - const uniqueArray = Array.from(new Map(combinedArray.map((item) => [item.id, item])).values()); - setOptions(uniqueArray || []); - }) - .catch(() => { - setOptions([]); - }) - .finally(() => { - setLoading(false); - }); - }, 500); - debouncer(inputValue); - }; - - const controller = new AbortController(); - fetchCarCodes(inputValue, controller); - return () => controller.abort(); - }, [inputValue]); - - return ( - { - setCarCode(multiple ? newValue || [] : newValue || null); - }} - inputValue={inputValue} - onInputChange={(event, newInputValue) => { - setInputValue(newInputValue || ""); - }} - options={options} - getOptionLabel={(option) => { - if (typeof option === "string") return option; - const { machine_code, car_name, plak_number } = option; - let label = `${machine_code || ""}`; - if (car_name) { - label += ` | ${car_name}`; - } - if (plak_number) { - label += ` | ${plak_number}`; - } - return label; - }} - isOptionEqualToValue={(option, value) => { - if (!value) return false; - if (value === "") return option.machine_code === ""; - return option.machine_code === (value?.machine_code || value); - }} - loading={loading} - loadingText="درحال جستجوی کد خودرو" - noOptionsText={inputValue?.length < 3 ? "حداقل سه رقم از کد خودرو را وارد کنید" : "کد خودرویی یافت نشد"} - fullWidth - renderInput={(params) => ( - - {loading ? : null} - {params.InputProps.endAdornment} - - ), - }} - /> - )} - /> - ); -}; -export default CarCode; +import { Autocomplete, CircularProgress, TextField } from "@mui/material"; +import { useEffect, useState } from "react"; +import useRequest from "@/lib/hooks/useRequest"; +import { debounce } from "@mui/material/utils"; +import { GET_CAR_LIST_SEARCH } from "@/core/utils/routes"; + +const CarCode = ({ carCode, setCarCode, inputValueDefault = "", error, multiple = false }) => { + const [inputValue, setInputValue] = useState(inputValueDefault); + const [options, setOptions] = useState([]); + const [loading, setLoading] = useState(false); + const requestServer = useRequest(); + + useEffect(() => { + const fetchCarCodes = (inputValue, controller) => { + const debouncer = debounce((query) => { + if (!query || query?.length < 3) { + setOptions([]); + return; + } + setLoading(true); + requestServer(`${GET_CAR_LIST_SEARCH}?machine_code=${query}`, "get", { + requestOptions: { signal: controller.signal }, + }) + .then((response) => { + const combinedArray = carCode ? [...carCode, ...response.data.data] : [...response.data.data]; + const uniqueArray = Array.from(new Map(combinedArray.map((item) => [item.id, item])).values()); + setOptions(uniqueArray || []); + }) + .catch(() => { + setOptions([]); + }) + .finally(() => { + setLoading(false); + }); + }, 500); + debouncer(inputValue); + }; + + const controller = new AbortController(); + fetchCarCodes(inputValue, controller); + return () => controller.abort(); + }, [inputValue]); + + return ( + { + setCarCode(multiple ? newValue || [] : newValue || null); + }} + inputValue={inputValue} + onInputChange={(event, newInputValue) => { + setInputValue(newInputValue || ""); + }} + options={options} + getOptionLabel={(option) => { + if (typeof option === "string") return option; + const { machine_code, car_name, plak_number } = option; + let label = `${machine_code || ""}`; + if (car_name) { + label += ` | ${car_name}`; + } + if (plak_number) { + label += ` | ${plak_number}`; + } + return label; + }} + isOptionEqualToValue={(option, value) => { + if (!value) return false; + if (value === "") return option.machine_code === ""; + return option.machine_code === (value?.machine_code || value); + }} + loading={loading} + loadingText="درحال جستجوی کد خودرو" + noOptionsText={inputValue?.length < 3 ? "حداقل سه رقم از کد خودرو را وارد کنید" : "کد خودرویی یافت نشد"} + fullWidth + renderInput={(params) => ( + + {loading ? : null} + {params.InputProps.endAdornment} + + ), + }} + /> + )} + /> + ); +}; +export default CarCode; diff --git a/src/core/components/CustomDatePicker.jsx b/src/core/components/CustomDatePicker.jsx index eb68fa7..6319667 100644 --- a/src/core/components/CustomDatePicker.jsx +++ b/src/core/components/CustomDatePicker.jsx @@ -1,53 +1,53 @@ -import React from "react"; -import { AdapterDateFnsJalali } from "@mui/x-date-pickers/AdapterDateFnsJalali"; -import { faIR } from "@mui/x-date-pickers/locales"; -import { LocalizationProvider, MobileDatePicker } from "@mui/x-date-pickers"; -import { IconButton, InputAdornment } from "@mui/material"; -import ClearIcon from "@mui/icons-material/Clear"; - -const CustomDatePicker = ({ dateValue, setDateValue, placeholder = "انتخاب تاریخ", size = "small" }) => { - const handleDateChange = (newValue) => { - setDateValue(newValue); - }; - - return ( - - - { - event.stopPropagation(); - setDateValue(null); - }} - sx={{ - color: "#bfbfbf", - "&:hover": { - backgroundColor: "rgba(189, 189, 189, 0.1)", - color: "#363434", - }, - }} - > - - - - ), - }, - }, - }} - > - - ); -}; -export default CustomDatePicker; +import React from "react"; +import { AdapterDateFnsJalali } from "@mui/x-date-pickers/AdapterDateFnsJalali"; +import { faIR } from "@mui/x-date-pickers/locales"; +import { LocalizationProvider, MobileDatePicker } from "@mui/x-date-pickers"; +import { IconButton, InputAdornment } from "@mui/material"; +import ClearIcon from "@mui/icons-material/Clear"; + +const CustomDatePicker = ({ dateValue, setDateValue, placeholder = "انتخاب تاریخ", size = "small" }) => { + const handleDateChange = (newValue) => { + setDateValue(newValue); + }; + + return ( + + + { + event.stopPropagation(); + setDateValue(null); + }} + sx={{ + color: "#bfbfbf", + "&:hover": { + backgroundColor: "rgba(189, 189, 189, 0.1)", + color: "#363434", + }, + }} + > + + + + ), + }, + }, + }} + > + + ); +}; +export default CustomDatePicker; diff --git a/src/core/components/DataTable/Main.js b/src/core/components/DataTable/Main.js index ef2d81a..ce23c14 100644 --- a/src/core/components/DataTable/Main.js +++ b/src/core/components/DataTable/Main.js @@ -1,179 +1,179 @@ -import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; -import { flattenArrayOfObjects } from "@/core/utils/flattenArrayOfObjects"; -import { flattenObjectOfObjects } from "@/core/utils/flattenObjectOfObjects"; -import isArrayEmpty from "@/core/utils/isArrayEmpty"; -import useDataTable from "@/lib/hooks/useDataTable"; -import useRequest from "@/lib/hooks/useRequest"; -import { useMaterialReactTable } from "material-react-table"; -import { useCallback, useEffect, useReducer, useState } from "react"; -import useSWR from "swr"; -import { FA_DATATABLE_LOCALIZATION } from "./localization/fa/datatable"; -import DataTable_Paper from "./table/Paper"; - -const rowSelectionReducer = (state, action) => { - switch (action.type) { - case "TOGGLE_ROW": - return { [action.payload]: true }; - case "RESET": - return {}; - default: - return state; - } -}; - -const DataTable_Main = (props) => { - const request = useRequest(); - const [rowSelection, dispatchRowSelection] = useReducer(rowSelectionReducer, {}); - const { filterData, sortData, setSortData, hideData } = useDataTable(); - const { - need_filter, - table_url, - user_id, - page_name, - table_name, - columns, - initialStateProps, - TableToolbar, - table_title, - RowActions, - specific_data, - specialFilter, - } = props; - const flatColumns = flattenArrayOfObjects(columns, "columns"); - const [pagination, setPagination] = useState({ pageIndex: 0, pageSize: 10 }); - const [totalRowCount, setTotalRowCount] = useState(0); - const flattenHideData = flattenObjectOfObjects(hideData); - const onSortingChange = (event) => { - setSortData(event); - }; - - const fetchUrl = useCallback(() => { - const params = new URLSearchParams(); - params.set("start", `${pagination.pageIndex * pagination.pageSize}`); - params.set("size", pagination.pageSize); - if (specialFilter) { - const filteredSpecialFilterData = Object.values(specialFilter).filter( - (filter) => !isArrayEmpty(filter.value) - ); - params.set("filters", JSON.stringify(filteredSpecialFilterData || [])); - } else { - const filteredFilterData = DataTableFilterDataStructure(filterData, isArrayEmpty); - params.set("filters", JSON.stringify(filteredFilterData.length === 0 ? [] : filteredFilterData)); - } - params.set( - "sorting", - JSON.stringify( - Object.values(sortData).map(({ id, ...rest }) => ({ - ...rest, - id: id.replace(/__/g, "."), - })) - ) - ); - return `${table_url}?${params}`; - }, [table_url, filterData, pagination, sortData, specialFilter]); - - const fetcher = async (url) => { - try { - const response = await request(url); - setTotalRowCount(response.data?.meta?.totalRowCount); - if (specific_data) { - return specific_data(response.data); - } else { - return response.data?.data; - } - } catch (error) { - throw error; - } - }; - - const { data, isValidating, mutate } = useSWR(props.data ? "" : fetchUrl(), fetcher, { - revalidateIfStale: true, - revalidateOnFocus: false, - revalidateOnReconnect: true, - keepPreviousData: true, - }); - - useEffect(() => { - if (!isValidating) return; - dispatchRowSelection({ type: "RESET" }); - }, [isValidating]); - - const table = useMaterialReactTable({ - localization: FA_DATATABLE_LOCALIZATION, - columns, - data: data ?? [], - muiTableBodyRowProps: ({ row }) => ({ - onClick: () => dispatchRowSelection({ type: "TOGGLE_ROW", payload: row.id }), - selected: !!rowSelection[row.id], - }), - initialState: { - density: "compact", - columnVisibility: flattenHideData, - sorting: sortData, - ...initialStateProps, - }, - state: { - showProgressBars: isValidating || props.loading, - columnVisibility: flattenHideData, - sorting: sortData, - pagination, - rowSelection, - }, - muiTableHeadProps: { - sx: { - borderTop: "1px solid #e1e1e1", - borderBottom: "2px solid #e1e1e1", - }, - }, - muiTableHeadCellProps: { - sx: { - color: "primary.main", - borderLeft: "1px solid #e1e1e1", - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - muiTableBodyCellProps: { - sx: { - borderLeft: "1px solid #e1e1e1", - "&:first-of-type": { - borderLeft: "unset", - }, - }, - }, - manualFiltering: true, - manualPagination: true, - manualSorting: true, - onPaginationChange: setPagination, - onSortingChange: onSortingChange, - rowCount: totalRowCount, - renderTopToolbarCustomActions: ({ table }) => ( - <> - {TableToolbar && ( - - )} - - ), - renderRowActions: ({ row }) => , - ...props, - }); - - return ( - - ); -}; -export default DataTable_Main; +import DataTableFilterDataStructure from "@/core/utils/DataTableFilterDataStructure"; +import { flattenArrayOfObjects } from "@/core/utils/flattenArrayOfObjects"; +import { flattenObjectOfObjects } from "@/core/utils/flattenObjectOfObjects"; +import isArrayEmpty from "@/core/utils/isArrayEmpty"; +import useDataTable from "@/lib/hooks/useDataTable"; +import useRequest from "@/lib/hooks/useRequest"; +import { useMaterialReactTable } from "material-react-table"; +import { useCallback, useEffect, useReducer, useState } from "react"; +import useSWR from "swr"; +import { FA_DATATABLE_LOCALIZATION } from "./localization/fa/datatable"; +import DataTable_Paper from "./table/Paper"; + +const rowSelectionReducer = (state, action) => { + switch (action.type) { + case "TOGGLE_ROW": + return { [action.payload]: true }; + case "RESET": + return {}; + default: + return state; + } +}; + +const DataTable_Main = (props) => { + const request = useRequest(); + const [rowSelection, dispatchRowSelection] = useReducer(rowSelectionReducer, {}); + const { filterData, sortData, setSortData, hideData } = useDataTable(); + const { + need_filter, + table_url, + user_id, + page_name, + table_name, + columns, + initialStateProps, + TableToolbar, + table_title, + RowActions, + specific_data, + specialFilter, + } = props; + const flatColumns = flattenArrayOfObjects(columns, "columns"); + const [pagination, setPagination] = useState({ pageIndex: 0, pageSize: 10 }); + const [totalRowCount, setTotalRowCount] = useState(0); + const flattenHideData = flattenObjectOfObjects(hideData); + const onSortingChange = (event) => { + setSortData(event); + }; + + const fetchUrl = useCallback(() => { + const params = new URLSearchParams(); + params.set("start", `${pagination.pageIndex * pagination.pageSize}`); + params.set("size", pagination.pageSize); + if (specialFilter) { + const filteredSpecialFilterData = Object.values(specialFilter).filter( + (filter) => !isArrayEmpty(filter.value) + ); + params.set("filters", JSON.stringify(filteredSpecialFilterData || [])); + } else { + const filteredFilterData = DataTableFilterDataStructure(filterData, isArrayEmpty); + params.set("filters", JSON.stringify(filteredFilterData.length === 0 ? [] : filteredFilterData)); + } + params.set( + "sorting", + JSON.stringify( + Object.values(sortData).map(({ id, ...rest }) => ({ + ...rest, + id: id.replace(/__/g, "."), + })) + ) + ); + return `${table_url}?${params}`; + }, [table_url, filterData, pagination, sortData, specialFilter]); + + const fetcher = async (url) => { + try { + const response = await request(url); + setTotalRowCount(response.data?.meta?.totalRowCount); + if (specific_data) { + return specific_data(response.data); + } else { + return response.data?.data; + } + } catch (error) { + throw error; + } + }; + + const { data, isValidating, mutate } = useSWR(props.data ? "" : fetchUrl(), fetcher, { + revalidateIfStale: true, + revalidateOnFocus: false, + revalidateOnReconnect: true, + keepPreviousData: true, + }); + + useEffect(() => { + if (!isValidating) return; + dispatchRowSelection({ type: "RESET" }); + }, [isValidating]); + + const table = useMaterialReactTable({ + localization: FA_DATATABLE_LOCALIZATION, + columns, + data: data ?? [], + muiTableBodyRowProps: ({ row }) => ({ + onClick: () => dispatchRowSelection({ type: "TOGGLE_ROW", payload: row.id }), + selected: !!rowSelection[row.id], + }), + initialState: { + density: "compact", + columnVisibility: flattenHideData, + sorting: sortData, + ...initialStateProps, + }, + state: { + showProgressBars: isValidating || props.loading, + columnVisibility: flattenHideData, + sorting: sortData, + pagination, + rowSelection, + }, + muiTableHeadProps: { + sx: { + borderTop: "1px solid #e1e1e1", + borderBottom: "2px solid #e1e1e1", + }, + }, + muiTableHeadCellProps: { + sx: { + color: "primary.main", + borderLeft: "1px solid #e1e1e1", + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + muiTableBodyCellProps: { + sx: { + borderLeft: "1px solid #e1e1e1", + "&:first-of-type": { + borderLeft: "unset", + }, + }, + }, + manualFiltering: true, + manualPagination: true, + manualSorting: true, + onPaginationChange: setPagination, + onSortingChange: onSortingChange, + rowCount: totalRowCount, + renderTopToolbarCustomActions: ({ table }) => ( + <> + {TableToolbar && ( + + )} + + ), + renderRowActions: ({ row }) => , + ...props, + }); + + return ( + + ); +}; +export default DataTable_Main; diff --git a/src/core/components/DataTable/body/TableBody.js b/src/core/components/DataTable/body/TableBody.js index b0750be..f0eaf0e 100644 --- a/src/core/components/DataTable/body/TableBody.js +++ b/src/core/components/DataTable/body/TableBody.js @@ -1,191 +1,191 @@ -import { parseFromValuesOrFunc } from "@/core/utils/utils"; -import { TableBody, Typography } from "@mui/material"; -import { useMRT_RowVirtualizer, useMRT_Rows } from "material-react-table"; -import { memo, useMemo } from "react"; -import DataTable_TableBodyRow, { Memo_DataTable_TableBodyRow } from "./TableBodyRow"; - -const DataTable_TableBody = ({ columnVirtualizer, table, ...rest }) => { - const { - getBottomRows, - getIsSomeRowsPinned, - getRowModel, - getState, - getTopRows, - options: { - enableStickyFooter, - enableStickyHeader, - layoutMode, - localization, - memoMode, - muiTableBodyProps, - renderDetailPanel, - renderEmptyRowsFallback, - rowPinningDisplayMode, - }, - refs: { tableFooterRef, tableHeadRef, tablePaperRef }, - } = table; - const { columnFilters, globalFilter, isFullScreen, rowPinning } = getState(); - - const tableBodyProps = { - ...parseFromValuesOrFunc(muiTableBodyProps, { table }), - ...rest, - }; - - const tableHeadHeight = ((enableStickyHeader || isFullScreen) && tableHeadRef.current?.clientHeight) || 0; - const tableFooterHeight = (enableStickyFooter && tableFooterRef.current?.clientHeight) || 0; - - const pinnedRowIds = useMemo(() => { - if (!rowPinning.bottom?.length && !rowPinning.top?.length) return []; - return getRowModel() - .rows.filter((row) => row.getIsPinned()) - .map((r) => r.id); - }, [rowPinning, getRowModel().rows]); - - const rows = useMRT_Rows(table); - - const rowVirtualizer = useMRT_RowVirtualizer(table, rows); - - const { virtualRows } = rowVirtualizer ?? {}; - - const commonRowProps = { - columnVirtualizer, - numRows: rows.length, - table, - }; - - return ( - <> - {!rowPinningDisplayMode?.includes("sticky") && getIsSomeRowsPinned("top") && ( - ({ - display: layoutMode?.startsWith("grid") ? "grid" : undefined, - position: "sticky", - top: tableHeadHeight - 1, - zIndex: 1, - ...parseFromValuesOrFunc(tableBodyProps?.sx, theme), - })} - > - {getTopRows().map((row, staticRowIndex) => { - const props = { - ...commonRowProps, - row, - staticRowIndex, - }; - return memoMode === "rows" ? ( - - ) : ( - - ); - })} - - )} - ({ - display: layoutMode?.startsWith("grid") ? "grid" : undefined, - height: rowVirtualizer ? `${rowVirtualizer.getTotalSize()}px` : undefined, - minHeight: !rows.length ? "100px" : undefined, - position: "relative", - ...parseFromValuesOrFunc(tableBodyProps?.sx, theme), - })} - > - {tableBodyProps?.children ?? - (!rows.length ? ( - - - {renderEmptyRowsFallback?.({ table }) ?? ( - - {globalFilter || columnFilters.length - ? localization.noResultsFound - : localization.noRecordsToDisplay} - - )} - - - ) : ( - <> - {(virtualRows ?? rows).map((rowOrVirtualRow, staticRowIndex) => { - let row = rowOrVirtualRow; - if (rowVirtualizer) { - if (renderDetailPanel) { - if (rowOrVirtualRow.index % 2 === 1) { - return null; - } else { - staticRowIndex = rowOrVirtualRow.index / 2; - } - } else { - staticRowIndex = rowOrVirtualRow.index; - } - row = rows[staticRowIndex]; - } - const props = { - ...commonRowProps, - pinnedRowIds, - row, - rowVirtualizer, - staticRowIndex, - virtualRow: rowVirtualizer ? rowOrVirtualRow : undefined, - }; - const key = `${row.id}-${row.index}`; - return memoMode === "rows" ? ( - - ) : ( - - ); - })} - - ))} - - {!rowPinningDisplayMode?.includes("sticky") && getIsSomeRowsPinned("bottom") && ( - ({ - bottom: tableFooterHeight - 1, - display: layoutMode?.startsWith("grid") ? "grid" : undefined, - position: "sticky", - zIndex: 1, - ...parseFromValuesOrFunc(tableBodyProps?.sx, theme), - })} - > - {getBottomRows().map((row, staticRowIndex) => { - const props = { - ...commonRowProps, - row, - staticRowIndex, - }; - return memoMode === "rows" ? ( - - ) : ( - - ); - })} - - )} - - ); -}; -export default DataTable_TableBody; - -export const Memo_DataTable_TableBody = memo( - DataTable_TableBody, - (prev, next) => prev.table.options.data === next.table.options.data -); +import { parseFromValuesOrFunc } from "@/core/utils/utils"; +import { TableBody, Typography } from "@mui/material"; +import { useMRT_RowVirtualizer, useMRT_Rows } from "material-react-table"; +import { memo, useMemo } from "react"; +import DataTable_TableBodyRow, { Memo_DataTable_TableBodyRow } from "./TableBodyRow"; + +const DataTable_TableBody = ({ columnVirtualizer, table, ...rest }) => { + const { + getBottomRows, + getIsSomeRowsPinned, + getRowModel, + getState, + getTopRows, + options: { + enableStickyFooter, + enableStickyHeader, + layoutMode, + localization, + memoMode, + muiTableBodyProps, + renderDetailPanel, + renderEmptyRowsFallback, + rowPinningDisplayMode, + }, + refs: { tableFooterRef, tableHeadRef, tablePaperRef }, + } = table; + const { columnFilters, globalFilter, isFullScreen, rowPinning } = getState(); + + const tableBodyProps = { + ...parseFromValuesOrFunc(muiTableBodyProps, { table }), + ...rest, + }; + + const tableHeadHeight = ((enableStickyHeader || isFullScreen) && tableHeadRef.current?.clientHeight) || 0; + const tableFooterHeight = (enableStickyFooter && tableFooterRef.current?.clientHeight) || 0; + + const pinnedRowIds = useMemo(() => { + if (!rowPinning.bottom?.length && !rowPinning.top?.length) return []; + return getRowModel() + .rows.filter((row) => row.getIsPinned()) + .map((r) => r.id); + }, [rowPinning, getRowModel().rows]); + + const rows = useMRT_Rows(table); + + const rowVirtualizer = useMRT_RowVirtualizer(table, rows); + + const { virtualRows } = rowVirtualizer ?? {}; + + const commonRowProps = { + columnVirtualizer, + numRows: rows.length, + table, + }; + + return ( + <> + {!rowPinningDisplayMode?.includes("sticky") && getIsSomeRowsPinned("top") && ( + ({ + display: layoutMode?.startsWith("grid") ? "grid" : undefined, + position: "sticky", + top: tableHeadHeight - 1, + zIndex: 1, + ...parseFromValuesOrFunc(tableBodyProps?.sx, theme), + })} + > + {getTopRows().map((row, staticRowIndex) => { + const props = { + ...commonRowProps, + row, + staticRowIndex, + }; + return memoMode === "rows" ? ( + + ) : ( + + ); + })} + + )} + ({ + display: layoutMode?.startsWith("grid") ? "grid" : undefined, + height: rowVirtualizer ? `${rowVirtualizer.getTotalSize()}px` : undefined, + minHeight: !rows.length ? "100px" : undefined, + position: "relative", + ...parseFromValuesOrFunc(tableBodyProps?.sx, theme), + })} + > + {tableBodyProps?.children ?? + (!rows.length ? ( + + + {renderEmptyRowsFallback?.({ table }) ?? ( + + {globalFilter || columnFilters.length + ? localization.noResultsFound + : localization.noRecordsToDisplay} + + )} + + + ) : ( + <> + {(virtualRows ?? rows).map((rowOrVirtualRow, staticRowIndex) => { + let row = rowOrVirtualRow; + if (rowVirtualizer) { + if (renderDetailPanel) { + if (rowOrVirtualRow.index % 2 === 1) { + return null; + } else { + staticRowIndex = rowOrVirtualRow.index / 2; + } + } else { + staticRowIndex = rowOrVirtualRow.index; + } + row = rows[staticRowIndex]; + } + const props = { + ...commonRowProps, + pinnedRowIds, + row, + rowVirtualizer, + staticRowIndex, + virtualRow: rowVirtualizer ? rowOrVirtualRow : undefined, + }; + const key = `${row.id}-${row.index}`; + return memoMode === "rows" ? ( + + ) : ( + + ); + })} + + ))} + + {!rowPinningDisplayMode?.includes("sticky") && getIsSomeRowsPinned("bottom") && ( + ({ + bottom: tableFooterHeight - 1, + display: layoutMode?.startsWith("grid") ? "grid" : undefined, + position: "sticky", + zIndex: 1, + ...parseFromValuesOrFunc(tableBodyProps?.sx, theme), + })} + > + {getBottomRows().map((row, staticRowIndex) => { + const props = { + ...commonRowProps, + row, + staticRowIndex, + }; + return memoMode === "rows" ? ( + + ) : ( + + ); + })} + + )} + + ); +}; +export default DataTable_TableBody; + +export const Memo_DataTable_TableBody = memo( + DataTable_TableBody, + (prev, next) => prev.table.options.data === next.table.options.data +); diff --git a/src/core/components/DataTable/body/TableBodyCell.js b/src/core/components/DataTable/body/TableBodyCell.js index 292f39e..ef4cadf 100644 --- a/src/core/components/DataTable/body/TableBodyCell.js +++ b/src/core/components/DataTable/body/TableBodyCell.js @@ -1,255 +1,255 @@ -import { getCommonMRTCellStyles, parseFromValuesOrFunc } from "@/core/utils/utils"; -import { useTheme } from "@emotion/react"; -import { Skeleton, TableCell } from "@mui/material"; -import { isCellEditable, openEditingCell } from "material-react-table"; -import { memo, useEffect, useMemo, useState } from "react"; -import DataTable_CopyButton from "../buttons/CopyButton"; -import DataTable_TableBodyCellValue from "./TableBodyCellValue"; - -const DataTable_TableBodyCell = ({ cell, numRows, rowRef, staticColumnIndex, staticRowIndex, table, ...rest }) => { - const theme = useTheme(); - const { - getState, - options: { - columnResizeDirection, - columnResizeMode, - createDisplayMode, - editDisplayMode, - enableCellActions, - enableClickToCopy, - enableColumnOrdering, - enableColumnPinning, - enableGrouping, - layoutMode, - mrtTheme: { draggingBorderColor, baseBackgroundColor }, - muiSkeletonProps, - muiTableBodyCellProps, - }, - setHoveredColumn, - } = table; - const { - actionCell, - columnSizingInfo, - creatingRow, - density, - draggingColumn, - draggingRow, - editingCell, - editingRow, - hoveredColumn, - hoveredRow, - isLoading, - showSkeletons, - } = getState(); - const { column, row } = cell; - const { columnDef } = column; - const { columnDefType } = columnDef; - - const args = { cell, column, row, table }; - const tableCellProps = { - ...parseFromValuesOrFunc(muiTableBodyCellProps, args), - ...parseFromValuesOrFunc(columnDef.muiTableBodyCellProps, args), - ...rest, - }; - - const skeletonProps = parseFromValuesOrFunc(muiSkeletonProps, { - cell, - column, - row, - table, - }); - - const [skeletonWidth, setSkeletonWidth] = useState(100); - useEffect(() => { - if ((!isLoading && !showSkeletons) || skeletonWidth !== 100) return; - const size = column.getSize(); - setSkeletonWidth( - columnDefType === "display" ? size / 2 : Math.round(Math.random() * (size - size / 3) + size / 3) - ); - }, [isLoading, showSkeletons]); - - const draggingBorders = useMemo(() => { - const isDraggingColumn = draggingColumn?.id === column.id; - const isHoveredColumn = hoveredColumn?.id === column.id; - const isDraggingRow = draggingRow?.id === row.id; - const isHoveredRow = hoveredRow?.id === row.id; - const isFirstColumn = column.getIsFirstColumn(); - const isLastColumn = column.getIsLastColumn(); - const isLastRow = numRows && staticRowIndex === numRows - 1; - const isResizingColumn = columnSizingInfo.isResizingColumn === column.id; - const showResizeBorder = isResizingColumn && columnResizeMode === "onChange"; - - const borderStyle = showResizeBorder - ? `2px solid ${draggingBorderColor} !important` - : isDraggingColumn || isDraggingRow - ? `1px dashed ${theme.palette.grey[500]} !important` - : isHoveredColumn || isHoveredRow || isResizingColumn - ? `2px dashed ${draggingBorderColor} !important` - : undefined; - - if (showResizeBorder) { - return columnResizeDirection === "ltr" ? { borderRight: borderStyle } : { borderLeft: borderStyle }; - } - - return borderStyle - ? { - borderBottom: - isDraggingRow || isHoveredRow || (isLastRow && !isResizingColumn) ? borderStyle : undefined, - borderLeft: - isDraggingColumn || isHoveredColumn || ((isDraggingRow || isHoveredRow) && isFirstColumn) - ? borderStyle - : undefined, - borderRight: - isDraggingColumn || isHoveredColumn || ((isDraggingRow || isHoveredRow) && isLastColumn) - ? borderStyle - : undefined, - borderTop: isDraggingRow || isHoveredRow ? borderStyle : undefined, - } - : undefined; - }, [columnSizingInfo.isResizingColumn, draggingColumn, draggingRow, hoveredColumn, hoveredRow, staticRowIndex]); - - const isColumnPinned = enableColumnPinning && columnDef.columnDefType !== "group" && column.getIsPinned(); - - const isEditable = isCellEditable({ cell, table }); - - const isEditing = - isEditable && - !["custom", "modal"].includes(editDisplayMode) && - (editDisplayMode === "table" || editingRow?.id === row.id || editingCell?.id === cell.id) && - !row.getIsGrouped(); - - const isCreating = isEditable && createDisplayMode === "row" && creatingRow?.id === row.id; - - const showClickToCopyButton = - (parseFromValuesOrFunc(enableClickToCopy, cell) === true || - parseFromValuesOrFunc(columnDef.enableClickToCopy, cell) === true) && - !["context-menu", false].includes( - // @ts-ignore - parseFromValuesOrFunc(columnDef.enableClickToCopy, cell) - ); - - const isRightClickable = parseFromValuesOrFunc(enableCellActions, cell); - - const cellValueProps = { - cell, - table, - }; - - const handleDoubleClick = (event) => { - tableCellProps?.onDoubleClick?.(event); - openEditingCell({ cell, table }); - }; - - const handleDragEnter = (e) => { - tableCellProps?.onDragEnter?.(e); - if (enableGrouping && hoveredColumn?.id === "drop-zone") { - setHoveredColumn(null); - } - if (enableColumnOrdering && draggingColumn) { - setHoveredColumn(columnDef.enableColumnOrdering !== false ? column : null); - } - }; - - const handleDragOver = (e) => { - if (columnDef.enableColumnOrdering !== false) { - e.preventDefault(); - } - }; - - const handleContextMenu = (e) => { - tableCellProps?.onContextMenu?.(e); - if (isRightClickable) { - e.preventDefault(); - table.setActionCell(cell); - table.refs.actionCellRef.current = e.currentTarget; - } - }; - - return ( - ({ - "&:hover": { - outline: - actionCell?.id === cell.id || - (editDisplayMode === "cell" && isEditable) || - (editDisplayMode === "table" && (isCreating || isEditing)) - ? `1px solid ${theme.palette.grey[500]}` - : undefined, - textOverflow: "clip", - }, - alignItems: layoutMode?.startsWith("grid") ? "center" : undefined, - cursor: isRightClickable - ? "context-menu" - : isEditable && editDisplayMode === "cell" - ? "pointer" - : "inherit", - outline: actionCell?.id === cell.id ? `1px solid ${theme.palette.grey[500]}` : undefined, - outlineOffset: "-1px", - overflow: "hidden", - p: - density === "compact" - ? columnDefType === "display" - ? "0 0.5rem" - : "0.5rem" - : density === "comfortable" - ? columnDefType === "display" - ? "0.5rem 0.75rem" - : "1rem" - : columnDefType === "display" - ? "1rem 1.25rem" - : "1.5rem", - - textOverflow: columnDefType !== "display" ? "ellipsis" : undefined, - whiteSpace: row.getIsPinned() || density === "compact" ? "nowrap" : "normal", - ...getCommonMRTCellStyles({ - column, - table, - tableCellProps, - theme, - }), - ...draggingBorders, - backgroundColor: baseBackgroundColor, - })} - > - {tableCellProps.children ?? ( - <> - {cell.getIsPlaceholder() ? ( - (columnDef.PlaceholderCell?.({ cell, column, row, table }) ?? null) - ) : showSkeletons !== false && (isLoading || showSkeletons) ? ( - - ) : columnDefType === "display" && - (["mrt-row-expand", "mrt-row-numbers", "mrt-row-select"].includes(column.id) || - !row.getIsGrouped()) ? ( - columnDef.Cell?.({ - cell, - column, - renderedCellValue: cell.renderValue(), - row, - rowRef, - staticColumnIndex, - staticRowIndex, - table, - }) - ) : showClickToCopyButton && columnDef.enableClickToCopy !== false ? ( - - - - ) : ( - - )} - {cell.getIsGrouped() && !columnDef.GroupedCell && <> ({row.subRows?.length})} - - )} - - ); -}; -export default DataTable_TableBodyCell; - -export const Memo_DataTable_TableBodyCell = memo(DataTable_TableBodyCell, (prev, next) => next.cell === prev.cell); +import { getCommonMRTCellStyles, parseFromValuesOrFunc } from "@/core/utils/utils"; +import { useTheme } from "@emotion/react"; +import { Skeleton, TableCell } from "@mui/material"; +import { isCellEditable, openEditingCell } from "material-react-table"; +import { memo, useEffect, useMemo, useState } from "react"; +import DataTable_CopyButton from "../buttons/CopyButton"; +import DataTable_TableBodyCellValue from "./TableBodyCellValue"; + +const DataTable_TableBodyCell = ({ cell, numRows, rowRef, staticColumnIndex, staticRowIndex, table, ...rest }) => { + const theme = useTheme(); + const { + getState, + options: { + columnResizeDirection, + columnResizeMode, + createDisplayMode, + editDisplayMode, + enableCellActions, + enableClickToCopy, + enableColumnOrdering, + enableColumnPinning, + enableGrouping, + layoutMode, + mrtTheme: { draggingBorderColor, baseBackgroundColor }, + muiSkeletonProps, + muiTableBodyCellProps, + }, + setHoveredColumn, + } = table; + const { + actionCell, + columnSizingInfo, + creatingRow, + density, + draggingColumn, + draggingRow, + editingCell, + editingRow, + hoveredColumn, + hoveredRow, + isLoading, + showSkeletons, + } = getState(); + const { column, row } = cell; + const { columnDef } = column; + const { columnDefType } = columnDef; + + const args = { cell, column, row, table }; + const tableCellProps = { + ...parseFromValuesOrFunc(muiTableBodyCellProps, args), + ...parseFromValuesOrFunc(columnDef.muiTableBodyCellProps, args), + ...rest, + }; + + const skeletonProps = parseFromValuesOrFunc(muiSkeletonProps, { + cell, + column, + row, + table, + }); + + const [skeletonWidth, setSkeletonWidth] = useState(100); + useEffect(() => { + if ((!isLoading && !showSkeletons) || skeletonWidth !== 100) return; + const size = column.getSize(); + setSkeletonWidth( + columnDefType === "display" ? size / 2 : Math.round(Math.random() * (size - size / 3) + size / 3) + ); + }, [isLoading, showSkeletons]); + + const draggingBorders = useMemo(() => { + const isDraggingColumn = draggingColumn?.id === column.id; + const isHoveredColumn = hoveredColumn?.id === column.id; + const isDraggingRow = draggingRow?.id === row.id; + const isHoveredRow = hoveredRow?.id === row.id; + const isFirstColumn = column.getIsFirstColumn(); + const isLastColumn = column.getIsLastColumn(); + const isLastRow = numRows && staticRowIndex === numRows - 1; + const isResizingColumn = columnSizingInfo.isResizingColumn === column.id; + const showResizeBorder = isResizingColumn && columnResizeMode === "onChange"; + + const borderStyle = showResizeBorder + ? `2px solid ${draggingBorderColor} !important` + : isDraggingColumn || isDraggingRow + ? `1px dashed ${theme.palette.grey[500]} !important` + : isHoveredColumn || isHoveredRow || isResizingColumn + ? `2px dashed ${draggingBorderColor} !important` + : undefined; + + if (showResizeBorder) { + return columnResizeDirection === "ltr" ? { borderRight: borderStyle } : { borderLeft: borderStyle }; + } + + return borderStyle + ? { + borderBottom: + isDraggingRow || isHoveredRow || (isLastRow && !isResizingColumn) ? borderStyle : undefined, + borderLeft: + isDraggingColumn || isHoveredColumn || ((isDraggingRow || isHoveredRow) && isFirstColumn) + ? borderStyle + : undefined, + borderRight: + isDraggingColumn || isHoveredColumn || ((isDraggingRow || isHoveredRow) && isLastColumn) + ? borderStyle + : undefined, + borderTop: isDraggingRow || isHoveredRow ? borderStyle : undefined, + } + : undefined; + }, [columnSizingInfo.isResizingColumn, draggingColumn, draggingRow, hoveredColumn, hoveredRow, staticRowIndex]); + + const isColumnPinned = enableColumnPinning && columnDef.columnDefType !== "group" && column.getIsPinned(); + + const isEditable = isCellEditable({ cell, table }); + + const isEditing = + isEditable && + !["custom", "modal"].includes(editDisplayMode) && + (editDisplayMode === "table" || editingRow?.id === row.id || editingCell?.id === cell.id) && + !row.getIsGrouped(); + + const isCreating = isEditable && createDisplayMode === "row" && creatingRow?.id === row.id; + + const showClickToCopyButton = + (parseFromValuesOrFunc(enableClickToCopy, cell) === true || + parseFromValuesOrFunc(columnDef.enableClickToCopy, cell) === true) && + !["context-menu", false].includes( + // @ts-ignore + parseFromValuesOrFunc(columnDef.enableClickToCopy, cell) + ); + + const isRightClickable = parseFromValuesOrFunc(enableCellActions, cell); + + const cellValueProps = { + cell, + table, + }; + + const handleDoubleClick = (event) => { + tableCellProps?.onDoubleClick?.(event); + openEditingCell({ cell, table }); + }; + + const handleDragEnter = (e) => { + tableCellProps?.onDragEnter?.(e); + if (enableGrouping && hoveredColumn?.id === "drop-zone") { + setHoveredColumn(null); + } + if (enableColumnOrdering && draggingColumn) { + setHoveredColumn(columnDef.enableColumnOrdering !== false ? column : null); + } + }; + + const handleDragOver = (e) => { + if (columnDef.enableColumnOrdering !== false) { + e.preventDefault(); + } + }; + + const handleContextMenu = (e) => { + tableCellProps?.onContextMenu?.(e); + if (isRightClickable) { + e.preventDefault(); + table.setActionCell(cell); + table.refs.actionCellRef.current = e.currentTarget; + } + }; + + return ( + ({ + "&:hover": { + outline: + actionCell?.id === cell.id || + (editDisplayMode === "cell" && isEditable) || + (editDisplayMode === "table" && (isCreating || isEditing)) + ? `1px solid ${theme.palette.grey[500]}` + : undefined, + textOverflow: "clip", + }, + alignItems: layoutMode?.startsWith("grid") ? "center" : undefined, + cursor: isRightClickable + ? "context-menu" + : isEditable && editDisplayMode === "cell" + ? "pointer" + : "inherit", + outline: actionCell?.id === cell.id ? `1px solid ${theme.palette.grey[500]}` : undefined, + outlineOffset: "-1px", + overflow: "hidden", + p: + density === "compact" + ? columnDefType === "display" + ? "0 0.5rem" + : "0.5rem" + : density === "comfortable" + ? columnDefType === "display" + ? "0.5rem 0.75rem" + : "1rem" + : columnDefType === "display" + ? "1rem 1.25rem" + : "1.5rem", + + textOverflow: columnDefType !== "display" ? "ellipsis" : undefined, + whiteSpace: row.getIsPinned() || density === "compact" ? "nowrap" : "normal", + ...getCommonMRTCellStyles({ + column, + table, + tableCellProps, + theme, + }), + ...draggingBorders, + backgroundColor: baseBackgroundColor, + })} + > + {tableCellProps.children ?? ( + <> + {cell.getIsPlaceholder() ? ( + (columnDef.PlaceholderCell?.({ cell, column, row, table }) ?? null) + ) : showSkeletons !== false && (isLoading || showSkeletons) ? ( + + ) : columnDefType === "display" && + (["mrt-row-expand", "mrt-row-numbers", "mrt-row-select"].includes(column.id) || + !row.getIsGrouped()) ? ( + columnDef.Cell?.({ + cell, + column, + renderedCellValue: cell.renderValue(), + row, + rowRef, + staticColumnIndex, + staticRowIndex, + table, + }) + ) : showClickToCopyButton && columnDef.enableClickToCopy !== false ? ( + + + + ) : ( + + )} + {cell.getIsGrouped() && !columnDef.GroupedCell && <> ({row.subRows?.length})} + + )} + + ); +}; +export default DataTable_TableBodyCell; + +export const Memo_DataTable_TableBodyCell = memo(DataTable_TableBodyCell, (prev, next) => next.cell === prev.cell); diff --git a/src/core/components/DataTable/body/TableBodyCellValue.js b/src/core/components/DataTable/body/TableBodyCellValue.js index aea105f..38c12a9 100644 --- a/src/core/components/DataTable/body/TableBodyCellValue.js +++ b/src/core/components/DataTable/body/TableBodyCellValue.js @@ -1,103 +1,103 @@ -import { Box } from "@mui/material"; - -const allowedTypes = ["string", "number"]; - -const DataTable_TableBodyCellValue = ({ cell, rowRef, staticColumnIndex, staticRowIndex, table }) => { - const { - getState, - options: { - enableFilterMatchHighlighting, - mrtTheme: { matchHighlightColor }, - }, - } = table; - const { column, row } = cell; - const { columnDef } = column; - const { globalFilter, globalFilterFn } = getState(); - const filterValue = column.getFilterValue(); - - let renderedCellValue = - cell.getIsAggregated() && columnDef.AggregatedCell - ? columnDef.AggregatedCell({ - cell, - column, - row, - table, - }) - : row.getIsGrouped() && !cell.getIsGrouped() - ? null - : cell.getIsGrouped() && columnDef.GroupedCell - ? columnDef.GroupedCell({ - cell, - column, - row, - table, - }) - : undefined; - - const isGroupedValue = renderedCellValue !== undefined; - - if (!isGroupedValue) { - renderedCellValue = cell.renderValue(); - } - - if ( - enableFilterMatchHighlighting && - columnDef.enableFilterMatchHighlighting !== false && - String(renderedCellValue) && - allowedTypes.includes(typeof renderedCellValue) && - ((filterValue && - allowedTypes.includes(typeof filterValue) && - ["autocomplete", "text"].includes(columnDef.filterVariant)) || - (globalFilter && allowedTypes.includes(typeof globalFilter) && column.getCanGlobalFilter())) - ) { - const chunks = highlightWords?.({ - matchExactly: (filterValue ? columnDef._filterFn : globalFilterFn) !== "fuzzy", - query: (filterValue ?? globalFilter ?? "").toString(), - text: renderedCellValue?.toString(), - }); - if (chunks?.length > 1 || chunks?.[0]?.match) { - renderedCellValue = ( - - {chunks?.map(({ key, match, text }) => ( - - )) ?? renderedCellValue} - - ); - } - } - - if (columnDef.Cell && !isGroupedValue) { - renderedCellValue = columnDef.Cell({ - cell, - column, - renderedCellValue, - row, - rowRef, - staticColumnIndex, - staticRowIndex, - table, - }); - } - - return renderedCellValue; -}; -export default DataTable_TableBodyCellValue; +import { Box } from "@mui/material"; + +const allowedTypes = ["string", "number"]; + +const DataTable_TableBodyCellValue = ({ cell, rowRef, staticColumnIndex, staticRowIndex, table }) => { + const { + getState, + options: { + enableFilterMatchHighlighting, + mrtTheme: { matchHighlightColor }, + }, + } = table; + const { column, row } = cell; + const { columnDef } = column; + const { globalFilter, globalFilterFn } = getState(); + const filterValue = column.getFilterValue(); + + let renderedCellValue = + cell.getIsAggregated() && columnDef.AggregatedCell + ? columnDef.AggregatedCell({ + cell, + column, + row, + table, + }) + : row.getIsGrouped() && !cell.getIsGrouped() + ? null + : cell.getIsGrouped() && columnDef.GroupedCell + ? columnDef.GroupedCell({ + cell, + column, + row, + table, + }) + : undefined; + + const isGroupedValue = renderedCellValue !== undefined; + + if (!isGroupedValue) { + renderedCellValue = cell.renderValue(); + } + + if ( + enableFilterMatchHighlighting && + columnDef.enableFilterMatchHighlighting !== false && + String(renderedCellValue) && + allowedTypes.includes(typeof renderedCellValue) && + ((filterValue && + allowedTypes.includes(typeof filterValue) && + ["autocomplete", "text"].includes(columnDef.filterVariant)) || + (globalFilter && allowedTypes.includes(typeof globalFilter) && column.getCanGlobalFilter())) + ) { + const chunks = highlightWords?.({ + matchExactly: (filterValue ? columnDef._filterFn : globalFilterFn) !== "fuzzy", + query: (filterValue ?? globalFilter ?? "").toString(), + text: renderedCellValue?.toString(), + }); + if (chunks?.length > 1 || chunks?.[0]?.match) { + renderedCellValue = ( + + {chunks?.map(({ key, match, text }) => ( + + )) ?? renderedCellValue} + + ); + } + } + + if (columnDef.Cell && !isGroupedValue) { + renderedCellValue = columnDef.Cell({ + cell, + column, + renderedCellValue, + row, + rowRef, + staticColumnIndex, + staticRowIndex, + table, + }); + } + + return renderedCellValue; +}; +export default DataTable_TableBodyCellValue; diff --git a/src/core/components/DataTable/body/TableBodyRow.js b/src/core/components/DataTable/body/TableBodyRow.js index 2d21f32..913acf1 100644 --- a/src/core/components/DataTable/body/TableBodyRow.js +++ b/src/core/components/DataTable/body/TableBodyRow.js @@ -1,216 +1,216 @@ -import { commonCellBeforeAfterStyles, getCommonPinnedCellStyles, parseFromValuesOrFunc } from "@/core/utils/utils"; -import { useTheme } from "@emotion/react"; -import { TableRow, alpha, darken, lighten } from "@mui/material"; -import { getIsRowSelected } from "material-react-table"; -import { memo, useMemo, useRef } from "react"; -import DataTable_TableBodyCell, { Memo_DataTable_TableBodyCell } from "./TableBodyCell"; -import DataTable_TableDetailPanel from "./TableDetailPanel"; - -const DataTable_TableBodyRow = ({ - columnVirtualizer, - numRows, - pinnedRowIds, - row, - rowVirtualizer, - staticRowIndex, - table, - virtualRow, - ...rest -}) => { - const theme = useTheme(); - - const { - getState, - options: { - enableRowOrdering, - enableRowPinning, - enableStickyFooter, - enableStickyHeader, - layoutMode, - memoMode, - mrtTheme: { baseBackgroundColor, pinnedRowBackgroundColor, selectedRowBackgroundColor }, - muiTableBodyRowProps, - renderDetailPanel, - rowPinningDisplayMode, - }, - refs: { tableFooterRef, tableHeadRef }, - setHoveredRow, - } = table; - const { density, draggingColumn, draggingRow, editingCell, editingRow, hoveredRow, isFullScreen, rowPinning } = - getState(); - - const visibleCells = row.getVisibleCells(); - - const { virtualColumns, virtualPaddingLeft, virtualPaddingRight } = columnVirtualizer ?? {}; - - const isRowSelected = getIsRowSelected({ row, table }); - const isRowPinned = enableRowPinning && row.getIsPinned(); - const isDraggingRow = draggingRow?.id === row.id; - const isHoveredRow = hoveredRow?.id === row.id; - - const tableRowProps = { - ...parseFromValuesOrFunc(muiTableBodyRowProps, { - row, - staticRowIndex, - table, - }), - ...rest, - }; - - const [bottomPinnedIndex, topPinnedIndex] = useMemo(() => { - if (!enableRowPinning || !rowPinningDisplayMode?.includes("sticky") || !pinnedRowIds || !row.getIsPinned()) - return []; - return [[...pinnedRowIds].reverse().indexOf(row.id), pinnedRowIds.indexOf(row.id)]; - }, [pinnedRowIds, rowPinning]); - - const tableHeadHeight = ((enableStickyHeader || isFullScreen) && tableHeadRef.current?.clientHeight) || 0; - const tableFooterHeight = (enableStickyFooter && tableFooterRef.current?.clientHeight) || 0; - - const sx = parseFromValuesOrFunc(tableRowProps?.sx, theme); - - const defaultRowHeight = density === "compact" ? 37 : density === "comfortable" ? 53 : 69; - - const customRowHeight = - // @ts-ignore - parseInt(tableRowProps?.style?.height ?? sx?.height, 10) || undefined; - - const rowHeight = customRowHeight || defaultRowHeight; - - const handleDragEnter = (_e) => { - if (enableRowOrdering && draggingRow) { - setHoveredRow(row); - } - }; - - const handleDragOver = (e) => { - e.preventDefault(); - }; - - const rowRef = useRef(null); - - const cellHighlightColor = isRowSelected - ? selectedRowBackgroundColor - : isRowPinned - ? pinnedRowBackgroundColor - : undefined; - - const cellHighlightColorHover = - tableRowProps?.hover !== false - ? isRowSelected - ? cellHighlightColor - : theme.palette.mode === "dark" - ? `${lighten(baseBackgroundColor, 0.2)}` - : `${darken(baseBackgroundColor, 0.2)}` - : undefined; - - return ( - <> - { - if (node) { - rowRef.current = node; - rowVirtualizer?.measureElement(node); - } - }} - selected={isRowSelected} - {...tableRowProps} - style={{ - transform: virtualRow ? `translateY(${virtualRow.start}px)` : undefined, - ...tableRowProps?.style, - }} - sx={(theme) => ({ - "&:hover td:after": cellHighlightColorHover - ? { - backgroundColor: alpha(cellHighlightColorHover, 0.3), - ...commonCellBeforeAfterStyles, - } - : undefined, - bottom: - !virtualRow && bottomPinnedIndex !== undefined && isRowPinned - ? `${bottomPinnedIndex * rowHeight + (enableStickyFooter ? tableFooterHeight - 1 : 0)}px` - : undefined, - boxSizing: "border-box", - display: layoutMode?.startsWith("grid") ? "flex" : undefined, - opacity: isRowPinned ? 0.97 : isDraggingRow || isHoveredRow ? 0.5 : 1, - position: virtualRow - ? "absolute" - : rowPinningDisplayMode?.includes("sticky") && isRowPinned - ? "sticky" - : "relative", - td: { - ...getCommonPinnedCellStyles({ table, theme }), - }, - "td:after": cellHighlightColor - ? { - backgroundColor: cellHighlightColor, - ...commonCellBeforeAfterStyles, - } - : undefined, - top: virtualRow - ? 0 - : topPinnedIndex !== undefined && isRowPinned - ? `${ - topPinnedIndex * rowHeight + - (enableStickyHeader || isFullScreen ? tableHeadHeight - 1 : 0) - }px` - : undefined, - transition: virtualRow ? "none" : "all 150ms ease-in-out", - width: "100%", - zIndex: rowPinningDisplayMode?.includes("sticky") && isRowPinned ? 2 : 0, - ...sx, - })} - > - {virtualPaddingLeft ? : null} - {(virtualColumns ?? visibleCells).map((cellOrVirtualCell, staticColumnIndex) => { - let cell = cellOrVirtualCell; - if (columnVirtualizer) { - staticColumnIndex = cellOrVirtualCell.index; - cell = visibleCells[staticColumnIndex]; - } - const props = { - cell, - numRows, - rowRef, - staticColumnIndex, - staticRowIndex, - table, - }; - return cell ? ( - memoMode === "cells" && - cell.column.columnDef.columnDefType === "data" && - !draggingColumn && - !draggingRow && - editingCell?.id !== cell.id && - editingRow?.id !== row.id ? ( - - ) : ( - - ) - ) : null; - })} - {virtualPaddingRight ? : null} - - {renderDetailPanel && !row.getIsGrouped() && ( - - )} - - ); -}; -export default DataTable_TableBodyRow; - -export const Memo_DataTable_TableBodyRow = memo( - DataTable_TableBodyRow, - (prev, next) => prev.row === next.row && prev.staticRowIndex === next.staticRowIndex -); +import { commonCellBeforeAfterStyles, getCommonPinnedCellStyles, parseFromValuesOrFunc } from "@/core/utils/utils"; +import { useTheme } from "@emotion/react"; +import { TableRow, alpha, darken, lighten } from "@mui/material"; +import { getIsRowSelected } from "material-react-table"; +import { memo, useMemo, useRef } from "react"; +import DataTable_TableBodyCell, { Memo_DataTable_TableBodyCell } from "./TableBodyCell"; +import DataTable_TableDetailPanel from "./TableDetailPanel"; + +const DataTable_TableBodyRow = ({ + columnVirtualizer, + numRows, + pinnedRowIds, + row, + rowVirtualizer, + staticRowIndex, + table, + virtualRow, + ...rest +}) => { + const theme = useTheme(); + + const { + getState, + options: { + enableRowOrdering, + enableRowPinning, + enableStickyFooter, + enableStickyHeader, + layoutMode, + memoMode, + mrtTheme: { baseBackgroundColor, pinnedRowBackgroundColor, selectedRowBackgroundColor }, + muiTableBodyRowProps, + renderDetailPanel, + rowPinningDisplayMode, + }, + refs: { tableFooterRef, tableHeadRef }, + setHoveredRow, + } = table; + const { density, draggingColumn, draggingRow, editingCell, editingRow, hoveredRow, isFullScreen, rowPinning } = + getState(); + + const visibleCells = row.getVisibleCells(); + + const { virtualColumns, virtualPaddingLeft, virtualPaddingRight } = columnVirtualizer ?? {}; + + const isRowSelected = getIsRowSelected({ row, table }); + const isRowPinned = enableRowPinning && row.getIsPinned(); + const isDraggingRow = draggingRow?.id === row.id; + const isHoveredRow = hoveredRow?.id === row.id; + + const tableRowProps = { + ...parseFromValuesOrFunc(muiTableBodyRowProps, { + row, + staticRowIndex, + table, + }), + ...rest, + }; + + const [bottomPinnedIndex, topPinnedIndex] = useMemo(() => { + if (!enableRowPinning || !rowPinningDisplayMode?.includes("sticky") || !pinnedRowIds || !row.getIsPinned()) + return []; + return [[...pinnedRowIds].reverse().indexOf(row.id), pinnedRowIds.indexOf(row.id)]; + }, [pinnedRowIds, rowPinning]); + + const tableHeadHeight = ((enableStickyHeader || isFullScreen) && tableHeadRef.current?.clientHeight) || 0; + const tableFooterHeight = (enableStickyFooter && tableFooterRef.current?.clientHeight) || 0; + + const sx = parseFromValuesOrFunc(tableRowProps?.sx, theme); + + const defaultRowHeight = density === "compact" ? 37 : density === "comfortable" ? 53 : 69; + + const customRowHeight = + // @ts-ignore + parseInt(tableRowProps?.style?.height ?? sx?.height, 10) || undefined; + + const rowHeight = customRowHeight || defaultRowHeight; + + const handleDragEnter = (_e) => { + if (enableRowOrdering && draggingRow) { + setHoveredRow(row); + } + }; + + const handleDragOver = (e) => { + e.preventDefault(); + }; + + const rowRef = useRef(null); + + const cellHighlightColor = isRowSelected + ? selectedRowBackgroundColor + : isRowPinned + ? pinnedRowBackgroundColor + : undefined; + + const cellHighlightColorHover = + tableRowProps?.hover !== false + ? isRowSelected + ? cellHighlightColor + : theme.palette.mode === "dark" + ? `${lighten(baseBackgroundColor, 0.2)}` + : `${darken(baseBackgroundColor, 0.2)}` + : undefined; + + return ( + <> + { + if (node) { + rowRef.current = node; + rowVirtualizer?.measureElement(node); + } + }} + selected={isRowSelected} + {...tableRowProps} + style={{ + transform: virtualRow ? `translateY(${virtualRow.start}px)` : undefined, + ...tableRowProps?.style, + }} + sx={(theme) => ({ + "&:hover td:after": cellHighlightColorHover + ? { + backgroundColor: alpha(cellHighlightColorHover, 0.3), + ...commonCellBeforeAfterStyles, + } + : undefined, + bottom: + !virtualRow && bottomPinnedIndex !== undefined && isRowPinned + ? `${bottomPinnedIndex * rowHeight + (enableStickyFooter ? tableFooterHeight - 1 : 0)}px` + : undefined, + boxSizing: "border-box", + display: layoutMode?.startsWith("grid") ? "flex" : undefined, + opacity: isRowPinned ? 0.97 : isDraggingRow || isHoveredRow ? 0.5 : 1, + position: virtualRow + ? "absolute" + : rowPinningDisplayMode?.includes("sticky") && isRowPinned + ? "sticky" + : "relative", + td: { + ...getCommonPinnedCellStyles({ table, theme }), + }, + "td:after": cellHighlightColor + ? { + backgroundColor: cellHighlightColor, + ...commonCellBeforeAfterStyles, + } + : undefined, + top: virtualRow + ? 0 + : topPinnedIndex !== undefined && isRowPinned + ? `${ + topPinnedIndex * rowHeight + + (enableStickyHeader || isFullScreen ? tableHeadHeight - 1 : 0) + }px` + : undefined, + transition: virtualRow ? "none" : "all 150ms ease-in-out", + width: "100%", + zIndex: rowPinningDisplayMode?.includes("sticky") && isRowPinned ? 2 : 0, + ...sx, + })} + > + {virtualPaddingLeft ? : null} + {(virtualColumns ?? visibleCells).map((cellOrVirtualCell, staticColumnIndex) => { + let cell = cellOrVirtualCell; + if (columnVirtualizer) { + staticColumnIndex = cellOrVirtualCell.index; + cell = visibleCells[staticColumnIndex]; + } + const props = { + cell, + numRows, + rowRef, + staticColumnIndex, + staticRowIndex, + table, + }; + return cell ? ( + memoMode === "cells" && + cell.column.columnDef.columnDefType === "data" && + !draggingColumn && + !draggingRow && + editingCell?.id !== cell.id && + editingRow?.id !== row.id ? ( + + ) : ( + + ) + ) : null; + })} + {virtualPaddingRight ? : null} + + {renderDetailPanel && !row.getIsGrouped() && ( + + )} + + ); +}; +export default DataTable_TableBodyRow; + +export const Memo_DataTable_TableBodyRow = memo( + DataTable_TableBodyRow, + (prev, next) => prev.row === next.row && prev.staticRowIndex === next.staticRowIndex +); diff --git a/src/core/components/DataTable/body/TableDetailPanel.js b/src/core/components/DataTable/body/TableDetailPanel.js index 853aab5..bba8a8a 100644 --- a/src/core/components/DataTable/body/TableDetailPanel.js +++ b/src/core/components/DataTable/body/TableDetailPanel.js @@ -1,87 +1,87 @@ -import { parseFromValuesOrFunc } from "@/core/utils/utils"; -import { Collapse, TableCell, TableRow } from "@mui/material"; - -const DataTable_TableDetailPanel = ({ - parentRowRef, - row, - rowVirtualizer, - staticRowIndex, - table, - virtualRow, - ...rest -}) => { - const { - getState, - getVisibleLeafColumns, - options: { - layoutMode, - mrtTheme: { baseBackgroundColor }, - muiDetailPanelProps, - muiTableBodyRowProps, - renderDetailPanel, - }, - } = table; - const { isLoading } = getState(); - - const tableRowProps = parseFromValuesOrFunc(muiTableBodyRowProps, { - isDetailPanel: true, - row, - staticRowIndex, - table, - }); - - const tableCellProps = { - ...parseFromValuesOrFunc(muiDetailPanelProps, { - row, - table, - }), - ...rest, - }; - - const DetailPanel = !isLoading && renderDetailPanel?.({ row, table }); - - return ( - { - if (node) { - rowVirtualizer?.measureElement?.(node); - } - }} - {...tableRowProps} - sx={(theme) => ({ - display: layoutMode?.startsWith("grid") ? "flex" : undefined, - position: virtualRow ? "absolute" : undefined, - top: virtualRow ? `${parentRowRef.current?.getBoundingClientRect()?.height}px` : undefined, - transform: virtualRow ? `translateY(${virtualRow?.start}px)` : undefined, - width: "100%", - ...parseFromValuesOrFunc(tableRowProps?.sx, theme), - })} - > - ({ - backgroundColor: virtualRow ? baseBackgroundColor : undefined, - borderBottom: !row.getIsExpanded() ? "none" : undefined, - display: layoutMode?.startsWith("grid") ? "flex" : undefined, - py: !!DetailPanel && row.getIsExpanded() ? "1rem" : 0, - transition: !virtualRow ? "all 150ms ease-in-out" : undefined, - width: `100%`, - ...parseFromValuesOrFunc(tableCellProps?.sx, theme), - })} - > - {virtualRow ? ( - row.getIsExpanded() && DetailPanel - ) : ( - - {DetailPanel} - - )} - - - ); -}; -export default DataTable_TableDetailPanel; +import { parseFromValuesOrFunc } from "@/core/utils/utils"; +import { Collapse, TableCell, TableRow } from "@mui/material"; + +const DataTable_TableDetailPanel = ({ + parentRowRef, + row, + rowVirtualizer, + staticRowIndex, + table, + virtualRow, + ...rest +}) => { + const { + getState, + getVisibleLeafColumns, + options: { + layoutMode, + mrtTheme: { baseBackgroundColor }, + muiDetailPanelProps, + muiTableBodyRowProps, + renderDetailPanel, + }, + } = table; + const { isLoading } = getState(); + + const tableRowProps = parseFromValuesOrFunc(muiTableBodyRowProps, { + isDetailPanel: true, + row, + staticRowIndex, + table, + }); + + const tableCellProps = { + ...parseFromValuesOrFunc(muiDetailPanelProps, { + row, + table, + }), + ...rest, + }; + + const DetailPanel = !isLoading && renderDetailPanel?.({ row, table }); + + return ( + { + if (node) { + rowVirtualizer?.measureElement?.(node); + } + }} + {...tableRowProps} + sx={(theme) => ({ + display: layoutMode?.startsWith("grid") ? "flex" : undefined, + position: virtualRow ? "absolute" : undefined, + top: virtualRow ? `${parentRowRef.current?.getBoundingClientRect()?.height}px` : undefined, + transform: virtualRow ? `translateY(${virtualRow?.start}px)` : undefined, + width: "100%", + ...parseFromValuesOrFunc(tableRowProps?.sx, theme), + })} + > + ({ + backgroundColor: virtualRow ? baseBackgroundColor : undefined, + borderBottom: !row.getIsExpanded() ? "none" : undefined, + display: layoutMode?.startsWith("grid") ? "flex" : undefined, + py: !!DetailPanel && row.getIsExpanded() ? "1rem" : 0, + transition: !virtualRow ? "all 150ms ease-in-out" : undefined, + width: `100%`, + ...parseFromValuesOrFunc(tableCellProps?.sx, theme), + })} + > + {virtualRow ? ( + row.getIsExpanded() && DetailPanel + ) : ( + + {DetailPanel} + + )} + + + ); +}; +export default DataTable_TableDetailPanel; diff --git a/src/core/components/DataTable/buttons/CopyButton.js b/src/core/components/DataTable/buttons/CopyButton.js index c4dfe4b..818a1e7 100644 --- a/src/core/components/DataTable/buttons/CopyButton.js +++ b/src/core/components/DataTable/buttons/CopyButton.js @@ -1,68 +1,68 @@ -import { getCommonTooltipProps, parseFromValuesOrFunc } from "@/core/utils/utils"; -import { Button, Tooltip } from "@mui/material"; -import { useState } from "react"; - -const DataTable_CopyButton = ({ cell, table, ...rest }) => { - const { - options: { localization, muiCopyButtonProps }, - } = table; - const { column, row } = cell; - const { columnDef } = column; - - const [copied, setCopied] = useState(false); - - const handleCopy = (event, text) => { - event.stopPropagation(); - navigator.clipboard.writeText(text); - setCopied(true); - setTimeout(() => setCopied(false), 4000); - }; - - const buttonProps = { - ...parseFromValuesOrFunc(muiCopyButtonProps, { - cell, - column, - row, - table, - }), - ...parseFromValuesOrFunc(columnDef.muiCopyButtonProps, { - cell, - column, - row, - table, - }), - ...rest, - }; - - return ( - - - - - - )} - - ); -} - -export default FilterBody; +"use client"; + +import FilterBodyControllerWithDependency from "@/core/components/DataTable/filter/FilterBodyControllerWithDependency"; +import FilterHeader from "@/core/components/DataTable/filter/FilterHeader"; +import useDataTable from "@/lib/hooks/useDataTable"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { Box, Button } from "@mui/material"; +import { useEffect, useState } from "react"; +import { useForm } from "react-hook-form"; +import * as Yup from "yup"; +import ScrollBox from "../../ScrollBox"; +import FilterBodyController from "./FilterBodyController"; + +function FilterBody({ columns, drawerState, setDrawerState }) { + const { filterData, setFilterData } = useDataTable(); + const [validationSchema, setValidationSchema] = useState(Yup.object({})); + + useEffect(() => { + const schema = Yup.object( + Object.keys(filterData).reduce((acc, key) => { + const initialValue = filterData[key]; + if (initialValue.filterMode === "between") { + acc[key] = Yup.object().shape({ + value: Yup.array() + .of(Yup.string().nullable()) + .test({ + test(value, ctx) { + const [start, end] = value || ["", ""]; + if ( + initialValue.datatype === "numeric" && + parseInt(end, 10) <= parseInt(start, 10) + ) { + return ctx.createError({ + message: `مقدار وارده باید بیشتر از (${start}) باشد`, + }); + } else if ((start && !end) || (!start && end)) { + return ctx.createError({ + message: "این بخش را تکمیل نمایید", + }); + } + return true; + }, + }), + }); + } + return acc; + }, {}) + ); + + setValidationSchema(schema); + }, [filterData]); + + const { + handleSubmit, + control, + reset, + formState: { errors, isDirty, isValid }, + } = useForm({ + defaultValues: filterData, + resolver: yupResolver(validationSchema), + mode: "all", + }); + + const onSubmit = (data) => { + setDrawerState(false); + setFilterData(data); + }; + + return ( + <> + + {Object.keys(filterData).length > 0 && ( + +
    + + {columns.map((column) => + column.enableColumnFilter ? ( + column.dependencyId ? ( + + ) : ( + + ) + ) : null + )} + + + + +
    +
    + )} + + ); +} + +export default FilterBody; diff --git a/src/core/components/DataTable/filter/FilterBodyController.jsx b/src/core/components/DataTable/filter/FilterBodyController.jsx index 40ccdf7..28238b3 100644 --- a/src/core/components/DataTable/filter/FilterBodyController.jsx +++ b/src/core/components/DataTable/filter/FilterBodyController.jsx @@ -1,25 +1,25 @@ -import { Controller, useWatch } from "react-hook-form"; -import FilterBodyField from "./FilterBodyField"; - -const FilterBodyController = ({ column, control, reset, errors }) => { - return ( - { - return ( - reset()} - errors={errors} - /> - ); - }} - /> - ); -}; -export default FilterBodyController; +import { Controller, useWatch } from "react-hook-form"; +import FilterBodyField from "./FilterBodyField"; + +const FilterBodyController = ({ column, control, reset, errors }) => { + return ( + { + return ( + reset()} + errors={errors} + /> + ); + }} + /> + ); +}; +export default FilterBodyController; diff --git a/src/core/components/DataTable/filter/FilterBodyControllerWithDependency.jsx b/src/core/components/DataTable/filter/FilterBodyControllerWithDependency.jsx index f531c48..a8a829e 100644 --- a/src/core/components/DataTable/filter/FilterBodyControllerWithDependency.jsx +++ b/src/core/components/DataTable/filter/FilterBodyControllerWithDependency.jsx @@ -1,27 +1,27 @@ -import { Controller, useWatch } from "react-hook-form"; -import FilterBodyField from "./FilterBodyField"; - -const FilterBodyControllerWithDependency = ({ column, control, reset, errors }) => { - const dependencyField = useWatch({ control, name: column.dependencyId }); - - return ( - { - return ( - reset()} - errors={errors} - /> - ); - }} - /> - ); -}; -export default FilterBodyControllerWithDependency; +import { Controller, useWatch } from "react-hook-form"; +import FilterBodyField from "./FilterBodyField"; + +const FilterBodyControllerWithDependency = ({ column, control, reset, errors }) => { + const dependencyField = useWatch({ control, name: column.dependencyId }); + + return ( + { + return ( + reset()} + errors={errors} + /> + ); + }} + /> + ); +}; +export default FilterBodyControllerWithDependency; diff --git a/src/core/components/DataTable/filter/FilterBodyField.jsx b/src/core/components/DataTable/filter/FilterBodyField.jsx index 869c354..401a67d 100644 --- a/src/core/components/DataTable/filter/FilterBodyField.jsx +++ b/src/core/components/DataTable/filter/FilterBodyField.jsx @@ -1,104 +1,104 @@ -import FilterOptionList from "@/core/components/DataTable/filter/FilterOptionList"; -import CustomDatePicker from "@/core/components/DataTable/filter/fieldsType/CustomDate/CustomDatePicker"; -import CustomDatePickerRange from "@/core/components/DataTable/filter/fieldsType/CustomDate/CustomDatePickerRange"; -import CustomSelect from "@/core/components/DataTable/filter/fieldsType/CustomSelect"; -import CustomSelectMultiple from "@/core/components/DataTable/filter/fieldsType/CustomSelectMultiple"; -import CustomTextField from "@/core/components/DataTable/filter/fieldsType/CustomTextField"; -import CustomTextFieldRange from "@/core/components/DataTable/filter/fieldsType/CustomTextFieldRange"; -import { useState } from "react"; - -const columnFilterModeOptionFa = { - equals: "برابر", - notEquals: "نابرابر", - contains: "شامل", - lessThan: "کوچکتر", - greaterThan: "بزرگتر", - fuzzy: "فازی", - between: "مابین", -}; - -function FilterBodyField({ - column, - filterParameters, - handleChange, - handleBlur, - dependencyFieldValue, - setFieldValue, - resetForm, - errors, -}) { - const [anchorEl, setAnchorEl] = useState(null); - const defaultFilterTranslation = - columnFilterModeOptionFa[filterParameters.filterMode] || filterParameters.filterMode; - - const handleOpenFilterBox = (event) => { - setAnchorEl(event.currentTarget); - }; - - const renderField = () => { - const commonProps = { - column, - filterParameters, - defaultFilterTranslation, - handleOpenFilterBox, - dependencyFieldValue, - setFieldValue, - handleChange, - handleBlur, - errors, - }; - - switch (filterParameters.datatype) { - case "numeric": - if (filterParameters.filterMode === "between") { - return ; - } - if (filterParameters.filterMode === "equals") { - return column.ColumnSelectComponent ? ( - - ) : ( - - ); - } - break; - case "date": - if (filterParameters.filterMode === "equals") { - return ; - } - if (filterParameters.filterMode === "between") { - return ; - } - break; - - case "array": - if (filterParameters.filterMode === "equals") { - return ; - } - break; - - default: - return ; - } - }; - - return ( - <> - {renderField()} - {Array.isArray(column.columnFilterModeOptions) && ( - - )} - - ); -} - -export default FilterBodyField; +import FilterOptionList from "@/core/components/DataTable/filter/FilterOptionList"; +import CustomDatePicker from "@/core/components/DataTable/filter/fieldsType/CustomDate/CustomDatePicker"; +import CustomDatePickerRange from "@/core/components/DataTable/filter/fieldsType/CustomDate/CustomDatePickerRange"; +import CustomSelect from "@/core/components/DataTable/filter/fieldsType/CustomSelect"; +import CustomSelectMultiple from "@/core/components/DataTable/filter/fieldsType/CustomSelectMultiple"; +import CustomTextField from "@/core/components/DataTable/filter/fieldsType/CustomTextField"; +import CustomTextFieldRange from "@/core/components/DataTable/filter/fieldsType/CustomTextFieldRange"; +import { useState } from "react"; + +const columnFilterModeOptionFa = { + equals: "برابر", + notEquals: "نابرابر", + contains: "شامل", + lessThan: "کوچکتر", + greaterThan: "بزرگتر", + fuzzy: "فازی", + between: "مابین", +}; + +function FilterBodyField({ + column, + filterParameters, + handleChange, + handleBlur, + dependencyFieldValue, + setFieldValue, + resetForm, + errors, +}) { + const [anchorEl, setAnchorEl] = useState(null); + const defaultFilterTranslation = + columnFilterModeOptionFa[filterParameters.filterMode] || filterParameters.filterMode; + + const handleOpenFilterBox = (event) => { + setAnchorEl(event.currentTarget); + }; + + const renderField = () => { + const commonProps = { + column, + filterParameters, + defaultFilterTranslation, + handleOpenFilterBox, + dependencyFieldValue, + setFieldValue, + handleChange, + handleBlur, + errors, + }; + + switch (filterParameters.datatype) { + case "numeric": + if (filterParameters.filterMode === "between") { + return ; + } + if (filterParameters.filterMode === "equals") { + return column.ColumnSelectComponent ? ( + + ) : ( + + ); + } + break; + case "date": + if (filterParameters.filterMode === "equals") { + return ; + } + if (filterParameters.filterMode === "between") { + return ; + } + break; + + case "array": + if (filterParameters.filterMode === "equals") { + return ; + } + break; + + default: + return ; + } + }; + + return ( + <> + {renderField()} + {Array.isArray(column.columnFilterModeOptions) && ( + + )} + + ); +} + +export default FilterBodyField; diff --git a/src/core/components/DataTable/filter/FilterButton.jsx b/src/core/components/DataTable/filter/FilterButton.jsx index 79cc879..625d12f 100644 --- a/src/core/components/DataTable/filter/FilterButton.jsx +++ b/src/core/components/DataTable/filter/FilterButton.jsx @@ -1,37 +1,37 @@ -"use client"; -import FilterAltIcon from "@mui/icons-material/FilterAlt"; -import { IconButton, Tooltip, Badge } from "@mui/material"; -import useDataTable from "@/lib/hooks/useDataTable"; - -function FilterButton({ drawerState, setDrawerState }) { - const { filterData } = useDataTable(); - const isValueEmpty = (value) => { - if (Array.isArray(value)) { - return value.length === 0 || value.every((v) => v === ""); - } - return value === "" || value === null || value === undefined; - }; - const filteredFilterData = Object.values(filterData).filter((filter) => !isValueEmpty(filter.value)); - return ( - - { - setDrawerState(!drawerState); - }} - aria-label="filter table" - > - - - - - - ); -} -export default FilterButton; +"use client"; +import FilterAltIcon from "@mui/icons-material/FilterAlt"; +import { IconButton, Tooltip, Badge } from "@mui/material"; +import useDataTable from "@/lib/hooks/useDataTable"; + +function FilterButton({ drawerState, setDrawerState }) { + const { filterData } = useDataTable(); + const isValueEmpty = (value) => { + if (Array.isArray(value)) { + return value.length === 0 || value.every((v) => v === ""); + } + return value === "" || value === null || value === undefined; + }; + const filteredFilterData = Object.values(filterData).filter((filter) => !isValueEmpty(filter.value)); + return ( + + { + setDrawerState(!drawerState); + }} + aria-label="filter table" + > + + + + + + ); +} +export default FilterButton; diff --git a/src/core/components/DataTable/filter/FilterCustom.jsx b/src/core/components/DataTable/filter/FilterCustom.jsx index f8d43f3..5589f61 100644 --- a/src/core/components/DataTable/filter/FilterCustom.jsx +++ b/src/core/components/DataTable/filter/FilterCustom.jsx @@ -1,32 +1,32 @@ -import { useCallback, useState } from "react"; -import FilterButton from "./FilterButton"; -import { Box, Drawer } from "@mui/material"; -import FilterDrawer from "../../FilterDrawer"; - -const FilterCustom = ({ filterData, setFilterData }) => { - const [open, setOpen] = useState(false); - - const closeDrawer = useCallback(() => setOpen(false), []); - - return ( - <> - - setOpen(false)} - sx={{ overflowY: "hidden", display: "flex", flexDirection: "column", height: "100%", zIndex: "1300" }} - > - - {open && ( - - )} - - - - ); -}; -export default FilterCustom; +import { useCallback, useState } from "react"; +import FilterButton from "./FilterButton"; +import { Box, Drawer } from "@mui/material"; +import FilterDrawer from "../../FilterDrawer"; + +const FilterCustom = ({ filterData, setFilterData }) => { + const [open, setOpen] = useState(false); + + const closeDrawer = useCallback(() => setOpen(false), []); + + return ( + <> + + setOpen(false)} + sx={{ overflowY: "hidden", display: "flex", flexDirection: "column", height: "100%", zIndex: "1300" }} + > + + {open && ( + + )} + + + + ); +}; +export default FilterCustom; diff --git a/src/core/components/DataTable/filter/FilterHeader.jsx b/src/core/components/DataTable/filter/FilterHeader.jsx index c7b01b5..bf63ffe 100644 --- a/src/core/components/DataTable/filter/FilterHeader.jsx +++ b/src/core/components/DataTable/filter/FilterHeader.jsx @@ -1,34 +1,34 @@ -"use client"; - -import CancelIcon from "@mui/icons-material/Cancel"; -import FilterAltIcon from "@mui/icons-material/FilterAlt"; -import { Box, IconButton, Typography } from "@mui/material"; - -function FilterHeader({ setDrawerState }) { - return ( - - - - - فیلتر - - - setDrawerState(false)}> - - - - ); -} - -export default FilterHeader; +"use client"; + +import CancelIcon from "@mui/icons-material/Cancel"; +import FilterAltIcon from "@mui/icons-material/FilterAlt"; +import { Box, IconButton, Typography } from "@mui/material"; + +function FilterHeader({ setDrawerState }) { + return ( + + + + + فیلتر + + + setDrawerState(false)}> + + + + ); +} + +export default FilterHeader; diff --git a/src/core/components/DataTable/filter/FilterOptionList.jsx b/src/core/components/DataTable/filter/FilterOptionList.jsx index 9293107..358be23 100644 --- a/src/core/components/DataTable/filter/FilterOptionList.jsx +++ b/src/core/components/DataTable/filter/FilterOptionList.jsx @@ -1,47 +1,47 @@ -"use client"; - -import { ListItem, Menu } from "@mui/material"; -import { useState } from "react"; - -function FilterOptionList({ - filterType, - filterOption, - filterParameters, - anchorEl, - columnFilterModeOptionFa, - setAnchorEl, - handleChange, -}) { - const [selectedFilter, setSelectedFilter] = useState(filterType); - - const handleChangeItem = (event, index) => { - handleChange({ - ...filterParameters, - value: filterOption[index] === "between" ? ["", ""] : "", - filterMode: filterOption[index], - }); - setSelectedFilter(filterOption[index]); - setAnchorEl(null); - }; - - const handleCloseFilterBox = () => { - setAnchorEl(null); - }; - - return ( - - {filterOption.map((option, index) => ( - handleChangeItem(event, index)} - selected={option === selectedFilter} - sx={{ cursor: "pointer", width: "100px", display: "flex", justifyContent: "center" }} - > - {columnFilterModeOptionFa[option]} - - ))} - - ); -} - -export default FilterOptionList; +"use client"; + +import { ListItem, Menu } from "@mui/material"; +import { useState } from "react"; + +function FilterOptionList({ + filterType, + filterOption, + filterParameters, + anchorEl, + columnFilterModeOptionFa, + setAnchorEl, + handleChange, +}) { + const [selectedFilter, setSelectedFilter] = useState(filterType); + + const handleChangeItem = (event, index) => { + handleChange({ + ...filterParameters, + value: filterOption[index] === "between" ? ["", ""] : "", + filterMode: filterOption[index], + }); + setSelectedFilter(filterOption[index]); + setAnchorEl(null); + }; + + const handleCloseFilterBox = () => { + setAnchorEl(null); + }; + + return ( + + {filterOption.map((option, index) => ( + handleChangeItem(event, index)} + selected={option === selectedFilter} + sx={{ cursor: "pointer", width: "100px", display: "flex", justifyContent: "center" }} + > + {columnFilterModeOptionFa[option]} + + ))} + + ); +} + +export default FilterOptionList; diff --git a/src/core/components/DataTable/filter/fieldsType/CustomDate/CustomDatePicker.jsx b/src/core/components/DataTable/filter/fieldsType/CustomDate/CustomDatePicker.jsx index e207cfb..fb8d9fb 100644 --- a/src/core/components/DataTable/filter/fieldsType/CustomDate/CustomDatePicker.jsx +++ b/src/core/components/DataTable/filter/fieldsType/CustomDate/CustomDatePicker.jsx @@ -1,23 +1,23 @@ -import React from "react"; -import MuiDatePicker from "@/core/components/DataTable/filter/fieldsType/CustomDate/MuiDatePicker"; -import { Typography } from "@mui/material"; - -function CustomDatePicker({ column, filterParameters, defaultFilterTranslation, handleChange }) { - return ( - { - handleChange({ ...filterParameters, value: formattedDate }); - }} - placeholder={column.header} - helperText={ - - نوع فیلتر: {defaultFilterTranslation} (تاریخ) - - } - /> - ); -} - -export default CustomDatePicker; +import React from "react"; +import MuiDatePicker from "@/core/components/DataTable/filter/fieldsType/CustomDate/MuiDatePicker"; +import { Typography } from "@mui/material"; + +function CustomDatePicker({ column, filterParameters, defaultFilterTranslation, handleChange }) { + return ( + { + handleChange({ ...filterParameters, value: formattedDate }); + }} + placeholder={column.header} + helperText={ + + نوع فیلتر: {defaultFilterTranslation} (تاریخ) + + } + /> + ); +} + +export default CustomDatePicker; diff --git a/src/core/components/DataTable/filter/fieldsType/CustomDate/CustomDatePickerRange.jsx b/src/core/components/DataTable/filter/fieldsType/CustomDate/CustomDatePickerRange.jsx index 498c0a2..415b5c4 100644 --- a/src/core/components/DataTable/filter/fieldsType/CustomDate/CustomDatePickerRange.jsx +++ b/src/core/components/DataTable/filter/fieldsType/CustomDate/CustomDatePickerRange.jsx @@ -1,41 +1,41 @@ -"use client"; - -import React from "react"; -import { Box, Typography } from "@mui/material"; -import MuiDatePicker from "@/core/components/DataTable/filter/fieldsType/CustomDate/MuiDatePicker"; - -function CustomDatePickerRange({ column, filterParameters, defaultFilterTranslation, handleChange, errors }) { - return ( - - { - handleChange({ ...filterParameters, value: [formattedDate, filterParameters.value[1]] }); - }} - maxDate={filterParameters.value[1]} - placeholder={`از تاریخ`} - helperText={ - - نوع فیلتر: {defaultFilterTranslation} (تاریخ) - - } - /> - { - handleChange({ ...filterParameters, value: [filterParameters.value[0], formattedDate] }); - }} - minDate={filterParameters.value[0]} - placeholder={`تا تاریخ`} - helperText={errors?.[`${column.id}`]?.value ? errors?.[`${column.id}`]?.value.message : null} - error={Boolean(errors?.[`${column.id}`]?.value)} - /> - - ); -} - -export default CustomDatePickerRange; +"use client"; + +import React from "react"; +import { Box, Typography } from "@mui/material"; +import MuiDatePicker from "@/core/components/DataTable/filter/fieldsType/CustomDate/MuiDatePicker"; + +function CustomDatePickerRange({ column, filterParameters, defaultFilterTranslation, handleChange, errors }) { + return ( + + { + handleChange({ ...filterParameters, value: [formattedDate, filterParameters.value[1]] }); + }} + maxDate={filterParameters.value[1]} + placeholder={`از تاریخ`} + helperText={ + + نوع فیلتر: {defaultFilterTranslation} (تاریخ) + + } + /> + { + handleChange({ ...filterParameters, value: [filterParameters.value[0], formattedDate] }); + }} + minDate={filterParameters.value[0]} + placeholder={`تا تاریخ`} + helperText={errors?.[`${column.id}`]?.value ? errors?.[`${column.id}`]?.value.message : null} + error={Boolean(errors?.[`${column.id}`]?.value)} + /> + + ); +} + +export default CustomDatePickerRange; diff --git a/src/core/components/DataTable/filter/fieldsType/CustomDate/MuiDatePicker.jsx b/src/core/components/DataTable/filter/fieldsType/CustomDate/MuiDatePicker.jsx index d2d9df0..aa93528 100644 --- a/src/core/components/DataTable/filter/fieldsType/CustomDate/MuiDatePicker.jsx +++ b/src/core/components/DataTable/filter/fieldsType/CustomDate/MuiDatePicker.jsx @@ -1,72 +1,72 @@ -import React from "react"; -import { LocalizationProvider, MobileDatePicker } from "@mui/x-date-pickers"; -import { AdapterDateFnsJalali } from "@mui/x-date-pickers/AdapterDateFnsJalali"; -import { faIR } from "@mui/x-date-pickers/locales"; -import { Box, FormHelperText, IconButton, InputAdornment } from "@mui/material"; -import ClearIcon from "@mui/icons-material/Clear"; -import moment from "jalali-moment"; - -function MuiDatePicker({ label, value, setFieldValue, name, minDate, maxDate, helperText, placeholder, error }) { - return ( - - - { - const date = new Date(value); - const formattedDate = moment(date).locale("en").format("YYYY-MM-DD"); - setFieldValue(name, formattedDate); - }} - minDate={minDate ? new Date(minDate) : null} - maxDate={maxDate ? new Date(maxDate) : null} - slotProps={{ - textField: { - size: "small", - error: error, - placeholder: placeholder, - InputProps: { - endAdornment: ( - - { - event.stopPropagation(); - setFieldValue(name, ""); - }} - sx={{ - color: "#bfbfbf", - "&:hover": { - backgroundColor: "rgba(189, 189, 189, 0.1)", - color: "#363434", - }, - }} - > - - - - ), - }, - InputLabelProps: { - shrink: true, - }, - }, - }} - /> - {/* - {helperText ? helperText : ""} - */} - - - ); -} - -export default MuiDatePicker; +import React from "react"; +import { LocalizationProvider, MobileDatePicker } from "@mui/x-date-pickers"; +import { AdapterDateFnsJalali } from "@mui/x-date-pickers/AdapterDateFnsJalali"; +import { faIR } from "@mui/x-date-pickers/locales"; +import { Box, FormHelperText, IconButton, InputAdornment } from "@mui/material"; +import ClearIcon from "@mui/icons-material/Clear"; +import moment from "jalali-moment"; + +function MuiDatePicker({ label, value, setFieldValue, name, minDate, maxDate, helperText, placeholder, error }) { + return ( + + + { + const date = new Date(value); + const formattedDate = moment(date).locale("en").format("YYYY-MM-DD"); + setFieldValue(name, formattedDate); + }} + minDate={minDate ? new Date(minDate) : null} + maxDate={maxDate ? new Date(maxDate) : null} + slotProps={{ + textField: { + size: "small", + error: error, + placeholder: placeholder, + InputProps: { + endAdornment: ( + + { + event.stopPropagation(); + setFieldValue(name, ""); + }} + sx={{ + color: "#bfbfbf", + "&:hover": { + backgroundColor: "rgba(189, 189, 189, 0.1)", + color: "#363434", + }, + }} + > + + + + ), + }, + InputLabelProps: { + shrink: true, + }, + }, + }} + /> + {/* + {helperText ? helperText : ""} + */} + + + ); +} + +export default MuiDatePicker; diff --git a/src/core/components/DataTable/filter/fieldsType/CustomSelect.jsx b/src/core/components/DataTable/filter/fieldsType/CustomSelect.jsx index f008c5e..742fb46 100644 --- a/src/core/components/DataTable/filter/fieldsType/CustomSelect.jsx +++ b/src/core/components/DataTable/filter/fieldsType/CustomSelect.jsx @@ -1,30 +1,30 @@ -"use client"; - -import { FormControl, InputLabel, MenuItem, OutlinedInput, Select } from "@mui/material"; -function CustomSelect({ column, filterParameters, handleChange }) { - return ( - - - {column.header} - - - - ); -} - -export default CustomSelect; +"use client"; + +import { FormControl, InputLabel, MenuItem, OutlinedInput, Select } from "@mui/material"; +function CustomSelect({ column, filterParameters, handleChange }) { + return ( + + + {column.header} + + + + ); +} + +export default CustomSelect; diff --git a/src/core/components/DataTable/filter/fieldsType/CustomSelectByDependency.jsx b/src/core/components/DataTable/filter/fieldsType/CustomSelectByDependency.jsx index 5a1f2d3..1bae48e 100644 --- a/src/core/components/DataTable/filter/fieldsType/CustomSelectByDependency.jsx +++ b/src/core/components/DataTable/filter/fieldsType/CustomSelectByDependency.jsx @@ -1,44 +1,44 @@ -"use client"; - -import { FormControl, FormHelperText, InputLabel, MenuItem, OutlinedInput, Select, Typography } from "@mui/material"; -import { useCallback, useEffect } from "react"; - -function CustomSelectByDependency({ - column, - filterParameters, - value, - defaultFilterTranslation, - handleChange, - columnSelectOption, -}) { - return ( - - - {column.header} - - - {/* - - نوع فیلتر: {defaultFilterTranslation} - - */} - - ); -} - -export default CustomSelectByDependency; +"use client"; + +import { FormControl, FormHelperText, InputLabel, MenuItem, OutlinedInput, Select, Typography } from "@mui/material"; +import { useCallback, useEffect } from "react"; + +function CustomSelectByDependency({ + column, + filterParameters, + value, + defaultFilterTranslation, + handleChange, + columnSelectOption, +}) { + return ( + + + {column.header} + + + {/* + + نوع فیلتر: {defaultFilterTranslation} + + */} + + ); +} + +export default CustomSelectByDependency; diff --git a/src/core/components/DataTable/filter/fieldsType/CustomSelectMultiple.jsx b/src/core/components/DataTable/filter/fieldsType/CustomSelectMultiple.jsx index 8ee2695..0147627 100644 --- a/src/core/components/DataTable/filter/fieldsType/CustomSelectMultiple.jsx +++ b/src/core/components/DataTable/filter/fieldsType/CustomSelectMultiple.jsx @@ -1,60 +1,60 @@ -"use client"; - -import { - Box, - Chip, - FormControl, - FormHelperText, - InputLabel, - MenuItem, - OutlinedInput, - Select, - Typography, -} from "@mui/material"; - -function CustomSelectMultiple({ column, filterParameters, defaultFilterTranslation, handleChange }) { - const columnSelectOption = column.columnSelectOption; - - const getLabelForValue = (value) => { - const option = columnSelectOption.find((opt) => opt.value === value); - return option ? option.label : value; - }; - - return ( - - - {column.header} - - - {/* - - نوع فیلتر: {defaultFilterTranslation} - - */} - - ); -} - -export default CustomSelectMultiple; +"use client"; + +import { + Box, + Chip, + FormControl, + FormHelperText, + InputLabel, + MenuItem, + OutlinedInput, + Select, + Typography, +} from "@mui/material"; + +function CustomSelectMultiple({ column, filterParameters, defaultFilterTranslation, handleChange }) { + const columnSelectOption = column.columnSelectOption; + + const getLabelForValue = (value) => { + const option = columnSelectOption.find((opt) => opt.value === value); + return option ? option.label : value; + }; + + return ( + + + {column.header} + + + {/* + + نوع فیلتر: {defaultFilterTranslation} + + */} + + ); +} + +export default CustomSelectMultiple; diff --git a/src/core/components/DataTable/filter/fieldsType/CustomTextField.jsx b/src/core/components/DataTable/filter/fieldsType/CustomTextField.jsx index c69105d..b8a3a27 100644 --- a/src/core/components/DataTable/filter/fieldsType/CustomTextField.jsx +++ b/src/core/components/DataTable/filter/fieldsType/CustomTextField.jsx @@ -1,41 +1,41 @@ -import { InputAdornment, TextField, Typography } from "@mui/material"; -import FilterListIcon from "@mui/icons-material/FilterList"; - -function CustomTextField({ - column, - defaultFilterTranslation, - filterParameters, - handleOpenFilterBox, - handleBlur, - handleChange, -}) { - return ( - handleChange({ ...filterParameters, value: e.target.value })} - onBlur={handleBlur} - fullWidth - // helperText={ - // - // نوع فیلتر: {defaultFilterTranslation} - // - // } - variant="outlined" - size="small" - sx={{ my: 1 }} - InputProps={{ - endAdornment: ( - - - - ), - }} - InputLabelProps={{ shrink: true }} - /> - ); -} - -export default CustomTextField; +import { InputAdornment, TextField, Typography } from "@mui/material"; +import FilterListIcon from "@mui/icons-material/FilterList"; + +function CustomTextField({ + column, + defaultFilterTranslation, + filterParameters, + handleOpenFilterBox, + handleBlur, + handleChange, +}) { + return ( + handleChange({ ...filterParameters, value: e.target.value })} + onBlur={handleBlur} + fullWidth + // helperText={ + // + // نوع فیلتر: {defaultFilterTranslation} + // + // } + variant="outlined" + size="small" + sx={{ my: 1 }} + InputProps={{ + endAdornment: ( + + + + ), + }} + InputLabelProps={{ shrink: true }} + /> + ); +} + +export default CustomTextField; diff --git a/src/core/components/DataTable/filter/fieldsType/CustomTextFieldRange.jsx b/src/core/components/DataTable/filter/fieldsType/CustomTextFieldRange.jsx index 57a2dc3..68407af 100644 --- a/src/core/components/DataTable/filter/fieldsType/CustomTextFieldRange.jsx +++ b/src/core/components/DataTable/filter/fieldsType/CustomTextFieldRange.jsx @@ -1,62 +1,62 @@ -import { Box, InputAdornment, TextField, Typography } from "@mui/material"; -import FilterListIcon from "@mui/icons-material/FilterList"; - -function CustomTextFieldRange({ - column, - defaultFilterTranslation, - handleOpenFilterBox, - handleChange, - filterParameters, - handleBlur, - errors, -}) { - return ( - - - handleChange({ ...filterParameters, value: [e.target.value, filterParameters.value[1]] }) - } - onBlur={handleBlur} - label={از {column.header}} - value={filterParameters.value[0]} - fullWidth - error={touched?.[`${column.id}`]?.value && Boolean(errors?.[`${column.id}`]?.value)} - helperText={ - - نوع فیلتر: {defaultFilterTranslation} - - } - variant="outlined" - size="small" - sx={{ my: 1, marginRight: 1 }} - /> - - handleChange({ ...filterParameters, value: [filterParameters.value[0], e.target.value] }) - } - onBlur={handleBlur} - error={Boolean(errors?.[`${column.id}`]?.value)} - helperText={errors?.[`${column.id}`]?.value ? errors?.[`${column.id}`]?.value.message : null} - label={تا {column.header}} - value={filterParameters.value[1]} - fullWidth - variant="outlined" - size="small" - sx={{ my: 1 }} - InputProps={{ - endAdornment: ( - - - - ), - }} - /> - - ); -} - -export default CustomTextFieldRange; +import { Box, InputAdornment, TextField, Typography } from "@mui/material"; +import FilterListIcon from "@mui/icons-material/FilterList"; + +function CustomTextFieldRange({ + column, + defaultFilterTranslation, + handleOpenFilterBox, + handleChange, + filterParameters, + handleBlur, + errors, +}) { + return ( + + + handleChange({ ...filterParameters, value: [e.target.value, filterParameters.value[1]] }) + } + onBlur={handleBlur} + label={از {column.header}} + value={filterParameters.value[0]} + fullWidth + error={touched?.[`${column.id}`]?.value && Boolean(errors?.[`${column.id}`]?.value)} + helperText={ + + نوع فیلتر: {defaultFilterTranslation} + + } + variant="outlined" + size="small" + sx={{ my: 1, marginRight: 1 }} + /> + + handleChange({ ...filterParameters, value: [filterParameters.value[0], e.target.value] }) + } + onBlur={handleBlur} + error={Boolean(errors?.[`${column.id}`]?.value)} + helperText={errors?.[`${column.id}`]?.value ? errors?.[`${column.id}`]?.value.message : null} + label={تا {column.header}} + value={filterParameters.value[1]} + fullWidth + variant="outlined" + size="small" + sx={{ my: 1 }} + InputProps={{ + endAdornment: ( + + + + ), + }} + /> + + ); +} + +export default CustomTextFieldRange; diff --git a/src/core/components/DataTable/filter/index.jsx b/src/core/components/DataTable/filter/index.jsx index 5885cb4..3d0b7a8 100644 --- a/src/core/components/DataTable/filter/index.jsx +++ b/src/core/components/DataTable/filter/index.jsx @@ -1,35 +1,35 @@ -"use client"; -import { useState } from "react"; -import FilterButton from "@/core/components/DataTable/filter/FilterButton"; -import FilterBody from "@/core/components/DataTable/filter/FilterBody"; -import { Box, Drawer } from "@mui/material"; - -function FilterColumn({ columns, user_id, page_name, table_name }) { - const [open, setOpen] = useState(false); - - return ( - <> - - setOpen(false)} - sx={{ overflowY: "hidden", display: "flex", flexDirection: "column", height: "100%", zIndex: "1300" }} - > - - {open && ( - - )} - - - - ); -} - -export default FilterColumn; +"use client"; +import { useState } from "react"; +import FilterButton from "@/core/components/DataTable/filter/FilterButton"; +import FilterBody from "@/core/components/DataTable/filter/FilterBody"; +import { Box, Drawer } from "@mui/material"; + +function FilterColumn({ columns, user_id, page_name, table_name }) { + const [open, setOpen] = useState(false); + + return ( + <> + + setOpen(false)} + sx={{ overflowY: "hidden", display: "flex", flexDirection: "column", height: "100%", zIndex: "1300" }} + > + + {open && ( + + )} + + + + ); +} + +export default FilterColumn; diff --git a/src/core/components/DataTable/head/TableHead.js b/src/core/components/DataTable/head/TableHead.js index 39ee214..aa12bb0 100644 --- a/src/core/components/DataTable/head/TableHead.js +++ b/src/core/components/DataTable/head/TableHead.js @@ -1,51 +1,51 @@ -import { parseFromValuesOrFunc } from "@/core/utils/utils"; -import { TableHead } from "@mui/material"; -import DataTable_TableHeadRow from "./TableHeadRow"; - -const DataTable_TableHead = ({ columnVirtualizer, table, ...rest }) => { - const { - getState, - options: { enableStickyHeader, layoutMode, muiTableHeadProps, positionToolbarAlertBanner }, - refs: { tableHeadRef }, - } = table; - const { isFullScreen, showAlertBanner } = getState(); - - const tableHeadProps = { - ...parseFromValuesOrFunc(muiTableHeadProps, { table }), - ...rest, - }; - - const stickyHeader = enableStickyHeader || isFullScreen; - - return ( - { - tableHeadRef.current = ref; - if (tableHeadProps?.ref) { - // @ts-ignore - tableHeadProps.ref.current = ref; - } - }} - sx={(theme) => ({ - display: layoutMode?.startsWith("grid") ? "grid" : undefined, - opacity: 0.97, - position: stickyHeader ? "sticky" : "relative", - top: stickyHeader && layoutMode?.startsWith("grid") ? 0 : undefined, - zIndex: stickyHeader ? 2 : undefined, - ...parseFromValuesOrFunc(tableHeadProps?.sx, theme), - })} - > - {table.getHeaderGroups().map((headerGroup, index) => ( - - ))} - - ); -}; -export default DataTable_TableHead; +import { parseFromValuesOrFunc } from "@/core/utils/utils"; +import { TableHead } from "@mui/material"; +import DataTable_TableHeadRow from "./TableHeadRow"; + +const DataTable_TableHead = ({ columnVirtualizer, table, ...rest }) => { + const { + getState, + options: { enableStickyHeader, layoutMode, muiTableHeadProps, positionToolbarAlertBanner }, + refs: { tableHeadRef }, + } = table; + const { isFullScreen, showAlertBanner } = getState(); + + const tableHeadProps = { + ...parseFromValuesOrFunc(muiTableHeadProps, { table }), + ...rest, + }; + + const stickyHeader = enableStickyHeader || isFullScreen; + + return ( + { + tableHeadRef.current = ref; + if (tableHeadProps?.ref) { + // @ts-ignore + tableHeadProps.ref.current = ref; + } + }} + sx={(theme) => ({ + display: layoutMode?.startsWith("grid") ? "grid" : undefined, + opacity: 0.97, + position: stickyHeader ? "sticky" : "relative", + top: stickyHeader && layoutMode?.startsWith("grid") ? 0 : undefined, + zIndex: stickyHeader ? 2 : undefined, + ...parseFromValuesOrFunc(tableHeadProps?.sx, theme), + })} + > + {table.getHeaderGroups().map((headerGroup, index) => ( + + ))} + + ); +}; +export default DataTable_TableHead; diff --git a/src/core/components/DataTable/head/TableHeadCell.js b/src/core/components/DataTable/head/TableHeadCell.js index 631a122..471ced5 100644 --- a/src/core/components/DataTable/head/TableHeadCell.js +++ b/src/core/components/DataTable/head/TableHeadCell.js @@ -1,244 +1,244 @@ -import { getCommonMRTCellStyles, parseFromValuesOrFunc } from "@/core/utils/utils"; -import { useTheme } from "@emotion/react"; -import { Box, TableCell } from "@mui/material"; -import { MRT_TableHeadCellSortLabel } from "material-react-table"; -import { useMemo } from "react"; - -const DataTable_TableHeadCell = ({ columnVirtualizer, header, staticColumnIndex, backgroundColor, table, ...rest }) => { - const theme = useTheme(); - const { - getState, - options: { - columnResizeDirection, - columnResizeMode, - enableColumnActions, - enableColumnDragging, - enableColumnOrdering, - enableColumnPinning, - enableGrouping, - enableMultiSort, - layoutMode, - mrtTheme: { draggingBorderColor }, - muiTableHeadCellProps, - }, - refs: { tableHeadCellRefs }, - setHoveredColumn, - } = table; - const { columnSizingInfo, density, draggingColumn, grouping, hoveredColumn, showColumnFilters } = getState(); - const { column } = header; - const { columnDef } = column; - const { columnDefType } = columnDef; - - const tableCellProps = { - ...parseFromValuesOrFunc(muiTableHeadCellProps, { column, table }), - ...parseFromValuesOrFunc(columnDef.muiTableHeadCellProps, { - column, - table, - }), - ...rest, - }; - - const isColumnPinned = enableColumnPinning && columnDef.columnDefType !== "group" && column.getIsPinned(); - - const showColumnActions = - (enableColumnActions || columnDef.enableColumnActions) && columnDef.enableColumnActions !== false; - - const showDragHandle = - enableColumnDragging !== false && - columnDef.enableColumnDragging !== false && - (enableColumnDragging || - (enableColumnOrdering && columnDef.enableColumnOrdering !== false) || - (enableGrouping && columnDef.enableGrouping !== false && !grouping.includes(column.id))); - - const headerPL = useMemo(() => { - let pl = 0; - if (column.getCanSort()) pl += 1; - if (showColumnActions) pl += 1.75; - if (showDragHandle) pl += 1.5; - return pl; - }, [showColumnActions, showDragHandle]); - - const draggingBorders = useMemo(() => { - const showResizeBorder = - columnSizingInfo.isResizingColumn === column.id && - columnResizeMode === "onChange" && - !header.subHeaders.length; - - const borderStyle = showResizeBorder - ? `2px solid ${draggingBorderColor} !important` - : draggingColumn?.id === column.id - ? `1px dashed ${theme.palette.grey[500]}` - : hoveredColumn?.id === column.id - ? `2px dashed ${draggingBorderColor}` - : undefined; - - if (showResizeBorder) { - return columnResizeDirection === "ltr" ? { borderRight: borderStyle } : { borderLeft: borderStyle }; - } - const draggingBorders = borderStyle - ? { - borderLeft: borderStyle, - borderRight: borderStyle, - borderTop: borderStyle, - } - : undefined; - - return draggingBorders; - }, [draggingColumn, hoveredColumn, columnSizingInfo.isResizingColumn]); - - const handleDragEnter = (_e) => { - if (enableGrouping && hoveredColumn?.id === "drop-zone") { - setHoveredColumn(null); - } - if (enableColumnOrdering && draggingColumn && columnDefType !== "group") { - setHoveredColumn(columnDef.enableColumnOrdering !== false ? column : null); - } - }; - - const handleDragOver = (e) => { - if (columnDef.enableColumnOrdering !== false) { - e.preventDefault(); - } - }; - - const HeaderElement = - parseFromValuesOrFunc(columnDef.Header, { - column, - header, - table, - }) ?? columnDef.header; - - const columnRelativeDepth = header.depth - column.depth; - - if (columnRelativeDepth > 1) { - return null; - } - - let rowSpan = 1; - if (header.isPlaceholder) { - const leafs = header.getLeafHeaders(); - rowSpan = leafs[leafs.length - 1].depth - header.depth; - } - - return ( - { - if (node) { - tableHeadCellRefs.current[column.id] = node; - if (columnDefType !== "group") { - columnVirtualizer?.measureElement?.(node); - } - } - }} - {...tableCellProps} - sx={(theme) => ({ - "& :hover": { - ".MuiButtonBase-root": { - opacity: 1, - }, - }, - flexDirection: layoutMode?.startsWith("grid") ? "column" : undefined, - fontWeight: "bold", - overflow: "visible", - p: - density === "compact" - ? "0.5rem" - : density === "comfortable" - ? columnDefType === "display" - ? "0.75rem" - : "1rem" - : columnDefType === "display" - ? "1rem 1.25rem" - : "1.5rem", - pb: columnDefType === "display" ? 0 : showColumnFilters || density === "compact" ? "0.4rem" : "0.6rem", - pt: - columnDefType === "group" || density === "compact" - ? "0.25rem" - : density === "comfortable" - ? ".75rem" - : "1.25rem", - userSelect: enableMultiSort && column.getCanSort() ? "none" : undefined, - verticalAlign: "middle", - ...getCommonMRTCellStyles({ - column, - header, - table, - tableCellProps, - theme, - }), - ...draggingBorders, - backgroundColor: backgroundColor, - })} - > - {tableCellProps.children ?? ( - - - - {HeaderElement} - - {column.getCanSort() && columnDefType !== "group" && ( - - )} - - - )} - - ); -}; -export default DataTable_TableHeadCell; +import { getCommonMRTCellStyles, parseFromValuesOrFunc } from "@/core/utils/utils"; +import { useTheme } from "@emotion/react"; +import { Box, TableCell } from "@mui/material"; +import { MRT_TableHeadCellSortLabel } from "material-react-table"; +import { useMemo } from "react"; + +const DataTable_TableHeadCell = ({ columnVirtualizer, header, staticColumnIndex, backgroundColor, table, ...rest }) => { + const theme = useTheme(); + const { + getState, + options: { + columnResizeDirection, + columnResizeMode, + enableColumnActions, + enableColumnDragging, + enableColumnOrdering, + enableColumnPinning, + enableGrouping, + enableMultiSort, + layoutMode, + mrtTheme: { draggingBorderColor }, + muiTableHeadCellProps, + }, + refs: { tableHeadCellRefs }, + setHoveredColumn, + } = table; + const { columnSizingInfo, density, draggingColumn, grouping, hoveredColumn, showColumnFilters } = getState(); + const { column } = header; + const { columnDef } = column; + const { columnDefType } = columnDef; + + const tableCellProps = { + ...parseFromValuesOrFunc(muiTableHeadCellProps, { column, table }), + ...parseFromValuesOrFunc(columnDef.muiTableHeadCellProps, { + column, + table, + }), + ...rest, + }; + + const isColumnPinned = enableColumnPinning && columnDef.columnDefType !== "group" && column.getIsPinned(); + + const showColumnActions = + (enableColumnActions || columnDef.enableColumnActions) && columnDef.enableColumnActions !== false; + + const showDragHandle = + enableColumnDragging !== false && + columnDef.enableColumnDragging !== false && + (enableColumnDragging || + (enableColumnOrdering && columnDef.enableColumnOrdering !== false) || + (enableGrouping && columnDef.enableGrouping !== false && !grouping.includes(column.id))); + + const headerPL = useMemo(() => { + let pl = 0; + if (column.getCanSort()) pl += 1; + if (showColumnActions) pl += 1.75; + if (showDragHandle) pl += 1.5; + return pl; + }, [showColumnActions, showDragHandle]); + + const draggingBorders = useMemo(() => { + const showResizeBorder = + columnSizingInfo.isResizingColumn === column.id && + columnResizeMode === "onChange" && + !header.subHeaders.length; + + const borderStyle = showResizeBorder + ? `2px solid ${draggingBorderColor} !important` + : draggingColumn?.id === column.id + ? `1px dashed ${theme.palette.grey[500]}` + : hoveredColumn?.id === column.id + ? `2px dashed ${draggingBorderColor}` + : undefined; + + if (showResizeBorder) { + return columnResizeDirection === "ltr" ? { borderRight: borderStyle } : { borderLeft: borderStyle }; + } + const draggingBorders = borderStyle + ? { + borderLeft: borderStyle, + borderRight: borderStyle, + borderTop: borderStyle, + } + : undefined; + + return draggingBorders; + }, [draggingColumn, hoveredColumn, columnSizingInfo.isResizingColumn]); + + const handleDragEnter = (_e) => { + if (enableGrouping && hoveredColumn?.id === "drop-zone") { + setHoveredColumn(null); + } + if (enableColumnOrdering && draggingColumn && columnDefType !== "group") { + setHoveredColumn(columnDef.enableColumnOrdering !== false ? column : null); + } + }; + + const handleDragOver = (e) => { + if (columnDef.enableColumnOrdering !== false) { + e.preventDefault(); + } + }; + + const HeaderElement = + parseFromValuesOrFunc(columnDef.Header, { + column, + header, + table, + }) ?? columnDef.header; + + const columnRelativeDepth = header.depth - column.depth; + + if (columnRelativeDepth > 1) { + return null; + } + + let rowSpan = 1; + if (header.isPlaceholder) { + const leafs = header.getLeafHeaders(); + rowSpan = leafs[leafs.length - 1].depth - header.depth; + } + + return ( + { + if (node) { + tableHeadCellRefs.current[column.id] = node; + if (columnDefType !== "group") { + columnVirtualizer?.measureElement?.(node); + } + } + }} + {...tableCellProps} + sx={(theme) => ({ + "& :hover": { + ".MuiButtonBase-root": { + opacity: 1, + }, + }, + flexDirection: layoutMode?.startsWith("grid") ? "column" : undefined, + fontWeight: "bold", + overflow: "visible", + p: + density === "compact" + ? "0.5rem" + : density === "comfortable" + ? columnDefType === "display" + ? "0.75rem" + : "1rem" + : columnDefType === "display" + ? "1rem 1.25rem" + : "1.5rem", + pb: columnDefType === "display" ? 0 : showColumnFilters || density === "compact" ? "0.4rem" : "0.6rem", + pt: + columnDefType === "group" || density === "compact" + ? "0.25rem" + : density === "comfortable" + ? ".75rem" + : "1.25rem", + userSelect: enableMultiSort && column.getCanSort() ? "none" : undefined, + verticalAlign: "middle", + ...getCommonMRTCellStyles({ + column, + header, + table, + tableCellProps, + theme, + }), + ...draggingBorders, + backgroundColor: backgroundColor, + })} + > + {tableCellProps.children ?? ( + + + + {HeaderElement} + + {column.getCanSort() && columnDefType !== "group" && ( + + )} + + + )} + + ); +}; +export default DataTable_TableHeadCell; diff --git a/src/core/components/DataTable/head/TableHeadRow.js b/src/core/components/DataTable/head/TableHeadRow.js index c639ee8..eb21a8d 100644 --- a/src/core/components/DataTable/head/TableHeadRow.js +++ b/src/core/components/DataTable/head/TableHeadRow.js @@ -1,58 +1,58 @@ -import { parseFromValuesOrFunc } from "@/core/utils/utils"; -import { TableRow } from "@mui/material"; -import DataTable_TableHeadCell from "./TableHeadCell"; - -const DataTable_TableHeadRow = ({ - columnVirtualizer, - headerGroup, - table, - index, // Add index prop - ...rest -}) => { - const { - options: { enableStickyHeader, layoutMode, muiTableHeadRowProps }, - } = table; - const { virtualColumns, virtualPaddingLeft, virtualPaddingRight } = columnVirtualizer ?? {}; - - const backgroundColor = index % 2 === 0 ? "#015688" : "#ff5c0f"; - - const tableRowProps = { - ...parseFromValuesOrFunc(muiTableHeadRowProps, { - headerGroup, - table, - }), - ...rest, - sx: (theme) => ({ - // Access theme from the sx function - ...(parseFromValuesOrFunc(muiTableHeadRowProps?.sx, theme) || {}), - display: layoutMode?.startsWith("grid") ? "flex" : undefined, - position: enableStickyHeader && layoutMode === "semantic" ? "sticky" : "relative", - top: 0, - }), - }; - - return ( - - {virtualPaddingLeft && } - {(virtualColumns ?? headerGroup.headers).map((headerOrVirtualHeader, staticColumnIndex) => { - const header = columnVirtualizer - ? headerGroup.headers[headerOrVirtualHeader.index] - : headerOrVirtualHeader; - - return header ? ( - - ) : null; - })} - {virtualPaddingRight && } - - ); -}; - -export default DataTable_TableHeadRow; +import { parseFromValuesOrFunc } from "@/core/utils/utils"; +import { TableRow } from "@mui/material"; +import DataTable_TableHeadCell from "./TableHeadCell"; + +const DataTable_TableHeadRow = ({ + columnVirtualizer, + headerGroup, + table, + index, // Add index prop + ...rest +}) => { + const { + options: { enableStickyHeader, layoutMode, muiTableHeadRowProps }, + } = table; + const { virtualColumns, virtualPaddingLeft, virtualPaddingRight } = columnVirtualizer ?? {}; + + const backgroundColor = index % 2 === 0 ? "#015688" : "#ff5c0f"; + + const tableRowProps = { + ...parseFromValuesOrFunc(muiTableHeadRowProps, { + headerGroup, + table, + }), + ...rest, + sx: (theme) => ({ + // Access theme from the sx function + ...(parseFromValuesOrFunc(muiTableHeadRowProps?.sx, theme) || {}), + display: layoutMode?.startsWith("grid") ? "flex" : undefined, + position: enableStickyHeader && layoutMode === "semantic" ? "sticky" : "relative", + top: 0, + }), + }; + + return ( + + {virtualPaddingLeft && } + {(virtualColumns ?? headerGroup.headers).map((headerOrVirtualHeader, staticColumnIndex) => { + const header = columnVirtualizer + ? headerGroup.headers[headerOrVirtualHeader.index] + : headerOrVirtualHeader; + + return header ? ( + + ) : null; + })} + {virtualPaddingRight && } + + ); +}; + +export default DataTable_TableHeadRow; diff --git a/src/core/components/DataTable/hide/HideBody.jsx b/src/core/components/DataTable/hide/HideBody.jsx index 8d34ea4..2ba3208 100644 --- a/src/core/components/DataTable/hide/HideBody.jsx +++ b/src/core/components/DataTable/hide/HideBody.jsx @@ -1,48 +1,48 @@ -"use client"; - -import { Box, Drawer, styled } from "@mui/material"; -import HideBodyField from "@/core/components/DataTable/hide/HideBodyField"; -import HideHeader from "@/core/components/DataTable/hide/HideHeader"; -import useDataTable from "@/lib/hooks/useDataTable"; -import HideOrShowAll from "@/core/components/DataTable/hide/HideOrShowAll"; - -const ScrollBox = styled(Box)({ - flexGrow: 1, - overflowY: "scroll", - maxWidth: "450px", - "::-webkit-scrollbar": { - width: "5px", - }, - "::-webkit-scrollbar-track": { - boxShadow: "inset 0 0 5px #fff", - borderRadius: "5px", - }, - "::-webkit-scrollbar-thumb": { - background: "#155175", - borderRadius: "0px", - }, -}); - -function HideBody({ columns, drawerState, setDrawerState }) { - const { hideData, setHideData } = useDataTable(); - - return ( - setDrawerState(false)} - sx={{ overflowY: "hidden", display: "flex", flexDirection: "column", height: "100%", zIndex: "1300" }} - > - - - - - {columns.map((column) => ( - - ))} - - - - ); -} - -export default HideBody; +"use client"; + +import { Box, Drawer, styled } from "@mui/material"; +import HideBodyField from "@/core/components/DataTable/hide/HideBodyField"; +import HideHeader from "@/core/components/DataTable/hide/HideHeader"; +import useDataTable from "@/lib/hooks/useDataTable"; +import HideOrShowAll from "@/core/components/DataTable/hide/HideOrShowAll"; + +const ScrollBox = styled(Box)({ + flexGrow: 1, + overflowY: "scroll", + maxWidth: "450px", + "::-webkit-scrollbar": { + width: "5px", + }, + "::-webkit-scrollbar-track": { + boxShadow: "inset 0 0 5px #fff", + borderRadius: "5px", + }, + "::-webkit-scrollbar-thumb": { + background: "#155175", + borderRadius: "0px", + }, +}); + +function HideBody({ columns, drawerState, setDrawerState }) { + const { hideData, setHideData } = useDataTable(); + + return ( + setDrawerState(false)} + sx={{ overflowY: "hidden", display: "flex", flexDirection: "column", height: "100%", zIndex: "1300" }} + > + + + + + {columns.map((column) => ( + + ))} + + + + ); +} + +export default HideBody; diff --git a/src/core/components/DataTable/hide/HideBodyField.jsx b/src/core/components/DataTable/hide/HideBodyField.jsx index 6b60966..81960cf 100644 --- a/src/core/components/DataTable/hide/HideBodyField.jsx +++ b/src/core/components/DataTable/hide/HideBodyField.jsx @@ -1,76 +1,76 @@ -import { alpha, Box, Checkbox, styled, Typography } from "@mui/material"; -import { SimpleTreeView } from "@mui/x-tree-view"; -import { TreeItem, treeItemClasses } from "@mui/x-tree-view/TreeItem"; - -const CustomTreeItem = styled(TreeItem)(({ theme }) => ({ - [`& .${treeItemClasses.content}`]: { - padding: theme.spacing(0.5, 0.5), - margin: theme.spacing(0.2, 0), - gap: 0, - }, - [`& .${treeItemClasses.iconContainer}`]: { - "& .close": { - opacity: 0.3, - }, - }, - [`& .${treeItemClasses.groupTransition}`]: { - marginLeft: 16, - paddingLeft: 16, - borderLeft: `1px dashed ${alpha(theme.palette.text.primary, 0.4)}`, - }, -})); - -function HideBodyField({ column, hideData, setHideData }) { - const handleCheckboxChange = () => { - setHideData((prevData) => { - const updateHideData = (data, id) => { - if (data.hasOwnProperty(id)) { - return { ...data, [id]: !data[id] }; - } - const updatedData = { ...data }; - for (const key in data) { - if (data[key] && typeof data[key] === "object") { - updatedData[key] = updateHideData(data[key], id); - } - } - return updatedData; - }; - - return updateHideData(prevData, column.id); - }); - }; - - const labelContent = (() => { - if (typeof hideData[column.id] === "boolean") { - return ( - - - {column.header} - - ); - } else { - return ( - - {column.header} - - ); - } - })(); - - return ( - - - {column.columns?.map((subColumn) => ( - - ))} - - - ); -} - -export default HideBodyField; +import { alpha, Box, Checkbox, styled, Typography } from "@mui/material"; +import { SimpleTreeView } from "@mui/x-tree-view"; +import { TreeItem, treeItemClasses } from "@mui/x-tree-view/TreeItem"; + +const CustomTreeItem = styled(TreeItem)(({ theme }) => ({ + [`& .${treeItemClasses.content}`]: { + padding: theme.spacing(0.5, 0.5), + margin: theme.spacing(0.2, 0), + gap: 0, + }, + [`& .${treeItemClasses.iconContainer}`]: { + "& .close": { + opacity: 0.3, + }, + }, + [`& .${treeItemClasses.groupTransition}`]: { + marginLeft: 16, + paddingLeft: 16, + borderLeft: `1px dashed ${alpha(theme.palette.text.primary, 0.4)}`, + }, +})); + +function HideBodyField({ column, hideData, setHideData }) { + const handleCheckboxChange = () => { + setHideData((prevData) => { + const updateHideData = (data, id) => { + if (data.hasOwnProperty(id)) { + return { ...data, [id]: !data[id] }; + } + const updatedData = { ...data }; + for (const key in data) { + if (data[key] && typeof data[key] === "object") { + updatedData[key] = updateHideData(data[key], id); + } + } + return updatedData; + }; + + return updateHideData(prevData, column.id); + }); + }; + + const labelContent = (() => { + if (typeof hideData[column.id] === "boolean") { + return ( + + + {column.header} + + ); + } else { + return ( + + {column.header} + + ); + } + })(); + + return ( + + + {column.columns?.map((subColumn) => ( + + ))} + + + ); +} + +export default HideBodyField; diff --git a/src/core/components/DataTable/hide/HideButton.jsx b/src/core/components/DataTable/hide/HideButton.jsx index fa93857..4b5a150 100644 --- a/src/core/components/DataTable/hide/HideButton.jsx +++ b/src/core/components/DataTable/hide/HideButton.jsx @@ -1,35 +1,35 @@ -"use client"; -import ViewColumnIcon from "@mui/icons-material/ViewColumn"; -import { IconButton, Tooltip, Badge } from "@mui/material"; -import useDataTable from "@/lib/hooks/useDataTable"; -import { flattenObjectOfObjects } from "@/core/utils/flattenObjectOfObjects"; - -function HideButton({ drawerState, setDrawerState }) { - const { hideData } = useDataTable(); - const flattenHideData = flattenObjectOfObjects(hideData); - const falseCount = Object.values(flattenHideData).filter((value) => value === false).length; - - return ( - - { - setDrawerState(!drawerState); - }} - aria-label="hide table column" - > - - - - - - ); -} - -export default HideButton; +"use client"; +import ViewColumnIcon from "@mui/icons-material/ViewColumn"; +import { IconButton, Tooltip, Badge } from "@mui/material"; +import useDataTable from "@/lib/hooks/useDataTable"; +import { flattenObjectOfObjects } from "@/core/utils/flattenObjectOfObjects"; + +function HideButton({ drawerState, setDrawerState }) { + const { hideData } = useDataTable(); + const flattenHideData = flattenObjectOfObjects(hideData); + const falseCount = Object.values(flattenHideData).filter((value) => value === false).length; + + return ( + + { + setDrawerState(!drawerState); + }} + aria-label="hide table column" + > + + + + + + ); +} + +export default HideButton; diff --git a/src/core/components/DataTable/hide/HideHeader.jsx b/src/core/components/DataTable/hide/HideHeader.jsx index 5adcf25..ce4c473 100644 --- a/src/core/components/DataTable/hide/HideHeader.jsx +++ b/src/core/components/DataTable/hide/HideHeader.jsx @@ -1,34 +1,34 @@ -"use client"; - -import { Box, IconButton, Typography } from "@mui/material"; -import CancelIcon from "@mui/icons-material/Cancel"; -import ViewColumnIcon from "@mui/icons-material/ViewColumn"; - -function FilterHeader({ setDrawerState }) { - return ( - - - - - نمایش/مخفی کردن ستون ها - - - setDrawerState(false)}> - - - - ); -} - -export default FilterHeader; +"use client"; + +import { Box, IconButton, Typography } from "@mui/material"; +import CancelIcon from "@mui/icons-material/Cancel"; +import ViewColumnIcon from "@mui/icons-material/ViewColumn"; + +function FilterHeader({ setDrawerState }) { + return ( + + + + + نمایش/مخفی کردن ستون ها + + + setDrawerState(false)}> + + + + ); +} + +export default FilterHeader; diff --git a/src/core/components/DataTable/hide/HideOrShowAll.jsx b/src/core/components/DataTable/hide/HideOrShowAll.jsx index c0d2e8d..bc9771e 100644 --- a/src/core/components/DataTable/hide/HideOrShowAll.jsx +++ b/src/core/components/DataTable/hide/HideOrShowAll.jsx @@ -1,70 +1,70 @@ -"use client"; - -import { Box, Button } from "@mui/material"; -import VisibilityIcon from "@mui/icons-material/Visibility"; -import VisibilityOffIcon from "@mui/icons-material/VisibilityOff"; - -const setAllValues = (obj, value) => { - const result = {}; - for (const key in obj) { - if (typeof obj[key] === "object" && obj[key] !== null) { - result[key] = setAllValues(obj[key], value); - } else { - result[key] = value; - } - } - return result; -}; - -const allValuesAre = (obj, value) => { - for (const key in obj) { - if (typeof obj[key] === "object" && obj[key] !== null) { - if (!allValuesAre(obj[key], value)) { - return false; - } - } else if (obj[key] !== value) { - return false; - } - } - return true; -}; - -function HideOrShowAll({ hideData, setHideData }) { - const handleShowAll = () => { - const newHideData = setAllValues(hideData, true); - setHideData(newHideData); - }; - - const handleHideAll = () => { - const newHideData = setAllValues(hideData, false); - setHideData(newHideData); - }; - - const allHidden = allValuesAre(hideData, false); - const allVisible = allValuesAre(hideData, true); - - return ( - - - - - ); -} - -export default HideOrShowAll; +"use client"; + +import { Box, Button } from "@mui/material"; +import VisibilityIcon from "@mui/icons-material/Visibility"; +import VisibilityOffIcon from "@mui/icons-material/VisibilityOff"; + +const setAllValues = (obj, value) => { + const result = {}; + for (const key in obj) { + if (typeof obj[key] === "object" && obj[key] !== null) { + result[key] = setAllValues(obj[key], value); + } else { + result[key] = value; + } + } + return result; +}; + +const allValuesAre = (obj, value) => { + for (const key in obj) { + if (typeof obj[key] === "object" && obj[key] !== null) { + if (!allValuesAre(obj[key], value)) { + return false; + } + } else if (obj[key] !== value) { + return false; + } + } + return true; +}; + +function HideOrShowAll({ hideData, setHideData }) { + const handleShowAll = () => { + const newHideData = setAllValues(hideData, true); + setHideData(newHideData); + }; + + const handleHideAll = () => { + const newHideData = setAllValues(hideData, false); + setHideData(newHideData); + }; + + const allHidden = allValuesAre(hideData, false); + const allVisible = allValuesAre(hideData, true); + + return ( + + + + + ); +} + +export default HideOrShowAll; diff --git a/src/core/components/DataTable/hide/index.jsx b/src/core/components/DataTable/hide/index.jsx index b917c56..4d52d96 100644 --- a/src/core/components/DataTable/hide/index.jsx +++ b/src/core/components/DataTable/hide/index.jsx @@ -1,24 +1,24 @@ -"use client"; - -import { useState } from "react"; -import HideButton from "@/core/components/DataTable/hide/HideButton"; -import HideBody from "@/core/components/DataTable/hide/HideBody"; - -function HideColumn({ columns, user_id, page_name, table_name }) { - const [open, setOpen] = useState(false); - return ( - <> - - - - ); -} - -export default HideColumn; +"use client"; + +import { useState } from "react"; +import HideButton from "@/core/components/DataTable/hide/HideButton"; +import HideBody from "@/core/components/DataTable/hide/HideBody"; + +function HideColumn({ columns, user_id, page_name, table_name }) { + const [open, setOpen] = useState(false); + return ( + <> + + + + ); +} + +export default HideColumn; diff --git a/src/core/components/DataTable/index.js b/src/core/components/DataTable/index.js index 1e881f9..320ddea 100644 --- a/src/core/components/DataTable/index.js +++ b/src/core/components/DataTable/index.js @@ -1,18 +1,18 @@ -import DataTable_Main from "./Main"; -import DataTableProvider from "@/lib/contexts/DataTable"; - -const DataTable = (props) => { - return ( - - - - ); -}; - -export default DataTable; +import DataTable_Main from "./Main"; +import DataTableProvider from "@/lib/contexts/DataTable"; + +const DataTable = (props) => { + return ( + + + + ); +}; + +export default DataTable; diff --git a/src/core/components/DataTable/localization/fa/datatable.js b/src/core/components/DataTable/localization/fa/datatable.js index e36f366..15df686 100644 --- a/src/core/components/DataTable/localization/fa/datatable.js +++ b/src/core/components/DataTable/localization/fa/datatable.js @@ -1,91 +1,91 @@ -export const FA_DATATABLE_LOCALIZATION = { - actions: "عملیات", - and: "و", - cancel: "لغو", - changeFilterMode: "تغییر حالت فیلتر", - changeSearchMode: "تغییر حالت جستجو", - clearFilter: "پاک کردن فیلتر", - clearSearch: "پاک کردن جستجو", - clearSort: "پاک کردن مرتب سازی", - clickToCopy: "کلیک برای کپی", - collapse: "جمع شدن", - collapseAll: "جمع شدن همه", - columnActions: "عملیات ستون", - copiedToClipboard: "کپی شد", - dropToGroupBy: "رها کردن برای گروه بندی بر اساس {column}", - edit: "ویرایش", - expand: "باز شدن", - expandAll: "باز شدن همه", - filterArrIncludes: "شامل", - filterArrIncludesAll: "شامل همه", - filterArrIncludesSome: "شامل", - filterBetween: "میان", - filterBetweenInclusive: "میان با احتساب هر دو", - filterByColumn: "فیلتر بر اساس {column}", - filterContains: "شامل", - filterEmpty: "خالی", - filterEndsWith: "به پایان می‌رسد با", - filterEquals: "برابر", - filterEqualsString: "برابر", - filterFuzzy: "نزدیک", - filterGreaterThan: "بزرگتر از", - filterGreaterThanOrEqualTo: "بزرگتر یا مساوی", - filterInNumberRange: "میان", - filterIncludesString: "شامل", - filterIncludesStringSensitive: "شامل", - filterLessThan: "کوچکتر از", - filterLessThanOrEqualTo: "کوچکتر یا مساوی", - filterMode: "حالت فیلتر: {filterType}", - filterNotEmpty: "غیر خالی", - filterNotEquals: "نا برابر", - filterStartsWith: "شروع می‌شود با", - filterWeakEquals: "برابر", - filteringByColumn: "فیلتر بر اساس {column} - {filterType} {filterValue}", - goToFirstPage: "رفتن به صفحه اول", - goToLastPage: "رفتن به صفحه آخر", - goToNextPage: "رفتن به صفحه بعدی", - goToPreviousPage: "رفتن به صفحه قبلی", - grab: "گرفتن", - groupByColumn: "گروه بندی بر اساس {column}", - groupedBy: "گروه بندی شده بر اساس", - hideAll: "پنهان کردن همه", - hideColumn: "پنهان کردن ستون {column}", - max: "حداکثر", - min: "حداقل", - move: "انتقال", - noRecordsToDisplay: "هیچ رکوردی برای نمایش وجود ندارد", - noResultsFound: "نتیجه‌ای یافت نشد", - of: "از", - or: "یا", - pinToLeft: "چسباندن به سمت چپ", - pinToRight: "چسباندن به سمت راست", - resetColumnSize: "بازنشانی اندازه ستون", - resetOrder: "بازنشانی ترتیب", - rowActions: "عملیات ردیف", - rowNumber: "#", - rowNumbers: "شماره ردیف", - rowsPerPage: "ردیف در هر صفحه", - save: "ذخیره", - search: "جستجو", - selectedCountOfRowCountRowsSelected: "{selectedCount} از {rowCount} ردیف انتخاب شده", - select: "انتخاب", - showAll: "نمایش همه", - showAllColumns: "نمایش همه ستون‌ها", - showHideColumns: "نمایش/مخفی کردن ستون‌ها", - showHideFilters: "نمایش/مخفی کردن فیلترها", - showHideSearch: "نمایش/مخفی کردن جستجو", - sortByColumnAsc: "مرتب سازی بر اساس {column} صعودی", - sortByColumnDesc: "مرتب سازی بر اساس {column} نزولی", - sortedByColumnAsc: "مرتب شده بر اساس {column} صعودی", - sortedByColumnDesc: "مرتب شده بر اساس {column} نزولی", - thenBy: "، سپس بر اساس ", - toggleDensity: "تغییر تراکم", - toggleFullScreen: "تغییر حالت تمام صفحه", - toggleSelectAll: "انتخاب/عدم انتخاب همه", - toggleSelectRow: "انتخاب/عدم انتخاب ردیف", - toggleVisibility: "تغییر پیدا/پنهان", - ungroupByColumn: "لغو گروه بندی بر اساس {column}", - unpin: "رها کردن", - unpinAll: "رها کردن همه", - unsorted: "بدون مرتب سازی", -}; +export const FA_DATATABLE_LOCALIZATION = { + actions: "عملیات", + and: "و", + cancel: "لغو", + changeFilterMode: "تغییر حالت فیلتر", + changeSearchMode: "تغییر حالت جستجو", + clearFilter: "پاک کردن فیلتر", + clearSearch: "پاک کردن جستجو", + clearSort: "پاک کردن مرتب سازی", + clickToCopy: "کلیک برای کپی", + collapse: "جمع شدن", + collapseAll: "جمع شدن همه", + columnActions: "عملیات ستون", + copiedToClipboard: "کپی شد", + dropToGroupBy: "رها کردن برای گروه بندی بر اساس {column}", + edit: "ویرایش", + expand: "باز شدن", + expandAll: "باز شدن همه", + filterArrIncludes: "شامل", + filterArrIncludesAll: "شامل همه", + filterArrIncludesSome: "شامل", + filterBetween: "میان", + filterBetweenInclusive: "میان با احتساب هر دو", + filterByColumn: "فیلتر بر اساس {column}", + filterContains: "شامل", + filterEmpty: "خالی", + filterEndsWith: "به پایان می‌رسد با", + filterEquals: "برابر", + filterEqualsString: "برابر", + filterFuzzy: "نزدیک", + filterGreaterThan: "بزرگتر از", + filterGreaterThanOrEqualTo: "بزرگتر یا مساوی", + filterInNumberRange: "میان", + filterIncludesString: "شامل", + filterIncludesStringSensitive: "شامل", + filterLessThan: "کوچکتر از", + filterLessThanOrEqualTo: "کوچکتر یا مساوی", + filterMode: "حالت فیلتر: {filterType}", + filterNotEmpty: "غیر خالی", + filterNotEquals: "نا برابر", + filterStartsWith: "شروع می‌شود با", + filterWeakEquals: "برابر", + filteringByColumn: "فیلتر بر اساس {column} - {filterType} {filterValue}", + goToFirstPage: "رفتن به صفحه اول", + goToLastPage: "رفتن به صفحه آخر", + goToNextPage: "رفتن به صفحه بعدی", + goToPreviousPage: "رفتن به صفحه قبلی", + grab: "گرفتن", + groupByColumn: "گروه بندی بر اساس {column}", + groupedBy: "گروه بندی شده بر اساس", + hideAll: "پنهان کردن همه", + hideColumn: "پنهان کردن ستون {column}", + max: "حداکثر", + min: "حداقل", + move: "انتقال", + noRecordsToDisplay: "هیچ رکوردی برای نمایش وجود ندارد", + noResultsFound: "نتیجه‌ای یافت نشد", + of: "از", + or: "یا", + pinToLeft: "چسباندن به سمت چپ", + pinToRight: "چسباندن به سمت راست", + resetColumnSize: "بازنشانی اندازه ستون", + resetOrder: "بازنشانی ترتیب", + rowActions: "عملیات ردیف", + rowNumber: "#", + rowNumbers: "شماره ردیف", + rowsPerPage: "ردیف در هر صفحه", + save: "ذخیره", + search: "جستجو", + selectedCountOfRowCountRowsSelected: "{selectedCount} از {rowCount} ردیف انتخاب شده", + select: "انتخاب", + showAll: "نمایش همه", + showAllColumns: "نمایش همه ستون‌ها", + showHideColumns: "نمایش/مخفی کردن ستون‌ها", + showHideFilters: "نمایش/مخفی کردن فیلترها", + showHideSearch: "نمایش/مخفی کردن جستجو", + sortByColumnAsc: "مرتب سازی بر اساس {column} صعودی", + sortByColumnDesc: "مرتب سازی بر اساس {column} نزولی", + sortedByColumnAsc: "مرتب شده بر اساس {column} صعودی", + sortedByColumnDesc: "مرتب شده بر اساس {column} نزولی", + thenBy: "، سپس بر اساس ", + toggleDensity: "تغییر تراکم", + toggleFullScreen: "تغییر حالت تمام صفحه", + toggleSelectAll: "انتخاب/عدم انتخاب همه", + toggleSelectRow: "انتخاب/عدم انتخاب ردیف", + toggleVisibility: "تغییر پیدا/پنهان", + ungroupByColumn: "لغو گروه بندی بر اساس {column}", + unpin: "رها کردن", + unpinAll: "رها کردن همه", + unsorted: "بدون مرتب سازی", +}; diff --git a/src/core/components/DataTable/menus/ActionMenuItem.js b/src/core/components/DataTable/menus/ActionMenuItem.js index 012fcc5..44550e4 100644 --- a/src/core/components/DataTable/menus/ActionMenuItem.js +++ b/src/core/components/DataTable/menus/ActionMenuItem.js @@ -1,38 +1,38 @@ -import { Box, IconButton, ListItemIcon, MenuItem } from "@mui/material"; - -const DataTable_ActionMenuItem = ({ icon, label, onOpenSubMenu, table, ...rest }) => { - const { - options: { - icons: { ArrowRightIcon }, - }, - } = table; - - return ( - - - {icon} - {label} - - {onOpenSubMenu && ( - - - - )} - - ); -}; -export default DataTable_ActionMenuItem; +import { Box, IconButton, ListItemIcon, MenuItem } from "@mui/material"; + +const DataTable_ActionMenuItem = ({ icon, label, onOpenSubMenu, table, ...rest }) => { + const { + options: { + icons: { ArrowRightIcon }, + }, + } = table; + + return ( + + + {icon} + {label} + + {onOpenSubMenu && ( + + + + )} + + ); +}; +export default DataTable_ActionMenuItem; diff --git a/src/core/components/DataTable/menus/CellActionMenu.js b/src/core/components/DataTable/menus/CellActionMenu.js index 5b27ca9..57cb9f3 100644 --- a/src/core/components/DataTable/menus/CellActionMenu.js +++ b/src/core/components/DataTable/menus/CellActionMenu.js @@ -1,94 +1,94 @@ -import { parseFromValuesOrFunc } from "@/core/utils/utils"; -import { Menu } from "@mui/material"; -import DataTable_ActionMenuItem from "./ActionMenuItem"; - -const DataTable_CellActionMenu = ({ table, ...rest }) => { - const { - getState, - options: { - editDisplayMode, - enableClickToCopy, - enableEditing, - icons: { ContentCopy, EditIcon }, - localization, - mrtTheme: { menuBackgroundColor }, - renderCellActionMenuItems, - }, - refs: { actionCellRef }, - } = table; - const { actionCell, density } = getState(); - const cell = actionCell || null; - const { row } = cell; - const { column } = cell; - const { columnDef } = column; - - const handleClose = (event) => { - event?.stopPropagation(); - table.setActionCell(null); - actionCellRef.current = null; - }; - - const internalMenuItems = [ - (parseFromValuesOrFunc(enableClickToCopy, cell) === "context-menu" || - parseFromValuesOrFunc(columnDef.enableClickToCopy, cell) === "context-menu") && ( - } - key={"mrt-copy"} - label={localization.copy} - onClick={(event) => { - event.stopPropagation(); - navigator.clipboard.writeText(cell.getValue()); - handleClose(); - }} - table={table} - /> - ), - parseFromValuesOrFunc(enableEditing, row) && editDisplayMode === "cell" && ( - } - key={"mrt-edit"} - label={localization.edit} - onClick={() => { - openEditingCell({ cell, table }); - handleClose(); - }} - table={table} - /> - ), - ].filter(Boolean); - - const renderActionProps = { - cell, - closeMenu: handleClose, - column, - internalMenuItems, - row, - table, - }; - - const menuItems = - columnDef.renderCellActionMenuItems?.(renderActionProps) ?? renderCellActionMenuItems?.(renderActionProps); - - return ( - (!!menuItems?.length || !!internalMenuItems?.length) && ( - event.stopPropagation()} - onClose={handleClose} - open={!!cell} - transformOrigin={{ horizontal: -100, vertical: 8 }} - {...rest} - > - {menuItems ?? internalMenuItems} - - ) - ); -}; -export default DataTable_CellActionMenu; +import { parseFromValuesOrFunc } from "@/core/utils/utils"; +import { Menu } from "@mui/material"; +import DataTable_ActionMenuItem from "./ActionMenuItem"; + +const DataTable_CellActionMenu = ({ table, ...rest }) => { + const { + getState, + options: { + editDisplayMode, + enableClickToCopy, + enableEditing, + icons: { ContentCopy, EditIcon }, + localization, + mrtTheme: { menuBackgroundColor }, + renderCellActionMenuItems, + }, + refs: { actionCellRef }, + } = table; + const { actionCell, density } = getState(); + const cell = actionCell || null; + const { row } = cell; + const { column } = cell; + const { columnDef } = column; + + const handleClose = (event) => { + event?.stopPropagation(); + table.setActionCell(null); + actionCellRef.current = null; + }; + + const internalMenuItems = [ + (parseFromValuesOrFunc(enableClickToCopy, cell) === "context-menu" || + parseFromValuesOrFunc(columnDef.enableClickToCopy, cell) === "context-menu") && ( + } + key={"mrt-copy"} + label={localization.copy} + onClick={(event) => { + event.stopPropagation(); + navigator.clipboard.writeText(cell.getValue()); + handleClose(); + }} + table={table} + /> + ), + parseFromValuesOrFunc(enableEditing, row) && editDisplayMode === "cell" && ( + } + key={"mrt-edit"} + label={localization.edit} + onClick={() => { + openEditingCell({ cell, table }); + handleClose(); + }} + table={table} + /> + ), + ].filter(Boolean); + + const renderActionProps = { + cell, + closeMenu: handleClose, + column, + internalMenuItems, + row, + table, + }; + + const menuItems = + columnDef.renderCellActionMenuItems?.(renderActionProps) ?? renderCellActionMenuItems?.(renderActionProps); + + return ( + (!!menuItems?.length || !!internalMenuItems?.length) && ( + event.stopPropagation()} + onClose={handleClose} + open={!!cell} + transformOrigin={{ horizontal: -100, vertical: 8 }} + {...rest} + > + {menuItems ?? internalMenuItems} + + ) + ); +}; +export default DataTable_CellActionMenu; diff --git a/src/core/components/DataTable/reset/ResetStorage.jsx b/src/core/components/DataTable/reset/ResetStorage.jsx index 7994867..79aff30 100644 --- a/src/core/components/DataTable/reset/ResetStorage.jsx +++ b/src/core/components/DataTable/reset/ResetStorage.jsx @@ -1,36 +1,36 @@ -"use client"; -import { IconButton, Tooltip, Badge } from "@mui/material"; -import AutorenewIcon from "@mui/icons-material/Autorenew"; -import useTableSetting from "@/lib/hooks/useTableSetting"; -import useDataTable from "@/lib/hooks/useDataTable"; - -function ResetStorage({ user_id, page_name, table_name }) { - const { resetAction } = useTableSetting(); - const { isAnyDirty } = useDataTable(); - const reset = () => { - resetAction(user_id, page_name, table_name); - }; - - return ( - - - {isAnyDirty ? ( - - - - ) : ( - - )} - - - ); -} - -export default ResetStorage; +"use client"; +import { IconButton, Tooltip, Badge } from "@mui/material"; +import AutorenewIcon from "@mui/icons-material/Autorenew"; +import useTableSetting from "@/lib/hooks/useTableSetting"; +import useDataTable from "@/lib/hooks/useDataTable"; + +function ResetStorage({ user_id, page_name, table_name }) { + const { resetAction } = useTableSetting(); + const { isAnyDirty } = useDataTable(); + const reset = () => { + resetAction(user_id, page_name, table_name); + }; + + return ( + + + {isAnyDirty ? ( + + + + ) : ( + + )} + + + ); +} + +export default ResetStorage; diff --git a/src/core/components/DataTable/table/Paper.js b/src/core/components/DataTable/table/Paper.js index 9ce08fc..6c3d997 100644 --- a/src/core/components/DataTable/table/Paper.js +++ b/src/core/components/DataTable/table/Paper.js @@ -1,100 +1,100 @@ -import { parseFromValuesOrFunc } from "@/core/utils/utils"; -import { Paper } from "@mui/material"; -import DataTable_BottomToolbar from "../toolbar/BottomToolbar"; -import DataTable_TopToolbar from "../toolbar/TopToolbar"; -import DataTable_TableContainer from "./TableContainer"; - -const DataTable_Paper = ({ - table, - table_name, - columns, - user_id, - page_name, - mutate, - need_filter, - table_url, - table_title, - setFilterData, - ...rest -}) => { - const { - getState, - options: { - enableBottomToolbar, - enableTopToolbar, - mrtTheme: { baseBackgroundColor }, - muiTablePaperProps, - renderBottomToolbar, - renderTopToolbar, - }, - refs: { tablePaperRef }, - } = table; - - const { isFullScreen } = getState(); - - const paperProps = { - ...parseFromValuesOrFunc(muiTablePaperProps, { table }), - ...rest, - }; - - return ( - { - tablePaperRef.current = ref; - if (paperProps?.ref) { - //@ts-ignore - paperProps.ref.current = ref; - } - }} - style={{ - ...(isFullScreen - ? { - bottom: 0, - height: "100dvh", - left: 0, - margin: 0, - maxHeight: "100dvh", - maxWidth: "100dvw", - padding: 0, - position: "fixed", - right: 0, - top: 0, - width: "100dvw", - zIndex: 999, - } - : {}), - ...paperProps?.style, - }} - sx={(theme) => ({ - backgroundColor: baseBackgroundColor, - backgroundImage: "unset", - overflow: "hidden", - transition: "all 100ms ease-in-out", - ...parseFromValuesOrFunc(paperProps?.sx, theme), - })} - > - {enableTopToolbar && - (parseFromValuesOrFunc(renderTopToolbar, { table }) ?? ( - - ))} - - {enableBottomToolbar && - (parseFromValuesOrFunc(renderBottomToolbar, { table }) ?? )} - - ); -}; -export default DataTable_Paper; +import { parseFromValuesOrFunc } from "@/core/utils/utils"; +import { Paper } from "@mui/material"; +import DataTable_BottomToolbar from "../toolbar/BottomToolbar"; +import DataTable_TopToolbar from "../toolbar/TopToolbar"; +import DataTable_TableContainer from "./TableContainer"; + +const DataTable_Paper = ({ + table, + table_name, + columns, + user_id, + page_name, + mutate, + need_filter, + table_url, + table_title, + setFilterData, + ...rest +}) => { + const { + getState, + options: { + enableBottomToolbar, + enableTopToolbar, + mrtTheme: { baseBackgroundColor }, + muiTablePaperProps, + renderBottomToolbar, + renderTopToolbar, + }, + refs: { tablePaperRef }, + } = table; + + const { isFullScreen } = getState(); + + const paperProps = { + ...parseFromValuesOrFunc(muiTablePaperProps, { table }), + ...rest, + }; + + return ( + { + tablePaperRef.current = ref; + if (paperProps?.ref) { + //@ts-ignore + paperProps.ref.current = ref; + } + }} + style={{ + ...(isFullScreen + ? { + bottom: 0, + height: "100dvh", + left: 0, + margin: 0, + maxHeight: "100dvh", + maxWidth: "100dvw", + padding: 0, + position: "fixed", + right: 0, + top: 0, + width: "100dvw", + zIndex: 999, + } + : {}), + ...paperProps?.style, + }} + sx={(theme) => ({ + backgroundColor: baseBackgroundColor, + backgroundImage: "unset", + overflow: "hidden", + transition: "all 100ms ease-in-out", + ...parseFromValuesOrFunc(paperProps?.sx, theme), + })} + > + {enableTopToolbar && + (parseFromValuesOrFunc(renderTopToolbar, { table }) ?? ( + + ))} + + {enableBottomToolbar && + (parseFromValuesOrFunc(renderBottomToolbar, { table }) ?? )} + + ); +}; +export default DataTable_Paper; diff --git a/src/core/components/DataTable/table/Table.js b/src/core/components/DataTable/table/Table.js index 1bf6b69..76663bb 100644 --- a/src/core/components/DataTable/table/Table.js +++ b/src/core/components/DataTable/table/Table.js @@ -1,73 +1,73 @@ -import { parseCSSVarId, parseFromValuesOrFunc } from "@/core/utils/utils"; -import { Table } from "@mui/material"; -import { useMRT_ColumnVirtualizer } from "material-react-table"; -import { useMemo } from "react"; -import DataTable_TableBody, { Memo_DataTable_TableBody } from "../body/TableBody"; -import DataTable_TableHead from "../head/TableHead"; - -const DataTable_Table = ({ table, ...rest }) => { - const { - getFlatHeaders, - getState, - options: { - columns, - enableStickyHeader, - enableTableFooter, - enableTableHead, - layoutMode, - memoMode, - muiTableProps, - renderCaption, - }, - } = table; - const { columnSizing, columnSizingInfo, columnVisibility, isFullScreen } = getState(); - - const tableProps = { - ...parseFromValuesOrFunc(muiTableProps, { table }), - ...rest, - }; - - const Caption = parseFromValuesOrFunc(renderCaption, { table }); - - const columnSizeVars = useMemo(() => { - const headers = getFlatHeaders(); - const colSizes = {}; - for (let i = 0; i < headers.length; i++) { - const header = headers[i]; - const colSize = header.getSize(); - colSizes[`--header-${parseCSSVarId(header.id)}-size`] = colSize; - colSizes[`--col-${parseCSSVarId(header.column.id)}-size`] = colSize; - } - return colSizes; - }, [columns, columnSizing, columnSizingInfo, columnVisibility]); - - const columnVirtualizer = useMRT_ColumnVirtualizer(table); - - const commonTableGroupProps = { - columnVirtualizer, - table, - }; - - return ( - ({ - display: layoutMode?.startsWith("grid") ? "grid" : undefined, - position: "relative", - ...parseFromValuesOrFunc(tableProps?.sx, theme), - })} - > - {!!Caption && } - {enableTableHead && } - {memoMode === "table-body" || columnSizingInfo.isResizingColumn ? ( - - ) : ( - - )} - {/* {enableTableFooter && } */} -
    {Caption}
    - ); -}; -export default DataTable_Table; +import { parseCSSVarId, parseFromValuesOrFunc } from "@/core/utils/utils"; +import { Table } from "@mui/material"; +import { useMRT_ColumnVirtualizer } from "material-react-table"; +import { useMemo } from "react"; +import DataTable_TableBody, { Memo_DataTable_TableBody } from "../body/TableBody"; +import DataTable_TableHead from "../head/TableHead"; + +const DataTable_Table = ({ table, ...rest }) => { + const { + getFlatHeaders, + getState, + options: { + columns, + enableStickyHeader, + enableTableFooter, + enableTableHead, + layoutMode, + memoMode, + muiTableProps, + renderCaption, + }, + } = table; + const { columnSizing, columnSizingInfo, columnVisibility, isFullScreen } = getState(); + + const tableProps = { + ...parseFromValuesOrFunc(muiTableProps, { table }), + ...rest, + }; + + const Caption = parseFromValuesOrFunc(renderCaption, { table }); + + const columnSizeVars = useMemo(() => { + const headers = getFlatHeaders(); + const colSizes = {}; + for (let i = 0; i < headers.length; i++) { + const header = headers[i]; + const colSize = header.getSize(); + colSizes[`--header-${parseCSSVarId(header.id)}-size`] = colSize; + colSizes[`--col-${parseCSSVarId(header.column.id)}-size`] = colSize; + } + return colSizes; + }, [columns, columnSizing, columnSizingInfo, columnVisibility]); + + const columnVirtualizer = useMRT_ColumnVirtualizer(table); + + const commonTableGroupProps = { + columnVirtualizer, + table, + }; + + return ( + ({ + display: layoutMode?.startsWith("grid") ? "grid" : undefined, + position: "relative", + ...parseFromValuesOrFunc(tableProps?.sx, theme), + })} + > + {!!Caption && } + {enableTableHead && } + {memoMode === "table-body" || columnSizingInfo.isResizingColumn ? ( + + ) : ( + + )} + {/* {enableTableFooter && } */} +
    {Caption}
    + ); +}; +export default DataTable_Table; diff --git a/src/core/components/DataTable/table/TableContainer.js b/src/core/components/DataTable/table/TableContainer.js index 3e1320e..2914518 100644 --- a/src/core/components/DataTable/table/TableContainer.js +++ b/src/core/components/DataTable/table/TableContainer.js @@ -1,72 +1,72 @@ -import { parseFromValuesOrFunc } from "@/core/utils/utils"; -import { TableContainer } from "@mui/material"; -import { useEffect, useLayoutEffect, useState } from "react"; -import DataTable_CellActionMenu from "../menus/CellActionMenu"; -import DataTable_Table from "./Table"; -import DataTable_TableLoadingOverlay from "./TableLoadingOverlay"; - -const useIsomorphicLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect; - -const DataTable_TableContainer = ({ table, ...rest }) => { - const { - getState, - options: { enableCellActions, enableStickyHeader, muiTableContainerProps }, - refs: { bottomToolbarRef, tableContainerRef, topToolbarRef }, - } = table; - const { actionCell, isFullScreen, isLoading, showLoadingOverlay } = getState(); - - const loading = showLoadingOverlay !== false && (isLoading || showLoadingOverlay); - - const [totalToolbarHeight, setTotalToolbarHeight] = useState(0); - - const tableContainerProps = { - ...parseFromValuesOrFunc(muiTableContainerProps, { - table, - }), - ...rest, - }; - - useIsomorphicLayoutEffect(() => { - const topToolbarHeight = typeof document !== "undefined" ? (topToolbarRef.current?.offsetHeight ?? 0) : 0; - - const bottomToolbarHeight = - typeof document !== "undefined" ? (bottomToolbarRef?.current?.offsetHeight ?? 0) : 0; - - setTotalToolbarHeight(topToolbarHeight + bottomToolbarHeight); - }); - - return ( - { - if (node) { - tableContainerRef.current = node; - if (tableContainerProps?.ref) { - //@ts-ignore - tableContainerProps.ref.current = node; - } - } - }} - style={{ - maxHeight: isFullScreen ? `calc(100vh - ${totalToolbarHeight}px)` : undefined, - ...tableContainerProps?.style, - }} - sx={(theme) => ({ - maxHeight: enableStickyHeader - ? `clamp(350px, calc(100vh - ${totalToolbarHeight}px), 9999px)` - : undefined, - maxWidth: "100%", - overflow: "auto", - position: "relative", - ...parseFromValuesOrFunc(tableContainerProps?.sx, theme), - })} - > - {loading ? : null} - - {enableCellActions && actionCell && } - - ); -}; -export default DataTable_TableContainer; +import { parseFromValuesOrFunc } from "@/core/utils/utils"; +import { TableContainer } from "@mui/material"; +import { useEffect, useLayoutEffect, useState } from "react"; +import DataTable_CellActionMenu from "../menus/CellActionMenu"; +import DataTable_Table from "./Table"; +import DataTable_TableLoadingOverlay from "./TableLoadingOverlay"; + +const useIsomorphicLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect; + +const DataTable_TableContainer = ({ table, ...rest }) => { + const { + getState, + options: { enableCellActions, enableStickyHeader, muiTableContainerProps }, + refs: { bottomToolbarRef, tableContainerRef, topToolbarRef }, + } = table; + const { actionCell, isFullScreen, isLoading, showLoadingOverlay } = getState(); + + const loading = showLoadingOverlay !== false && (isLoading || showLoadingOverlay); + + const [totalToolbarHeight, setTotalToolbarHeight] = useState(0); + + const tableContainerProps = { + ...parseFromValuesOrFunc(muiTableContainerProps, { + table, + }), + ...rest, + }; + + useIsomorphicLayoutEffect(() => { + const topToolbarHeight = typeof document !== "undefined" ? (topToolbarRef.current?.offsetHeight ?? 0) : 0; + + const bottomToolbarHeight = + typeof document !== "undefined" ? (bottomToolbarRef?.current?.offsetHeight ?? 0) : 0; + + setTotalToolbarHeight(topToolbarHeight + bottomToolbarHeight); + }); + + return ( + { + if (node) { + tableContainerRef.current = node; + if (tableContainerProps?.ref) { + //@ts-ignore + tableContainerProps.ref.current = node; + } + } + }} + style={{ + maxHeight: isFullScreen ? `calc(100vh - ${totalToolbarHeight}px)` : undefined, + ...tableContainerProps?.style, + }} + sx={(theme) => ({ + maxHeight: enableStickyHeader + ? `clamp(350px, calc(100vh - ${totalToolbarHeight}px), 9999px)` + : undefined, + maxWidth: "100%", + overflow: "auto", + position: "relative", + ...parseFromValuesOrFunc(tableContainerProps?.sx, theme), + })} + > + {loading ? : null} + + {enableCellActions && actionCell && } + + ); +}; +export default DataTable_TableContainer; diff --git a/src/core/components/DataTable/table/TableLoadingOverlay.js b/src/core/components/DataTable/table/TableLoadingOverlay.js index 0c417dd..b21b306 100644 --- a/src/core/components/DataTable/table/TableLoadingOverlay.js +++ b/src/core/components/DataTable/table/TableLoadingOverlay.js @@ -1,44 +1,44 @@ -import { Box, CircularProgress } from "@mui/material"; - -const DataTable_TableLoadingOverlay = ({ table, ...rest }) => { - const { - options: { - localization, - mrtTheme: { baseBackgroundColor }, - muiCircularProgressProps, - }, - } = table; - - const circularProgressProps = { - ...parseFromValuesOrFunc(muiCircularProgressProps, { table }), - ...rest, - }; - - return ( - - {circularProgressProps?.Component ?? ( - - )} - - ); -}; -export default DataTable_TableLoadingOverlay; +import { Box, CircularProgress } from "@mui/material"; + +const DataTable_TableLoadingOverlay = ({ table, ...rest }) => { + const { + options: { + localization, + mrtTheme: { baseBackgroundColor }, + muiCircularProgressProps, + }, + } = table; + + const circularProgressProps = { + ...parseFromValuesOrFunc(muiCircularProgressProps, { table }), + ...rest, + }; + + return ( + + {circularProgressProps?.Component ?? ( + + )} + + ); +}; +export default DataTable_TableLoadingOverlay; diff --git a/src/core/components/DataTable/toolbar/BottomToolbar.js b/src/core/components/DataTable/toolbar/BottomToolbar.js index ced2c06..cb29df0 100644 --- a/src/core/components/DataTable/toolbar/BottomToolbar.js +++ b/src/core/components/DataTable/toolbar/BottomToolbar.js @@ -1,72 +1,72 @@ -import { getCommonToolbarStyles, parseFromValuesOrFunc } from "@/core/utils/utils"; -import { Box, alpha, useMediaQuery } from "@mui/material"; -import DataTable_LinearProgressBar from "./LinearProgressBar"; -import DataTable_TablePagination from "./TablePagination"; - -const DataTable_BottomToolbar = ({ table, ...rest }) => { - const { - getState, - options: { enablePagination, muiBottomToolbarProps, positionPagination, renderBottomToolbarCustomActions }, - refs: { bottomToolbarRef }, - } = table; - const { isFullScreen } = getState(); - - const isMobile = useMediaQuery("(max-width:720px)"); - const toolbarProps = { - ...parseFromValuesOrFunc(muiBottomToolbarProps, { table }), - ...rest, - }; - - const stackAlertBanner = isMobile || !!renderBottomToolbarCustomActions; - return ( - { - if (node) { - bottomToolbarRef.current = node; - if (toolbarProps?.ref) { - // @ts-ignore - toolbarProps.ref.current = node; - } - } - }} - sx={(theme) => ({ - ...getCommonToolbarStyles({ table, theme }), - bottom: isFullScreen ? "0" : undefined, - boxShadow: `0 1px 2px -1px ${alpha(theme.palette.grey[700], 0.5)} inset`, - left: 0, - position: isFullScreen ? "fixed" : "relative", - right: 0, - ...parseFromValuesOrFunc(toolbarProps?.sx, theme), - })} - > - - - {renderBottomToolbarCustomActions ? renderBottomToolbarCustomActions({ table }) : } - - {enablePagination && ["both", "bottom"].includes(positionPagination ?? "") && ( - - )} - - - - ); -}; -export default DataTable_BottomToolbar; +import { getCommonToolbarStyles, parseFromValuesOrFunc } from "@/core/utils/utils"; +import { Box, alpha, useMediaQuery } from "@mui/material"; +import DataTable_LinearProgressBar from "./LinearProgressBar"; +import DataTable_TablePagination from "./TablePagination"; + +const DataTable_BottomToolbar = ({ table, ...rest }) => { + const { + getState, + options: { enablePagination, muiBottomToolbarProps, positionPagination, renderBottomToolbarCustomActions }, + refs: { bottomToolbarRef }, + } = table; + const { isFullScreen } = getState(); + + const isMobile = useMediaQuery("(max-width:720px)"); + const toolbarProps = { + ...parseFromValuesOrFunc(muiBottomToolbarProps, { table }), + ...rest, + }; + + const stackAlertBanner = isMobile || !!renderBottomToolbarCustomActions; + return ( + { + if (node) { + bottomToolbarRef.current = node; + if (toolbarProps?.ref) { + // @ts-ignore + toolbarProps.ref.current = node; + } + } + }} + sx={(theme) => ({ + ...getCommonToolbarStyles({ table, theme }), + bottom: isFullScreen ? "0" : undefined, + boxShadow: `0 1px 2px -1px ${alpha(theme.palette.grey[700], 0.5)} inset`, + left: 0, + position: isFullScreen ? "fixed" : "relative", + right: 0, + ...parseFromValuesOrFunc(toolbarProps?.sx, theme), + })} + > + + + {renderBottomToolbarCustomActions ? renderBottomToolbarCustomActions({ table }) : } + + {enablePagination && ["both", "bottom"].includes(positionPagination ?? "") && ( + + )} + + + + ); +}; +export default DataTable_BottomToolbar; diff --git a/src/core/components/DataTable/toolbar/LinearProgressBar.js b/src/core/components/DataTable/toolbar/LinearProgressBar.js index 74c465f..bac4985 100644 --- a/src/core/components/DataTable/toolbar/LinearProgressBar.js +++ b/src/core/components/DataTable/toolbar/LinearProgressBar.js @@ -1,40 +1,40 @@ -import { parseFromValuesOrFunc } from "@/core/utils/utils"; -import { Collapse, LinearProgress } from "@mui/material"; - -const DataTable_LinearProgressBar = ({ isTopToolbar, table, ...rest }) => { - const { - getState, - options: { muiLinearProgressProps }, - } = table; - const { isSaving, showProgressBars } = getState(); - - const linearProgressProps = { - ...parseFromValuesOrFunc(muiLinearProgressProps, { - isTopToolbar, - table, - }), - ...rest, - }; - - return ( - - - - ); -}; -export default DataTable_LinearProgressBar; +import { parseFromValuesOrFunc } from "@/core/utils/utils"; +import { Collapse, LinearProgress } from "@mui/material"; + +const DataTable_LinearProgressBar = ({ isTopToolbar, table, ...rest }) => { + const { + getState, + options: { muiLinearProgressProps }, + } = table; + const { isSaving, showProgressBars } = getState(); + + const linearProgressProps = { + ...parseFromValuesOrFunc(muiLinearProgressProps, { + isTopToolbar, + table, + }), + ...rest, + }; + + return ( + + + + ); +}; +export default DataTable_LinearProgressBar; diff --git a/src/core/components/DataTable/toolbar/TablePagination.js b/src/core/components/DataTable/toolbar/TablePagination.js index 6492b41..4d79830 100644 --- a/src/core/components/DataTable/toolbar/TablePagination.js +++ b/src/core/components/DataTable/toolbar/TablePagination.js @@ -1,218 +1,218 @@ -import { flipIconStyles, getCommonTooltipProps, parseFromValuesOrFunc } from "@/core/utils/utils"; -import { useTheme } from "@emotion/react"; -import { - Box, - IconButton, - InputLabel, - MenuItem, - Pagination, - PaginationItem, - Select, - Tooltip, - Typography, - useMediaQuery, -} from "@mui/material"; - -const defaultRowsPerPage = [5, 10, 15, 20, 25, 30, 50, 100]; - -const DataTable_TablePagination = ({ position = "bottom", table, ...rest }) => { - const theme = useTheme(); - const isMobile = useMediaQuery("(max-width: 720px)"); - - const { - getState, - options: { - enableToolbarInternalActions, - icons: { ChevronLeftIcon, ChevronRightIcon, FirstPageIcon, LastPageIcon }, - localization, - muiPaginationProps, - paginationDisplayMode, - }, - } = table; - - const { - pagination: { pageIndex = 0, pageSize = 10 }, - showGlobalFilter, - } = getState(); - - const paginationProps = { - ...parseFromValuesOrFunc(muiPaginationProps, { - table, - }), - ...rest, - }; - - const totalRowCount = table.getRowCount(); - const numberOfPages = table.getPageCount(); - const showFirstLastPageButtons = numberOfPages > 2; - const firstRowIndex = pageIndex * pageSize; - const lastRowIndex = Math.min(pageIndex * pageSize + pageSize, totalRowCount); - - const { - SelectProps = {}, - disabled = false, - rowsPerPageOptions = defaultRowsPerPage, - showFirstButton = showFirstLastPageButtons, - showLastButton = showFirstLastPageButtons, - showRowsPerPage = true, - ...restPaginationProps - } = paginationProps ?? {}; - - const disableBack = pageIndex <= 0 || disabled; - const disableNext = lastRowIndex >= totalRowCount || disabled; - - if (isMobile && SelectProps?.native !== false) { - SelectProps.native = true; - } - - const tooltipProps = getCommonTooltipProps(); - - return ( - - {showRowsPerPage && ( - - - {localization.rowsPerPage} - - - - )} - {paginationDisplayMode === "pages" ? ( - table.setPageIndex(newPageIndex - 1)} - page={pageIndex + 1} - renderItem={(item) => ( - - )} - showFirstButton={showFirstButton} - showLastButton={showLastButton} - {...restPaginationProps} - /> - ) : paginationDisplayMode === "default" ? ( - <> - {`${ - lastRowIndex === 0 ? 0 : (firstRowIndex + 1).toLocaleString() - }-${lastRowIndex.toLocaleString()} ${ - localization.of - } ${totalRowCount.toLocaleString()}`} - - {showFirstButton && ( - - - table.firstPage()} - size="small" - > - - - - - )} - - - table.previousPage()} - size="small" - > - - - - - - - table.nextPage()} - size="small" - > - - - - - {showLastButton && ( - - - table.lastPage()} - size="small" - > - - - - - )} - - - ) : null} - - ); -}; -export default DataTable_TablePagination; +import { flipIconStyles, getCommonTooltipProps, parseFromValuesOrFunc } from "@/core/utils/utils"; +import { useTheme } from "@emotion/react"; +import { + Box, + IconButton, + InputLabel, + MenuItem, + Pagination, + PaginationItem, + Select, + Tooltip, + Typography, + useMediaQuery, +} from "@mui/material"; + +const defaultRowsPerPage = [5, 10, 15, 20, 25, 30, 50, 100]; + +const DataTable_TablePagination = ({ position = "bottom", table, ...rest }) => { + const theme = useTheme(); + const isMobile = useMediaQuery("(max-width: 720px)"); + + const { + getState, + options: { + enableToolbarInternalActions, + icons: { ChevronLeftIcon, ChevronRightIcon, FirstPageIcon, LastPageIcon }, + localization, + muiPaginationProps, + paginationDisplayMode, + }, + } = table; + + const { + pagination: { pageIndex = 0, pageSize = 10 }, + showGlobalFilter, + } = getState(); + + const paginationProps = { + ...parseFromValuesOrFunc(muiPaginationProps, { + table, + }), + ...rest, + }; + + const totalRowCount = table.getRowCount(); + const numberOfPages = table.getPageCount(); + const showFirstLastPageButtons = numberOfPages > 2; + const firstRowIndex = pageIndex * pageSize; + const lastRowIndex = Math.min(pageIndex * pageSize + pageSize, totalRowCount); + + const { + SelectProps = {}, + disabled = false, + rowsPerPageOptions = defaultRowsPerPage, + showFirstButton = showFirstLastPageButtons, + showLastButton = showFirstLastPageButtons, + showRowsPerPage = true, + ...restPaginationProps + } = paginationProps ?? {}; + + const disableBack = pageIndex <= 0 || disabled; + const disableNext = lastRowIndex >= totalRowCount || disabled; + + if (isMobile && SelectProps?.native !== false) { + SelectProps.native = true; + } + + const tooltipProps = getCommonTooltipProps(); + + return ( + + {showRowsPerPage && ( + + + {localization.rowsPerPage} + + + + )} + {paginationDisplayMode === "pages" ? ( + table.setPageIndex(newPageIndex - 1)} + page={pageIndex + 1} + renderItem={(item) => ( + + )} + showFirstButton={showFirstButton} + showLastButton={showLastButton} + {...restPaginationProps} + /> + ) : paginationDisplayMode === "default" ? ( + <> + {`${ + lastRowIndex === 0 ? 0 : (firstRowIndex + 1).toLocaleString() + }-${lastRowIndex.toLocaleString()} ${ + localization.of + } ${totalRowCount.toLocaleString()}`} + + {showFirstButton && ( + + + table.firstPage()} + size="small" + > + + + + + )} + + + table.previousPage()} + size="small" + > + + + + + + + table.nextPage()} + size="small" + > + + + + + {showLastButton && ( + + + table.lastPage()} + size="small" + > + + + + + )} + + + ) : null} + + ); +}; +export default DataTable_TablePagination; diff --git a/src/core/components/DataTable/toolbar/TopToolbar.js b/src/core/components/DataTable/toolbar/TopToolbar.js index ea0c6d0..2906866 100644 --- a/src/core/components/DataTable/toolbar/TopToolbar.js +++ b/src/core/components/DataTable/toolbar/TopToolbar.js @@ -1,138 +1,138 @@ -import { getCommonToolbarStyles, parseFromValuesOrFunc } from "@/core/utils/utils"; -import { Box, Typography, useMediaQuery } from "@mui/material"; -import DataTable_LinearProgressBar from "./LinearProgressBar"; -import DataTable_TablePagination from "./TablePagination"; -import FilterColumn from "@/core/components/DataTable/filter"; -import UpdateTable from "@/core/components/DataTable/update/UpdateTable"; -import ResetStorage from "@/core/components/DataTable/reset/ResetStorage"; -import HideColumn from "@/core/components/DataTable/hide"; -import FilterCustom from "../filter/FilterCustom"; - -const DataTable_TopToolbar = ({ - mutate, - need_filter, - table, - columns, - table_url, - user_id, - page_name, - table_name, - table_title, - special_data, - special_filter, - setFilterData, -}) => { - const { - getState, - options: { - enablePagination, - enableToolbarInternalActions, - muiTopToolbarProps, - positionPagination, - renderTopToolbarCustomActions, - }, - refs: { topToolbarRef }, - } = table; - const { isFullScreen, showGlobalFilter } = getState(); - - const isMobile = useMediaQuery("(max-width:720px)"); - const isTablet = useMediaQuery("(max-width:1024px)"); - - const toolbarProps = parseFromValuesOrFunc(muiTopToolbarProps, { table }); - - const stackAlertBanner = isMobile || !!renderTopToolbarCustomActions || (showGlobalFilter && isTablet); - - return ( - { - topToolbarRef.current = ref; - if (toolbarProps?.ref) { - // @ts-ignore - toolbarProps.ref.current = ref; - } - }} - sx={(theme) => ({ - ...getCommonToolbarStyles({ table, theme }), - position: isFullScreen ? "sticky" : "relative", - top: isFullScreen ? "0" : undefined, - ...parseFromValuesOrFunc(toolbarProps?.sx, theme), - })} - > - - - {renderTopToolbarCustomActions?.({ table })} - - - {table_title || ""} - - {enableToolbarInternalActions && ( - - {!special_data && ( - <> - - - - )} - - {need_filter && ( - - )} - {special_filter && setFilterData && ( - - )} - - )} - - {enablePagination && ["both", "top"].includes(positionPagination ?? "") && ( - - )} - - - ); -}; - -export default DataTable_TopToolbar; +import { getCommonToolbarStyles, parseFromValuesOrFunc } from "@/core/utils/utils"; +import { Box, Typography, useMediaQuery } from "@mui/material"; +import DataTable_LinearProgressBar from "./LinearProgressBar"; +import DataTable_TablePagination from "./TablePagination"; +import FilterColumn from "@/core/components/DataTable/filter"; +import UpdateTable from "@/core/components/DataTable/update/UpdateTable"; +import ResetStorage from "@/core/components/DataTable/reset/ResetStorage"; +import HideColumn from "@/core/components/DataTable/hide"; +import FilterCustom from "../filter/FilterCustom"; + +const DataTable_TopToolbar = ({ + mutate, + need_filter, + table, + columns, + table_url, + user_id, + page_name, + table_name, + table_title, + special_data, + special_filter, + setFilterData, +}) => { + const { + getState, + options: { + enablePagination, + enableToolbarInternalActions, + muiTopToolbarProps, + positionPagination, + renderTopToolbarCustomActions, + }, + refs: { topToolbarRef }, + } = table; + const { isFullScreen, showGlobalFilter } = getState(); + + const isMobile = useMediaQuery("(max-width:720px)"); + const isTablet = useMediaQuery("(max-width:1024px)"); + + const toolbarProps = parseFromValuesOrFunc(muiTopToolbarProps, { table }); + + const stackAlertBanner = isMobile || !!renderTopToolbarCustomActions || (showGlobalFilter && isTablet); + + return ( + { + topToolbarRef.current = ref; + if (toolbarProps?.ref) { + // @ts-ignore + toolbarProps.ref.current = ref; + } + }} + sx={(theme) => ({ + ...getCommonToolbarStyles({ table, theme }), + position: isFullScreen ? "sticky" : "relative", + top: isFullScreen ? "0" : undefined, + ...parseFromValuesOrFunc(toolbarProps?.sx, theme), + })} + > + + + {renderTopToolbarCustomActions?.({ table })} + + + {table_title || ""} + + {enableToolbarInternalActions && ( + + {!special_data && ( + <> + + + + )} + + {need_filter && ( + + )} + {special_filter && setFilterData && ( + + )} + + )} + + {enablePagination && ["both", "top"].includes(positionPagination ?? "") && ( + + )} + + + ); +}; + +export default DataTable_TopToolbar; diff --git a/src/core/components/DataTable/update/UpdateTable.jsx b/src/core/components/DataTable/update/UpdateTable.jsx index 8a60c8d..5d36437 100644 --- a/src/core/components/DataTable/update/UpdateTable.jsx +++ b/src/core/components/DataTable/update/UpdateTable.jsx @@ -1,19 +1,19 @@ -"use client"; -import { IconButton, Tooltip } from "@mui/material"; -import RestartAltIcon from "@mui/icons-material/RestartAlt"; - -function UpdateTable({ mutate }) { - const update = () => { - mutate(); - }; - - return ( - - - - - - ); -} - -export default UpdateTable; +"use client"; +import { IconButton, Tooltip } from "@mui/material"; +import RestartAltIcon from "@mui/icons-material/RestartAlt"; + +function UpdateTable({ mutate }) { + const update = () => { + mutate(); + }; + + return ( + + + + + + ); +} + +export default UpdateTable; diff --git a/src/core/components/DataTableWithAuth.jsx b/src/core/components/DataTableWithAuth.jsx index 3363495..79492fd 100644 --- a/src/core/components/DataTableWithAuth.jsx +++ b/src/core/components/DataTableWithAuth.jsx @@ -1,8 +1,8 @@ -import DataTable from "@/core/components/DataTable"; -import { useAuth } from "@/lib/contexts/auth"; - -const DataTableWithAuth = (props) => { - const { user } = useAuth(); - return ; -}; -export default DataTableWithAuth; +import DataTable from "@/core/components/DataTable"; +import { useAuth } from "@/lib/contexts/auth"; + +const DataTableWithAuth = (props) => { + const { user } = useAuth(); + return ; +}; +export default DataTableWithAuth; diff --git a/src/core/components/DialogLoading.jsx b/src/core/components/DialogLoading.jsx index 18bcbcf..9a9fb2d 100644 --- a/src/core/components/DialogLoading.jsx +++ b/src/core/components/DialogLoading.jsx @@ -1,36 +1,36 @@ -import { Box, Skeleton } from "@mui/material"; - -const DialogLoading = ({ loadingOpen }) => { - return ( - - - - - - - - - - - - - - - ); -}; - -export default DialogLoading; +import { Box, Skeleton } from "@mui/material"; + +const DialogLoading = ({ loadingOpen }) => { + return ( + + + + + + + + + + + + + + + ); +}; + +export default DialogLoading; diff --git a/src/core/components/DialogTransition.jsx b/src/core/components/DialogTransition.jsx index 1232e48..4a4e4de 100644 --- a/src/core/components/DialogTransition.jsx +++ b/src/core/components/DialogTransition.jsx @@ -1,8 +1,8 @@ -import { Slide } from "@mui/material"; -import React from "react"; - -const DialogTransition = React.forwardRef(function Transition(props, ref) { - return ; -}); - -export default DialogTransition; +import { Slide } from "@mui/material"; +import React from "react"; + +const DialogTransition = React.forwardRef(function Transition(props, ref) { + return ; +}); + +export default DialogTransition; diff --git a/src/core/components/FilterDrawer/FilterController.jsx b/src/core/components/FilterDrawer/FilterController.jsx index 4a6a125..1f60920 100644 --- a/src/core/components/FilterDrawer/FilterController.jsx +++ b/src/core/components/FilterDrawer/FilterController.jsx @@ -1,25 +1,25 @@ -import { Controller } from "react-hook-form"; -import FilterField from "./FilterField"; - -const FilterController = ({ item, control, reset, errors }) => { - return ( - { - return ( - reset()} - errors={errors} - /> - ); - }} - /> - ); -}; -export default FilterController; +import { Controller } from "react-hook-form"; +import FilterField from "./FilterField"; + +const FilterController = ({ item, control, reset, errors }) => { + return ( + { + return ( + reset()} + errors={errors} + /> + ); + }} + /> + ); +}; +export default FilterController; diff --git a/src/core/components/FilterDrawer/FilterControllerWithDependency.jsx b/src/core/components/FilterDrawer/FilterControllerWithDependency.jsx index 361941f..3ba3956 100644 --- a/src/core/components/FilterDrawer/FilterControllerWithDependency.jsx +++ b/src/core/components/FilterDrawer/FilterControllerWithDependency.jsx @@ -1,27 +1,27 @@ -import { Controller, useWatch } from "react-hook-form"; -import FilterField from "./FilterField"; - -const FilterControllerWithDependency = ({ item, control, reset, errors }) => { - const dependencyField = useWatch({ control, name: item.dependencyId }); - - return ( - { - return ( - reset()} - errors={errors} - /> - ); - }} - /> - ); -}; -export default FilterControllerWithDependency; +import { Controller, useWatch } from "react-hook-form"; +import FilterField from "./FilterField"; + +const FilterControllerWithDependency = ({ item, control, reset, errors }) => { + const dependencyField = useWatch({ control, name: item.dependencyId }); + + return ( + { + return ( + reset()} + errors={errors} + /> + ); + }} + /> + ); +}; +export default FilterControllerWithDependency; diff --git a/src/core/components/FilterDrawer/FilterField.jsx b/src/core/components/FilterDrawer/FilterField.jsx index ed86df8..1ae9457 100644 --- a/src/core/components/FilterDrawer/FilterField.jsx +++ b/src/core/components/FilterDrawer/FilterField.jsx @@ -1,103 +1,103 @@ -import { useState } from "react"; -import CustomTextFieldRange from "./fieldsType/CustomTextFieldRange"; -import CustomSelect from "./fieldsType/CustomSelect"; -import CustomDatePicker from "../CustomDatePicker"; -import CustomDatePickerRange from "./fieldsType/CustomDate/CustomDatePickerRange"; -import CustomSelectMultiple from "./fieldsType/CustomSelectMultiple"; -import CustomTextField from "./fieldsType/CustomTextField"; -import FilterOptionList from "./FilterOptionList"; - -const filterModeOptionFa = { - equals: "برابر", - notEquals: "نابرابر", - contains: "شامل", - lessThan: "کوچکتر", - greaterThan: "بزرگتر", - fuzzy: "فازی", - between: "مابین", -}; - -function FilterField({ - item, - filterParameters, - handleChange, - handleBlur, - dependencyFieldValue, - setFieldValue, - resetForm, - errors, -}) { - const [anchorEl, setAnchorEl] = useState(null); - const defaultFilterTranslation = filterModeOptionFa[filterParameters.filterMode] || filterParameters.filterMode; - - const handleOpenFilterBox = (event) => { - setAnchorEl(event.currentTarget); - }; - - const renderField = () => { - const commonProps = { - item, - filterParameters, - defaultFilterTranslation, - handleOpenFilterBox, - dependencyFieldValue, - setFieldValue, - handleChange, - handleBlur, - errors, - }; - - switch (filterParameters.datatype) { - case "numeric": - if (filterParameters.filterMode === "between") { - return ; - } - if (filterParameters.filterMode === "equals") { - return item.SelectComponent ? ( - - ) : ( - - ); - } - break; - case "date": - if (filterParameters.filterMode === "equals") { - return ; - } - if (filterParameters.filterMode === "between") { - return ; - } - break; - - case "array": - if (filterParameters.filterMode === "equals") { - return ; - } - break; - - default: - return ; - } - }; - - return ( - <> - {renderField()} - {Array.isArray(item.filterModeOptions) && ( - - )} - - ); -} - -export default FilterField; +import { useState } from "react"; +import CustomTextFieldRange from "./fieldsType/CustomTextFieldRange"; +import CustomSelect from "./fieldsType/CustomSelect"; +import CustomDatePicker from "../CustomDatePicker"; +import CustomDatePickerRange from "./fieldsType/CustomDate/CustomDatePickerRange"; +import CustomSelectMultiple from "./fieldsType/CustomSelectMultiple"; +import CustomTextField from "./fieldsType/CustomTextField"; +import FilterOptionList from "./FilterOptionList"; + +const filterModeOptionFa = { + equals: "برابر", + notEquals: "نابرابر", + contains: "شامل", + lessThan: "کوچکتر", + greaterThan: "بزرگتر", + fuzzy: "فازی", + between: "مابین", +}; + +function FilterField({ + item, + filterParameters, + handleChange, + handleBlur, + dependencyFieldValue, + setFieldValue, + resetForm, + errors, +}) { + const [anchorEl, setAnchorEl] = useState(null); + const defaultFilterTranslation = filterModeOptionFa[filterParameters.filterMode] || filterParameters.filterMode; + + const handleOpenFilterBox = (event) => { + setAnchorEl(event.currentTarget); + }; + + const renderField = () => { + const commonProps = { + item, + filterParameters, + defaultFilterTranslation, + handleOpenFilterBox, + dependencyFieldValue, + setFieldValue, + handleChange, + handleBlur, + errors, + }; + + switch (filterParameters.datatype) { + case "numeric": + if (filterParameters.filterMode === "between") { + return ; + } + if (filterParameters.filterMode === "equals") { + return item.SelectComponent ? ( + + ) : ( + + ); + } + break; + case "date": + if (filterParameters.filterMode === "equals") { + return ; + } + if (filterParameters.filterMode === "between") { + return ; + } + break; + + case "array": + if (filterParameters.filterMode === "equals") { + return ; + } + break; + + default: + return ; + } + }; + + return ( + <> + {renderField()} + {Array.isArray(item.filterModeOptions) && ( + + )} + + ); +} + +export default FilterField; diff --git a/src/core/components/FilterDrawer/FilterOptionList.jsx b/src/core/components/FilterDrawer/FilterOptionList.jsx index 1a797f6..400c9af 100644 --- a/src/core/components/FilterDrawer/FilterOptionList.jsx +++ b/src/core/components/FilterDrawer/FilterOptionList.jsx @@ -1,47 +1,47 @@ -"use client"; - -import { ListItem, Menu } from "@mui/material"; -import { useState } from "react"; - -function FilterOptionList({ - filterType, - filterOption, - filterParameters, - anchorEl, - filterModeOptionFa, - setAnchorEl, - handleChange, -}) { - const [selectedFilter, setSelectedFilter] = useState(filterType); - - const handleChangeItem = (event, index) => { - handleChange({ - ...filterParameters, - value: filterOption[index] === "between" ? ["", ""] : "", - filterMode: filterOption[index], - }); - setSelectedFilter(filterOption[index]); - setAnchorEl(null); - }; - - const handleCloseFilterBox = () => { - setAnchorEl(null); - }; - - return ( - - {filterOption.map((option, index) => ( - handleChangeItem(event, index)} - selected={option === selectedFilter} - sx={{ cursor: "pointer", width: "100px", display: "flex", justifyContent: "center" }} - > - {filterModeOptionFa[option]} - - ))} - - ); -} - -export default FilterOptionList; +"use client"; + +import { ListItem, Menu } from "@mui/material"; +import { useState } from "react"; + +function FilterOptionList({ + filterType, + filterOption, + filterParameters, + anchorEl, + filterModeOptionFa, + setAnchorEl, + handleChange, +}) { + const [selectedFilter, setSelectedFilter] = useState(filterType); + + const handleChangeItem = (event, index) => { + handleChange({ + ...filterParameters, + value: filterOption[index] === "between" ? ["", ""] : "", + filterMode: filterOption[index], + }); + setSelectedFilter(filterOption[index]); + setAnchorEl(null); + }; + + const handleCloseFilterBox = () => { + setAnchorEl(null); + }; + + return ( + + {filterOption.map((option, index) => ( + handleChangeItem(event, index)} + selected={option === selectedFilter} + sx={{ cursor: "pointer", width: "100px", display: "flex", justifyContent: "center" }} + > + {filterModeOptionFa[option]} + + ))} + + ); +} + +export default FilterOptionList; diff --git a/src/core/components/FilterDrawer/fieldsType/CustomDate/CustomDatePicker.jsx b/src/core/components/FilterDrawer/fieldsType/CustomDate/CustomDatePicker.jsx index e207cfb..fb8d9fb 100644 --- a/src/core/components/FilterDrawer/fieldsType/CustomDate/CustomDatePicker.jsx +++ b/src/core/components/FilterDrawer/fieldsType/CustomDate/CustomDatePicker.jsx @@ -1,23 +1,23 @@ -import React from "react"; -import MuiDatePicker from "@/core/components/DataTable/filter/fieldsType/CustomDate/MuiDatePicker"; -import { Typography } from "@mui/material"; - -function CustomDatePicker({ column, filterParameters, defaultFilterTranslation, handleChange }) { - return ( - { - handleChange({ ...filterParameters, value: formattedDate }); - }} - placeholder={column.header} - helperText={ - - نوع فیلتر: {defaultFilterTranslation} (تاریخ) - - } - /> - ); -} - -export default CustomDatePicker; +import React from "react"; +import MuiDatePicker from "@/core/components/DataTable/filter/fieldsType/CustomDate/MuiDatePicker"; +import { Typography } from "@mui/material"; + +function CustomDatePicker({ column, filterParameters, defaultFilterTranslation, handleChange }) { + return ( + { + handleChange({ ...filterParameters, value: formattedDate }); + }} + placeholder={column.header} + helperText={ + + نوع فیلتر: {defaultFilterTranslation} (تاریخ) + + } + /> + ); +} + +export default CustomDatePicker; diff --git a/src/core/components/FilterDrawer/fieldsType/CustomDate/CustomDatePickerRange.jsx b/src/core/components/FilterDrawer/fieldsType/CustomDate/CustomDatePickerRange.jsx index 58c597f..b3ce7eb 100644 --- a/src/core/components/FilterDrawer/fieldsType/CustomDate/CustomDatePickerRange.jsx +++ b/src/core/components/FilterDrawer/fieldsType/CustomDate/CustomDatePickerRange.jsx @@ -1,41 +1,41 @@ -"use client"; - -import React from "react"; -import { Box, Typography } from "@mui/material"; -import MuiDatePicker from "@/core/components/DataTable/filter/fieldsType/CustomDate/MuiDatePicker"; - -function CustomDatePickerRange({ item, filterParameters, defaultFilterTranslation, handleChange, errors }) { - return ( - - { - handleChange({ ...filterParameters, value: [formattedDate, filterParameters.value[1]] }); - }} - maxDate={filterParameters.value[1]} - placeholder={`از تاریخ`} - helperText={ - - نوع فیلتر: {defaultFilterTranslation} (تاریخ) - - } - /> - { - handleChange({ ...filterParameters, value: [filterParameters.value[0], formattedDate] }); - }} - minDate={filterParameters.value[0]} - placeholder={`تا تاریخ`} - helperText={errors?.[`${item.id}`]?.value ? errors?.[`${item.id}`]?.value.message : null} - error={Boolean(errors?.[`${item.id}`]?.value)} - /> - - ); -} - -export default CustomDatePickerRange; +"use client"; + +import React from "react"; +import { Box, Typography } from "@mui/material"; +import MuiDatePicker from "@/core/components/DataTable/filter/fieldsType/CustomDate/MuiDatePicker"; + +function CustomDatePickerRange({ item, filterParameters, defaultFilterTranslation, handleChange, errors }) { + return ( + + { + handleChange({ ...filterParameters, value: [formattedDate, filterParameters.value[1]] }); + }} + maxDate={filterParameters.value[1]} + placeholder={`از تاریخ`} + helperText={ + + نوع فیلتر: {defaultFilterTranslation} (تاریخ) + + } + /> + { + handleChange({ ...filterParameters, value: [filterParameters.value[0], formattedDate] }); + }} + minDate={filterParameters.value[0]} + placeholder={`تا تاریخ`} + helperText={errors?.[`${item.id}`]?.value ? errors?.[`${item.id}`]?.value.message : null} + error={Boolean(errors?.[`${item.id}`]?.value)} + /> + + ); +} + +export default CustomDatePickerRange; diff --git a/src/core/components/FilterDrawer/fieldsType/CustomDate/MuiDatePicker.jsx b/src/core/components/FilterDrawer/fieldsType/CustomDate/MuiDatePicker.jsx index d2d9df0..aa93528 100644 --- a/src/core/components/FilterDrawer/fieldsType/CustomDate/MuiDatePicker.jsx +++ b/src/core/components/FilterDrawer/fieldsType/CustomDate/MuiDatePicker.jsx @@ -1,72 +1,72 @@ -import React from "react"; -import { LocalizationProvider, MobileDatePicker } from "@mui/x-date-pickers"; -import { AdapterDateFnsJalali } from "@mui/x-date-pickers/AdapterDateFnsJalali"; -import { faIR } from "@mui/x-date-pickers/locales"; -import { Box, FormHelperText, IconButton, InputAdornment } from "@mui/material"; -import ClearIcon from "@mui/icons-material/Clear"; -import moment from "jalali-moment"; - -function MuiDatePicker({ label, value, setFieldValue, name, minDate, maxDate, helperText, placeholder, error }) { - return ( - - - { - const date = new Date(value); - const formattedDate = moment(date).locale("en").format("YYYY-MM-DD"); - setFieldValue(name, formattedDate); - }} - minDate={minDate ? new Date(minDate) : null} - maxDate={maxDate ? new Date(maxDate) : null} - slotProps={{ - textField: { - size: "small", - error: error, - placeholder: placeholder, - InputProps: { - endAdornment: ( - - { - event.stopPropagation(); - setFieldValue(name, ""); - }} - sx={{ - color: "#bfbfbf", - "&:hover": { - backgroundColor: "rgba(189, 189, 189, 0.1)", - color: "#363434", - }, - }} - > - - - - ), - }, - InputLabelProps: { - shrink: true, - }, - }, - }} - /> - {/* - {helperText ? helperText : ""} - */} - - - ); -} - -export default MuiDatePicker; +import React from "react"; +import { LocalizationProvider, MobileDatePicker } from "@mui/x-date-pickers"; +import { AdapterDateFnsJalali } from "@mui/x-date-pickers/AdapterDateFnsJalali"; +import { faIR } from "@mui/x-date-pickers/locales"; +import { Box, FormHelperText, IconButton, InputAdornment } from "@mui/material"; +import ClearIcon from "@mui/icons-material/Clear"; +import moment from "jalali-moment"; + +function MuiDatePicker({ label, value, setFieldValue, name, minDate, maxDate, helperText, placeholder, error }) { + return ( + + + { + const date = new Date(value); + const formattedDate = moment(date).locale("en").format("YYYY-MM-DD"); + setFieldValue(name, formattedDate); + }} + minDate={minDate ? new Date(minDate) : null} + maxDate={maxDate ? new Date(maxDate) : null} + slotProps={{ + textField: { + size: "small", + error: error, + placeholder: placeholder, + InputProps: { + endAdornment: ( + + { + event.stopPropagation(); + setFieldValue(name, ""); + }} + sx={{ + color: "#bfbfbf", + "&:hover": { + backgroundColor: "rgba(189, 189, 189, 0.1)", + color: "#363434", + }, + }} + > + + + + ), + }, + InputLabelProps: { + shrink: true, + }, + }, + }} + /> + {/* + {helperText ? helperText : ""} + */} + + + ); +} + +export default MuiDatePicker; diff --git a/src/core/components/FilterDrawer/fieldsType/CustomSelect.jsx b/src/core/components/FilterDrawer/fieldsType/CustomSelect.jsx index 61172e6..32b0ffa 100644 --- a/src/core/components/FilterDrawer/fieldsType/CustomSelect.jsx +++ b/src/core/components/FilterDrawer/fieldsType/CustomSelect.jsx @@ -1,30 +1,30 @@ -"use client"; - -import { FormControl, InputLabel, MenuItem, OutlinedInput, Select } from "@mui/material"; -function CustomSelect({ item, filterParameters, handleChange }) { - return ( - - - {item.header} - - - - ); -} - -export default CustomSelect; +"use client"; + +import { FormControl, InputLabel, MenuItem, OutlinedInput, Select } from "@mui/material"; +function CustomSelect({ item, filterParameters, handleChange }) { + return ( + + + {item.header} + + + + ); +} + +export default CustomSelect; diff --git a/src/core/components/FilterDrawer/fieldsType/CustomSelectByDependency.jsx b/src/core/components/FilterDrawer/fieldsType/CustomSelectByDependency.jsx index 69536cd..6f88ea4 100644 --- a/src/core/components/FilterDrawer/fieldsType/CustomSelectByDependency.jsx +++ b/src/core/components/FilterDrawer/fieldsType/CustomSelectByDependency.jsx @@ -1,30 +1,30 @@ -"use client"; - -import { FormControl, InputLabel, MenuItem, OutlinedInput, Select } from "@mui/material"; -function CustomSelectByDependency({ item, filterParameters, value, handleChange, selectOption }) { - return ( - - - {item.header} - - - - ); -} - -export default CustomSelectByDependency; +"use client"; + +import { FormControl, InputLabel, MenuItem, OutlinedInput, Select } from "@mui/material"; +function CustomSelectByDependency({ item, filterParameters, value, handleChange, selectOption }) { + return ( + + + {item.header} + + + + ); +} + +export default CustomSelectByDependency; diff --git a/src/core/components/FilterDrawer/fieldsType/CustomSelectMultiple.jsx b/src/core/components/FilterDrawer/fieldsType/CustomSelectMultiple.jsx index c1fd7fa..e7cf9e2 100644 --- a/src/core/components/FilterDrawer/fieldsType/CustomSelectMultiple.jsx +++ b/src/core/components/FilterDrawer/fieldsType/CustomSelectMultiple.jsx @@ -1,55 +1,55 @@ -"use client"; - -import { - Box, - Chip, - FormControl, - FormHelperText, - InputLabel, - MenuItem, - OutlinedInput, - Select, - Typography, -} from "@mui/material"; - -function CustomSelectMultiple({ item, filterParameters, handleChange }) { - const selectOption = item.selectOption; - - const getLabelForValue = (value) => { - const option = selectOption.find((opt) => opt.value === value); - return option ? option.label : value; - }; - - return ( - - - {item.header} - - - - ); -} - -export default CustomSelectMultiple; +"use client"; + +import { + Box, + Chip, + FormControl, + FormHelperText, + InputLabel, + MenuItem, + OutlinedInput, + Select, + Typography, +} from "@mui/material"; + +function CustomSelectMultiple({ item, filterParameters, handleChange }) { + const selectOption = item.selectOption; + + const getLabelForValue = (value) => { + const option = selectOption.find((opt) => opt.value === value); + return option ? option.label : value; + }; + + return ( + + + {item.header} + + + + ); +} + +export default CustomSelectMultiple; diff --git a/src/core/components/FilterDrawer/fieldsType/CustomTextField.jsx b/src/core/components/FilterDrawer/fieldsType/CustomTextField.jsx index 86a9c57..7a1ec92 100644 --- a/src/core/components/FilterDrawer/fieldsType/CustomTextField.jsx +++ b/src/core/components/FilterDrawer/fieldsType/CustomTextField.jsx @@ -1,29 +1,29 @@ -import { InputAdornment, TextField, Typography } from "@mui/material"; -import FilterListIcon from "@mui/icons-material/FilterList"; - -function CustomTextField({ item, filterParameters, handleOpenFilterBox, handleBlur, handleChange }) { - return ( - handleChange({ ...filterParameters, value: e.target.value })} - onBlur={handleBlur} - fullWidth - variant="outlined" - size="small" - sx={{ my: 1 }} - InputProps={{ - endAdornment: ( - - - - ), - }} - InputLabelProps={{ shrink: true }} - /> - ); -} - -export default CustomTextField; +import { InputAdornment, TextField, Typography } from "@mui/material"; +import FilterListIcon from "@mui/icons-material/FilterList"; + +function CustomTextField({ item, filterParameters, handleOpenFilterBox, handleBlur, handleChange }) { + return ( + handleChange({ ...filterParameters, value: e.target.value })} + onBlur={handleBlur} + fullWidth + variant="outlined" + size="small" + sx={{ my: 1 }} + InputProps={{ + endAdornment: ( + + + + ), + }} + InputLabelProps={{ shrink: true }} + /> + ); +} + +export default CustomTextField; diff --git a/src/core/components/FilterDrawer/fieldsType/CustomTextFieldRange.jsx b/src/core/components/FilterDrawer/fieldsType/CustomTextFieldRange.jsx index 147ec85..af63d67 100644 --- a/src/core/components/FilterDrawer/fieldsType/CustomTextFieldRange.jsx +++ b/src/core/components/FilterDrawer/fieldsType/CustomTextFieldRange.jsx @@ -1,62 +1,62 @@ -import { Box, InputAdornment, TextField, Typography } from "@mui/material"; -import FilterListIcon from "@mui/icons-material/FilterList"; - -function CustomTextFieldRange({ - item, - defaultFilterTranslation, - handleOpenFilterBox, - handleChange, - filterParameters, - handleBlur, - errors, -}) { - return ( - - - handleChange({ ...filterParameters, value: [e.target.value, filterParameters.value[1]] }) - } - onBlur={handleBlur} - label={از {item.header}} - value={filterParameters.value[0]} - fullWidth - error={touched?.[`${item.id}`]?.value && Boolean(errors?.[`${item.id}`]?.value)} - helperText={ - - نوع فیلتر: {defaultFilterTranslation} - - } - variant="outlined" - size="small" - sx={{ my: 1, marginRight: 1 }} - /> - - handleChange({ ...filterParameters, value: [filterParameters.value[0], e.target.value] }) - } - onBlur={handleBlur} - error={Boolean(errors?.[`${item.id}`]?.value)} - helperText={errors?.[`${item.id}`]?.value ? errors?.[`${item.id}`]?.value.message : null} - label={تا {item.header}} - value={filterParameters.value[1]} - fullWidth - variant="outlined" - size="small" - sx={{ my: 1 }} - InputProps={{ - endAdornment: ( - - - - ), - }} - /> - - ); -} - -export default CustomTextFieldRange; +import { Box, InputAdornment, TextField, Typography } from "@mui/material"; +import FilterListIcon from "@mui/icons-material/FilterList"; + +function CustomTextFieldRange({ + item, + defaultFilterTranslation, + handleOpenFilterBox, + handleChange, + filterParameters, + handleBlur, + errors, +}) { + return ( + + + handleChange({ ...filterParameters, value: [e.target.value, filterParameters.value[1]] }) + } + onBlur={handleBlur} + label={از {item.header}} + value={filterParameters.value[0]} + fullWidth + error={touched?.[`${item.id}`]?.value && Boolean(errors?.[`${item.id}`]?.value)} + helperText={ + + نوع فیلتر: {defaultFilterTranslation} + + } + variant="outlined" + size="small" + sx={{ my: 1, marginRight: 1 }} + /> + + handleChange({ ...filterParameters, value: [filterParameters.value[0], e.target.value] }) + } + onBlur={handleBlur} + error={Boolean(errors?.[`${item.id}`]?.value)} + helperText={errors?.[`${item.id}`]?.value ? errors?.[`${item.id}`]?.value.message : null} + label={تا {item.header}} + value={filterParameters.value[1]} + fullWidth + variant="outlined" + size="small" + sx={{ my: 1 }} + InputProps={{ + endAdornment: ( + + + + ), + }} + /> + + ); +} + +export default CustomTextFieldRange; diff --git a/src/core/components/FilterDrawer/index.jsx b/src/core/components/FilterDrawer/index.jsx index a231b71..50f2355 100644 --- a/src/core/components/FilterDrawer/index.jsx +++ b/src/core/components/FilterDrawer/index.jsx @@ -1,153 +1,153 @@ -import { yupResolver } from "@hookform/resolvers/yup"; -import { Cancel, FilterAlt } from "@mui/icons-material"; -import { Box, Button, IconButton, Typography } from "@mui/material"; -import { useForm } from "react-hook-form"; -import * as Yup from "yup"; -import ScrollBox from "../ScrollBox"; -import FilterController from "./FilterController"; -import FilterControllerWithDependency from "./FilterControllerWithDependency"; - -const headerSx = { - display: "flex", - alignItems: "center", - justifyContent: "space-between", - px: 2, - py: 1, - backgroundColor: "#155175", - boxShadow: "rgba(0, 0, 0, 0.19) 0px 10px 20px, rgba(0, 0, 0, 0.23) 0px 6px 6px", - maxWidth: "450px", -}; - -const headerTitleSx = { display: "flex", alignItems: "center" }; -const headerIconSx = { color: "#fff", mr: 1 }; -const iconButtonSx = { color: "#fff" }; - -const formContainerSx = { px: 2, py: 3 }; -const footerSx = { display: "flex", justifyContent: "center", alignItems: "center", pb: 2 }; - -const submitButtonSx = { - px: 8, - boxShadow: "rgba(0, 0, 0, 0.23) 0px 6px 6px, rgba(0, 0, 0, 0.19) 10px 0px 20px", - backgroundColor: "primary2", - ":hover": { backgroundColor: "primary2" }, -}; - -const validationSchema = Yup.object({ - activity_date_time: Yup.array() - .of(Yup.string().nullable()) - .test({ - test(value, ctx) { - const [start, end] = value || ["", ""]; - if ((start && !end) || (!start && end)) { - return ctx.createError({ message: "این بخش را تکمیل نمایید" }); - } - return true; - }, - }), -}); - -const FilterDrawer = ({ defaultValues, setFilterData, closeDrawer }) => { - const { - control, - errors, - reset, - handleSubmit, - formState: { isDirty }, - } = useForm({ - defaultValues, - resolver: yupResolver( - Yup.object( - Object.keys(defaultValues).reduce((acc, key) => { - const initialValue = defaultValues[key]; - if (initialValue.filterMode === "between") { - acc[key] = Yup.object().shape({ - value: Yup.array() - .of(Yup.string().nullable()) - .test({ - test(value, ctx) { - const [start, end] = value || ["", ""]; - if ( - initialValue.datatype === "numeric" && - parseInt(end, 10) <= parseInt(start, 10) - ) { - return ctx.createError({ - message: `مقدار وارده باید بیشتر از (${start}) باشد`, - }); - } else if ((start && !end) || (!start && end)) { - return ctx.createError({ - message: "این بخش را تکمیل نمایید", - }); - } - return true; - }, - }), - }); - } - return acc; - }, {}) - ) - ), - mode: "all", - }); - - const onSubmit = (data) => { - setFilterData(data); - closeDrawer(); - }; - - return ( - <> - - - - - فیلتر - - - - - - - -
    - - {Object.values(defaultValues).map( - (item) => - item.enable && - (item.dependencyId ? ( - - ) : ( - - )) - )} - - - - - -
    -
    - - ); -}; -export default FilterDrawer; +import { yupResolver } from "@hookform/resolvers/yup"; +import { Cancel, FilterAlt } from "@mui/icons-material"; +import { Box, Button, IconButton, Typography } from "@mui/material"; +import { useForm } from "react-hook-form"; +import * as Yup from "yup"; +import ScrollBox from "../ScrollBox"; +import FilterController from "./FilterController"; +import FilterControllerWithDependency from "./FilterControllerWithDependency"; + +const headerSx = { + display: "flex", + alignItems: "center", + justifyContent: "space-between", + px: 2, + py: 1, + backgroundColor: "#155175", + boxShadow: "rgba(0, 0, 0, 0.19) 0px 10px 20px, rgba(0, 0, 0, 0.23) 0px 6px 6px", + maxWidth: "450px", +}; + +const headerTitleSx = { display: "flex", alignItems: "center" }; +const headerIconSx = { color: "#fff", mr: 1 }; +const iconButtonSx = { color: "#fff" }; + +const formContainerSx = { px: 2, py: 3 }; +const footerSx = { display: "flex", justifyContent: "center", alignItems: "center", pb: 2 }; + +const submitButtonSx = { + px: 8, + boxShadow: "rgba(0, 0, 0, 0.23) 0px 6px 6px, rgba(0, 0, 0, 0.19) 10px 0px 20px", + backgroundColor: "primary2", + ":hover": { backgroundColor: "primary2" }, +}; + +const validationSchema = Yup.object({ + activity_date_time: Yup.array() + .of(Yup.string().nullable()) + .test({ + test(value, ctx) { + const [start, end] = value || ["", ""]; + if ((start && !end) || (!start && end)) { + return ctx.createError({ message: "این بخش را تکمیل نمایید" }); + } + return true; + }, + }), +}); + +const FilterDrawer = ({ defaultValues, setFilterData, closeDrawer }) => { + const { + control, + errors, + reset, + handleSubmit, + formState: { isDirty }, + } = useForm({ + defaultValues, + resolver: yupResolver( + Yup.object( + Object.keys(defaultValues).reduce((acc, key) => { + const initialValue = defaultValues[key]; + if (initialValue.filterMode === "between") { + acc[key] = Yup.object().shape({ + value: Yup.array() + .of(Yup.string().nullable()) + .test({ + test(value, ctx) { + const [start, end] = value || ["", ""]; + if ( + initialValue.datatype === "numeric" && + parseInt(end, 10) <= parseInt(start, 10) + ) { + return ctx.createError({ + message: `مقدار وارده باید بیشتر از (${start}) باشد`, + }); + } else if ((start && !end) || (!start && end)) { + return ctx.createError({ + message: "این بخش را تکمیل نمایید", + }); + } + return true; + }, + }), + }); + } + return acc; + }, {}) + ) + ), + mode: "all", + }); + + const onSubmit = (data) => { + setFilterData(data); + closeDrawer(); + }; + + return ( + <> + + + + + فیلتر + + + + + + + +
    + + {Object.values(defaultValues).map( + (item) => + item.enable && + (item.dependencyId ? ( + + ) : ( + + )) + )} + + + + + +
    +
    + + ); +}; +export default FilterDrawer; diff --git a/src/core/components/FlyToLocation.jsx b/src/core/components/FlyToLocation.jsx index 0f63772..8efc8f6 100644 --- a/src/core/components/FlyToLocation.jsx +++ b/src/core/components/FlyToLocation.jsx @@ -1,32 +1,32 @@ -import { useEffect, useState } from "react"; -import { useMap } from "react-leaflet"; - -const FlyToUserLocation = ({ Component }) => { - const [userPosition, setUserPosition] = useState(null); - const map = useMap(); - - const handleLocateUser = () => { - if (navigator.geolocation) { - navigator.geolocation.getCurrentPosition( - (position) => { - setUserPosition([position.coords.latitude, position.coords.longitude]); - }, - (error) => { - console.error("Location error:", error); - } - ); - } else { - alert("مرورگر شما از موقعیت‌یاب پشتیبانی نمی‌کند."); - } - }; - - useEffect(() => { - if (userPosition) { - map.flyTo(userPosition, 16); - } - }, [userPosition, map]); - - return ; -}; - -export default FlyToUserLocation; +import { useEffect, useState } from "react"; +import { useMap } from "react-leaflet"; + +const FlyToUserLocation = ({ Component }) => { + const [userPosition, setUserPosition] = useState(null); + const map = useMap(); + + const handleLocateUser = () => { + if (navigator.geolocation) { + navigator.geolocation.getCurrentPosition( + (position) => { + setUserPosition([position.coords.latitude, position.coords.longitude]); + }, + (error) => { + console.error("Location error:", error); + } + ); + } else { + alert("مرورگر شما از موقعیت‌یاب پشتیبانی نمی‌کند."); + } + }; + + useEffect(() => { + if (userPosition) { + map.flyTo(userPosition, 16); + } + }, [userPosition, map]); + + return ; +}; + +export default FlyToUserLocation; diff --git a/src/core/components/FormMaker/DateType.jsx b/src/core/components/FormMaker/DateType.jsx index f928694..09cad15 100644 --- a/src/core/components/FormMaker/DateType.jsx +++ b/src/core/components/FormMaker/DateType.jsx @@ -1,35 +1,35 @@ -import { FormControl } from "@mui/material"; -import CustomDatePicker from "@/core/components/CustomDatePicker"; -import moment from "jalali-moment"; -import { useEffect, useState } from "react"; - -const DateType = ({ itemInfo, defaultValues, setDefaultValues }) => { - const [dateValue, setDateValue] = useState(null); - const handleDateChange = (newValue) => { - const date = new Date(newValue); - const formattedDate = moment(date).locale("fa").format("YYYY/MM/DD"); - setDefaultValues((prev) => ({ - ...prev, - [itemInfo.id]: newValue ? formattedDate : "", - })); - setDateValue(moment(date).format("YYYY/MM/DD")); - }; - - useEffect(() => { - if (defaultValues[itemInfo.id]) { - setDateValue(moment.from(defaultValues[itemInfo.id], "fa", "YYYY/MM/DD")); - } - }, []); - - return ( - - - - ); -}; - -export default DateType; +import { FormControl } from "@mui/material"; +import CustomDatePicker from "@/core/components/CustomDatePicker"; +import moment from "jalali-moment"; +import { useEffect, useState } from "react"; + +const DateType = ({ itemInfo, defaultValues, setDefaultValues }) => { + const [dateValue, setDateValue] = useState(null); + const handleDateChange = (newValue) => { + const date = new Date(newValue); + const formattedDate = moment(date).locale("fa").format("YYYY/MM/DD"); + setDefaultValues((prev) => ({ + ...prev, + [itemInfo.id]: newValue ? formattedDate : "", + })); + setDateValue(moment(date).format("YYYY/MM/DD")); + }; + + useEffect(() => { + if (defaultValues[itemInfo.id]) { + setDateValue(moment.from(defaultValues[itemInfo.id], "fa", "YYYY/MM/DD")); + } + }, []); + + return ( + + + + ); +}; + +export default DateType; diff --git a/src/core/components/FormMaker/InputType.jsx b/src/core/components/FormMaker/InputType.jsx index af90551..5bfb7ee 100644 --- a/src/core/components/FormMaker/InputType.jsx +++ b/src/core/components/FormMaker/InputType.jsx @@ -1,31 +1,31 @@ -import { FormControl, InputLabel, OutlinedInput } from "@mui/material"; -import React from "react"; - -const InputType = ({ itemInfo, defaultValues, setDefaultValues }) => { - const handleChange = (event) => { - const { value } = event.target; - setDefaultValues((prevValues) => ({ - ...prevValues, - [itemInfo.id]: value, - })); - }; - const label = itemInfo.unit ? `${itemInfo.name} (${itemInfo.unit})` : itemInfo.name; - - return ( - - {label} - - - ); -}; - -export default InputType; +import { FormControl, InputLabel, OutlinedInput } from "@mui/material"; +import React from "react"; + +const InputType = ({ itemInfo, defaultValues, setDefaultValues }) => { + const handleChange = (event) => { + const { value } = event.target; + setDefaultValues((prevValues) => ({ + ...prevValues, + [itemInfo.id]: value, + })); + }; + const label = itemInfo.unit ? `${itemInfo.name} (${itemInfo.unit})` : itemInfo.name; + + return ( + + {label} + + + ); +}; + +export default InputType; diff --git a/src/core/components/FormMaker/SelectType.jsx b/src/core/components/FormMaker/SelectType.jsx index 3292b65..334c5ec 100644 --- a/src/core/components/FormMaker/SelectType.jsx +++ b/src/core/components/FormMaker/SelectType.jsx @@ -1,34 +1,34 @@ -import { FormControl, InputLabel, MenuItem, Select } from "@mui/material"; -import React from "react"; - -const SelectType = ({ itemInfo, defaultValues, setDefaultValues }) => { - const handleChange = (event) => { - const newValue = event.target.value; - setDefaultValues((prev) => ({ - ...prev, - [itemInfo.id]: newValue, - })); - }; - const label = itemInfo.unit ? `${itemInfo.name} (${itemInfo.unit})` : itemInfo.name; - return ( - - {label} - - - ); -}; - -export default SelectType; +import { FormControl, InputLabel, MenuItem, Select } from "@mui/material"; +import React from "react"; + +const SelectType = ({ itemInfo, defaultValues, setDefaultValues }) => { + const handleChange = (event) => { + const newValue = event.target.value; + setDefaultValues((prev) => ({ + ...prev, + [itemInfo.id]: newValue, + })); + }; + const label = itemInfo.unit ? `${itemInfo.name} (${itemInfo.unit})` : itemInfo.name; + return ( + + {label} + + + ); +}; + +export default SelectType; diff --git a/src/core/components/FormMaker/index.jsx b/src/core/components/FormMaker/index.jsx index 2699eb6..ad5d592 100644 --- a/src/core/components/FormMaker/index.jsx +++ b/src/core/components/FormMaker/index.jsx @@ -1,33 +1,33 @@ -import InputType from "./InputType"; -import SelectType from "./SelectType"; -import DateType from "./DateType"; -import { Grid } from "@mui/material"; - -const componentMap = { - input: InputType, - select: SelectType, - date: DateType, -}; - -const FormMaker = ({ formInfo, defaultValues, setDefaultValues }) => { - return ( - - {formInfo?.map((itemInfo) => { - const Component = componentMap[itemInfo.type] || null; - return ( - - {Component ? ( - - ) : null} - - ); - })} - - ); -}; - -export default FormMaker; +import InputType from "./InputType"; +import SelectType from "./SelectType"; +import DateType from "./DateType"; +import { Grid } from "@mui/material"; + +const componentMap = { + input: InputType, + select: SelectType, + date: DateType, +}; + +const FormMaker = ({ formInfo, defaultValues, setDefaultValues }) => { + return ( + + {formInfo?.map((itemInfo) => { + const Component = componentMap[itemInfo.type] || null; + return ( + + {Component ? ( + + ) : null} + + ); + })} + + ); +}; + +export default FormMaker; diff --git a/src/core/components/HourSelect.jsx b/src/core/components/HourSelect.jsx index 37f62cd..efe43bd 100644 --- a/src/core/components/HourSelect.jsx +++ b/src/core/components/HourSelect.jsx @@ -1,26 +1,26 @@ -import { FormControl, FormHelperText, InputLabel, MenuItem, Select } from "@mui/material"; - -const HourSelect = ({ label, error, name, value, onChange }) => { - return ( - - {label} - - {error?.message} - - ); -}; -export default HourSelect; +import { FormControl, FormHelperText, InputLabel, MenuItem, Select } from "@mui/material"; + +const HourSelect = ({ label, error, name, value, onChange }) => { + return ( + + {label} + + {error?.message} + + ); +}; +export default HourSelect; diff --git a/src/core/components/LoadingHardPage.jsx b/src/core/components/LoadingHardPage.jsx index e0ff917..363c921 100644 --- a/src/core/components/LoadingHardPage.jsx +++ b/src/core/components/LoadingHardPage.jsx @@ -1,61 +1,61 @@ -"use client"; -import { Backdrop, Box, Stack, styled, Typography, useTheme } from "@mui/material"; -import SvgLoading from "@/core/components/svgs/SvgLoading"; -import SvgError from "@/core/components/svgs/SvgError"; - -const LoadingImage = styled(Box)({ - "@keyframes load": { - "0%": { - transform: "scale(1)", - }, - "50%": { - transform: "scale(.5)", - }, - "100%": { - transform: "scale(1)", - }, - }, - animation: "load 2s infinite", -}); - -const LoadingHardPage = ({ - children, - loading, - authState, - sx = {}, - icon = null, - width = 200, - height = 200, - label = "", -}) => { - const theme = useTheme(); - return ( - <> - theme.zIndex.drawer + 1, ...sx }} open={loading}> - - {authState ? ( - - {icon ? ( - {icon} - ) : ( - - )} - - ) : ( - - {icon ? ( - {icon} - ) : ( - - )} - - )} - {label} - - - {children} - - ); -}; - -export default LoadingHardPage; +"use client"; +import { Backdrop, Box, Stack, styled, Typography, useTheme } from "@mui/material"; +import SvgLoading from "@/core/components/svgs/SvgLoading"; +import SvgError from "@/core/components/svgs/SvgError"; + +const LoadingImage = styled(Box)({ + "@keyframes load": { + "0%": { + transform: "scale(1)", + }, + "50%": { + transform: "scale(.5)", + }, + "100%": { + transform: "scale(1)", + }, + }, + animation: "load 2s infinite", +}); + +const LoadingHardPage = ({ + children, + loading, + authState, + sx = {}, + icon = null, + width = 200, + height = 200, + label = "", +}) => { + const theme = useTheme(); + return ( + <> + theme.zIndex.drawer + 1, ...sx }} open={loading}> + + {authState ? ( + + {icon ? ( + {icon} + ) : ( + + )} + + ) : ( + + {icon ? ( + {icon} + ) : ( + + )} + + )} + {label} + + + {children} + + ); +}; + +export default LoadingHardPage; diff --git a/src/core/components/LtrTextField.jsx b/src/core/components/LtrTextField.jsx index f31527c..77e8711 100644 --- a/src/core/components/LtrTextField.jsx +++ b/src/core/components/LtrTextField.jsx @@ -1,10 +1,10 @@ -import { TextField, styled } from "@mui/material"; - -const LtrTextField = styled(TextField)` - .MuiInputBase-input { - /* @noflip */ - direction: ltr; - } -`; - -export default LtrTextField; +import { TextField, styled } from "@mui/material"; + +const LtrTextField = styled(TextField)` + .MuiInputBase-input { + /* @noflip */ + direction: ltr; + } +`; + +export default LtrTextField; diff --git a/src/core/components/MapInfoOneMarker.jsx b/src/core/components/MapInfoOneMarker.jsx index 8a887da..f9644fb 100644 --- a/src/core/components/MapInfoOneMarker.jsx +++ b/src/core/components/MapInfoOneMarker.jsx @@ -1,181 +1,181 @@ -import HereIcon from "@/assets/images/examine_marker_active.png"; -import MapLoading from "@/core/components/MapLayer/Loading"; -import { MyLocation } from "@mui/icons-material"; -import { Alert, Box, Button, Stack, Typography, Zoom } from "@mui/material"; -import L from "leaflet"; -import "leaflet/dist/leaflet.css"; -import dynamic from "next/dynamic"; -import { useEffect, useRef, useState } from "react"; -import { Marker, useMapEvents } from "react-leaflet"; -import FlyToUserLocation from "./FlyToLocation"; - -const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { - loading: () => , - ssr: false, -}); - -const createCustomIcon = (size, iconUrl, labelText, color) => { - if (labelText) { - return L.divIcon({ - className: "custom-marker", // Apply your custom CSS class - html: ` -
    -
    - ${labelText} -
    -
    -
    `, - iconSize: [50, 50], - iconAnchor: [25, 50], - }); - } - - return L.icon({ - iconUrl: iconUrl, - iconSize: size, - iconAnchor: [size[0] / 2, size[1]], - popupAnchor: [0, -size[1]], - }); -}; -const MAX_ZOOM_FOR_MARKER = 13; - -const MapInteraction = ({ setValue, startLat, startLng, title }) => { - const [isMarkerLocked, setIsMarkerLocked] = useState(!!(startLat && startLng)); - const [enableSend, setEnableSend] = useState(false); - const [startIconColor, setStartIconColor] = useState(startLat ? "#1CAC66" : "#003d4f"); - const [markerPosition, setMarkerPosition] = useState( - startLat && startLng ? { lat: startLat, lng: startLng } : null - ); - const markerRef = useRef(); - - const map = useMapEvents({ - move(e) { - setEnableSend(e.target.getZoom() > MAX_ZOOM_FOR_MARKER); - if (!isMarkerLocked && markerRef.current) { - markerRef.current.setLatLng(e.target.getCenter()); - } - }, - zoom(e) { - setEnableSend(e.target.getZoom() > MAX_ZOOM_FOR_MARKER); - if (!isMarkerLocked && markerRef.current) { - markerRef.current.setLatLng(e.target.getCenter()); - } - }, - }); - - useEffect(() => { - if (startLat && startLng) { - const position = { lat: startLat, lng: startLng }; - map.setView(position, 15); - } - }, [startLat, startLng, map]); - - const handleMarkerClick = () => { - if (!enableSend) return; - if (!isMarkerLocked) { - const center = map.getCenter(); - setValue("start_point", { lat: center.lat.toString(), lng: center.lng.toString() }); - setMarkerPosition({ lat: center.lat, lng: center.lng }); // به‌روزرسانی موقعیت مارکر - setIsMarkerLocked(true); - setStartIconColor("#1CAC66"); - } - }; - - const handleUnlockMarker = () => { - setValue("start_point", null); // حذف مقدار قبلی - setIsMarkerLocked(false); // باز کردن قفل مارکر - setMarkerPosition(null); // تنظیم مارکر به مرکز نقشه - setStartIconColor("#003d4f"); - }; - - return ( - <> - - - - - {title} - - - - - - - - ( - - )} - /> - - - ); -}; - -const MapInfoOneMarker = ({ - setValue, - errors, - StartPoint = null, - title = "برای ثبت محل فعالیت، لطفاً نقشه را بیشتر زوم کنید.", -}) => { - return ( - - - - - - - - {errors.start_point && ( - - {errors.start_point.message} - - )} - - - ); -}; - -export default MapInfoOneMarker; +import HereIcon from "@/assets/images/examine_marker_active.png"; +import MapLoading from "@/core/components/MapLayer/Loading"; +import { MyLocation } from "@mui/icons-material"; +import { Alert, Box, Button, Stack, Typography, Zoom } from "@mui/material"; +import L from "leaflet"; +import "leaflet/dist/leaflet.css"; +import dynamic from "next/dynamic"; +import { useEffect, useRef, useState } from "react"; +import { Marker, useMapEvents } from "react-leaflet"; +import FlyToUserLocation from "./FlyToLocation"; + +const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { + loading: () => , + ssr: false, +}); + +const createCustomIcon = (size, iconUrl, labelText, color) => { + if (labelText) { + return L.divIcon({ + className: "custom-marker", // Apply your custom CSS class + html: ` +
    +
    + ${labelText} +
    +
    +
    `, + iconSize: [50, 50], + iconAnchor: [25, 50], + }); + } + + return L.icon({ + iconUrl: iconUrl, + iconSize: size, + iconAnchor: [size[0] / 2, size[1]], + popupAnchor: [0, -size[1]], + }); +}; +const MAX_ZOOM_FOR_MARKER = 13; + +const MapInteraction = ({ setValue, startLat, startLng, title }) => { + const [isMarkerLocked, setIsMarkerLocked] = useState(!!(startLat && startLng)); + const [enableSend, setEnableSend] = useState(false); + const [startIconColor, setStartIconColor] = useState(startLat ? "#1CAC66" : "#003d4f"); + const [markerPosition, setMarkerPosition] = useState( + startLat && startLng ? { lat: startLat, lng: startLng } : null + ); + const markerRef = useRef(); + + const map = useMapEvents({ + move(e) { + setEnableSend(e.target.getZoom() > MAX_ZOOM_FOR_MARKER); + if (!isMarkerLocked && markerRef.current) { + markerRef.current.setLatLng(e.target.getCenter()); + } + }, + zoom(e) { + setEnableSend(e.target.getZoom() > MAX_ZOOM_FOR_MARKER); + if (!isMarkerLocked && markerRef.current) { + markerRef.current.setLatLng(e.target.getCenter()); + } + }, + }); + + useEffect(() => { + if (startLat && startLng) { + const position = { lat: startLat, lng: startLng }; + map.setView(position, 15); + } + }, [startLat, startLng, map]); + + const handleMarkerClick = () => { + if (!enableSend) return; + if (!isMarkerLocked) { + const center = map.getCenter(); + setValue("start_point", { lat: center.lat.toString(), lng: center.lng.toString() }); + setMarkerPosition({ lat: center.lat, lng: center.lng }); // به‌روزرسانی موقعیت مارکر + setIsMarkerLocked(true); + setStartIconColor("#1CAC66"); + } + }; + + const handleUnlockMarker = () => { + setValue("start_point", null); // حذف مقدار قبلی + setIsMarkerLocked(false); // باز کردن قفل مارکر + setMarkerPosition(null); // تنظیم مارکر به مرکز نقشه + setStartIconColor("#003d4f"); + }; + + return ( + <> + + + + + {title} + + + + + + + + ( + + )} + /> + + + ); +}; + +const MapInfoOneMarker = ({ + setValue, + errors, + StartPoint = null, + title = "برای ثبت محل فعالیت، لطفاً نقشه را بیشتر زوم کنید.", +}) => { + return ( + + + + + + + + {errors.start_point && ( + + {errors.start_point.message} + + )} + + + ); +}; + +export default MapInfoOneMarker; diff --git a/src/core/components/MapInfoTwoMarker.jsx b/src/core/components/MapInfoTwoMarker.jsx index 668635c..5dd0a2e 100644 --- a/src/core/components/MapInfoTwoMarker.jsx +++ b/src/core/components/MapInfoTwoMarker.jsx @@ -1,267 +1,267 @@ -import React, { useEffect, useRef, useState } from "react"; -import { Marker, useMapEvents } from "react-leaflet"; -import "leaflet/dist/leaflet.css"; -import L from "leaflet"; -import { Alert, Box, Button, Stack, Typography, Zoom } from "@mui/material"; -import dynamic from "next/dynamic"; -import MapLoading from "@/core/components/MapLayer/Loading"; -import EndIcon from "@/assets/images/examine_marker_active.png"; -import StartIcon from "@/assets/images/examine_marker.png"; -import FlyToUserLocation from "./FlyToLocation"; -import { MyLocation } from "@mui/icons-material"; - -const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { - loading: () => , - ssr: false, -}); -const createCustomIcon = (size, iconUrl, labelText, color) => { - if (labelText) { - return L.divIcon({ - className: "custom-marker", // Apply your custom CSS class - html: ` -
    -
    - ${labelText} -
    -
    -
    `, - iconSize: [50, 50], - iconAnchor: [25, 50], - }); - } - return L.icon({ - iconUrl: iconUrl, - iconSize: size, - iconAnchor: [size[0] / 2, size[1]], - popupAnchor: [0, -size[1]], - }); -}; -const MAX_ZOOM_FOR_MARKER = 13; - -const MapInteraction = ({ setValue, startLat, startLng, endLat, endLng }) => { - const [isStartLocked, setIsStartLocked] = useState(!!(startLat && startLng)); - const [isEndLocked, setIsEndLocked] = useState(!!(endLat && endLng)); - const [startPosition, setStartPosition] = useState(startLat && startLng ? { lat: startLat, lng: startLng } : null); - const [endPosition, setEndPosition] = useState(endLat && endLng ? { lat: endLat, lng: endLng } : null); - const [enableSend, setEnableSend] = useState(false); - const [startIconColor, setStartIconColor] = useState(startLat ? "#1CAC66" : "#003d4f"); - const [endIconColor, setEndIconColor] = useState(endLat ? "#D13131" : "#003d4f"); - const startRef = useRef(); - const endRef = useRef(); - - const map = useMapEvents({ - move(e) { - setEnableSend(e.target.getZoom() > MAX_ZOOM_FOR_MARKER); - if (!isStartLocked && startRef.current) { - startRef.current.setLatLng(e.target.getCenter()); - } else if (isStartLocked && !isEndLocked && endRef.current) { - endRef.current.setLatLng(e.target.getCenter()); - } - }, - zoom(e) { - setEnableSend(e.target.getZoom() > MAX_ZOOM_FOR_MARKER); - if (!isStartLocked && startRef.current) { - startRef.current.setLatLng(e.target.getCenter()); - } else if (isStartLocked && !isEndLocked && endRef.current) { - endRef.current.setLatLng(e.target.getCenter()); - } - }, - }); - - useEffect(() => { - if (startLat && endLng) { - map.fitBounds( - [ - { lat: startLat, lng: startLng }, - { lat: endLat, lng: endLng }, - ], - { paddingTopLeft: [64, 64], paddingBottomRight: [64, 64] } - ); - } - }, [startLat, map, endLng]); - - const handleUnlockStart = () => { - setIsStartLocked(false); - setStartPosition(null); - setValue("start_point", null); - setStartIconColor("#003d4f"); - }; - - const handleUnlockEnd = () => { - setIsEndLocked(false); - setIsStartLocked(false); - setEndPosition(null); - setStartPosition(null); - setValue("end_point", ""); - setValue("start_point", null); - setStartIconColor("#003d4f"); - setEndIconColor("#003d4f"); - }; - - return ( - <> - { - if (!enableSend) return; - if (!isStartLocked) { - const center = map.getCenter(); - setValue("start_point", { lat: center.lat.toString(), lng: center.lng.toString() }); - setStartPosition({ lat: center.lat, lng: center.lng }); - setIsStartLocked(true); - setStartIconColor("#1CAC66"); - map.panBy([25, 25]); - } - }, - }} - /> - - - - برای ثبت محل فعالیت، لطفاً نقشه را بیشتر زوم کنید. - - - - {isStartLocked && !isEndLocked && ( - - - - )} - {isStartLocked && ( - <> - - - - برای ثبت محل فعالیت، لطفاً نقشه را بیشتر زوم کنید. - - - - { - if (!enableSend) return; - if (!isEndLocked) { - const center = map.getCenter(); - setValue("end_point", { lat: center.lat.toString(), lng: center.lng.toString() }); - setEndPosition({ lat: center.lat, lng: center.lng }); - setIsEndLocked(true); - setEndIconColor("#D13131"); - map.fitBounds([startPosition, map.getCenter()], { - paddingTopLeft: [64, 64], - paddingBottomRight: [64, 64], - }); - } - }, - }} - /> - - )} - {isEndLocked && ( - - - - )} - - ( - - )} - /> - - - ); -}; - -const MapInfoTwoMarker = ({ setValue, errors, StartPoint = null, EndPoint = null }) => { - return ( - - - - - - - - {errors.start_point && ( - - {errors.start_point.message} - - )} - {errors.end_point && ( - - {errors.end_point.message} - - )} - - - ); -}; -export default MapInfoTwoMarker; +import React, { useEffect, useRef, useState } from "react"; +import { Marker, useMapEvents } from "react-leaflet"; +import "leaflet/dist/leaflet.css"; +import L from "leaflet"; +import { Alert, Box, Button, Stack, Typography, Zoom } from "@mui/material"; +import dynamic from "next/dynamic"; +import MapLoading from "@/core/components/MapLayer/Loading"; +import EndIcon from "@/assets/images/examine_marker_active.png"; +import StartIcon from "@/assets/images/examine_marker.png"; +import FlyToUserLocation from "./FlyToLocation"; +import { MyLocation } from "@mui/icons-material"; + +const MapLayer = dynamic(() => import("@/core/components/MapLayer"), { + loading: () => , + ssr: false, +}); +const createCustomIcon = (size, iconUrl, labelText, color) => { + if (labelText) { + return L.divIcon({ + className: "custom-marker", // Apply your custom CSS class + html: ` +
    +
    + ${labelText} +
    +
    +
    `, + iconSize: [50, 50], + iconAnchor: [25, 50], + }); + } + return L.icon({ + iconUrl: iconUrl, + iconSize: size, + iconAnchor: [size[0] / 2, size[1]], + popupAnchor: [0, -size[1]], + }); +}; +const MAX_ZOOM_FOR_MARKER = 13; + +const MapInteraction = ({ setValue, startLat, startLng, endLat, endLng }) => { + const [isStartLocked, setIsStartLocked] = useState(!!(startLat && startLng)); + const [isEndLocked, setIsEndLocked] = useState(!!(endLat && endLng)); + const [startPosition, setStartPosition] = useState(startLat && startLng ? { lat: startLat, lng: startLng } : null); + const [endPosition, setEndPosition] = useState(endLat && endLng ? { lat: endLat, lng: endLng } : null); + const [enableSend, setEnableSend] = useState(false); + const [startIconColor, setStartIconColor] = useState(startLat ? "#1CAC66" : "#003d4f"); + const [endIconColor, setEndIconColor] = useState(endLat ? "#D13131" : "#003d4f"); + const startRef = useRef(); + const endRef = useRef(); + + const map = useMapEvents({ + move(e) { + setEnableSend(e.target.getZoom() > MAX_ZOOM_FOR_MARKER); + if (!isStartLocked && startRef.current) { + startRef.current.setLatLng(e.target.getCenter()); + } else if (isStartLocked && !isEndLocked && endRef.current) { + endRef.current.setLatLng(e.target.getCenter()); + } + }, + zoom(e) { + setEnableSend(e.target.getZoom() > MAX_ZOOM_FOR_MARKER); + if (!isStartLocked && startRef.current) { + startRef.current.setLatLng(e.target.getCenter()); + } else if (isStartLocked && !isEndLocked && endRef.current) { + endRef.current.setLatLng(e.target.getCenter()); + } + }, + }); + + useEffect(() => { + if (startLat && endLng) { + map.fitBounds( + [ + { lat: startLat, lng: startLng }, + { lat: endLat, lng: endLng }, + ], + { paddingTopLeft: [64, 64], paddingBottomRight: [64, 64] } + ); + } + }, [startLat, map, endLng]); + + const handleUnlockStart = () => { + setIsStartLocked(false); + setStartPosition(null); + setValue("start_point", null); + setStartIconColor("#003d4f"); + }; + + const handleUnlockEnd = () => { + setIsEndLocked(false); + setIsStartLocked(false); + setEndPosition(null); + setStartPosition(null); + setValue("end_point", ""); + setValue("start_point", null); + setStartIconColor("#003d4f"); + setEndIconColor("#003d4f"); + }; + + return ( + <> + { + if (!enableSend) return; + if (!isStartLocked) { + const center = map.getCenter(); + setValue("start_point", { lat: center.lat.toString(), lng: center.lng.toString() }); + setStartPosition({ lat: center.lat, lng: center.lng }); + setIsStartLocked(true); + setStartIconColor("#1CAC66"); + map.panBy([25, 25]); + } + }, + }} + /> + + + + برای ثبت محل فعالیت، لطفاً نقشه را بیشتر زوم کنید. + + + + {isStartLocked && !isEndLocked && ( + + + + )} + {isStartLocked && ( + <> + + + + برای ثبت محل فعالیت، لطفاً نقشه را بیشتر زوم کنید. + + + + { + if (!enableSend) return; + if (!isEndLocked) { + const center = map.getCenter(); + setValue("end_point", { lat: center.lat.toString(), lng: center.lng.toString() }); + setEndPosition({ lat: center.lat, lng: center.lng }); + setIsEndLocked(true); + setEndIconColor("#D13131"); + map.fitBounds([startPosition, map.getCenter()], { + paddingTopLeft: [64, 64], + paddingBottomRight: [64, 64], + }); + } + }, + }} + /> + + )} + {isEndLocked && ( + + + + )} + + ( + + )} + /> + + + ); +}; + +const MapInfoTwoMarker = ({ setValue, errors, StartPoint = null, EndPoint = null }) => { + return ( + + + + + + + + {errors.start_point && ( + + {errors.start_point.message} + + )} + {errors.end_point && ( + + {errors.end_point.message} + + )} + + + ); +}; +export default MapInfoTwoMarker; diff --git a/src/core/components/MapLayer/Loading/index.jsx b/src/core/components/MapLayer/Loading/index.jsx index 806168c..55a991a 100644 --- a/src/core/components/MapLayer/Loading/index.jsx +++ b/src/core/components/MapLayer/Loading/index.jsx @@ -1,13 +1,13 @@ -import { Box, LinearProgress, Stack } from "@mui/material"; - -function MapLoading() { - return ( - - - - - - ); -} - -export default MapLoading; +import { Box, LinearProgress, Stack } from "@mui/material"; + +function MapLoading() { + return ( + + + + + + ); +} + +export default MapLoading; diff --git a/src/core/components/MapLayer/index.jsx b/src/core/components/MapLayer/index.jsx index 1a07c9c..618b857 100644 --- a/src/core/components/MapLayer/index.jsx +++ b/src/core/components/MapLayer/index.jsx @@ -1,43 +1,43 @@ -"use client"; -import { MapContainer, TileLayer, useMap } from "react-leaflet"; - -export const IRAN_CENTER = L.latLng(32.4279, 53.688); - -const MapOptions = ({ options }) => { - const map = useMap(); - if (!options) return; - - if (options.mapDrag) { - map.dragging.enable(); - map.scrollWheelZoom.enable(); - map.touchZoom.enable(); - map.doubleClickZoom.enable(); - } else { - map.dragging.disable(); - map.scrollWheelZoom.disable(); - map.touchZoom.disable(); - map.doubleClickZoom.disable(); - } -}; - -function MapLayer({ children, style, otherLayers, options }) { - return ( - <> - - - - {children} - - {otherLayers} - - ); -} - -export default MapLayer; +"use client"; +import { MapContainer, TileLayer, useMap } from "react-leaflet"; + +export const IRAN_CENTER = L.latLng(32.4279, 53.688); + +const MapOptions = ({ options }) => { + const map = useMap(); + if (!options) return; + + if (options.mapDrag) { + map.dragging.enable(); + map.scrollWheelZoom.enable(); + map.touchZoom.enable(); + map.doubleClickZoom.enable(); + } else { + map.dragging.disable(); + map.scrollWheelZoom.disable(); + map.touchZoom.disable(); + map.doubleClickZoom.disable(); + } +}; + +function MapLayer({ children, style, otherLayers, options }) { + return ( + <> + + + + {children} + + {otherLayers} + + ); +} + +export default MapLayer; diff --git a/src/core/components/MuiDatePicker.jsx b/src/core/components/MuiDatePicker.jsx index f931188..cb2abc5 100644 --- a/src/core/components/MuiDatePicker.jsx +++ b/src/core/components/MuiDatePicker.jsx @@ -1,77 +1,77 @@ -import React from "react"; -import { LocalizationProvider, MobileDatePicker } from "@mui/x-date-pickers"; -import { AdapterDateFnsJalali } from "@mui/x-date-pickers/AdapterDateFnsJalali"; -import { faIR } from "@mui/x-date-pickers/locales"; -import { Box, FormHelperText, IconButton, InputAdornment } from "@mui/material"; -import ClearIcon from "@mui/icons-material/Clear"; -import moment from "jalali-moment"; - -function MuiDatePicker({ value, setFieldValue, name, minDate, maxDate, helperText, placeholder, error, label }) { - return ( - <> - - - { - const date = new Date(value); - const formattedDate = moment(date).locale("en").format("YYYY-MM-DD"); - setFieldValue(name, formattedDate); - }} - minDate={minDate ? new Date(minDate) : null} - maxDate={maxDate ? new Date(maxDate) : null} - slotProps={{ - textField: { - error: error, - size: "small", - placeholder: placeholder, - InputLabelProps: { - shrink: true, - }, - InputProps: { - endAdornment: ( - - { - event.stopPropagation(); - setFieldValue(name, ""); - }} - sx={{ - color: "#bfbfbf", - "&:hover": { - backgroundColor: "rgba(189, 189, 189, 0.1)", - color: "#363434", - }, - }} - > - - - - ), - }, - }, - }} - /> - - - {helperText && ( - - {helperText} - - )} - - ); -} - -export default MuiDatePicker; +import React from "react"; +import { LocalizationProvider, MobileDatePicker } from "@mui/x-date-pickers"; +import { AdapterDateFnsJalali } from "@mui/x-date-pickers/AdapterDateFnsJalali"; +import { faIR } from "@mui/x-date-pickers/locales"; +import { Box, FormHelperText, IconButton, InputAdornment } from "@mui/material"; +import ClearIcon from "@mui/icons-material/Clear"; +import moment from "jalali-moment"; + +function MuiDatePicker({ value, setFieldValue, name, minDate, maxDate, helperText, placeholder, error, label }) { + return ( + <> + + + { + const date = new Date(value); + const formattedDate = moment(date).locale("en").format("YYYY-MM-DD"); + setFieldValue(name, formattedDate); + }} + minDate={minDate ? new Date(minDate) : null} + maxDate={maxDate ? new Date(maxDate) : null} + slotProps={{ + textField: { + error: error, + size: "small", + placeholder: placeholder, + InputLabelProps: { + shrink: true, + }, + InputProps: { + endAdornment: ( + + { + event.stopPropagation(); + setFieldValue(name, ""); + }} + sx={{ + color: "#bfbfbf", + "&:hover": { + backgroundColor: "rgba(189, 189, 189, 0.1)", + color: "#363434", + }, + }} + > + + + + ), + }, + }, + }} + /> + + + {helperText && ( + + {helperText} + + )} + + ); +} + +export default MuiDatePicker; diff --git a/src/core/components/MuiTimePicker.jsx b/src/core/components/MuiTimePicker.jsx index a8fc46c..53b8f02 100644 --- a/src/core/components/MuiTimePicker.jsx +++ b/src/core/components/MuiTimePicker.jsx @@ -1,81 +1,84 @@ -import React from "react"; -import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider"; -import { MobileTimePicker } from "@mui/x-date-pickers/MobileTimePicker"; -import { AdapterDateFnsJalali } from "@mui/x-date-pickers/AdapterDateFnsJalali"; -import { faIR } from "@mui/x-date-pickers/locales"; -import { Box, FormHelperText, IconButton, InputAdornment } from "@mui/material"; -import ClearIcon from "@mui/icons-material/Clear"; - -function MuiTimePicker({ value, setFieldValue, name, minTime, maxTime, helperText, placeholder, error, label }) { - // Ensure value, minTime, maxTime are Date objects - const parsedValue = value || null; - const parsedMinTime = minTime || null; - const parsedMaxTime = maxTime || null; - - return ( - <> - - - { - setFieldValue(name, newValue); - }} - minTime={parsedMinTime} - maxTime={parsedMaxTime} - slotProps={{ - textField: { - placeholder: placeholder, - size: "small", - error: error, - InputLabelProps: { - shrink: true, - }, - InputProps: { - endAdornment: ( - - { - event.stopPropagation(); - setFieldValue(name, ""); - }} - sx={{ - color: "#bfbfbf", - "&:hover": { - backgroundColor: "rgba(189, 189, 189, 0.1)", - color: "#363434", - }, - }} - > - - - - ), - }, - }, - }} - /> - - - {helperText && ( - - {helperText} - - )} - - ); -} - -export default MuiTimePicker; +import ClearIcon from "@mui/icons-material/Clear"; +import { Box, FormHelperText, IconButton, InputAdornment } from "@mui/material"; +import { AdapterDateFnsJalali } from "@mui/x-date-pickers/AdapterDateFnsJalali"; +import { faIR } from "@mui/x-date-pickers/locales"; +import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider"; +import { MobileTimePicker } from "@mui/x-date-pickers/MobileTimePicker"; +import { parseISO } from "date-fns"; + +const parseIfString = (val) => + val instanceof Date ? val : typeof val === "string" && val !== "" ? parseISO(val) : null; + +function MuiTimePicker({ value, setFieldValue, name, minTime, maxTime, helperText, placeholder, error, label }) { + // Ensure value, minTime, maxTime are Date objects + const parsedValue = parseIfString(value); + const parsedMinTime = parseIfString(minTime); + const parsedMaxTime = parseIfString(maxTime); + + return ( + <> + + + { + setFieldValue(name, newValue); + }} + minTime={parsedMinTime} + maxTime={parsedMaxTime} + slotProps={{ + textField: { + placeholder: placeholder, + size: "small", + error: error, + InputLabelProps: { + shrink: true, + }, + InputProps: { + endAdornment: ( + + { + event.stopPropagation(); + setFieldValue(name, ""); + }} + sx={{ + color: "#bfbfbf", + "&:hover": { + backgroundColor: "rgba(189, 189, 189, 0.1)", + color: "#363434", + }, + }} + > + + + + ), + }, + }, + }} + /> + + + {helperText && ( + + {helperText} + + )} + + ); +} + +export default MuiTimePicker; diff --git a/src/core/components/NotificationDesign/AskForKeepData.jsx b/src/core/components/NotificationDesign/AskForKeepData.jsx index 9e1cbd9..118ccc2 100644 --- a/src/core/components/NotificationDesign/AskForKeepData.jsx +++ b/src/core/components/NotificationDesign/AskForKeepData.jsx @@ -1,65 +1,65 @@ -"use client"; - -import SaveIcon from "@mui/icons-material/Save"; -import { Box, Button, Typography } from "@mui/material"; -import DownloadIcon from "@mui/icons-material/Download"; -import { toast } from "react-toastify"; -import useTableSetting from "@/lib/hooks/useTableSetting"; -import { flattenObjectOfObjects } from "@/core/utils/flattenObjectOfObjects"; - -function AskForKeepData({ filterData, sortData, hideData, user_id, page_name, table_name, columns }) { - const { filterAction, sortAction, hideAction } = useTableSetting(); - - const filteredHideData = Object.fromEntries(Object.entries(hideData).filter(([key, value]) => value === false)); - - const flattenHideData = flattenObjectOfObjects(filteredHideData); - - const onSaveFilter = () => { - const filteredItems = Object.keys(filterData) - .map((key) => { - const value = filterData[key].value; - if ( - value !== "" && - !( - Array.isArray(value) && - (value.length === 0 || (value.length === 2 && value[0] === "" && value[1] === "")) - ) - ) { - return filterData[key]; - } - }) - .filter(Boolean); - filterAction(user_id, page_name, table_name, filteredItems, columns); - sortAction(user_id, page_name, table_name, sortData, columns); - hideAction(user_id, page_name, table_name, flattenHideData, columns); - toast.dismiss({ containerId: "datatable" }); - }; - - const handleDismiss = () => { - toast.dismiss({ containerId: "datatable" }); - }; - - return ( - - - - ذخیره سازی تغییرات - - - - - آیا مایل به ذخیره تغییر های اعمال شده برای دفعات بعد هستید؟ - - - - - - - ); -} - -export default AskForKeepData; +"use client"; + +import SaveIcon from "@mui/icons-material/Save"; +import { Box, Button, Typography } from "@mui/material"; +import DownloadIcon from "@mui/icons-material/Download"; +import { toast } from "react-toastify"; +import useTableSetting from "@/lib/hooks/useTableSetting"; +import { flattenObjectOfObjects } from "@/core/utils/flattenObjectOfObjects"; + +function AskForKeepData({ filterData, sortData, hideData, user_id, page_name, table_name, columns }) { + const { filterAction, sortAction, hideAction } = useTableSetting(); + + const filteredHideData = Object.fromEntries(Object.entries(hideData).filter(([key, value]) => value === false)); + + const flattenHideData = flattenObjectOfObjects(filteredHideData); + + const onSaveFilter = () => { + const filteredItems = Object.keys(filterData) + .map((key) => { + const value = filterData[key].value; + if ( + value !== "" && + !( + Array.isArray(value) && + (value.length === 0 || (value.length === 2 && value[0] === "" && value[1] === "")) + ) + ) { + return filterData[key]; + } + }) + .filter(Boolean); + filterAction(user_id, page_name, table_name, filteredItems, columns); + sortAction(user_id, page_name, table_name, sortData, columns); + hideAction(user_id, page_name, table_name, flattenHideData, columns); + toast.dismiss({ containerId: "datatable" }); + }; + + const handleDismiss = () => { + toast.dismiss({ containerId: "datatable" }); + }; + + return ( + + + + ذخیره سازی تغییرات + + + + + آیا مایل به ذخیره تغییر های اعمال شده برای دفعات بعد هستید؟ + + + + + + + ); +} + +export default AskForKeepData; diff --git a/src/core/components/NumberField.jsx b/src/core/components/NumberField.jsx index 80a48f2..093fcd0 100644 --- a/src/core/components/NumberField.jsx +++ b/src/core/components/NumberField.jsx @@ -1,29 +1,29 @@ -import React from "react"; -import { Stack, Typography } from "@mui/material"; -import LtrTextField from "@/core/components/LtrTextField"; -import InputAdornment from "@mui/material/InputAdornment"; - -const NumberField = React.forwardRef((props, ref) => { - return ( - - - - {(props.value / 1).toLocaleString()} - - - {props.unit} - - - - ), - }} - /> - ); -}); -NumberField.displayName = "NumberField"; -export default NumberField; +import React from "react"; +import { Stack, Typography } from "@mui/material"; +import LtrTextField from "@/core/components/LtrTextField"; +import InputAdornment from "@mui/material/InputAdornment"; + +const NumberField = React.forwardRef((props, ref) => { + return ( + + + + {(props.value / 1).toLocaleString()} + + + {props.unit} + + + + ), + }} + /> + ); +}); +NumberField.displayName = "NumberField"; +export default NumberField; diff --git a/src/core/components/PageLoading.jsx b/src/core/components/PageLoading.jsx index c5b2159..9d3a5ce 100644 --- a/src/core/components/PageLoading.jsx +++ b/src/core/components/PageLoading.jsx @@ -1,12 +1,12 @@ -"use client"; -import { Paper } from "@mui/material"; -import LoadingHardPage from "./LoadingHardPage"; - -const PageLoading = () => { - return ( - - - - ); -}; -export default PageLoading; +"use client"; +import { Paper } from "@mui/material"; +import LoadingHardPage from "./LoadingHardPage"; + +const PageLoading = () => { + return ( + + + + ); +}; +export default PageLoading; diff --git a/src/core/components/PageTitle.jsx b/src/core/components/PageTitle.jsx index 4c93098..b5f9dd0 100644 --- a/src/core/components/PageTitle.jsx +++ b/src/core/components/PageTitle.jsx @@ -1,18 +1,18 @@ -"use client"; - -import { Chip, Divider, Typography } from "@mui/material"; - -const PageTitle = ({ title }) => { - return ( - - - {title} - - } - /> - - ); -}; -export default PageTitle; +"use client"; + +import { Chip, Divider, Typography } from "@mui/material"; + +const PageTitle = ({ title }) => { + return ( + + + {title} + + } + /> + + ); +}; +export default PageTitle; diff --git a/src/core/components/PersianTextField.jsx b/src/core/components/PersianTextField.jsx index 1b2b490..6d01894 100644 --- a/src/core/components/PersianTextField.jsx +++ b/src/core/components/PersianTextField.jsx @@ -1,18 +1,18 @@ -import usePersianInput from "@/lib/hooks/usePersianInput"; -import { TextField } from "@mui/material"; -import { useRef } from "react"; - -const PersianTextField = (props) => { - const { onChange, ...rest } = props; - const inputRef = useRef(null); - - const handleChange = (value) => { - onChange(value); - }; - - usePersianInput(inputRef, handleChange); - - return ; -}; - -export default PersianTextField; +import usePersianInput from "@/lib/hooks/usePersianInput"; +import { TextField } from "@mui/material"; +import { useRef } from "react"; + +const PersianTextField = (props) => { + const { onChange, ...rest } = props; + const inputRef = useRef(null); + + const handleChange = (value) => { + onChange(value); + }; + + usePersianInput(inputRef, handleChange); + + return ; +}; + +export default PersianTextField; diff --git a/src/core/components/PlateNumber.jsx b/src/core/components/PlateNumber.jsx index 7b396d5..25e1e51 100644 --- a/src/core/components/PlateNumber.jsx +++ b/src/core/components/PlateNumber.jsx @@ -1,197 +1,197 @@ -import { Box, Button, Drawer, FormHelperText, Stack, TextField } from "@mui/material"; -import AccessibleIcon from "@mui/icons-material/Accessible"; -import { Controller, useFormState, useWatch } from "react-hook-form"; -import { useEffect, useState } from "react"; - -const plate_words = [ - { id: 1, value: "الف", name: "الف" }, - { id: 2, value: "ب", name: "ب" }, - { id: 3, value: "پ", name: "پ" }, - { id: 4, value: "ت", name: "ت" }, - { id: 5, value: "ث", name: "ث" }, - { id: 6, value: "ج", name: "ج" }, - { id: 7, value: "د", name: "د" }, - { id: 8, value: "ز", name: "ز" }, - { id: 9, value: "س", name: "س" }, - { id: 10, value: "ش", name: "ش" }, - { id: 11, value: "ص", name: "ص" }, - { id: 12, value: "ط", name: "ط" }, - { id: 13, value: "ع", name: "ع" }, - { id: 14, value: "ف", name: "ف" }, - { id: 15, value: "ق", name: "ق" }, - { id: 16, value: "ک", name: "گ" }, - { id: 17, value: "ل", name: "ل" }, - { id: 18, value: "م", name: "م" }, - { id: 19, value: "ن", name: "ن" }, - { id: 20, value: "و", name: "و" }, - { id: 21, value: "ه", name: "ه" }, - { id: 22, value: "ی", name: "ی" }, - { id: 23, value: "*", name: }, -]; - -const PlateNumber = ({ control }) => { - const platePart2 = useWatch({ control, name: "plate_part2" }); - const [plateDrawer, setPlateDrawer] = useState(false); - const { errors } = useFormState({ control }); - const plateErrors = ["plate_part1", "plate_part2", "plate_part3", "plate_part4"].some((part) => errors[part]); - - return ( - <> - - ( - { - const inputValue = event.target.value; - if (isNaN(Number(inputValue))) { - return; - } - inputValue.length <= 2 ? field.onChange(inputValue) : null; - }} - size="small" - placeholder="xx" - sx={{ flexGrow: 2, "& fieldset": { border: "none" } }} - /> - )} - /> - ( - { - const inputValue = event.target.value; - if (isNaN(Number(inputValue))) { - return; - } - inputValue.length <= 3 ? field.onChange(inputValue) : null; - }} - size="small" - placeholder="xxx" - sx={{ - flexGrow: 3, - borderLeft: 1, - borderRadius: 0, - borderColor: "divider", - "& fieldset": { border: "none" }, - }} - /> - )} - /> - - - - setPlateDrawer(false)} - > - - {plate_words.map((item) => ( - ( - - )} - /> - ))} - - - ( - { - const inputValue = event.target.value; - if (isNaN(Number(inputValue))) { - return; - } - inputValue.length <= 2 ? field.onChange(inputValue) : null; - }} - /> - )} - /> - - - - - - - {plateErrors && ( - - پلاک نامعتبر است!!! - - )} - - ); -}; -export default PlateNumber; +import { Box, Button, Drawer, FormHelperText, Stack, TextField } from "@mui/material"; +import AccessibleIcon from "@mui/icons-material/Accessible"; +import { Controller, useFormState, useWatch } from "react-hook-form"; +import { useEffect, useState } from "react"; + +const plate_words = [ + { id: 1, value: "الف", name: "الف" }, + { id: 2, value: "ب", name: "ب" }, + { id: 3, value: "پ", name: "پ" }, + { id: 4, value: "ت", name: "ت" }, + { id: 5, value: "ث", name: "ث" }, + { id: 6, value: "ج", name: "ج" }, + { id: 7, value: "د", name: "د" }, + { id: 8, value: "ز", name: "ز" }, + { id: 9, value: "س", name: "س" }, + { id: 10, value: "ش", name: "ش" }, + { id: 11, value: "ص", name: "ص" }, + { id: 12, value: "ط", name: "ط" }, + { id: 13, value: "ع", name: "ع" }, + { id: 14, value: "ف", name: "ف" }, + { id: 15, value: "ق", name: "ق" }, + { id: 16, value: "ک", name: "گ" }, + { id: 17, value: "ل", name: "ل" }, + { id: 18, value: "م", name: "م" }, + { id: 19, value: "ن", name: "ن" }, + { id: 20, value: "و", name: "و" }, + { id: 21, value: "ه", name: "ه" }, + { id: 22, value: "ی", name: "ی" }, + { id: 23, value: "*", name: }, +]; + +const PlateNumber = ({ control }) => { + const platePart2 = useWatch({ control, name: "plate_part2" }); + const [plateDrawer, setPlateDrawer] = useState(false); + const { errors } = useFormState({ control }); + const plateErrors = ["plate_part1", "plate_part2", "plate_part3", "plate_part4"].some((part) => errors[part]); + + return ( + <> + + ( + { + const inputValue = event.target.value; + if (isNaN(Number(inputValue))) { + return; + } + inputValue.length <= 2 ? field.onChange(inputValue) : null; + }} + size="small" + placeholder="xx" + sx={{ flexGrow: 2, "& fieldset": { border: "none" } }} + /> + )} + /> + ( + { + const inputValue = event.target.value; + if (isNaN(Number(inputValue))) { + return; + } + inputValue.length <= 3 ? field.onChange(inputValue) : null; + }} + size="small" + placeholder="xxx" + sx={{ + flexGrow: 3, + borderLeft: 1, + borderRadius: 0, + borderColor: "divider", + "& fieldset": { border: "none" }, + }} + /> + )} + /> + + + + setPlateDrawer(false)} + > + + {plate_words.map((item) => ( + ( + + )} + /> + ))} + + + ( + { + const inputValue = event.target.value; + if (isNaN(Number(inputValue))) { + return; + } + inputValue.length <= 2 ? field.onChange(inputValue) : null; + }} + /> + )} + /> + + + + + + + {plateErrors && ( + + پلاک نامعتبر است!!! + + )} + + ); +}; +export default PlateNumber; diff --git a/src/core/components/Profile/ChangePass/Form.jsx b/src/core/components/Profile/ChangePass/Form.jsx index 80d1890..7a67951 100644 --- a/src/core/components/Profile/ChangePass/Form.jsx +++ b/src/core/components/Profile/ChangePass/Form.jsx @@ -1,152 +1,152 @@ -"use client"; - -import { - Chip, - Divider, - FormControl, - FormHelperText, - Grid, - IconButton, - InputAdornment, - InputLabel, - OutlinedInput, -} from "@mui/material"; -import StyledForm from "@/core/components/StyledForm"; -import { useForm } from "react-hook-form"; -import useRequest from "@/lib/hooks/useRequest"; -import { CHANGE_USER_PASSWORD } from "@/core/utils/routes"; -import { object, string } from "yup"; -import { yupResolver } from "@hookform/resolvers/yup"; -import { useEffect, useState } from "react"; -import Visibility from "@mui/icons-material/Visibility"; -import VisibilityOff from "@mui/icons-material/VisibilityOff"; - -const validationSchema = object({ - current_password: string().required("اجباری"), - new_password: string().required("اجباری"), - repeat_new_password: string() - .required("اجباری") - .test("password-match", "رمز عبور جدید و تکرار آن باید یکسان باشند", function (value) { - return this.parent.new_password === value; - }), -}); - -const Form = ({ handleCloseForm, setLoading }) => { - const request = useRequest(); - const [showNewPassword, setShowNewPassword] = useState(); - const [showRepeatNewPassword, setShowRepeatNewPassword] = useState(); - - const defaultValues = { - current_password: "", - new_password: "", - repeat_new_password: "", - }; - - const { - register, - handleSubmit, - formState: { isSubmitting, errors }, - } = useForm({ defaultValues, resolver: yupResolver(validationSchema) }); - - useEffect(() => { - setLoading(isSubmitting); - }, [isSubmitting]); - - const onSubmit = async (data) => { - const formData = new FormData(); - formData.append("current_password", data.current_password); - formData.append("new_password", data.new_password); - try { - await request(CHANGE_USER_PASSWORD, "post", { data: formData, signal: controller.signal }); - handleCloseForm(); - } catch (error) {} - }; - - return ( - <> - - - - - - - - رمز عبور فعلی - - - {errors.current_password ? errors.current_password.message : null} - - - - - - رمز عبور جدید - - setShowNewPassword(!showNewPassword)} - onMouseDown={(event) => event.preventDefault()} - edge="end" - > - {showNewPassword ? : } - - - } - /> - - {errors.new_password ? errors.new_password.message : null} - - - - - - تکرار رمز عبور جدید - - setShowRepeatNewPassword(!showRepeatNewPassword)} - onMouseDown={(event) => event.preventDefault()} - edge="end" - > - {showRepeatNewPassword ? : } - - - } - /> - - {errors.repeat_new_password ? errors.repeat_new_password.message : null} - - - - - - - ); -}; -export default Form; +"use client"; + +import { + Chip, + Divider, + FormControl, + FormHelperText, + Grid, + IconButton, + InputAdornment, + InputLabel, + OutlinedInput, +} from "@mui/material"; +import StyledForm from "@/core/components/StyledForm"; +import { useForm } from "react-hook-form"; +import useRequest from "@/lib/hooks/useRequest"; +import { CHANGE_USER_PASSWORD } from "@/core/utils/routes"; +import { object, string } from "yup"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { useEffect, useState } from "react"; +import Visibility from "@mui/icons-material/Visibility"; +import VisibilityOff from "@mui/icons-material/VisibilityOff"; + +const validationSchema = object({ + current_password: string().required("اجباری"), + new_password: string().required("اجباری"), + repeat_new_password: string() + .required("اجباری") + .test("password-match", "رمز عبور جدید و تکرار آن باید یکسان باشند", function (value) { + return this.parent.new_password === value; + }), +}); + +const Form = ({ handleCloseForm, setLoading }) => { + const request = useRequest(); + const [showNewPassword, setShowNewPassword] = useState(); + const [showRepeatNewPassword, setShowRepeatNewPassword] = useState(); + + const defaultValues = { + current_password: "", + new_password: "", + repeat_new_password: "", + }; + + const { + register, + handleSubmit, + formState: { isSubmitting, errors }, + } = useForm({ defaultValues, resolver: yupResolver(validationSchema) }); + + useEffect(() => { + setLoading(isSubmitting); + }, [isSubmitting]); + + const onSubmit = async (data) => { + const formData = new FormData(); + formData.append("current_password", data.current_password); + formData.append("new_password", data.new_password); + try { + await request(CHANGE_USER_PASSWORD, "post", { data: formData, signal: controller.signal }); + handleCloseForm(); + } catch (error) {} + }; + + return ( + <> + + + + + + + + رمز عبور فعلی + + + {errors.current_password ? errors.current_password.message : null} + + + + + + رمز عبور جدید + + setShowNewPassword(!showNewPassword)} + onMouseDown={(event) => event.preventDefault()} + edge="end" + > + {showNewPassword ? : } + + + } + /> + + {errors.new_password ? errors.new_password.message : null} + + + + + + تکرار رمز عبور جدید + + setShowRepeatNewPassword(!showRepeatNewPassword)} + onMouseDown={(event) => event.preventDefault()} + edge="end" + > + {showRepeatNewPassword ? : } + + + } + /> + + {errors.repeat_new_password ? errors.repeat_new_password.message : null} + + + + + + + ); +}; +export default Form; diff --git a/src/core/components/Profile/ChangePass/index.jsx b/src/core/components/Profile/ChangePass/index.jsx index 0a507db..de9f5cf 100644 --- a/src/core/components/Profile/ChangePass/index.jsx +++ b/src/core/components/Profile/ChangePass/index.jsx @@ -1,47 +1,47 @@ -"use client"; - -import { Dialog, DialogActions, DialogContent } from "@mui/material"; -import Form from "./Form"; -import SaveIcon from "@mui/icons-material/Save"; -import { LoadingButton } from "@mui/lab"; -import { useState } from "react"; - -const ChangePass = ({ open, setOpen }) => { - const [loading, setLoading] = useState(false); - - const handleCloseForm = () => { - setOpen(false); - }; - - return ( - - -
    - - - - بستن - - } - > - تغییر - - -
    - ); -}; -export default ChangePass; +"use client"; + +import { Dialog, DialogActions, DialogContent } from "@mui/material"; +import Form from "./Form"; +import SaveIcon from "@mui/icons-material/Save"; +import { LoadingButton } from "@mui/lab"; +import { useState } from "react"; + +const ChangePass = ({ open, setOpen }) => { + const [loading, setLoading] = useState(false); + + const handleCloseForm = () => { + setOpen(false); + }; + + return ( + + + + + + + بستن + + } + > + تغییر + + + + ); +}; +export default ChangePass; diff --git a/src/core/components/Profile/ProfileActions.jsx b/src/core/components/Profile/ProfileActions.jsx index 063dc5f..7f1cf7c 100644 --- a/src/core/components/Profile/ProfileActions.jsx +++ b/src/core/components/Profile/ProfileActions.jsx @@ -1,61 +1,61 @@ -"use client"; -import { Box, Divider, IconButton, Tooltip } from "@mui/material"; -import PowerSettingsNewIcon from "@mui/icons-material/PowerSettingsNew"; -import ModeEditIcon from "@mui/icons-material/ModeEdit"; -import VpnKeyIcon from "@mui/icons-material/VpnKey"; -import { useState } from "react"; -import Update from "@/core/components/Profile/Update"; -import ChangePass from "@/core/components/Profile/ChangePass"; -import { useAuth } from "@/lib/contexts/auth"; -import useRequest from "@/lib/hooks/useRequest"; -import { LOGOUT_USER_ROUTE } from "@/core/utils/routes"; - -const ProfileActions = () => { - const { getUser, logout } = useAuth(); - const requestServer = useRequest(); - const [openUpdate, setOpenUpdate] = useState(false); - const [openChangePass, setOpenChangePass] = useState(false); - - const openUpdateProfile = () => { - getUser(); - setOpenUpdate(true); - }; - const handleLogout = () => { - requestServer(LOGOUT_USER_ROUTE, "post").then(() => { - logout(); - }); - }; - - return ( - <> - - - - - - - - - - - - - - - { - setOpenChangePass(true); - }} - > - - - - - - - - ); -}; -export default ProfileActions; +"use client"; +import { Box, Divider, IconButton, Tooltip } from "@mui/material"; +import PowerSettingsNewIcon from "@mui/icons-material/PowerSettingsNew"; +import ModeEditIcon from "@mui/icons-material/ModeEdit"; +import VpnKeyIcon from "@mui/icons-material/VpnKey"; +import { useState } from "react"; +import Update from "@/core/components/Profile/Update"; +import ChangePass from "@/core/components/Profile/ChangePass"; +import { useAuth } from "@/lib/contexts/auth"; +import useRequest from "@/lib/hooks/useRequest"; +import { LOGOUT_USER_ROUTE } from "@/core/utils/routes"; + +const ProfileActions = () => { + const { getUser, logout } = useAuth(); + const requestServer = useRequest(); + const [openUpdate, setOpenUpdate] = useState(false); + const [openChangePass, setOpenChangePass] = useState(false); + + const openUpdateProfile = () => { + getUser(); + setOpenUpdate(true); + }; + const handleLogout = () => { + requestServer(LOGOUT_USER_ROUTE, "post").then(() => { + logout(); + }); + }; + + return ( + <> + + + + + + + + + + + + + + + { + setOpenChangePass(true); + }} + > + + + + + + + + ); +}; +export default ProfileActions; diff --git a/src/core/components/Profile/ProfileInfo.jsx b/src/core/components/Profile/ProfileInfo.jsx index 6af5082..53c4881 100644 --- a/src/core/components/Profile/ProfileInfo.jsx +++ b/src/core/components/Profile/ProfileInfo.jsx @@ -1,38 +1,38 @@ -"use client"; - -import { useAuth } from "@/lib/contexts/auth"; -import { Avatar, Box, Chip, Divider, Stack, Typography } from "@mui/material"; -import moment from "jalali-moment"; - -const ProfileInfo = () => { - const { user } = useAuth(); - - return ( - <> - - - - - {`${user.first_name} ${user.last_name}`} - - .: {user.name} :. - - - - - آخرین ورود - - - - {moment(user.last_login).locale("fa").fromNow()} - - - - - - - - - ); -}; -export default ProfileInfo; +"use client"; + +import { useAuth } from "@/lib/contexts/auth"; +import { Avatar, Box, Chip, Divider, Stack, Typography } from "@mui/material"; +import moment from "jalali-moment"; + +const ProfileInfo = () => { + const { user } = useAuth(); + + return ( + <> + + + + + {`${user.first_name} ${user.last_name}`} + + .: {user.name} :. + + + + + آخرین ورود + + + + {moment(user.last_login).locale("fa").fromNow()} + + + + + + + + + ); +}; +export default ProfileInfo; diff --git a/src/core/components/Profile/Update/Form.jsx b/src/core/components/Profile/Update/Form.jsx index c34561d..255b840 100644 --- a/src/core/components/Profile/Update/Form.jsx +++ b/src/core/components/Profile/Update/Form.jsx @@ -1,257 +1,257 @@ -"use client"; - -import { - Autocomplete, - Avatar, - Backdrop, - Box, - Button, - Chip, - Divider, - FormControl, - FormHelperText, - Grid, - InputLabel, - OutlinedInput, - TextField, -} from "@mui/material"; -import StyledForm from "@/core/components/StyledForm"; -import useRequest from "@/lib/hooks/useRequest"; -import { Controller, useForm } from "react-hook-form"; -import { useAuth } from "@/lib/contexts/auth"; -import CloudUploadIcon from "@mui/icons-material/CloudUpload"; -import { styled } from "@mui/material/styles"; -import { useEffect, useState } from "react"; -import { yupResolver } from "@hookform/resolvers/yup"; -import { object, string } from "yup"; -import { UPDATE_USER_ROUTE } from "@/core/utils/routes"; - -const degreeItems = ["دیپلم", "کارشناسی", "کارشناسی ارشد", "دکترا"]; - -const VisuallyHiddenInput = styled("input")({ - clip: "rect(0 0 0 0)", - clipPath: "inset(50%)", - height: 1, - overflow: "hidden", - position: "absolute", - bottom: 0, - left: 0, - whiteSpace: "nowrap", - width: 1, -}); - -const validationSchema = object({ - first_name: string().required("اجباری"), - last_name: string().required("اجباری"), - degree: string().required("اجباری"), - major: string().required("اجباری"), - mobile: string().required("اجباری"), -}); - -const Form = ({ handleCloseForm, setLoading }) => { - const request = useRequest(); - const { user, getUser } = useAuth(); - const [uploadBackDrop, setUploadBackDrop] = useState(false); - const [avatarUrl, setAvatarUrl] = useState(user?.avatar || ""); - const defaultValues = { - first_name: user.first_name, - last_name: user.last_name, - major: user.major, - degree: user.degree, - mobile: user.mobile, - avatar: null, - }; - - const { - control, - watch, - register, - setValue, - handleSubmit, - formState: { isSubmitting, errors }, - } = useForm({ defaultValues, resolver: yupResolver(validationSchema) }); - - const handleFileChange = (event) => { - const file = event.target.files[0]; - if (file) { - const objectUrl = URL.createObjectURL(file); - setAvatarUrl(objectUrl); - setValue("avatar", file); - } - }; - - useEffect(() => { - setLoading(isSubmitting); - }, [isSubmitting]); - - const onSubmit = async (data) => { - const formData = new FormData(); - formData.append("first_name", data.first_name); - formData.append("last_name", data.last_name); - formData.append("major", data.major); - formData.append("degree", data.degree); - formData.append("mobile", data.mobile); - if (data.avatar) { - formData.append("avatar", data.avatar); - } - - try { - await request(UPDATE_USER_ROUTE, "post", { data: formData }); - getUser(); - handleCloseForm(); - } catch (error) {} - }; - - return ( - <> - - - - - - - - - - - نام - - - {errors.first_name ? errors.first_name.message : null} - - - - - - نام خانوادگی - - - {errors.last_name ? errors.last_name.message : null} - - - - - - رشته تحصیلی - - {errors.major ? errors.major.message : null} - - - - ( - - { - onChange(newValue); - }} - options={degreeItems} - renderInput={(params) => ( - - )} - /> - {error ? error.message : null} - - )} - /> - - - - موبایل - - {errors.mobile ? errors.mobile.message : null} - - - - - - ); -}; -export default Form; +"use client"; + +import { + Autocomplete, + Avatar, + Backdrop, + Box, + Button, + Chip, + Divider, + FormControl, + FormHelperText, + Grid, + InputLabel, + OutlinedInput, + TextField, +} from "@mui/material"; +import StyledForm from "@/core/components/StyledForm"; +import useRequest from "@/lib/hooks/useRequest"; +import { Controller, useForm } from "react-hook-form"; +import { useAuth } from "@/lib/contexts/auth"; +import CloudUploadIcon from "@mui/icons-material/CloudUpload"; +import { styled } from "@mui/material/styles"; +import { useEffect, useState } from "react"; +import { yupResolver } from "@hookform/resolvers/yup"; +import { object, string } from "yup"; +import { UPDATE_USER_ROUTE } from "@/core/utils/routes"; + +const degreeItems = ["دیپلم", "کارشناسی", "کارشناسی ارشد", "دکترا"]; + +const VisuallyHiddenInput = styled("input")({ + clip: "rect(0 0 0 0)", + clipPath: "inset(50%)", + height: 1, + overflow: "hidden", + position: "absolute", + bottom: 0, + left: 0, + whiteSpace: "nowrap", + width: 1, +}); + +const validationSchema = object({ + first_name: string().required("اجباری"), + last_name: string().required("اجباری"), + degree: string().required("اجباری"), + major: string().required("اجباری"), + mobile: string().required("اجباری"), +}); + +const Form = ({ handleCloseForm, setLoading }) => { + const request = useRequest(); + const { user, getUser } = useAuth(); + const [uploadBackDrop, setUploadBackDrop] = useState(false); + const [avatarUrl, setAvatarUrl] = useState(user?.avatar || ""); + const defaultValues = { + first_name: user.first_name, + last_name: user.last_name, + major: user.major, + degree: user.degree, + mobile: user.mobile, + avatar: null, + }; + + const { + control, + watch, + register, + setValue, + handleSubmit, + formState: { isSubmitting, errors }, + } = useForm({ defaultValues, resolver: yupResolver(validationSchema) }); + + const handleFileChange = (event) => { + const file = event.target.files[0]; + if (file) { + const objectUrl = URL.createObjectURL(file); + setAvatarUrl(objectUrl); + setValue("avatar", file); + } + }; + + useEffect(() => { + setLoading(isSubmitting); + }, [isSubmitting]); + + const onSubmit = async (data) => { + const formData = new FormData(); + formData.append("first_name", data.first_name); + formData.append("last_name", data.last_name); + formData.append("major", data.major); + formData.append("degree", data.degree); + formData.append("mobile", data.mobile); + if (data.avatar) { + formData.append("avatar", data.avatar); + } + + try { + await request(UPDATE_USER_ROUTE, "post", { data: formData }); + getUser(); + handleCloseForm(); + } catch (error) {} + }; + + return ( + <> + + + + + + + + + + + نام + + + {errors.first_name ? errors.first_name.message : null} + + + + + + نام خانوادگی + + + {errors.last_name ? errors.last_name.message : null} + + + + + + رشته تحصیلی + + {errors.major ? errors.major.message : null} + + + + ( + + { + onChange(newValue); + }} + options={degreeItems} + renderInput={(params) => ( + + )} + /> + {error ? error.message : null} + + )} + /> + + + + موبایل + + {errors.mobile ? errors.mobile.message : null} + + + + + + ); +}; +export default Form; diff --git a/src/core/components/Profile/Update/index.jsx b/src/core/components/Profile/Update/index.jsx index 4cec971..e99babd 100644 --- a/src/core/components/Profile/Update/index.jsx +++ b/src/core/components/Profile/Update/index.jsx @@ -1,44 +1,44 @@ -"use client"; - -import { Button, Dialog, DialogActions, DialogContent, useMediaQuery } from "@mui/material"; -import { useTheme } from "@mui/material/styles"; -import Form from "./Form"; -import SaveIcon from "@mui/icons-material/Save"; -import { LoadingButton } from "@mui/lab"; -import { useState } from "react"; - -const Update = ({ open, setOpen }) => { - const theme = useTheme(); - const fullScreen = useMediaQuery(theme.breakpoints.down("sm")); - const [loading, setLoading] = useState(false); - - const handleCloseForm = () => { - setOpen(false); - }; - - return ( - - - - - - - } - > - ویرایش - - - - ); -}; -export default Update; +"use client"; + +import { Button, Dialog, DialogActions, DialogContent, useMediaQuery } from "@mui/material"; +import { useTheme } from "@mui/material/styles"; +import Form from "./Form"; +import SaveIcon from "@mui/icons-material/Save"; +import { LoadingButton } from "@mui/lab"; +import { useState } from "react"; + +const Update = ({ open, setOpen }) => { + const theme = useTheme(); + const fullScreen = useMediaQuery(theme.breakpoints.down("sm")); + const [loading, setLoading] = useState(false); + + const handleCloseForm = () => { + setOpen(false); + }; + + return ( + + + + + + + } + > + ویرایش + + + + ); +}; +export default Update; diff --git a/src/core/components/Profile/index.jsx b/src/core/components/Profile/index.jsx index fd5cbf4..0cb8f87 100644 --- a/src/core/components/Profile/index.jsx +++ b/src/core/components/Profile/index.jsx @@ -1,22 +1,22 @@ -"use client"; - -import { Stack } from "@mui/material"; -import ProfileInfo from "./ProfileInfo"; -import ProfileActions from "./ProfileActions"; - -const Profile = () => { - return ( - - - - - ); -}; -export default Profile; +"use client"; + +import { Stack } from "@mui/material"; +import ProfileInfo from "./ProfileInfo"; +import ProfileActions from "./ProfileActions"; + +const Profile = () => { + return ( + + + + + ); +}; +export default Profile; diff --git a/src/core/components/RahdarCode.jsx b/src/core/components/RahdarCode.jsx index 7ebf1d2..0e77855 100644 --- a/src/core/components/RahdarCode.jsx +++ b/src/core/components/RahdarCode.jsx @@ -1,97 +1,97 @@ -"use client"; -import { Autocomplete, CircularProgress, TextField } from "@mui/material"; -import { useEffect, useState } from "react"; -import useRequest from "@/lib/hooks/useRequest"; -import { debounce } from "@mui/material/utils"; -import { GET_RAHDARANS_LIST_SEARCH } from "@/core/utils/routes"; - -const RahdarCode = ({ rahdarsCode, setRahdarsCode, error, multiple = true }) => { - const [inputValue, setInputValue] = useState(""); // مدیریت مقدار تایپ‌شده - const [options, setOptions] = useState([]); - const [loading, setLoading] = useState(false); - const requestServer = useRequest(); - - useEffect(() => { - const fetchRahdarCodes = (inputValue, controller) => { - const debouncer = debounce((query) => { - if ((query || "").length < 3) { - setOptions([]); - return; - } - setLoading(true); - requestServer(`${GET_RAHDARANS_LIST_SEARCH}?code=${query}`, "get", { - requestOptions: { signal: controller.signal }, - }) - .then((response) => { - const combinedArray = rahdarsCode - ? [...rahdarsCode, ...response.data.data] - : [...response.data.data]; - const uniqueArray = Array.from(new Map(combinedArray.map((item) => [item.id, item])).values()); - setOptions(uniqueArray || []); - }) - .catch(() => { - setOptions([]); - }) - .finally(() => { - setLoading(false); - }); - }, 500); - debouncer(inputValue); - }; - - const controller = new AbortController(); - fetchRahdarCodes(inputValue, controller); - return () => controller.abort(); - }, [inputValue]); - - return ( - { - setRahdarsCode(multiple ? newValue || [] : newValue || null); // مدیریت حالت چندگانه و تک‌گانه - }} - inputValue={inputValue} // مقدار تایپ‌شده - onInputChange={(event, newInputValue) => { - setInputValue(newInputValue || ""); // به‌روزرسانی مقدار تایپ‌شده - }} - options={options} // گزینه‌های موجود - getOptionLabel={(option) => (typeof option === "string" ? option : `${option.code} - ${option.name}`)} - isOptionEqualToValue={(option, value) => { - if (!value) return false; - if (value === "") return option.code === ""; - return option.code === (value?.code || value); - }} - loading={loading} - loadingText="درحال جستجوی کد راهدار" - noOptionsText={ - (inputValue || "").length < 3 ? "حداقل سه رقم از کد راهدار را وارد کنید" : "کد راهداری یافت نشد" - } - fullWidth - renderInput={(params) => ( - - {loading ? : null} - {params.InputProps.endAdornment} - - ), - }} - /> - )} - /> - ); -}; -export default RahdarCode; +"use client"; +import { Autocomplete, CircularProgress, TextField } from "@mui/material"; +import { useEffect, useState } from "react"; +import useRequest from "@/lib/hooks/useRequest"; +import { debounce } from "@mui/material/utils"; +import { GET_RAHDARANS_LIST_SEARCH } from "@/core/utils/routes"; + +const RahdarCode = ({ rahdarsCode, setRahdarsCode, error, multiple = true }) => { + const [inputValue, setInputValue] = useState(""); // مدیریت مقدار تایپ‌شده + const [options, setOptions] = useState([]); + const [loading, setLoading] = useState(false); + const requestServer = useRequest(); + + useEffect(() => { + const fetchRahdarCodes = (inputValue, controller) => { + const debouncer = debounce((query) => { + if ((query || "").length < 3) { + setOptions([]); + return; + } + setLoading(true); + requestServer(`${GET_RAHDARANS_LIST_SEARCH}?code=${query}`, "get", { + requestOptions: { signal: controller.signal }, + }) + .then((response) => { + const combinedArray = rahdarsCode + ? [...rahdarsCode, ...response.data.data] + : [...response.data.data]; + const uniqueArray = Array.from(new Map(combinedArray.map((item) => [item.id, item])).values()); + setOptions(uniqueArray || []); + }) + .catch(() => { + setOptions([]); + }) + .finally(() => { + setLoading(false); + }); + }, 500); + debouncer(inputValue); + }; + + const controller = new AbortController(); + fetchRahdarCodes(inputValue, controller); + return () => controller.abort(); + }, [inputValue]); + + return ( + { + setRahdarsCode(multiple ? newValue || [] : newValue || null); // مدیریت حالت چندگانه و تک‌گانه + }} + inputValue={inputValue} // مقدار تایپ‌شده + onInputChange={(event, newInputValue) => { + setInputValue(newInputValue || ""); // به‌روزرسانی مقدار تایپ‌شده + }} + options={options} // گزینه‌های موجود + getOptionLabel={(option) => (typeof option === "string" ? option : `${option.code} - ${option.name}`)} + isOptionEqualToValue={(option, value) => { + if (!value) return false; + if (value === "") return option.code === ""; + return option.code === (value?.code || value); + }} + loading={loading} + loadingText="درحال جستجوی کد راهدار" + noOptionsText={ + (inputValue || "").length < 3 ? "حداقل سه رقم از کد راهدار را وارد کنید" : "کد راهداری یافت نشد" + } + fullWidth + renderInput={(params) => ( + + {loading ? : null} + {params.InputProps.endAdornment} + + ), + }} + /> + )} + /> + ); +}; +export default RahdarCode; diff --git a/src/core/components/ScrollBox.jsx b/src/core/components/ScrollBox.jsx index 11f8404..23f940e 100644 --- a/src/core/components/ScrollBox.jsx +++ b/src/core/components/ScrollBox.jsx @@ -1,19 +1,19 @@ -import { Box, styled } from "@mui/material"; - -const ScrollBox = styled(Box)({ - flexGrow: 1, - overflowY: "auto", - maxWidth: "450px", - "::-webkit-scrollbar": { - width: "5px", - }, - "::-webkit-scrollbar-track": { - boxShadow: "inset 0 0 5px #fff", - borderRadius: "5px", - }, - "::-webkit-scrollbar-thumb": { - background: "#155175", - borderRadius: "0px", - }, -}); -export default ScrollBox; +import { Box, styled } from "@mui/material"; + +const ScrollBox = styled(Box)({ + flexGrow: 1, + overflowY: "auto", + maxWidth: "450px", + "::-webkit-scrollbar": { + width: "5px", + }, + "::-webkit-scrollbar-track": { + boxShadow: "inset 0 0 5px #fff", + borderRadius: "5px", + }, + "::-webkit-scrollbar-thumb": { + background: "#155175", + borderRadius: "0px", + }, +}); +export default ScrollBox; diff --git a/src/core/components/SelectBox.jsx b/src/core/components/SelectBox.jsx index 765acaa..80e47ec 100644 --- a/src/core/components/SelectBox.jsx +++ b/src/core/components/SelectBox.jsx @@ -1,59 +1,59 @@ -import { FormControl, FormHelperText, InputLabel, MenuItem, Select } from "@mui/material"; - -function SelectBox({ - name, - value, - onChange, - isDependency = false, - dependencyLabel = "", - onBlur, - selectors, - label, - error, - schema, - disabled, - helperText, - isLoading, - errorEcured, - variant = "outlined", -}) { - return ( - - {label} - - {helperText || error?.message} - - ); -} -export default SelectBox; +import { FormControl, FormHelperText, InputLabel, MenuItem, Select } from "@mui/material"; + +function SelectBox({ + name, + value, + onChange, + isDependency = false, + dependencyLabel = "", + onBlur, + selectors, + label, + error, + schema, + disabled, + helperText, + isLoading, + errorEcured, + variant = "outlined", +}) { + return ( + + {label} + + {helperText || error?.message} + + ); +} +export default SelectBox; diff --git a/src/core/components/ShowLocationMarker.jsx b/src/core/components/ShowLocationMarker.jsx index e30a4e4..634580d 100644 --- a/src/core/components/ShowLocationMarker.jsx +++ b/src/core/components/ShowLocationMarker.jsx @@ -1,181 +1,181 @@ -"use client"; - -import { Marker, useMap } from "react-leaflet"; -import { useEffect } from "react"; -import L from "leaflet"; -import AzmayeshActiveIcon from "@/assets/images/examine_marker_active.png"; -import { Box, FormControl, InputAdornment, InputLabel, OutlinedInput, Stack, useMediaQuery } from "@mui/material"; -import VerifiedIcon from "@mui/icons-material/Verified"; -import { useTheme } from "@emotion/react"; - -const ShowLocationMarker = ({ start_lat, start_lng, end_lat, end_lng }) => { - const map = useMap(); - const theme = useTheme(); - const isMobile = useMediaQuery(theme.breakpoints.down("sm")); - - const defaultIconSize = [35, 35]; - - const createCustomIcon = (size, iconUrl) => { - return L.icon({ - iconUrl: iconUrl, - iconSize: size, - iconAnchor: [size[0] / 2, size[1]], - popupAnchor: [0, -size[1]], - }); - }; - - useEffect(() => { - if (start_lat && end_lng) { - map.fitBounds( - [ - { lat: start_lat, lng: start_lng }, - { lat: end_lat, lng: end_lng }, - ], - { paddingTopLeft: [16, 16], paddingBottomRight: [16, 130] } - ); - } else if (start_lat) { - map.setView({ lat: start_lat, lng: start_lng }, 15); - } - }, [start_lat, start_lng, map, end_lng, end_lat]); - - return ( - <> - {start_lat && start_lng && ( - - )} - {end_lat && end_lng && ( - - )} - - - {start_lat && start_lng && ( - - - - {end_lat && end_lng ? "طول جغرافیایی شروع" : "طول جغرافیایی"} - - - - - } - label={end_lat && end_lng ? "طول جغرافیایی شروع" : "طول جغرافیایی"} - /> - - - - {end_lat && end_lng ? "عرض جغرافیایی شروع" : "عرض جغرافیایی"} - - - - - } - label={end_lat && end_lng ? "عرض جغرافیایی شروع" : "عرض جغرافیایی"} - /> - - - )} - {end_lat && end_lng && ( - - - - طول جغرافیایی پایان - - - - - } - label="طول جغرافیایی پایان" - /> - - - - عرض جغرافیایی پایان - - - - - } - label="عرض جغرافیایی پایان" - /> - - - )} - - - - ); -}; - -export default ShowLocationMarker; +"use client"; + +import { Marker, useMap } from "react-leaflet"; +import { useEffect } from "react"; +import L from "leaflet"; +import AzmayeshActiveIcon from "@/assets/images/examine_marker_active.png"; +import { Box, FormControl, InputAdornment, InputLabel, OutlinedInput, Stack, useMediaQuery } from "@mui/material"; +import VerifiedIcon from "@mui/icons-material/Verified"; +import { useTheme } from "@emotion/react"; + +const ShowLocationMarker = ({ start_lat, start_lng, end_lat, end_lng }) => { + const map = useMap(); + const theme = useTheme(); + const isMobile = useMediaQuery(theme.breakpoints.down("sm")); + + const defaultIconSize = [35, 35]; + + const createCustomIcon = (size, iconUrl) => { + return L.icon({ + iconUrl: iconUrl, + iconSize: size, + iconAnchor: [size[0] / 2, size[1]], + popupAnchor: [0, -size[1]], + }); + }; + + useEffect(() => { + if (start_lat && end_lng) { + map.fitBounds( + [ + { lat: start_lat, lng: start_lng }, + { lat: end_lat, lng: end_lng }, + ], + { paddingTopLeft: [16, 16], paddingBottomRight: [16, 130] } + ); + } else if (start_lat) { + map.setView({ lat: start_lat, lng: start_lng }, 15); + } + }, [start_lat, start_lng, map, end_lng, end_lat]); + + return ( + <> + {start_lat && start_lng && ( + + )} + {end_lat && end_lng && ( + + )} + + + {start_lat && start_lng && ( + + + + {end_lat && end_lng ? "طول جغرافیایی شروع" : "طول جغرافیایی"} + + + + + } + label={end_lat && end_lng ? "طول جغرافیایی شروع" : "طول جغرافیایی"} + /> + + + + {end_lat && end_lng ? "عرض جغرافیایی شروع" : "عرض جغرافیایی"} + + + + + } + label={end_lat && end_lng ? "عرض جغرافیایی شروع" : "عرض جغرافیایی"} + /> + + + )} + {end_lat && end_lng && ( + + + + طول جغرافیایی پایان + + + + + } + label="طول جغرافیایی پایان" + /> + + + + عرض جغرافیایی پایان + + + + + } + label="عرض جغرافیایی پایان" + /> + + + )} + + + + ); +}; + +export default ShowLocationMarker; diff --git a/src/core/components/ShowPlak.jsx b/src/core/components/ShowPlak.jsx index 6e02934..77f89d1 100644 --- a/src/core/components/ShowPlak.jsx +++ b/src/core/components/ShowPlak.jsx @@ -1,62 +1,62 @@ -import { Stack } from "@mui/material"; - -const ShowPlak = ({ plak_number }) => { - const processPlak = (plak_number) => { - const parts = plak_number.match(/^([\u0600-\u06FF]+)(\d+)-(\d+)([^\d]*)(\d+)$/); - if (!parts) return {}; - - return { - region: parts[1], // "ايران" - mainNumber: parts[2], // "13" - serial: parts[3], // "189" - letter: parts[4], // "الف" - number: parts[5], // "15" - }; - }; - const plakParts = processPlak(plak_number); - return ( - - - {plakParts.region} {plakParts.mainNumber} - - - - {plakParts.serial} - - - {plakParts.letter} - - - {plakParts.number} - - - - ); -}; -export default ShowPlak; +import { Stack } from "@mui/material"; + +const ShowPlak = ({ plak_number }) => { + const processPlak = (plak_number) => { + const parts = plak_number.match(/^([\u0600-\u06FF]+)(\d+)-(\d+)([^\d]*)(\d+)$/); + if (!parts) return {}; + + return { + region: parts[1], // "ايران" + mainNumber: parts[2], // "13" + serial: parts[3], // "189" + letter: parts[4], // "الف" + number: parts[5], // "15" + }; + }; + const plakParts = processPlak(plak_number); + return ( + + + {plakParts.region} {plakParts.mainNumber} + + + + {plakParts.serial} + + + {plakParts.letter} + + + {plakParts.number} + + + + ); +}; +export default ShowPlak; diff --git a/src/core/components/StyledForm.jsx b/src/core/components/StyledForm.jsx index accf0ab..4630191 100644 --- a/src/core/components/StyledForm.jsx +++ b/src/core/components/StyledForm.jsx @@ -1,5 +1,5 @@ -import { styled } from "@mui/material"; - -const StyledForm = styled("form")``; - -export default StyledForm; +import { styled } from "@mui/material"; + +const StyledForm = styled("form")``; + +export default StyledForm; diff --git a/src/core/components/Toasts/error.jsx b/src/core/components/Toasts/error.jsx index dbc25e8..47882fb 100644 --- a/src/core/components/Toasts/error.jsx +++ b/src/core/components/Toasts/error.jsx @@ -1,216 +1,216 @@ -import { toast } from "react-toastify"; -import { Box, Typography } from "@mui/material"; -import { Dangerous } from "@mui/icons-material"; - -export const errorServerToast = (toastContainer) => - toast.error( - () => ( - - - - - {"The request failed due to an internal error."} - - - - ), - { - icon: false, - containerId: toastContainer, - autoClose: 5000, - hideProgressBar: true, - pauseOnHover: true, - closeOnClick: false, - draggable: true, - } - ); - -export const errorUnauthorizedToast = (toastContainer) => - toast.error( - () => ( - - - - - {"The user is not authorized to make the request."} - - - - ), - { - icon: false, - containerId: toastContainer, - autoClose: 3000, - hideProgressBar: true, - pauseOnHover: true, - closeOnClick: false, - draggable: true, - } - ); -export const errorAccessDeniedToast = (message, toastContainer) => - toast.error( - () => ( - - - - - {message || "Access Denied"} - - - - ), - { - icon: false, - containerId: toastContainer, - autoClose: 3000, - hideProgressBar: true, - pauseOnHover: true, - closeOnClick: false, - draggable: true, - } - ); - -export const errorLogicToast = (message, toastContainer) => - toast.error( - () => ( - - - - - - {message || - "The request was well-formed but was unable to be followed due to semantic errors."} - - - - - ), - { - icon: false, - containerId: toastContainer, - autoClose: false, - closeOnClick: false, - draggable: false, - } - ); - -export const errorValidationToast = (message, toastContainer) => - toast.error( - () => ( - - - - - - {message || - "The request was well-formed but was unable to be followed due to semantic errors."} - - - - - ), - { - icon: false, - containerId: toastContainer, - autoClose: false, - closeOnClick: false, - draggable: false, - } - ); - -export const errorTooManyToast = (toastContainer) => - toast.error( - () => ( - - - - - - {"Too many requests have been sent within a given time span."} - - - - - ), - { - icon: false, - containerId: toastContainer, - autoClose: false, - closeOnClick: false, - draggable: false, - } - ); - -export const errorClientToast = (toastContainer) => - toast.error( - () => ( - - - - - - { - "The API request is invalid or improperly formed. Consequently, the API server could not understand the request." - } - - - - - ), - { - icon: false, - containerId: toastContainer, - autoClose: false, - closeOnClick: false, - draggable: false, - } - ); +import { toast } from "react-toastify"; +import { Box, Typography } from "@mui/material"; +import { Dangerous } from "@mui/icons-material"; + +export const errorServerToast = (toastContainer) => + toast.error( + () => ( + + + + + {"The request failed due to an internal error."} + + + + ), + { + icon: false, + containerId: toastContainer, + autoClose: 5000, + hideProgressBar: true, + pauseOnHover: true, + closeOnClick: false, + draggable: true, + } + ); + +export const errorUnauthorizedToast = (toastContainer) => + toast.error( + () => ( + + + + + {"The user is not authorized to make the request."} + + + + ), + { + icon: false, + containerId: toastContainer, + autoClose: 3000, + hideProgressBar: true, + pauseOnHover: true, + closeOnClick: false, + draggable: true, + } + ); +export const errorAccessDeniedToast = (message, toastContainer) => + toast.error( + () => ( + + + + + {message || "Access Denied"} + + + + ), + { + icon: false, + containerId: toastContainer, + autoClose: 3000, + hideProgressBar: true, + pauseOnHover: true, + closeOnClick: false, + draggable: true, + } + ); + +export const errorLogicToast = (message, toastContainer) => + toast.error( + () => ( + + + + + + {message || + "The request was well-formed but was unable to be followed due to semantic errors."} + + + + + ), + { + icon: false, + containerId: toastContainer, + autoClose: false, + closeOnClick: false, + draggable: false, + } + ); + +export const errorValidationToast = (message, toastContainer) => + toast.error( + () => ( + + + + + + {message || + "The request was well-formed but was unable to be followed due to semantic errors."} + + + + + ), + { + icon: false, + containerId: toastContainer, + autoClose: false, + closeOnClick: false, + draggable: false, + } + ); + +export const errorTooManyToast = (toastContainer) => + toast.error( + () => ( + + + + + + {"Too many requests have been sent within a given time span."} + + + + + ), + { + icon: false, + containerId: toastContainer, + autoClose: false, + closeOnClick: false, + draggable: false, + } + ); + +export const errorClientToast = (toastContainer) => + toast.error( + () => ( + + + + + + { + "The API request is invalid or improperly formed. Consequently, the API server could not understand the request." + } + + + + + ), + { + icon: false, + containerId: toastContainer, + autoClose: false, + closeOnClick: false, + draggable: false, + } + ); diff --git a/src/core/components/Toasts/success.jsx b/src/core/components/Toasts/success.jsx index fc11759..5df4084 100644 --- a/src/core/components/Toasts/success.jsx +++ b/src/core/components/Toasts/success.jsx @@ -1,33 +1,33 @@ -import { toast } from "react-toastify"; -import { Box, Typography } from "@mui/material"; -import { Beenhere } from "@mui/icons-material"; - -export const successToast = (toastContainer) => - toast.success( - () => ( - - - - - {"عملیات با موفقیت انجام شد"} - - - - ), - { - icon: false, - containerId: toastContainer, - autoClose: 3000, - hideProgressBar: true, - pauseOnHover: true, - closeOnClick: false, - draggable: true, - } - ); +import { toast } from "react-toastify"; +import { Box, Typography } from "@mui/material"; +import { Beenhere } from "@mui/icons-material"; + +export const successToast = (toastContainer) => + toast.success( + () => ( + + + + + {"عملیات با موفقیت انجام شد"} + + + + ), + { + icon: false, + containerId: toastContainer, + autoClose: 3000, + hideProgressBar: true, + pauseOnHover: true, + closeOnClick: false, + draggable: true, + } + ); diff --git a/src/core/components/UploadSystem.jsx b/src/core/components/UploadSystem.jsx index 43167ad..654beab 100644 --- a/src/core/components/UploadSystem.jsx +++ b/src/core/components/UploadSystem.jsx @@ -1,95 +1,95 @@ -import { Box, Button, Paper, Typography } from "@mui/material"; -import AddIcon from "@mui/icons-material/Add"; -import DeleteForeverIcon from "@mui/icons-material/DeleteForever"; -import { useRef } from "react"; - -const UploadSystem = ({ selectedImage, handleUploadChange, imageSize, fileType, showAddIcon }) => { - const fileInputRef = useRef(null); - - const handleClick = () => { - fileInputRef.current.click(); - }; - - return ( - - {showAddIcon ? ( - - - - فرمت قابل قبول : png, jpg -
    - حداکثر 3Mb -
    -
    - ) : ( - <> - {fileType && fileType.startsWith("image/") && ( - - - - )} - - )} - -
    - ); -}; -export default UploadSystem; +import { Box, Button, Paper, Typography } from "@mui/material"; +import AddIcon from "@mui/icons-material/Add"; +import DeleteForeverIcon from "@mui/icons-material/DeleteForever"; +import { useRef } from "react"; + +const UploadSystem = ({ selectedImage, handleUploadChange, imageSize, fileType, showAddIcon }) => { + const fileInputRef = useRef(null); + + const handleClick = () => { + fileInputRef.current.click(); + }; + + return ( + + {showAddIcon ? ( + + + + فرمت قابل قبول : png, jpg +
    + حداکثر 3Mb +
    +
    + ) : ( + <> + {fileType && fileType.startsWith("image/") && ( + + + + )} + + )} + +
    + ); +}; +export default UploadSystem; diff --git a/src/core/components/svgs/SvgError.jsx b/src/core/components/svgs/SvgError.jsx index 3c41d22..beae3eb 100644 --- a/src/core/components/svgs/SvgError.jsx +++ b/src/core/components/svgs/SvgError.jsx @@ -1,94 +1,94 @@ -import { useTheme } from "@mui/material"; - -const SvgError = ({ width, height, color = null }) => { - const theme = useTheme(); - const fillColor = color || theme.palette.primary.main; - - return ( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ); -}; - -export default SvgError; +import { useTheme } from "@mui/material"; + +const SvgError = ({ width, height, color = null }) => { + const theme = useTheme(); + const fillColor = color || theme.palette.primary.main; + + return ( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ); +}; + +export default SvgError; diff --git a/src/core/components/svgs/SvgLoading.jsx b/src/core/components/svgs/SvgLoading.jsx index ced3cd1..12340be 100644 --- a/src/core/components/svgs/SvgLoading.jsx +++ b/src/core/components/svgs/SvgLoading.jsx @@ -1,292 +1,292 @@ -import { useTheme } from "@mui/material"; - -const SvgLoading = ({ width, height, color = null }) => { - const theme = useTheme(); - const fillColor = color || theme.palette.primary.main; - - return ( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ); -}; - -export default SvgLoading; +import { useTheme } from "@mui/material"; + +const SvgLoading = ({ width, height, color = null }) => { + const theme = useTheme(); + const fillColor = color || theme.palette.primary.main; + + return ( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ); +}; + +export default SvgLoading; diff --git a/src/core/components/svgs/SvgNotFound.jsx b/src/core/components/svgs/SvgNotFound.jsx index 5d16909..4beab9a 100644 --- a/src/core/components/svgs/SvgNotFound.jsx +++ b/src/core/components/svgs/SvgNotFound.jsx @@ -1,162 +1,162 @@ -import { useTheme } from "@mui/material"; - -const SvgNotFound = ({ width, height, color = null }) => { - const theme = useTheme(); - const fillColor = color || theme.palette.primary.main; - - return ( - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ); -}; -export default SvgNotFound; +import { useTheme } from "@mui/material"; + +const SvgNotFound = ({ width, height, color = null }) => { + const theme = useTheme(); + const fillColor = color || theme.palette.primary.main; + + return ( + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ); +}; +export default SvgNotFound; diff --git a/src/core/middlewares/withAuth.js b/src/core/middlewares/withAuth.js index 216b55b..df10a34 100644 --- a/src/core/middlewares/withAuth.js +++ b/src/core/middlewares/withAuth.js @@ -1,22 +1,22 @@ -"use client"; -import { useAuth } from "@/lib/contexts/auth"; -import { usePathname, useRouter } from "next/navigation"; -import { useEffect } from "react"; - -function WithAuthMiddleware({ children }) { - const router = useRouter(); - const pathName = usePathname(); - const { isAuth, initAuthState } = useAuth(); - - useEffect(() => { - if (!initAuthState) return; - if (!isAuth) { - router.replace(`${process.env.NEXT_PUBLIC_API_URL}/login?_back=${encodeURIComponent(pathName)}`); - } - }, [isAuth, initAuthState]); - - if (!initAuthState || !isAuth) return null; - return <>{children}; -} - -export default WithAuthMiddleware; +"use client"; +import { useAuth } from "@/lib/contexts/auth"; +import { usePathname, useRouter } from "next/navigation"; +import { useEffect } from "react"; + +function WithAuthMiddleware({ children }) { + const router = useRouter(); + const pathName = usePathname(); + const { isAuth, initAuthState } = useAuth(); + + useEffect(() => { + if (!initAuthState) return; + if (!isAuth) { + router.replace(`${process.env.NEXT_PUBLIC_API_URL}/login?_back=${encodeURIComponent(pathName)}`); + } + }, [isAuth, initAuthState]); + + if (!initAuthState || !isAuth) return null; + return <>{children}; +} + +export default WithAuthMiddleware; diff --git a/src/core/middlewares/withPermission.js b/src/core/middlewares/withPermission.js index 9a7d3a6..2a5a776 100644 --- a/src/core/middlewares/withPermission.js +++ b/src/core/middlewares/withPermission.js @@ -1,37 +1,37 @@ -"use client"; - -import { Box, Typography } from "@mui/material"; -import { usePermissions } from "@/lib/hooks/usePermissions"; -import { useEffect, useState } from "react"; - -function WithPermission({ children, permission_name }) { - const { data, error, isLoading } = usePermissions(); - const [cachedData, setCachedData] = useState(null); - - useEffect(() => { - if (data) { - setCachedData(data); - } - }, [data]); - - if (isLoading || !cachedData || !permission_name) { - return null; - } - - const hasPermission = - permission_name.includes("all") || permission_name.some((permission) => cachedData.includes(permission)); - - if (!hasPermission) { - return ( - - - شما دسترسی لازم به این صفحه را ندارید - - - ); - } - - return <>{children}; -} - -export default WithPermission; +"use client"; + +import { Box, Typography } from "@mui/material"; +import { usePermissions } from "@/lib/hooks/usePermissions"; +import { useEffect, useState } from "react"; + +function WithPermission({ children, permission_name }) { + const { data, error, isLoading } = usePermissions(); + const [cachedData, setCachedData] = useState(null); + + useEffect(() => { + if (data) { + setCachedData(data); + } + }, [data]); + + if (isLoading || !cachedData || !permission_name) { + return null; + } + + const hasPermission = + permission_name.includes("all") || permission_name.some((permission) => cachedData.includes(permission)); + + if (!hasPermission) { + return ( + + + شما دسترسی لازم به این صفحه را ندارید + + + ); + } + + return <>{children}; +} + +export default WithPermission; diff --git a/src/core/utils/DataTableFilterDataStructure.js b/src/core/utils/DataTableFilterDataStructure.js index 43f1144..bb71446 100644 --- a/src/core/utils/DataTableFilterDataStructure.js +++ b/src/core/utils/DataTableFilterDataStructure.js @@ -1,10 +1,10 @@ -export default function DataTableFilterDataStructure(filterData, isValueEmpty) { - return Object.values(filterData) - .filter((filter) => !isValueEmpty(filter.value)) - .map(({ filterMode, id, datatype, value }) => ({ - id: id.replace(/__/g, "."), - fn: filterMode, - datatype, - value, - })); -} +export default function DataTableFilterDataStructure(filterData, isValueEmpty) { + return Object.values(filterData) + .filter((filter) => !isValueEmpty(filter.value)) + .map(({ filterMode, id, datatype, value }) => ({ + id: id.replace(/__/g, "."), + fn: filterMode, + datatype, + value, + })); +} diff --git a/src/core/utils/cacheRtl.js b/src/core/utils/cacheRtl.js index a646aa5..1730fec 100644 --- a/src/core/utils/cacheRtl.js +++ b/src/core/utils/cacheRtl.js @@ -1,28 +1,28 @@ -"use client"; -import createCache from "@emotion/cache"; -import { prefixer } from "stylis"; -import stylisRTLPlugin from "stylis-plugin-rtl"; -import { CacheProvider } from "@emotion/react"; - -const isBrowser = typeof document !== "undefined"; - -const createEmotionCache = () => { - let insertionPoint; - - if (isBrowser) { - const emotionInsertionPoint = document.querySelector('meta[name="emotion-insertion-point"]'); - insertionPoint = emotionInsertionPoint ?? undefined; - } - - return createCache({ - insertionPoint, - key: "mui-rtl", - stylisPlugins: [prefixer, stylisRTLPlugin], - }); -}; - -const cacheProviderRtl = (props) => { - return {props.children}; -}; - -export default cacheProviderRtl; +"use client"; +import createCache from "@emotion/cache"; +import { prefixer } from "stylis"; +import stylisRTLPlugin from "stylis-plugin-rtl"; +import { CacheProvider } from "@emotion/react"; + +const isBrowser = typeof document !== "undefined"; + +const createEmotionCache = () => { + let insertionPoint; + + if (isBrowser) { + const emotionInsertionPoint = document.querySelector('meta[name="emotion-insertion-point"]'); + insertionPoint = emotionInsertionPoint ?? undefined; + } + + return createCache({ + insertionPoint, + key: "mui-rtl", + stylisPlugins: [prefixer, stylisRTLPlugin], + }); +}; + +const cacheProviderRtl = (props) => { + return {props.children}; +}; + +export default cacheProviderRtl; diff --git a/src/core/utils/errorResponse.js b/src/core/utils/errorResponse.js index 2a147ed..160ac57 100644 --- a/src/core/utils/errorResponse.js +++ b/src/core/utils/errorResponse.js @@ -1,65 +1,65 @@ -"use client"; -import { toast } from "react-toastify"; -import { - errorAccessDeniedToast, - errorClientToast, - errorLogicToast, - errorServerToast, - errorTooManyToast, - errorUnauthorizedToast, - errorValidationToast, -} from "@/core/components/Toasts/error"; - -const isServerError = (status) => status >= 500 && status <= 599; -const isClientError = (status) => status >= 400 && status <= 499; - -const errorServer = (response, notification, toastContainer) => { - if (notification) errorServerToast(toastContainer); -}; - -const errorClient = (response, notification, toastContainer, logout) => { - switch (response.status) { - case 401: - logout(); - if (notification) errorUnauthorizedToast(toastContainer); - break; - case 403: - if (notification) errorAccessDeniedToast(response.data.message, toastContainer); - break; - case 422: - if ("type" in response.data) { - if (Array.isArray(response.data.message)) { - response.data.message.map((item) => { - if (notification) errorLogicToast(item, toastContainer); - }); - } else { - if (notification) errorLogicToast(response.data.message, toastContainer); - } - break; - } - if (notification) { - const errorsMap = Object.keys(response.data.errors); - const errorsArray = response.data.errors; - - errorsMap.map((item, index) => { - errorValidationToast(errorsArray[item][0], toastContainer); - }); - } - break; - case 429: - if (notification) errorTooManyToast(toastContainer); - break; - default: - if (notification) errorClientToast(toastContainer); - break; - } -}; - -export const errorResponse = (response, notification, toastContainer, logout) => { - if (notification) toast.dismiss({ containerId: toastContainer }); - if (isServerError(response.status)) { - errorServer(response, notification, toastContainer); - } else if (isClientError(response.status)) { - errorClient(response, notification, toastContainer, logout); - } -}; +"use client"; +import { toast } from "react-toastify"; +import { + errorAccessDeniedToast, + errorClientToast, + errorLogicToast, + errorServerToast, + errorTooManyToast, + errorUnauthorizedToast, + errorValidationToast, +} from "@/core/components/Toasts/error"; + +const isServerError = (status) => status >= 500 && status <= 599; +const isClientError = (status) => status >= 400 && status <= 499; + +const errorServer = (response, notification, toastContainer) => { + if (notification) errorServerToast(toastContainer); +}; + +const errorClient = (response, notification, toastContainer, logout) => { + switch (response.status) { + case 401: + logout(); + if (notification) errorUnauthorizedToast(toastContainer); + break; + case 403: + if (notification) errorAccessDeniedToast(response.data.message, toastContainer); + break; + case 422: + if ("type" in response.data) { + if (Array.isArray(response.data.message)) { + response.data.message.map((item) => { + if (notification) errorLogicToast(item, toastContainer); + }); + } else { + if (notification) errorLogicToast(response.data.message, toastContainer); + } + break; + } + if (notification) { + const errorsMap = Object.keys(response.data.errors); + const errorsArray = response.data.errors; + + errorsMap.map((item, index) => { + errorValidationToast(errorsArray[item][0], toastContainer); + }); + } + break; + case 429: + if (notification) errorTooManyToast(toastContainer); + break; + default: + if (notification) errorClientToast(toastContainer); + break; + } +}; + +export const errorResponse = (response, notification, toastContainer, logout) => { + if (notification) toast.dismiss({ containerId: toastContainer }); + if (isServerError(response.status)) { + errorServer(response, notification, toastContainer); + } else if (isClientError(response.status)) { + errorClient(response, notification, toastContainer, logout); + } +}; diff --git a/src/core/utils/filterMenuItems.js b/src/core/utils/filterMenuItems.js index bd35a95..685eb1e 100644 --- a/src/core/utils/filterMenuItems.js +++ b/src/core/utils/filterMenuItems.js @@ -1,17 +1,17 @@ -export function filterMenuItems(items, _permissions = []) { - return items.reduce((acc, item) => { - if (item.permissions) { - if (item.permissions.some((permission) => _permissions.includes(permission))) { - acc.push(item); - } - } else if (item.hasSubitems) { - const filteredSubItems = filterMenuItems(item.Subitems, _permissions); - if (filteredSubItems.length > 0) { - acc.push({ ...item, Subitems: filteredSubItems }); - } - } else { - acc.push(item); - } - return acc; - }, []); -} +export function filterMenuItems(items, _permissions = []) { + return items.reduce((acc, item) => { + if (item.permissions) { + if (item.permissions.some((permission) => _permissions.includes(permission))) { + acc.push(item); + } + } else if (item.hasSubitems) { + const filteredSubItems = filterMenuItems(item.Subitems, _permissions); + if (filteredSubItems.length > 0) { + acc.push({ ...item, Subitems: filteredSubItems }); + } + } else { + acc.push(item); + } + return acc; + }, []); +} diff --git a/src/core/utils/flattenArrayOfObjects.js b/src/core/utils/flattenArrayOfObjects.js index e4d5051..a059935 100644 --- a/src/core/utils/flattenArrayOfObjects.js +++ b/src/core/utils/flattenArrayOfObjects.js @@ -1,9 +1,9 @@ -export const flattenArrayOfObjects = (array, key) => { - return array.reduce((acc, obj) => { - acc.push(obj); - if (Array.isArray(obj[key])) { - acc.push(...flattenArrayOfObjects(obj[key], key)); - } - return acc; - }, []); -}; +export const flattenArrayOfObjects = (array, key) => { + return array.reduce((acc, obj) => { + acc.push(obj); + if (Array.isArray(obj[key])) { + acc.push(...flattenArrayOfObjects(obj[key], key)); + } + return acc; + }, []); +}; diff --git a/src/core/utils/flattenObjectOfObjects.js b/src/core/utils/flattenObjectOfObjects.js index fb03576..b8c8e3e 100644 --- a/src/core/utils/flattenObjectOfObjects.js +++ b/src/core/utils/flattenObjectOfObjects.js @@ -1,12 +1,12 @@ -export const flattenObjectOfObjects = (obj, res = {}) => { - for (let key in obj) { - if (obj.hasOwnProperty(key)) { - if (typeof obj[key] === "object" && obj[key] !== null) { - flattenObjectOfObjects(obj[key], res); - } else { - res[key] = obj[key]; - } - } - } - return res; -}; +export const flattenObjectOfObjects = (obj, res = {}) => { + for (let key in obj) { + if (obj.hasOwnProperty(key)) { + if (typeof obj[key] === "object" && obj[key] !== null) { + flattenObjectOfObjects(obj[key], res); + } else { + res[key] = obj[key]; + } + } + } + return res; +}; diff --git a/src/core/utils/formatCounter.js b/src/core/utils/formatCounter.js index 7cf9122..ba35251 100644 --- a/src/core/utils/formatCounter.js +++ b/src/core/utils/formatCounter.js @@ -1,7 +1,7 @@ -export const formatCounter = (counter) => { - const minutes = Math.floor(counter / 60) - .toString() - .padStart(2, "0"); - const seconds = (counter % 60).toString().padStart(2, "0"); - return `${minutes}:${seconds}`; -}; +export const formatCounter = (counter) => { + const minutes = Math.floor(counter / 60) + .toString() + .padStart(2, "0"); + const seconds = (counter % 60).toString().padStart(2, "0"); + return `${minutes}:${seconds}`; +}; diff --git a/src/core/utils/formatSecondsToHHMMSS.js b/src/core/utils/formatSecondsToHHMMSS.js index e7f630c..2077b64 100644 --- a/src/core/utils/formatSecondsToHHMMSS.js +++ b/src/core/utils/formatSecondsToHHMMSS.js @@ -1,10 +1,10 @@ -import moment from "jalali-moment"; - -export const formatSecondsToHHMMSS = (seconds) => { - const duration = moment.duration(seconds, "seconds"); - const hours = Math.floor(duration.asHours()); - const minutes = duration.minutes(); - const secs = duration.seconds(); - - return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}:${String(secs).padStart(2, "0")}`; -}; +import moment from "jalali-moment"; + +export const formatSecondsToHHMMSS = (seconds) => { + const duration = moment.duration(seconds, "seconds"); + const hours = Math.floor(duration.asHours()); + const minutes = duration.minutes(); + const secs = duration.seconds(); + + return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}:${String(secs).padStart(2, "0")}`; +}; diff --git a/src/core/utils/getValueByPath.js b/src/core/utils/getValueByPath.js index a31f76f..118931a 100644 --- a/src/core/utils/getValueByPath.js +++ b/src/core/utils/getValueByPath.js @@ -1,14 +1,14 @@ -export const getValueByPath = (obj, path) => { - const keys = path.split("."); - - let value = obj; - - for (const key of keys) { - if (value === undefined) { - return undefined; - } - value = value[key]; - } - - return value; -}; +export const getValueByPath = (obj, path) => { + const keys = path.split("."); + + let value = obj; + + for (const key of keys) { + if (value === undefined) { + return undefined; + } + value = value[key]; + } + + return value; +}; diff --git a/src/core/utils/headerMenu.js b/src/core/utils/headerMenu.js index dc58a18..6faa5fa 100644 --- a/src/core/utils/headerMenu.js +++ b/src/core/utils/headerMenu.js @@ -1,82 +1,82 @@ -const api = process.env.NEXT_PUBLIC_API_URL; - -export const headerMenu = [ - { - title: "تصادفات", - subMenu: [ - [ - { - title: "تصادفات روزانه", - href: api + "/v2/daily_accidents/create", - }, - ], - ], - }, - { - title: "گزارش های جامع", - subMenu: [ - [ - { - title: "گزارش محوری", - href: api + "/v2/axis_reports", - }, - { - title: "هوش تجاری (‌BI)", - href: api + "/v2/axis_reports", - }, - ], - ], - }, - { - title: "زیرساخت و ناوگان", - subMenu: [ - [ - { - title: "پراکندگی بر روی نقشه راهدارخانه ها", - href: api + "/v2/map?type=rahdar", - }, - { - title: "راهدارخانه ها", - href: "/infrastructure/toll-house", - }, - ], - [ - { - title: "ممیزی ماشین آلات راهداری کشور", - href: api + "/cmms-audit", - }, - ], - ], - }, - { - title: "سامانه های راهداری", - subMenu: [ - [ - { - title: "تحقیق و توسعه", - href: api + "/RandD", - }, - { - title: "سامانه مدیریت یکپارچه زیرساخت های راه (PMS,BMS,SMS)", - href: "http://roadams.rmto.ir", - }, - { - title: "سامانه مدیریت ناوگان (FMS)", - href: "http://fms.141.ir", - }, - { - title: "سامانه جامع مدیریت سوانح و حوادث جاده ای", - href: "https://items.rmto.ir", - }, - { - title: "سامانه مدیریت نگهداری ماشین آلات (CMMS)", - href: "https://cmms.rmto.ir/Login.aspx?ReturnUrl=%2f", - }, - { - title: "درگاه کاتالوگ داده", - href: "https://roadams.rmto.ir:8080", - }, - ], - ], - }, -]; +const api = process.env.NEXT_PUBLIC_API_URL; + +export const headerMenu = [ + { + title: "تصادفات", + subMenu: [ + [ + { + title: "تصادفات روزانه", + href: api + "/v2/daily_accidents/create", + }, + ], + ], + }, + { + title: "گزارش های جامع", + subMenu: [ + [ + { + title: "گزارش محوری", + href: api + "/v2/axis_reports", + }, + { + title: "هوش تجاری (‌BI)", + href: api + "/v2/axis_reports", + }, + ], + ], + }, + { + title: "زیرساخت و ناوگان", + subMenu: [ + [ + { + title: "پراکندگی بر روی نقشه راهدارخانه ها", + href: api + "/v2/map?type=rahdar", + }, + { + title: "راهدارخانه ها", + href: "/infrastructure/toll-house", + }, + ], + [ + { + title: "ممیزی ماشین آلات راهداری کشور", + href: api + "/cmms-audit", + }, + ], + ], + }, + { + title: "سامانه های راهداری", + subMenu: [ + [ + { + title: "تحقیق و توسعه", + href: api + "/RandD", + }, + { + title: "سامانه مدیریت یکپارچه زیرساخت های راه (PMS,BMS,SMS)", + href: "http://roadams.rmto.ir", + }, + { + title: "سامانه مدیریت ناوگان (FMS)", + href: "http://fms.141.ir", + }, + { + title: "سامانه جامع مدیریت سوانح و حوادث جاده ای", + href: "https://items.rmto.ir", + }, + { + title: "سامانه مدیریت نگهداری ماشین آلات (CMMS)", + href: "https://cmms.rmto.ir/Login.aspx?ReturnUrl=%2f", + }, + { + title: "درگاه کاتالوگ داده", + href: "https://roadams.rmto.ir:8080", + }, + ], + ], + }, +]; diff --git a/src/core/utils/isArrayEmpty.js b/src/core/utils/isArrayEmpty.js index 81624fb..8036fef 100644 --- a/src/core/utils/isArrayEmpty.js +++ b/src/core/utils/isArrayEmpty.js @@ -1,6 +1,6 @@ -export default function isArrayEmpty(value) { - if (Array.isArray(value)) { - return value.length === 0 || value.every((v) => v === ""); - } - return value === "" || value === null || value === undefined; -} +export default function isArrayEmpty(value) { + if (Array.isArray(value)) { + return value.length === 0 || value.every((v) => v === ""); + } + return value === "" || value === null || value === undefined; +} diff --git a/src/core/utils/machineTypes.js b/src/core/utils/machineTypes.js new file mode 100644 index 0000000..62d3642 --- /dev/null +++ b/src/core/utils/machineTypes.js @@ -0,0 +1,4 @@ +export const machineType = [ + { id: "grader", name_fa: "گریدر" }, + { id: "loder", name_fa: "لودر" }, +]; diff --git a/src/core/utils/nationalCodeValidation.js b/src/core/utils/nationalCodeValidation.js index 747f4cd..d2a6532 100644 --- a/src/core/utils/nationalCodeValidation.js +++ b/src/core/utils/nationalCodeValidation.js @@ -1,30 +1,30 @@ -function validateNationalCode(code) { - const invalidCodes = [ - "1111111111", - "2222222222", - "3333333333", - "4444444444", - "5555555555", - "6666666666", - "7777777777", - "8888888888", - "9999999999", - ]; - if (invalidCodes.includes(code)) return false; - - const L = code.length; - if (L < 8 || parseInt(code, 10) === 0) return false; - - code = code.padStart(10, "0"); - if (parseInt(code.substr(3, 6), 10) === 0) return false; - - const c = parseInt(code.charAt(9), 10); - let s = 0; - for (let i = 0; i < 9; i++) { - s += parseInt(code.charAt(i), 10) * (10 - i); - } - s = s % 11; - return (s < 2 && c === s) || (s >= 2 && c === 11 - s); -} - -export default validateNationalCode; +function validateNationalCode(code) { + const invalidCodes = [ + "1111111111", + "2222222222", + "3333333333", + "4444444444", + "5555555555", + "6666666666", + "7777777777", + "8888888888", + "9999999999", + ]; + if (invalidCodes.includes(code)) return false; + + const L = code.length; + if (L < 8 || parseInt(code, 10) === 0) return false; + + code = code.padStart(10, "0"); + if (parseInt(code.substr(3, 6), 10) === 0) return false; + + const c = parseInt(code.charAt(9), 10); + let s = 0; + for (let i = 0; i < 9; i++) { + s += parseInt(code.charAt(i), 10) * (10 - i); + } + s = s % 11; + return (s < 2 && c === s) || (s >= 2 && c === 11 - s); +} + +export default validateNationalCode; diff --git a/src/core/utils/pageMenu.js b/src/core/utils/pageMenu.js index f4d0aba..a6a6d43 100644 --- a/src/core/utils/pageMenu.js +++ b/src/core/utils/pageMenu.js @@ -1,544 +1,544 @@ -import SpaceDashboardIcon from "@mui/icons-material/SpaceDashboard"; -import GroupsIcon from "@mui/icons-material/Groups"; -import AccountTreeIcon from "@mui/icons-material/AccountTree"; -import FactCheckIcon from "@mui/icons-material/FactCheck"; -import FireTruckIcon from "@mui/icons-material/FireTruck"; -import RouteIcon from "@mui/icons-material/Route"; -import DoorbellIcon from "@mui/icons-material/Doorbell"; -import ElectricBoltIcon from "@mui/icons-material/ElectricBolt"; -import CottageIcon from "@mui/icons-material/Cottage"; -import GppMaybeIcon from "@mui/icons-material/GppMaybe"; -import GavelIcon from "@mui/icons-material/Gavel"; -import BallotIcon from "@mui/icons-material/Ballot"; -import AssistantIcon from "@mui/icons-material/Assistant"; -import AdminPanelSettingsIcon from "@mui/icons-material/AdminPanelSettings"; -import MapIcon from "@mui/icons-material/Map"; -import SpeedIcon from "@mui/icons-material/Speed"; -import EngineeringIcon from "@mui/icons-material/Engineering"; -import ReportIcon from "@mui/icons-material/Report"; -import AssessmentIcon from "@mui/icons-material/Assessment"; -import AssignmentLateIcon from "@mui/icons-material/AssignmentLate"; -import LockPersonIcon from "@mui/icons-material/LockPerson"; -import LineAxisIcon from "@mui/icons-material/LineAxis"; -import ScienceIcon from "@mui/icons-material/Science"; -import DriveEtaIcon from "@mui/icons-material/DriveEta"; -import BiotechIcon from "@mui/icons-material/Biotech"; - -export const pageMenu = [ - { - id: "dashboard", - label: "پیشخوان", - type: "page", - route: "/dashboard", - icon: , - permissions: ["all"], - }, - { - id: "userManagement", - label: "مدیریت کاربران", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/user_management", - icon: , - permissions: ["full-user-management", "limited-user-management"], - }, - { - id: "projectsManagment", - label: "پروژه های راهداری", - type: "menu", - icon: , - hasSubitems: true, - Subitems: [ - { - id: "projectsManagmentFinance", - label: "ثبت قرارداد و پروژه", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/rahdari_projects/finance", - icon: , - permissions: ["show-contract", "show-contract-province"], - }, - { - id: "projectsManagmentList", - label: "لیست پروژه ها", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/rahdari_projects/projects_list", - icon: , - permissions: ["all"], - }, - { - id: "projectsManagmentProposal", - label: "پروژه های پیشنهادی", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/rahdari_projects/proposal", - icon: , - permissions: ["show-proposal", "show-proposal-province"], - }, - { - id: "projectsManagmentLawmaker", - label: "درخواست نمایندگان", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/rahdari_projects/lawmakers", - icon: , - permissions: ["show-lawmaker", "show-lawmaker-province"], - }, - { - id: "projectsManagmentMap", - label: "پراکندگی بر روی نقشه", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=rahdari_projects", - icon: , - permissions: ["all"], - }, - ], - }, - { - id: "roadItemManagment", - label: "فعالیت های روزانه", - type: "menu", - icon: , - hasSubitems: true, - badges: [{ key: "roadItem.total" }], - Subitems: [ - { - id: "roadItemManagmentSupervisor", - label: "ارزیابی", - type: "menu", - icon: , - hasSubitems: true, - badges: [{ key: "roadItem.supervise_cnt" }], - Subitems: [ - { - id: "roadItemManagmentSupervisorCartable", - label: "کارتابل", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_items/supervisor/cartable", - permissions: [ - "show-road-item-supervise-cartable", - "show-road-item-supervise-cartable-province", - ], - }, - ], - }, - { - id: "roadItemManagmentOparation", - label: "عملیات", - type: "menu", - icon: , - hasSubitems: true, - badges: [{ key: "roadItem.operation_cnt" }], - Subitems: [ - { - id: "roadItemManagmentOparationCreate", - label: "ثبت فعالیت", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_items/operator/create", - permissions: ["create-road-item"], - }, - { - id: "roadItemManagmentOparationCartable", - label: "کارتابل", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_items/operator/cartable", - permissions: ["create-road-item"], - }, - ], - }, - { - id: "roadItemManagmentMap", - label: "پراکندگی بر روی نقشه", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=road_items", - icon: , - permissions: [ - "show-road-item-supervise-cartable", - "show-road-item-supervise-cartable-province", - "create-road-item", - ], - }, - { - id: "roadItemManagmentReport", - label: "گزارش ها", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_items/report", - icon: , - permissions: [ - "show-road-item-supervise-cartable", - "show-road-item-supervise-cartable-province", - "create-road-item", - ], - }, - ], - }, - { - id: "roadPatrolManagment", - label: "گشت راهداری و ترابری", - type: "menu", - icon: , - hasSubitems: true, - Subitems: [ - { - id: "roadPatrolManagmentSupervisor", - label: "ارزیابی", - type: "menu", - icon: , - hasSubitems: true, - Subitems: [ - { - id: "roadPatrolManagmentSupervisorCartable", - label: "کارتابل", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_patrols/supervisor/cartable", - permissions: [ - "show-road-patrol-supervise-cartable", - "show-road-patrol-supervise-cartable-province", - ], - }, - ], - }, - { - id: "roadPatrolManagmentOparation", - label: "عملیات", - type: "menu", - icon: , - hasSubitems: true, - Subitems: [ - { - id: "roadPatrolManagmentOparationCreate", - label: "ثبت اقدام", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_patrols/operator/create", - permissions: ["add-road-patrol"], - }, - { - id: "roadPatrolManagmentOparationCartable", - label: "کارتابل", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_patrols/operator/cartable", - permissions: ["add-road-patrol"], - }, - ], - }, - { - id: "roadPatrolManagmentMap", - label: "پراکندگی بر روی نقشه", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=road_patrols", - icon: , - permissions: [ - "add-road-patrol", - "show-road-patrol-supervise-cartable", - "show-road-patrol-supervise-cartable-province", - ], - }, - { - id: "roadPatrolManagmentReport", - label: "گزارش ها", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_patrols/report", - icon: , - permissions: [ - "add-road-patrol", - "show-road-patrol-supervise-cartable", - "show-road-patrol-supervise-cartable-province", - ], - }, - ], - }, - { - id: "inquiryPrivacyManagment", - label: "استعلام حریم راه", - type: "menu", - icon: , - hasSubitems: true, - Subitems: [ - { - id: "cityAdminZaminGov", - label: "استعلام حرائم پنجره واحد", - type: "page", - route: "/dashboard/inquiry-privacy/city-admin/zamin-gov", - permissions: [], - }, - { - id: "provinceAdminZaminGov", - label: "استعلام حرائم پنجره واحد", - type: "page", - route: "/dashboard/inquiry-privacy/province-admin/zamin-gov", - permissions: [], - }, - { - id: "assistantZaminGov", - label: "استعلام حرائم پنجره واحد", - type: "page", - route: "/dashboard/inquiry-privacy/assistant/zamin-gov", - permissions: [], - }, - { - id: "generalManagerZaminGov", - label: "استعلام حرائم پنجره واحد", - type: "page", - route: "/dashboard/inquiry-privacy/general-manager/zamin-gov", - permissions: [], - }, - ], - }, - { - id: "safetyAndPrivacyManagment", - label: "نگهداری حریم راه", - type: "menu", - icon: , - hasSubitems: true, - badges: [ - { key: "safetyAndPrivacy.supervise_cnt" }, - { key: "safetyAndPrivacy.step_one", color: "warning" }, - { key: "safetyAndPrivacy.step_two", color: "error" }, - ], - Subitems: [ - { - id: "safetyAndPrivacyManagmentSupervisor", - label: "ارزیابی", - type: "menu", - icon: , - hasSubitems: true, - badges: [{ key: "safetyAndPrivacy.supervise_cnt" }], - Subitems: [ - { - id: "safetyAndPrivacyManagmentSupervisorCartable", - label: "کارتابل", - type: "page", - route: "/dashboard/road-safety/supervisor", - permissions: [ - "show-safety-and-privacy-operator-cartable", - "show-safety-and-privacy-operator-cartable-province", - ], - }, - ], - }, - { - id: "safetyAndPrivacyManagmentOparation", - label: "عملیات", - type: "menu", - icon: , - hasSubitems: true, - badges: [ - { key: "safetyAndPrivacy.step_one", color: "warning" }, - { key: "safetyAndPrivacy.step_two", color: "error" }, - ], - Subitems: [ - { - id: "safetyAndPrivacyManagmentOparationCartable", - label: "کارتابل", - type: "page", - route: "/dashboard/road-safety/operator", - permissions: ["show-safety-and-privacy-operator-cartable-edarate-shahri"], - }, - ], - }, - { - id: "safetyAndPrivacyManagmentMap", - label: "پراکندگی بر روی نقشه", - type: "page", - route: "/dashboard/road-safety/reports/map", - icon: , - permissions: [ - "show-safety-and-privacy-operator-cartable", - "show-safety-and-privacy-operator-cartable-province", - "show-safety-and-privacy-operator-cartable-edarate-shahri", - ], - }, - { - id: "safetyAndPrivacyManagmentReport", - label: "گزارش ها", - type: "page", - route: "/dashboard/road-safety/reports", - icon: , - permissions: [ - "show-safety-and-privacy-operator-cartable", - "show-safety-and-privacy-operator-cartable-province", - "show-safety-and-privacy-operator-cartable-edarate-shahri", - ], - }, - ], - }, - { - id: "roadObservationsManagment", - label: "واکنش سریع", - type: "menu", - icon: , - hasSubitems: true, - badges: [{ key: "roadObserved.total" }], - Subitems: [ - { - id: "roadObservationsManagmentSupervisor", - label: "ارزیابی", - type: "menu", - icon: , - hasSubitems: true, - badges: [{ key: "roadObserved.supervise_cnt" }, { key: "roadObserved.complaint_cnt", color: "info" }], - Subitems: [ - { - id: "roadObservationsManagmentSupervisorCartable", - label: "کارتابل", - type: "page", - route: "/dashboard/fast-react/supervisor", - permissions: ["show-fast-react", "show-fast-react-province"], - }, - ], - }, - { - id: "roadObservationsManagmentOparation", - label: "عملیات", - type: "menu", - icon: , - hasSubitems: true, - badges: [{ key: "roadObserved.operation_cnt" }, { key: "roadObserved.complaint_cnt", color: "info" }], - Subitems: [ - { - id: "roadObservationsManagmentOparationCartable", - label: "کارتابل", - type: "page", - route: "/dashboard/fast-react/operator", - permissions: ["show-fast-react-edarate-shahri"], - }, - ], - }, - { - id: "roadObservationsManagmentMap", - label: "پراکندگی بر روی نقشه", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=road_observations", - icon: , - permissions: ["all"], - }, - { - id: "roadObservationsManagmentReport", - label: "گزارش ها", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_observations/report/index", - icon: , - permissions: ["all"], - }, - ], - }, - { - id: "winterCampManagment", - label: "قرارگاه زمستانی", - type: "menu", - icon: , - hasSubitems: true, - Subitems: [ - { - id: "winterCampManagmentBlocking", - label: "محور های انسدادی", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/winter_camp", - icon: , - permissions: ["show-camp", "show-camp-province"], - }, - { - id: "winterCampManagmentFirstRing", - label: "محور های حلقه اول", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=camp", - icon: , - permissions: ["show-camp", "show-camp-province"], - }, - { - id: "winterCampManagmentReport", - label: "گزارش ها", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=campNew", - icon: , - permissions: ["show-camp", "show-camp-province"], - }, - ], - }, - { - id: "receiptManagment", - label: "خسارات وارده بر ابنیه فنی و تاسیسات راه", - type: "menu", - icon: , - hasSubitems: true, - Subitems: [ - { - id: "receiptManagmentOparation", - label: "عملیات", - type: "menu", - icon: , - hasSubitems: true, - Subitems: [ - { - id: "receiptManagmentOparationCartable", - label: "کارتابل", - type: "page", - route: "/dashboard/damages/operator", - permissions: ["show-receipt", "show-receipt-province"], - }, - ], - }, - { - id: "damagesManagmentReport", - label: "گزارش ها", - type: "page", - route: "/dashboard/damages/report", - icon: , - permissions: ["show-receipt", "show-receipt-province"], - }, - ], - }, - { - id: "azmayesh", - label: "آزمایشات (OPTS)", - type: "page", - route: "/dashboard/azmayesh", - icon: , - permissions: ["azmayesh-management"], - }, - { - id: "azmayeshType", - label: "نوع آزمایشات", - type: "page", - route: "/dashboard/azmayesh_type", - icon: , - permissions: ["azmayesh-type-management"], - }, - { - id: "adminManagement", - label: "مدیریت سامانه", - type: "menu", - icon: , - hasSubitems: true, - Subitems: [ - { - id: "permissionItem", - label: "سطح دسترسی ها", - type: "page", - route: "/dashboard/permissions", - icon: , - permissions: ["manage-permissions"], - }, - { - id: "userActivities", - label: "انواع فعالیت کاربران", - type: "page", - route: "/dashboard/user-activities", - icon: , - permissions: ["manage-log-list"], - }, - { - id: "damageItems", - label: "آیتم خسارات وارده بر ابنیه فنی", - type: "page", - route: "/dashboard/damage-items", - icon: , - permissions: ["manage-damage"], - }, - { - id: "CarDetails", - label: "اطلاعات خودرو", - type: "page", - route: "/dashboard/car-details", - icon: , - permissions: [""], - }, - ], - }, -]; +import SpaceDashboardIcon from "@mui/icons-material/SpaceDashboard"; +import GroupsIcon from "@mui/icons-material/Groups"; +import AccountTreeIcon from "@mui/icons-material/AccountTree"; +import FactCheckIcon from "@mui/icons-material/FactCheck"; +import FireTruckIcon from "@mui/icons-material/FireTruck"; +import RouteIcon from "@mui/icons-material/Route"; +import DoorbellIcon from "@mui/icons-material/Doorbell"; +import ElectricBoltIcon from "@mui/icons-material/ElectricBolt"; +import CottageIcon from "@mui/icons-material/Cottage"; +import GppMaybeIcon from "@mui/icons-material/GppMaybe"; +import GavelIcon from "@mui/icons-material/Gavel"; +import BallotIcon from "@mui/icons-material/Ballot"; +import AssistantIcon from "@mui/icons-material/Assistant"; +import AdminPanelSettingsIcon from "@mui/icons-material/AdminPanelSettings"; +import MapIcon from "@mui/icons-material/Map"; +import SpeedIcon from "@mui/icons-material/Speed"; +import EngineeringIcon from "@mui/icons-material/Engineering"; +import ReportIcon from "@mui/icons-material/Report"; +import AssessmentIcon from "@mui/icons-material/Assessment"; +import AssignmentLateIcon from "@mui/icons-material/AssignmentLate"; +import LockPersonIcon from "@mui/icons-material/LockPerson"; +import LineAxisIcon from "@mui/icons-material/LineAxis"; +import ScienceIcon from "@mui/icons-material/Science"; +import DriveEtaIcon from "@mui/icons-material/DriveEta"; +import BiotechIcon from "@mui/icons-material/Biotech"; + +export const pageMenu = [ + { + id: "dashboard", + label: "پیشخوان", + type: "page", + route: "/dashboard", + icon: , + permissions: ["all"], + }, + { + id: "userManagement", + label: "مدیریت کاربران", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/user_management", + icon: , + permissions: ["full-user-management", "limited-user-management"], + }, + { + id: "projectsManagment", + label: "پروژه های راهداری", + type: "menu", + icon: , + hasSubitems: true, + Subitems: [ + { + id: "projectsManagmentFinance", + label: "ثبت قرارداد و پروژه", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/rahdari_projects/finance", + icon: , + permissions: ["show-contract", "show-contract-province"], + }, + { + id: "projectsManagmentList", + label: "لیست پروژه ها", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/rahdari_projects/projects_list", + icon: , + permissions: ["all"], + }, + { + id: "projectsManagmentProposal", + label: "پروژه های پیشنهادی", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/rahdari_projects/proposal", + icon: , + permissions: ["show-proposal", "show-proposal-province"], + }, + { + id: "projectsManagmentLawmaker", + label: "درخواست نمایندگان", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/rahdari_projects/lawmakers", + icon: , + permissions: ["show-lawmaker", "show-lawmaker-province"], + }, + { + id: "projectsManagmentMap", + label: "پراکندگی بر روی نقشه", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=rahdari_projects", + icon: , + permissions: ["all"], + }, + ], + }, + { + id: "roadItemManagment", + label: "فعالیت های روزانه", + type: "menu", + icon: , + hasSubitems: true, + badges: [{ key: "roadItem.total" }], + Subitems: [ + { + id: "roadItemManagmentSupervisor", + label: "ارزیابی", + type: "menu", + icon: , + hasSubitems: true, + badges: [{ key: "roadItem.supervise_cnt" }], + Subitems: [ + { + id: "roadItemManagmentSupervisorCartable", + label: "کارتابل", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_items/supervisor/cartable", + permissions: [ + "show-road-item-supervise-cartable", + "show-road-item-supervise-cartable-province", + ], + }, + ], + }, + { + id: "roadItemManagmentOparation", + label: "عملیات", + type: "menu", + icon: , + hasSubitems: true, + badges: [{ key: "roadItem.operation_cnt" }], + Subitems: [ + { + id: "roadItemManagmentOparationCreate", + label: "ثبت فعالیت", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_items/operator/create", + permissions: ["create-road-item"], + }, + { + id: "roadItemManagmentOparationCartable", + label: "کارتابل", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_items/operator/cartable", + permissions: ["create-road-item"], + }, + ], + }, + { + id: "roadItemManagmentMap", + label: "پراکندگی بر روی نقشه", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=road_items", + icon: , + permissions: [ + "show-road-item-supervise-cartable", + "show-road-item-supervise-cartable-province", + "create-road-item", + ], + }, + { + id: "roadItemManagmentReport", + label: "گزارش ها", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_items/report", + icon: , + permissions: [ + "show-road-item-supervise-cartable", + "show-road-item-supervise-cartable-province", + "create-road-item", + ], + }, + ], + }, + { + id: "roadPatrolManagment", + label: "گشت راهداری و ترابری", + type: "menu", + icon: , + hasSubitems: true, + Subitems: [ + { + id: "roadPatrolManagmentSupervisor", + label: "ارزیابی", + type: "menu", + icon: , + hasSubitems: true, + Subitems: [ + { + id: "roadPatrolManagmentSupervisorCartable", + label: "کارتابل", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_patrols/supervisor/cartable", + permissions: [ + "show-road-patrol-supervise-cartable", + "show-road-patrol-supervise-cartable-province", + ], + }, + ], + }, + { + id: "roadPatrolManagmentOparation", + label: "عملیات", + type: "menu", + icon: , + hasSubitems: true, + Subitems: [ + { + id: "roadPatrolManagmentOparationCreate", + label: "ثبت اقدام", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_patrols/operator/create", + permissions: ["add-road-patrol"], + }, + { + id: "roadPatrolManagmentOparationCartable", + label: "کارتابل", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_patrols/operator/cartable", + permissions: ["add-road-patrol"], + }, + ], + }, + { + id: "roadPatrolManagmentMap", + label: "پراکندگی بر روی نقشه", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=road_patrols", + icon: , + permissions: [ + "add-road-patrol", + "show-road-patrol-supervise-cartable", + "show-road-patrol-supervise-cartable-province", + ], + }, + { + id: "roadPatrolManagmentReport", + label: "گزارش ها", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_patrols/report", + icon: , + permissions: [ + "add-road-patrol", + "show-road-patrol-supervise-cartable", + "show-road-patrol-supervise-cartable-province", + ], + }, + ], + }, + { + id: "inquiryPrivacyManagment", + label: "استعلام حریم راه", + type: "menu", + icon: , + hasSubitems: true, + Subitems: [ + { + id: "cityAdminZaminGov", + label: "استعلام حرائم پنجره واحد", + type: "page", + route: "/dashboard/inquiry-privacy/city-admin/zamin-gov", + permissions: [], + }, + { + id: "provinceAdminZaminGov", + label: "استعلام حرائم پنجره واحد", + type: "page", + route: "/dashboard/inquiry-privacy/province-admin/zamin-gov", + permissions: [], + }, + { + id: "assistantZaminGov", + label: "استعلام حرائم پنجره واحد", + type: "page", + route: "/dashboard/inquiry-privacy/assistant/zamin-gov", + permissions: [], + }, + { + id: "generalManagerZaminGov", + label: "استعلام حرائم پنجره واحد", + type: "page", + route: "/dashboard/inquiry-privacy/general-manager/zamin-gov", + permissions: [], + }, + ], + }, + { + id: "safetyAndPrivacyManagment", + label: "نگهداری حریم راه", + type: "menu", + icon: , + hasSubitems: true, + badges: [ + { key: "safetyAndPrivacy.supervise_cnt" }, + { key: "safetyAndPrivacy.step_one", color: "warning" }, + { key: "safetyAndPrivacy.step_two", color: "error" }, + ], + Subitems: [ + { + id: "safetyAndPrivacyManagmentSupervisor", + label: "ارزیابی", + type: "menu", + icon: , + hasSubitems: true, + badges: [{ key: "safetyAndPrivacy.supervise_cnt" }], + Subitems: [ + { + id: "safetyAndPrivacyManagmentSupervisorCartable", + label: "کارتابل", + type: "page", + route: "/dashboard/road-safety/supervisor", + permissions: [ + "show-safety-and-privacy-operator-cartable", + "show-safety-and-privacy-operator-cartable-province", + ], + }, + ], + }, + { + id: "safetyAndPrivacyManagmentOparation", + label: "عملیات", + type: "menu", + icon: , + hasSubitems: true, + badges: [ + { key: "safetyAndPrivacy.step_one", color: "warning" }, + { key: "safetyAndPrivacy.step_two", color: "error" }, + ], + Subitems: [ + { + id: "safetyAndPrivacyManagmentOparationCartable", + label: "کارتابل", + type: "page", + route: "/dashboard/road-safety/operator", + permissions: ["show-safety-and-privacy-operator-cartable-edarate-shahri"], + }, + ], + }, + { + id: "safetyAndPrivacyManagmentMap", + label: "پراکندگی بر روی نقشه", + type: "page", + route: "/dashboard/road-safety/reports/map", + icon: , + permissions: [ + "show-safety-and-privacy-operator-cartable", + "show-safety-and-privacy-operator-cartable-province", + "show-safety-and-privacy-operator-cartable-edarate-shahri", + ], + }, + { + id: "safetyAndPrivacyManagmentReport", + label: "گزارش ها", + type: "page", + route: "/dashboard/road-safety/reports", + icon: , + permissions: [ + "show-safety-and-privacy-operator-cartable", + "show-safety-and-privacy-operator-cartable-province", + "show-safety-and-privacy-operator-cartable-edarate-shahri", + ], + }, + ], + }, + { + id: "roadObservationsManagment", + label: "واکنش سریع", + type: "menu", + icon: , + hasSubitems: true, + badges: [{ key: "roadObserved.total" }], + Subitems: [ + { + id: "roadObservationsManagmentSupervisor", + label: "ارزیابی", + type: "menu", + icon: , + hasSubitems: true, + badges: [{ key: "roadObserved.supervise_cnt" }, { key: "roadObserved.complaint_cnt", color: "info" }], + Subitems: [ + { + id: "roadObservationsManagmentSupervisorCartable", + label: "کارتابل", + type: "page", + route: "/dashboard/fast-react/supervisor", + permissions: ["show-fast-react", "show-fast-react-province"], + }, + ], + }, + { + id: "roadObservationsManagmentOparation", + label: "عملیات", + type: "menu", + icon: , + hasSubitems: true, + badges: [{ key: "roadObserved.operation_cnt" }, { key: "roadObserved.complaint_cnt", color: "info" }], + Subitems: [ + { + id: "roadObservationsManagmentOparationCartable", + label: "کارتابل", + type: "page", + route: "/dashboard/fast-react/operator", + permissions: ["show-fast-react-edarate-shahri"], + }, + ], + }, + { + id: "roadObservationsManagmentMap", + label: "پراکندگی بر روی نقشه", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=road_observations", + icon: , + permissions: ["all"], + }, + { + id: "roadObservationsManagmentReport", + label: "گزارش ها", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_observations/report/index", + icon: , + permissions: ["all"], + }, + ], + }, + { + id: "winterCampManagment", + label: "قرارگاه زمستانی", + type: "menu", + icon: , + hasSubitems: true, + Subitems: [ + { + id: "winterCampManagmentBlocking", + label: "محور های انسدادی", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/winter_camp", + icon: , + permissions: ["show-camp", "show-camp-province"], + }, + { + id: "winterCampManagmentFirstRing", + label: "محور های حلقه اول", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=camp", + icon: , + permissions: ["show-camp", "show-camp-province"], + }, + { + id: "winterCampManagmentReport", + label: "گزارش ها", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=campNew", + icon: , + permissions: ["show-camp", "show-camp-province"], + }, + ], + }, + { + id: "receiptManagment", + label: "خسارات وارده بر ابنیه فنی و تاسیسات راه", + type: "menu", + icon: , + hasSubitems: true, + Subitems: [ + { + id: "receiptManagmentOparation", + label: "عملیات", + type: "menu", + icon: , + hasSubitems: true, + Subitems: [ + { + id: "receiptManagmentOparationCartable", + label: "کارتابل", + type: "page", + route: "/dashboard/damages/operator", + permissions: ["show-receipt", "show-receipt-province"], + }, + ], + }, + { + id: "damagesManagmentReport", + label: "گزارش ها", + type: "page", + route: "/dashboard/damages/report", + icon: , + permissions: ["show-receipt", "show-receipt-province"], + }, + ], + }, + { + id: "azmayesh", + label: "آزمایشات (OPTS)", + type: "page", + route: "/dashboard/azmayesh", + icon: , + permissions: ["azmayesh-management"], + }, + { + id: "azmayeshType", + label: "نوع آزمایشات", + type: "page", + route: "/dashboard/azmayesh_type", + icon: , + permissions: ["azmayesh-type-management"], + }, + { + id: "adminManagement", + label: "مدیریت سامانه", + type: "menu", + icon: , + hasSubitems: true, + Subitems: [ + { + id: "permissionItem", + label: "سطح دسترسی ها", + type: "page", + route: "/dashboard/permissions", + icon: , + permissions: ["manage-permissions"], + }, + { + id: "userActivities", + label: "انواع فعالیت کاربران", + type: "page", + route: "/dashboard/user-activities", + icon: , + permissions: ["manage-log-list"], + }, + { + id: "damageItems", + label: "آیتم خسارات وارده بر ابنیه فنی", + type: "page", + route: "/dashboard/damage-items", + icon: , + permissions: ["manage-damage"], + }, + { + id: "CarDetails", + label: "اطلاعات خودرو", + type: "page", + route: "/dashboard/car-details", + icon: , + permissions: [""], + }, + ], + }, +]; diff --git a/src/core/utils/pageMenuDev.js b/src/core/utils/pageMenuDev.js index f881e04..1cb3650 100644 --- a/src/core/utils/pageMenuDev.js +++ b/src/core/utils/pageMenuDev.js @@ -1,548 +1,579 @@ -import SpaceDashboardIcon from "@mui/icons-material/SpaceDashboard"; -import GroupsIcon from "@mui/icons-material/Groups"; -import AccountTreeIcon from "@mui/icons-material/AccountTree"; -import FactCheckIcon from "@mui/icons-material/FactCheck"; -import FireTruckIcon from "@mui/icons-material/FireTruck"; -import RouteIcon from "@mui/icons-material/Route"; -import DoorbellIcon from "@mui/icons-material/Doorbell"; -import ElectricBoltIcon from "@mui/icons-material/ElectricBolt"; -import CottageIcon from "@mui/icons-material/Cottage"; -import GppMaybeIcon from "@mui/icons-material/GppMaybe"; -import GavelIcon from "@mui/icons-material/Gavel"; -import BallotIcon from "@mui/icons-material/Ballot"; -import AssistantIcon from "@mui/icons-material/Assistant"; -import AdminPanelSettingsIcon from "@mui/icons-material/AdminPanelSettings"; -import MapIcon from "@mui/icons-material/Map"; -import SpeedIcon from "@mui/icons-material/Speed"; -import EngineeringIcon from "@mui/icons-material/Engineering"; -import AssessmentIcon from "@mui/icons-material/Assessment"; -import AssignmentLateIcon from "@mui/icons-material/AssignmentLate"; -import LockPersonIcon from "@mui/icons-material/LockPerson"; -import LineAxisIcon from "@mui/icons-material/LineAxis"; -import ScienceIcon from "@mui/icons-material/Science"; -import DriveEtaIcon from "@mui/icons-material/DriveEta"; -import BiotechIcon from "@mui/icons-material/Biotech"; - -export const pageMenuDev = [ - { - id: "dashboard", - label: "پیشخوان", - type: "page", - route: "/dashboard", - icon: , - permissions: ["all"], - }, - { - id: "userManagement", - label: "مدیریت کاربران", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/user_management", - icon: , - permissions: ["full-user-management", "limited-user-management"], - }, - { - id: "projectsManagment", - label: "پروژه های راهداری", - type: "menu", - icon: , - hasSubitems: true, - Subitems: [ - { - id: "projectsManagmentFinance", - label: "ثبت قرارداد و پروژه", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/rahdari_projects/finance", - icon: , - permissions: ["show-contract", "show-contract-province"], - }, - { - id: "projectsManagmentList", - label: "لیست پروژه ها", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/rahdari_projects/projects_list", - icon: , - permissions: ["all"], - }, - { - id: "projectsManagmentProposal", - label: "پروژه های پیشنهادی", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/rahdari_projects/proposal", - icon: , - permissions: ["show-proposal", "show-proposal-province"], - }, - { - id: "projectsManagmentLawmaker", - label: "درخواست نمایندگان", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/rahdari_projects/lawmakers", - icon: , - permissions: ["show-lawmaker", "show-lawmaker-province"], - }, - { - id: "projectsManagmentMap", - label: "پراکندگی بر روی نقشه", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=rahdari_projects", - icon: , - permissions: ["all"], - }, - ], - }, - { - id: "roadItemManagment", - label: "فعالیت های روزانه", - type: "menu", - icon: , - hasSubitems: true, - badges: [{ key: "roadItem.total" }], - Subitems: [ - { - id: "roadItemManagmentSupervisor", - label: "ارزیابی", - type: "menu", - icon: , - hasSubitems: true, - badges: [{ key: "roadItem.supervise_cnt" }], - Subitems: [ - { - id: "roadItemManagmentSupervisorCartable", - label: "کارتابل", - type: "page", - route: "/dashboard/road-items/supervisor", - permissions: [ - "show-road-item-supervise-cartable", - "show-road-item-supervise-cartable-province", - ], - }, - ], - }, - { - id: "roadItemManagmentOparation", - label: "عملیات", - type: "menu", - icon: , - hasSubitems: true, - badges: [{ key: "roadItem.operation_cnt" }], - Subitems: [ - { - id: "roadItemManagmentOparationCartable", - label: "کارتابل", - type: "page", - route: "/dashboard/road-items/operator", - permissions: ["create-road-item"], - }, - ], - }, - { - id: "roadItemManagmentMap", - label: "پراکندگی بر روی نقشه", - type: "page", - route: "/dashboard/road-items/reports/map", - icon: , - permissions: [ - "show-road-item-supervise-cartable", - "show-road-item-supervise-cartable-province", - "create-road-item", - ], - }, - { - id: "roadItemManagmentReport", - label: "گزارش ها", - type: "menu", - icon: , - hasSubitems: true, - Subitems: [ - { - id: "roadItemManagmentReportProvince", - label: "تعداد فعالیت ها به تفکیک آیتم", - type: "page", - route: "/dashboard/road-items/reports/items-report", - permissions: [ - "show-road-item-supervise-cartable", - "show-road-item-supervise-cartable-province", - "create-road-item", - ], - }, - { - id: "roadItemManagmentReportItems", - label: "تعداد و حجم فعالیت ها به تفکیک موارد اقدام شده", - type: "page", - route: "/dashboard/road-items/reports/sub-items-report", - permissions: [ - "show-road-item-supervise-cartable", - "show-road-item-supervise-cartable-province", - "create-road-item", - ], - }, - ], - }, - ], - }, - { - id: "roadPatrolManagment", - label: "گشت راهداری و ترابری", - type: "menu", - icon: , - hasSubitems: true, - Subitems: [ - { - id: "roadPatrolManagmentSupervisor", - label: "ارزیابی", - type: "menu", - icon: , - hasSubitems: true, - Subitems: [ - { - id: "roadPatrolManagmentSupervisorCartable", - label: "کارتابل", - type: "page", - route: "/dashboard/road-patrols/supervisor", - permissions: [ - "show-road-patrol-supervise-cartable", - "show-road-patrol-supervise-cartable-province", - ], - }, - ], - }, - { - id: "roadPatrolManagmentOparation", - label: "عملیات", - type: "menu", - icon: , - hasSubitems: true, - Subitems: [ - { - id: "roadPatrolManagmentOparationCartable", - label: "کارتابل", - type: "page", - route: "/dashboard/road-patrols/operator", - permissions: ["add-road-patrol"], - }, - ], - }, - { - id: "roadPatrolManagmentMap", - label: "پراکندگی بر روی نقشه", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=road_patrols", - icon: , - permissions: [ - "add-road-patrol", - "show-road-patrol-supervise-cartable", - "show-road-patrol-supervise-cartable-province", - ], - }, - { - id: "roadPatrolManagmentReport", - label: "گزارش ها", - type: "page", - route: "/dashboard/road-patrols/reports", - icon: , - permissions: [ - "add-road-patrol", - "show-road-patrol-supervise-cartable", - "show-road-patrol-supervise-cartable-province", - ], - }, - ], - }, - { - id: "inquiryPrivacyManagment", - label: "استعلام حریم راه", - type: "menu", - icon: , - hasSubitems: true, - Subitems: [ - { - id: "cityAdminZaminGov", - label: "استعلام حرائم پنجره واحد", - type: "page", - route: "/dashboard/inquiry-privacy/city-admin/zamin-gov", - permissions: [], - }, - { - id: "provinceAdminZaminGov", - label: "استعلام حرائم پنجره واحد", - type: "page", - route: "/dashboard/inquiry-privacy/province-admin/zamin-gov", - permissions: [], - }, - { - id: "assistantZaminGov", - label: "استعلام حرائم پنجره واحد", - type: "page", - route: "/dashboard/inquiry-privacy/assistant/zamin-gov", - permissions: [], - }, - { - id: "generalManagerZaminGov", - label: "استعلام حرائم پنجره واحد", - type: "page", - route: "/dashboard/inquiry-privacy/general-manager/zamin-gov", - permissions: [], - }, - ], - }, - { - id: "safetyAndPrivacyManagment", - label: "نگهداری حریم راه", - type: "menu", - icon: , - hasSubitems: true, - badges: [ - { key: "safetyAndPrivacy.supervise_cnt" }, - { key: "safetyAndPrivacy.step_one", color: "warning" }, - { key: "safetyAndPrivacy.step_two", color: "error" }, - ], - Subitems: [ - { - id: "safetyAndPrivacyManagmentSupervisor", - label: "ارزیابی", - type: "menu", - icon: , - hasSubitems: true, - badges: [{ key: "safetyAndPrivacy.supervise_cnt" }], - Subitems: [ - { - id: "safetyAndPrivacyManagmentSupervisorCartable", - label: "کارتابل", - type: "page", - route: "/dashboard/road-safety/supervisor", - permissions: [ - "show-safety-and-privacy-operator-cartable", - "show-safety-and-privacy-operator-cartable-province", - ], - }, - ], - }, - { - id: "safetyAndPrivacyManagmentOparation", - label: "عملیات", - type: "menu", - icon: , - hasSubitems: true, - badges: [ - { key: "safetyAndPrivacy.step_one", color: "warning" }, - { key: "safetyAndPrivacy.step_two", color: "error" }, - ], - Subitems: [ - { - id: "safetyAndPrivacyManagmentOparationCartable", - label: "کارتابل", - type: "page", - route: "/dashboard/road-safety/operator", - permissions: ["show-safety-and-privacy-operator-cartable-edarate-shahri"], - }, - ], - }, - { - id: "safetyAndPrivacyManagmentMap", - label: "پراکندگی بر روی نقشه", - type: "page", - route: "/dashboard/road-safety/reports/map", - icon: , - permissions: [ - "show-safety-and-privacy-operator-cartable", - "show-safety-and-privacy-operator-cartable-province", - "show-safety-and-privacy-operator-cartable-edarate-shahri", - ], - }, - { - id: "safetyAndPrivacyManagmentReport", - label: "گزارش ها", - type: "page", - route: "/dashboard/road-safety/reports", - icon: , - permissions: [ - "show-safety-and-privacy-operator-cartable", - "show-safety-and-privacy-operator-cartable-province", - "show-safety-and-privacy-operator-cartable-edarate-shahri", - ], - }, - ], - }, - { - id: "roadObservationsManagment", - label: "واکنش سریع", - type: "menu", - icon: , - hasSubitems: true, - badges: [{ key: "roadObserved.total" }], - Subitems: [ - { - id: "roadObservationsManagmentSupervisor", - label: "ارزیابی", - type: "menu", - icon: , - hasSubitems: true, - badges: [{ key: "roadObserved.supervise_cnt" }, { key: "roadObserved.complaint_cnt", color: "info" }], - Subitems: [ - { - id: "roadObservationsManagmentSupervisorCartable", - label: "کارتابل", - type: "page", - route: "/dashboard/fast-react/supervisor", - permissions: ["show-fast-react", "show-fast-react-province"], - }, - ], - }, - { - id: "roadObservationsManagmentOparation", - label: "عملیات", - type: "menu", - icon: , - hasSubitems: true, - badges: [{ key: "roadObserved.operation_cnt" }, { key: "roadObserved.complaint_cnt", color: "info" }], - Subitems: [ - { - id: "roadObservationsManagmentOparationCartable", - label: "کارتابل", - type: "page", - route: "/dashboard/fast-react/operator", - permissions: ["show-fast-react-edarate-shahri"], - }, - ], - }, - { - id: "roadObservationsManagmentMap", - label: "پراکندگی بر روی نقشه", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=road_observations", - icon: , - permissions: ["all"], - }, - { - id: "roadObservationsManagmentReport", - label: "گزارش ها", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_observations/report/index", - icon: , - permissions: ["all"], - }, - ], - }, - { - id: "winterCampManagment", - label: "قرارگاه زمستانی", - type: "menu", - icon: , - hasSubitems: true, - Subitems: [ - { - id: "winterCampManagmentBlocking", - label: "محور های انسدادی", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/winter_camp", - icon: , - permissions: ["show-camp", "show-camp-province"], - }, - { - id: "winterCampManagmentFirstRing", - label: "محور های حلقه اول", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=camp", - icon: , - permissions: ["show-camp", "show-camp-province"], - }, - { - id: "winterCampManagmentReport", - label: "گزارش ها", - type: "page", - route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=campNew", - icon: , - permissions: ["show-camp", "show-camp-province"], - }, - ], - }, - { - id: "receiptManagment", - label: "خسارات وارده بر ابنیه فنی و تاسیسات راه", - type: "menu", - icon: , - hasSubitems: true, - Subitems: [ - { - id: "receiptManagmentOparation", - label: "عملیات", - type: "menu", - icon: , - hasSubitems: true, - Subitems: [ - { - id: "receiptManagmentOparationCartable", - label: "کارتابل", - type: "page", - route: "/dashboard/damages/operator", - permissions: ["all"], - }, - ], - }, - { - id: "damagesManagmentReport", - label: "گزارش ها", - type: "page", - route: "/dashboard/damages/report", - icon: , - permissions: ["show-receipt", "show-receipt-province"], - }, - ], - }, - { - id: "azmayesh", - label: "آزمایشات (OPTS)", - type: "page", - route: "/dashboard/azmayesh", - icon: , - permissions: ["azmayesh-management"], - }, - { - id: "azmayeshType", - label: "نوع آزمایشات", - type: "page", - route: "/dashboard/azmayesh_type", - icon: , - permissions: ["azmayesh-type-management"], - }, - { - id: "adminManagement", - label: "مدیریت سامانه", - type: "menu", - icon: , - hasSubitems: true, - Subitems: [ - { - id: "permissionItem", - label: "سطح دسترسی ها", - type: "page", - route: "/dashboard/permissions", - icon: , - permissions: ["manage-permissions"], - }, - { - id: "userActivities", - label: "انواع فعالیت کاربران", - type: "page", - route: "/dashboard/user-activities", - icon: , - permissions: ["manage-log-list"], - }, - { - id: "damageItems", - label: "آیتم خسارات وارده بر ابنیه فنی", - type: "page", - route: "/dashboard/damage-items", - icon: , - permissions: ["manage-damage"], - }, - { - id: "CarDetails", - label: "اطلاعات خودرو", - type: "page", - route: "/dashboard/car-details", - icon: , - permissions: [""], - }, - ], - }, -]; +import SpaceDashboardIcon from "@mui/icons-material/SpaceDashboard"; +import GroupsIcon from "@mui/icons-material/Groups"; +import AccountTreeIcon from "@mui/icons-material/AccountTree"; +import FactCheckIcon from "@mui/icons-material/FactCheck"; +import FireTruckIcon from "@mui/icons-material/FireTruck"; +import RouteIcon from "@mui/icons-material/Route"; +import DoorbellIcon from "@mui/icons-material/Doorbell"; +import ElectricBoltIcon from "@mui/icons-material/ElectricBolt"; +import CottageIcon from "@mui/icons-material/Cottage"; +import GppMaybeIcon from "@mui/icons-material/GppMaybe"; +import GavelIcon from "@mui/icons-material/Gavel"; +import BallotIcon from "@mui/icons-material/Ballot"; +import AssistantIcon from "@mui/icons-material/Assistant"; +import AdminPanelSettingsIcon from "@mui/icons-material/AdminPanelSettings"; +import MapIcon from "@mui/icons-material/Map"; +import SpeedIcon from "@mui/icons-material/Speed"; +import EngineeringIcon from "@mui/icons-material/Engineering"; +import AssessmentIcon from "@mui/icons-material/Assessment"; +import AssignmentLateIcon from "@mui/icons-material/AssignmentLate"; +import LockPersonIcon from "@mui/icons-material/LockPerson"; +import LineAxisIcon from "@mui/icons-material/LineAxis"; +import ScienceIcon from "@mui/icons-material/Science"; +import DriveEtaIcon from "@mui/icons-material/DriveEta"; +import BiotechIcon from "@mui/icons-material/Biotech"; +import { Mediation } from "@mui/icons-material"; + +export const pageMenuDev = [ + { + id: "dashboard", + label: "پیشخوان", + type: "page", + route: "/dashboard", + icon: , + permissions: ["all"], + }, + { + id: "userManagement", + label: "مدیریت کاربران", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/user_management", + icon: , + permissions: ["full-user-management", "limited-user-management"], + }, + { + id: "projectsManagment", + label: "پروژه های راهداری", + type: "menu", + icon: , + hasSubitems: true, + Subitems: [ + { + id: "projectsManagmentFinance", + label: "ثبت قرارداد و پروژه", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/rahdari_projects/finance", + icon: , + permissions: ["show-contract", "show-contract-province"], + }, + { + id: "projectsManagmentList", + label: "لیست پروژه ها", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/rahdari_projects/projects_list", + icon: , + permissions: ["all"], + }, + { + id: "projectsManagmentProposal", + label: "پروژه های پیشنهادی", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/rahdari_projects/proposal", + icon: , + permissions: ["show-proposal", "show-proposal-province"], + }, + { + id: "projectsManagmentLawmaker", + label: "درخواست نمایندگان", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/rahdari_projects/lawmakers", + icon: , + permissions: ["show-lawmaker", "show-lawmaker-province"], + }, + { + id: "projectsManagmentMap", + label: "پراکندگی بر روی نقشه", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=rahdari_projects", + icon: , + permissions: ["all"], + }, + ], + }, + { + id: "roadMissionsManagemnet", + label: "ماموریت ها", + type: "menu", + icon: , + hasSubitems: true, + Subitems: [ + { + id: "roadMissionsManagemnetRequests", + label: "کارتابل", + type: "page", + route: "/dashboard/road-missions/operator", + permissions: ["all"], + }, + { + id: "roadMissionsManagemnetNaqlie", + label: "نقلیه", + type: "page", + route: "/dashboard/road-missions/transportation", + permissions: ["all"], + }, + { + id: "roadMissionsManagemnetControl", + label: "کنترل", + type: "page", + route: "/dashboard/road-missions/control", + permissions: ["all"], + }, + ], + }, + { + id: "roadItemManagment", + label: "فعالیت های روزانه", + type: "menu", + icon: , + hasSubitems: true, + badges: [{ key: "roadItem.total" }], + Subitems: [ + { + id: "roadItemManagmentSupervisor", + label: "ارزیابی", + type: "menu", + icon: , + hasSubitems: true, + badges: [{ key: "roadItem.supervise_cnt" }], + Subitems: [ + { + id: "roadItemManagmentSupervisorCartable", + label: "کارتابل", + type: "page", + route: "/dashboard/road-items/supervisor", + permissions: [ + "show-road-item-supervise-cartable", + "show-road-item-supervise-cartable-province", + ], + }, + ], + }, + { + id: "roadItemManagmentOparation", + label: "عملیات", + type: "menu", + icon: , + hasSubitems: true, + badges: [{ key: "roadItem.operation_cnt" }], + Subitems: [ + { + id: "roadItemManagmentOparationCartable", + label: "کارتابل", + type: "page", + route: "/dashboard/road-items/operator", + permissions: ["create-road-item"], + }, + ], + }, + { + id: "roadItemManagmentMap", + label: "پراکندگی بر روی نقشه", + type: "page", + route: "/dashboard/road-items/reports/map", + icon: , + permissions: [ + "show-road-item-supervise-cartable", + "show-road-item-supervise-cartable-province", + "create-road-item", + ], + }, + { + id: "roadItemManagmentReport", + label: "گزارش ها", + type: "menu", + icon: , + hasSubitems: true, + Subitems: [ + { + id: "roadItemManagmentReportProvince", + label: "تعداد فعالیت ها به تفکیک آیتم", + type: "page", + route: "/dashboard/road-items/reports/items-report", + permissions: [ + "show-road-item-supervise-cartable", + "show-road-item-supervise-cartable-province", + "create-road-item", + ], + }, + { + id: "roadItemManagmentReportItems", + label: "تعداد و حجم فعالیت ها به تفکیک موارد اقدام شده", + type: "page", + route: "/dashboard/road-items/reports/sub-items-report", + permissions: [ + "show-road-item-supervise-cartable", + "show-road-item-supervise-cartable-province", + "create-road-item", + ], + }, + ], + }, + ], + }, + { + id: "roadPatrolManagment", + label: "گشت راهداری و ترابری", + type: "menu", + icon: , + hasSubitems: true, + Subitems: [ + { + id: "roadPatrolManagmentSupervisor", + label: "ارزیابی", + type: "menu", + icon: , + hasSubitems: true, + Subitems: [ + { + id: "roadPatrolManagmentSupervisorCartable", + label: "کارتابل", + type: "page", + route: "/dashboard/road-patrols/supervisor", + permissions: [ + "show-road-patrol-supervise-cartable", + "show-road-patrol-supervise-cartable-province", + ], + }, + ], + }, + { + id: "roadPatrolManagmentOparation", + label: "عملیات", + type: "menu", + icon: , + hasSubitems: true, + Subitems: [ + { + id: "roadPatrolManagmentOparationCartable", + label: "کارتابل", + type: "page", + route: "/dashboard/road-patrols/operator", + permissions: ["add-road-patrol"], + }, + ], + }, + { + id: "roadPatrolManagmentMap", + label: "پراکندگی بر روی نقشه", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=road_patrols", + icon: , + permissions: [ + "add-road-patrol", + "show-road-patrol-supervise-cartable", + "show-road-patrol-supervise-cartable-province", + ], + }, + { + id: "roadPatrolManagmentReport", + label: "گزارش ها", + type: "page", + route: "/dashboard/road-patrols/reports", + icon: , + permissions: [ + "add-road-patrol", + "show-road-patrol-supervise-cartable", + "show-road-patrol-supervise-cartable-province", + ], + }, + ], + }, + { + id: "inquiryPrivacyManagment", + label: "استعلام حریم راه", + type: "menu", + icon: , + hasSubitems: true, + Subitems: [ + { + id: "cityAdminZaminGov", + label: "استعلام حرائم پنجره واحد", + type: "page", + route: "/dashboard/inquiry-privacy/city-admin/zamin-gov", + permissions: [], + }, + { + id: "provinceAdminZaminGov", + label: "استعلام حرائم پنجره واحد", + type: "page", + route: "/dashboard/inquiry-privacy/province-admin/zamin-gov", + permissions: [], + }, + { + id: "assistantZaminGov", + label: "استعلام حرائم پنجره واحد", + type: "page", + route: "/dashboard/inquiry-privacy/assistant/zamin-gov", + permissions: [], + }, + { + id: "generalManagerZaminGov", + label: "استعلام حرائم پنجره واحد", + type: "page", + route: "/dashboard/inquiry-privacy/general-manager/zamin-gov", + permissions: [], + }, + ], + }, + { + id: "safetyAndPrivacyManagment", + label: "نگهداری حریم راه", + type: "menu", + icon: , + hasSubitems: true, + badges: [ + { key: "safetyAndPrivacy.supervise_cnt" }, + { key: "safetyAndPrivacy.step_one", color: "warning" }, + { key: "safetyAndPrivacy.step_two", color: "error" }, + ], + Subitems: [ + { + id: "safetyAndPrivacyManagmentSupervisor", + label: "ارزیابی", + type: "menu", + icon: , + hasSubitems: true, + badges: [{ key: "safetyAndPrivacy.supervise_cnt" }], + Subitems: [ + { + id: "safetyAndPrivacyManagmentSupervisorCartable", + label: "کارتابل", + type: "page", + route: "/dashboard/road-safety/supervisor", + permissions: [ + "show-safety-and-privacy-operator-cartable", + "show-safety-and-privacy-operator-cartable-province", + ], + }, + ], + }, + { + id: "safetyAndPrivacyManagmentOparation", + label: "عملیات", + type: "menu", + icon: , + hasSubitems: true, + badges: [ + { key: "safetyAndPrivacy.step_one", color: "warning" }, + { key: "safetyAndPrivacy.step_two", color: "error" }, + ], + Subitems: [ + { + id: "safetyAndPrivacyManagmentOparationCartable", + label: "کارتابل", + type: "page", + route: "/dashboard/road-safety/operator", + permissions: ["show-safety-and-privacy-operator-cartable-edarate-shahri"], + }, + ], + }, + { + id: "safetyAndPrivacyManagmentMap", + label: "پراکندگی بر روی نقشه", + type: "page", + route: "/dashboard/road-safety/reports/map", + icon: , + permissions: [ + "show-safety-and-privacy-operator-cartable", + "show-safety-and-privacy-operator-cartable-province", + "show-safety-and-privacy-operator-cartable-edarate-shahri", + ], + }, + { + id: "safetyAndPrivacyManagmentReport", + label: "گزارش ها", + type: "page", + route: "/dashboard/road-safety/reports", + icon: , + permissions: [ + "show-safety-and-privacy-operator-cartable", + "show-safety-and-privacy-operator-cartable-province", + "show-safety-and-privacy-operator-cartable-edarate-shahri", + ], + }, + ], + }, + { + id: "roadObservationsManagment", + label: "واکنش سریع", + type: "menu", + icon: , + hasSubitems: true, + badges: [{ key: "roadObserved.total" }], + Subitems: [ + { + id: "roadObservationsManagmentSupervisor", + label: "ارزیابی", + type: "menu", + icon: , + hasSubitems: true, + badges: [{ key: "roadObserved.supervise_cnt" }, { key: "roadObserved.complaint_cnt", color: "info" }], + Subitems: [ + { + id: "roadObservationsManagmentSupervisorCartable", + label: "کارتابل", + type: "page", + route: "/dashboard/fast-react/supervisor", + permissions: ["show-fast-react", "show-fast-react-province"], + }, + ], + }, + { + id: "roadObservationsManagmentOparation", + label: "عملیات", + type: "menu", + icon: , + hasSubitems: true, + badges: [{ key: "roadObserved.operation_cnt" }, { key: "roadObserved.complaint_cnt", color: "info" }], + Subitems: [ + { + id: "roadObservationsManagmentOparationCartable", + label: "کارتابل", + type: "page", + route: "/dashboard/fast-react/operator", + permissions: ["show-fast-react-edarate-shahri"], + }, + ], + }, + { + id: "roadObservationsManagmentMap", + label: "پراکندگی بر روی نقشه", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=road_observations", + icon: , + permissions: ["all"], + }, + { + id: "roadObservationsManagmentReport", + label: "گزارش ها", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/road_observations/report/index", + icon: , + permissions: ["all"], + }, + ], + }, + { + id: "winterCampManagment", + label: "قرارگاه زمستانی", + type: "menu", + icon: , + hasSubitems: true, + Subitems: [ + { + id: "winterCampManagmentBlocking", + label: "محور های انسدادی", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/winter_camp", + icon: , + permissions: ["show-camp", "show-camp-province"], + }, + { + id: "winterCampManagmentFirstRing", + label: "محور های حلقه اول", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=camp", + icon: , + permissions: ["show-camp", "show-camp-province"], + }, + { + id: "winterCampManagmentReport", + label: "گزارش ها", + type: "page", + route: process.env.NEXT_PUBLIC_API_URL + "/v2/map?type=campNew", + icon: , + permissions: ["show-camp", "show-camp-province"], + }, + ], + }, + { + id: "receiptManagment", + label: "خسارات وارده بر ابنیه فنی و تاسیسات راه", + type: "menu", + icon: , + hasSubitems: true, + Subitems: [ + { + id: "receiptManagmentOparation", + label: "عملیات", + type: "menu", + icon: , + hasSubitems: true, + Subitems: [ + { + id: "receiptManagmentOparationCartable", + label: "کارتابل", + type: "page", + route: "/dashboard/damages/operator", + permissions: ["all"], + }, + ], + }, + { + id: "damagesManagmentReport", + label: "گزارش ها", + type: "page", + route: "/dashboard/damages/report", + icon: , + permissions: ["show-receipt", "show-receipt-province"], + }, + ], + }, + { + id: "azmayesh", + label: "آزمایشات (OPTS)", + type: "page", + route: "/dashboard/azmayesh", + icon: , + permissions: ["azmayesh-management"], + }, + { + id: "azmayeshType", + label: "نوع آزمایشات", + type: "page", + route: "/dashboard/azmayesh_type", + icon: , + permissions: ["azmayesh-type-management"], + }, + { + id: "adminManagement", + label: "مدیریت سامانه", + type: "menu", + icon: , + hasSubitems: true, + Subitems: [ + { + id: "permissionItem", + label: "سطح دسترسی ها", + type: "page", + route: "/dashboard/permissions", + icon: , + permissions: ["manage-permissions"], + }, + { + id: "userActivities", + label: "انواع فعالیت کاربران", + type: "page", + route: "/dashboard/user-activities", + icon: , + permissions: ["manage-log-list"], + }, + { + id: "damageItems", + label: "آیتم خسارات وارده بر ابنیه فنی", + type: "page", + route: "/dashboard/damage-items", + icon: , + permissions: ["manage-damage"], + }, + { + id: "CarDetails", + label: "اطلاعات خودرو", + type: "page", + route: "/dashboard/car-details", + icon: , + permissions: [""], + }, + ], + }, +]; diff --git a/src/core/utils/routes.js b/src/core/utils/routes.js index 83018ae..741127c 100644 --- a/src/core/utils/routes.js +++ b/src/core/utils/routes.js @@ -1,178 +1,193 @@ -const api = process.env.NEXT_PUBLIC_API_URL; - -export const GET_USER_ROUTE = api + "/api/v3/profile/info"; -export const LOGOUT_USER_ROUTE = api + "/api/v3/logout"; -export const UPDATE_USER_ROUTE = api + "/api/v3/profile/edit"; -export const CHANGE_USER_PASSWORD = api + "/api/v3/profile/change_password"; -export const GET_LOGIN_ROUTE = api + "/login_dev"; -export const GET_PERMISSIONS_ROUTE = api + "/webapi/user/get-permission"; -export const GET_SIDEBAR_BADGE_ROUTE = api + "/api/v3/notifications"; -export const REFER_ADMIN_PROVINCE = "/v3/api/fake-submit"; -export const REFER_ADMIN_CITY = "/v3/api/fake-submit"; -export const GET_CITY_LISTS = api + "/public/contents/provinces"; -export const GET_PROVINCE_LISTS = api + "/public/contents/provinces"; -export const GET_PREV_STATE_OPINION = "/v3/api/fake-prev-state-opinion"; -export const SUBMIT_ROAD_SAFETY_FORM = "/v3/api/fake-submit"; -export const CREATE_AZMAYESH = api + "/api/v3/azmayeshes/store"; -export const UPDATE_AZMAYESH = api + "/api/v3/azmayeshes/update"; -export const GET_AZMAYESH_TYPE_LIST = api + "/api/v3/azmayesh_types/list"; -export const GET_AZMAYESH_TYPE_LIST_TABLE = api + "/api/v3/azmayesh_types"; -export const GET_AZMAYESH_LIST = api + "/api/v3/azmayeshes"; -export const DELETE_AZMAYESH = api + "/api/v3/azmayeshes/delete"; -export const GET_AZMAYESH_SAMPLE_FIELDS = api + "/api/v3/azmayesh_types/fields"; -export const ADD_SAMPLE_TO_AZMAYESH = api + "/api/v3/azmayesh_samples/store"; -export const UPDATE_SAMPLE_OF_AZMAYESH = api + "/api/v3/azmayesh_samples/update"; -export const GET_SAMPLE_LIST = api + "/api/v3/azmayesh_samples"; -export const DELETE_SAMPLE_LIST = api + "/api/v3/azmayesh_samples/delete"; -export const DELETE_AZMAYESH_TYPE_LIST = api + "/api/v3/azmayesh_types/delete"; -export const ADD_AZMAYESH_TYPE = api + "/api/v3/azmayesh_types/store"; -export const UPDATE_AZMAYESH_TYPE = api + "/api/v3/azmayesh_types/update"; - -//road patrol -export const GET_ROAD_PATROL_OPERATOR_LIST = api + "/api/v3/road_patrols/operator_index"; -export const EXPORT_ROAD_PATROL_OPERATOR_LIST = api + "/api/v3/road_patrols/operator_report"; -export const GET_ROAD_PATROL_SUPERVISOR_LIST = api + "/api/v3/road_patrols/supervisor_index"; -export const EXPORT_ROAD_PATROL_SUPERVISOR_LIST = api + "/api/v3/road_patrols/supervisor_report"; -export const EXPORT_PROVINCE_ROAD_PATROL_REPORTS = api + "/api/v3/road_patrol_reports/province_activity_excel"; -export const EXPORT_COUNTRY_ROAD_PATROL_REPORTS = api + "/api/v3/road_patrol_reports/country_activity_excel"; -export const DELETE_ROAD_PATROL_SUPERVISOR = api + "/api/v3/road_patrols/delete"; -export const GET_CMMS_MACHINE_ROAD_PATROL = api + "/api/v3/road_patrols/machines"; -export const GET_ROAD_PATROL_OPERATOR_REPORT = api + "/v2/road_patrols/operator/report"; -export const GET_ROAD_PATROL_SUPERVISOR_REPORT = api + "/v2/road_patrols/operator/report"; -export const GET_RAHDARAN_ROAD_POTROL = api + "/api/v3/road_patrols/rahdaran"; -export const CREATE_PATROL = api + "/api/v3/road_patrols/store"; -export const GET_FMS_DATA = api + "/api/v3/fms_vehicle/get_activity"; -export const GET_OTP_TOKEN = api + "/api/v3/otp/get_token"; -export const GET_PROVINCE_ACTIVITY_REPORT = api + "/api/v3/road_patrol_reports/country_activity"; -export const GET_CITY_ACTIVITY_REPORT = api + "/api/v3/road_patrol_reports/province_activity"; - -// road items -export const GET_ROAD_ITEMS_SUPERVISOR_LIST = api + "/api/v3/road_items/supervisor_index"; -export const EXPORT_ROAD_ITEMS_SUPERVISOR_LIST = api + "/api/v3/road_items/supervisor_report"; -export const GET_ROAD_ITEMS_OPERATOR_LIST = api + "/api/v3/road_items/operator_index"; -export const EXPORT_ROAD_ITEMS_OPERATOR_LIST = api + "/api/v3/road_items/operator_report"; -export const EXPORT_PROVINCE_ROAD_ITEM_REPORTS_PER_ITEM = - api + "/api/v3/road_item_reports/province_activity_excel_per_item"; -export const EXPORT_COUNTRY_ROAD_ITEM_REPORTS_PER_ITEM = - api + "/api/v3/road_item_reports/country_activity_excel_per_item"; -export const EXPORT_PROVINCE_ROAD_ITEM_REPORTS_PER_SUB_ITEM = - api + "/api/v3/road_item_reports/province_activity_excel_per_sub_item"; -export const EXPORT_COUNTRY_ROAD_ITEM_REPORTS_PER_SUB_ITEM = - api + "/api/v3/road_item_reports/country_activity_excel_per_sub_item"; -export const GET_ROAD_ITEMS_ITEM = api + "/api/v3/items"; -export const GET_ROAD_ITEMS_SUB_ITEM = api + "/api/v3/sub_items"; -export const GET_EDARAT_LISTS = api + "/public/contents/edarate_shahri_by_province"; -export const CREATE_ROAD_ITEMS = api + "/api/v3/road_items/store"; -export const UPDATE_ROAD_ITEMS = api + "/api/v3/road_items/update"; -export const VERIFY_BY_SUPERVISOR = api + "/api/v3/road_items/verify_by_supervisor"; -export const REJECT_BY_SUPERVISOR = api + "/api/v3/road_items/verify_by_supervisor"; -export const DELETE_BY_SUPERVISOR = api + "/api/v3/road_items/delete"; -export const RESTORE_BY_SUPERVISOR = api + "/api/v3/road_items/restore"; -export const GET_CAR_LIST_SEARCH = api + "/api/v3/cmms_machines/search"; -export const GET_RAHDARANS_LIST_SEARCH = api + "/api/v3/rahdaran/search"; -export const GET_OBSERVED_GASHT_LIST = api + "/api/v3/observed_items/filter"; -export const GET_ROAD_ITEMS_REPORT_MAP = api + "/api/v3/road_item_reports/activities_on_map"; -export const GET_ROAD_ITEM = api + "/api/v3/road_item_reports/show_on_map"; -export const GET_PROVINCE_ACTIVITY_PER_ITEM = api + "/api/v3/road_item_reports/country_activity_per_item"; -export const GET_CITY_ACTIVITY_PER_ITEM = api + "/api/v3/road_item_reports/province_activity_per_item"; -export const GET_PROVINCE_ACTIVITY_PER_SUB_ITEM = api + "/api/v3/road_item_reports/country_activity_per_sub_item"; -export const GET_CITY_ACTIVITY_PER_SUB_ITEM = api + "/api/v3/road_item_reports/province_activity_per_sub_item"; -export const GET_IMAGES_ROAD_ITEM = api + "/api/v3/road_items/files"; -export const GET_CMMS_MACHINE_ROAD_ITEM = api + "/api/v3/road_items/machines"; -export const GET_RAHDARAN_ROAD_ITEM = api + "/api/v3/road_items/rahdaran"; - -// damage items -export const GET_RECEIPT_DAMAGE_ITEMS_LIST = api + "/api/v3/damages"; -export const CREATE_RECEIPT_DAMAGE_ITEMS = api + "/api/v3/damages"; -export const UPDATE_RECEIPT_DAMAGE_ITEMS = api + "/api/v3/damages"; -export const ATIVITY_RECEIPT_DAMAGE_ITEMS = api + "/api/v3/damages/activate"; - -// damage receipt -export const GET_TECHNICAL_DAMAGE_OPERATOR_LIST = api + "/api/v3/receipts"; -export const CREATE_DAMAGE = api + "/api/v3/receipts"; -export const GET_DAMAGE_ITEM_LIST = api + "/api/v3/damages/list"; -export const DELETE_DAMAGE_ITEM = api + "/api/v3/receipts"; -export const CREATE_FACTOR_DAMAGE = api + "/api/v3/receipts/submit_invoice"; -export const CONFIRM_PAYMENT_INFO = api + "/api/v3/receipts/confirm_payment_info"; -export const CHECK_PAYMENT_STATUS = api + "/api/v3/receipts/check_payment_status"; -export const SEND_SMS_AGAIN = api + "/api/v3/receipts/send_sms_again"; -export const EXPORT_DAMAGES_OPERATOR_LIST = api + "/api/v3/receipts/excel_report"; -export const GET_DAMAGE_ITEM_DETAILS = api + "/api/v3/receipts"; -export const UPDATE_DAMAGE_ITEM = api + "/api/v3/receipts"; -export const GET_INSURANCE = api + "/api/v3/receipts/generate_insurance_letter"; -export const GET_INSURANCE_PAGE = api + "/v2/receipt/send-to-insurance"; -export const GET_POLICERAH = api + "/api/v3/receipts/generate_police_document"; -export const GET_POLICERAH_PAGE = api + "/v2/receipt/document-release"; - -// recept report -export const GET_COUNTRY_RECEIPT_REPORT = api + "/api/v3/receipt_reports/country_report"; -export const GET_PROVINCE_RECEIPT_REPORT = api + "/api/v3/receipt_reports/province_report"; -export const EXPORT_COUNTRY_RECEIPT_REPORT = api + "/api/v3/receipt_reports/country_excel_report"; -export const EXPORT_PROVINCE_RECEIPT_REPORT = api + "/api/v3/receipt_reports/province_excel_report"; - -// activity code log -export const ACTIVITY_LOG = api + "/api/v3/profile/add_activity"; - -// fast react -export const GET_FAST_REACT_SUPERVISOR = api + "/api/v3/road_observations/supervisor/index"; -export const GET_FAST_REACT_COMPLAINTS = api + "/api/v3/road_observations/complaints_index"; -export const VERIFY_BY_FAST_REACT_SUPERVISOR = api + "/api/v3/road_observations/supervisor/verify"; -export const REJECT_BY_FAST_REACT_SUPERVISOR = api + "/api/v3/road_observations/supervisor/verify"; -export const REGISTER_COMPLAINTS_LIST = api + "/api/v3/road_observations/operator/register"; -export const GET_FAST_REACT_OPERATOR = api + "/api/v3/road_observations/operator/cartable"; -export const GET_FAST_REACT_REFER_LIST = api + "/api/v3/road_observations/refer_list"; -export const REFER_FAST_REACT = api + "/api/v3/road_observations/refer"; -export const RESTORE_FAST_REACT = api + "/api/v3/road_observations/supervisor/restore"; -export const GET_FAST_REACT_ITEM_DETAIL = api + "/api/v3/road_observations"; -export const UPDATE_FAST_REACT = api + "/api/v3/road_observations/operator/modify_registration"; -export const EXPORT_FAST_REACT_SUPERVISOR_LIST = api + "/api/v3/road_observations/supervisor/report"; -export const EXPORT_FAST_REACT_OPERATOR_LIST = api + "/api/v3/road_observations/operator/report"; -export const EXPORT_FAST_REACT_COMPLAINT_LIST = api + "/api/v3/road_observations/complaints_report"; - -// road safety -export const GET_SAFETY_AND_PRIVACY_OPERATOR = api + "/api/v3/safety_and_privacy/operator"; -export const DELETE_SAFETY_AND_PRIVACY = api + "/api/v3/safety_and_privacy/operator"; -export const FIRST_STEP_STORE = api + "/api/v3/safety_and_privacy/operator/first_step_store"; -export const SECOND_STEP_STORE = api + "/api/v3/safety_and_privacy/operator/second_step_store"; -export const THIRD_STEP_STORE = api + "/api/v3/safety_and_privacy/operator/third_step_store"; -export const UPDATE_SAFETY_AND_PRIVACY = api + "/api/v3/safety_and_privacy/operator"; -export const FINISH_ROAD_SAFETY_BY_SUPERVISOR = api + "/api/v3/safety_and_privacy/operator/finish"; -export const EXPORT_OPERATOR_ROAD_SAFETY = api + "/api/v3/safety_and_privacy/operator/excel_report"; - -export const GET_SAFETY_AND_PRIVACY_SUPERVISOR = api + "/api/v3/safety_and_privacy/supervisor"; -export const EXPORT_SUPERVISOR_ROAD_SAFETY = api + "/api/v3/safety_and_privacy/supervisor/excel_report"; -export const CONFIRM_ROAD_SAFETY_BY_SUPERVISOR = api + "/api/v3/safety_and_privacy/supervisor/confirm"; -export const REJECT_ROAD_SAFETY_BY_SUPERVISOR = api + "/api/v3/safety_and_privacy/supervisor/reject"; - -export const DESERIALIZE_JUDICIARY_DOCUMENT = api + "/api/v3/safety_and_privacy/deserialize"; -export const GET_SAFETY_AND_PRIVACY_ITEM = api + "/api/v3/safety_and_privacy/sub_items"; -export const GET_ROAD_SAFETY_PROVINCE_ACTIVITY_REPORT = - api + "/api/v3/safety_and_privacy_report/operator/country_activity"; -export const GET_ROAD_SAFETY_CITY_ACTIVITY_REPORT = - api + "/api/v3/safety_and_privacy_report/operator/province_activity"; -export const GET_ROAD_SAFETY_REPORT_MAP = api + "/api/v3/safety_and_privacy/map"; -export const GET_ROAD_SAFETY_DETAILS = api + "/api/v3/safety_and_privacy/operator"; -export const EXPORT_COUNTRY_ROAD_SAFETY_REPORT = - api + "/api/v3/safety_and_privacy_report/operator/country_excel_activity"; -export const EXPORT_PROVINCE_ROAD_SAFETY_REPORT = - api + "/api/v3/safety_and_privacy_report/operator/province_excel_activity"; - -// permission table -export const GET_PERMISSION_TABLE_LIST = api + "/api/v3/permissions"; -export const DELETE_PERMISSION = api + "/api/v3/permissions"; -export const UPDATE_PERMISSION = api + "/api/v3/permissions"; -export const CREATE_PERMISSION = api + "/api/v3/permissions"; - -// user activities -export const GET_USER_ACTIVITIES_LIST = api + "/api/v3/log_list"; -export const CREATE_USER_ACTIVITY = api + "/api/v3/log_list"; -export const UPDATE_USER_ACTIVITY = api + "/api/v3/log_list"; -export const DELETE_USER_ACTIVITIES = api + "/api/v3/log_list"; - -// toll-house -export const GET_TOLL_HOUSE_LIST = api + "/api/v3/road_maintenance_station"; -export const CREATE_TOLL_HOUSE = api + "/api/v3/road_maintenance_station"; -export const GET_TOLL_HOUSE_DETAILS = api + "/api/v3/road_maintenance_station"; -export const DELETE_TOLL_HOUSE_ITEM = api + "/api/v3/road_maintenance_station"; -export const UPDATE_TOLL_HOUSE_ITEM = api + "/api/v3/road_maintenance_station"; -export const GET_TOLL_HOUSE_IMAGES = api + "/api/v3/road_maintenance_station/images"; +const api = process.env.NEXT_PUBLIC_API_URL; + +export const GET_USER_ROUTE = api + "/api/v3/profile/info"; +export const LOGOUT_USER_ROUTE = api + "/api/v3/logout"; +export const UPDATE_USER_ROUTE = api + "/api/v3/profile/edit"; +export const CHANGE_USER_PASSWORD = api + "/api/v3/profile/change_password"; +export const GET_LOGIN_ROUTE = api + "/login_dev"; +export const GET_PERMISSIONS_ROUTE = api + "/webapi/user/get-permission"; +export const GET_SIDEBAR_BADGE_ROUTE = api + "/api/v3/notifications"; +export const REFER_ADMIN_PROVINCE = "/v3/api/fake-submit"; +export const REFER_ADMIN_CITY = "/v3/api/fake-submit"; +export const GET_CITY_LISTS = api + "/public/contents/provinces"; +export const GET_PROVINCE_LISTS = api + "/public/contents/provinces"; +export const GET_PREV_STATE_OPINION = "/v3/api/fake-prev-state-opinion"; +export const SUBMIT_ROAD_SAFETY_FORM = "/v3/api/fake-submit"; +export const CREATE_AZMAYESH = api + "/api/v3/azmayeshes/store"; +export const UPDATE_AZMAYESH = api + "/api/v3/azmayeshes/update"; +export const GET_AZMAYESH_TYPE_LIST = api + "/api/v3/azmayesh_types/list"; +export const GET_AZMAYESH_TYPE_LIST_TABLE = api + "/api/v3/azmayesh_types"; +export const GET_AZMAYESH_LIST = api + "/api/v3/azmayeshes"; +export const DELETE_AZMAYESH = api + "/api/v3/azmayeshes/delete"; +export const GET_AZMAYESH_SAMPLE_FIELDS = api + "/api/v3/azmayesh_types/fields"; +export const ADD_SAMPLE_TO_AZMAYESH = api + "/api/v3/azmayesh_samples/store"; +export const UPDATE_SAMPLE_OF_AZMAYESH = api + "/api/v3/azmayesh_samples/update"; +export const GET_SAMPLE_LIST = api + "/api/v3/azmayesh_samples"; +export const DELETE_SAMPLE_LIST = api + "/api/v3/azmayesh_samples/delete"; +export const DELETE_AZMAYESH_TYPE_LIST = api + "/api/v3/azmayesh_types/delete"; +export const ADD_AZMAYESH_TYPE = api + "/api/v3/azmayesh_types/store"; +export const UPDATE_AZMAYESH_TYPE = api + "/api/v3/azmayesh_types/update"; + +//road patrol +export const GET_ROAD_PATROL_OPERATOR_LIST = api + "/api/v3/road_patrols/operator_index"; +export const EXPORT_ROAD_PATROL_OPERATOR_LIST = api + "/api/v3/road_patrols/operator_report"; +export const GET_ROAD_PATROL_SUPERVISOR_LIST = api + "/api/v3/road_patrols/supervisor_index"; +export const EXPORT_ROAD_PATROL_SUPERVISOR_LIST = api + "/api/v3/road_patrols/supervisor_report"; +export const EXPORT_PROVINCE_ROAD_PATROL_REPORTS = api + "/api/v3/road_patrol_reports/province_activity_excel"; +export const EXPORT_COUNTRY_ROAD_PATROL_REPORTS = api + "/api/v3/road_patrol_reports/country_activity_excel"; +export const DELETE_ROAD_PATROL_SUPERVISOR = api + "/api/v3/road_patrols/delete"; +export const GET_CMMS_MACHINE_ROAD_PATROL = api + "/api/v3/road_patrols/machines"; +export const GET_ROAD_PATROL_OPERATOR_REPORT = api + "/v2/road_patrols/operator/report"; +export const GET_ROAD_PATROL_SUPERVISOR_REPORT = api + "/v2/road_patrols/operator/report"; +export const GET_RAHDARAN_ROAD_POTROL = api + "/api/v3/road_patrols/rahdaran"; +export const CREATE_PATROL = api + "/api/v3/road_patrols/store"; +export const GET_FMS_DATA = api + "/api/v3/fms_vehicle/get_activity"; +export const GET_OTP_TOKEN = api + "/api/v3/otp/get_token"; +export const GET_PROVINCE_ACTIVITY_REPORT = api + "/api/v3/road_patrol_reports/country_activity"; +export const GET_CITY_ACTIVITY_REPORT = api + "/api/v3/road_patrol_reports/province_activity"; + +// road items +export const GET_ROAD_ITEMS_SUPERVISOR_LIST = api + "/api/v3/road_items/supervisor_index"; +export const EXPORT_ROAD_ITEMS_SUPERVISOR_LIST = api + "/api/v3/road_items/supervisor_report"; +export const GET_ROAD_ITEMS_OPERATOR_LIST = api + "/api/v3/road_items/operator_index"; +export const EXPORT_ROAD_ITEMS_OPERATOR_LIST = api + "/api/v3/road_items/operator_report"; +export const EXPORT_PROVINCE_ROAD_ITEM_REPORTS_PER_ITEM = + api + "/api/v3/road_item_reports/province_activity_excel_per_item"; +export const EXPORT_COUNTRY_ROAD_ITEM_REPORTS_PER_ITEM = + api + "/api/v3/road_item_reports/country_activity_excel_per_item"; +export const EXPORT_PROVINCE_ROAD_ITEM_REPORTS_PER_SUB_ITEM = + api + "/api/v3/road_item_reports/province_activity_excel_per_sub_item"; +export const EXPORT_COUNTRY_ROAD_ITEM_REPORTS_PER_SUB_ITEM = + api + "/api/v3/road_item_reports/country_activity_excel_per_sub_item"; +export const GET_ROAD_ITEMS_ITEM = api + "/api/v3/items"; +export const GET_ROAD_ITEMS_SUB_ITEM = api + "/api/v3/sub_items"; +export const GET_EDARAT_LISTS = api + "/public/contents/edarate_shahri_by_province"; +export const CREATE_ROAD_ITEMS = api + "/api/v3/road_items/store"; +export const UPDATE_ROAD_ITEMS = api + "/api/v3/road_items/update"; +export const VERIFY_BY_SUPERVISOR = api + "/api/v3/road_items/verify_by_supervisor"; +export const REJECT_BY_SUPERVISOR = api + "/api/v3/road_items/verify_by_supervisor"; +export const DELETE_BY_SUPERVISOR = api + "/api/v3/road_items/delete"; +export const RESTORE_BY_SUPERVISOR = api + "/api/v3/road_items/restore"; +export const GET_CAR_LIST_SEARCH = api + "/api/v3/cmms_machines/search"; +export const GET_RAHDARANS_LIST_SEARCH = api + "/api/v3/rahdaran/search"; +export const GET_OBSERVED_GASHT_LIST = api + "/api/v3/observed_items/filter"; +export const GET_ROAD_ITEMS_REPORT_MAP = api + "/api/v3/road_item_reports/activities_on_map"; +export const GET_ROAD_ITEM = api + "/api/v3/road_item_reports/show_on_map"; +export const GET_PROVINCE_ACTIVITY_PER_ITEM = api + "/api/v3/road_item_reports/country_activity_per_item"; +export const GET_CITY_ACTIVITY_PER_ITEM = api + "/api/v3/road_item_reports/province_activity_per_item"; +export const GET_PROVINCE_ACTIVITY_PER_SUB_ITEM = api + "/api/v3/road_item_reports/country_activity_per_sub_item"; +export const GET_CITY_ACTIVITY_PER_SUB_ITEM = api + "/api/v3/road_item_reports/province_activity_per_sub_item"; +export const GET_IMAGES_ROAD_ITEM = api + "/api/v3/road_items/files"; +export const GET_CMMS_MACHINE_ROAD_ITEM = api + "/api/v3/road_items/machines"; +export const GET_RAHDARAN_ROAD_ITEM = api + "/api/v3/road_items/rahdaran"; + +// damage items +export const GET_RECEIPT_DAMAGE_ITEMS_LIST = api + "/api/v3/damages"; +export const CREATE_RECEIPT_DAMAGE_ITEMS = api + "/api/v3/damages"; +export const UPDATE_RECEIPT_DAMAGE_ITEMS = api + "/api/v3/damages"; +export const ATIVITY_RECEIPT_DAMAGE_ITEMS = api + "/api/v3/damages/activate"; + +// damage receipt +export const GET_TECHNICAL_DAMAGE_OPERATOR_LIST = api + "/api/v3/receipts"; +export const CREATE_DAMAGE = api + "/api/v3/receipts"; +export const GET_DAMAGE_ITEM_LIST = api + "/api/v3/damages/list"; +export const DELETE_DAMAGE_ITEM = api + "/api/v3/receipts"; +export const CREATE_FACTOR_DAMAGE = api + "/api/v3/receipts/submit_invoice"; +export const CONFIRM_PAYMENT_INFO = api + "/api/v3/receipts/confirm_payment_info"; +export const CHECK_PAYMENT_STATUS = api + "/api/v3/receipts/check_payment_status"; +export const SEND_SMS_AGAIN = api + "/api/v3/receipts/send_sms_again"; +export const EXPORT_DAMAGES_OPERATOR_LIST = api + "/api/v3/receipts/excel_report"; +export const GET_DAMAGE_ITEM_DETAILS = api + "/api/v3/receipts"; +export const UPDATE_DAMAGE_ITEM = api + "/api/v3/receipts"; +export const GET_INSURANCE = api + "/api/v3/receipts/generate_insurance_letter"; +export const GET_INSURANCE_PAGE = api + "/v2/receipt/send-to-insurance"; +export const GET_POLICERAH = api + "/api/v3/receipts/generate_police_document"; +export const GET_POLICERAH_PAGE = api + "/v2/receipt/document-release"; + +// recept report +export const GET_COUNTRY_RECEIPT_REPORT = api + "/api/v3/receipt_reports/country_report"; +export const GET_PROVINCE_RECEIPT_REPORT = api + "/api/v3/receipt_reports/province_report"; +export const EXPORT_COUNTRY_RECEIPT_REPORT = api + "/api/v3/receipt_reports/country_excel_report"; +export const EXPORT_PROVINCE_RECEIPT_REPORT = api + "/api/v3/receipt_reports/province_excel_report"; + +// activity code log +export const ACTIVITY_LOG = api + "/api/v3/profile/add_activity"; + +// fast react +export const GET_FAST_REACT_SUPERVISOR = api + "/api/v3/road_observations/supervisor/index"; +export const GET_FAST_REACT_COMPLAINTS = api + "/api/v3/road_observations/complaints_index"; +export const VERIFY_BY_FAST_REACT_SUPERVISOR = api + "/api/v3/road_observations/supervisor/verify"; +export const REJECT_BY_FAST_REACT_SUPERVISOR = api + "/api/v3/road_observations/supervisor/verify"; +export const REGISTER_COMPLAINTS_LIST = api + "/api/v3/road_observations/operator/register"; +export const GET_FAST_REACT_OPERATOR = api + "/api/v3/road_observations/operator/cartable"; +export const GET_FAST_REACT_REFER_LIST = api + "/api/v3/road_observations/refer_list"; +export const REFER_FAST_REACT = api + "/api/v3/road_observations/refer"; +export const RESTORE_FAST_REACT = api + "/api/v3/road_observations/supervisor/restore"; +export const GET_FAST_REACT_ITEM_DETAIL = api + "/api/v3/road_observations"; +export const UPDATE_FAST_REACT = api + "/api/v3/road_observations/operator/modify_registration"; +export const EXPORT_FAST_REACT_SUPERVISOR_LIST = api + "/api/v3/road_observations/supervisor/report"; +export const EXPORT_FAST_REACT_OPERATOR_LIST = api + "/api/v3/road_observations/operator/report"; +export const EXPORT_FAST_REACT_COMPLAINT_LIST = api + "/api/v3/road_observations/complaints_report"; + +// road safety +export const GET_SAFETY_AND_PRIVACY_OPERATOR = api + "/api/v3/safety_and_privacy/operator"; +export const DELETE_SAFETY_AND_PRIVACY = api + "/api/v3/safety_and_privacy/operator"; +export const FIRST_STEP_STORE = api + "/api/v3/safety_and_privacy/operator/first_step_store"; +export const SECOND_STEP_STORE = api + "/api/v3/safety_and_privacy/operator/second_step_store"; +export const THIRD_STEP_STORE = api + "/api/v3/safety_and_privacy/operator/third_step_store"; +export const UPDATE_SAFETY_AND_PRIVACY = api + "/api/v3/safety_and_privacy/operator"; +export const FINISH_ROAD_SAFETY_BY_SUPERVISOR = api + "/api/v3/safety_and_privacy/operator/finish"; +export const EXPORT_OPERATOR_ROAD_SAFETY = api + "/api/v3/safety_and_privacy/operator/excel_report"; + +export const GET_SAFETY_AND_PRIVACY_SUPERVISOR = api + "/api/v3/safety_and_privacy/supervisor"; +export const EXPORT_SUPERVISOR_ROAD_SAFETY = api + "/api/v3/safety_and_privacy/supervisor/excel_report"; +export const CONFIRM_ROAD_SAFETY_BY_SUPERVISOR = api + "/api/v3/safety_and_privacy/supervisor/confirm"; +export const REJECT_ROAD_SAFETY_BY_SUPERVISOR = api + "/api/v3/safety_and_privacy/supervisor/reject"; + +export const DESERIALIZE_JUDICIARY_DOCUMENT = api + "/api/v3/safety_and_privacy/deserialize"; +export const GET_SAFETY_AND_PRIVACY_ITEM = api + "/api/v3/safety_and_privacy/sub_items"; +export const GET_ROAD_SAFETY_PROVINCE_ACTIVITY_REPORT = + api + "/api/v3/safety_and_privacy_report/operator/country_activity"; +export const GET_ROAD_SAFETY_CITY_ACTIVITY_REPORT = + api + "/api/v3/safety_and_privacy_report/operator/province_activity"; +export const GET_ROAD_SAFETY_REPORT_MAP = api + "/api/v3/safety_and_privacy/map"; +export const GET_ROAD_SAFETY_DETAILS = api + "/api/v3/safety_and_privacy/operator"; +export const EXPORT_COUNTRY_ROAD_SAFETY_REPORT = + api + "/api/v3/safety_and_privacy_report/operator/country_excel_activity"; +export const EXPORT_PROVINCE_ROAD_SAFETY_REPORT = + api + "/api/v3/safety_and_privacy_report/operator/province_excel_activity"; + +// permission table +export const GET_PERMISSION_TABLE_LIST = api + "/api/v3/permissions"; +export const DELETE_PERMISSION = api + "/api/v3/permissions"; +export const UPDATE_PERMISSION = api + "/api/v3/permissions"; +export const CREATE_PERMISSION = api + "/api/v3/permissions"; + +// user activities +export const GET_USER_ACTIVITIES_LIST = api + "/api/v3/log_list"; +export const CREATE_USER_ACTIVITY = api + "/api/v3/log_list"; +export const UPDATE_USER_ACTIVITY = api + "/api/v3/log_list"; +export const DELETE_USER_ACTIVITIES = api + "/api/v3/log_list"; + +// toll-house +export const GET_TOLL_HOUSE_LIST = api + "/api/v3/road_maintenance_station"; +export const CREATE_TOLL_HOUSE = api + "/api/v3/road_maintenance_station"; +export const GET_TOLL_HOUSE_DETAILS = api + "/api/v3/road_maintenance_station"; +export const DELETE_TOLL_HOUSE_ITEM = api + "/api/v3/road_maintenance_station"; +export const UPDATE_TOLL_HOUSE_ITEM = api + "/api/v3/road_maintenance_station"; +export const GET_TOLL_HOUSE_IMAGES = api + "/api/v3/road_maintenance_station/images"; + +// road missions +export const GET_ROAD_MISSIONS_OPERATOR_LIST = api + "/api/v3/missions/request_portal"; +export const GET_ROAD_MISSIONS_TRANSPORTATION_LIST = api + "/api/v3/missions/transportation_unit"; +export const GET_ROAD_MISSIONS_CONTROL_LIST = api + "/api/v3/missions/control_unit"; +export const REQUEST_MISSION = api + "/api/v3/missions/request_portal"; +export const UPDATE_REQUEST_MISSION = api + "/api/v3/missions/request_portal"; +export const DELETE_REQUEST_MISSION = api + "/api/v3/missions/request_portal"; +export const GET_RAHDARAN_BY_ID = api + "/api/v3/missions/details/rahdaran"; +export const ALLOCATE_REQUEST_MISSION = api + "/api/v3/missions/transportation_unit/allocate"; +export const DEALLOCATE_REQUEST_MISSION = api + "/api/v3/missions/transportation_unit/deallocate"; +export const START_MISSION = api + "/api/v3/missions/control_unit/start"; +export const FINISH_MISSION = api + "/api/v3/missions/control_unit/finish"; + +export const GET_MACHINES_TABLE_LIST = api + "/api/v3/cmms_machines"; diff --git a/src/core/utils/successRequest.js b/src/core/utils/successRequest.js index 7fbde71..9c34c44 100644 --- a/src/core/utils/successRequest.js +++ b/src/core/utils/successRequest.js @@ -1,10 +1,10 @@ -"use client"; -import { toast } from "react-toastify"; -import { successToast } from "@/core/components/Toasts/success"; - -export const successRequest = (notification, toastContainer) => { - if (notification) { - toast.dismiss({ containerId: toastContainer }); - successToast(toastContainer); - } -}; +"use client"; +import { toast } from "react-toastify"; +import { successToast } from "@/core/components/Toasts/success"; + +export const successRequest = (notification, toastContainer) => { + if (notification) { + toast.dismiss({ containerId: toastContainer }); + successToast(toastContainer); + } +}; diff --git a/src/core/utils/theme.js b/src/core/utils/theme.js index 21a3056..ec341a2 100644 --- a/src/core/utils/theme.js +++ b/src/core/utils/theme.js @@ -1,36 +1,36 @@ -"use client"; -import { createTheme } from "@mui/material"; -import { grey } from "@mui/material/colors"; - -const theme = createTheme({ - direction: "rtl", - typography: { - fontFamily: `IRANSansFaNum, sans-serif`, - fontSize: 12, - }, - palette: { - primary: { - main: "#2070af", - contrastText: "#fff", - }, - primary2: { - main: "#015688", - contrastText: "#fff", - }, - secondary: { - main: grey[700], - }, - }, - components: { - MuiBackdrop: { - styleOverrides: { - root: { - backdropFilter: "blur(2px)", - backgroundColor: "rgba(0, 0, 0, 0.5)", - }, - }, - }, - }, -}); - -export default theme; +"use client"; +import { createTheme } from "@mui/material"; +import { grey } from "@mui/material/colors"; + +const theme = createTheme({ + direction: "rtl", + typography: { + fontFamily: `IRANSansFaNum, sans-serif`, + fontSize: 12, + }, + palette: { + primary: { + main: "#2070af", + contrastText: "#fff", + }, + primary2: { + main: "#015688", + contrastText: "#fff", + }, + secondary: { + main: grey[700], + }, + }, + components: { + MuiBackdrop: { + styleOverrides: { + root: { + backdropFilter: "blur(2px)", + backgroundColor: "rgba(0, 0, 0, 0.5)", + }, + }, + }, + }, +}); + +export default theme; diff --git a/src/core/utils/utils.js b/src/core/utils/utils.js index a0a320d..eec2824 100644 --- a/src/core/utils/utils.js +++ b/src/core/utils/utils.js @@ -1,120 +1,150 @@ -import { alpha, darken } from "@mui/material"; - -export const parseCSSVarId = (id) => id.replace(/[^a-zA-Z0-9]/g, "_"); - -export const parseFromValuesOrFunc = (fn, arg) => (fn instanceof Function ? fn(arg) : fn); - -export const getCommonToolbarStyles = ({ table }) => ({ - alignItems: "flex-start", - backgroundColor: table.options.mrtTheme.baseBackgroundColor, - display: "grid", - flexWrap: "wrap-reverse", - minHeight: "3.5rem", - overflow: "hidden", - position: "relative", - transition: "all 150ms ease-in-out", - zIndex: 1, -}); - -export const getCommonTooltipProps = (placement) => ({ - disableInteractive: true, - enterDelay: 500, - enterNextDelay: 500, - placement, -}); - -export const flipIconStyles = (theme) => - theme.direction === "rtl" ? { style: { transform: "scaleX(-1)" } } : undefined; - -export const getCommonPinnedCellStyles = ({ column, table, theme }) => { - const { baseBackgroundColor } = table.options.mrtTheme; - const isPinned = column?.getIsPinned(); - - return { - '&[data-pinned="true"]': { - "&:before": { - backgroundColor: alpha(darken(baseBackgroundColor, theme.palette.mode === "dark" ? 0.05 : 0.01), 0.97), - boxShadow: column - ? isPinned === "left" && column.getIsLastColumn(isPinned) - ? `-4px 0 4px -4px ${alpha(theme.palette.grey[700], 0.5)} inset` - : isPinned === "right" && column.getIsFirstColumn(isPinned) - ? `4px 0 4px -4px ${alpha(theme.palette.grey[700], 0.5)} inset` - : undefined - : undefined, - ...commonCellBeforeAfterStyles, - }, - }, - }; -}; - -export const getCommonMRTCellStyles = ({ column, header, table, tableCellProps, theme }) => { - const { - getState, - options: { enableColumnVirtualization, layoutMode }, - } = table; - const { draggingColumn } = getState(); - const { columnDef } = column; - const { columnDefType } = columnDef; - - const isColumnPinned = columnDef.columnDefType !== "group" && column.getIsPinned(); - - const widthStyles = { - minWidth: `max(calc(var(--${header ? "header" : "col"}-${parseCSSVarId( - header?.id ?? column.id - )}-size) * 1px), ${columnDef.minSize ?? 30}px)`, - width: `calc(var(--${header ? "header" : "col"}-${parseCSSVarId(header?.id ?? column.id)}-size) * 1px)`, - }; - - if (layoutMode === "grid") { - widthStyles.flex = `${ - [0, false].includes(columnDef.grow) - ? 0 - : `var(--${header ? "header" : "col"}-${parseCSSVarId(header?.id ?? column.id)}-size)` - } 0 auto`; - } else if (layoutMode === "grid-no-grow") { - widthStyles.flex = `${+(columnDef.grow || 0)} 0 auto`; - } - - const pinnedStyles = isColumnPinned - ? { - ...getCommonPinnedCellStyles({ column, table, theme }), - left: isColumnPinned === "left" ? `${column.getStart("left")}px` : undefined, - opacity: 0.97, - position: "sticky", - right: isColumnPinned === "right" ? `${column.getAfter("right")}px` : undefined, - } - : {}; - - return { - backgroundColor: "inherit", - backgroundImage: "inherit", - display: layoutMode?.startsWith("grid") ? "flex" : undefined, - justifyContent: - columnDefType === "group" ? "center" : layoutMode?.startsWith("grid") ? tableCellProps.align : undefined, - opacity: - table.getState().draggingColumn?.id === column.id || table.getState().hoveredColumn?.id === column.id - ? 0.5 - : 1, - position: "relative", - transition: enableColumnVirtualization ? "none" : `padding 150ms ease-in-out`, - zIndex: - column.getIsResizing() || draggingColumn?.id === column.id - ? 2 - : columnDefType !== "group" && isColumnPinned - ? 1 - : 0, - ...pinnedStyles, - ...widthStyles, - ...parseFromValuesOrFunc(tableCellProps?.sx, theme), - }; -}; - -export const commonCellBeforeAfterStyles = { - content: '""', - height: "100%", - left: 0, - position: "absolute", - top: 0, - width: "100%", - zIndex: -1, -}; +import { alpha, darken } from "@mui/material"; + +export const parseCSSVarId = (id) => id.replace(/[^a-zA-Z0-9]/g, "_"); + +export const parseFromValuesOrFunc = (fn, arg) => (fn instanceof Function ? fn(arg) : fn); + +export const getCommonToolbarStyles = ({ table }) => ({ + alignItems: "flex-start", + backgroundColor: table.options.mrtTheme.baseBackgroundColor, + display: "grid", + flexWrap: "wrap-reverse", + minHeight: "3.5rem", + overflow: "hidden", + position: "relative", + transition: "all 150ms ease-in-out", + zIndex: 1, +}); + +export const getCommonTooltipProps = (placement) => ({ + disableInteractive: true, + enterDelay: 500, + enterNextDelay: 500, + placement, +}); + +export const flipIconStyles = (theme) => + theme.direction === "rtl" ? { style: { transform: "scaleX(-1)" } } : undefined; + +export const getCommonPinnedCellStyles = ({ column, table, theme }) => { + const { baseBackgroundColor } = table.options.mrtTheme; + const isPinned = column?.getIsPinned(); + + return { + '&[data-pinned="true"]': { + "&:before": { + backgroundColor: alpha(darken(baseBackgroundColor, theme.palette.mode === "dark" ? 0.05 : 0.01), 0.97), + boxShadow: column + ? isPinned === "left" && column.getIsLastColumn(isPinned) + ? `-4px 0 4px -4px ${alpha(theme.palette.grey[700], 0.5)} inset` + : isPinned === "right" && column.getIsFirstColumn(isPinned) + ? `4px 0 4px -4px ${alpha(theme.palette.grey[700], 0.5)} inset` + : undefined + : undefined, + ...commonCellBeforeAfterStyles, + }, + }, + }; +}; + +export const getCommonMRTCellStyles = ({ column, header, table, tableCellProps, theme }) => { + const { + getState, + options: { enableColumnVirtualization, layoutMode }, + } = table; + const { draggingColumn } = getState(); + const { columnDef } = column; + const { columnDefType } = columnDef; + + const isColumnPinned = columnDef.columnDefType !== "group" && column.getIsPinned(); + + const widthStyles = { + minWidth: `max(calc(var(--${header ? "header" : "col"}-${parseCSSVarId( + header?.id ?? column.id + )}-size) * 1px), ${columnDef.minSize ?? 30}px)`, + width: `calc(var(--${header ? "header" : "col"}-${parseCSSVarId(header?.id ?? column.id)}-size) * 1px)`, + }; + + if (layoutMode === "grid") { + widthStyles.flex = `${ + [0, false].includes(columnDef.grow) + ? 0 + : `var(--${header ? "header" : "col"}-${parseCSSVarId(header?.id ?? column.id)}-size)` + } 0 auto`; + } else if (layoutMode === "grid-no-grow") { + widthStyles.flex = `${+(columnDef.grow || 0)} 0 auto`; + } + + const pinnedStyles = isColumnPinned + ? { + ...getCommonPinnedCellStyles({ column, table, theme }), + left: isColumnPinned === "left" ? `${column.getStart("left")}px` : undefined, + opacity: 0.97, + position: "sticky", + right: isColumnPinned === "right" ? `${column.getAfter("right")}px` : undefined, + } + : {}; + + return { + backgroundColor: "inherit", + backgroundImage: "inherit", + display: layoutMode?.startsWith("grid") ? "flex" : undefined, + justifyContent: + columnDefType === "group" ? "center" : layoutMode?.startsWith("grid") ? tableCellProps.align : undefined, + opacity: + table.getState().draggingColumn?.id === column.id || table.getState().hoveredColumn?.id === column.id + ? 0.5 + : 1, + position: "relative", + transition: enableColumnVirtualization ? "none" : `padding 150ms ease-in-out`, + zIndex: + column.getIsResizing() || draggingColumn?.id === column.id + ? 2 + : columnDefType !== "group" && isColumnPinned + ? 1 + : 0, + ...pinnedStyles, + ...widthStyles, + ...parseFromValuesOrFunc(tableCellProps?.sx, theme), + }; +}; + +export const commonCellBeforeAfterStyles = { + content: '""', + height: "100%", + left: 0, + position: "absolute", + top: 0, + width: "100%", + zIndex: -1, +}; + +function closePolygonIfNeeded(coords) { + if ( + coords.length > 0 && + (coords[0][0] !== coords[coords.length - 1][0] || coords[0][1] !== coords[coords.length - 1][1]) + ) { + coords.push(coords[0]); + } + return coords; +} + +export const getClosedPolygonCoordinates = (polygon) => { + const latLngs = polygon.getLatLngs(); + + // گرفتن حلقه اصلی (فرض بر این است که فقط یک ring وجود دارد) + const ring = Array.isArray(latLngs[0]) ? latLngs[0] : latLngs; + + // تبدیل به آرایه ساده [lat, lng] + const coordinates = ring.map((point) => [point.lat, point.lng]); + + // بررسی بسته بودن حلقه + const first = coordinates[0]; + const last = coordinates[coordinates.length - 1]; + + if (first[0] !== last[0] || first[1] !== last[1]) { + coordinates.push(first); // بستن حلقه + } + + return coordinates; +}; diff --git a/src/lib/contexts/DataTable.js b/src/lib/contexts/DataTable.js index 76f0f13..8409ba8 100644 --- a/src/lib/contexts/DataTable.js +++ b/src/lib/contexts/DataTable.js @@ -1,179 +1,179 @@ -import { createContext, useEffect, useState } from "react"; -import { toast } from "react-toastify"; -import useTableSetting from "@/lib/hooks/useTableSetting"; -import { flattenArrayOfObjects } from "@/core/utils/flattenArrayOfObjects"; -import AskForKeepData from "@/core/components/NotificationDesign/AskForKeepData"; -import { LinearProgress } from "@mui/material"; - -export const DataTableContext = createContext(); - -const DataTableProvider = ({ children, user_id, page_name, table_name, columns, initialSort = [] }) => { - const { settingStore } = useTableSetting(); - const [isInitStates, setInitStates] = useState(false); - const flatColumns = flattenArrayOfObjects(columns, "columns"); - const [initFilter, setInitFilter] = useState({}); - const [filterData, setFilterData] = useState({}); - const [initSort, setInitSort] = useState(initialSort || []); - const [sortData, setSortData] = useState(initialSort || []); - const [initHide, setInitHide] = useState({}); - const [hideData, setHideData] = useState({}); - const [isDirty, setIsDirty] = useState(false); - const [isAnyDirty, setIsAnyDirty] = useState(false); - - useEffect(() => { - let hasAnyConflict = false; - const hasConflict = - JSON.stringify(hideData) !== JSON.stringify(initHide) || - JSON.stringify(sortData) !== JSON.stringify(initSort) || - JSON.stringify(filterData) !== JSON.stringify(initFilter); - - const CheckFilterValues = Object.values(filterData).every((innerObject) => { - if (innerObject.datatype === "date" && innerObject.filterMode === "between") { - return ( - Array.isArray(innerObject.value) && - innerObject.value.length === 2 && - innerObject.value.every((v) => v === "") - ); - } else { - return innerObject.value === ""; - } - }); - const flattenObject = (obj) => { - let result = {}; - for (const key in obj) { - if (typeof obj[key] === "object" && obj[key] !== null) { - Object.assign(result, flattenObject(obj[key])); // باز کردن اشیای تودرتو - } else { - result[key] = obj[key]; - } - } - return result; - }; - - // تبدیل آبجکت به آبجکت فلت شده - const flatHideData = flattenObject(hideData); - - const CheckHideValues = Object.values(flatHideData).every((value) => value === true); - hasAnyConflict = - !CheckHideValues || JSON.stringify(sortData) !== JSON.stringify(initialSort) || !CheckFilterValues; - - setIsDirty(hasConflict); - setIsAnyDirty(hasAnyConflict); - }, [hideData, sortData, filterData, initHide, initSort, initFilter]); - - useEffect(() => { - if (!settingStore) return; - const filterValues = flatColumns.reduce((acc, column) => { - if (!column.enableColumnFilter) return acc; - const storeFilter = settingStore?.[user_id]?.[page_name]?.[table_name]?.["filters"]?.find( - (filter) => filter.id === column.id - ); - if (column.datatype === "array") { - acc[column.id] = { - id: column.id, - value: storeFilter?.value || [], - filterMode: storeFilter?.filterMode || column.filterMode, - datatype: column.datatype, - }; - } else if (column.filterMode === "between") { - acc[column.id] = { - id: column.id, - value: storeFilter?.value || ["", ""], - filterMode: storeFilter?.filterMode || column.filterMode, - datatype: column.datatype, - }; - } else { - acc[column.id] = { - id: column.id, - value: storeFilter?.value || "", - filterMode: storeFilter?.filterMode || column.filterMode, - datatype: column.datatype, - }; - } - return acc; - }, {}); - - const getHideValues = (columns) => { - return columns.reduce((acc, column) => { - const columnId = column.id; - const storeHide = settingStore?.[user_id]?.[page_name]?.[table_name]?.["hides"]?.[columnId]; - if (column.columns && column.columns.length > 0) { - acc[columnId] = getHideValues(column.columns); - } else { - acc[columnId] = storeHide !== undefined ? storeHide : true; - } - - return acc; - }, {}); - }; - - const hideValues = getHideValues(columns); - setHideData(hideValues); - setInitHide(hideValues); - setFilterData(filterValues); - setInitFilter(filterValues); - setSortData(settingStore?.[user_id]?.[page_name]?.[table_name]?.["sorts"] || initialSort); - setInitSort(settingStore?.[user_id]?.[page_name]?.[table_name]?.["sorts"] || initialSort); - setInitStates(true); - }, [settingStore]); - - useEffect(() => { - if ( - JSON.stringify(initFilter) !== JSON.stringify(filterData) || - JSON.stringify(initSort) !== JSON.stringify(sortData) || - JSON.stringify(initHide) !== JSON.stringify(hideData) - ) { - if (!toast.isActive("keep_data", "filtering")) { - toast( - , - { - containerId: "filtering", - toastId: "keep_data", - className: "filter-toast", - position: "bottom-left", - draggable: true, - autoClose: false, - } - ); - } else { - toast.update("keep_data", { - containerId: "filtering", - toastId: "keep_data", - render: ( - - ), - }); - } - } else { - toast.dismiss({ containerId: "datatable" }); - } - }, [filterData, sortData, hideData]); - - if (!isInitStates) return ; - - return ( - - {children} - - ); -}; - -export default DataTableProvider; +import { createContext, useEffect, useState } from "react"; +import { toast } from "react-toastify"; +import useTableSetting from "@/lib/hooks/useTableSetting"; +import { flattenArrayOfObjects } from "@/core/utils/flattenArrayOfObjects"; +import AskForKeepData from "@/core/components/NotificationDesign/AskForKeepData"; +import { LinearProgress } from "@mui/material"; + +export const DataTableContext = createContext(); + +const DataTableProvider = ({ children, user_id, page_name, table_name, columns, initialSort = [] }) => { + const { settingStore } = useTableSetting(); + const [isInitStates, setInitStates] = useState(false); + const flatColumns = flattenArrayOfObjects(columns, "columns"); + const [initFilter, setInitFilter] = useState({}); + const [filterData, setFilterData] = useState({}); + const [initSort, setInitSort] = useState(initialSort || []); + const [sortData, setSortData] = useState(initialSort || []); + const [initHide, setInitHide] = useState({}); + const [hideData, setHideData] = useState({}); + const [isDirty, setIsDirty] = useState(false); + const [isAnyDirty, setIsAnyDirty] = useState(false); + + useEffect(() => { + let hasAnyConflict = false; + const hasConflict = + JSON.stringify(hideData) !== JSON.stringify(initHide) || + JSON.stringify(sortData) !== JSON.stringify(initSort) || + JSON.stringify(filterData) !== JSON.stringify(initFilter); + + const CheckFilterValues = Object.values(filterData).every((innerObject) => { + if (innerObject.datatype === "date" && innerObject.filterMode === "between") { + return ( + Array.isArray(innerObject.value) && + innerObject.value.length === 2 && + innerObject.value.every((v) => v === "") + ); + } else { + return innerObject.value === ""; + } + }); + const flattenObject = (obj) => { + let result = {}; + for (const key in obj) { + if (typeof obj[key] === "object" && obj[key] !== null) { + Object.assign(result, flattenObject(obj[key])); // باز کردن اشیای تودرتو + } else { + result[key] = obj[key]; + } + } + return result; + }; + + // تبدیل آبجکت به آبجکت فلت شده + const flatHideData = flattenObject(hideData); + + const CheckHideValues = Object.values(flatHideData).every((value) => value === true); + hasAnyConflict = + !CheckHideValues || JSON.stringify(sortData) !== JSON.stringify(initialSort) || !CheckFilterValues; + + setIsDirty(hasConflict); + setIsAnyDirty(hasAnyConflict); + }, [hideData, sortData, filterData, initHide, initSort, initFilter]); + + useEffect(() => { + if (!settingStore) return; + const filterValues = flatColumns.reduce((acc, column) => { + if (!column.enableColumnFilter) return acc; + const storeFilter = settingStore?.[user_id]?.[page_name]?.[table_name]?.["filters"]?.find( + (filter) => filter.id === column.id + ); + if (column.datatype === "array") { + acc[column.id] = { + id: column.id, + value: storeFilter?.value || [], + filterMode: storeFilter?.filterMode || column.filterMode, + datatype: column.datatype, + }; + } else if (column.filterMode === "between") { + acc[column.id] = { + id: column.id, + value: storeFilter?.value || ["", ""], + filterMode: storeFilter?.filterMode || column.filterMode, + datatype: column.datatype, + }; + } else { + acc[column.id] = { + id: column.id, + value: storeFilter?.value || "", + filterMode: storeFilter?.filterMode || column.filterMode, + datatype: column.datatype, + }; + } + return acc; + }, {}); + + const getHideValues = (columns) => { + return columns.reduce((acc, column) => { + const columnId = column.id; + const storeHide = settingStore?.[user_id]?.[page_name]?.[table_name]?.["hides"]?.[columnId]; + if (column.columns && column.columns.length > 0) { + acc[columnId] = getHideValues(column.columns); + } else { + acc[columnId] = storeHide !== undefined ? storeHide : true; + } + + return acc; + }, {}); + }; + + const hideValues = getHideValues(columns); + setHideData(hideValues); + setInitHide(hideValues); + setFilterData(filterValues); + setInitFilter(filterValues); + setSortData(settingStore?.[user_id]?.[page_name]?.[table_name]?.["sorts"] || initialSort); + setInitSort(settingStore?.[user_id]?.[page_name]?.[table_name]?.["sorts"] || initialSort); + setInitStates(true); + }, [settingStore]); + + useEffect(() => { + if ( + JSON.stringify(initFilter) !== JSON.stringify(filterData) || + JSON.stringify(initSort) !== JSON.stringify(sortData) || + JSON.stringify(initHide) !== JSON.stringify(hideData) + ) { + if (!toast.isActive("keep_data", "filtering")) { + toast( + , + { + containerId: "filtering", + toastId: "keep_data", + className: "filter-toast", + position: "bottom-left", + draggable: true, + autoClose: false, + } + ); + } else { + toast.update("keep_data", { + containerId: "filtering", + toastId: "keep_data", + render: ( + + ), + }); + } + } else { + toast.dismiss({ containerId: "datatable" }); + } + }, [filterData, sortData, hideData]); + + if (!isInitStates) return ; + + return ( + + {children} + + ); +}; + +export default DataTableProvider; diff --git a/src/lib/contexts/auth.js b/src/lib/contexts/auth.js index eac1d6d..8356528 100644 --- a/src/lib/contexts/auth.js +++ b/src/lib/contexts/auth.js @@ -1,94 +1,94 @@ -"use client"; -import { GET_USER_ROUTE } from "@/core/utils/routes"; -import axios from "axios"; -import { createContext, useCallback, useContext, useEffect, useReducer, useState } from "react"; - -const initAuth = { - initAuthState: false, - isAuth: false, - user: {}, -}; - -const authReducer = (state, action) => { - switch (action.type) { - case "CLEAR_USER": - return { ...state, user: {} }; - case "CHANGE_USER": - return { ...state, user: action.user }; - case "CHANGE_AUTH_STATE": - return { ...state, isAuth: action.isAuth }; - case "CHANGE_INIT_AUTH": - return { ...state, initAuthState: action.initAuthState }; - default: - return state; - } -}; - -const AuthContext = createContext(); - -export const AuthProvider = ({ children }) => { - const [errorState, setErrorState] = useState({ status: null, message: "" }); - const [state, dispatch] = useReducer(authReducer, initAuth); - - const clearUser = useCallback(() => { - dispatch({ type: "CLEAR_USER" }); - }, []); - - const changeUser = useCallback((user) => { - dispatch({ type: "CHANGE_USER", user }); - }, []); - - const changeAuthState = useCallback((isAuth) => { - dispatch({ type: "CHANGE_AUTH_STATE", isAuth }); - }, []); - - const changeInitAuth = useCallback((initAuthState) => { - dispatch({ type: "CHANGE_INIT_AUTH", initAuthState }); - }, []); - - const logout = () => { - clearUser(); - changeAuthState(false); - changeInitAuth(true); - }; - - const getUser = useCallback(async () => { - try { - const { data } = await axios.get(GET_USER_ROUTE, { withCredentials: true }); - changeUser(data.data); - changeAuthState(true); - changeInitAuth(true); - setErrorState(false); - } catch (error) { - if (error.response && error.response.status === 401) { - clearUser(); - changeAuthState(false); - changeInitAuth(true); - return; - } - let status = error.response && error.response.status ? error.response.status : "نامشخص"; - setErrorState({ status, message: " مشکلی در احراز هویت رخ داده است . دقایقی بعد امتحان کنید!!!" }); - } - }, [clearUser, changeUser, changeAuthState, changeInitAuth]); - - useEffect(() => { - getUser(); - }, []); - - return ( - - {children} - - ); -}; - -export const useAuth = () => useContext(AuthContext); +"use client"; +import { GET_USER_ROUTE } from "@/core/utils/routes"; +import axios from "axios"; +import { createContext, useCallback, useContext, useEffect, useReducer, useState } from "react"; + +const initAuth = { + initAuthState: false, + isAuth: false, + user: {}, +}; + +const authReducer = (state, action) => { + switch (action.type) { + case "CLEAR_USER": + return { ...state, user: {} }; + case "CHANGE_USER": + return { ...state, user: action.user }; + case "CHANGE_AUTH_STATE": + return { ...state, isAuth: action.isAuth }; + case "CHANGE_INIT_AUTH": + return { ...state, initAuthState: action.initAuthState }; + default: + return state; + } +}; + +const AuthContext = createContext(); + +export const AuthProvider = ({ children }) => { + const [errorState, setErrorState] = useState({ status: null, message: "" }); + const [state, dispatch] = useReducer(authReducer, initAuth); + + const clearUser = useCallback(() => { + dispatch({ type: "CLEAR_USER" }); + }, []); + + const changeUser = useCallback((user) => { + dispatch({ type: "CHANGE_USER", user }); + }, []); + + const changeAuthState = useCallback((isAuth) => { + dispatch({ type: "CHANGE_AUTH_STATE", isAuth }); + }, []); + + const changeInitAuth = useCallback((initAuthState) => { + dispatch({ type: "CHANGE_INIT_AUTH", initAuthState }); + }, []); + + const logout = () => { + clearUser(); + changeAuthState(false); + changeInitAuth(true); + }; + + const getUser = useCallback(async () => { + try { + const { data } = await axios.get(GET_USER_ROUTE, { withCredentials: true }); + changeUser(data.data); + changeAuthState(true); + changeInitAuth(true); + setErrorState(false); + } catch (error) { + if (error.response && error.response.status === 401) { + clearUser(); + changeAuthState(false); + changeInitAuth(true); + return; + } + let status = error.response && error.response.status ? error.response.status : "نامشخص"; + setErrorState({ status, message: " مشکلی در احراز هویت رخ داده است . دقایقی بعد امتحان کنید!!!" }); + } + }, [clearUser, changeUser, changeAuthState, changeInitAuth]); + + useEffect(() => { + getUser(); + }, []); + + return ( + + {children} + + ); +}; + +export const useAuth = () => useContext(AuthContext); diff --git a/src/lib/contexts/tableSetting.js b/src/lib/contexts/tableSetting.js index c73a08d..52bc46f 100644 --- a/src/lib/contexts/tableSetting.js +++ b/src/lib/contexts/tableSetting.js @@ -1,134 +1,134 @@ -"use client"; - -import { createContext, useCallback, useEffect, useState } from "react"; -import LZString from "lz-string"; - -export const TableSettingContext = createContext(); - -const decompressData = (compressedData) => { - try { - const decompressed = LZString.decompressFromUTF16(compressedData); - if (decompressed === null) { - localStorage.removeItem("_setting-app"); - return null; - } else { - return JSON.parse(decompressed); - } - } catch (error) { - localStorage.removeItem("_setting-app"); - return null; - } -}; - -export const TableSettingProvider = ({ children }) => { - const [settingStore, setSettingStore] = useState({}); - - useEffect(() => { - const compressedData = localStorage.getItem("_setting-app"); - - const data = compressedData ? decompressData(compressedData) : null; - if (data) { - setSettingStore(data); - } - }, []); - - const hideAction = useCallback((user_id, page_name, table_name, settingValue) => { - clearAction(user_id, page_name, table_name, "hides"); - updateSettingStorage(user_id, page_name, table_name, "hides", settingValue); - }, []); - - const sortAction = useCallback((user_id, page_name, table_name, settingValue) => { - updateSettingStorage(user_id, page_name, table_name, "sorts", settingValue); - }, []); - - const filterAction = (user_id, page_name, table_name, settingValue) => { - updateSettingStorage(user_id, page_name, table_name, "filters", settingValue); - }; - - const resetAction = (user_id, page_name, table_name) => { - const compressedData = localStorage.getItem("_setting-app"); - const prevLocalStorage = compressedData ? decompressData(compressedData) : {}; - - const userSettings = prevLocalStorage[user_id] || {}; - const pageSettings = userSettings[page_name] || {}; - delete pageSettings[table_name]; - - const resetData = { - ...prevLocalStorage, - [user_id]: { - ...userSettings, - [page_name]: { - ...pageSettings, - }, - }, - }; - - localStorage.setItem("_setting-app", LZString.compressToUTF16(JSON.stringify(resetData))); - setSettingStore(resetData); - }; - - const updateSettingStorage = (user_id, page_name, table_name, settingType, settingValue) => { - const compressedData = localStorage.getItem("_setting-app"); - const prevLocalStorage = compressedData ? decompressData(compressedData) : {}; - - const userSettings = prevLocalStorage[user_id] || {}; - const pageSettings = userSettings[page_name] || {}; - const tableSettings = pageSettings[table_name] || {}; - - let newSettings; - if (settingType === "sorts" || settingType === "filters") { - newSettings = [...settingValue]; - } else { - newSettings = { ...(tableSettings[settingType] || {}), ...settingValue }; - } - - const updatedLocalStorage = { - ...prevLocalStorage, - [user_id]: { - ...userSettings, - [page_name]: { - ...pageSettings, - [table_name]: { - ...tableSettings, - [settingType]: Array.isArray(settingValue) ? [...newSettings] : { ...newSettings }, - }, - }, - }, - }; - - localStorage.setItem("_setting-app", LZString.compressToUTF16(JSON.stringify(updatedLocalStorage))); - setSettingStore(updatedLocalStorage); - }; - - const clearAction = (user_id, page_name, table_name, key) => { - const compressedData = localStorage.getItem("_setting-app"); - const prevLocalStorage = compressedData ? decompressData(compressedData) : {}; - - const userSettings = prevLocalStorage[user_id] || {}; - const pageSettings = userSettings[page_name] || {}; - const tableSettings = pageSettings[table_name] || {}; - - const updatedSettings = { - ...prevLocalStorage, - [user_id]: { - ...userSettings, - [page_name]: { - ...pageSettings, - [table_name]: { - ...tableSettings, - [key]: Array.isArray(tableSettings[key]) ? [] : {}, - }, - }, - }, - }; - - localStorage.setItem("_setting-app", LZString.compressToUTF16(JSON.stringify(updatedSettings))); - setSettingStore(updatedSettings); - }; - - return ( - - {children} - - ); -}; +"use client"; + +import { createContext, useCallback, useEffect, useState } from "react"; +import LZString from "lz-string"; + +export const TableSettingContext = createContext(); + +const decompressData = (compressedData) => { + try { + const decompressed = LZString.decompressFromUTF16(compressedData); + if (decompressed === null) { + localStorage.removeItem("_setting-app"); + return null; + } else { + return JSON.parse(decompressed); + } + } catch (error) { + localStorage.removeItem("_setting-app"); + return null; + } +}; + +export const TableSettingProvider = ({ children }) => { + const [settingStore, setSettingStore] = useState({}); + + useEffect(() => { + const compressedData = localStorage.getItem("_setting-app"); + + const data = compressedData ? decompressData(compressedData) : null; + if (data) { + setSettingStore(data); + } + }, []); + + const hideAction = useCallback((user_id, page_name, table_name, settingValue) => { + clearAction(user_id, page_name, table_name, "hides"); + updateSettingStorage(user_id, page_name, table_name, "hides", settingValue); + }, []); + + const sortAction = useCallback((user_id, page_name, table_name, settingValue) => { + updateSettingStorage(user_id, page_name, table_name, "sorts", settingValue); + }, []); + + const filterAction = (user_id, page_name, table_name, settingValue) => { + updateSettingStorage(user_id, page_name, table_name, "filters", settingValue); + }; + + const resetAction = (user_id, page_name, table_name) => { + const compressedData = localStorage.getItem("_setting-app"); + const prevLocalStorage = compressedData ? decompressData(compressedData) : {}; + + const userSettings = prevLocalStorage[user_id] || {}; + const pageSettings = userSettings[page_name] || {}; + delete pageSettings[table_name]; + + const resetData = { + ...prevLocalStorage, + [user_id]: { + ...userSettings, + [page_name]: { + ...pageSettings, + }, + }, + }; + + localStorage.setItem("_setting-app", LZString.compressToUTF16(JSON.stringify(resetData))); + setSettingStore(resetData); + }; + + const updateSettingStorage = (user_id, page_name, table_name, settingType, settingValue) => { + const compressedData = localStorage.getItem("_setting-app"); + const prevLocalStorage = compressedData ? decompressData(compressedData) : {}; + + const userSettings = prevLocalStorage[user_id] || {}; + const pageSettings = userSettings[page_name] || {}; + const tableSettings = pageSettings[table_name] || {}; + + let newSettings; + if (settingType === "sorts" || settingType === "filters") { + newSettings = [...settingValue]; + } else { + newSettings = { ...(tableSettings[settingType] || {}), ...settingValue }; + } + + const updatedLocalStorage = { + ...prevLocalStorage, + [user_id]: { + ...userSettings, + [page_name]: { + ...pageSettings, + [table_name]: { + ...tableSettings, + [settingType]: Array.isArray(settingValue) ? [...newSettings] : { ...newSettings }, + }, + }, + }, + }; + + localStorage.setItem("_setting-app", LZString.compressToUTF16(JSON.stringify(updatedLocalStorage))); + setSettingStore(updatedLocalStorage); + }; + + const clearAction = (user_id, page_name, table_name, key) => { + const compressedData = localStorage.getItem("_setting-app"); + const prevLocalStorage = compressedData ? decompressData(compressedData) : {}; + + const userSettings = prevLocalStorage[user_id] || {}; + const pageSettings = userSettings[page_name] || {}; + const tableSettings = pageSettings[table_name] || {}; + + const updatedSettings = { + ...prevLocalStorage, + [user_id]: { + ...userSettings, + [page_name]: { + ...pageSettings, + [table_name]: { + ...tableSettings, + [key]: Array.isArray(tableSettings[key]) ? [] : {}, + }, + }, + }, + }; + + localStorage.setItem("_setting-app", LZString.compressToUTF16(JSON.stringify(updatedSettings))); + setSettingStore(updatedSettings); + }; + + return ( + + {children} + + ); +}; diff --git a/src/lib/hooks/useAzmayesh.js b/src/lib/hooks/useAzmayesh.js index f0e3c4e..5231881 100644 --- a/src/lib/hooks/useAzmayesh.js +++ b/src/lib/hooks/useAzmayesh.js @@ -1,30 +1,30 @@ -import { useEffect, useState } from "react"; -import { GET_AZMAYESH_TYPE_LIST } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; - -const useAzmayesh = () => { - const requestServer = useRequest(); - const [azmayeshes, setAzmayeshes] = useState([]); - const [loadingAzmayeshes, setLoadingAzmayeshes] = useState(true); - const [errorAzmayeshes, setErrorAzmayeshes] = useState(null); - - useEffect(() => { - const fetchTests = async () => { - try { - const response = await requestServer(`${GET_AZMAYESH_TYPE_LIST}`); - setAzmayeshes(response.data.data); - setLoadingAzmayeshes(false); - } catch (e) { - console.error("Error fetching tests types:", e); - setErrorAzmayeshes(e); - setLoadingAzmayeshes(false); - } - }; - - fetchTests(); - }, []); - - return { azmayeshes, loadingAzmayeshes, errorAzmayeshes }; -}; - -export default useAzmayesh; +import { useEffect, useState } from "react"; +import { GET_AZMAYESH_TYPE_LIST } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; + +const useAzmayesh = () => { + const requestServer = useRequest(); + const [azmayeshes, setAzmayeshes] = useState([]); + const [loadingAzmayeshes, setLoadingAzmayeshes] = useState(true); + const [errorAzmayeshes, setErrorAzmayeshes] = useState(null); + + useEffect(() => { + const fetchTests = async () => { + try { + const response = await requestServer(`${GET_AZMAYESH_TYPE_LIST}`); + setAzmayeshes(response.data.data); + setLoadingAzmayeshes(false); + } catch (e) { + console.error("Error fetching tests types:", e); + setErrorAzmayeshes(e); + setLoadingAzmayeshes(false); + } + }; + + fetchTests(); + }, []); + + return { azmayeshes, loadingAzmayeshes, errorAzmayeshes }; +}; + +export default useAzmayesh; diff --git a/src/lib/hooks/useCities.js b/src/lib/hooks/useCities.js index dfaadbb..5577e21 100644 --- a/src/lib/hooks/useCities.js +++ b/src/lib/hooks/useCities.js @@ -1,59 +1,59 @@ -import { useEffect, useReducer } from "react"; -import { GET_CITY_LISTS } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; -const ACTIONS = { - LOADING: "loading", - SUCCESS: "success", - ERROR: "error", - RESET: "reset", -}; - -const initialState = { - data: [], - loading: true, - error: null, -}; -function reducer(state, action) { - switch (action.type) { - case ACTIONS.LOADING: - return { ...state, loading: true, error: null }; - case ACTIONS.SUCCESS: - return { ...state, loading: false, data: action.payload }; - case ACTIONS.ERROR: - return { ...state, loading: false, error: action.payload }; - case ACTIONS.RESET: - return { ...initialState, loading: false }; - default: - return state; - } -} -const useCities = (id) => { - const requestServer = useRequest(); - const [state, dispatch] = useReducer(reducer, initialState); - - useEffect(() => { - if (!id) { - dispatch({ type: ACTIONS.RESET }); - return; - } - const fetchCityLists = async () => { - dispatch({ type: ACTIONS.LOADING }); - try { - const response = await requestServer(`${GET_CITY_LISTS}/${id}`); - dispatch({ type: ACTIONS.SUCCESS, payload: response.data.data }); - } catch (error) { - dispatch({ type: ACTIONS.ERROR, payload: error }); - } - }; - - fetchCityLists(); - }, [id]); - - return { - cityList: state.data, - loadingCityList: state.loading, - errorCityList: state.error, - }; -}; - -export default useCities; +import { useEffect, useReducer } from "react"; +import { GET_CITY_LISTS } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; +const ACTIONS = { + LOADING: "loading", + SUCCESS: "success", + ERROR: "error", + RESET: "reset", +}; + +const initialState = { + data: [], + loading: true, + error: null, +}; +function reducer(state, action) { + switch (action.type) { + case ACTIONS.LOADING: + return { ...state, loading: true, error: null }; + case ACTIONS.SUCCESS: + return { ...state, loading: false, data: action.payload }; + case ACTIONS.ERROR: + return { ...state, loading: false, error: action.payload }; + case ACTIONS.RESET: + return { ...initialState, loading: false }; + default: + return state; + } +} +const useCities = (id) => { + const requestServer = useRequest(); + const [state, dispatch] = useReducer(reducer, initialState); + + useEffect(() => { + if (!id) { + dispatch({ type: ACTIONS.RESET }); + return; + } + const fetchCityLists = async () => { + dispatch({ type: ACTIONS.LOADING }); + try { + const response = await requestServer(`${GET_CITY_LISTS}/${id}`); + dispatch({ type: ACTIONS.SUCCESS, payload: response.data.data }); + } catch (error) { + dispatch({ type: ACTIONS.ERROR, payload: error }); + } + }; + + fetchCityLists(); + }, [id]); + + return { + cityList: state.data, + loadingCityList: state.loading, + errorCityList: state.error, + }; +}; + +export default useCities; diff --git a/src/lib/hooks/useDamageItemList.js b/src/lib/hooks/useDamageItemList.js index 8349f06..106a976 100644 --- a/src/lib/hooks/useDamageItemList.js +++ b/src/lib/hooks/useDamageItemList.js @@ -1,29 +1,29 @@ -import { useEffect, useState } from "react"; -import { GET_DAMAGE_ITEM_LIST, GET_PROVINCE_LISTS } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; - -const useDamageItemList = () => { - const requestServer = useRequest(); - const [damageItemList, setDamageItemList] = useState([]); - const [loadingDamageItemList, setLoadingDamageItemList] = useState(true); - const [errorDamageItemList, setErrorDamageItemList] = useState(null); - - useEffect(() => { - const fetchDamageItem = async () => { - try { - const response = await requestServer(`${GET_DAMAGE_ITEM_LIST}`); - setDamageItemList(response.data.data); - setLoadingDamageItemList(false); - } catch (e) { - setErrorDamageItemList(e); - setLoadingDamageItemList(false); - } - }; - - fetchDamageItem(); - }, []); - - return { damageItemList, loadingDamageItemList, errorDamageItemList }; -}; - -export default useDamageItemList; +import { useEffect, useState } from "react"; +import { GET_DAMAGE_ITEM_LIST, GET_PROVINCE_LISTS } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; + +const useDamageItemList = () => { + const requestServer = useRequest(); + const [damageItemList, setDamageItemList] = useState([]); + const [loadingDamageItemList, setLoadingDamageItemList] = useState(true); + const [errorDamageItemList, setErrorDamageItemList] = useState(null); + + useEffect(() => { + const fetchDamageItem = async () => { + try { + const response = await requestServer(`${GET_DAMAGE_ITEM_LIST}`); + setDamageItemList(response.data.data); + setLoadingDamageItemList(false); + } catch (e) { + setErrorDamageItemList(e); + setLoadingDamageItemList(false); + } + }; + + fetchDamageItem(); + }, []); + + return { damageItemList, loadingDamageItemList, errorDamageItemList }; +}; + +export default useDamageItemList; diff --git a/src/lib/hooks/useDataTable.js b/src/lib/hooks/useDataTable.js index d1254cb..b9789ba 100644 --- a/src/lib/hooks/useDataTable.js +++ b/src/lib/hooks/useDataTable.js @@ -1,10 +1,10 @@ -import { useContext } from "react"; -import { DataTableContext } from "@/lib/contexts/DataTable"; - -const useTableSetting = () => { - const { filterData, setFilterData, sortData, setSortData, hideData, setHideData, isDirty, isAnyDirty } = - useContext(DataTableContext); - return { filterData, setFilterData, sortData, setSortData, hideData, setHideData, isDirty, isAnyDirty }; -}; - -export default useTableSetting; +import { useContext } from "react"; +import { DataTableContext } from "@/lib/contexts/DataTable"; + +const useTableSetting = () => { + const { filterData, setFilterData, sortData, setSortData, hideData, setHideData, isDirty, isAnyDirty } = + useContext(DataTableContext); + return { filterData, setFilterData, sortData, setSortData, hideData, setHideData, isDirty, isAnyDirty }; +}; + +export default useTableSetting; diff --git a/src/lib/hooks/useEdaratLists.js b/src/lib/hooks/useEdaratLists.js index ad0bc53..c0d1d9a 100644 --- a/src/lib/hooks/useEdaratLists.js +++ b/src/lib/hooks/useEdaratLists.js @@ -1,62 +1,62 @@ -import { useEffect, useReducer } from "react"; -import { GET_EDARAT_LISTS } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; - -const ACTIONS = { - LOADING: "loading", - SUCCESS: "success", - ERROR: "error", - RESET: "reset", -}; - -const initialState = { - data: [], - loading: true, - error: null, -}; - -function reducer(state, action) { - switch (action.type) { - case ACTIONS.LOADING: - return { ...state, loading: true, error: null }; - case ACTIONS.SUCCESS: - return { ...state, loading: false, data: action.payload }; - case ACTIONS.ERROR: - return { ...state, loading: false, error: action.payload }; - case ACTIONS.RESET: - return { ...initialState, loading: false }; - default: - return state; - } -} - -const useEdaratLists = (id) => { - const requestServer = useRequest({ notificationShow: false }); - const [state, dispatch] = useReducer(reducer, initialState); - useEffect(() => { - if (!id) { - dispatch({ type: ACTIONS.RESET }); - return; - } - - const fetchEdaratLists = async () => { - dispatch({ type: ACTIONS.LOADING }); - try { - const response = await requestServer(`${GET_EDARAT_LISTS}/${id}`); - dispatch({ type: ACTIONS.SUCCESS, payload: response.data.data }); - } catch (error) { - dispatch({ type: ACTIONS.ERROR, payload: error }); - } - }; - - fetchEdaratLists(); - }, [id]); - - return { - edaratList: state.data, - loadingEdaratList: state.loading, - errorEdaratList: state.error, - }; -}; - -export default useEdaratLists; +import { useEffect, useReducer } from "react"; +import { GET_EDARAT_LISTS } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; + +const ACTIONS = { + LOADING: "loading", + SUCCESS: "success", + ERROR: "error", + RESET: "reset", +}; + +const initialState = { + data: [], + loading: true, + error: null, +}; + +function reducer(state, action) { + switch (action.type) { + case ACTIONS.LOADING: + return { ...state, loading: true, error: null }; + case ACTIONS.SUCCESS: + return { ...state, loading: false, data: action.payload }; + case ACTIONS.ERROR: + return { ...state, loading: false, error: action.payload }; + case ACTIONS.RESET: + return { ...initialState, loading: false }; + default: + return state; + } +} + +const useEdaratLists = (id) => { + const requestServer = useRequest({ notificationShow: false }); + const [state, dispatch] = useReducer(reducer, initialState); + useEffect(() => { + if (!id) { + dispatch({ type: ACTIONS.RESET }); + return; + } + + const fetchEdaratLists = async () => { + dispatch({ type: ACTIONS.LOADING }); + try { + const response = await requestServer(`${GET_EDARAT_LISTS}/${id}`); + dispatch({ type: ACTIONS.SUCCESS, payload: response.data.data }); + } catch (error) { + dispatch({ type: ACTIONS.ERROR, payload: error }); + } + }; + + fetchEdaratLists(); + }, [id]); + + return { + edaratList: state.data, + loadingEdaratList: state.loading, + errorEdaratList: state.error, + }; +}; + +export default useEdaratLists; diff --git a/src/lib/hooks/usePermissions.js b/src/lib/hooks/usePermissions.js index 3fb4921..57b5040 100644 --- a/src/lib/hooks/usePermissions.js +++ b/src/lib/hooks/usePermissions.js @@ -1,18 +1,18 @@ -import { GET_PERMISSIONS_ROUTE } from "@/core/utils/routes"; -import useSWR from "swr"; -import useRequest from "./useRequest"; - -export const usePermissions = () => { - const request = useRequest(); - - const fetcher = async (url) => { - try { - const response = await request(url); - return response.data.data; - } catch (error) { - throw new Error(); - } - }; - - return useSWR(GET_PERMISSIONS_ROUTE, fetcher, { keepPreviousData: true, dedupingInterval: 30000 }); -}; +import { GET_PERMISSIONS_ROUTE } from "@/core/utils/routes"; +import useSWR from "swr"; +import useRequest from "./useRequest"; + +export const usePermissions = () => { + const request = useRequest(); + + const fetcher = async (url) => { + try { + const response = await request(url); + return response.data.data; + } catch (error) { + throw new Error(); + } + }; + + return useSWR(GET_PERMISSIONS_ROUTE, fetcher, { keepPreviousData: true, dedupingInterval: 30000 }); +}; diff --git a/src/lib/hooks/usePersianInput.js b/src/lib/hooks/usePersianInput.js index 641c27d..6802052 100644 --- a/src/lib/hooks/usePersianInput.js +++ b/src/lib/hooks/usePersianInput.js @@ -1,49 +1,49 @@ -import { useEffect } from "react"; -function usePersianInput(inputRef, onChange) { - useEffect(() => { - const input = inputRef.current; - if (!input) return; - - const handleInput = (event) => { - const originalValue = event.target.value; - const filteredValue = originalValue.replace(/[A-Za-z]/g, ""); - if (filteredValue !== originalValue) { - event.target.value = filteredValue; - if (onChange) { - onChange(filteredValue); - } - } else if (onChange) { - onChange(originalValue); - } - }; - - const handleKeyDown = (event) => { - const controlKeys = [ - "Backspace", - "Delete", - "Tab", - "Escape", - "Enter", - "ArrowLeft", - "ArrowRight", - "ArrowUp", - "ArrowDown", - ]; - if (controlKeys.includes(event.key)) return; - - if (/[A-Za-z]/.test(event.key)) { - event.preventDefault(); - } - }; - - input.addEventListener("input", handleInput); - input.addEventListener("keydown", handleKeyDown); - - return () => { - input.removeEventListener("input", handleInput); - input.removeEventListener("keydown", handleKeyDown); - }; - }, [inputRef, onChange]); -} - -export default usePersianInput; +import { useEffect } from "react"; +function usePersianInput(inputRef, onChange) { + useEffect(() => { + const input = inputRef.current; + if (!input) return; + + const handleInput = (event) => { + const originalValue = event.target.value; + const filteredValue = originalValue.replace(/[A-Za-z]/g, ""); + if (filteredValue !== originalValue) { + event.target.value = filteredValue; + if (onChange) { + onChange(filteredValue); + } + } else if (onChange) { + onChange(originalValue); + } + }; + + const handleKeyDown = (event) => { + const controlKeys = [ + "Backspace", + "Delete", + "Tab", + "Escape", + "Enter", + "ArrowLeft", + "ArrowRight", + "ArrowUp", + "ArrowDown", + ]; + if (controlKeys.includes(event.key)) return; + + if (/[A-Za-z]/.test(event.key)) { + event.preventDefault(); + } + }; + + input.addEventListener("input", handleInput); + input.addEventListener("keydown", handleKeyDown); + + return () => { + input.removeEventListener("input", handleInput); + input.removeEventListener("keydown", handleKeyDown); + }; + }, [inputRef, onChange]); +} + +export default usePersianInput; diff --git a/src/lib/hooks/usePrevStateopinion.js b/src/lib/hooks/usePrevStateopinion.js index 0d5ce73..1b01c0b 100644 --- a/src/lib/hooks/usePrevStateopinion.js +++ b/src/lib/hooks/usePrevStateopinion.js @@ -1,31 +1,31 @@ -import { useState, useEffect } from "react"; -import axios from "axios"; -import { GET_PREV_STATE_OPINION } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; - -const usePrevStateOpinion = () => { - const requestServer = useRequest(); - const [message, setMessage] = useState([]); - const [loadingMessage, setLoadingMessage] = useState(true); - const [errorMessage, setErrorMessage] = useState(null); - - useEffect(() => { - const fetchStateOpnion = async () => { - try { - const response = await requestServer(`${GET_PREV_STATE_OPINION}`); - setMessage(response.data.message); - setLoadingMessage(false); - } catch (e) { - console.error("Error fetching state:", e); - setErrorMessage(e); - setLoadingMessage(false); - } - }; - - fetchStateOpnion(); - }, []); - - return { message, loadingMessage, errorMessage }; -}; - -export default usePrevStateOpinion; +import { useState, useEffect } from "react"; +import axios from "axios"; +import { GET_PREV_STATE_OPINION } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; + +const usePrevStateOpinion = () => { + const requestServer = useRequest(); + const [message, setMessage] = useState([]); + const [loadingMessage, setLoadingMessage] = useState(true); + const [errorMessage, setErrorMessage] = useState(null); + + useEffect(() => { + const fetchStateOpnion = async () => { + try { + const response = await requestServer(`${GET_PREV_STATE_OPINION}`); + setMessage(response.data.message); + setLoadingMessage(false); + } catch (e) { + console.error("Error fetching state:", e); + setErrorMessage(e); + setLoadingMessage(false); + } + }; + + fetchStateOpnion(); + }, []); + + return { message, loadingMessage, errorMessage }; +}; + +export default usePrevStateOpinion; diff --git a/src/lib/hooks/useProvince.js b/src/lib/hooks/useProvince.js index a670efd..0e007ce 100644 --- a/src/lib/hooks/useProvince.js +++ b/src/lib/hooks/useProvince.js @@ -1,29 +1,29 @@ -import { useEffect, useState } from "react"; -import { GET_PROVINCE_LISTS } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; - -const useProvinces = () => { - const requestServer = useRequest(); - const [provinces, setProvinces] = useState([]); - const [loadingProvinces, setLoadingProvinces] = useState(true); - const [errorProvinces, setErrorProvinces] = useState(null); - - useEffect(() => { - const fetchProvinces = async () => { - try { - const response = await requestServer(`${GET_PROVINCE_LISTS}`); - setProvinces(response.data.data); - setLoadingProvinces(false); - } catch (e) { - setErrorProvinces(e); - setLoadingProvinces(false); - } - }; - - fetchProvinces(); - }, []); - - return { provinces, loadingProvinces, errorProvinces }; -}; - -export default useProvinces; +import { useEffect, useState } from "react"; +import { GET_PROVINCE_LISTS } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; + +const useProvinces = () => { + const requestServer = useRequest(); + const [provinces, setProvinces] = useState([]); + const [loadingProvinces, setLoadingProvinces] = useState(true); + const [errorProvinces, setErrorProvinces] = useState(null); + + useEffect(() => { + const fetchProvinces = async () => { + try { + const response = await requestServer(`${GET_PROVINCE_LISTS}`); + setProvinces(response.data.data); + setLoadingProvinces(false); + } catch (e) { + setErrorProvinces(e); + setLoadingProvinces(false); + } + }; + + fetchProvinces(); + }, []); + + return { provinces, loadingProvinces, errorProvinces }; +}; + +export default useProvinces; diff --git a/src/lib/hooks/useRequest.js b/src/lib/hooks/useRequest.js index 0587778..f7ba1ff 100644 --- a/src/lib/hooks/useRequest.js +++ b/src/lib/hooks/useRequest.js @@ -1,60 +1,60 @@ -import { errorResponse } from "@/core/utils/errorResponse"; -import { successRequest } from "@/core/utils/successRequest"; -import axios from "axios"; -import { useAuth } from "../contexts/auth"; -import { useSidebarBadge } from "./useSidebarBadge"; - -const defaultOptions = { - data: {}, - requestOptions: { - headers: {}, - }, - notificationShow: true, - notificationSuccess: false, - notificationFailed: true, - hasSidebarUpdate: false, -}; - -const useRequest = (initOptions) => { - const { mutate: sidebarUpdate } = useSidebarBadge(); - const { logout } = useAuth(); - - const _options = Object.assign({}, defaultOptions, initOptions); - - /** - * Performs an HTTP request. - * @param {string} url - The URL to send the request to. - * @param {'get' | 'post' | 'put' | 'delete'} [method='get'] - HTTP method. - * @param {object} [options] - Additional request options. - * @returns {Promise} - Axios response. - */ - return async (url = "", method = "get", options) => { - const mergedOptions = Object.assign({}, _options, options); - try { - const response = await axios({ - url, - method, - data: method === "get" ? null : mergedOptions.data, - withCredentials: true, - ...mergedOptions.requestOptions, - }); - if (mergedOptions.hasSidebarUpdate) { - if (method === "post" || method === "put" || method === "delete") sidebarUpdate(); - } - successRequest(mergedOptions.notificationShow && mergedOptions.notificationSuccess, "request_data"); - return response; - } catch (error) { - if (error.response) { - errorResponse( - error.response, - mergedOptions.notificationShow && mergedOptions.notificationFailed, - "request_data", - logout - ); - } - throw error; - } - }; -}; - -export default useRequest; +import { errorResponse } from "@/core/utils/errorResponse"; +import { successRequest } from "@/core/utils/successRequest"; +import axios from "axios"; +import { useAuth } from "../contexts/auth"; +import { useSidebarBadge } from "./useSidebarBadge"; + +const defaultOptions = { + data: {}, + requestOptions: { + headers: {}, + }, + notificationShow: true, + notificationSuccess: false, + notificationFailed: true, + hasSidebarUpdate: false, +}; + +const useRequest = (initOptions) => { + const { mutate: sidebarUpdate } = useSidebarBadge(); + const { logout } = useAuth(); + + const _options = Object.assign({}, defaultOptions, initOptions); + + /** + * Performs an HTTP request. + * @param {string} url - The URL to send the request to. + * @param {'get' | 'post' | 'put' | 'delete'} [method='get'] - HTTP method. + * @param {object} [options] - Additional request options. + * @returns {Promise} - Axios response. + */ + return async (url = "", method = "get", options) => { + const mergedOptions = Object.assign({}, _options, options); + try { + const response = await axios({ + url, + method, + data: method === "get" ? null : mergedOptions.data, + withCredentials: true, + ...mergedOptions.requestOptions, + }); + if (mergedOptions.hasSidebarUpdate) { + if (method === "post" || method === "put" || method === "delete") sidebarUpdate(); + } + successRequest(mergedOptions.notificationShow && mergedOptions.notificationSuccess, "request_data"); + return response; + } catch (error) { + if (error.response) { + errorResponse( + error.response, + mergedOptions.notificationShow && mergedOptions.notificationFailed, + "request_data", + logout + ); + } + throw error; + } + }; +}; + +export default useRequest; diff --git a/src/lib/hooks/useRoadItemGetISubtems.js b/src/lib/hooks/useRoadItemGetISubtems.js index 368f72d..e6605a3 100644 --- a/src/lib/hooks/useRoadItemGetISubtems.js +++ b/src/lib/hooks/useRoadItemGetISubtems.js @@ -1,62 +1,62 @@ -import { useEffect, useReducer } from "react"; -import { GET_ROAD_ITEMS_SUB_ITEM } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; - -const ACTIONS = { - LOADING: "loading", - SUCCESS: "success", - ERROR: "error", - RESET: "reset", -}; - -const initialState = { - data: [], - loading: true, - error: null, -}; - -function reducer(state, action) { - switch (action.type) { - case ACTIONS.LOADING: - return { ...state, loading: true, error: null }; - case ACTIONS.SUCCESS: - return { ...state, loading: false, data: action.payload }; - case ACTIONS.ERROR: - return { ...state, loading: false, error: action.payload }; - case ACTIONS.RESET: - return { ...initialState, loading: false }; - default: - return state; - } -} - -const useRoadItemGetSubItems = (id) => { - const requestServer = useRequest({ notificationShow: false }); - const [state, dispatch] = useReducer(reducer, initialState); - useEffect(() => { - if (!id) { - dispatch({ type: ACTIONS.RESET }); - return; - } - - const fetchSubItems = async () => { - dispatch({ type: ACTIONS.LOADING }); - try { - const response = await requestServer(`${GET_ROAD_ITEMS_SUB_ITEM}/${id}`); - dispatch({ type: ACTIONS.SUCCESS, payload: response.data.data }); - } catch (error) { - dispatch({ type: ACTIONS.ERROR, payload: error }); - } - }; - - fetchSubItems(); - }, [id]); - - return { - subItemsList: state.data, - loadingSubItemsList: state.loading, - errorSubItemsList: state.error, - }; -}; - -export default useRoadItemGetSubItems; +import { useEffect, useReducer } from "react"; +import { GET_ROAD_ITEMS_SUB_ITEM } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; + +const ACTIONS = { + LOADING: "loading", + SUCCESS: "success", + ERROR: "error", + RESET: "reset", +}; + +const initialState = { + data: [], + loading: true, + error: null, +}; + +function reducer(state, action) { + switch (action.type) { + case ACTIONS.LOADING: + return { ...state, loading: true, error: null }; + case ACTIONS.SUCCESS: + return { ...state, loading: false, data: action.payload }; + case ACTIONS.ERROR: + return { ...state, loading: false, error: action.payload }; + case ACTIONS.RESET: + return { ...initialState, loading: false }; + default: + return state; + } +} + +const useRoadItemGetSubItems = (id) => { + const requestServer = useRequest({ notificationShow: false }); + const [state, dispatch] = useReducer(reducer, initialState); + useEffect(() => { + if (!id) { + dispatch({ type: ACTIONS.RESET }); + return; + } + + const fetchSubItems = async () => { + dispatch({ type: ACTIONS.LOADING }); + try { + const response = await requestServer(`${GET_ROAD_ITEMS_SUB_ITEM}/${id}`); + dispatch({ type: ACTIONS.SUCCESS, payload: response.data.data }); + } catch (error) { + dispatch({ type: ACTIONS.ERROR, payload: error }); + } + }; + + fetchSubItems(); + }, [id]); + + return { + subItemsList: state.data, + loadingSubItemsList: state.loading, + errorSubItemsList: state.error, + }; +}; + +export default useRoadItemGetSubItems; diff --git a/src/lib/hooks/useRoadItemGetItems.js b/src/lib/hooks/useRoadItemGetItems.js index 1528735..3dec5ab 100644 --- a/src/lib/hooks/useRoadItemGetItems.js +++ b/src/lib/hooks/useRoadItemGetItems.js @@ -1,30 +1,30 @@ -import { useEffect, useState } from "react"; -import { GET_ROAD_ITEMS_ITEM } from "@/core/utils/routes"; -import useRequest from "@/lib/hooks/useRequest"; - -const useRoadItemGetItems = () => { - const requestServer = useRequest(); - const [itemsList, setItemsList] = useState([]); - const [loadingItemsList, setLoadingItemsList] = useState(true); - const [errorItemsList, setErrorItemsList] = useState(null); - - useEffect(() => { - const fetchItems = async () => { - try { - const response = await requestServer(`${GET_ROAD_ITEMS_ITEM}`); - setItemsList(response.data.data); - setLoadingItemsList(false); - setErrorItemsList(false); - } catch (e) { - setErrorItemsList(e); - setLoadingItemsList(false); - } - }; - - fetchItems(); - }, []); - - return { itemsList, loadingItemsList, errorItemsList }; -}; - -export default useRoadItemGetItems; +import { useEffect, useState } from "react"; +import { GET_ROAD_ITEMS_ITEM } from "@/core/utils/routes"; +import useRequest from "@/lib/hooks/useRequest"; + +const useRoadItemGetItems = () => { + const requestServer = useRequest(); + const [itemsList, setItemsList] = useState([]); + const [loadingItemsList, setLoadingItemsList] = useState(true); + const [errorItemsList, setErrorItemsList] = useState(null); + + useEffect(() => { + const fetchItems = async () => { + try { + const response = await requestServer(`${GET_ROAD_ITEMS_ITEM}`); + setItemsList(response.data.data); + setLoadingItemsList(false); + setErrorItemsList(false); + } catch (e) { + setErrorItemsList(e); + setLoadingItemsList(false); + } + }; + + fetchItems(); + }, []); + + return { itemsList, loadingItemsList, errorItemsList }; +}; + +export default useRoadItemGetItems; diff --git a/src/lib/hooks/useSafetyAndPrivacyGetItems.js b/src/lib/hooks/useSafetyAndPrivacyGetItems.js index d97dbbf..5361911 100644 --- a/src/lib/hooks/useSafetyAndPrivacyGetItems.js +++ b/src/lib/hooks/useSafetyAndPrivacyGetItems.js @@ -1,30 +1,30 @@ -import { useEffect, useState } from "react"; -import useRequest from "@/lib/hooks/useRequest"; -import { GET_SAFETY_AND_PRIVACY_ITEM } from "@/core/utils/routes"; - -const useSafetyAndPrivacyGetItems = () => { - const requestServer = useRequest(); - const [itemsList, setItemsList] = useState([]); - const [loadingItemsList, setLoadingItemsList] = useState(true); - const [errorItemsList, setErrorItemsList] = useState(null); - - useEffect(() => { - const fetchItems = async () => { - try { - const response = await requestServer(`${GET_SAFETY_AND_PRIVACY_ITEM}`); - setItemsList(response.data.data); - setLoadingItemsList(false); - setErrorItemsList(false); - } catch (e) { - setErrorItemsList(e); - setLoadingItemsList(false); - } - }; - - fetchItems(); - }, []); - - return { itemsList, loadingItemsList, errorItemsList }; -}; - -export default useSafetyAndPrivacyGetItems; +import { useEffect, useState } from "react"; +import useRequest from "@/lib/hooks/useRequest"; +import { GET_SAFETY_AND_PRIVACY_ITEM } from "@/core/utils/routes"; + +const useSafetyAndPrivacyGetItems = () => { + const requestServer = useRequest(); + const [itemsList, setItemsList] = useState([]); + const [loadingItemsList, setLoadingItemsList] = useState(true); + const [errorItemsList, setErrorItemsList] = useState(null); + + useEffect(() => { + const fetchItems = async () => { + try { + const response = await requestServer(`${GET_SAFETY_AND_PRIVACY_ITEM}`); + setItemsList(response.data.data); + setLoadingItemsList(false); + setErrorItemsList(false); + } catch (e) { + setErrorItemsList(e); + setLoadingItemsList(false); + } + }; + + fetchItems(); + }, []); + + return { itemsList, loadingItemsList, errorItemsList }; +}; + +export default useSafetyAndPrivacyGetItems; diff --git a/src/lib/hooks/useSidebarBadge.js b/src/lib/hooks/useSidebarBadge.js index e74e358..e75881d 100644 --- a/src/lib/hooks/useSidebarBadge.js +++ b/src/lib/hooks/useSidebarBadge.js @@ -1,16 +1,16 @@ -import { GET_SIDEBAR_BADGE_ROUTE } from "@/core/utils/routes"; -import axios from "axios"; -import useSWR from "swr"; - -export const useSidebarBadge = () => { - const fetcher = async (url) => { - try { - const response = await axios({ url, method: "get", withCredentials: true }); - return response.data.data; - } catch (error) { - throw new Error(); - } - }; - - return useSWR(GET_SIDEBAR_BADGE_ROUTE, fetcher, { keepPreviousData: true, dedupingInterval: 30000 }); -}; +import { GET_SIDEBAR_BADGE_ROUTE } from "@/core/utils/routes"; +import axios from "axios"; +import useSWR from "swr"; + +export const useSidebarBadge = () => { + const fetcher = async (url) => { + try { + const response = await axios({ url, method: "get", withCredentials: true }); + return response.data.data; + } catch (error) { + throw new Error(); + } + }; + + return useSWR(GET_SIDEBAR_BADGE_ROUTE, fetcher, { keepPreviousData: true, dedupingInterval: 30000 }); +}; diff --git a/src/lib/hooks/useTableSetting.js b/src/lib/hooks/useTableSetting.js index c841ffc..4c65d69 100644 --- a/src/lib/hooks/useTableSetting.js +++ b/src/lib/hooks/useTableSetting.js @@ -1,9 +1,9 @@ -import { useContext } from "react"; -import { TableSettingContext } from "../contexts/tableSetting"; - -const useTableSetting = () => { - const { settingStore, hideAction, sortAction, filterAction, resetAction } = useContext(TableSettingContext); - return { settingStore, hideAction, sortAction, filterAction, resetAction }; -}; - -export default useTableSetting; +import { useContext } from "react"; +import { TableSettingContext } from "../contexts/tableSetting"; + +const useTableSetting = () => { + const { settingStore, hideAction, sortAction, filterAction, resetAction } = useContext(TableSettingContext); + return { settingStore, hideAction, sortAction, filterAction, resetAction }; +}; + +export default useTableSetting;