Project List - update project plannedWork and completedWork based on task changes

This commit is contained in:
pramod mahajan 2025-07-14 00:51:32 +05:30
parent 5f54f5e29a
commit 9aa49989de
5 changed files with 281 additions and 404 deletions

View File

@ -54,7 +54,6 @@ export const ReportTask = ({ report, closeModal }) => {
}, [report, reset]); }, [report, reset]);
const onSubmit = (data) => { const onSubmit = (data) => {
const reportData = { const reportData = {
...data, ...data,
id: report?.id, id: report?.id,
@ -62,7 +61,12 @@ export const ReportTask = ({ report, closeModal }) => {
checkList: [], checkList: [],
}; };
reportTask({ reportData, workAreaId: report?.workItem?.workArea?.id }); reportTask({
reportData,
workAreaId: report?.workItem?.workArea?.id,
buildingId: report?.workItem?.workArea?.floor?.building.id,
floorId: report?.workItem?.workArea?.floor?.id,
});
}; };
const handleClose = () => { const handleClose = () => {
closeModal(); closeModal();
@ -181,7 +185,11 @@ export const ReportTask = ({ report, closeModal }) => {
</div> </div>
</div> </div>
<div className="col-12 text-center my-2"> <div className="col-12 text-center my-2">
<button type="submit" className="btn btn-sm btn-primary me-3" disabled={isPending}> <button
type="submit"
className="btn btn-sm btn-primary me-3"
disabled={isPending}
>
{isPending ? "Please wait" : "Submit Report"} {isPending ? "Please wait" : "Submit Report"}
</button> </button>
<button <button

View File

@ -116,7 +116,8 @@ useEffect(() => {
floorId: floor?.id, floorId: floor?.id,
workAreaId: workArea?.id, workAreaId: workArea?.id,
}; };
UpdateTask([payload]) let plannedTask = workItem?.workItem?.plannedWork || workItem?.plannedWork || 0
UpdateTask({payload:[payload],PreviousPlannedWork:plannedTask})
} }
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

@ -97,7 +97,7 @@ const TaskModel = ({ project, onSubmit, onClose }) => {
const onSubmitForm = async (data) => { const onSubmitForm = async (data) => {
const payload = [data]; const payload = [data];
CreateTask(payload); CreateTask({payload,PreviousPlannedWork:0});
}; };
return ( return (
@ -177,8 +177,8 @@ const TaskModel = ({ project, onSubmit, onClose }) => {
className="form-select form-select-sm" className="form-select form-select-sm"
{...register("activityID")} {...register("activityID")}
> >
<option value="">Select Activity</option> <option value={activityLoading ? "Loading.....":" "}>{!activityLoading && "Select Activity"}</option>
{activityData.map((a) => ( {activityData?.length > 0 && activityData.map((a) => (
<option key={a.id} value={a.id}> <option key={a.id} value={a.id}>
{a.activityName} {a.activityName}
</option> </option>
@ -197,7 +197,8 @@ const TaskModel = ({ project, onSubmit, onClose }) => {
className="form-select form-select-sm" className="form-select form-select-sm"
{...register("workCategoryId")} {...register("workCategoryId")}
> >
{categoryData.map((c) => ( <option value={categoryLoading ? "Loading.....":" "}>{!categoryLoading && "Select Activity"}</option>
{categoryData?.length > 0 && categoryData.map((c) => (
<option key={c.id} value={c.id}> <option key={c.id} value={c.id}>
{c.name} {c.name}
</option> </option>
@ -263,13 +264,14 @@ const TaskModel = ({ project, onSubmit, onClose }) => {
<button <button
type="submit" type="submit"
className="btn btn-sm btn-primary me-3" className="btn btn-sm btn-primary me-3"
disabled={isSubmitting} disabled={isPending}
> >
{isSubmitting ? "Please Wait..." : "Add Task"} {isPending ? "Please Wait..." : "Add Task"}
</button> </button>
<button <button
type="button" type="button"
className="btn btn-sm btn-label-secondary" className="btn btn-sm btn-label-secondary"
disabled={isPending}
onClick={onClose} onClick={onClose}
> >
Cancel Cancel

View File

@ -6,200 +6,14 @@ 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 = () => {
// const loggedUser = useSelector((store) => store.globalVariables.loginUser);
// const [projects, setProjects] = useState([]);
// const [loading, setLoading] = useState(true);
// const [error, setError] = useState("");
// const fetchData = async () => {
// const projectIds = loggedUser?.projects || [];
// const filterProjects = (projectsList) => {
// return projectsList
// .filter((proj) => projectIds.includes(String(proj.id)))
// .sort((a, b) => a?.name?.localeCompare(b.name));
// };
// const projects_cache = getCachedData("projectslist");
// if (!projects_cache) {
// setLoading(true);
// try {
// const response = await ProjectRepository.getProjectList();
// const allProjects = response.data;
// const filtered = filterProjects(allProjects);
// setProjects(filtered);
// cacheData("projectslist", allProjects);
// } catch (err) {
// setError("Failed to fetch data.");
// } finally {
// setLoading(false);
// }
// } else {
// if (!projects.length) {
// const filtered = filterProjects(projects_cache);
// setProjects(filtered);
// setLoading(false);
// }
// }
// };
// useEffect(() => {
// if (loggedUser) {
// fetchData();
// }
// }, [loggedUser]);
// return { projects, loading, error, refetch: fetchData };
// };
// export const useEmployeesByProjectAllocated = (selectedProject) => {
// const [projectEmployees, setEmployeeList] = useState([]);
// const [loading, setLoading] = useState(true);
// const [projects, setProjects] = useState([]);
// const fetchData = async (projectid) => {
// try {
// let EmployeeByProject_Cache = getCachedData("empListByProjectAllocated");
// if (
// !EmployeeByProject_Cache ||
// !EmployeeByProject_Cache.projectId === projectid
// ) {
// let response = await ProjectRepository.getProjectAllocation(projectid);
// setEmployeeList(response.data);
// cacheData("empListByProjectAllocated", {
// data: response.data,
// projectId: projectid,
// });
// setLoading(false);
// } else {
// setEmployeeList(EmployeeByProject_Cache.data);
// setLoading(false);
// }
// } catch (err) {
// setError("Failed to fetch data.");
// setLoading(false);
// }
// };
// useEffect(() => {
// if (selectedProject) {
// fetchData(selectedProject);
// }
// }, [selectedProject]);
// return { projectEmployees, loading, projects };
// };
// export const useProjectDetails = (projectId) => {
// const { profile } = useProfile();
// const [projects_Details, setProject_Details] = useState(null);
// const [loading, setLoading] = useState(true);
// const [error, setError] = useState("");
// const fetchData = async () => {
// setLoading(true);
// const project_cache = getCachedData("projectInfo");
// if (!project_cache || project_cache?.projectId != projectId) {
// ProjectRepository.getProjectByprojectId(projectId)
// .then((response) => {
// setProject_Details(response.data);
// cacheData("projectInfo", {
// projectId: projectId,
// data: response.data,
// });
// setLoading(false);
// })
// .catch((error) => {
// console.error(error);
// setError("Failed to fetch data.");
// setLoading(false);
// });
// } else {
// setProject_Details(project_cache.data);
// setLoading(false);
// }
// };
// useEffect(() => {
// if (profile && projectId != undefined) {
// fetchData();
// }
// }, [projectId, profile]);
// return { projects_Details, loading, error, refetch: fetchData };
// };
// export const useProjectsByEmployee = (employeeId) => {
// const [projectList, setProjectList] = useState([]);
// const [loading, setLoading] = useState(false);
// const [error, setError] = useState("");
// const fetchProjects = async (id) => {
// try {
// setLoading(true);
// setError(""); // clear previous error
// const res = await ProjectRepository.getProjectsByEmployee(id);
// setProjectList(res.data);
// cacheData("ProjectsByEmployee", { data: res.data, employeeId: id });
// setLoading(false);
// } catch (err) {
// setError(err?.message || "Failed to fetch projects");
// setLoading(false);
// }
// };
// useEffect(() => {
// if (!employeeId) return;
// const cache_project = getCachedData("ProjectsByEmployee");
// if (!cache_project?.data || cache_project?.employeeId !== employeeId) {
// fetchProjects(employeeId);
// } else {
// setProjectList(cache_project.data);
// }
// }, [employeeId]);
// return {
// projectList,
// loading,
// error,
// refetch: fetchProjects,
// };
// };
// export const useProjectName = () => {
// const [loading, setLoading] = useState(true);
// const [projectNames, setProjectName] = useState([]);
// const [Error, setError] = useState();
// const dispatch = useDispatch();
// const fetchData = async () => {
// try {
// let response = await ProjectRepository.projectNameList();
// setProjectName(response.data);
// cacheData("basicProjectNameList", response.data);
// setLoading(false);
// if(response.data.length === 1){
// dispatch(setProjectId(response.data[0]?.id));
// }
// } catch (err) {
// setError("Failed to fetch data.");
// setLoading(false);
// }
// };
// useEffect(() => {
// fetchData();
// }, []);
// return { projectNames, loading, Error, fetchData };
// };
// ------------------------------Query------------------- // ------------------------------Query-------------------
export const useProjects = () => { export const useProjects = () => {
@ -211,7 +25,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,97 +41,112 @@ 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 {
data: projectInfra, data: projectInfra,
isLoading, isLoading,
error, error,
} = useQuery({ } = useQuery({
queryKey: ["ProjectInfra", projectId], queryKey: ["ProjectInfra", projectId],
queryFn: async () => { queryFn: async () => {
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 +155,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 +186,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 +207,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 +233,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 +247,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 +264,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 +306,74 @@ 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 }) =>
await ProjectRepository.manageProjectTasks(payload),
onSuccess: (data, variables) => {
const { PreviousPlannedWork } = variables;
queryClient.invalidateQueries({ queryKey: ["WorkItems"] });
const getPlannedDelta = (previous, current) => current - previous;
queryClient.setQueryData(["ProjectsList"], (projects) => {
if (!projects) return projects;
return projects.map((project) => {
if (project.id !== selectedProject) return project;
const previous = PreviousPlannedWork ?? 0;
const current = data?.data[0]?.workItem.plannedWork ?? 0;
const plannedWorkDelta = getPlannedDelta(previous, current);
const updatedPlannedWork =
(project.plannedWork ?? 0) + plannedWorkDelta;
return {
...project,
plannedWork: updatedPlannedWork,
};
});
});
return useMutation( {
mutationFn: async ( payload ) => await ProjectRepository.manageProjectTasks( payload ),
onSuccess: ( data, variables ) =>
{
queryClient.invalidateQueries({ queryKey: ["WorkItems"] })
if (onSuccessCallback) onSuccessCallback(data); if (onSuccessCallback) onSuccessCallback(data);
}, },
onError: (error) => onError: (error) => {
{ const message =
const message = error?.response?.data?.message ||
error?.response?.data?.message || error.message || 'Error occurred during API call'; error.message ||
showToast(message, 'error'); "Error occurred during API call";
} showToast(message, "error");
},
}) });
} };
export const useDeleteProjectTask = (onSuccessCallback) => { export const useDeleteProjectTask = (onSuccessCallback) => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: async ( {workItemId, workAreaId} ) => mutationFn: async ({ workItemId, workAreaId }) => {
{
return await ProjectRepository.deleteProjectTask(workItemId); return await ProjectRepository.deleteProjectTask(workItemId);
}, },
onSuccess: ( _, variables ) => onSuccess: (_, variables) => {
{
showToast("Task deleted successfully", "success"); showToast("Task deleted successfully", "success");
queryClient.invalidateQueries({queryKey:[ "WorkItems",variables.workAreaId]}); 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();
}, },
}); });
}; };

View File

@ -1,11 +1,10 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { TasksRepository } from "../repositories/TaskRepository"; import { TasksRepository } from "../repositories/TaskRepository";
import { cacheData, getCachedData } from "../slices/apiDataManager"; import { cacheData, getCachedData } from "../slices/apiDataManager";
import {MasterRespository} from "../repositories/MastersRepository"; import { MasterRespository } from "../repositories/MastersRepository";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import showToast from "../services/toastService"; import showToast from "../services/toastService";
import {useSelector} from "react-redux"; import { useSelector } from "react-redux";
// ---------Query--------------------------------- // ---------Query---------------------------------
@ -28,7 +27,6 @@ export const useTaskList = (projectId, dateFrom, toDate) => {
return response.data; return response.data;
}, },
enabled, enabled,
}); });
return { TaskList, loading, error, refetch }; return { TaskList, loading, error, refetch };
@ -46,7 +44,7 @@ export const useTaskById = (TaskId) => {
const res = await TasksRepository.getTaskById(TaskId); const res = await TasksRepository.getTaskById(TaskId);
return res.data; return res.data;
}, },
enabled: !!TaskId, enabled: !!TaskId,
}); });
return { Task, loading, error, refetch }; return { Task, loading, error, refetch };
@ -75,47 +73,81 @@ export const useAuditStatus = () => {
const res = await MasterRespository.getAuditStatus(); const res = await MasterRespository.getAuditStatus();
return res.data; return res.data;
}, },
}); });
return { status, loading, error, refetch }; return { status, loading, error, refetch };
}; };
// ---------====================Mutation================------------------
const toDate = new Date().toISOString().split("T")[0];
const dateFrom = new Date(Date.now() - 6 * 24 * 60 * 60 * 1000)
.toISOString()
.split("T")[0];
// -----------------------Mutation------------------------ export const useReportTask = ({ onSuccessCallback, onErrorCallback } = {}) => {
const toDate = new Date().toISOString().split('T')[0]; const selectedProject = useSelector(
const dateFrom = new Date(Date.now() - 6 * 24 * 60 * 60 * 1000).toISOString().split('T')[0]; (store) => store.localVariables.projectId
);
export const useReportTask = ( {onSuccessCallback, onErrorCallback} = {} ) =>
{
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const { const { mutate, isPending, isSuccess, isError, error } = useMutation({
mutate, mutationFn: async ({ reportData, workAreaId }) => {
isPending,
isSuccess,
isError,
error,
} = useMutation({
mutationFn: async ( {reportData,workAreaId} ) =>
{
debugger
return await TasksRepository.reportTask(reportData); return await TasksRepository.reportTask(reportData);
}, },
onSuccess: ( data, variables ) => onSuccess: (data, variables) => {
{ const { workAreaId, buildingId, floorId } = variables;
const {workAreaId} = variables; queryClient.invalidateQueries({ queryKey: ["taskList"] });
queryClient.invalidateQueries( {queryKey: [ "taskList" ]} ); queryClient.invalidateQueries({ queryKey: ["WorkItems", workAreaId] });
queryClient.invalidateQueries( {queryKey: [ "WorkItems", workAreaId ]} ); queryClient.setQueryData(["ProjectInfra", selectedProject], (oldData) => {
queryClient.invalidateQueries( {queryKey: [ 'ProjectsList' ]} ); if (!oldData) return oldData;
showToast( "Task Reported Successfully.", "success" ); 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 {
...floor,
workAreas: floor.workAreas.map((area) => {
if (area.id !== workAreaId) return area;
return {
...area,
completedWork:
(area.completedWork ?? 0) +
(data?.data?.completedTask ?? 0),
};
}),
};
}),
};
});
});
queryClient.setQueryData(["ProjectsList"], (projects) => {
if (!projects) return projects;
const updatedProject = JSON.parse(JSON.stringify(projects));
return updatedProject.map((project) => {
if (project.id !== selectedProject) return project;
return {
...project,
completedWork:
(project.completedWork ?? 0) + (data?.data?.completedTask ?? 0),
};
});
});
showToast("Task Reported Successfully.", "success");
if (onSuccessCallback) onSuccessCallback(data); if (onSuccessCallback) onSuccessCallback(data);
}, },
onError: (error) => { onError: (error) => {
const msg = const msg =
error?.response?.data?.message || error.message || "Error occurred during API call"; error?.response?.data?.message ||
showToast( msg, "error" ); error.message ||
"Error occurred during API call";
showToast(msg, "error");
}, },
}); });
@ -145,16 +177,12 @@ export const useSubmitTaskComment = ({ actionAllow, onSuccessCallback }) => {
return response.data; return response.data;
}, },
onSuccess: ( data,variables ) => onSuccess: (data, variables) => {
{
const workAreaId = variables?.commentsData?.workItem?.workArea?.id; const workAreaId = variables?.commentsData?.workItem?.workArea?.id;
queryClient.invalidateQueries({ queryKey: ["taskList"] }); queryClient.invalidateQueries({ queryKey: ["taskList"] });
if (actionAllow) { if (actionAllow) {
showToast( "Review submitted successfully.", "success" ); showToast("Review submitted successfully.", "success");
} else {
} else
{
showToast("Comment sent successfully.", "success"); showToast("Comment sent successfully.", "success");
} }
@ -162,7 +190,10 @@ export const useSubmitTaskComment = ({ actionAllow, onSuccessCallback }) => {
}, },
onError: (error) => { onError: (error) => {
const msg = error?.response?.data?.message || error.message || "Error during API call"; const msg =
error?.response?.data?.message ||
error.message ||
"Error during API call";
showToast(msg, "error"); showToast(msg, "error");
}, },
}); });
@ -170,24 +201,23 @@ export const useSubmitTaskComment = ({ actionAllow, onSuccessCallback }) => {
return { submitComment: mutate, isPending }; return { submitComment: mutate, isPending };
}; };
export const useCreateTask = ( {onSuccessCallback, onErrorCallback} = {} ) => export const useCreateTask = ({ onSuccessCallback, onErrorCallback } = {}) => {
{
const queryClient = useQueryClient(); const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: async ({payload,workAreaId}) => { mutationFn: async ({ payload, workAreaId }) => {
return await TasksRepository.assignTask(payload); return await TasksRepository.assignTask(payload);
}, },
onSuccess: ( _, variables ) => onSuccess: (_, variables) => {
{ queryClient.invalidateQueries({ queryKey: ["taskList"] });
queryClient.invalidateQueries( {queryKey: [ "taskList" ]} ); queryClient.invalidateQueries({
queryClient.invalidateQueries( {queryKey: [ "WorkItems", variables?.workAreaId ]} ); queryKey: ["WorkItems", variables?.workAreaId],
showToast( "Task Assigned Successfully.", "success" ); });
showToast("Task Assigned Successfully.", "success");
if (onSuccessCallback) onSuccessCallback(variables); if (onSuccessCallback) onSuccessCallback(variables);
}, },
onError: ( error ) => onError: (error) => {
{
showToast("Something went wrong. Please try again.", "error"); showToast("Something went wrong. Please try again.", "error");
if (onErrorCallback) onErrorCallback(error); if (onErrorCallback) onErrorCallback(error);
}, },
}); });
}; };