Issues_July_2W: Project overview widgets #256

Merged
vikas.nale merged 17 commits from Issues_July_2W into main 2025-07-15 12:28:46 +00:00
4 changed files with 376 additions and 204 deletions
Showing only changes of commit 788f0baee4 - Show all commits

View File

@ -116,7 +116,17 @@ useEffect(() => {
floorId: floor?.id, floorId: floor?.id,
workAreaId: workArea?.id, workAreaId: workArea?.id,
}; };
UpdateTask([payload]) let plannedTask =
workItem?.workItem?.plannedWork || workItem?.plannedWork || 0;
let completedTask = workItem?.workItem?.completedWork || workItem?.completedWork || 0
UpdateTask({
payload: [payload],
PreviousPlannedWork: plannedTask,
buildingId: building?.id,
floorId: floor?.id,
workAreaId: workArea?.id,
previousCompletedWork:completedTask
});
} }
return ( return (
<form className="row g-2 p-2 p-md-1" onSubmit={handleSubmit(onSubmitForm)}> <form className="row g-2 p-2 p-md-1" onSubmit={handleSubmit(onSubmitForm)}>

View File

@ -69,10 +69,9 @@ const TaskModel = ({ project, onSubmit, onClose }) => {
const selectedCategory = categoryData?.find((c) => c.id === watchCategoryId); const selectedCategory = categoryData?.find((c) => c.id === watchCategoryId);
const { mutate: CreateTask, isPending } = useManageTask({ const { mutate: CreateTask, isPending } = useManageTask({
onSuccessCallback: ( response ) => onSuccessCallback: (response) => {
{ showToast(response?.message, "success");
showToast( response?.message, "success" ) onClose?.();
onClose?.()
}, },
}); });
useEffect(() => { useEffect(() => {
@ -97,7 +96,9 @@ const TaskModel = ({ project, onSubmit, onClose }) => {
const onSubmitForm = async (data) => { const onSubmitForm = async (data) => {
const payload = [data]; const payload = [data];
CreateTask(payload); CreateTask({payload:payload,buildingId: data.buildingID,
floorId: data.floorId,
workAreaId: data.workAreaId, PreviousPlannedWork:0,previousCompletedWork:0});
}; };
return ( return (

View File

@ -10,7 +10,10 @@ import {
} from "../../../utils/constants"; } from "../../../utils/constants";
import ConfirmModal from "../../common/ConfirmModal"; import ConfirmModal from "../../common/ConfirmModal";
import ProjectRepository from "../../../repositories/ProjectRepository"; import ProjectRepository from "../../../repositories/ProjectRepository";
import { useDeleteProjectTask, useProjectDetails } from "../../../hooks/useProjects"; import {
useDeleteProjectTask,
useProjectDetails,
} from "../../../hooks/useProjects";
import showToast from "../../../services/toastService"; import showToast from "../../../services/toastService";
import { import {
cacheData, cacheData,
@ -19,7 +22,7 @@ import {
} from "../../../slices/apiDataManager"; } from "../../../slices/apiDataManager";
import { refreshData } from "../../../slices/localVariablesSlice"; import { refreshData } from "../../../slices/localVariablesSlice";
import GlobalModel from "../../common/GlobalModel"; import GlobalModel from "../../common/GlobalModel";
import {useDeleteMasterItem} from "../../../hooks/masterHook/useMaster"; import { useDeleteMasterItem } from "../../../hooks/masterHook/useMaster";
const WorkItem = ({ const WorkItem = ({
workItem, workItem,
@ -40,9 +43,8 @@ const WorkItem = ({
const [loadingDelete, setLoadingDelete] = useState(false); const [loadingDelete, setLoadingDelete] = useState(false);
const project = getCachedData("projectInfo"); const project = getCachedData("projectInfo");
const openModal = () => setIsModalOpen(true); const openModal = () => setIsModalOpen(true);
const closeModal = () => setIsModalOpen( false ); const closeModal = () => setIsModalOpen(false);
const showModalDelete = () => setShowModal2(true); const showModalDelete = () => setShowModal2(true);
const closeModalDelete = () => setShowModal2(false); const closeModalDelete = () => setShowModal2(false);
@ -50,7 +52,7 @@ const WorkItem = ({
return (completed * 100) / planned + "%"; return (completed * 100) / planned + "%";
}; };
const {mutate:DeleteTask,isPending } = useDeleteProjectTask(() => { const { mutate: DeleteTask, isPending } = useDeleteProjectTask(() => {
closeModalDelete?.(); closeModalDelete?.();
}); });
@ -61,7 +63,7 @@ const WorkItem = ({
setNewWorkItem(workItem); setNewWorkItem(workItem);
}, [workItem]); }, [workItem]);
const refreshWorkItem = (plannedTask) =>{ const refreshWorkItem = (plannedTask) => {
if (workItem) { if (workItem) {
const updated = { const updated = {
...workItem, ...workItem,
@ -69,7 +71,7 @@ const WorkItem = ({
}; };
setNewWorkItem(updated); setNewWorkItem(updated);
} }
} };
let assigndata = { let assigndata = {
building: forBuilding, building: forBuilding,
floor: forFloor, floor: forFloor,
@ -85,15 +87,17 @@ const WorkItem = ({
tooltipTriggerList.forEach((el) => new bootstrap.Tooltip(el)); tooltipTriggerList.forEach((el) => new bootstrap.Tooltip(el));
}, []); }, []);
const handleSubmit = async () => { const handleSubmit = async () => {
let WorkItemId = workItem.workItemId || workItem.id; let WorkItemId = workItem.workItemId || workItem.id;
DeleteTask({workItemId:WorkItemId,workAreaId:forWorkArea?.id}) debugger
DeleteTask({
workItemId: WorkItemId,
workAreaId: forWorkArea?.id,
completedTask: workItem?.completedWork,
plannedTask: workItem?.plannedWork,
buildingId: forBuilding?.id,
floorId: forFloor?.id,
});
}; };
const PlannedWork = const PlannedWork =
@ -104,18 +108,26 @@ const WorkItem = ({
<> <>
{isModalOpen && ( {isModalOpen && (
<GlobalModel isOpen={isModalOpen} size="lg" closeModal={closeModal}> <GlobalModel isOpen={isModalOpen} size="lg" closeModal={closeModal}>
<AssignTask assignData={assigndata} onClose={closeModal} setAssigned={refreshWorkItem} /> <AssignTask
assignData={assigndata}
onClose={closeModal}
setAssigned={refreshWorkItem}
/>
</GlobalModel> </GlobalModel>
)} )}
{showModal && ( {showModal && (
<GlobalModel isOpen={showModal} size="lg" closeModal={()=>setShowModal(false)}> <GlobalModel
isOpen={showModal}
size="lg"
closeModal={() => setShowModal(false)}
>
<EditActivityModal <EditActivityModal
workItem={workItem} workItem={workItem}
workArea={forWorkArea} workArea={forWorkArea}
building={forBuilding} building={forBuilding}
floor={forFloor} floor={forFloor}
onClose={()=>setShowModal(false)} onClose={() => setShowModal(false)}
/> />
</GlobalModel> </GlobalModel>
)} )}
@ -167,7 +179,6 @@ const WorkItem = ({
: "NA"} : "NA"}
</td> </td>
<td className="text-center table-cell-small d-none d-md-table-cell"> <td className="text-center table-cell-small d-none d-md-table-cell">
<span className="fw-light"> <span className="fw-light">
{hasWorkItem {hasWorkItem
@ -195,9 +206,7 @@ const WorkItem = ({
<td className="text-center d-none d-md-table-cell"> <td className="text-center d-none d-md-table-cell">
{hasWorkItem {hasWorkItem
? `${ ? `${
NewWorkItem?.todaysAssigned ?? NewWorkItem?.todaysAssigned ?? workItem?.todaysAssigned ?? "0"
workItem?.todaysAssigned ??
"0"
}` }`
: "NA"} : "NA"}
</td> </td>
@ -251,7 +260,7 @@ const WorkItem = ({
<i <i
className="bx bxs-edit text-secondary cursor-pointer" className="bx bxs-edit text-secondary cursor-pointer"
title="Edit" title="Edit"
onClick={()=>setShowModal(true)} onClick={() => setShowModal(true)}
role="button" role="button"
></i> ></i>
<i <i
@ -293,7 +302,7 @@ const WorkItem = ({
<li> <li>
<a <a
className="dropdown-item d-flex align-items-center" className="dropdown-item d-flex align-items-center"
onClick={()=>setShowModal(true) } onClick={() => setShowModal(true)}
> >
<i className="bx bxs-edit text-secondary me-2"></i> Edit <i className="bx bxs-edit text-secondary me-2"></i> Edit
</a> </a>

View File

@ -6,7 +6,12 @@ import { useDispatch, useSelector } from "react-redux";
import { setProjectId } from "../slices/localVariablesSlice"; import { setProjectId } from "../slices/localVariablesSlice";
import EmployeeList from "../components/Directory/EmployeeList"; import EmployeeList from "../components/Directory/EmployeeList";
import eventBus from "../services/eventBus"; import eventBus from "../services/eventBus";
import {Mutation, useMutation, useQuery, useQueryClient} from "@tanstack/react-query"; import {
Mutation,
useMutation,
useQuery,
useQueryClient,
} from "@tanstack/react-query";
import showToast from "../services/toastService"; import showToast from "../services/toastService";
// export const useProjects = () => { // export const useProjects = () => {
@ -211,7 +216,7 @@ export const useProjects = () => {
error, error,
refetch, refetch,
} = useQuery({ } = useQuery({
queryKey: ['ProjectsList'], queryKey: ["ProjectsList"],
queryFn: async () => { queryFn: async () => {
const response = await ProjectRepository.getProjectList(); const response = await ProjectRepository.getProjectList();
return response.data; return response.data;
@ -227,84 +232,99 @@ export const useProjects = () => {
}; };
}; };
export const useEmployeesByProjectAllocated = (selectedProject) => export const useEmployeesByProjectAllocated = (selectedProject) => {
{ const {
const {data = [], isLoading, refetch, error} = useQuery( { data = [],
queryKey: ["empListByProjectAllocated", selectedProject ], isLoading,
queryFn: async () => refetch,
{ error,
const res = await ProjectRepository.getProjectAllocation( selectedProject ); } = useQuery({
return res.data || res queryKey: ["empListByProjectAllocated", selectedProject],
queryFn: async () => {
const res = await ProjectRepository.getProjectAllocation(selectedProject);
return res.data || res;
}, },
enabled: !!selectedProject, enabled: !!selectedProject,
onError: ( error ) => onError: (error) => {
{ showToast(
showToast(error.message || "Error while Fetching project Allocated Employees", "error"); error.message || "Error while Fetching project Allocated Employees",
} "error"
} ) );
},
});
return { return {
projectEmployees: data, projectEmployees: data,
loading:isLoading, loading: isLoading,
error, error,
refetch refetch,
} };
} };
export const useProjectDetails = ( projectId,isAuto = true ) => export const useProjectDetails = (projectId, isAuto = true) => {
{ const {
const {data: projects_Details, isLoading, error, refetch} = useQuery( { data: projects_Details,
queryKey: [ "projectInfo", projectId ], isLoading,
queryFn: async () => error,
{ refetch,
const res = await ProjectRepository.getProjectByprojectId( projectId ); } = useQuery({
queryKey: ["projectInfo", projectId],
queryFn: async () => {
const res = await ProjectRepository.getProjectByprojectId(projectId);
return res.data || res; return res.data || res;
}, },
enabled: !!projectId && isAuto, enabled: !!projectId && isAuto,
onError: ( error ) => onError: (error) => {
{ showToast(
showToast(error.message || "Error while Fetching project Details", "error"); error.message || "Error while Fetching project Details",
} "error"
} ) );
return { projects_Details, loading:isLoading, error, refetch }; },
} });
return { projects_Details, loading: isLoading, error, refetch };
};
export const useProjectsByEmployee = (employeeId) => export const useProjectsByEmployee = (employeeId) => {
{ const {
const { data:projectNameList =[],isLoading,error,refetch} = useQuery( { data: projectNameList = [],
queryKey: [ "ProjectsByEmployee", employeeId ], isLoading,
queryFn: async () => error,
{ refetch,
const res = await ProjectRepository.getProjectsByEmployee( employeeId ); } = useQuery({
queryKey: ["ProjectsByEmployee", employeeId],
queryFn: async () => {
const res = await ProjectRepository.getProjectsByEmployee(employeeId);
return res.data || res; return res.data || res;
}, },
enabled: !!employeeId, enabled: !!employeeId,
onError: ( error ) => onError: (error) => {
{ showToast(
showToast(error.message || "Error while Fetching project Employee", "error"); error.message || "Error while Fetching project Employee",
} "error"
}) );
return {projectList, loading:isLoading,error,refetch } },
} });
return { projectList, loading: isLoading, error, refetch };
};
export const useProjectName = () => export const useProjectName = () => {
{ const {
const {data = [],isLoading,error,refetch} = useQuery( { data = [],
queryKey: [ "basicProjectNameList" ], isLoading,
queryFn: async () => error,
{ refetch,
} = useQuery({
queryKey: ["basicProjectNameList"],
queryFn: async () => {
const res = await ProjectRepository.projectNameList(); const res = await ProjectRepository.projectNameList();
return res.data || res; return res.data || res;
}, },
onError: ( error ) => onError: (error) => {
{
showToast(error.message || "Error while Fetching project Name", "error"); showToast(error.message || "Error while Fetching project Name", "error");
} },
} ) });
return {projectNames:data,loading:isLoading,Error:error,refetch} return { projectNames: data, loading: isLoading, Error: error, refetch };
} };
export const useProjectInfra = (projectId) => { export const useProjectInfra = (projectId) => {
const { const {
@ -317,7 +337,7 @@ export const useProjectInfra = (projectId) => {
const res = await ProjectRepository.getProjectInfraByproject(projectId); const res = await ProjectRepository.getProjectInfraByproject(projectId);
return res.data; return res.data;
}, },
enabled: !!projectId , enabled: !!projectId,
onError: (error) => { onError: (error) => {
showToast(error.message || "Error while fetching project infra", "error"); showToast(error.message || "Error while fetching project infra", "error");
}, },
@ -326,30 +346,27 @@ export const useProjectInfra = (projectId) => {
return { projectInfra, isLoading, error }; return { projectInfra, isLoading, error };
}; };
export const useProjectTasks = (workAreaId, IsExpandedArea = false) => {
export const useProjectTasks = (workAreaId,IsExpandedArea=false) => const {
{ data: ProjectTaskList,
const { data:ProjectTaskList,isLoading,error } = useQuery( { isLoading,
queryKey: [ "WorkItems",workAreaId ], error,
queryFn: async () => } = useQuery({
{ queryKey: ["WorkItems", workAreaId],
queryFn: async () => {
const res = await ProjectRepository.getProjectTasksByWorkArea(workAreaId); const res = await ProjectRepository.getProjectTasksByWorkArea(workAreaId);
return res.data; return res.data;
}, },
enabled: !!workAreaId && !!IsExpandedArea, enabled: !!workAreaId && !!IsExpandedArea,
onError: ( error ) => onError: (error) => {
{
showToast(error.message || "Error while Fetching project Tasks", "error"); showToast(error.message || "Error while Fetching project Tasks", "error");
} },
} ) });
return {ProjectTaskList,isLoading,error} return { ProjectTaskList, isLoading, error };
} };
// -- -------------Mutation------------------------------- // -- -------------Mutation-------------------------------
export const useCreateProject = ({ onSuccessCallback }) => { export const useCreateProject = ({ onSuccessCallback }) => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
@ -360,8 +377,8 @@ export const useCreateProject = ({ onSuccessCallback }) => {
}, },
onSuccess: (data) => { onSuccess: (data) => {
// Invalidate the cache // Invalidate the cache
queryClient.invalidateQueries( {queryKey: [ 'ProjectsList' ]} ); queryClient.invalidateQueries({ queryKey: ["ProjectsList"] });
queryClient.invalidateQueries({queryKey:['basicProjectNameList']}); queryClient.invalidateQueries({ queryKey: ["basicProjectNameList"] });
// Emit event for consumers (like useProjects or others) // Emit event for consumers (like useProjects or others)
eventBus.emit("project", { eventBus.emit("project", {
@ -381,27 +398,19 @@ export const useCreateProject = ({ onSuccessCallback }) => {
}); });
}; };
export const useUpdateProject = ({ onSuccessCallback }) => { export const useUpdateProject = ({ onSuccessCallback }) => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const { const { mutate, isPending, isSuccess, isError } = useMutation({
mutate, mutationFn: async ({ projectId, updatedData }) => {
isPending,
isSuccess,
isError,
} = useMutation({
mutationFn: async ( {projectId, updatedData} ) =>
{
return await ProjectRepository.updateProject(projectId, updatedData); return await ProjectRepository.updateProject(projectId, updatedData);
}, },
onSuccess: ( data, variables ) => onSuccess: (data, variables) => {
{
const { projectId } = variables; const { projectId } = variables;
queryClient.invalidateQueries({queryKey:["ProjectsList"]}); queryClient.invalidateQueries({ queryKey: ["ProjectsList"] });
queryClient.invalidateQueries( {queryKey: [ "projectInfo", projectId ]} ); queryClient.invalidateQueries({ queryKey: ["projectInfo", projectId] });
queryClient.invalidateQueries({queryKey:['basicProjectNameList']}); queryClient.invalidateQueries({ queryKey: ["basicProjectNameList"] });
eventBus.emit("project", { eventBus.emit("project", {
keyword: "Update_Project", keyword: "Update_Project",
@ -415,9 +424,8 @@ export const useUpdateProject = ({ onSuccessCallback }) => {
} }
}, },
onError: ( error ) => onError: (error) => {
{ console.log(error);
console.log(error)
showToast(error?.message || "Error while updating project", "error"); showToast(error?.message || "Error while updating project", "error");
}, },
}); });
@ -430,20 +438,16 @@ export const useUpdateProject = ({ onSuccessCallback }) => {
}; };
}; };
export const useManageProjectInfra = ({ onSuccessCallback }) => {
export const useManageProjectInfra = ( {onSuccessCallback} ) =>
{
const queryClient = useQueryClient(); const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: async ( {infraObject, projectId} ) => mutationFn: async ({ infraObject, projectId }) => {
{
return await ProjectRepository.manageProjectInfra(infraObject); return await ProjectRepository.manageProjectInfra(infraObject);
}, },
onSuccess: ( data, variables ) => onSuccess: (data, variables) => {
{
const { projectId } = variables; const { projectId } = variables;
queryClient.invalidateQueries({queryKey:["ProjectInfra", projectId]}); queryClient.invalidateQueries({ queryKey: ["ProjectInfra", projectId] });
if (onSuccessCallback) onSuccessCallback(data,variables); if (onSuccessCallback) onSuccessCallback(data, variables);
}, },
onError: (error) => { onError: (error) => {
showToast(error.message || "Failed to update Project Infra", "error"); showToast(error.message || "Failed to update Project Infra", "error");
@ -451,39 +455,36 @@ export const useManageProjectInfra = ( {onSuccessCallback} ) =>
}); });
}; };
export const useManageProjectAllocation = ({ export const useManageProjectAllocation = ({
onSuccessCallback, onSuccessCallback,
onErrorCallback, onErrorCallback,
}) => { }) => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const { const { mutate, isPending, isSuccess, isError } = useMutation({
mutate, mutationFn: async ({ items }) => {
isPending,
isSuccess,
isError,
} = useMutation({
mutationFn: async ( {items} ) =>
{
const response = await ProjectRepository.manageProjectAllocation(items); const response = await ProjectRepository.manageProjectAllocation(items);
return response.data; return response.data;
}, },
onSuccess: (data, variables, context) => { onSuccess: (data, variables, context) => {
queryClient.invalidateQueries({queryKey:['empListByProjectAllocated']}); queryClient.invalidateQueries({
queryClient.removeQueries({queryKey:["projectEmployees"]}) queryKey: ["empListByProjectAllocated"],
});
queryClient.removeQueries({ queryKey: ["projectEmployees"] });
if (variables?.added) { if (variables?.added) {
showToast('Employee Assigned Successfully', 'success'); showToast("Employee Assigned Successfully", "success");
} else { } else {
showToast('Removed Employee Successfully', 'success'); showToast("Removed Employee Successfully", "success");
} }
if (onSuccessCallback) onSuccessCallback(data, context); if (onSuccessCallback) onSuccessCallback(data, context);
}, },
onError: (error) => { onError: (error) => {
const message = const message =
error?.response?.data?.message || error.message || 'Error occurred during API call'; error?.response?.data?.message ||
showToast(message, 'error'); error.message ||
"Error occurred during API call";
showToast(message, "error");
if (onErrorCallback) onErrorCallback(error); if (onErrorCallback) onErrorCallback(error);
}, },
}); });
@ -496,48 +497,199 @@ export const useManageProjectAllocation = ({
}; };
}; };
export const useManageTask = ({onSuccessCallback}) => export const useManageTask = ({ onSuccessCallback }) => {
{
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const selectedProject = useSelector(
(store) => store.localVariables.projectId
);
return useMutation({
mutationFn: async ({
payload,
PreviousPlannedWork,
previousCompletedWork,
buildingId,
floorId,
workAreaId,
}) => await ProjectRepository.manageProjectTasks(payload),
onSuccess: (data, variables) => {
const {
workAreaId,
buildingId,
floorId,
PreviousPlannedWork,
previousCompletedWork,
} = variables;
queryClient.invalidateQueries({ queryKey: ["WorkItems"] });
const getPlannedDelta = (previous, current) => current - previous;
queryClient.setQueryData(["ProjectInfra", selectedProject], (oldData) => {
if (!oldData) return oldData;
const { workAreaId, floorId, buildingId } = variables;
const updatedData = JSON.parse(JSON.stringify(oldData));
return updatedData.map((building) => {
if (building.id !== buildingId) return building;
return {
...building,
floors: building.floors.map((floor) => {
if (floor.id !== floorId) return floor;
return useMutation( { return {
mutationFn: async ( payload ) => await ProjectRepository.manageProjectTasks( payload ), ...floor,
onSuccess: ( data, variables ) => workAreas: floor.workAreas.map((area) => {
{ if (area.id !== workAreaId) return area;
queryClient.invalidateQueries({ queryKey: ["WorkItems"] })
const previousPlanned = PreviousPlannedWork ?? 0;
const currentPlanned =
data?.data[0]?.workItem.plannedWork ?? 0;
const plannedWorkDelta = getPlannedDelta(
previousPlanned,
currentPlanned
);
const updatedPlannedWork =
(area.plannedWork ?? 0) + plannedWorkDelta;
const previousCompleted = previousCompletedWork;
const currentCompleted =
data?.data[0]?.workItem.completedWork ?? 0;
const completedWorkDelta = getPlannedDelta(
previousCompleted,
currentCompleted
);
const updatedCompletedWork =
(area.completedWork ?? 0) + completedWorkDelta;
return {
...area,
plannedWork: updatedPlannedWork,
completedWork: updatedCompletedWork,
};
}),
};
}),
};
});
});
queryClient.setQueryData(["ProjectsList"], (projects) => {
if (!projects) return projects;
return projects.map((project) => {
if (project.id !== selectedProject) return project;
const previousPlanned = PreviousPlannedWork ?? 0;
const currentPlanned = data?.data[0]?.workItem.plannedWork ?? 0;
const plannedWorkDelta = getPlannedDelta(
previousPlanned,
currentPlanned
);
const updatedPlannedWork =
(project.plannedWork ?? 0) + plannedWorkDelta;
const previousCompleted = previousCompletedWork;
const currentCompleted = data?.data[0]?.workItem.completedWork ?? 0;
const completedWorkDelta = getPlannedDelta(
previousCompleted,
currentCompleted
);
const updatedCompletedWork =
(project.completedWork ?? 0) + completedWorkDelta;
return {
...project,
plannedWork: updatedPlannedWork,
completedWork: updatedCompletedWork,
};
});
});
if (onSuccessCallback) onSuccessCallback(data); if (onSuccessCallback) onSuccessCallback(data);
}, },
onError: (error) => onError: (error) => {
{
const message = const message =
error?.response?.data?.message || error.message || 'Error occurred during API call'; error?.response?.data?.message ||
showToast(message, 'error'); error.message ||
} "Error occurred during API call";
showToast(message, "error");
}) },
} });
};
export const useDeleteProjectTask = (onSuccessCallback) => { export const useDeleteProjectTask = (onSuccessCallback) => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const selectedProject = useSelector(
(store) => store.localVariables.projectId
);
return useMutation({ return useMutation({
mutationFn: async ( {workItemId, workAreaId} ) => mutationFn: async ({
{ workItemId,
workAreaId,
completedTask,
plannedTask,
}) => {
return await ProjectRepository.deleteProjectTask(workItemId); return await ProjectRepository.deleteProjectTask(workItemId);
}, },
onSuccess: ( _, variables ) => onSuccess: (_, variables) => {
{ const { completedTask, plannedTask, workAreaId, buildingId, floorId } =
variables;
queryClient.invalidateQueries({
queryKey: ["WorkItems", variables.workAreaId],
});
queryClient.setQueryData(["ProjectInfra", selectedProject], (oldData) => {
if (!oldData) return oldData;
const { workAreaId, floorId, buildingId, plannedTask, completedTask } =
variables;
const updatedData = JSON.parse(JSON.stringify(oldData));
return updatedData.map((building) => {
if (building.id !== buildingId) return building;
return {
...building,
floors: building.floors.map((floor) => {
if (floor.id !== floorId) return floor;
return {
...floor,
workAreas: floor.workAreas.map((area) => {
if (area.id !== workAreaId) return area;
return {
...area,
plannedWork: (area.plannedWork ?? 0) - plannedTask,
completedWork: (area.completedWork ?? 0) - completedTask,
};
}),
};
}),
};
});
});
queryClient.setQueryData(["ProjectsList"], (projects) => {
if (!projects) return projects;
return projects.map((project) => {
if (project.id !== selectedProject) return project;
return {
...project,
plannedWork: (project.plannedWork ?? 0) - plannedTask,
completedWork: (project.completedWork ?? 0) - completedTask,
};
});
});
showToast("Task deleted successfully", "success"); showToast("Task deleted successfully", "success");
queryClient.invalidateQueries({queryKey:[ "WorkItems",variables.workAreaId]});
if (onSuccessCallback) onSuccessCallback(); if (onSuccessCallback) onSuccessCallback();
}, },
onError: (error) => { onError: (error) => {
showToast( showToast(
error?.response?.data?.message || error.message || "Failed to delete task", error?.response?.data?.message ||
error.message ||
"Failed to delete task",
"error" "error"
); );
if (onSuccessCallback) onSuccessCallback(); if (onSuccessCallback) onSuccessCallback();
}, },
}); });
}; };