Enhancement implemented in the Attendance component to include search functionality.
This commit is contained in:
parent
820f80562f
commit
e96187cfa1
@ -6,28 +6,36 @@ import RenderAttendanceStatus from "./RenderAttendanceStatus";
|
||||
import { useSelector, useDispatch } from "react-redux";
|
||||
import { fetchAttendanceData } from "../../slices/apiSlice/attedanceLogsSlice";
|
||||
import DateRangePicker from "../common/DateRangePicker";
|
||||
import { clearCacheKey, getCachedData } from "../../slices/apiDataManager";
|
||||
import eventBus from "../../services/eventBus";
|
||||
import AttendanceRepository from "../../repositories/AttendanceRepository";
|
||||
|
||||
const usePagination = (data, itemsPerPage) => {
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const maxPage = Math.ceil(data.length / itemsPerPage);
|
||||
const totalItems = Array.isArray(data) ? data.length : 0;
|
||||
const maxPage = Math.ceil(totalItems / itemsPerPage);
|
||||
|
||||
const currentItems = useMemo(() => {
|
||||
if (!Array.isArray(data) || data.length === 0) {
|
||||
return [];
|
||||
}
|
||||
const startIndex = (currentPage - 1) * itemsPerPage;
|
||||
const endIndex = startIndex + itemsPerPage;
|
||||
return data.slice(startIndex, endIndex);
|
||||
}, [data, currentPage, itemsPerPage]);
|
||||
|
||||
const paginate = useCallback((pageNumber) => setCurrentPage(pageNumber), []);
|
||||
const resetPage = useCallback(() => setCurrentPage(1), []);
|
||||
const paginate = useCallback((pageNumber) => {
|
||||
if (pageNumber > 0 && pageNumber <= maxPage) {
|
||||
setCurrentPage(pageNumber);
|
||||
}
|
||||
}, [maxPage]);
|
||||
|
||||
const resetPage = useCallback(() => setCurrentPage(1), []); // This is returned by the hook
|
||||
|
||||
return {
|
||||
currentPage,
|
||||
totalPages: maxPage,
|
||||
currentItems,
|
||||
paginate,
|
||||
resetPage,
|
||||
resetPage, // Ensure resetPage is returned here
|
||||
};
|
||||
};
|
||||
|
||||
@ -36,38 +44,44 @@ const AttendanceLog = ({
|
||||
projectId,
|
||||
setshowOnlyCheckout,
|
||||
showOnlyCheckout,
|
||||
searchQuery, // Prop for search query
|
||||
}) => {
|
||||
const [dateRange, setDateRange] = useState({ startDate: "", endDate: "" });
|
||||
const dispatch = useDispatch();
|
||||
const { data, loading, error } = useSelector((store) => store.attendanceLogs);
|
||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||
const [processedData, setProcessedData] = useState([]);
|
||||
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
const today = useMemo(() => {
|
||||
const d = new Date();
|
||||
d.setHours(0, 0, 0, 0);
|
||||
return d;
|
||||
}, []);
|
||||
|
||||
const yesterday = new Date();
|
||||
yesterday.setDate(yesterday.getDate() - 1);
|
||||
const yesterday = useMemo(() => {
|
||||
const d = new Date();
|
||||
d.setDate(d.getDate() - 1);
|
||||
return d;
|
||||
}, []);
|
||||
|
||||
const isSameDay = (dateStr) => {
|
||||
const isSameDay = useCallback((dateStr) => {
|
||||
if (!dateStr) return false;
|
||||
const d = new Date(dateStr);
|
||||
d.setHours(0, 0, 0, 0);
|
||||
return d.getTime() === today.getTime();
|
||||
};
|
||||
}, [today]);
|
||||
|
||||
const isBeforeToday = (dateStr) => {
|
||||
const isBeforeToday = useCallback((dateStr) => {
|
||||
if (!dateStr) return false;
|
||||
const d = new Date(dateStr);
|
||||
d.setHours(0, 0, 0, 0);
|
||||
return d.getTime() < today.getTime();
|
||||
};
|
||||
}, [today]);
|
||||
|
||||
const sortByName = (a, b) => {
|
||||
const nameA = a.firstName.toLowerCase() + a.lastName.toLowerCase();
|
||||
const nameB = b.firstName.toLowerCase() + b.lastName.toLowerCase();
|
||||
return nameA?.localeCompare(nameB);
|
||||
};
|
||||
const sortByName = useCallback((a, b) => {
|
||||
const nameA = `${a.firstName || ""} ${a.lastName || ""}`.toLowerCase();
|
||||
const nameB = `${b.firstName || ""} ${b.lastName || ""}`.toLowerCase();
|
||||
return nameA.localeCompare(nameB);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const { startDate, endDate } = dateRange;
|
||||
@ -81,11 +95,29 @@ const AttendanceLog = ({
|
||||
setIsRefreshing(false);
|
||||
}, [dateRange, projectId, dispatch, isRefreshing]);
|
||||
|
||||
const filtering = (data) => {
|
||||
const filteredData = showOnlyCheckout
|
||||
const processedData = useMemo(() => {
|
||||
let filteredData = showOnlyCheckout
|
||||
? data.filter((item) => item.checkOutTime === null)
|
||||
: data;
|
||||
|
||||
// Apply search query filter
|
||||
if (searchQuery) {
|
||||
const lowerCaseSearchQuery = searchQuery.toLowerCase();
|
||||
filteredData = filteredData.filter((att) => {
|
||||
// Construct a full name from available parts, filtering out null/undefined
|
||||
const fullName = [att.firstName, att.middleName, att.lastName]
|
||||
.filter(Boolean) // This removes null, undefined, or empty string parts
|
||||
.join(" ")
|
||||
.toLowerCase();
|
||||
|
||||
return (
|
||||
att.employeeName?.toLowerCase().includes(lowerCaseSearchQuery) ||
|
||||
att.employeeId?.toLowerCase().includes(lowerCaseSearchQuery) ||
|
||||
fullName.includes(lowerCaseSearchQuery)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const group1 = filteredData
|
||||
.filter((d) => d.activity === 1 && isSameDay(d.checkInTime))
|
||||
.sort(sortByName);
|
||||
@ -130,71 +162,65 @@ const AttendanceLog = ({
|
||||
);
|
||||
|
||||
// Create the final sorted array
|
||||
const finalData = sortedDates.flatMap((date) => groupedByDate[date]);
|
||||
setProcessedData(finalData);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
filtering(data)
|
||||
}, [data, showOnlyCheckout]);
|
||||
return sortedDates.flatMap((date) => groupedByDate[date]);
|
||||
}, [data, showOnlyCheckout, searchQuery, isSameDay, isBeforeToday, sortByName]);
|
||||
|
||||
const {
|
||||
currentPage,
|
||||
totalPages,
|
||||
currentItems: paginatedAttendances,
|
||||
paginate,
|
||||
resetPage,
|
||||
resetPage, // Destructure resetPage here
|
||||
} = usePagination(processedData, 20);
|
||||
|
||||
// Reset to the first page whenever processedData changes (due to switch on/off)
|
||||
// Reset page when processedData changes (due to filters/search)
|
||||
useEffect(() => {
|
||||
resetPage();
|
||||
}, [processedData, resetPage]);
|
||||
}, [processedData, resetPage]); // Add resetPage to dependency array
|
||||
|
||||
const handler = useCallback(
|
||||
(msg) => {
|
||||
const { startDate, endDate } = dateRange;
|
||||
const checkIn = msg.response.checkInTime.substring(0, 10);
|
||||
if (
|
||||
projectId === msg.projectId &&
|
||||
startDate <= checkIn &&
|
||||
checkIn <= endDate
|
||||
) {
|
||||
const updatedAttendance = data.map((item) =>
|
||||
item.id === msg.response.id
|
||||
? { ...item, ...msg.response }
|
||||
: item
|
||||
);
|
||||
(msg) => {
|
||||
const { startDate, endDate } = dateRange;
|
||||
const checkIn = msg.response.checkInTime ? msg.response.checkInTime.substring(0, 10) : null;
|
||||
|
||||
filtering(updatedAttendance);
|
||||
resetPage();
|
||||
}
|
||||
},
|
||||
[projectId, dateRange, data, filtering, resetPage]
|
||||
);
|
||||
if (
|
||||
projectId === msg.projectId &&
|
||||
checkIn &&
|
||||
startDate <= checkIn &&
|
||||
checkIn <= endDate
|
||||
) {
|
||||
dispatch(
|
||||
fetchAttendanceData({
|
||||
projectId,
|
||||
fromDate: startDate,
|
||||
toDate: endDate,
|
||||
})
|
||||
);
|
||||
}
|
||||
},
|
||||
[projectId, dateRange, dispatch]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
useEffect(() => {
|
||||
eventBus.on("attendance_log", handler);
|
||||
return () => eventBus.off("attendance_log", handler);
|
||||
}, [handler]);
|
||||
|
||||
const employeeHandler = useCallback(
|
||||
const employeeHandler = useCallback(
|
||||
(msg) => {
|
||||
const { startDate, endDate } = dateRange;
|
||||
if (data.some((item) => item.employeeId == msg.employeeId)) {
|
||||
dispatch(
|
||||
fetchAttendanceData({
|
||||
projectId,
|
||||
fromDate: startDate,
|
||||
toDate: endDate,
|
||||
})
|
||||
)
|
||||
}
|
||||
dispatch(
|
||||
fetchAttendanceData({
|
||||
projectId,
|
||||
fromDate: startDate,
|
||||
toDate: endDate,
|
||||
})
|
||||
);
|
||||
},
|
||||
[projectId, dateRange,data]
|
||||
[projectId, dateRange, dispatch]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
useEffect(() => {
|
||||
eventBus.on("employee", employeeHandler);
|
||||
return () => eventBus.off("employee", employeeHandler);
|
||||
}, [employeeHandler]);
|
||||
@ -224,9 +250,8 @@ const AttendanceLog = ({
|
||||
</div>
|
||||
<div className="col-md-2 m-0 text-end">
|
||||
<i
|
||||
className={`bx bx-refresh cursor-pointer fs-4 ${
|
||||
loading || isRefreshing ? "spin" : ""
|
||||
}`}
|
||||
className={`bx bx-refresh cursor-pointer fs-4 ${loading || isRefreshing ? "spin" : ""
|
||||
}`}
|
||||
title="Refresh"
|
||||
onClick={() => setIsRefreshing(true)}
|
||||
/>
|
||||
@ -234,9 +259,9 @@ const AttendanceLog = ({
|
||||
</div>
|
||||
<div
|
||||
className="table-responsive text-nowrap"
|
||||
style={{ minHeight: "200px", display: 'flex', alignItems: 'center', justifyContent: 'center' }}
|
||||
style={{ minHeight: "200px", display: 'flex' }}
|
||||
>
|
||||
{data && data.length > 0 && (
|
||||
{processedData && processedData.length > 0 ? (
|
||||
<table className="table mb-0">
|
||||
<thead>
|
||||
<tr>
|
||||
@ -269,9 +294,9 @@ const AttendanceLog = ({
|
||||
const previousAttendance = arr[index - 1];
|
||||
const previousDate = previousAttendance
|
||||
? moment(
|
||||
previousAttendance.checkInTime ||
|
||||
previousAttendance.checkOutTime
|
||||
).format("YYYY-MM-DD")
|
||||
previousAttendance.checkInTime ||
|
||||
previousAttendance.checkOutTime
|
||||
).format("YYYY-MM-DD")
|
||||
: null;
|
||||
|
||||
if (!previousDate || currentDate !== previousDate) {
|
||||
@ -289,7 +314,7 @@ const AttendanceLog = ({
|
||||
);
|
||||
}
|
||||
acc.push(
|
||||
<tr key={index}>
|
||||
<tr key={attendance.id || index}>
|
||||
<td colSpan={2}>
|
||||
<div className="d-flex justify-content-start align-items-center">
|
||||
<Avatar
|
||||
@ -330,17 +355,22 @@ const AttendanceLog = ({
|
||||
}, [])}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
{!loading && !isRefreshing && data.length === 0 && (
|
||||
<span className="text-muted">No employee logs</span>
|
||||
)}
|
||||
{/* {error && !loading && !isRefreshing && (
|
||||
<tr>
|
||||
<td colSpan={6}>{error}</td>
|
||||
</tr>
|
||||
)} */}
|
||||
) : (
|
||||
!loading &&
|
||||
!isRefreshing && (
|
||||
<div
|
||||
className="d-flex justify-content-center align-items-center text-muted"
|
||||
style={{
|
||||
width: "100%",
|
||||
}}
|
||||
>
|
||||
No employee logs.
|
||||
</div>
|
||||
)
|
||||
)
|
||||
}
|
||||
</div>
|
||||
{!loading && !isRefreshing && processedData.length > 10 && (
|
||||
{!loading && !isRefreshing && processedData.length > 20 && (
|
||||
<nav aria-label="Page ">
|
||||
<ul className="pagination pagination-sm justify-content-end py-1">
|
||||
<li className={`page-item ${currentPage === 1 ? "disabled" : ""}`}>
|
||||
@ -355,9 +385,8 @@ const AttendanceLog = ({
|
||||
(pageNumber) => (
|
||||
<li
|
||||
key={pageNumber}
|
||||
className={`page-item ${
|
||||
currentPage === pageNumber ? "active" : ""
|
||||
}`}
|
||||
className={`page-item ${currentPage === pageNumber ? "active" : ""
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
className="page-link"
|
||||
@ -369,9 +398,8 @@ const AttendanceLog = ({
|
||||
)
|
||||
)}
|
||||
<li
|
||||
className={`page-item ${
|
||||
currentPage === totalPages ? "disabled" : ""
|
||||
}`}
|
||||
className={`page-item ${currentPage === totalPages ? "disabled" : ""
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
className="page-link"
|
||||
@ -387,4 +415,4 @@ const AttendanceLog = ({
|
||||
);
|
||||
};
|
||||
|
||||
export default AttendanceLog;
|
||||
export default AttendanceLog;
|
@ -7,51 +7,39 @@ import { useRegularizationRequests } from "../../hooks/useAttendance";
|
||||
import moment from "moment";
|
||||
import usePagination from "../../hooks/usePagination";
|
||||
import eventBus from "../../services/eventBus";
|
||||
import { cacheData, clearCacheKey } from "../../slices/apiDataManager";
|
||||
import { cacheData } from "../../slices/apiDataManager";
|
||||
|
||||
const Regularization = ({ handleRequest }) => {
|
||||
var selectedProject = useSelector((store) => store.localVariables.projectId);
|
||||
const [regularizesList, setregularizedList] = useState([]);
|
||||
const { regularizes, loading, error, refetch } =
|
||||
useRegularizationRequests(selectedProject);
|
||||
const Regularization = ({ handleRequest, searchQuery }) => {
|
||||
const selectedProject = useSelector((store) => store.localVariables.projectId);
|
||||
const [regularizesList, setRegularizedList] = useState([]);
|
||||
const { regularizes, loading, refetch } = useRegularizationRequests(selectedProject);
|
||||
|
||||
useEffect(() => {
|
||||
setregularizedList(regularizes);
|
||||
setRegularizedList(regularizes);
|
||||
}, [regularizes]);
|
||||
|
||||
const sortByName = (a, b) => {
|
||||
const nameA = a.firstName.toLowerCase() + a.lastName.toLowerCase();
|
||||
const nameB = b.firstName.toLowerCase() + b.lastName.toLowerCase();
|
||||
return nameA?.localeCompare(nameB);
|
||||
const nameA = (a.firstName + a.lastName).toLowerCase();
|
||||
const nameB = (b.firstName + b.lastName).toLowerCase();
|
||||
return nameA.localeCompare(nameB);
|
||||
};
|
||||
|
||||
const handler = useCallback(
|
||||
(msg) => {
|
||||
if (selectedProject == msg.projectId) {
|
||||
const updatedAttendance = regularizes?.filter( item => item.id !== msg.response.id );
|
||||
const updatedAttendance = regularizes?.filter(item => item.id !== msg.response.id);
|
||||
cacheData("regularizedList", {
|
||||
data: updatedAttendance,
|
||||
projectId: selectedProject,
|
||||
});
|
||||
// clearCacheKey("regularizedList")
|
||||
refetch();
|
||||
}
|
||||
},
|
||||
[selectedProject, regularizes]
|
||||
);
|
||||
|
||||
|
||||
const filteredData = [...regularizesList]?.sort(sortByName);
|
||||
|
||||
const { currentPage, totalPages, currentItems, paginate } = usePagination(
|
||||
filteredData,
|
||||
20
|
||||
);
|
||||
useEffect(() => {
|
||||
eventBus.on("regularization", handler);
|
||||
return () => eventBus.off("regularization", handler);
|
||||
}, [handler]);
|
||||
|
||||
const employeeHandler = useCallback(
|
||||
const employeeHandler = useCallback(
|
||||
(msg) => {
|
||||
if (regularizes.some((item) => item.employeeId == msg.employeeId)) {
|
||||
refetch();
|
||||
@ -60,16 +48,36 @@ const Regularization = ({ handleRequest }) => {
|
||||
[regularizes]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
useEffect(() => {
|
||||
eventBus.on("regularization", handler);
|
||||
return () => eventBus.off("regularization", handler);
|
||||
}, [handler]);
|
||||
|
||||
useEffect(() => {
|
||||
eventBus.on("employee", employeeHandler);
|
||||
return () => eventBus.off("employee", employeeHandler);
|
||||
}, [employeeHandler]);
|
||||
|
||||
// ✅ Search filter logic added here
|
||||
const filteredData = [...regularizesList]
|
||||
?.filter((item) => {
|
||||
if (!searchQuery) return true;
|
||||
const lowerSearch = searchQuery.toLowerCase();
|
||||
const fullName = `${item.firstName || ""} ${item.lastName || ""}`.toLowerCase();
|
||||
|
||||
return (
|
||||
item.firstName?.toLowerCase().includes(lowerSearch) ||
|
||||
item.lastName?.toLowerCase().includes(lowerSearch) ||
|
||||
fullName.includes(lowerSearch) ||
|
||||
item.employeeId?.toLowerCase().includes(lowerSearch)
|
||||
);
|
||||
})
|
||||
.sort(sortByName);
|
||||
|
||||
const { currentPage, totalPages, currentItems, paginate } = usePagination(filteredData, 20);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="table-responsive text-nowrap pb-4"
|
||||
|
||||
>
|
||||
<div className="table-responsive text-nowrap pb-4">
|
||||
<table className="table mb-0">
|
||||
<thead>
|
||||
<tr>
|
||||
@ -85,66 +93,53 @@ const Regularization = ({ handleRequest }) => {
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{/* {loading && (
|
||||
<td colSpan={6} className="text-center py-5">
|
||||
Loading...
|
||||
</td>
|
||||
)} */}
|
||||
|
||||
{!loading &&
|
||||
(currentItems?.length > 0 ? (
|
||||
currentItems?.map((att, index) => (
|
||||
<tr key={index}>
|
||||
<td colSpan={2}>
|
||||
<div className="d-flex justify-content-start align-items-center">
|
||||
<Avatar
|
||||
firstName={att.firstName}
|
||||
lastName={att.lastName}
|
||||
></Avatar>
|
||||
<div className="d-flex flex-column">
|
||||
<a href="#" className="text-heading text-truncate">
|
||||
<span className="fw-normal">
|
||||
{att.firstName} {att.lastName}
|
||||
</span>
|
||||
</a>
|
||||
</div>
|
||||
{!loading && currentItems?.length > 0 ? (
|
||||
currentItems.map((att, index) => (
|
||||
<tr key={index}>
|
||||
<td colSpan={2}>
|
||||
<div className="d-flex justify-content-start align-items-center">
|
||||
<Avatar firstName={att.firstName} lastName={att.lastName} />
|
||||
<div className="d-flex flex-column">
|
||||
<a href="#" className="text-heading text-truncate">
|
||||
<span className="fw-normal">
|
||||
{att.firstName} {att.lastName}
|
||||
</span>
|
||||
</a>
|
||||
</div>
|
||||
</td>
|
||||
<td>{moment(att.checkOutTime).format("DD-MMM-YYYY")}</td>
|
||||
<td>{convertShortTime(att.checkInTime)}</td>
|
||||
<td>
|
||||
{att.checkOutTime
|
||||
? convertShortTime(att.checkOutTime)
|
||||
: "--"}
|
||||
</td>
|
||||
<td className="text-center ">
|
||||
{/* <div className='d-flex justify-content-center align-items-center gap-3'> */}
|
||||
<RegularizationActions
|
||||
attendanceData={att}
|
||||
handleRequest={handleRequest}
|
||||
refresh={refetch}
|
||||
/>
|
||||
{/* </div> */}
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
) : (
|
||||
<tr>
|
||||
<td
|
||||
colSpan={6}
|
||||
className="text-center"
|
||||
style={{
|
||||
height: "200px",
|
||||
verticalAlign: "middle",
|
||||
borderBottom: "none",
|
||||
}}
|
||||
>
|
||||
No Record Found
|
||||
</div>
|
||||
</td>
|
||||
<td>{moment(att.checkOutTime).format("DD-MMM-YYYY")}</td>
|
||||
<td>{convertShortTime(att.checkInTime)}</td>
|
||||
<td>
|
||||
{att.checkOutTime ? convertShortTime(att.checkOutTime) : "--"}
|
||||
</td>
|
||||
<td className="text-center">
|
||||
<RegularizationActions
|
||||
attendanceData={att}
|
||||
handleRequest={handleRequest}
|
||||
refresh={refetch}
|
||||
/>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
))
|
||||
) : (
|
||||
<tr>
|
||||
<td
|
||||
colSpan={6}
|
||||
className="text-center"
|
||||
style={{
|
||||
height: "200px",
|
||||
verticalAlign: "middle",
|
||||
borderBottom: "none",
|
||||
}}
|
||||
>
|
||||
{loading ? "Loading..." : "No Record Found"}
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
{!loading && totalPages > 1 && (
|
||||
<nav aria-label="Page ">
|
||||
<ul className="pagination pagination-sm justify-content-end py-1 mt-3">
|
||||
@ -159,25 +154,18 @@ const Regularization = ({ handleRequest }) => {
|
||||
{[...Array(totalPages)].map((_, index) => (
|
||||
<li
|
||||
key={index}
|
||||
className={`page-item ${
|
||||
currentPage === index + 1 ? "active" : ""
|
||||
}`}
|
||||
className={`page-item ${currentPage === index + 1 ? "active" : ""}`}
|
||||
>
|
||||
<button
|
||||
className="page-link "
|
||||
onClick={() => paginate(index + 1)}
|
||||
>
|
||||
<button className="page-link" onClick={() => paginate(index + 1)}>
|
||||
{index + 1}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
<li
|
||||
className={`page-item ${
|
||||
currentPage === totalPages ? "disabled" : ""
|
||||
}`}
|
||||
className={`page-item ${currentPage === totalPages ? "disabled" : ""}`}
|
||||
>
|
||||
<button
|
||||
className="page-link "
|
||||
className="page-link"
|
||||
onClick={() => paginate(currentPage + 1)}
|
||||
>
|
||||
»
|
||||
@ -190,4 +178,4 @@ const Regularization = ({ handleRequest }) => {
|
||||
);
|
||||
};
|
||||
|
||||
export default Regularization;
|
||||
export default Regularization;
|
||||
|
@ -10,13 +10,11 @@ import AttendanceLog from "../../components/Activities/AttendcesLogs";
|
||||
import Attendance from "../../components/Activities/Attendance";
|
||||
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 { useDispatch, useSelector } from "react-redux";
|
||||
import { setProjectId } from "../../slices/localVariablesSlice";
|
||||
import { markCurrentAttendance } from "../../slices/apiSlice/attendanceAllSlice";
|
||||
import { hasUserPermission } from "../../utils/authUtils";
|
||||
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
|
||||
import { REGULARIZE_ATTENDANCE } from "../../utils/constants";
|
||||
import eventBus from "../../services/eventBus";
|
||||
@ -25,10 +23,11 @@ import { useProjectName } from "../../hooks/useProjects";
|
||||
|
||||
const AttendancePage = () => {
|
||||
const [activeTab, setActiveTab] = useState("all");
|
||||
const [ShowPending, setShowPending] = useState(false);
|
||||
const [showPending, setShowPending] = useState(false); // Renamed for consistency
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const loginUser = getCachedProfileData();
|
||||
var selectedProject = useSelector((store) => store.localVariables.projectId);
|
||||
const dispatch = useDispatch()
|
||||
const selectedProject = useSelector((store) => store.localVariables.projectId);
|
||||
const dispatch = useDispatch();
|
||||
const {
|
||||
attendance,
|
||||
loading: attLoading,
|
||||
@ -40,7 +39,7 @@ const AttendancePage = () => {
|
||||
const [modelConfig, setModelConfig] = useState();
|
||||
const DoRegularized = useHasUserPermission(REGULARIZE_ATTENDANCE);
|
||||
const { projectNames, loading: projectLoading, fetchData } = useProjectName();
|
||||
|
||||
|
||||
|
||||
const [formData, setFormData] = useState({
|
||||
markTime: "",
|
||||
@ -50,12 +49,16 @@ const AttendancePage = () => {
|
||||
|
||||
const handler = useCallback(
|
||||
(msg) => {
|
||||
if (selectedProject == msg.projectId) {
|
||||
const updatedAttendance = attendances.map((item) =>
|
||||
item.employeeId === msg.response.employeeId
|
||||
? { ...item, ...msg.response }
|
||||
: item
|
||||
);
|
||||
if (selectedProject === msg.projectId) {
|
||||
// Ensure attendances is not null before mapping
|
||||
const updatedAttendance = attendances
|
||||
? attendances.map((item) =>
|
||||
item.employeeId === msg.response.employeeId
|
||||
? { ...item, ...msg.response }
|
||||
: item
|
||||
)
|
||||
: [msg.response]; // If attendances is null, initialize with new response
|
||||
|
||||
cacheData("Attendance", {
|
||||
data: updatedAttendance,
|
||||
projectId: selectedProject,
|
||||
@ -63,12 +66,12 @@ const AttendancePage = () => {
|
||||
setAttendances(updatedAttendance);
|
||||
}
|
||||
},
|
||||
[selectedProject, attrecall]
|
||||
[selectedProject, attendances] // Removed attrecall as it's not a direct dependency for this state update
|
||||
);
|
||||
|
||||
const employeeHandler = useCallback(
|
||||
(msg) => {
|
||||
if (attendances.some((item) => item.employeeId == msg.employeeId)) {
|
||||
if (attendances?.some((item) => item.employeeId === msg.employeeId)) {
|
||||
AttendanceRepository.getAttendance(selectedProject)
|
||||
.then((response) => {
|
||||
cacheData("Attendance", { data: response.data, selectedProject });
|
||||
@ -85,7 +88,7 @@ const AttendancePage = () => {
|
||||
const getRole = (roleId) => {
|
||||
if (!empRoles) return "Unassigned";
|
||||
if (!roleId) return "Unassigned";
|
||||
const role = empRoles.find((b) => b.id == roleId);
|
||||
const role = empRoles.find((b) => b.id === roleId);
|
||||
return role ? role.role : "Unassigned";
|
||||
};
|
||||
|
||||
@ -105,24 +108,35 @@ const AttendancePage = () => {
|
||||
modalElement.classList.remove("show");
|
||||
modalElement.style.display = "none";
|
||||
document.body.classList.remove("modal-open");
|
||||
document.querySelector(".modal-backdrop")?.remove();
|
||||
const modalBackdrop = document.querySelector(".modal-backdrop");
|
||||
if (modalBackdrop) {
|
||||
modalBackdrop.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");
|
||||
// Check if payload and employeeId exist before mapping
|
||||
if (action.payload && action.payload.employeeId) {
|
||||
const updatedAttendance = attendances
|
||||
? attendances.map((item) =>
|
||||
item.employeeId === action.payload.employeeId
|
||||
? { ...item, ...action.payload }
|
||||
: item
|
||||
)
|
||||
: [action.payload]; // If attendances is null, initialize with new payload
|
||||
|
||||
cacheData("Attendance", {
|
||||
data: updatedAttendance,
|
||||
projectId: selectedProject,
|
||||
});
|
||||
setAttendances(updatedAttendance);
|
||||
showToast("Attendance Marked Successfully", "success");
|
||||
} else {
|
||||
showToast("Failed to mark attendance: Invalid response", "error");
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
showToast(error.message, "error");
|
||||
@ -130,31 +144,56 @@ const AttendancePage = () => {
|
||||
};
|
||||
|
||||
const handleToggle = (event) => {
|
||||
setShowOnlyCheckout(event.target.checked);
|
||||
setShowPending(event.target.checked);
|
||||
};
|
||||
useEffect(() => {
|
||||
if(selectedProject == null){
|
||||
dispatch(setProjectId(projectNames[0]?.id));
|
||||
}
|
||||
},[])
|
||||
if (selectedProject === null && projectNames.length > 0) {
|
||||
dispatch(setProjectId(projectNames[0]?.id));
|
||||
}
|
||||
}, [selectedProject, projectNames, dispatch]);
|
||||
|
||||
|
||||
// Open modal when modelConfig is set
|
||||
useEffect(() => {
|
||||
if (modelConfig !== null) {
|
||||
openModel();
|
||||
}
|
||||
}, [modelConfig, isCreateModalOpen]);
|
||||
}, [modelConfig]); // Removed isCreateModalOpen from here as it's set by openModel()
|
||||
|
||||
useEffect(() => {
|
||||
setAttendances(attendance);
|
||||
}, [attendance]);
|
||||
|
||||
// Filter and search logic for the 'Today's' tab (Attendance component)
|
||||
const filteredAndSearchedTodayAttendance = useCallback(() => {
|
||||
let currentData = attendances;
|
||||
|
||||
const filteredAttendance = ShowPending
|
||||
? attendances?.filter(
|
||||
if (showPending) {
|
||||
currentData = currentData?.filter(
|
||||
(att) => att?.checkInTime !== null && att?.checkOutTime === null
|
||||
)
|
||||
: attendances;
|
||||
);
|
||||
}
|
||||
|
||||
if (searchQuery) {
|
||||
const lowerCaseSearchQuery = searchQuery.toLowerCase();
|
||||
currentData = currentData?.filter((att) => {
|
||||
// Combine first, middle, and last names for a comprehensive search
|
||||
const fullName = [att.firstName, att.middleName, att.lastName]
|
||||
.filter(Boolean) // Remove null or undefined parts
|
||||
.join(" ")
|
||||
.toLowerCase();
|
||||
|
||||
return (
|
||||
att.employeeName?.toLowerCase().includes(lowerCaseSearchQuery) ||
|
||||
att.employeeId?.toLowerCase().includes(lowerCaseSearchQuery) ||
|
||||
fullName.includes(lowerCaseSearchQuery)
|
||||
);
|
||||
});
|
||||
}
|
||||
return currentData;
|
||||
}, [attendances, showPending, searchQuery]);
|
||||
|
||||
|
||||
// Event bus listeners
|
||||
useEffect(() => {
|
||||
eventBus.on("attendance", handler);
|
||||
return () => eventBus.off("attendance", handler);
|
||||
@ -190,97 +229,74 @@ const AttendancePage = () => {
|
||||
]}
|
||||
></Breadcrumb>
|
||||
<div className="nav-align-top nav-tabs-shadow">
|
||||
{/* <ul className="nav nav-tabs" role="tablist">
|
||||
<div
|
||||
className="dataTables_length text-start py-2 px-2 d-flex "
|
||||
id="DataTables_Table_0_length"
|
||||
>
|
||||
{loginUser && loginUser?.projects?.length > 1 && (
|
||||
<label>
|
||||
<select
|
||||
name="DataTables_Table_0_length"
|
||||
aria-controls="DataTables_Table_0"
|
||||
className="form-select form-select-sm"
|
||||
value={selectedProject}
|
||||
onChange={(e) => dispatch(setProjectId(e.target.value))}
|
||||
aria-label=""
|
||||
>
|
||||
{!projectLoading &&
|
||||
projects
|
||||
?.filter((project) =>
|
||||
loginUser?.projects?.map(String).includes(project.id)
|
||||
)
|
||||
.map((project) => (
|
||||
<option value={project.id} key={project.id}>
|
||||
{project.name}
|
||||
</option>
|
||||
))}
|
||||
{projectLoading && (
|
||||
<option value="Loading..." disabled>
|
||||
Loading...
|
||||
</option>
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
)}
|
||||
<ul className="nav nav-tabs d-flex justify-content-between align-items-center" role="tablist">
|
||||
<div className="d-flex">
|
||||
<li className="nav-item">
|
||||
<button
|
||||
type="button"
|
||||
className={`nav-link ${activeTab === "all" ? "active" : ""} fs-6`}
|
||||
onClick={() => setActiveTab("all")}
|
||||
data-bs-toggle="tab"
|
||||
data-bs-target="#navs-top-home"
|
||||
>
|
||||
Today's
|
||||
</button>
|
||||
</li>
|
||||
<li className="nav-item">
|
||||
<button
|
||||
type="button"
|
||||
className={`nav-link ${activeTab === "logs" ? "active" : ""} fs-6`}
|
||||
onClick={() => setActiveTab("logs")}
|
||||
data-bs-toggle="tab"
|
||||
data-bs-target="#navs-top-profile"
|
||||
>
|
||||
Logs
|
||||
</button>
|
||||
</li>
|
||||
<li className={`nav-item ${!DoRegularized && "d-none"}`}>
|
||||
<button
|
||||
type="button"
|
||||
className={`nav-link ${activeTab === "regularization" ? "active" : ""
|
||||
} fs-6`}
|
||||
onClick={() => setActiveTab("regularization")}
|
||||
data-bs-toggle="tab"
|
||||
data-bs-target="#navs-top-messages"
|
||||
>
|
||||
Regularization
|
||||
</button>
|
||||
</li>
|
||||
</div>
|
||||
{/* Search Box remains here */}
|
||||
<div className="p-2">
|
||||
<input
|
||||
type="text"
|
||||
className="form-control form-control-sm" // Bootstrap small size input
|
||||
placeholder="Search employee..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
// style={{ width: "200px", height: "30px" }} // Optional: further reduce width/height
|
||||
/>
|
||||
</div>
|
||||
</ul> */}
|
||||
|
||||
<ul className="nav nav-tabs" role="tablist">
|
||||
<li className="nav-item">
|
||||
<button
|
||||
type="button"
|
||||
className={`nav-link ${activeTab === "all" ? "active" : ""} fs-6`}
|
||||
onClick={() => setActiveTab("all")}
|
||||
data-bs-toggle="tab"
|
||||
data-bs-target="#navs-top-home"
|
||||
>
|
||||
Today's
|
||||
</button>
|
||||
</li>
|
||||
<li className="nav-item">
|
||||
<button
|
||||
type="button"
|
||||
className={`nav-link ${activeTab === "logs" ? "active" : ""} fs-6`}
|
||||
onClick={() => setActiveTab("logs")}
|
||||
data-bs-toggle="tab"
|
||||
data-bs-target="#navs-top-profile"
|
||||
>
|
||||
Logs
|
||||
</button>
|
||||
</li>
|
||||
<li className={`nav-item ${!DoRegularized && "d-none"}`}>
|
||||
<button
|
||||
type="button"
|
||||
className={`nav-link ${
|
||||
activeTab === "regularization" ? "active" : ""
|
||||
} fs-6`}
|
||||
onClick={() => setActiveTab("regularization")}
|
||||
data-bs-toggle="tab"
|
||||
data-bs-target="#navs-top-messages"
|
||||
>
|
||||
Regularization
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
<div className="tab-content attedanceTabs py-0 px-1 px-sm-3">
|
||||
{activeTab === "all" && (
|
||||
<>
|
||||
{!attLoading && (
|
||||
<div className="tab-pane fade show active py-0">
|
||||
<Attendance
|
||||
attendance={filteredAttendance}
|
||||
handleModalData={handleModalData}
|
||||
getRole={getRole}
|
||||
setshowOnlyCheckout={setShowPending}
|
||||
showOnlyCheckout={ShowPending}
|
||||
/>
|
||||
</div>
|
||||
<Attendance
|
||||
attendance={filteredAndSearchedTodayAttendance()}
|
||||
handleModalData={handleModalData}
|
||||
getRole={getRole}
|
||||
setshowOnlyCheckout={setShowPending}
|
||||
showOnlyCheckout={showPending}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{!attLoading && filteredAttendance?.length === 0 && (
|
||||
{!attLoading && filteredAndSearchedTodayAttendance()?.length === 0 && (
|
||||
<p>
|
||||
{" "}
|
||||
{ShowPending
|
||||
{showPending
|
||||
? "No Pending Available"
|
||||
: "No Employee assigned yet."}{" "}
|
||||
</p>
|
||||
@ -294,18 +310,21 @@ const AttendancePage = () => {
|
||||
handleModalData={handleModalData}
|
||||
projectId={selectedProject}
|
||||
setshowOnlyCheckout={setShowPending}
|
||||
showOnlyCheckout={ShowPending}
|
||||
showOnlyCheckout={showPending}
|
||||
searchQuery={searchQuery} // Pass search query to AttendanceLog
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === "regularization" && DoRegularized && (
|
||||
<div className="tab-pane fade show active py-0">
|
||||
<Regularization handleRequest={handleSubmit} />
|
||||
<Regularization
|
||||
handleRequest={handleSubmit}
|
||||
searchQuery={searchQuery} // ✅ Pass it here
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{attLoading && <span>Loading..</span>}
|
||||
{!attLoading && !attendances && <span>Not Found</span>}
|
||||
</div>
|
||||
</div>
|
||||
@ -314,4 +333,4 @@ const AttendancePage = () => {
|
||||
);
|
||||
};
|
||||
|
||||
export default AttendancePage;
|
||||
export default AttendancePage;
|
Loading…
x
Reference in New Issue
Block a user