All the changes of Search functionality in Attendance page.

This commit is contained in:
Kartik Sharma 2025-07-28 11:21:37 +05:30
parent 254aaf1977
commit 8b2aef8a52
8 changed files with 298 additions and 380 deletions

View File

@ -6,34 +6,27 @@ import RenderAttendanceStatus from "./RenderAttendanceStatus";
import usePagination from "../../hooks/usePagination";
import { useNavigate } from "react-router-dom";
import { ITEMS_PER_PAGE } from "../../utils/constants";
import { useAttendance } from "../../hooks/useAttendance";
import { useAttendance } from "../../hooks/useAttendance"; // This hook is already providing data
import { useSelector } from "react-redux";
import { useQueryClient } from "@tanstack/react-query";
import eventBus from "../../services/eventBus";
const Attendance = ({ getRole, handleModalData }) => {
const Attendance = ({ getRole, handleModalData, attendance: filteredAndSearchedAttendanceFromParent, showOnlyCheckout, setshowOnlyCheckout }) => {
const queryClient = useQueryClient();
const [loading, setLoading] = useState(false);
const navigate = useNavigate();
const [todayDate, setTodayDate] = useState(new Date());
const [ShowPending, setShowPending] = useState(false);
const selectedProject = useSelector(
(store) => store.localVariables.projectId
);
const {
attendance,
loading: attLoading,
recall: attrecall,
isFetching
} = useAttendance(selectedProject);
const filteredAttendance = ShowPending
? attendance?.filter(
(att) => att?.checkInTime !== null && att?.checkOutTime === null
)
: attendance;
} = useAttendance(selectedProject); // Keep this hook to manage recall and fetching status
const attendanceList = Array.isArray(filteredAttendance)
? filteredAttendance
const attendanceList = Array.isArray(filteredAndSearchedAttendanceFromParent)
? filteredAndSearchedAttendanceFromParent
: [];
const sortByName = (a, b) => {
@ -41,6 +34,7 @@ const Attendance = ({ getRole, handleModalData }) => {
const nameB = (b.firstName + b.lastName).toLowerCase();
return nameA?.localeCompare(nameB);
};
const group1 = attendanceList
.filter((d) => d.activity === 1 || d.activity === 4)
.sort(sortByName);
@ -48,41 +42,39 @@ const Attendance = ({ getRole, handleModalData }) => {
.filter((d) => d.activity === 0)
.sort(sortByName);
const filteredData = [...group1, ...group2];
const finalFilteredDataForPagination = [...group1, ...group2];
const { currentPage, totalPages, currentItems, paginate } = usePagination(
filteredData,
finalFilteredDataForPagination, // Use the data that's already been searched and grouped
ITEMS_PER_PAGE
);
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) {
queryClient.setQueryData(["attendance", selectedProject], (oldData) => {
if (!oldData) {
queryClient.invalidateQueries({queryKey:["attendance"]})
};
queryClient.invalidateQueries({ queryKey: ["attendance"] });
return; // Exit to avoid mapping on undefined oldData
}
return oldData.map((record) =>
record.employeeId === msg.response.employeeId ? { ...record, ...msg.response } : record
);
});
}
},
[selectedProject, attrecall]
[selectedProject, queryClient] // Added queryClient to dependencies
);
const employeeHandler = useCallback(
(msg) => {
if (attendances.some((item) => item.employeeId == msg.employeeId)) {
if (attrecall) { // Check if attrecall function exists
attrecall();
}
},
[selectedProject, attendance]
[attrecall] // Dependency should be attrecall, not `selectedProject` or `attendance` here
);
useEffect(() => {
eventBus.on("attendance", handler);
return () => eventBus.off("attendance", handler);
@ -105,13 +97,14 @@ const Attendance = ({ getRole, handleModalData }) => {
role="switch"
id="inactiveEmployeesCheckbox"
disabled={isFetching}
checked={ShowPending}
onChange={(e) => setShowPending(e.target.checked)}
checked={showOnlyCheckout} // Use prop for checked state
onChange={(e) => setshowOnlyCheckout(e.target.checked)} // Use prop for onChange
/>
<label className="form-check-label ms-0">Show Pending</label>
</div>
</div>
{Array.isArray(attendance) && attendance.length > 0 ? (
{/* Use `filteredAndSearchedAttendanceFromParent` for the initial check of data presence */}
{Array.isArray(filteredAndSearchedAttendanceFromParent) && filteredAndSearchedAttendanceFromParent.length > 0 ? (
<>
<table className="table ">
<thead>
@ -129,7 +122,7 @@ const Attendance = ({ getRole, handleModalData }) => {
</tr>
</thead>
<tbody className="table-border-bottom-0 ">
{currentItems &&
{currentItems && currentItems.length > 0 ? ( // Check currentItems length before mapping
currentItems
.sort((a, b) => {
const checkInA = a?.checkInTime
@ -186,18 +179,22 @@ const Attendance = ({ getRole, handleModalData }) => {
/>
</td>
</tr>
))}
{!attendance && (
<span className="text-secondary m-4">No employees assigned to the project!</span>
))
) : (
<tr>
<td colSpan="6" className="text-center text-muted py-4">
No matching records found.
</td>
</tr>
)}
</tbody>
</table>
{!loading && filteredData.length > 20 && (
{!attLoading && finalFilteredDataForPagination.length > ITEMS_PER_PAGE && ( // Use the data before pagination for total count check
<nav aria-label="Page ">
<ul className="pagination pagination-sm justify-content-end py-1">
<li
className={`page-item ${
className={`page-item ${
currentPage === 1 ? "disabled" : ""
}`}
>
@ -243,18 +240,20 @@ const Attendance = ({ getRole, handleModalData }) => {
<div>Loading...</div>
) : (
<div className="text-muted">
{Array.isArray(attendance)
? "No employees assigned to the project"
: "Attendance data unavailable"}
{/* Check the actual prop passed for initial data presence */}
{Array.isArray(filteredAndSearchedAttendanceFromParent) && filteredAndSearchedAttendanceFromParent.length === 0
? ""
: "Attendance data unavailable."}
</div>
)}
{currentItems?.length == 0 && attendance.length > 0 && (
<div className="my-4"><span className="text-secondary">No Pending Record Available !</span></div>
{/* This condition should check `currentItems` or `finalFilteredDataForPagination` */}
{currentItems?.length === 0 && finalFilteredDataForPagination.length > 0 && showOnlyCheckout && (
<div className="my-4"><span className="text-secondary">No Pending Record Available for your search!</span></div>
)}
</div>
</>
);
};
export default Attendance;
export default Attendance;

View File

@ -4,22 +4,19 @@ import Avatar from "../common/Avatar";
import { convertShortTime } from "../../utils/dateUtils";
import RenderAttendanceStatus from "./RenderAttendanceStatus";
import { useSelector, useDispatch } from "react-redux";
import { fetchAttendanceData, setAttendanceData } from "../../slices/apiSlice/attedanceLogsSlice"; // Make sure setAttendanceData is correctly imported
import { fetchAttendanceData, setAttendanceData } 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";
import { useAttendancesLogs } from "../../hooks/useAttendance";
import { queryClient } from "../../layouts/AuthLayout";
// Custom hook for pagination
const usePagination = (data, itemsPerPage) => {
const [currentPage, setCurrentPage] = useState(1);
// Ensure data is an array before accessing length
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);
@ -31,6 +28,7 @@ const usePagination = (data, itemsPerPage) => {
}
}, [maxPage]);
// Ensure resetPage is returned by the hook
const resetPage = useCallback(() => setCurrentPage(1), []);
return {
@ -47,28 +45,12 @@ const AttendanceLog = ({
projectId,
setshowOnlyCheckout,
showOnlyCheckout,
searchQuery,
searchQuery, // Prop for search query
}) => {
const selectedProject = useSelector(
(store) => store.localVariables.projectId
);
// Initialize date range with sensible defaults, e.g., last 7 days or current day
const defaultEndDate = moment().format("YYYY-MM-DD");
const defaultStartDate = moment().subtract(6, 'days').format("YYYY-MM-DD"); // Last 7 days including today
const [dateRange, setDateRange] = useState({
startDate: defaultStartDate,
endDate: defaultEndDate
});
const [dateRange, setDateRange] = useState({ startDate: "", endDate: "" });
const dispatch = useDispatch();
const [loading, setLoading] = useState(false);
const [showPending,setShowPending] = useState(false)
const { data: attendanceLogsData, loading: logsLoading, isFetching: logsFetching } = useSelector(
(state) => state.attendanceLogs
);
const [isRefreshing, setIsRefreshing] = useState(false); // Local state for refresh spinner
const { data, loading, error } = useSelector((store) => store.attendanceLogs);
const [isRefreshing, setIsRefreshing] = useState(false);
const today = useMemo(() => {
const d = new Date();
@ -79,25 +61,22 @@ const AttendanceLog = ({
const yesterday = useMemo(() => {
const d = new Date();
d.setDate(d.getDate() - 1);
d.setHours(0, 0, 0, 0); // Set to start of day for accurate comparison
return d;
}, []);
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
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 = useCallback((a, b) => {
const nameA = `${a.firstName || ""} ${a.lastName || ""}`.toLowerCase();
@ -105,7 +84,6 @@ const AttendanceLog = ({
return nameA.localeCompare(nameB);
}, []);
// Effect to fetch attendance data when dateRange or projectId changes
useEffect(() => {
const { startDate, endDate } = dateRange;
dispatch(
@ -115,33 +93,40 @@ const AttendanceLog = ({
toDate: endDate,
})
);
setIsRefreshing(false); // Reset refreshing state after fetch attempt
}, [dateRange, projectId, dispatch, isRefreshing]); // isRefreshing is a dependency because it triggers a re-fetch
setIsRefreshing(false);
}, [dateRange, projectId, dispatch, isRefreshing]);
const processedData = useMemo(() => {
let filteredData = showOnlyCheckout // Use the prop directly
? attendanceLogsData.filter((item) => item.checkOutTime === null) // Use attendanceLogsData
: attendanceLogsData; // Use attendanceLogsData
let filteredData = showOnlyCheckout
? data.filter((item) => item.checkOutTime === null)
: data;
// Apply search query filter
if (searchQuery) {
const lowerCaseSearchQuery = searchQuery.toLowerCase();
const lowerCaseSearchQuery = searchQuery.toLowerCase().trim(); // Trim whitespace
filteredData = filteredData.filter((att) => {
// Construct a full name from available parts, filtering out null/undefined
// Option 1: Combine firstName, middleName, lastName
const fullName = [att.firstName, att.middleName, att.lastName]
.filter(Boolean) // This removes null, undefined, or empty string parts
.join(" ")
.toLowerCase();
// Option 2: Check `employeeName` if it exists and is reliable
const employeeName = att.employeeName?.toLowerCase() || "";
// Option 3: Check `employeeId`
const employeeId = att.employeeId?.toLowerCase() || "";
// Check if the search query is included in any of the relevant fields
return (
att.employeeName?.toLowerCase().includes(lowerCaseSearchQuery) ||
att.employeeId?.toLowerCase().includes(lowerCaseSearchQuery) ||
fullName.includes(lowerCaseSearchQuery)
fullName.includes(lowerCaseSearchQuery) ||
employeeName.includes(lowerCaseSearchQuery) ||
employeeId.includes(lowerCaseSearchQuery)
);
});
}
// Grouping and sorting logic remains mostly the same, ensuring 'filteredData' is used
const group1 = filteredData
.filter((d) => d.activity === 1 && isSameDay(d.checkInTime))
.sort(sortByName);
@ -172,10 +157,7 @@ const AttendanceLog = ({
// Group by date
const groupedByDate = sortedList.reduce((acc, item) => {
// Use checkInTime for activity 1, and checkOutTime for others or if checkInTime is null
const dateString = item.activity === 1 ? item.checkInTime : item.checkOutTime;
const date = dateString ? moment(dateString).format("YYYY-MM-DD") : null;
const date = (item.checkInTime || item.checkOutTime)?.split("T")[0];
if (date) {
acc[date] = acc[date] || [];
acc[date].push(item);
@ -183,78 +165,65 @@ const AttendanceLog = ({
return acc;
}, {});
// Sort dates in descending order
const sortedDates = Object.keys(groupedByDate).sort(
(a, b) => new Date(b) - new Date(a)
);
// Create the final sorted array
return sortedDates.flatMap((date) => groupedByDate[date]);
}, [attendanceLogsData, showOnlyCheckout, searchQuery, isSameDay, isBeforeToday, sortByName]);
}, [data, showOnlyCheckout, searchQuery, isSameDay, isBeforeToday, sortByName]);
const {
currentPage,
totalPages,
currentItems: paginatedAttendances,
paginate,
resetPage,
resetPage, // Destructure resetPage here
} = usePagination(processedData, 20);
// Effect to reset pagination when search query or showOnlyCheckout changes
// Effect to reset pagination when search query changes
useEffect(() => {
resetPage();
}, [searchQuery, showOnlyCheckout, resetPage]);
}, [searchQuery, resetPage]); // Add resetPage to dependencies
// Handler for 'attendance_log' event from eventBus
// This will now trigger a re-fetch of data
const handler = useCallback(
(msg) => {
// Check if the event is relevant to the current project and date range
const { startDate, endDate } = dateRange;
const eventDate = (msg.response.checkInTime || msg.response.checkOutTime)?.substring(0, 10);
// Only refetch if the event relates to the currently viewed project and date range
const checkIn = msg.response.checkInTime.substring(0, 10);
if (
projectId === msg.projectId &&
eventDate &&
eventDate >= startDate && // Ensure eventDate is within the current range
eventDate <= endDate
startDate <= checkIn &&
checkIn <= endDate
) {
// Trigger a re-fetch of attendance data to get the latest state
dispatch(
fetchAttendanceData({
projectId,
fromDate: startDate,
toDate: endDate,
})
const updatedAttendance = data.map((item) =>
item.id === msg.response.id
? { ...item, ...msg.response }
: item
);
dispatch(setAttendanceData(updatedAttendance)); // Update Redux store
}
},
[projectId, dateRange, dispatch]
[projectId, dateRange, data, dispatch]
);
useEffect(() => {
eventBus.on("attendance_log", handler);
return () => eventBus.off("attendance_log", handler);
}, [handler]);
// Handler for 'employee' event from eventBus (already triggers a refetch)
const employeeHandler = useCallback(
(msg) => {
const { startDate, endDate } = dateRange;
if (data.some((item) => item.employeeId == msg.employeeId)) {
// dispatch(
// fetchAttendanceData({
// ,
// fromDate: startDate,
// toDate: endDate,
// })
// );
refetch()
}
dispatch(
fetchAttendanceData({
projectId,
fromDate: startDate,
toDate: endDate,
})
);
},
[selectedProject, dateRange, data]
[projectId, dateRange, dispatch]
);
useEffect(() => {
@ -262,11 +231,6 @@ const AttendanceLog = ({
return () => eventBus.off("employee", employeeHandler);
}, [employeeHandler]);
const handleRefreshClick = () => {
setIsRefreshing(true); // Set refreshing state to true
// The useEffect for fetching data will automatically trigger due to isRefreshing dependency
};
return (
<>
<div
@ -276,14 +240,13 @@ const AttendanceLog = ({
<div className="d-flex align-items-center my-0 ">
<DateRangePicker
onRangeChange={setDateRange}
defaultStartDate={yesterday.toLocaleDateString("en-CA")} // Pass default as string YYYY-MM-DD
defaultStartDate={yesterday}
/>
<div className="form-check form-switch text-start m-0 ms-5">
<input
type="checkbox"
className="form-check-input"
role="switch"
disabled={logsFetching}
id="inactiveEmployeesCheckbox"
checked={showOnlyCheckout}
onChange={(e) => setshowOnlyCheckout(e.target.checked)}
@ -293,10 +256,10 @@ const AttendanceLog = ({
</div>
<div className="col-md-2 m-0 text-end">
<i
className={`bx bx-refresh cursor-pointer fs-4 ${logsLoading || isRefreshing ? "spin" : ""
className={`bx bx-refresh cursor-pointer fs-4 ${loading || isRefreshing ? "spin" : ""
}`}
title="Refresh"
onClick={handleRefreshClick}
onClick={() => setIsRefreshing(true)}
/>
</div>
</div>
@ -304,12 +267,7 @@ const AttendanceLog = ({
className="table-responsive text-nowrap"
style={{ minHeight: "200px", display: 'flex' }}
>
{/* Conditional rendering for loading state */}
{(logsLoading || isRefreshing) ? (
<div className="d-flex justify-content-center align-items-center text-muted w-100">
Loading...
</div>
) : processedData && processedData.length > 0 ? (
{processedData && processedData.length > 0 ? (
<table className="table mb-0">
<thead>
<tr>
@ -328,84 +286,96 @@ const AttendanceLog = ({
</tr>
</thead>
<tbody>
{paginatedAttendances.reduce((acc, attendance, index, arr) => {
const currentDate = moment(
attendance.checkInTime || attendance.checkOutTime
).format("YYYY-MM-DD");
const previousAttendance = arr[index - 1];
const previousDate = previousAttendance
? moment(
previousAttendance.checkInTime ||
previousAttendance.checkOutTime
).format("YYYY-MM-DD")
: null;
{(loading || isRefreshing) && (
<tr>
<td colSpan={6}>Loading...</td>
</tr>
)}
{!loading &&
!isRefreshing &&
paginatedAttendances.reduce((acc, attendance, index, arr) => {
const currentDate = moment(
attendance.checkInTime || attendance.checkOutTime
).format("YYYY-MM-DD");
const previousAttendance = arr[index - 1];
const previousDate = previousAttendance
? moment(
previousAttendance.checkInTime ||
previousAttendance.checkOutTime
).format("YYYY-MM-DD")
: null;
if (!previousDate || currentDate !== previousDate) {
if (!previousDate || currentDate !== previousDate) {
acc.push(
<tr
key={`header-${currentDate}`}
className="table-row-header"
>
<td colSpan={6} className="text-start">
<strong>
{moment(currentDate).format("DD-MM-YYYY")}
</strong>
</td>
</tr>
);
}
acc.push(
<tr
key={`header-${currentDate}`}
className="table-row-header"
>
<td colSpan={6} className="text-start">
<strong>
{moment(currentDate).format("DD-MM-YYYY")}
</strong>
<tr key={attendance.id || index}>
<td colSpan={2}>
<div className="d-flex justify-content-start align-items-center">
<Avatar
firstName={attendance.firstName}
lastName={attendance.lastName}
/>
<div className="d-flex flex-column">
<a href="#" className="text-heading text-truncate">
<span className="fw-normal">
{attendance.firstName} {attendance.lastName}
</span>
</a>
</div>
</div>
</td>
<td>
{moment(
attendance.checkInTime || attendance.checkOutTime
).format("DD-MMM-YYYY")}
</td>
<td>{convertShortTime(attendance.checkInTime)}</td>
<td>
{attendance.checkOutTime
? convertShortTime(attendance.checkOutTime)
: "--"}
</td>
<td className="text-center">
<RenderAttendanceStatus
attendanceData={attendance}
handleModalData={handleModalData}
Tab={2}
currentDate={today.toLocaleDateString("en-CA")}
/>
</td>
</tr>
);
}
acc.push(
<tr key={attendance.id || index}>
<td colSpan={2}>
<div className="d-flex justify-content-start align-items-center">
<Avatar
firstName={attendance.firstName}
lastName={attendance.lastName}
/>
<div className="d-flex flex-column">
<a href="#" className="text-heading text-truncate">
<span className="fw-normal">
{attendance.firstName} {attendance.lastName}
</span>
</a>
</div>
</div>
</td>
<td>
{moment(
attendance.checkInTime || attendance.checkOutTime
).format("DD-MMM-YYYY")}
</td>
<td>{convertShortTime(attendance.checkInTime)}</td>
<td>
{attendance.checkOutTime
? convertShortTime(attendance.checkOutTime)
: "--"}
</td>
<td className="text-center">
<RenderAttendanceStatus
attendanceData={attendance}
handleModalData={handleModalData}
Tab={2}
currentDate={today.toLocaleDateString("en-CA")}
/>
</td>
</tr>
);
return acc;
}, [])}
return acc;
}, [])}
</tbody>
</table>
) : (
<div
className="d-flex justify-content-center align-items-center text-muted w-100"
style={{ height: "200px" }} // Added height for better visual during no data
>
No employee logs.
</div>
!loading &&
!isRefreshing && (
<div
className="d-flex justify-content-center align-items-center text-muted"
style={{
width: "100%",
}}
>
No employee logs.
</div>
)
)}
</div>
{!logsLoading && !isRefreshing && processedData.length > 20 && (
{!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" : ""}`}>
@ -420,9 +390,8 @@ const AttendanceLog = ({
(pageNumber) => (
<li
key={pageNumber}
className={`page-item ${
currentPage === pageNumber ? "active" : ""
}`}
className={`page-item ${currentPage === pageNumber ? "active" : ""
}`}
>
<button
className="page-link"
@ -434,9 +403,8 @@ const AttendanceLog = ({
)
)}
<li
className={`page-item ${
currentPage === totalPages ? "disabled" : ""
}`}
className={`page-item ${currentPage === totalPages ? "disabled" : ""
}`}
>
<button
className="page-link"
@ -452,4 +420,4 @@ const AttendanceLog = ({
);
};
export default AttendanceLog;
export default AttendanceLog;

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({

View File

@ -7,55 +7,47 @@ 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 { useQueryClient } from "@tanstack/react-query";
import { cacheData } from "../../slices/apiDataManager";
const Regularization = ({ handleRequest }) => {
const queryClient = useQueryClient();
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);
// Update regularizesList when regularizes data changes
useEffect(() => {
setregularizedList(regularizes);
setRegularizedList(regularizes);
}, [regularizes]);
const sortByName = useCallback((a, b) => {
const sortByName = (a, b) => {
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) { // Use strict equality for comparison
// Filter out the updated item to effectively remove it from the list
// as it's likely been processed (approved/rejected)
const updatedAttendance = regularizesList?.filter(item => item.id !== msg.response.id);
if (selectedProject == msg.projectId) {
const updatedAttendance = regularizes?.filter(item => item.id !== msg.response.id);
cacheData("regularizedList", {
data: updatedAttendance,
projectId: selectedProject,
});
// Refetch to get the latest data from the source, ensuring consistency
refetch();
}
},
[selectedProject, regularizesList, refetch] // Added regularizesList and refetch to dependencies
[selectedProject, regularizes]
);
const employeeHandler = useCallback(
(msg) => {
// If any regularization request belongs to the updated employee, refetch
if (regularizes?.some((item) => item.employeeId === msg.employeeId)) { // Use strict equality
if (regularizes.some((item) => item.employeeId == msg.employeeId)) {
refetch();
}
},
[regularizes, refetch] // Added refetch to dependencies
[regularizes]
);
// Event bus listeners
useEffect(() => {
eventBus.on("regularization", handler);
return () => eventBus.off("regularization", handler);
@ -66,7 +58,7 @@ const Regularization = ({ handleRequest }) => {
return () => eventBus.off("employee", employeeHandler);
}, [employeeHandler]);
// Search filter logic
// Search filter logic added here
const filteredData = [...regularizesList]
?.filter((item) => {
if (!searchQuery) return true;
@ -86,34 +78,27 @@ const Regularization = ({ handleRequest }) => {
return (
<div className="table-responsive text-nowrap pb-4">
{loading ? (
<div className="my-2">
<p className="text-secondary">Loading...</p>
</div>
) : currentItems?.length > 0 ? (
<table className="table mb-0">
<thead>
<tr>
<th colSpan={2}>Name</th>
<th>Date</th>
<th>
<i className="bx bxs-down-arrow-alt text-success"></i>Check-In
</th>
<th>
<i className="bx bxs-up-arrow-alt text-danger"></i>Check-Out
</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{currentItems?.map((att, index) => (
<table className="table mb-0">
<thead>
<tr>
<th colSpan={2}>Name</th>
<th>Date</th>
<th>
<i className="bx bxs-down-arrow-alt text-success"></i>Check-In
</th>
<th>
<i className="bx bxs-up-arrow-alt text-danger"></i>Check-Out
</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{!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>
<Avatar firstName={att.firstName} lastName={att.lastName} />
<div className="d-flex flex-column">
<a href="#" className="text-heading text-truncate">
<span className="fw-normal">
@ -128,28 +113,37 @@ const Regularization = ({ handleRequest }) => {
<td>
{att.checkOutTime ? convertShortTime(att.checkOutTime) : "--"}
</td>
<td className="text-center ">
<td className="text-center">
<RegularizationActions
attendanceData={att}
handleRequest={handleRequest}
refresh={refetch}
/>
{/* </div> */}
</td>
</tr>
))}
</tbody>
</table>
) : (
<div className="my-4">
{" "}
<span className="text-secondary">No Requests Found !</span>
</div>
)}
))
) : (
<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">
<li className={`page-item  ${currentPage === 1 ? "disabled" : ""}`}>
<li className={`page-item ${currentPage === 1 ? "disabled" : ""}`}>
<button
className="page-link btn-xs"
onClick={() => paginate(currentPage - 1)}
@ -160,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)}
>
&raquo;

View File

@ -5,7 +5,6 @@ import { useDashboardTasksCardData } from "../../hooks/useDashboard_Data";
const TasksCard = () => {
const projectId = useSelector((store) => store.localVariables?.projectId);
const { tasksCardData, loading, error } = useDashboardTasksCardData(projectId);
console.log(tasksCardData);
return (
<div className="card p-3 h-100 text-center d-flex justify-content-between">

View File

@ -37,7 +37,7 @@ const Header = () => {
const allowedProjectStatusIds = [
"603e994b-a27f-4e5d-a251-f3d69b0498ba", // On Hold
"cdad86aa-8a56-4ff4-b633-9c629057dfef", // In Progress
"ef1c356e-0fe0-42df-a5d3-8daee355492d", // Inactive - Removed as per requirement
// "ef1c356e-0fe0-42df-a5d3-8daee355492d", // Inactive - Removed as per requirement
"b74da4c2-d07e-46f2-9919-e75e49b12731", // Active
];

View File

@ -104,17 +104,15 @@ export const useDashboardTeamsCardData = (projectId) => {
useEffect(() => {
const fetchTeamsData = async () => {
if (!projectId) return; // Skip if projectId is not provided
setLoading(true);
setError("");
try {
const response = await GlobalRepository.getDashboardTeamsCardData(projectId);
setTeamsData(response.data); // Handle undefined/null
setTeamsData(response.data || {});
} catch (err) {
setError("Failed to fetch teams card data.");
console.error(err);
console.error("Error fetching teams card data:", err);
setTeamsData({});
} finally {
setLoading(false);

View File

@ -1,57 +1,50 @@
import React, { useState, useEffect, useCallback } from "react";
import {
cacheData,
clearCacheKey,
getCachedData,
getCachedProfileData,
} from "../../slices/apiDataManager"; // clearCacheKey and getCachedData are not used
} from "../../slices/apiDataManager";
import Breadcrumb from "../../components/common/Breadcrumb";
import AttendanceLog from "../../components/Activities/AttendcesLogs";
import Attendance from "../../components/Activities/Attendance";
// import AttendanceModel from "../../components/Activities/AttendanceModel";
import AttendanceModel from "../../components/Activities/AttendanceModel";
import showToast from "../../services/toastService";
// import { useProjects } from "../../hooks/useProjects";
import Regularization from "../../components/Activities/Regularization";
import { useAttendance } 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 { markCurrentAttendance } from "../../slices/apiSlice/attendanceAllSlice";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { REGULARIZE_ATTENDANCE } from "../../utils/constants";
import eventBus from "../../services/eventBus";
// import AttendanceRepository from "../../repositories/AttendanceRepository";
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 [searchQuery, setSearchQuery] = useState("");
// const loginUser = getCachedProfileData(); // Declared but not used
const loginUser = getCachedProfileData();
const selectedProject = useSelector((store) => store.localVariables.projectId);
const dispatch = useDispatch();
const {
attendance,
loading: attLoading,
// recall: attrecall, // Declared but not used in the current logic
recall: attrecall,
} = useAttendance(selectedProject);
const [attendances, setAttendances] = useState();
const [empRoles, setEmpRoles] = useState(null); // This state is declared but never populated or used
const [empRoles, setEmpRoles] = useState(null);
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
const [modelConfig, setModelConfig] = useState(null); // Initialize with null for clarity
const [modelConfig, setModelConfig] = useState(null); // Initialize as null
const DoRegularized = useHasUserPermission(REGULARIZE_ATTENDANCE);
// const { projectNames, loading: projectLoading, fetchData } = useProjectName(); // loading and fetchData are not used directly here
const { projectNames, loading: projectLoading, fetchData } = useProjectName();
// FormData is declared but not used in the provided snippet's logic
// const [formData, setFormData] = useState({
// markTime: "",
// description: "",
// date: new Date().toLocaleDateString(),
// });
const [formData, setFormData] = useState({
markTime: "",
description: "",
date: new Date().toLocaleDateString(),
});
const handler = useCallback(
(msg) => {
@ -66,7 +59,7 @@ const AttendancePage = () => {
cacheData("Attendance", {
data: updatedAttendance,
projectId: selectedProject, // Corrected key from selectedProject to projectId for consistency
projectId: selectedProject,
});
setAttendances(updatedAttendance);
}
@ -76,13 +69,11 @@ const AttendancePage = () => {
const employeeHandler = useCallback(
(msg) => {
// This logic fetches all attendance when an employee event occurs,
// which might be inefficient if only a single employee's data needs updating.
// Consider a more granular update if performance is an issue.
// This logic seems fine for refetching if an employee ID exists in current attendances
if (attendances?.some((item) => item.employeeId === msg.employeeId)) {
AttendanceRepository.getAttendance(selectedProject)
.then((response) => {
cacheData("Attendance", { data: response.data, projectId: selectedProject }); // Corrected key
cacheData("Attendance", { data: response.data, selectedProject });
setAttendances(response.data);
})
.catch((error) => {
@ -93,29 +84,27 @@ const AttendancePage = () => {
[selectedProject, attendances]
);
// The `getRole` function has a duplicate line: `const role = empRoles.find((b) => b.id === roleId);`
// Also, `empRoles` is declared but never set. If this function is meant to be used,
// `empRoles` needs to be fetched and set in the state.
const getRole = useCallback((roleId) => {
if (!empRoles) return "Unassigned"; // empRoles is always null with current code
const getRole = (roleId) => {
if (!empRoles) return "Unassigned";
if (!roleId) return "Unassigned";
const role = empRoles.find((b) => b.id === roleId);
return role ? role.role : "Unassigned";
}, [empRoles]);
const openModel = useCallback(() => {
setIsCreateModalOpen(true);
}, []);
};
// Simplified and moved modal opening logic
const handleModalData = useCallback((employee) => {
setModelConfig(employee);
setIsCreateModalOpen(true); // Open the modal directly when data is set
}, []);
const closeModal = useCallback(() => {
setModelConfig(null);
setIsCreateModalOpen(false);
// Directly manipulating DOM is generally discouraged in React.
// Consider using React state to control modal visibility.
// Directly manipulating the DOM is generally not recommended in React.
// React handles modal visibility via state. If you must, ensure it's
// for external libraries or for very specific, controlled reasons.
// For a typical Bootstrap modal, just setting `isCreateModalOpen` to false
// should be enough if the modal component itself handles the Bootstrap classes.
const modalElement = document.getElementById("check-Out-modal");
if (modalElement) {
modalElement.classList.remove("show");
@ -155,24 +144,17 @@ const AttendancePage = () => {
});
}, [dispatch, attendances, selectedProject]);
const handleToggle = useCallback((event) => {
setShowPending(event.target.checked);
}, []);
// Use useProjectName hook to get projectNames and set selected project
const { projectNames } = useProjectName();
const handleToggle = (event) => {
setShowPending(event.target.checked);
};
useEffect(() => {
if (selectedProject === null && projectNames.length > 0) {
dispatch(setProjectId(projectNames[0]?.id));
}
}, [selectedProject, projectNames, dispatch]);
useEffect(() => {
if (modelConfig !== null) {
openModel();
}
}, [modelConfig, openModel]); // Added openModel to dependency array
useEffect(() => {
setAttendances(attendance);
}, [attendance]);
@ -204,8 +186,6 @@ const AttendancePage = () => {
return currentData;
}, [attendances, showPending, searchQuery]);
// Event bus listeners
useEffect(() => {
eventBus.on("attendance", handler);
return () => eventBus.off("attendance", handler);
@ -218,11 +198,11 @@ const AttendancePage = () => {
return (
<>
{/* {isCreateModalOpen && modelConfig && (
{isCreateModalOpen && modelConfig && (
<div
className="modal fade show"
style={{ display: "block" }}
id="check-Out-modalg"
id="check-Out-modal"
tabIndex="-1"
aria-hidden="true"
>
@ -232,29 +212,6 @@ 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">
@ -265,7 +222,10 @@ const AttendancePage = () => {
]}
></Breadcrumb>
<div className="nav-align-top nav-tabs-shadow">
<ul className="nav nav-tabs d-flex justify-content-between align-items-center" role="tablist">
<ul
className="nav nav-tabs d-flex justify-content-between align-items-center"
role="tablist"
>
<div className="d-flex">
<li className="nav-item">
<button
@ -292,8 +252,9 @@ const AttendancePage = () => {
<li className={`nav-item ${!DoRegularized && "d-none"}`}>
<button
type="button"
className={`nav-link ${activeTab === "regularization" ? "active" : ""
} fs-6`}
className={`nav-link ${
activeTab === "regularization" ? "active" : ""
} fs-6`}
onClick={() => setActiveTab("regularization")}
data-bs-toggle="tab"
data-bs-target="#navs-top-messages"
@ -302,7 +263,6 @@ const AttendancePage = () => {
</button>
</li>
</div>
{/* Search Box remains here */}
<div className="p-2">
<input
type="text"
@ -312,30 +272,33 @@ const AttendancePage = () => {
onChange={(e) => setSearchQuery(e.target.value)}
/>
</div>
</ul>
<div className="tab-content attedanceTabs py-0 px-1 px-sm-3" >
<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={filteredAndSearchedTodayAttendance()}
handleModalData={handleModalData}
getRole={getRole}
setshowOnlyCheckout={setShowPending}
showOnlyCheckout={showPending}
searchQuery={searchQuery}
/>
</div>
)}
{!attLoading && filteredAndSearchedTodayAttendance()?.length === 0 && (
<p>
{" "}
{showPending
{showPending
? "No Pending Available"
: "No Employee assigned yet."}{" "}
</p>
)}
</div>
</>
)}
{activeTab === "logs" && (
<div className="tab-pane fade show active py-0">
<AttendanceLog
@ -347,6 +310,7 @@ const AttendancePage = () => {
/>
</div>
)}
{activeTab === "regularization" && DoRegularized && (
<div className="tab-pane fade show active py-0">
<Regularization
@ -355,6 +319,8 @@ const AttendancePage = () => {
/>
</div>
)}
{!attLoading && !attendances && <span>Not Found</span>}
</div>
</div>
</div>
@ -362,4 +328,4 @@ const AttendancePage = () => {
);
};
export default AttendancePage;
export default AttendancePage;