React Query Integration for Server State Sync in Clinet #245

Merged
admin merged 60 commits from react-query into main 2025-07-11 11:32:19 +00:00
3 changed files with 166 additions and 308 deletions
Showing only changes of commit e6d6f0ac30 - Show all commits

View File

@ -1,33 +1,34 @@
import React, { useState,useEffect } from "react";
import React, { useState, useEffect } from "react";
import { formatDate } from "../../utils/dateUtils";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import showToast from "../../services/toastService";
import { TasksRepository } from "../../repositories/TaskRepository";
import {useReportTask} from "../../hooks/useTasks";
import { useReportTask } from "../../hooks/useTasks";
export const ReportTask = ({ report, closeModal }) => {
const [ loading, setloading ] = useState( false );
const [loading, setloading] = useState(false);
const { mutate: reportTask, isPending } = useReportTask({
onSuccessCallback: () => {
// refetch();
reset();
setloading(false);
closeModal();
},
onErrorCallback: () => {
setloading(false);
},
} );
onSuccessCallback: () => {
reset();
setloading(false);
closeModal();
},
onErrorCallback: () => {
setloading(false);
},
});
const maxPending =
report?.workItem?.plannedWork - report?.workItem?.completedWork;
const schema = z.object({
completedTask: z
.preprocess(
(val) => (val === "" || val === null || Number.isNaN(val) ? undefined : Number(val)),
completedTask: z.preprocess(
(val) =>
val === "" || val === null || Number.isNaN(val)
? undefined
: Number(val),
z
.number({
required_error: "Completed Work must be a number",
@ -38,215 +39,165 @@ export const ReportTask = ({ report, closeModal }) => {
message: `Completed task cannot exceed total pending tasks: ${maxPending}`,
})
),
comment: z.string().min(1, "Comment cannot be empty"),
});
comment: z.string().min(1, "Comment cannot be empty"),
});
const {
register,
handleSubmit,
formState: {errors},
reset
formState: { errors },
reset,
} = useForm({
resolver: zodResolver(schema),
defaultValues: { completedTask: 0, comment: "" },
});
useEffect(() => {
if (report) {
reset({ completedTask: 0, comment: "" });
}
}, [report, reset]);
// const onSubmit = async (data) => {
// try {
// setloading(true);
// const reportData = {
// ...data,
// id: report?.id,
// reportedDate: new Date().toISOString(),
// checkList: [],
// };
// let response = await TasksRepository.reportTask(reportData);
// showToast("Task Reported Successfully.", "success");
// refetch();
// reset()
// setloading(false);
// closeModal();
// } catch ( error )
// {
// const msg = error.response.data.message || error.message || "Error Occur During Api Call"
// showToast(msg, "error");
// }
// }
useEffect(() => {
if (report) {
reset({ completedTask: 0, comment: "" });
}
}, [report, reset]);
const onSubmit = (data) => {
setloading(true);
const reportData = {
...data,
id: report?.id,
reportedDate: new Date().toISOString(),
checkList: [],
};
setloading(true);
const reportData = {
...data,
id: report?.id,
reportedDate: new Date().toISOString(),
checkList: [],
};
reportTask(reportData);
};
reportTask({ reportData, workAreaId: report?.workItem?.workArea?.id });
};
const handleClose = () => {
closeModal();
reset();
};
return (
<div className="container m-0">
<div className="text-center">
<p className="fs-6 fw-semibold">Report Task</p>
</div>
<div className="mb-1 row text-start">
<label
htmlFor="html5-text-input"
className="col-md-4 col-form-label"
>
Assigned Date :{" "}
</label>
<div className="col-md-8 text-start">
<label className="col-md-2 col-form-label">
{formatDate(report?.assignmentDate)}
</label>
</div>
</div>
<div className="mb-1 row text-start">
<label
htmlFor="html5-search-input"
className="col-md-4 col-form-label"
>
Assigned By :{" "}
</label>
<div className="col-md-8 text-start">
<label className=" col-form-label">{` ${report?.assignedBy.firstName} ${report?.assignedBy.lastName}`}</label>
</div>
</div>
<div className="mb-1 row text-start">
<label
htmlFor="html5-email-input"
className="col-md-4 col-form-label"
>
Wrok Area :
</label>
<div className="col-md-8 text-start text-wrap">
<label className=" col-form-label">
{" "}
{report?.workItem?.workArea?.floor?.building?.name}{" "}
<i className="bx bx-chevron-right"></i>{" "}
{report?.workItem?.workArea?.floor?.floorName}{" "}
<i className="bx bx-chevron-right"> </i>
{report?.workItem?.workArea?.areaName}
</label>
</div>
</div>
<div className="mb-1 row text-start">
<label
htmlFor="html5-email-input"
className="col-md-4 col-form-label"
>
Activity :
</label>
<div className="col-md-8 text-start text-wrap">
<label className=" col-form-label">
{report?.workItem?.activityMaster.activityName}
</label>
</div>
</div>
<div className="mb-1 row text-start">
<label
htmlFor="html5-email-input"
className="col-md-4 col-form-label"
>
Team Size :
</label>
<div className="col-md-8 text-start text-wrap">
<label className=" col-form-label">
{report?.teamMembers?.length}
</label>
</div>
</div>
<div className="mb-1 row text-start">
<label
htmlFor="html5-email-input"
className="col-md-4 col-form-label"
>
Assigned :
</label>
<div className="col-md-8 text-start text-wrap">
<label className=" col-form-label">
{report?.plannedTask} of{" "}
{report?.workItem.plannedWork -
report?.workItem.completedWork}{" "}
Pending
</label>
</div>
</div>
<form onSubmit={handleSubmit(onSubmit)}>
<div className="mb-1 row text-start">
<label
htmlFor="html5-email-input"
className="col-md-4 col-form-label"
>
Completed Work
</label>
<div className="col-md-8 text-start text-wrap">
<input
{...register("completedTask", { valueAsNumber: true })}
id="smallInput"
className="form-control form-control-sm"
type="number"
placeholder="Completed Work"
/>
{errors.completedTask && (
<div className="danger-text">
{errors.completedTask.message}
</div>
)}
</div>
</div>
<div className="mb-1 row text-start">
<label
htmlFor="html5-email-input"
className="col-md-4 col-form-label"
>
Comment
</label>
<div className="col-md-8 text-start text-wrap">
<textarea
{...register("comment")}
className="form-control"
id="exampleFormControlTextarea1"
rows="1"
placeholder="Enter comment"
/>
{errors.comment && (
<div className="danger-text">{errors.comment.message}</div>
)}
</div>
</div>
<div className="col-12 text-center my-2">
<button type="submit" className="btn btn-sm btn-primary me-3">
{loading ? "Please wait" : "Submit Report"}
</button>
<button
type="button"
className="btn btn-sm btn-label-secondary"
onClick={handleClose}
>
Cancel
</button>
</div>
</form>
<div className="mb-1 row text-start">
<label htmlFor="html5-text-input" className="col-md-4 col-form-label">
Assigned Date :{" "}
</label>
<div className="col-md-8 text-start">
<label className="col-md-2 col-form-label">
{formatDate(report?.assignmentDate)}
</label>
</div>
</div>
<div className="mb-1 row text-start">
<label htmlFor="html5-search-input" className="col-md-4 col-form-label">
Assigned By :{" "}
</label>
<div className="col-md-8 text-start">
<label className=" col-form-label">{` ${report?.assignedBy.firstName} ${report?.assignedBy.lastName}`}</label>
</div>
</div>
<div className="mb-1 row text-start">
<label htmlFor="html5-email-input" className="col-md-4 col-form-label">
Wrok Area :
</label>
<div className="col-md-8 text-start text-wrap">
<label className=" col-form-label">
{" "}
{report?.workItem?.workArea?.floor?.building?.name}{" "}
<i className="bx bx-chevron-right"></i>{" "}
{report?.workItem?.workArea?.floor?.floorName}{" "}
<i className="bx bx-chevron-right"> </i>
{report?.workItem?.workArea?.areaName}
</label>
</div>
</div>
<div className="mb-1 row text-start">
<label htmlFor="html5-email-input" className="col-md-4 col-form-label">
Activity :
</label>
<div className="col-md-8 text-start text-wrap">
<label className=" col-form-label">
{report?.workItem?.activityMaster.activityName}
</label>
</div>
</div>
<div className="mb-1 row text-start">
<label htmlFor="html5-email-input" className="col-md-4 col-form-label">
Team Size :
</label>
<div className="col-md-8 text-start text-wrap">
<label className=" col-form-label">
{report?.teamMembers?.length}
</label>
</div>
</div>
<div className="mb-1 row text-start">
<label htmlFor="html5-email-input" className="col-md-4 col-form-label">
Assigned :
</label>
<div className="col-md-8 text-start text-wrap">
<label className=" col-form-label">
{report?.plannedTask} of{" "}
{report?.workItem.plannedWork - report?.workItem.completedWork}{" "}
Pending
</label>
</div>
</div>
<form onSubmit={handleSubmit(onSubmit)}>
<div className="mb-1 row text-start">
<label
htmlFor="html5-email-input"
className="col-md-4 col-form-label"
>
Completed Work
</label>
<div className="col-md-8 text-start text-wrap">
<input
{...register("completedTask", { valueAsNumber: true })}
id="smallInput"
className="form-control form-control-sm"
type="number"
placeholder="Completed Work"
/>
{errors.completedTask && (
<div className="danger-text">{errors.completedTask.message}</div>
)}
</div>
</div>
<div className="mb-1 row text-start">
<label
htmlFor="html5-email-input"
className="col-md-4 col-form-label"
>
Comment
</label>
<div className="col-md-8 text-start text-wrap">
<textarea
{...register("comment")}
className="form-control"
id="exampleFormControlTextarea1"
rows="1"
placeholder="Enter comment"
/>
{errors.comment && (
<div className="danger-text">{errors.comment.message}</div>
)}
</div>
</div>
<div className="col-12 text-center my-2">
<button type="submit" className="btn btn-sm btn-primary me-3">
{loading ? "Please wait" : "Submit Report"}
</button>
<button
type="button"
className="btn btn-sm btn-label-secondary"
onClick={handleClose}
>
Cancel
</button>
</div>
</form>
</div>
);
};

View File

@ -459,14 +459,15 @@ export const useManageProjectAllocation = ({
isSuccess,
isError,
} = useMutation({
mutationFn: async ({ items }) => {
mutationFn: async ( {items} ) =>
{
const response = await ProjectRepository.manageProjectAllocation(items);
return response.data;
},
onSuccess: (data, variables, context) => {
queryClient.invalidateQueries(['empListByProjectAllocated']);
if (context?.added) {
if (variables?.added) {
showToast('Employee Assigned Successfully', 'success');
} else {
showToast('Removed Employee Successfully', 'success');

View File

@ -5,106 +5,7 @@ import {MasterRespository} from "../repositories/MastersRepository";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import showToast from "../services/toastService";
import {useSelector} from "react-redux";
// import {formatDate} from "../utils/dateUtils";
// export const useTaskList = (projectId, dateFrom, toDate) => {
// const [TaskList, setTaskList] = useState([]);
// const [loading, setLoading] = useState(false);
// const [error, setError] = useState(null);
// const fetchList = async (projectId, dateFrom, toDate) => {
// const taskList_cached = getCachedData("taskList");
// // if (!taskList_cached || taskList_cached?.projectId !== projectId) {
// try {
// setLoading(true);
// const resp = await TasksRepository.getTaskList(
// projectId,
// dateFrom,
// toDate
// );
// setTaskList(resp.data);
// cacheData("taskList", { projectId: projectId, data: resp.data });
// setLoading(false);
// } catch (err) {
// setLoading(false);
// setError(err);
// }
// // } else {
// // setTaskList(taskList_cached.data);
// // }
// };
// useEffect( () =>
// {
// if (projectId && dateFrom && toDate) {
// fetchList(projectId, dateFrom, toDate);
// }
// }, [projectId, dateFrom, toDate]);
// return { TaskList, loading, error, refetch:fetchList};
// };
// export const useTaskById = (TaskId) =>
// {
// const [Task, setTask] = useState([]);
// const [loading, setLoading] = useState(false);
// const [ error, setError ] = useState( null );
// const fetchTask = async(TaskId) =>
// {
// try
// {
// let res = await TasksRepository.getTaskById( TaskId );
// setTask( res.data );
// } catch ( error )
// {
// setError(err)
// }
// }
// useEffect( () =>
// {
// if ( TaskId )
// {
// fetchTask(TaskId)
// }
// }, [ TaskId ] )
// return { Task,loading}
// }
// export const useAuditStatus = () =>
// {
// const [ status, setStatus ] = useState( [] );
// const [ error, setError ] = useState( '' );
// const [ loading, setLoading ] = useState( false )
// const fetchStatus = async() =>
// {
// try
// {
// const res = await MasterRespository.getAuditStatus()
// setStatus( res.data )
// cacheData("AuditStatus",res.data)
// } catch ( err )
// {
// setError(err)
// }
// }
// useEffect(() => {
// const cache_status = getCachedData('AuditStatus');
// if (cache_status) {
// setStatus(cache_status);
// } else {
// fetchStatus();
// }
// }, []);
// return {status,error,loading}
// }
// ---------Query---------------------------------
@ -197,12 +98,17 @@ export const useReportTask = ( {onSuccessCallback, onErrorCallback} = {} ) =>
isError,
error,
} = useMutation({
mutationFn: async (reportData) => {
mutationFn: async ( {reportData,workAreaId} ) =>
{
debugger
return await TasksRepository.reportTask(reportData);
},
onSuccess: (data) => {
onSuccess: ( data, variables ) =>
{
const {workAreaId} = variables;
queryClient.invalidateQueries( {queryKey: [ "taskList" ]} );
queryClient.invalidateQueries( {queryKey: [ "WorkItems", workAreaId ]} );
showToast( "Task Reported Successfully.", "success" );
queryClient.invalidateQueries({ queryKey: ["taskList"] });
if (onSuccessCallback) onSuccessCallback(data);
},
onError: (error) => {
@ -247,7 +153,7 @@ export const useSubmitTaskComment = ({ actionAllow, onSuccessCallback }) => {
if (actionAllow) {
showToast( "Review submitted successfully.", "success" );
queryClient.invalidateQueries({ queryKey: [ "WorkItems", workAreaId ] });
// queryClient.invalidateQueries({ queryKey: [ "WorkItems", workAreaId ] });
} else
{
showToast("Comment sent successfully.", "success");