From d97566402368ee050e0d247904a9401d5e70c355 Mon Sep 17 00:00:00 2001 From: "pramod.mahajan" Date: Tue, 23 Sep 2025 17:48:56 +0530 Subject: [PATCH] integrated service group wise activity operation delete,edit and create --- src/components/Dashboard/Activity.jsx | 358 +++++++++--------- src/components/master/CreateActivity.jsx | 34 +- src/components/master/EditActivity.jsx | 53 +-- .../master/Services/ManageActivity.jsx | 274 ++++++++++++++ .../master/Services/ManageGroup.jsx | 63 ++- .../master/Services/ServicesGroups.jsx | 314 ++++++++++----- src/hooks/masterHook/useMaster.js | 186 ++++++--- src/pages/master/MasterPage.jsx | 44 ++- src/repositories/MastersRepository.jsx | 25 +- 9 files changed, 942 insertions(+), 409 deletions(-) create mode 100644 src/components/master/Services/ManageActivity.jsx diff --git a/src/components/Dashboard/Activity.jsx b/src/components/Dashboard/Activity.jsx index a1f9c5fc..78483ed5 100644 --- a/src/components/Dashboard/Activity.jsx +++ b/src/components/Dashboard/Activity.jsx @@ -1,194 +1,194 @@ -import React, { useState, useEffect } from "react"; -import LineChart from "../Charts/LineChart"; -import { useProjects } from "../../hooks/useProjects"; -import { useDashboard_ActivityData } from "../../hooks/useDashboard_Data"; -import ApexChart from "../Charts/Circlechart"; +// import React, { useState, useEffect } from "react"; +// import LineChart from "../Charts/LineChart"; +// import { useProjects } from "../../hooks/useProjects"; +// import { useDashboard_ActivityData } from "../../hooks/useDashboard_Data"; +// import ApexChart from "../Charts/Circlechart"; -const LOCAL_STORAGE_PROJECT_KEY = "selectedActivityProjectId"; +// const LOCAL_STORAGE_PROJECT_KEY = "selectedActivityProjectId"; -const Activity = () => { - const { projects } = useProjects(); - const today = new Date().toISOString().split("T")[0]; // Format: YYYY-MM-DD - const [selectedDate, setSelectedDate] = useState(today); - const storedProjectId = localStorage.getItem(LOCAL_STORAGE_PROJECT_KEY); - const initialProjectId = storedProjectId || "all"; - const [selectedProjectId, setSelectedProjectId] = useState(initialProjectId); - const [displayedProjectName, setDisplayedProjectName] = useState("Select Project"); - const [activeTab, setActiveTab] = useState("all"); +// const Activity = () => { +// const { projects } = useProjects(); +// const today = new Date().toISOString().split("T")[0]; // Format: YYYY-MM-DD +// const [selectedDate, setSelectedDate] = useState(today); +// const storedProjectId = localStorage.getItem(LOCAL_STORAGE_PROJECT_KEY); +// const initialProjectId = storedProjectId || "all"; +// const [selectedProjectId, setSelectedProjectId] = useState(initialProjectId); +// const [displayedProjectName, setDisplayedProjectName] = useState("Select Project"); +// const [activeTab, setActiveTab] = useState("all"); - const { dashboard_Activitydata: ActivityData, isLoading, error: isError } = - useDashboard_ActivityData(selectedDate, selectedProjectId); +// const { dashboard_Activitydata: ActivityData, isLoading, error: isError } = +// useDashboard_ActivityData(selectedDate, selectedProjectId); - useEffect(() => { - if (selectedProjectId === "all") { - setDisplayedProjectName("All Projects"); - } else if (projects) { - const foundProject = projects.find((p) => p.id === selectedProjectId); - setDisplayedProjectName(foundProject ? foundProject.name : "Select Project"); - } else { - setDisplayedProjectName("Select Project"); - } +// useEffect(() => { +// if (selectedProjectId === "all") { +// setDisplayedProjectName("All Projects"); +// } else if (projects) { +// const foundProject = projects.find((p) => p.id === selectedProjectId); +// setDisplayedProjectName(foundProject ? foundProject.name : "Select Project"); +// } else { +// setDisplayedProjectName("Select Project"); +// } - localStorage.setItem(LOCAL_STORAGE_PROJECT_KEY, selectedProjectId); - }, [selectedProjectId, projects]); +// localStorage.setItem(LOCAL_STORAGE_PROJECT_KEY, selectedProjectId); +// }, [selectedProjectId, projects]); - const handleProjectSelect = (projectId) => { - setSelectedProjectId(projectId); - }; +// const handleProjectSelect = (projectId) => { +// setSelectedProjectId(projectId); +// }; - const handleDateChange = (e) => { - setSelectedDate(e.target.value); - }; +// const handleDateChange = (e) => { +// setSelectedDate(e.target.value); +// }; - return ( -
-
-
-
-
Activity
-

Activity Progress Chart

-
+// return ( +//
+//
+//
+//
+//
Activity
+//

Activity Progress Chart

+//
-
- -
    -
  • - -
  • - {projects?.map((project) => ( -
  • - -
  • - ))} -
-
-
-
+//
+// +//
    +//
  • +// +//
  • +// {projects?.map((project) => ( +//
  • +// +//
  • +// ))} +//
+//
+//
+//
- {/* ✅ Date Picker Aligned Left with Padding */} -
-
- -
-
+// {/* ✅ Date Picker Aligned Left with Padding */} +//
+//
+// +//
+//
- {/* Tabs */} -
    -
  • - -
  • -
  • - -
  • -
+// {/* Tabs */} +//
    +//
  • +// +//
  • +//
  • +// +//
  • +//
-
- {activeTab === "all" && ( -
-
- {isLoading ? ( -

Loading activity data...

- ) : isError ? ( -

No data available.

- ) : ( - ActivityData && ( - <> -
- Allocated Task -
-

- {ActivityData.totalCompletedWork?.toLocaleString()}/ - {ActivityData.totalPlannedWork?.toLocaleString()} -

- Completed / Assigned -
- -
- - ) - )} -
+//
+// {activeTab === "all" && ( +//
+//
+// {isLoading ? ( +//

Loading activity data...

+// ) : isError ? ( +//

No data available.

+// ) : ( +// ActivityData && ( +// <> +//
+// Allocated Task +//
+//

+// {ActivityData.totalCompletedWork?.toLocaleString()}/ +// {ActivityData.totalPlannedWork?.toLocaleString()} +//

+// Completed / Assigned +//
+// +//
+// +// ) +// )} +//
-
- {!isLoading && !isError && ActivityData && ( - <> -
- Activities -
-

- {ActivityData.totalCompletedWork?.toLocaleString()}/ - {ActivityData.totalPlannedWork?.toLocaleString()} -

- Pending / Assigned -
- -
- - )} -
-
- )} +//
+// {!isLoading && !isError && ActivityData && ( +// <> +//
+// Activities +//
+//

+// {ActivityData.totalCompletedWork?.toLocaleString()}/ +// {ActivityData.totalPlannedWork?.toLocaleString()} +//

+// Pending / Assigned +//
+// +//
+// +// )} +//
+//
+// )} - {activeTab === "logs" && ( -
- - - - - - - - - {[{ - activity: "Code Review / Remote", - assignedToday: 3, - completed: 2 - }].map((log, index) => ( - - - - - ))} - -
Activity / LocationAssigned / Completed
{log.activity}{log.assignedToday} / {log.completed}
-
- )} -
-
- ); -}; +// {activeTab === "logs" && ( +//
+// +// +// +// +// +// +// +// +// {[{ +// activity: "Code Review / Remote", +// assignedToday: 3, +// completed: 2 +// }].map((log, index) => ( +// +// +// +// +// ))} +// +//
Activity / LocationAssigned / Completed
{log.activity}{log.assignedToday} / {log.completed}
+//
+// )} +//
+//
+// ); +// }; -export default Activity; +// export default Activity; diff --git a/src/components/master/CreateActivity.jsx b/src/components/master/CreateActivity.jsx index d707593d..1db2bb79 100644 --- a/src/components/master/CreateActivity.jsx +++ b/src/components/master/CreateActivity.jsx @@ -24,7 +24,7 @@ const schema = z.object({ .optional(), }); -const CreateActivity = ({ onClose }) => { +const CreateActivity = ({ activity = null, whichGroup = null, close }) => { const maxDescriptionLength = 255; const { mutate: createActivity, isPending: isLoading } = useCreateActivity(() => onClose?.()); @@ -86,25 +86,19 @@ const CreateActivity = ({ onClose }) => { const onSubmit = (formData) => { createActivity(formData); }; - // const onSubmit = (data) => { - // setIsLoading(true); - - // MasterRespository.createActivity(data) - // .then( ( resp ) => - // { - - // const cachedData = getCachedData("Activity"); - // const updatedData = [ ...cachedData, resp?.data ]; - // cacheData("Activity", updatedData); - // showToast("Activity Successfully Added.", "success"); - // setIsLoading(false); - // handleClose() - // }) - // .catch((error) => { - // showToast(error.message, "error"); - // setIsLoading(false); - // }); - // }; + + useEffect(()=>{ + if (activity) { + reset({ + activityName: activity.activityName || '', + unitOfMeasurement: activity.unitOfMeasurement || '', + checkList: activity.checkList?.map((check) => ({ + description: check.description || '', + isMandatory: check.isMandatory || false, + })) || [{ description: '', isMandatory: false }], + }); + } + },[activity,reset]) const handleClose = useCallback(() => { reset(); onClose(); diff --git a/src/components/master/EditActivity.jsx b/src/components/master/EditActivity.jsx index 43816f4c..15e85255 100644 --- a/src/components/master/EditActivity.jsx +++ b/src/components/master/EditActivity.jsx @@ -24,7 +24,7 @@ const schema = z.object({ }); -const UpdateActivity = ({ activityData, onClose }) => { +const UpdateActivity = ({ activity = null, whichService = null, close }) => { const { mutate: updateActivity, isPending: isLoading } = useUpdateActivity(() => onClose?.()); const { @@ -40,10 +40,10 @@ const UpdateActivity = ({ activityData, onClose }) => { } = useForm({ resolver: zodResolver(schema), defaultValues: { - id: activityData?.id, - activityName: activityData?.activityName, - unitOfMeasurement: activityData?.unitOfMeasurement, - checkList: activityData?.checkLists || [], + id: activity?.id, + activityName: activity?.activityName, + unitOfMeasurement: activity?.unitOfMeasurement, + checkList: activity?.checkLists || [], }, }); @@ -53,15 +53,15 @@ const UpdateActivity = ({ activityData, onClose }) => { }); useEffect(() => { - if (activityData) { + if (activity) { reset({ - id: activityData.id, - activityName: activityData.activityName, - unitOfMeasurement: activityData.unitOfMeasurement, - checkList: activityData.checkLists || [], + id: activity.id, + activityName: activity.activityName, + unitOfMeasurement: activity.unitOfMeasurement, + checkList: activity.checkLists || [], }); } - }, [activityData, reset]); + }, [activity, reset]); const addChecklistItem = () => { const values = getValues("checkList"); @@ -91,36 +91,10 @@ const UpdateActivity = ({ activityData, onClose }) => { }; const onSubmit = (formData) => { - const payload = { ...formData, id: activityData.id }; - updateActivity({ id: activityData.id, payload }); + const payload = { ...formData, id: activity.id }; + updateActivity({ id: activity.id, payload }); }; - // const onSubmit = async(data) => { - // setIsLoading(true); - // const Activity = {...data, id:activityData.id} - // try - // { - // const response = await MasterRespository.updateActivity( activityData?.id, Activity ); - // const updatedActivity = response.data; - // const cachedData = getCachedData("Activity") - - // if (cachedData) { - // const updatedActivities = cachedData.map((activity) => - // activity.id === updatedActivity.id ? { ...activity, ...updatedActivity } : activity - // ); - - // cacheData( "Activity", updatedActivities ); - // onClose() - // } - // setIsLoading( false ) - // showToast("Activity Successfully Updated", "success"); - // } catch ( err ) - // { - // setIsLoading( false ) - - // showToast("error.message", "error"); - // } - // }; useEffect(() => { const tooltipTriggerList = Array.from(document.querySelectorAll('[data-bs-toggle="tooltip"]')); @@ -129,7 +103,6 @@ const UpdateActivity = ({ activityData, onClose }) => { return (
- {/*
Update Activity
*/}
{/* Activity Name */}
diff --git a/src/components/master/Services/ManageActivity.jsx b/src/components/master/Services/ManageActivity.jsx new file mode 100644 index 00000000..e3d0fa2c --- /dev/null +++ b/src/components/master/Services/ManageActivity.jsx @@ -0,0 +1,274 @@ +import React, { useState, useEffect, useCallback } from "react"; +import { useFieldArray, useForm } from "react-hook-form"; +import { z } from "zod"; +import { zodResolver } from "@hookform/resolvers/zod"; + +import { + useCreateActivity, + useUpdateActivity, +} from "../../../hooks/masterHook/useMaster"; +import Label from "../../common/Label"; + +const schema = z.object({ + activityName: z.string().min(1, { message: "Activity Name is required" }), + unitOfMeasurement: z + .string() + .min(1, { message: "Unit of Measurement is required" }), + checkList: z + .array( + z.object({ + description: z + .string() + .min(1, { message: "descriptionlist item cannot be empty" }), + isMandatory: z.boolean().default(false), + id: z.any().default(null), + }) + ) + .optional(), +}); + +const ManageActivity = ({ activity = null, whichGroup = null, close }) => { + const maxDescriptionLength = 255; + const { mutate: createActivity, isPending: isLoading } = useCreateActivity( + () => close?.() + ); + const { mutate: UpdateActivity, isPending: isUpdating } = useUpdateActivity( + () => close?.() + ); + + const { + register, + handleSubmit, + control, + setValue, + clearErrors, + setError, + getValues, + reset, + formState: { errors }, + } = useForm({ + resolver: zodResolver(schema), + defaultValues: { + activityName: "", + unitOfMeasurement: "", + checkList: [], + }, + }); + + const { + fields: checkListItems, + append, + remove, + } = useFieldArray({ + control, + name: "checkList", + }); + + const addChecklistItem = useCallback(() => { + const values = getValues("checkList"); + const lastIndex = checkListItems.length - 1; + + if ( + checkListItems.length > 0 && + (!values?.[lastIndex] || values[lastIndex].description.trim() === "") + ) { + setError(`checkList.${lastIndex}.description`, { + type: "manual", + message: "Please fill this checklist item before adding another.", + }); + return; + } + + clearErrors(`checkList.${lastIndex}.description`); + append({ id: null, description: "", isMandatory: false }); + }, [checkListItems, getValues, append, setError, clearErrors]); + + const removeChecklistItem = useCallback( + (index) => { + remove(index); + }, + [remove] + ); + + const handleChecklistChange = useCallback( + (index, value) => { + setValue(`checkList.${index}`, value); + }, + [setValue] + ); + + const onSubmit = (formData) => { + let payload = { + ...formData, + activityGroupId: whichGroup, + }; + if (activity) { + UpdateActivity({ id: activity.id, payload: payload }); + } else { + createActivity(payload); + } + }; + + useEffect(() => { + if (activity) { + reset({ + activityName: activity.activityName || "", + unitOfMeasurement: activity.unitOfMeasurement || "", + checkList: activity.checkLists?.map((check) => ({ + id: check.id || null, // Use the ID provided in the checklist + description: check.description || "", + isMandatory: check.isMandatory || false, + })) || [{ description: "", isMandatory: false }], // Default to an empty checklist item + }); + } + }, [activity, reset]); + const handleClose = useCallback(() => { + reset(); + close(); + }, [reset, close]); + + useEffect(() => { + const tooltipTriggerList = Array.from( + document.querySelectorAll('[data-bs-toggle="tooltip"]') + ); + tooltipTriggerList.forEach((el) => new bootstrap.Tooltip(el)); + }, []); + let isPending = isLoading || isUpdating; + return ( + + {/*
Create Activity
*/} +
+
+ + + {errors.activityName && ( +

{errors.activityName.message}

+ )} +
+ +
+ + + {errors.unitOfMeasurement && ( +

{errors.unitOfMeasurement.message}

+ )} +
+ +
+

+ {checkListItems.length > 0 ? "Check List" : "Add Check List"} +

+ {checkListItems.length > 0 && ( + + + + + + + + + + {checkListItems.map((item, index) => ( + + + + + + ))} + +
+ Name + + Is Mandatory + Action
+ + + handleChecklistChange(index, e.target.value) + } + /> + {errors.checkList?.[index]?.description && ( + + {errors.checkList[index]?.description?.message} + + )} + + + + +
+ )} + +
+ +
+ + +
+
+ + ); +}; + +export default ManageActivity; diff --git a/src/components/master/Services/ManageGroup.jsx b/src/components/master/Services/ManageGroup.jsx index 1a31f2f7..56ec49f5 100644 --- a/src/components/master/Services/ManageGroup.jsx +++ b/src/components/master/Services/ManageGroup.jsx @@ -1,24 +1,57 @@ import { useForm } from "react-hook-form"; -import { useCreateActivityGroup } from "../../../hooks/masterHook/useMaster"; +import { + useCreateActivityGroup, + useUpdateActivityGroup, +} from "../../../hooks/masterHook/useMaster"; import { zodResolver } from "@hookform/resolvers/zod"; import { ActivityGroupSchema } from "./ServicesSchema"; import Label from "../../common/Label"; +import { useEffect } from "react"; -const ManageGroup = ({ group = null, close }) => { +const ManageGroup = ({ group = null, whichService = null, close }) => { const { register, handleSubmit, + reset, formState: { errors }, } = useForm({ resolver: zodResolver(ActivityGroupSchema), defaultValues: { name: "", description: "" }, }); - const { mutate: createGroup, isPending } = useCreateActivityGroup(); + const { mutate: createGroup, isPending: isCreating } = useCreateActivityGroup( + () => close() + ); + const { mutate: UpdateGroup, isPending: isUpdating } = useUpdateActivityGroup( + () => close() + ); - const onSubmit = (payload) => { - console.log(payload); - // createGroup + useEffect(() => { + if (group) { + reset({ + name: group.name || " ", + description: group.description || "", + }); + } + }, [group, reset]); + const onSubmit = (formdata) => { + if (group) { + let payload = { + ...formdata, + serviceId: whichService, + id: group.id, + }; + UpdateGroup({ id: group.id, payload: payload }); + } else { + let payload = { + ...formdata, + serviceId: whichService, + }; + + createGroup(payload); + } }; + + let isPending = isCreating || isUpdating; return (
@@ -28,9 +61,13 @@ const ManageGroup = ({ group = null, close }) => { - {errors.name &&

{errors.name.message}

} + {errors.name && ( +

{errors.name.message}

+ )}
diff --git a/src/hooks/masterHook/useMaster.js b/src/hooks/masterHook/useMaster.js index 7846fa77..9afee253 100644 --- a/src/hooks/masterHook/useMaster.js +++ b/src/hooks/masterHook/useMaster.js @@ -18,16 +18,20 @@ export const useServices = () => { }; export const useGroups = (serviceId) => { - return useQuery({ - queryFn: ["groups", serviceId], + return useQuery({ + queryKey: ["groups", serviceId], queryFn: async () => await MasterRespository.getActivityGrops(serviceId), - }) + enabled: !!serviceId, + }); }; export const useActivitiesByGroups = (groupId) => { - return useQuery({ - queryFn: ["activties", groupId], - queryFn: async () => await MasterRespository.getActivityGrops(groupId), - }) + return useQuery({ + queryKey: ["activties", groupId], + queryFn: async () => await MasterRespository.getActivitesByGroup(groupId), + + enabled: !!groupId, + + }); }; export const useGlobalServices = () => { return useQuery({ @@ -46,8 +50,6 @@ export const useMasterMenu = () => { }); }; - - export const useActivitiesMaster = () => { const { data: activities = [], @@ -446,47 +448,7 @@ export const useUpdateApplicationRole = (onSuccessCallback) => { }); }; -// Activity------------------------------ -export const useCreateActivity = (onSuccessCallback) => { - const queryClient = useQueryClient(); - return useMutation({ - mutationFn: async (payload) => { - const resp = await MasterRespository.createActivity(payload); - return resp.data; - }, - onSuccess: (data) => { - queryClient.invalidateQueries({ queryKey: ["masterData", "Activity"] }); - showToast("Activity added successfully", "success"); - if (onSuccessCallback) onSuccessCallback(data); - }, - onError: (error) => { - showToast(error.message || "Something went wrong", "error"); - }, - }); -}; - -export const useUpdateActivity = (onSuccessCallback) => { - const queryClient = useQueryClient(); - - return useMutation({ - mutationFn: async ({ id, payload }) => { - const response = await MasterRespository.updateActivity(id, payload); - return response.data; - }, - onSuccess: (data, variables) => { - queryClient.invalidateQueries({ - queryKey: ["masterData", "Activity"], - }); - showToast("Activity updated successfully.", "success"); - - if (onSuccessCallback) onSuccessCallback(data); - }, - onError: (error) => { - showToast(error.message || "Something went wrong", "error"); - }, - }); -}; //-----Create work Category------------------------------- export const useCreateWorkCategory = (onSuccessCallback) => { @@ -785,20 +747,23 @@ export const useUpdateService = (onSuccessCallback) => { }); }; -export const useCreateActivityGroup =()=>{ - const queryClient = useQueryClient(); +export const useCreateActivityGroup = (onSuccessCallback) => { + const queryClient = useQueryClient(); return useMutation({ mutationFn: async (payload) => { - const response = await MasterRespository.createActivityGroup(payload) + const response = await MasterRespository.createActivityGroup(payload); return response; }, onSuccess: (data, variables) => { queryClient.invalidateQueries({ - queryKey: ["masterData", "Services"], + queryKey: ["groups"], }); - showToast(data.message || "Activity Group created successfully.", "success"); + showToast( + data.message || "Activity Group created successfully.", + "success" + ); if (onSuccessCallback) onSuccessCallback(data); }, @@ -806,7 +771,73 @@ export const useCreateActivityGroup =()=>{ showToast(error?.message || "Something went wrong", "error"); }, }); -} +}; +export const useUpdateActivityGroup = (onSuccessCallback) => { + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: async ({id,payload}) => { + const response = await MasterRespository.updateActivityGrop(id,payload); + return response; + }, + onSuccess: (data, variables) => { + queryClient.invalidateQueries({ + queryKey: ["groups"], + }); + + showToast( + data.message || "Activity Group Updated successfully.", + "success" + ); + + if (onSuccessCallback) onSuccessCallback(data); + }, + onError: (error) => { + showToast(error?.message || "Something went wrong", "error"); + }, + }); +}; +// Activity------------------------------ +export const useCreateActivity = (onSuccessCallback) => { + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: async (payload) => { + const resp = await MasterRespository.createActivity(payload); + return resp.data; + }, + onSuccess: (data) => { + queryClient.invalidateQueries({ queryKey: ["activties"] }); + showToast("Activity added successfully", "success"); + if (onSuccessCallback) onSuccessCallback(data); + }, + onError: (error) => { + showToast(error.message || "Something went wrong", "error"); + }, + }); +}; + +export const useUpdateActivity = (onSuccessCallback) => { + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: async ({ id, payload }) => { + const response = await MasterRespository.updateActivity(id, payload); + return response.data; + }, + onSuccess: (data, variables) => { + queryClient.invalidateQueries({ + queryKey: ["activties"], + }); + showToast("Activity updated successfully.", "success"); + + if (onSuccessCallback) onSuccessCallback(data); + }, + onError: (error) => { + showToast(error.message || "Something went wrong", "error"); + }, + }); +}; // -------------------Expense Status---------------------------------- export const useCreateExpenseStatus = (onSuccessCallback) => { @@ -969,3 +1000,48 @@ export const useDeleteMasterItem = () => { }, }); }; + + +export const useDeleteServiceGroup =()=>{ + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: async (id)=>await MasterRespository.deleteActivityGroup(id), + onSuccess: ({_,variable}) => { + + queryClient.invalidateQueries({ queryKey: ["groups"] }); + + showToast(`Group deleted successfully.`, "success"); + }, + + onError: (error) => { + const message = + error?.response?.data?.message || + error?.message || + "Error occurred during deletion"; + showToast(message, "error"); + }, + }); +} +export const useDeleteActivity =()=>{ + const queryClient = useQueryClient(); + + return useMutation({ + mutationFn: async (id)=>await MasterRespository.deleteActivity(id), + onSuccess: ({_,variable}) => { + + + queryClient.invalidateQueries({ queryKey: ["activties"] }); + + showToast(`Acivity deleted successfully.`, "success"); + }, + + onError: (error) => { + const message = + error?.response?.data?.message || + error?.message || + "Error occurred during deletion"; + showToast(message, "error"); + }, + }); +} diff --git a/src/pages/master/MasterPage.jsx b/src/pages/master/MasterPage.jsx index b187efd1..323e3442 100644 --- a/src/pages/master/MasterPage.jsx +++ b/src/pages/master/MasterPage.jsx @@ -1,4 +1,4 @@ -import React, { useState, useMemo, useEffect } from "react"; +import React, { useState, useMemo, useEffect, createContext, useContext } from "react"; import { useDispatch, useSelector } from "react-redux"; import { useQueryClient } from "@tanstack/react-query"; import Breadcrumb from "../../components/common/Breadcrumb"; @@ -6,7 +6,9 @@ import MasterModal from "../../components/master/MasterModal"; import ConfirmModal from "../../components/common/ConfirmModal"; import MasterTable from "./MasterTable"; import useMaster, { + useDeleteActivity, useDeleteMasterItem, + useDeleteServiceGroup, useMasterMenu, } from "../../hooks/masterHook/useMaster"; import { changeMaster } from "../../slices/localVariablesSlice"; @@ -14,6 +16,16 @@ import { useHasUserPermission } from "../../hooks/useHasUserPermission"; import { MANAGE_MASTER } from "../../utils/constants"; import GlobalModel from "../../components/common/GlobalModel"; + +export const MasterContext = createContext(); +export const useMasterContext = () => { + const context = useContext(MasterContext); + if (!context) { + throw new Error("useMasterContext must be used within an MasterProvider"); + } + return context; +}; + const MasterPage = () => { const dispatch = useDispatch(); const queryClient = useQueryClient(); @@ -34,6 +46,9 @@ const MasterPage = () => { isError: isMasterError, } = useMaster(); const { mutate: DeleteMaster, isPending: isDeleting } = useDeleteMasterItem(); + const [isDeleletingServiceItem,setDeleletingServiceItem] = useState({isOpen:false,ItemId:null,whichItem:null}) + const {mutate:DeleteSericeGroup,isPending:deletingGroup} =useDeleteServiceGroup() + const {mutate:DeleteAcivity,isPending:deletingActivity} = useDeleteActivity() const [modalConfig, setModalConfig] = useState(null); const [deleteData, setDeleteData] = useState(null); @@ -73,6 +88,18 @@ const MasterPage = () => { ); }; + + const handleDeleteServiceItem =()=>{ + if(!isDeleletingServiceItem.ItemId) return + if(isDeleletingServiceItem.whichItem == "activiy"){ + DeleteAcivity(isDeleletingServiceItem.ItemId,{onSuccess:()=>setDeleletingServiceItem({isOpen:false,ItemId:null,whichItem:null})}) + }else{ + DeleteSericeGroup(isDeleletingServiceItem.ItemId,{onSuccess:()=>setDeleletingServiceItem({isOpen:false,ItemId:null,whichItem:null})}) + } + + + } + if (menuErrorFlag || isMasterError) return (
@@ -87,7 +114,7 @@ const MasterPage = () => { ); return ( - <> + {modalConfig && ( { /> )} + { onSubmit={handleDeleteSubmit} onClose={() => setDeleteData(null)} /> + + setDeleletingServiceItem({isOpen:false,ItemId:null,whichItem:null})} + />
{
- + ); }; diff --git a/src/repositories/MastersRepository.jsx b/src/repositories/MastersRepository.jsx index 00778dc1..3e9fac8f 100644 --- a/src/repositories/MastersRepository.jsx +++ b/src/repositories/MastersRepository.jsx @@ -32,11 +32,11 @@ export const MasterRespository = { getActivites: () => api.get("api/master/activities"), createActivity: (data) => api.post("api/master/activity", data), -//Services + //Services getService: () => api.get("api/master/service/list"), createService: (data) => api.post("api/master/service/create", data), updateService: (id, data) => api.put(`api/master/service/edit/${id}`, data), - "Services": (id) => api.delete(`/api/master/service/delete/${id}`), + Services: (id) => api.delete(`/api/master/service/delete/${id}`), updateActivity: (id, data) => api.post(`api/master/activity/edit/${id}`, data), @@ -114,15 +114,20 @@ export const MasterRespository = { updateDocumentType: (id, data) => api.put(`/api/Master/document-type/edit/${id}`, data), + getGlobalServices: () => api.get("/api/Master/global-service/list"), + getMasterServices: () => api.get("/api/Master/service/list"), + getActivityGrops: (serviceId) => + api.get(`/api/Master/activity-group/list?serviceId=${serviceId}`), + createActivityGroup: (data) => + api.post(`/api/Master/activity-group/create`, data), + updateActivityGrop: (serviceId, data) => + api.put(`/api/Master/activity-group/edit/${serviceId}`, data), + getActivitesByGroup: (activityGroupId) => + api.get(`api/master/activities?activityGroupId=${activityGroupId}`), + deleteActivityGroup:(id)=>api.delete(`/api/Master/activity-group/delete/${id}`), - getGlobalServices:()=>api.get("/api/Master/global-service/list"), - getMasterServices:()=>api.get("/api/Master/service/list"), - getActivityGrops:(serviceId)=>api.get(`/api/Master/activity-group/list?serviceId=${serviceId}`), - createActivityGroup:(data)=>api.post(`/api/Master/activity-group/create`), - getActivitesByGroup: (serviceId) => api.get(`api/master/activities/activityGroupId=${activityGroupId}`), + deleteActivity:(id)=>api.delete(`/api/Master/activity/delete/${id}`), - - - getOrganizationType:()=>api.get('/api/Master/organization-type/list') + getOrganizationType: () => api.get("/api/Master/organization-type/list"), };