Handle undefined 'variables' in employee assignment toast logic

This commit is contained in:
Pramod Mahajan 2025-07-03 13:16:01 +05:30
parent e24b873677
commit e6d6f0ac30
3 changed files with 166 additions and 308 deletions

View File

@ -1,33 +1,34 @@
import React, { useState,useEffect } from "react"; import React, { useState, useEffect } from "react";
import { formatDate } from "../../utils/dateUtils"; import { formatDate } from "../../utils/dateUtils";
import { useForm } from "react-hook-form"; import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod"; import { z } from "zod";
import showToast from "../../services/toastService"; import showToast from "../../services/toastService";
import { TasksRepository } from "../../repositories/TaskRepository"; import { TasksRepository } from "../../repositories/TaskRepository";
import {useReportTask} from "../../hooks/useTasks"; import { useReportTask } from "../../hooks/useTasks";
export const ReportTask = ({ report, closeModal }) => { export const ReportTask = ({ report, closeModal }) => {
const [ loading, setloading ] = useState( false ); const [loading, setloading] = useState(false);
const { mutate: reportTask, isPending } = useReportTask({ const { mutate: reportTask, isPending } = useReportTask({
onSuccessCallback: () => { onSuccessCallback: () => {
// refetch(); reset();
reset(); setloading(false);
setloading(false); closeModal();
closeModal(); },
}, onErrorCallback: () => {
onErrorCallback: () => { setloading(false);
setloading(false); },
}, });
} );
const maxPending = const maxPending =
report?.workItem?.plannedWork - report?.workItem?.completedWork; report?.workItem?.plannedWork - report?.workItem?.completedWork;
const schema = z.object({ const schema = z.object({
completedTask: z completedTask: z.preprocess(
.preprocess( (val) =>
(val) => (val === "" || val === null || Number.isNaN(val) ? undefined : Number(val)), val === "" || val === null || Number.isNaN(val)
? undefined
: Number(val),
z z
.number({ .number({
required_error: "Completed Work must be a 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}`, 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 { const {
register, register,
handleSubmit, handleSubmit,
formState: {errors}, formState: { errors },
reset reset,
} = useForm({ } = useForm({
resolver: zodResolver(schema), resolver: zodResolver(schema),
defaultValues: { completedTask: 0, comment: "" }, defaultValues: { completedTask: 0, comment: "" },
}); });
useEffect(() => {
useEffect(() => { if (report) {
if (report) { reset({ completedTask: 0, comment: "" });
reset({ completedTask: 0, comment: "" }); }
} }, [report, reset]);
}, [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");
// }
// }
const onSubmit = (data) => { const onSubmit = (data) => {
setloading(true); setloading(true);
const reportData = { const reportData = {
...data, ...data,
id: report?.id, id: report?.id,
reportedDate: new Date().toISOString(), reportedDate: new Date().toISOString(),
checkList: [], checkList: [],
}; };
reportTask(reportData); reportTask({ reportData, workAreaId: report?.workItem?.workArea?.id });
}; };
const handleClose = () => { const handleClose = () => {
closeModal(); closeModal();
reset(); reset();
}; };
return ( return (
<div className="container m-0"> <div className="container m-0">
<div className="text-center"> <div className="text-center">
<p className="fs-6 fw-semibold">Report Task</p> <p className="fs-6 fw-semibold">Report Task</p>
</div> </div>
<div className="mb-1 row text-start"> <div className="mb-1 row text-start">
<label <label htmlFor="html5-text-input" className="col-md-4 col-form-label">
htmlFor="html5-text-input" Assigned Date :{" "}
className="col-md-4 col-form-label" </label>
> <div className="col-md-8 text-start">
Assigned Date :{" "} <label className="col-md-2 col-form-label">
</label> {formatDate(report?.assignmentDate)}
<div className="col-md-8 text-start"> </label>
<label className="col-md-2 col-form-label"> </div>
{formatDate(report?.assignmentDate)} </div>
</label> <div className="mb-1 row text-start">
</div> <label htmlFor="html5-search-input" className="col-md-4 col-form-label">
</div> Assigned By :{" "}
<div className="mb-1 row text-start"> </label>
<label <div className="col-md-8 text-start">
htmlFor="html5-search-input" <label className=" col-form-label">{` ${report?.assignedBy.firstName} ${report?.assignedBy.lastName}`}</label>
className="col-md-4 col-form-label" </div>
> </div>
Assigned By :{" "} <div className="mb-1 row text-start">
</label> <label htmlFor="html5-email-input" className="col-md-4 col-form-label">
<div className="col-md-8 text-start"> Wrok Area :
<label className=" col-form-label">{` ${report?.assignedBy.firstName} ${report?.assignedBy.lastName}`}</label> </label>
</div> <div className="col-md-8 text-start text-wrap">
</div> <label className=" col-form-label">
<div className="mb-1 row text-start"> {" "}
<label {report?.workItem?.workArea?.floor?.building?.name}{" "}
htmlFor="html5-email-input" <i className="bx bx-chevron-right"></i>{" "}
className="col-md-4 col-form-label" {report?.workItem?.workArea?.floor?.floorName}{" "}
> <i className="bx bx-chevron-right"> </i>
Wrok Area : {report?.workItem?.workArea?.areaName}
</label> </label>
<div className="col-md-8 text-start text-wrap"> </div>
<label className=" col-form-label"> </div>
{" "} <div className="mb-1 row text-start">
{report?.workItem?.workArea?.floor?.building?.name}{" "} <label htmlFor="html5-email-input" className="col-md-4 col-form-label">
<i className="bx bx-chevron-right"></i>{" "} Activity :
{report?.workItem?.workArea?.floor?.floorName}{" "} </label>
<i className="bx bx-chevron-right"> </i> <div className="col-md-8 text-start text-wrap">
{report?.workItem?.workArea?.areaName} <label className=" col-form-label">
</label> {report?.workItem?.activityMaster.activityName}
</div> </label>
</div> </div>
<div className="mb-1 row text-start"> </div>
<label <div className="mb-1 row text-start">
htmlFor="html5-email-input" <label htmlFor="html5-email-input" className="col-md-4 col-form-label">
className="col-md-4 col-form-label" Team Size :
> </label>
Activity : <div className="col-md-8 text-start text-wrap">
</label> <label className=" col-form-label">
<div className="col-md-8 text-start text-wrap"> {report?.teamMembers?.length}
<label className=" col-form-label"> </label>
{report?.workItem?.activityMaster.activityName} </div>
</label> </div>
</div> <div className="mb-1 row text-start">
</div> <label htmlFor="html5-email-input" className="col-md-4 col-form-label">
<div className="mb-1 row text-start"> Assigned :
<label </label>
htmlFor="html5-email-input" <div className="col-md-8 text-start text-wrap">
className="col-md-4 col-form-label" <label className=" col-form-label">
> {report?.plannedTask} of{" "}
Team Size : {report?.workItem.plannedWork - report?.workItem.completedWork}{" "}
</label> Pending
<div className="col-md-8 text-start text-wrap"> </label>
<label className=" col-form-label"> </div>
{report?.teamMembers?.length} </div>
</label> <form onSubmit={handleSubmit(onSubmit)}>
</div> <div className="mb-1 row text-start">
</div> <label
<div className="mb-1 row text-start"> htmlFor="html5-email-input"
<label className="col-md-4 col-form-label"
htmlFor="html5-email-input" >
className="col-md-4 col-form-label" Completed Work
> </label>
Assigned : <div className="col-md-8 text-start text-wrap">
</label> <input
<div className="col-md-8 text-start text-wrap"> {...register("completedTask", { valueAsNumber: true })}
<label className=" col-form-label"> id="smallInput"
{report?.plannedTask} of{" "} className="form-control form-control-sm"
{report?.workItem.plannedWork - type="number"
report?.workItem.completedWork}{" "} placeholder="Completed Work"
Pending />
</label> {errors.completedTask && (
</div> <div className="danger-text">{errors.completedTask.message}</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> </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, isSuccess,
isError, isError,
} = useMutation({ } = useMutation({
mutationFn: async ({ items }) => { 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(['empListByProjectAllocated']); queryClient.invalidateQueries(['empListByProjectAllocated']);
if (context?.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');

View File

@ -5,106 +5,7 @@ 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";
// 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--------------------------------- // ---------Query---------------------------------
@ -197,12 +98,17 @@ export const useReportTask = ( {onSuccessCallback, onErrorCallback} = {} ) =>
isError, isError,
error, error,
} = useMutation({ } = useMutation({
mutationFn: async (reportData) => { mutationFn: async ( {reportData,workAreaId} ) =>
{
debugger
return await TasksRepository.reportTask(reportData); 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" ); showToast( "Task Reported Successfully.", "success" );
queryClient.invalidateQueries({ queryKey: ["taskList"] });
if (onSuccessCallback) onSuccessCallback(data); if (onSuccessCallback) onSuccessCallback(data);
}, },
onError: (error) => { onError: (error) => {
@ -247,7 +153,7 @@ export const useSubmitTaskComment = ({ actionAllow, onSuccessCallback }) => {
if (actionAllow) { if (actionAllow) {
showToast( "Review submitted successfully.", "success" ); showToast( "Review submitted successfully.", "success" );
queryClient.invalidateQueries({ queryKey: [ "WorkItems", workAreaId ] }); // queryClient.invalidateQueries({ queryKey: [ "WorkItems", workAreaId ] });
} else } else
{ {
showToast("Comment sent successfully.", "success"); showToast("Comment sent successfully.", "success");