added query hook for fetching and posting data

This commit is contained in:
pramod mahajan 2025-07-17 09:52:14 +05:30
parent 1978460169
commit 59196b3cf0
6 changed files with 263 additions and 128 deletions

View File

@ -9,6 +9,7 @@ import DateRangePicker from "../common/DateRangePicker";
import { clearCacheKey, getCachedData } from "../../slices/apiDataManager";
import eventBus from "../../services/eventBus";
import AttendanceRepository from "../../repositories/AttendanceRepository";
import { useAttendancesLogs } from "../../hooks/useAttendance";
const usePagination = (data, itemsPerPage) => {
const [currentPage, setCurrentPage] = useState(1);
@ -37,9 +38,12 @@ const AttendanceLog = ({
setshowOnlyCheckout,
showOnlyCheckout,
}) => {
const selectedProject = useSelector((store)=>store.localVariables.projectId)
const [dateRange, setDateRange] = useState({ startDate: "", endDate: "" });
const dispatch = useDispatch();
const { data, loading, error } = useSelector((store) => store.attendanceLogs);
const [loading,setLoading] = useState(false)
// const { data, loading, error } = useSelector((store) => store.attendanceLogs);
const [isRefreshing, setIsRefreshing] = useState(false);
const [processedData, setProcessedData] = useState([]);
@ -69,18 +73,18 @@ const AttendanceLog = ({
return nameA?.localeCompare(nameB);
};
useEffect(() => {
const { startDate, endDate } = dateRange;
dispatch(
fetchAttendanceData({
projectId,
fromDate: startDate,
toDate: endDate,
})
);
setIsRefreshing(false);
}, [dateRange, projectId, dispatch, isRefreshing]);
// useEffect(() => {
// const { startDate, endDate } = dateRange;
// dispatch(
// fetchAttendanceData({
// projectId,
// fromDate: startDate,
// toDate: endDate,
// })
// );
// setIsRefreshing(false);
// }, [dateRange, projectId, dispatch, isRefreshing]);
const {data= [],isLoading, error, refetch,isFetching} = useAttendancesLogs(selectedProject,dateRange.startDate, dateRange.endDate)
const filtering = (data) => {
const filteredData = showOnlyCheckout
? data.filter((item) => item.checkOutTime === null)
@ -146,7 +150,6 @@ const AttendanceLog = ({
resetPage,
} = usePagination(processedData, 20);
// Reset to the first page whenever processedData changes (due to switch on/off)
useEffect(() => {
resetPage();
}, [processedData, resetPage]);
@ -225,10 +228,10 @@ const AttendanceLog = ({
<div className="col-md-2 m-0 text-end">
<i
className={`bx bx-refresh cursor-pointer fs-4 ${
loading || isRefreshing ? "spin" : ""
isFetching ? "spin" : ""
}`}
title="Refresh"
onClick={() => setIsRefreshing(true)}
onClick={()=>refetch()}
/>
</div>
</div>
@ -331,14 +334,9 @@ const AttendanceLog = ({
</tbody>
</table>
)}
{!loading && !isRefreshing && data.length === 0 && (
{!loading && !isRefreshing && data?.length === 0 && (
<span className="text-muted">No employee logs</span>
)}
{/* {error && !loading && !isRefreshing && (
<tr>
<td colSpan={6}>{error}</td>
</tr>
)} */}
</div>
{!loading && !isRefreshing && processedData.length > 10 && (
<nav aria-label="Page ">

View File

@ -8,6 +8,7 @@ import { useDispatch, useSelector } from "react-redux";
import { markAttendance } from "../../slices/apiSlice/attedanceLogsSlice";
import showToast from "../../services/toastService";
import { checkIfCurrentDate } from "../../utils/dateUtils";
import { useMarkAttendance } from "../../hooks/useAttendance";
const schema = z.object({
@ -18,6 +19,7 @@ const schema = z.object({
const CheckCheckOutmodel = ({ modeldata, closeModal, handleSubmitForm, }) => {
const projectId = useSelector((store) => store.localVariables.projectId)
const {mutate:MarkAttendance} = useMarkAttendance()
const [isLoading, setIsLoading] = useState(false);
const coords = usePositionTracker();
const dispatch = useDispatch()
@ -44,29 +46,34 @@ const CheckCheckOutmodel = ({ modeldata, closeModal, handleSubmitForm, }) => {
const onSubmit = (data) => {
let record = { ...data, date: new Date().toLocaleDateString(), latitude: coords.latitude, longitude: coords.longitude, employeeId: modeldata.employeeId, action: modeldata.action, id: modeldata?.id || null }
if (modeldata.forWhichTab === 1) {
handleSubmitForm(record)
} else {
// if (modeldata.forWhichTab === 1 || modeldata.forWhichTab === 2) {
// handleSubmitForm(record)
const payload = {
Id: modeldata?.id || null,
comment: data.description,
employeeID: modeldata.employeeId,
projectId: projectId,
date: new Date().toISOString(),
markTime: data.markTime,
latitude: coords.latitude.toString(),
longitude: coords.longitude.toString(),
action: modeldata.action,
image: null,
};
MarkAttendance({payload,forWhichTab:modeldata.forWhichTab})
// } else {
// dispatch(markAttendance(record))
// .unwrap()
// .then((data) => {
// if ( modeldata?.currentDate && checkIfCurrentDate( modeldata?.currentDate ) )
// {
dispatch(markAttendance(record))
.unwrap()
.then((data) => {
// showToast("Attendance Marked Successfully", "success");
// })
// .catch((error) => {
showToast("Attendance Marked Successfully", "success");
})
.catch((error) => {
// showToast(error, "error");
showToast(error, "error");
});
// } else
// {
// let formData = {...data, date: new Date().toLocaleDateString(),latitude:coords.latitude,longitude:coords.longitude,employeeId:modeldata.employeeId,projectId:projectId,action:modeldata.action,id:modeldata?.id || null}
// }
}
// });
// }
closeModal()
};
@ -175,7 +182,6 @@ export const Regularization = ({ modeldata, closeModal, handleSubmitForm }) => {
const onSubmit = (data) => {
let record = { ...data, date: new Date().toLocaleDateString(), latitude: coords.latitude, longitude: coords.longitude, }
handleSubmitForm(record)
closeModal()

View File

@ -6,12 +6,16 @@ import { usePositionTracker } from '../../hooks/usePositionTracker';
import {markCurrentAttendance} from '../../slices/apiSlice/attendanceAllSlice';
import {cacheData, getCachedData} from '../../slices/apiDataManager';
import showToast from '../../services/toastService';
import { useMarkAttendance } from '../../hooks/useAttendance';
import { useQueryClient } from '@tanstack/react-query';
const RegularizationActions = ({attendanceData,handleRequest,refresh}) => {
const [status,setStatus] = useState()
const [loadingApprove,setLoadingForApprove] = useState(false)
const [loadingReject,setLoadingForReject] = useState(false)
const {mutate:MarkAttendance,isPending} = useMarkAttendance()
const queryClient = useQueryClient()
const projectId = useSelector((store)=>store.localVariables.projectId)
const {latitude,longitude} = usePositionTracker();
@ -24,11 +28,11 @@ const dispatch = useDispatch()
}else{
setLoadingForReject(true)
}
// setLoading(true)
let req_Data = {
let payload = {
id:request_attendance.id || null,
description: ` ${IsReqularize ? "Approved" : "Rejected"}! regularization request`,
employeeId:request_attendance?.employeeId,
comment: ` ${IsReqularize ? "Approved" : "Rejected"}! regularization request`,
employeeID:request_attendance?.employeeId,
projectId:projectId,
date:new Date().toISOString(),
markTime:new Date().toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit" }),
@ -37,22 +41,46 @@ const dispatch = useDispatch()
action:IsReqularize ? 4 : 5,
image:null
}
dispatch( markCurrentAttendance( req_Data ) ).then( ( action ) =>
{
const regularizedList = getCachedData("regularizedList")
const updatedata = regularizedList?.data?.filter( item => item.id !== action.payload.id );
cacheData("regularizedList",{data:updatedata,projectId:projectId})
setLoadingForApprove( false )
setLoadingForReject( false )
refresh()
}).catch( ( error ) =>
MarkAttendance(
{ payload, forWhichTab: 3 },
{
showToast(error.message,"error")
});
onSuccess: () => {
queryClient.invalidateQueries({queryKey:["regularizedList"]})
if (IsReqularize) {
setLoadingForApprove(false);
} else {
setLoadingForReject(false);
}
showToast(`Successfully ${IsReqularize ? "approved" : "rejected"}`, "success");
},
onError: (error) => {
showToast(error.message || "Failed to submit", "error");
if (IsReqularize) {
setLoadingForApprove(false);
} else {
setLoadingForReject(false);
}
},
}
);
// dispatch( markCurrentAttendance( req_Data ) ).then( ( action ) =>
// {
// const regularizedList = getCachedData("regularizedList")
// const updatedata = regularizedList?.data?.filter( item => item.id !== action.payload.id );
// cacheData("regularizedList",{data:updatedata,projectId:projectId})
// setLoadingForApprove( false )
// setLoadingForReject( false )
// refresh()
// }).catch( ( error ) =>
// {
// showToast(error.message,"error")
// });
}

View File

@ -1,8 +1,10 @@
import { useEffect, useState } from "react";
import { cacheData, getCachedData } from "../slices/apiDataManager";
import AttendanceRepository from "../repositories/AttendanceRepository";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import showToast from "../services/toastService";
import { useSelector } from "react-redux";
import { store } from "../store/store";
// export const useAttendace =(projectId)=>{
@ -114,7 +116,7 @@ import showToast from "../services/toastService";
// ----------------------------Query-----------------------------
export const useAttendace = (projectId) => {
export const useAttendance = (projectId) => {
const {
data: attendance = [],
isLoading: loading,
@ -122,8 +124,7 @@ export const useAttendace = (projectId) => {
refetch: recall,
} = useQuery({
queryKey: ["attendance", projectId],
queryFn: async ({ queryKey }) => {
const [, projectId] = queryKey;
queryFn: async () => {
const response = await AttendanceRepository.getAttendance(projectId);
return response.data;
},
@ -141,6 +142,23 @@ export const useAttendace = (projectId) => {
};
};
export const useAttendancesLogs = (projectId, fromDate, toDate) => {
const enabled = !!projectId && !!fromDate && !!toDate;
return useQuery({
queryKey: ["attendanceLogs", projectId, fromDate, toDate],
queryFn: async () => {
const res = await AttendanceRepository.getAttendanceFilteredByDate(
projectId,
fromDate,
toDate
);
return res.data;
},
enabled,
});
};
export const useEmployeeAttendacesLog = (id) => {
const {
@ -168,6 +186,19 @@ export const useEmployeeAttendacesLog = (id) => {
};
};
export const useAttendanceByEmployee = (employeeId, fromDate, toDate) => {
const enabled = !!employeeId && !!fromDate && !!toDate;
return useQuery({
queryKey: ["employeeAttendance", employeeId, fromDate, toDate],
queryFn: async () => {
const res = await AttendanceRepository.getAttendanceByEmployee(employeeId, fromDate, toDate);
return res.data;
},
enabled,
});
};
export const useRegularizationRequests = (projectId) => {
const {
data: regularizes = [],
@ -175,7 +206,7 @@ export const useRegularizationRequests = (projectId) => {
error,
refetch,
} = useQuery({
queryKey: ["regularizationRequests", projectId],
queryKey: ["regularizedList", projectId],
queryFn: async () => {
const response = await AttendanceRepository.getRegularizeList(projectId);
return response.data;
@ -193,3 +224,37 @@ export const useRegularizationRequests = (projectId) => {
refetch,
};
};
// -------------------Mutation--------------------------------------
export const useMarkAttendance = () => {
const queryClient = useQueryClient();
const selectedProject = useSelector((store)=>store.localVariables.projectId)
return useMutation({
mutationFn: async ({payload,forWhichTab}) => {
const res = await AttendanceRepository.markAttendance(payload);
return res.data;
},
onSuccess: (data,variables) => {
if(variables.forWhichTab == 1){
queryClient.setQueryData(["attendance",selectedProject], (oldData) => {
if (!oldData) return oldData;
return oldData.map((emp) =>
emp.employeeId === data.employeeId ? { ...emp, ...data } : emp
);
});
}else{
queryClient.invalidateQueries({
queryKey: ["attendanceLogs"],
});
}
if(variables.forWhichTab !== 3) showToast("Attendance marked successfully", "success");
},
onError: (error) => {
showToast(error.message || "Failed to mark attendance", "error");
},
});
};

View File

@ -12,7 +12,7 @@ import AttendanceModel from "../../components/Activities/AttendanceModel";
import showToast from "../../services/toastService";
// import { useProjects } from "../../hooks/useProjects";
import Regularization from "../../components/Activities/Regularization";
import { useAttendace } from "../../hooks/useAttendance";
import { useAttendance } from "../../hooks/useAttendance";
import { useDispatch, useSelector } from "react-redux";
import { setProjectId } from "../../slices/localVariablesSlice";
import { markCurrentAttendance } from "../../slices/apiSlice/attendanceAllSlice";
@ -22,10 +22,16 @@ import { REGULARIZE_ATTENDANCE } from "../../utils/constants";
import eventBus from "../../services/eventBus";
import AttendanceRepository from "../../repositories/AttendanceRepository";
import { useProjectName } from "../../hooks/useProjects";
import GlobalModel from "../../components/common/GlobalModel";
import CheckCheckOutmodel from "../../components/Activities/CheckCheckOutForm";
import AttendLogs from "../../components/Activities/AttendLogs";
import Confirmation from "../../components/Activities/Confirmation";
import { useQueryClient } from "@tanstack/react-query";
const AttendancePage = () => {
const [activeTab, setActiveTab] = useState("all");
const [ShowPending, setShowPending] = useState(false);
const queryClient = useQueryClient()
const loginUser = getCachedProfileData();
var selectedProject = useSelector((store) => store.localVariables.projectId);
const dispatch = useDispatch()
@ -33,7 +39,7 @@ const AttendancePage = () => {
attendance,
loading: attLoading,
recall: attrecall,
} = useAttendace(selectedProject);
} = useAttendance(selectedProject);
const [attendances, setAttendances] = useState();
const [empRoles, setEmpRoles] = useState(null);
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
@ -56,11 +62,17 @@ const AttendancePage = () => {
? { ...item, ...msg.response }
: item
);
cacheData("Attendance", {
data: updatedAttendance,
projectId: selectedProject,
});
setAttendances(updatedAttendance);
// cacheData("Attendance", {
// data: updatedAttendance,
// projectId: selectedProject,
// });
queryClient.setQueryData(["attendance",selectedProject], (oldData) => {
if (!oldData) return oldData;
return oldData.map((emp) =>
emp.employeeId === data.employeeId ? { ...emp, ...data } : emp
);
});
// setAttendances(updatedAttendance);
}
},
[selectedProject, attrecall]
@ -69,14 +81,16 @@ const AttendancePage = () => {
const employeeHandler = useCallback(
(msg) => {
if (attendances.some((item) => item.employeeId == msg.employeeId)) {
AttendanceRepository.getAttendance(selectedProject)
.then((response) => {
cacheData("Attendance", { data: response.data, selectedProject });
setAttendances(response.data);
})
.catch((error) => {
console.error(error);
});
// AttendanceRepository.getAttendance(selectedProject)
// .then((response) => {
// cacheData("Attendance", { data: response.data, selectedProject });
// setAttendances(response.data);
// })
// .catch((error) => {
// console.error(error);
// });
attrecall()
}
},
[selectedProject, attendances]
@ -100,34 +114,34 @@ const AttendancePage = () => {
const closeModal = () => {
setModelConfig(null);
setIsCreateModalOpen(false);
const modalElement = document.getElementById("check-Out-modal");
if (modalElement) {
modalElement.classList.remove("show");
modalElement.style.display = "none";
document.body.classList.remove("modal-open");
document.querySelector(".modal-backdrop")?.remove();
}
// const modalElement = document.getElementById("check-Out-modal");
// if (modalElement) {
// modalElement.classList.remove("show");
// modalElement.style.display = "none";
// document.body.classList.remove("modal-open");
// document.querySelector(".modal-backdrop")?.remove();
// }
};
const handleSubmit = (formData) => {
dispatch(markCurrentAttendance(formData))
.then((action) => {
const updatedAttendance = attendances.map((item) =>
item.employeeId === action.payload.employeeId
? { ...item, ...action.payload }
: item
);
cacheData("Attendance", {
data: updatedAttendance,
projectId: selectedProject,
});
setAttendances(updatedAttendance);
showToast("Attedance Marked Successfully", "success");
})
.catch((error) => {
showToast(error.message, "error");
});
};
// const handleSubmit = (formData) => {
// dispatch(markCurrentAttendance(formData))
// .then((action) => {
// const updatedAttendance = attendances.map((item) =>
// item.employeeId === action.payload.employeeId
// ? { ...item, ...action.payload }
// : item
// );
// cacheData("Attendance", {
// data: updatedAttendance,
// projectId: selectedProject,
// });
// setAttendances(updatedAttendance);
// showToast("Attedance Marked Successfully", "success");
// })
// .catch((error) => {
// showToast(error.message, "error");
// });
// };
const handleToggle = (event) => {
setShowOnlyCheckout(event.target.checked);
@ -166,11 +180,11 @@ const AttendancePage = () => {
}, [employeeHandler]);
return (
<>
{isCreateModalOpen && modelConfig && (
{/* {isCreateModalOpen && modelConfig && (
<div
className="modal fade show"
style={{ display: "block" }}
id="check-Out-modal"
id="check-Out-modalg"
tabIndex="-1"
aria-hidden="true"
>
@ -180,8 +194,28 @@ const AttendancePage = () => {
handleSubmitForm={handleSubmit}
/>
</div>
)}
)} */}
{isCreateModalOpen && modelConfig && (
<GlobalModel isOpen={isCreateModalOpen} size={modelConfig?.action === 6 && "lg"} closeModal={closeModal}>
{(modelConfig?.action === 0 || modelConfig?.action === 1 || modelConfig?.action === 2) && (
<CheckCheckOutmodel modeldata={modelConfig} closeModal={closeModal} />
)}
{/* For view logs */}
{modelConfig?.action === 6 && (
<AttendLogs Id={modelConfig?.id} closeModal={closeModal} />
)}
{
modelConfig?.action === 7 &&(
<Confirmation closeModal={closeModal} />
)
}
</GlobalModel>
)}
<div className="container-fluid">
<Breadcrumb
data={[
@ -267,7 +301,8 @@ const AttendancePage = () => {
{activeTab === "regularization" && DoRegularized && (
<div className="tab-pane fade show active py-0">
<Regularization handleRequest={handleSubmit} />
{/* <Regularization handleRequest={handleSubmit} /> */}
<Regularization />
</div>
)}

View File

@ -8,6 +8,7 @@ import Avatar from "../../components/common/Avatar";
import { convertShortTime } from "../../utils/dateUtils";
import RenderAttendanceStatus from "../../components/Activities/RenderAttendanceStatus";
import AttendLogs from "../../components/Activities/AttendLogs";
import { useAttendanceByEmployee } from "../../hooks/useAttendance";
const AttendancesEmployeeRecords = ({ employee }) => {
const [attendances, setAttendnaces] = useState([]);
@ -15,10 +16,12 @@ const AttendancesEmployeeRecords = ({ employee }) => {
const [dateRange, setDateRange] = useState({ startDate: "", endDate: "" });
const [isModalOpen, setIsModalOpen] = useState(false);
const [attendanceId, setAttendanecId] = useState();
const {data =[],isLoading:loading,isFetching,error,refetch} = useAttendanceByEmployee(employee,dateRange.startDate, dateRange.endDate)
const dispatch = useDispatch();
const { data, loading, error } = useSelector(
(store) => store.employeeAttendance
);
// const { data, loading, error } = useSelector(
// (store) => store.employeeAttendance
// );
const [isRefreshing, setIsRefreshing] = useState(true);
@ -88,18 +91,18 @@ const AttendancesEmployeeRecords = ({ employee }) => {
20
);
useEffect(() => {
const { startDate, endDate } = dateRange;
if (startDate && endDate) {
dispatch(
fetchEmployeeAttendanceData({
employeeId: employee,
fromDate: startDate,
toDate: endDate,
})
);
}
}, [dateRange, employee, isRefreshing]);
// useEffect(() => {
// const { startDate, endDate } = dateRange;
// if (startDate && endDate) {
// dispatch(
// fetchEmployeeAttendanceData({
// employeeId: employee,
// fromDate: startDate,
// toDate: endDate,
// })
// );
// }
// }, [dateRange, employee, isRefreshing]);
const openModal = (id) => {
setAttendanecId(id);
@ -145,11 +148,11 @@ const AttendancesEmployeeRecords = ({ employee }) => {
</div>
<div className="col-md-2 m-0 text-end">
<i
className={`bx bx-refresh cursor-pointer fs-4 ${loading ? "spin" : ""
className={`bx bx-refresh cursor-pointer fs-4 ${isFetching ? "spin" : ""
}`}
data-toggle="tooltip"
title="Refresh"
onClick={() => setIsRefreshing(!isRefreshing)}
onClick={() => refetch()}
/>
</div>
</div>