Refactor_Expenses #321
@ -4,7 +4,7 @@ import Avatar from "../common/Avatar";
|
|||||||
import { convertShortTime } from "../../utils/dateUtils";
|
import { convertShortTime } from "../../utils/dateUtils";
|
||||||
import RenderAttendanceStatus from "./RenderAttendanceStatus";
|
import RenderAttendanceStatus from "./RenderAttendanceStatus";
|
||||||
import { useSelector, useDispatch } from "react-redux";
|
import { useSelector, useDispatch } from "react-redux";
|
||||||
import { fetchAttendanceData } from "../../slices/apiSlice/attedanceLogsSlice";
|
import { fetchAttendanceData, setAttendanceData } from "../../slices/apiSlice/attedanceLogsSlice"; // Make sure setAttendanceData is correctly imported
|
||||||
import DateRangePicker from "../common/DateRangePicker";
|
import DateRangePicker from "../common/DateRangePicker";
|
||||||
import { clearCacheKey, getCachedData } from "../../slices/apiDataManager";
|
import { clearCacheKey, getCachedData } from "../../slices/apiDataManager";
|
||||||
import eventBus from "../../services/eventBus";
|
import eventBus from "../../services/eventBus";
|
||||||
@ -12,16 +12,25 @@ import AttendanceRepository from "../../repositories/AttendanceRepository";
|
|||||||
import { useAttendancesLogs } from "../../hooks/useAttendance";
|
import { useAttendancesLogs } from "../../hooks/useAttendance";
|
||||||
import { queryClient } from "../../layouts/AuthLayout";
|
import { queryClient } from "../../layouts/AuthLayout";
|
||||||
|
|
||||||
|
// Custom hook for pagination
|
||||||
const usePagination = (data, itemsPerPage) => {
|
const usePagination = (data, itemsPerPage) => {
|
||||||
const [currentPage, setCurrentPage] = useState(1);
|
const [currentPage, setCurrentPage] = useState(1);
|
||||||
const maxPage = Math.ceil(data.length / itemsPerPage);
|
// 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(() => {
|
const currentItems = useMemo(() => {
|
||||||
const startIndex = (currentPage - 1) * itemsPerPage;
|
const startIndex = (currentPage - 1) * itemsPerPage;
|
||||||
const endIndex = startIndex + itemsPerPage;
|
const endIndex = startIndex + itemsPerPage;
|
||||||
return data.slice(startIndex, endIndex);
|
return data.slice(startIndex, endIndex);
|
||||||
}, [data, currentPage, itemsPerPage]);
|
}, [data, currentPage, itemsPerPage]);
|
||||||
|
|
||||||
const paginate = useCallback((pageNumber) => setCurrentPage(pageNumber), []);
|
const paginate = useCallback((pageNumber) => {
|
||||||
|
if (pageNumber > 0 && pageNumber <= maxPage) {
|
||||||
|
setCurrentPage(pageNumber);
|
||||||
|
}
|
||||||
|
}, [maxPage]);
|
||||||
|
|
||||||
const resetPage = useCallback(() => setCurrentPage(1), []);
|
const resetPage = useCallback(() => setCurrentPage(1), []);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@ -35,21 +44,44 @@ const usePagination = (data, itemsPerPage) => {
|
|||||||
|
|
||||||
const AttendanceLog = ({
|
const AttendanceLog = ({
|
||||||
handleModalData,
|
handleModalData,
|
||||||
|
projectId,
|
||||||
|
setshowOnlyCheckout,
|
||||||
|
showOnlyCheckout,
|
||||||
|
searchQuery,
|
||||||
}) => {
|
}) => {
|
||||||
const selectedProject = useSelector(
|
const selectedProject = useSelector(
|
||||||
(store) => store.localVariables.projectId
|
(store) => store.localVariables.projectId
|
||||||
);
|
);
|
||||||
const [dateRange, setDateRange] = useState({ startDate: "", endDate: "" });
|
// 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 dispatch = useDispatch();
|
const dispatch = useDispatch();
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const [showPending,setShowPending] = useState(false)
|
const [showPending,setShowPending] = useState(false)
|
||||||
|
|
||||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
const { data: attendanceLogsData, loading: logsLoading, isFetching: logsFetching } = useSelector(
|
||||||
const [processedData, setProcessedData] = useState([]);
|
(state) => state.attendanceLogs
|
||||||
|
);
|
||||||
|
|
||||||
const today = new Date();
|
const [isRefreshing, setIsRefreshing] = useState(false); // Local state for refresh spinner
|
||||||
today.setHours(0, 0, 0, 0);
|
|
||||||
|
|
||||||
|
const today = useMemo(() => {
|
||||||
|
const d = new Date();
|
||||||
|
d.setHours(0, 0, 0, 0);
|
||||||
|
return d;
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
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();
|
const yesterday = new Date();
|
||||||
yesterday.setDate(yesterday.getDate() - 1);
|
yesterday.setDate(yesterday.getDate() - 1);
|
||||||
|
|
||||||
@ -67,28 +99,49 @@ const AttendanceLog = ({
|
|||||||
return d.getTime() < today.getTime();
|
return d.getTime() < today.getTime();
|
||||||
};
|
};
|
||||||
|
|
||||||
const sortByName = (a, b) => {
|
const sortByName = useCallback((a, b) => {
|
||||||
const nameA = a.firstName.toLowerCase() + a.lastName.toLowerCase();
|
const nameA = `${a.firstName || ""} ${a.lastName || ""}`.toLowerCase();
|
||||||
const nameB = b.firstName.toLowerCase() + b.lastName.toLowerCase();
|
const nameB = `${b.firstName || ""} ${b.lastName || ""}`.toLowerCase();
|
||||||
return nameA?.localeCompare(nameB);
|
return nameA.localeCompare(nameB);
|
||||||
};
|
}, []);
|
||||||
|
|
||||||
const {
|
// Effect to fetch attendance data when dateRange or projectId changes
|
||||||
data = [],
|
useEffect(() => {
|
||||||
isLoading,
|
const { startDate, endDate } = dateRange;
|
||||||
error,
|
dispatch(
|
||||||
refetch,
|
fetchAttendanceData({
|
||||||
isFetching,
|
projectId,
|
||||||
} = useAttendancesLogs(
|
fromDate: startDate,
|
||||||
selectedProject,
|
toDate: endDate,
|
||||||
dateRange.startDate,
|
})
|
||||||
dateRange.endDate
|
);
|
||||||
);
|
setIsRefreshing(false); // Reset refreshing state after fetch attempt
|
||||||
const filtering = (data) => {
|
}, [dateRange, projectId, dispatch, isRefreshing]); // isRefreshing is a dependency because it triggers a re-fetch
|
||||||
const filteredData = showPending
|
|
||||||
? data.filter((item) => item.checkOutTime === null)
|
|
||||||
: data;
|
|
||||||
|
|
||||||
|
const processedData = useMemo(() => {
|
||||||
|
let filteredData = showOnlyCheckout // Use the prop directly
|
||||||
|
? attendanceLogsData.filter((item) => item.checkOutTime === null) // Use attendanceLogsData
|
||||||
|
: attendanceLogsData; // Use attendanceLogsData
|
||||||
|
|
||||||
|
// 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)
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Grouping and sorting logic remains mostly the same, ensuring 'filteredData' is used
|
||||||
const group1 = filteredData
|
const group1 = filteredData
|
||||||
.filter((d) => d.activity === 1 && isSameDay(d.checkInTime))
|
.filter((d) => d.activity === 1 && isSameDay(d.checkInTime))
|
||||||
.sort(sortByName);
|
.sort(sortByName);
|
||||||
@ -119,7 +172,10 @@ const AttendanceLog = ({
|
|||||||
|
|
||||||
// Group by date
|
// Group by date
|
||||||
const groupedByDate = sortedList.reduce((acc, item) => {
|
const groupedByDate = sortedList.reduce((acc, item) => {
|
||||||
const date = (item.checkInTime || item.checkOutTime)?.split("T")[0];
|
// 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;
|
||||||
|
|
||||||
if (date) {
|
if (date) {
|
||||||
acc[date] = acc[date] || [];
|
acc[date] = acc[date] || [];
|
||||||
acc[date].push(item);
|
acc[date].push(item);
|
||||||
@ -131,13 +187,9 @@ const AttendanceLog = ({
|
|||||||
(a, b) => new Date(b) - new Date(a)
|
(a, b) => new Date(b) - new Date(a)
|
||||||
);
|
);
|
||||||
|
|
||||||
const finalData = sortedDates.flatMap((date) => groupedByDate[date]);
|
// Create the final sorted array
|
||||||
setProcessedData(finalData);
|
return sortedDates.flatMap((date) => groupedByDate[date]);
|
||||||
};
|
}, [attendanceLogsData, showOnlyCheckout, searchQuery, isSameDay, isBeforeToday, sortByName]);
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
filtering(data);
|
|
||||||
}, [data, showPending]);
|
|
||||||
|
|
||||||
const {
|
const {
|
||||||
currentPage,
|
currentPage,
|
||||||
@ -147,40 +199,46 @@ const AttendanceLog = ({
|
|||||||
resetPage,
|
resetPage,
|
||||||
} = usePagination(processedData, 20);
|
} = usePagination(processedData, 20);
|
||||||
|
|
||||||
|
// Effect to reset pagination when search query or showOnlyCheckout changes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
resetPage();
|
resetPage();
|
||||||
}, [processedData, resetPage]);
|
}, [searchQuery, showOnlyCheckout, resetPage]);
|
||||||
|
|
||||||
|
// Handler for 'attendance_log' event from eventBus
|
||||||
|
// This will now trigger a re-fetch of data
|
||||||
const handler = useCallback(
|
const handler = useCallback(
|
||||||
(msg) => {
|
(msg) => {
|
||||||
|
// Check if the event is relevant to the current project and date range
|
||||||
const { startDate, endDate } = dateRange;
|
const { startDate, endDate } = dateRange;
|
||||||
const checkIn = msg.response.checkInTime.substring(0, 10);
|
const eventDate = (msg.response.checkInTime || msg.response.checkOutTime)?.substring(0, 10);
|
||||||
if (
|
|
||||||
selectedProject === msg.projectId &&
|
|
||||||
startDate <= checkIn &&
|
|
||||||
checkIn <= endDate
|
|
||||||
) {
|
|
||||||
queryClient.setQueriesData(["attendanceLogs"],(oldData)=>{
|
|
||||||
if(!oldData) {
|
|
||||||
queryClient.invalidateQueries({queryKey:["attendanceLogs"]})
|
|
||||||
}
|
|
||||||
return oldData.map((record) =>
|
|
||||||
record.id === msg.response.id ? { ...record, ...msg.response } : record
|
|
||||||
);
|
|
||||||
})
|
|
||||||
|
|
||||||
filtering(updatedAttendance);
|
// Only refetch if the event relates to the currently viewed project and date range
|
||||||
resetPage();
|
if (
|
||||||
|
projectId === msg.projectId &&
|
||||||
|
eventDate &&
|
||||||
|
eventDate >= startDate && // Ensure eventDate is within the current range
|
||||||
|
eventDate <= endDate
|
||||||
|
) {
|
||||||
|
// Trigger a re-fetch of attendance data to get the latest state
|
||||||
|
dispatch(
|
||||||
|
fetchAttendanceData({
|
||||||
|
projectId,
|
||||||
|
fromDate: startDate,
|
||||||
|
toDate: endDate,
|
||||||
|
})
|
||||||
|
);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[selectedProject, dateRange, data, filtering, resetPage]
|
[projectId, dateRange, dispatch]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
eventBus.on("attendance_log", handler);
|
eventBus.on("attendance_log", handler);
|
||||||
return () => eventBus.off("attendance_log", handler);
|
return () => eventBus.off("attendance_log", handler);
|
||||||
}, [handler]);
|
}, [handler]);
|
||||||
|
|
||||||
|
// Handler for 'employee' event from eventBus (already triggers a refetch)
|
||||||
const employeeHandler = useCallback(
|
const employeeHandler = useCallback(
|
||||||
(msg) => {
|
(msg) => {
|
||||||
const { startDate, endDate } = dateRange;
|
const { startDate, endDate } = dateRange;
|
||||||
@ -204,6 +262,11 @@ const AttendanceLog = ({
|
|||||||
return () => eventBus.off("employee", employeeHandler);
|
return () => eventBus.off("employee", employeeHandler);
|
||||||
}, [employeeHandler]);
|
}, [employeeHandler]);
|
||||||
|
|
||||||
|
const handleRefreshClick = () => {
|
||||||
|
setIsRefreshing(true); // Set refreshing state to true
|
||||||
|
// The useEffect for fetching data will automatically trigger due to isRefreshing dependency
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div
|
<div
|
||||||
@ -213,35 +276,40 @@ const AttendanceLog = ({
|
|||||||
<div className="d-flex align-items-center my-0 ">
|
<div className="d-flex align-items-center my-0 ">
|
||||||
<DateRangePicker
|
<DateRangePicker
|
||||||
onRangeChange={setDateRange}
|
onRangeChange={setDateRange}
|
||||||
defaultStartDate={yesterday}
|
defaultStartDate={yesterday.toLocaleDateString("en-CA")} // Pass default as string YYYY-MM-DD
|
||||||
/>
|
/>
|
||||||
<div className="form-check form-switch text-start m-0 ms-5">
|
<div className="form-check form-switch text-start m-0 ms-5">
|
||||||
<input
|
<input
|
||||||
type="checkbox"
|
type="checkbox"
|
||||||
className="form-check-input"
|
className="form-check-input"
|
||||||
role="switch"
|
role="switch"
|
||||||
disabled={isFetching}
|
disabled={logsFetching}
|
||||||
id="inactiveEmployeesCheckbox"
|
id="inactiveEmployeesCheckbox"
|
||||||
checked={showPending}
|
checked={showOnlyCheckout}
|
||||||
onChange={(e) => setShowPending(e.target.checked)}
|
onChange={(e) => setshowOnlyCheckout(e.target.checked)}
|
||||||
/>
|
/>
|
||||||
<label className="form-check-label ms-0">Show Pending</label>
|
<label className="form-check-label ms-0">Show Pending</label>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="col-md-2 m-0 text-end">
|
<div className="col-md-2 m-0 text-end">
|
||||||
<i
|
<i
|
||||||
className={`bx bx-refresh cursor-pointer fs-4 ${
|
className={`bx bx-refresh cursor-pointer fs-4 ${logsLoading || isRefreshing ? "spin" : ""
|
||||||
isFetching ? "spin" : ""
|
}`}
|
||||||
}`}
|
|
||||||
title="Refresh"
|
title="Refresh"
|
||||||
onClick={() => refetch()}
|
onClick={handleRefreshClick}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="table-responsive text-nowrap">
|
<div
|
||||||
{isLoading ? (
|
className="table-responsive text-nowrap"
|
||||||
<div><p className="text-secondary">Loading...</p></div>
|
style={{ minHeight: "200px", display: 'flex' }}
|
||||||
) : data?.length > 0 ? (
|
>
|
||||||
|
{/* 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 ? (
|
||||||
<table className="table mb-0">
|
<table className="table mb-0">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr>
|
||||||
@ -267,9 +335,9 @@ const AttendanceLog = ({
|
|||||||
const previousAttendance = arr[index - 1];
|
const previousAttendance = arr[index - 1];
|
||||||
const previousDate = previousAttendance
|
const previousDate = previousAttendance
|
||||||
? moment(
|
? moment(
|
||||||
previousAttendance.checkInTime ||
|
previousAttendance.checkInTime ||
|
||||||
previousAttendance.checkOutTime
|
previousAttendance.checkOutTime
|
||||||
).format("YYYY-MM-DD")
|
).format("YYYY-MM-DD")
|
||||||
: null;
|
: null;
|
||||||
|
|
||||||
if (!previousDate || currentDate !== previousDate) {
|
if (!previousDate || currentDate !== previousDate) {
|
||||||
@ -287,7 +355,7 @@ const AttendanceLog = ({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
acc.push(
|
acc.push(
|
||||||
<tr key={index}>
|
<tr key={attendance.id || index}>
|
||||||
<td colSpan={2}>
|
<td colSpan={2}>
|
||||||
<div className="d-flex justify-content-start align-items-center">
|
<div className="d-flex justify-content-start align-items-center">
|
||||||
<Avatar
|
<Avatar
|
||||||
@ -329,13 +397,15 @@ const AttendanceLog = ({
|
|||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
) : (
|
) : (
|
||||||
<div className="my-4"><span className="text-secondary">No Record Available !</span></div>
|
<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>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{paginatedAttendances?.length == 0 && data?.length > 0 && (
|
{!logsLoading && !isRefreshing && processedData.length > 20 && (
|
||||||
<div className="my-4"><span className="text-secondary">No Pending Record Available !</span></div>
|
|
||||||
)}
|
|
||||||
{processedData.length > 10 && (
|
|
||||||
<nav aria-label="Page ">
|
<nav aria-label="Page ">
|
||||||
<ul className="pagination pagination-sm justify-content-end py-1">
|
<ul className="pagination pagination-sm justify-content-end py-1">
|
||||||
<li className={`page-item ${currentPage === 1 ? "disabled" : ""}`}>
|
<li className={`page-item ${currentPage === 1 ? "disabled" : ""}`}>
|
||||||
|
|||||||
@ -17,68 +17,73 @@ const Regularization = ({ handleRequest }) => {
|
|||||||
const { regularizes, loading, error, refetch } =
|
const { regularizes, loading, error, refetch } =
|
||||||
useRegularizationRequests(selectedProject);
|
useRegularizationRequests(selectedProject);
|
||||||
|
|
||||||
|
// Update regularizesList when regularizes data changes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setregularizedList(regularizes);
|
setregularizedList(regularizes);
|
||||||
}, [regularizes]);
|
}, [regularizes]);
|
||||||
|
|
||||||
const sortByName = (a, b) => {
|
const sortByName = useCallback((a, b) => {
|
||||||
const nameA = a.firstName.toLowerCase() + a.lastName.toLowerCase();
|
const nameA = (a.firstName + a.lastName).toLowerCase();
|
||||||
const nameB = b.firstName.toLowerCase() + b.lastName.toLowerCase();
|
const nameB = (b.firstName + b.lastName).toLowerCase();
|
||||||
return nameA?.localeCompare(nameB);
|
return nameA.localeCompare(nameB);
|
||||||
};
|
}, []);
|
||||||
|
|
||||||
const handler = useCallback(
|
const handler = useCallback(
|
||||||
(msg) => {
|
(msg) => {
|
||||||
if (selectedProject == msg.projectId) {
|
if (selectedProject === msg.projectId) { // Use strict equality for comparison
|
||||||
// const updatedAttendance = regularizes?.filter(
|
// Filter out the updated item to effectively remove it from the list
|
||||||
// (item) => item.id !== msg.response.id
|
// as it's likely been processed (approved/rejected)
|
||||||
// );
|
const updatedAttendance = regularizesList?.filter(item => item.id !== msg.response.id);
|
||||||
// cacheData("regularizedList", {
|
cacheData("regularizedList", {
|
||||||
// data: updatedAttendance,
|
data: updatedAttendance,
|
||||||
// projectId: selectedProject,
|
projectId: selectedProject,
|
||||||
// });
|
});
|
||||||
// refetch();
|
// Refetch to get the latest data from the source, ensuring consistency
|
||||||
|
refetch();
|
||||||
queryClient.setQueryData(
|
|
||||||
["regularizedList", selectedProject],
|
|
||||||
(oldData) => {
|
|
||||||
if (!oldData) {
|
|
||||||
queryClient.invalidateQueries({ queryKey: ["regularizedList"] });
|
|
||||||
}
|
|
||||||
return oldData.filter((record) => record.id !== msg.response.id);
|
|
||||||
}
|
|
||||||
),
|
|
||||||
queryClient.invalidateQueries({ queryKey: ["attendanceLogs"] });
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[selectedProject, regularizes]
|
[selectedProject, regularizesList, refetch] // Added regularizesList and refetch to dependencies
|
||||||
);
|
);
|
||||||
|
|
||||||
const filteredData = [...regularizesList]?.sort(sortByName);
|
const employeeHandler = useCallback(
|
||||||
|
(msg) => {
|
||||||
const { currentPage, totalPages, currentItems, paginate } = usePagination(
|
// If any regularization request belongs to the updated employee, refetch
|
||||||
filteredData,
|
if (regularizes?.some((item) => item.employeeId === msg.employeeId)) { // Use strict equality
|
||||||
20
|
refetch();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[regularizes, refetch] // Added refetch to dependencies
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Event bus listeners
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
eventBus.on("regularization", handler);
|
eventBus.on("regularization", handler);
|
||||||
return () => eventBus.off("regularization", handler);
|
return () => eventBus.off("regularization", handler);
|
||||||
}, [handler]);
|
}, [handler]);
|
||||||
|
|
||||||
const employeeHandler = useCallback(
|
|
||||||
(msg) => {
|
|
||||||
if (regularizes.some((item) => item.employeeId == msg.employeeId)) {
|
|
||||||
refetch();
|
|
||||||
}
|
|
||||||
},
|
|
||||||
[regularizes]
|
|
||||||
);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
eventBus.on("employee", employeeHandler);
|
eventBus.on("employee", employeeHandler);
|
||||||
return () => eventBus.off("employee", employeeHandler);
|
return () => eventBus.off("employee", employeeHandler);
|
||||||
}, [employeeHandler]);
|
}, [employeeHandler]);
|
||||||
|
|
||||||
|
// Search filter logic
|
||||||
|
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 (
|
return (
|
||||||
<div className="table-responsive text-nowrap pb-4">
|
<div className="table-responsive text-nowrap pb-4">
|
||||||
{loading ? (
|
{loading ? (
|
||||||
@ -144,7 +149,7 @@ const Regularization = ({ handleRequest }) => {
|
|||||||
{!loading && totalPages > 1 && (
|
{!loading && totalPages > 1 && (
|
||||||
<nav aria-label="Page ">
|
<nav aria-label="Page ">
|
||||||
<ul className="pagination pagination-sm justify-content-end py-1 mt-3">
|
<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
|
<button
|
||||||
className="page-link btn-xs"
|
className="page-link btn-xs"
|
||||||
onClick={() => paginate(currentPage - 1)}
|
onClick={() => paginate(currentPage - 1)}
|
||||||
|
|||||||
@ -1,10 +1,8 @@
|
|||||||
import React, { useState, useEffect, useCallback } from "react";
|
import React, { useState, useEffect, useCallback } from "react";
|
||||||
import {
|
import {
|
||||||
cacheData,
|
cacheData,
|
||||||
clearCacheKey,
|
|
||||||
getCachedData,
|
|
||||||
getCachedProfileData,
|
getCachedProfileData,
|
||||||
} from "../../slices/apiDataManager";
|
} from "../../slices/apiDataManager"; // clearCacheKey and getCachedData are not used
|
||||||
import Breadcrumb from "../../components/common/Breadcrumb";
|
import Breadcrumb from "../../components/common/Breadcrumb";
|
||||||
import AttendanceLog from "../../components/Activities/AttendcesLogs";
|
import AttendanceLog from "../../components/Activities/AttendcesLogs";
|
||||||
import Attendance from "../../components/Activities/Attendance";
|
import Attendance from "../../components/Activities/Attendance";
|
||||||
@ -30,102 +28,194 @@ import { useQueryClient } from "@tanstack/react-query";
|
|||||||
|
|
||||||
const AttendancePage = () => {
|
const AttendancePage = () => {
|
||||||
const [activeTab, setActiveTab] = useState("all");
|
const [activeTab, setActiveTab] = useState("all");
|
||||||
const [ShowPending, setShowPending] = useState(false);
|
const [showPending, setShowPending] = useState(false);
|
||||||
const queryClient = useQueryClient();
|
const [searchQuery, setSearchQuery] = useState("");
|
||||||
const loginUser = getCachedProfileData();
|
// const loginUser = getCachedProfileData(); // Declared but not used
|
||||||
var selectedProject = useSelector((store) => store.localVariables.projectId);
|
const selectedProject = useSelector((store) => store.localVariables.projectId);
|
||||||
const dispatch = useDispatch();
|
const dispatch = useDispatch();
|
||||||
// const {
|
|
||||||
// attendance,
|
const {
|
||||||
// loading: attLoading,
|
attendance,
|
||||||
// recall: attrecall,
|
loading: attLoading,
|
||||||
// } = useAttendance(selectedProject);
|
// recall: attrecall, // Declared but not used in the current logic
|
||||||
|
} = useAttendance(selectedProject);
|
||||||
const [attendances, setAttendances] = useState();
|
const [attendances, setAttendances] = useState();
|
||||||
const [empRoles, setEmpRoles] = useState(null);
|
const [empRoles, setEmpRoles] = useState(null); // This state is declared but never populated or used
|
||||||
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
|
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
|
||||||
const [modelConfig, setModelConfig] = useState();
|
const [modelConfig, setModelConfig] = useState(null); // Initialize with null for clarity
|
||||||
const DoRegularized = useHasUserPermission(REGULARIZE_ATTENDANCE);
|
const DoRegularized = useHasUserPermission(REGULARIZE_ATTENDANCE);
|
||||||
const { projectNames, loading: projectLoading, fetchData } = useProjectName();
|
// const { projectNames, loading: projectLoading, fetchData } = useProjectName(); // loading and fetchData are not used directly here
|
||||||
|
|
||||||
const [formData, setFormData] = useState({
|
// FormData is declared but not used in the provided snippet's logic
|
||||||
markTime: "",
|
// const [formData, setFormData] = useState({
|
||||||
description: "",
|
// markTime: "",
|
||||||
date: new Date().toLocaleDateString(),
|
// description: "",
|
||||||
});
|
// date: new Date().toLocaleDateString(),
|
||||||
|
// });
|
||||||
|
|
||||||
// const handler = useCallback(
|
const handler = useCallback(
|
||||||
// (msg) => {
|
(msg) => {
|
||||||
// if (selectedProject == msg.projectId) {
|
if (selectedProject === msg.projectId) {
|
||||||
// const updatedAttendance = attendances.map((item) =>
|
const updatedAttendance = attendances
|
||||||
// item.employeeId === msg.response.employeeId
|
? attendances.map((item) =>
|
||||||
// ? { ...item, ...msg.response }
|
item.employeeId === msg.response.employeeId
|
||||||
// : item
|
? { ...item, ...msg.response }
|
||||||
// );
|
: item
|
||||||
// queryClient.setQueryData(["attendance", selectedProject], (oldData) => {
|
)
|
||||||
// if (!oldData) return oldData;
|
: [msg.response];
|
||||||
// return oldData.map((emp) =>
|
|
||||||
// emp.employeeId === data.employeeId ? { ...emp, ...data } : emp
|
|
||||||
// );
|
|
||||||
// });
|
|
||||||
// }
|
|
||||||
// },
|
|
||||||
// [selectedProject, attrecall]
|
|
||||||
// );
|
|
||||||
|
|
||||||
// const employeeHandler = useCallback(
|
cacheData("Attendance", {
|
||||||
// (msg) => {
|
data: updatedAttendance,
|
||||||
// if (attendances.some((item) => item.employeeId == msg.employeeId)) {
|
projectId: selectedProject, // Corrected key from selectedProject to projectId for consistency
|
||||||
// attrecall();
|
});
|
||||||
// }
|
setAttendances(updatedAttendance);
|
||||||
// },
|
}
|
||||||
// [selectedProject, attendances]
|
},
|
||||||
// );
|
[selectedProject, attendances]
|
||||||
useEffect(() => {
|
);
|
||||||
if (selectedProject == null) {
|
|
||||||
dispatch(setProjectId(projectNames[0]?.id));
|
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.
|
||||||
|
if (attendances?.some((item) => item.employeeId === msg.employeeId)) {
|
||||||
|
AttendanceRepository.getAttendance(selectedProject)
|
||||||
|
.then((response) => {
|
||||||
|
cacheData("Attendance", { data: response.data, projectId: selectedProject }); // Corrected key
|
||||||
|
setAttendances(response.data);
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.error(error);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[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
|
||||||
|
if (!roleId) return "Unassigned";
|
||||||
|
const role = empRoles.find((b) => b.id === roleId);
|
||||||
|
return role ? role.role : "Unassigned";
|
||||||
|
}, [empRoles]);
|
||||||
|
|
||||||
|
const openModel = useCallback(() => {
|
||||||
|
setIsCreateModalOpen(true);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleModalData = useCallback((employee) => {
|
||||||
|
setModelConfig(employee);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const closeModal = useCallback(() => {
|
||||||
|
setModelConfig(null);
|
||||||
|
setIsCreateModalOpen(false);
|
||||||
|
// Directly manipulating DOM is generally discouraged in React.
|
||||||
|
// Consider using React state to control modal visibility.
|
||||||
|
const modalElement = document.getElementById("check-Out-modal");
|
||||||
|
if (modalElement) {
|
||||||
|
modalElement.classList.remove("show");
|
||||||
|
modalElement.style.display = "none";
|
||||||
|
document.body.classList.remove("modal-open");
|
||||||
|
const modalBackdrop = document.querySelector(".modal-backdrop");
|
||||||
|
if (modalBackdrop) {
|
||||||
|
modalBackdrop.remove();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const getRole = (roleId) => {
|
const handleSubmit = useCallback((formData) => {
|
||||||
if (!empRoles) return "Unassigned";
|
dispatch(markCurrentAttendance(formData))
|
||||||
if (!roleId) return "Unassigned";
|
.then((action) => {
|
||||||
const role = empRoles.find((b) => b.id == roleId);
|
if (action.payload && action.payload.employeeId) {
|
||||||
return role ? role.role : "Unassigned";
|
const updatedAttendance = attendances
|
||||||
};
|
? attendances.map((item) =>
|
||||||
|
item.employeeId === action.payload.employeeId
|
||||||
|
? { ...item, ...action.payload }
|
||||||
|
: item
|
||||||
|
)
|
||||||
|
: [action.payload];
|
||||||
|
|
||||||
const openModel = () => {
|
cacheData("Attendance", {
|
||||||
setIsCreateModalOpen(true);
|
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");
|
||||||
|
});
|
||||||
|
}, [dispatch, attendances, selectedProject]);
|
||||||
|
|
||||||
const handleModalData = (employee) => {
|
const handleToggle = useCallback((event) => {
|
||||||
setModelConfig(employee);
|
setShowPending(event.target.checked);
|
||||||
};
|
}, []);
|
||||||
|
|
||||||
const closeModal = () => {
|
|
||||||
setModelConfig(null);
|
|
||||||
setIsCreateModalOpen(false);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handleToggle = (event) => {
|
|
||||||
setShowOnlyCheckout(event.target.checked);
|
|
||||||
};
|
|
||||||
|
|
||||||
|
// Use useProjectName hook to get projectNames and set selected project
|
||||||
|
const { projectNames } = useProjectName();
|
||||||
|
useEffect(() => {
|
||||||
|
if (selectedProject === null && projectNames.length > 0) {
|
||||||
|
dispatch(setProjectId(projectNames[0]?.id));
|
||||||
|
}
|
||||||
|
}, [selectedProject, projectNames, dispatch]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (modelConfig !== null) {
|
if (modelConfig !== null) {
|
||||||
openModel();
|
openModel();
|
||||||
}
|
}
|
||||||
}, [modelConfig, isCreateModalOpen]);
|
}, [modelConfig, openModel]); // Added openModel to dependency array
|
||||||
|
|
||||||
// useEffect(() => {
|
useEffect(() => {
|
||||||
// eventBus.on("attendance", handler);
|
setAttendances(attendance);
|
||||||
// return () => eventBus.off("attendance", handler);
|
}, [attendance]);
|
||||||
// }, [handler]);
|
|
||||||
|
const filteredAndSearchedTodayAttendance = useCallback(() => {
|
||||||
|
let currentData = attendances;
|
||||||
|
|
||||||
|
if (showPending) {
|
||||||
|
currentData = currentData?.filter(
|
||||||
|
(att) => att?.checkInTime !== null && att?.checkOutTime === null
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (searchQuery) {
|
||||||
|
const lowerCaseSearchQuery = searchQuery.toLowerCase();
|
||||||
|
currentData = currentData?.filter((att) => {
|
||||||
|
const fullName = [att.firstName, att.middleName, att.lastName]
|
||||||
|
.filter(Boolean)
|
||||||
|
.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);
|
||||||
|
}, [handler]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
eventBus.on("employee", employeeHandler);
|
||||||
|
return () => eventBus.off("employee", employeeHandler);
|
||||||
|
}, [employeeHandler]);
|
||||||
|
|
||||||
// useEffect(() => {
|
|
||||||
// eventBus.on("employee", employeeHandler);
|
|
||||||
// return () => eventBus.off("employee", employeeHandler);
|
|
||||||
// }, [employeeHandler]);
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{/* {isCreateModalOpen && modelConfig && (
|
{/* {isCreateModalOpen && modelConfig && (
|
||||||
@ -174,47 +264,55 @@ const AttendancePage = () => {
|
|||||||
{ label: "Attendance", link: null },
|
{ label: "Attendance", link: null },
|
||||||
]}
|
]}
|
||||||
></Breadcrumb>
|
></Breadcrumb>
|
||||||
<div className="nav-align-top nav-tabs-shadow" >
|
<div className="nav-align-top nav-tabs-shadow">
|
||||||
<ul className="nav nav-tabs" role="tablist">
|
<ul className="nav nav-tabs d-flex justify-content-between align-items-center" role="tablist">
|
||||||
<li className="nav-item">
|
<div className="d-flex">
|
||||||
<button
|
<li className="nav-item">
|
||||||
type="button"
|
<button
|
||||||
className={`nav-link ${
|
type="button"
|
||||||
activeTab === "all" ? "active" : ""
|
className={`nav-link ${activeTab === "all" ? "active" : ""} fs-6`}
|
||||||
} fs-6`}
|
onClick={() => setActiveTab("all")}
|
||||||
onClick={() => setActiveTab("all")}
|
data-bs-toggle="tab"
|
||||||
data-bs-toggle="tab"
|
data-bs-target="#navs-top-home"
|
||||||
data-bs-target="#navs-top-home"
|
>
|
||||||
>
|
Today's
|
||||||
Today's
|
</button>
|
||||||
</button>
|
</li>
|
||||||
</li>
|
<li className="nav-item">
|
||||||
<li className="nav-item">
|
<button
|
||||||
<button
|
type="button"
|
||||||
type="button"
|
className={`nav-link ${activeTab === "logs" ? "active" : ""} fs-6`}
|
||||||
className={`nav-link ${
|
onClick={() => setActiveTab("logs")}
|
||||||
activeTab === "logs" ? "active" : ""
|
data-bs-toggle="tab"
|
||||||
} fs-6`}
|
data-bs-target="#navs-top-profile"
|
||||||
onClick={() => setActiveTab("logs")}
|
>
|
||||||
data-bs-toggle="tab"
|
Logs
|
||||||
data-bs-target="#navs-top-profile"
|
</button>
|
||||||
>
|
</li>
|
||||||
Logs
|
<li className={`nav-item ${!DoRegularized && "d-none"}`}>
|
||||||
</button>
|
<button
|
||||||
</li>
|
type="button"
|
||||||
<li className={`nav-item ${!DoRegularized && "d-none"}`}>
|
className={`nav-link ${activeTab === "regularization" ? "active" : ""
|
||||||
<button
|
} fs-6`}
|
||||||
type="button"
|
onClick={() => setActiveTab("regularization")}
|
||||||
className={`nav-link ${
|
data-bs-toggle="tab"
|
||||||
activeTab === "regularization" ? "active" : ""
|
data-bs-target="#navs-top-messages"
|
||||||
} fs-6`}
|
>
|
||||||
onClick={() => setActiveTab("regularization")}
|
Regularization
|
||||||
data-bs-toggle="tab"
|
</button>
|
||||||
data-bs-target="#navs-top-messages"
|
</li>
|
||||||
>
|
</div>
|
||||||
Regularization
|
{/* Search Box remains here */}
|
||||||
</button>
|
<div className="p-2">
|
||||||
</li>
|
<input
|
||||||
|
type="text"
|
||||||
|
className="form-control form-control-sm"
|
||||||
|
placeholder="Search employee..."
|
||||||
|
value={searchQuery}
|
||||||
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
</ul>
|
</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" && (
|
{activeTab === "all" && (
|
||||||
@ -222,19 +320,39 @@ const AttendancePage = () => {
|
|||||||
<Attendance
|
<Attendance
|
||||||
handleModalData={handleModalData}
|
handleModalData={handleModalData}
|
||||||
getRole={getRole}
|
getRole={getRole}
|
||||||
|
setshowOnlyCheckout={setShowPending}
|
||||||
|
showOnlyCheckout={showPending}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
{!attLoading && filteredAndSearchedTodayAttendance()?.length === 0 && (
|
||||||
|
<p>
|
||||||
|
{" "}
|
||||||
|
{showPending
|
||||||
|
{showPending
|
||||||
|
? "No Pending Available"
|
||||||
|
: "No Employee assigned yet."}{" "}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
{activeTab === "logs" && (
|
{activeTab === "logs" && (
|
||||||
<div className="tab-pane fade show active py-0">
|
<div className="tab-pane fade show active py-0">
|
||||||
<AttendanceLog
|
<AttendanceLog
|
||||||
handleModalData={handleModalData}
|
handleModalData={handleModalData}
|
||||||
|
projectId={selectedProject}
|
||||||
|
setshowOnlyCheckout={setShowPending}
|
||||||
|
showOnlyCheckout={showPending}
|
||||||
|
searchQuery={searchQuery}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{activeTab === "regularization" && DoRegularized && (
|
{activeTab === "regularization" && DoRegularized && (
|
||||||
<div className="tab-pane fade show active py-0">
|
<div className="tab-pane fade show active py-0">
|
||||||
<Regularization />
|
<Regularization
|
||||||
|
handleRequest={handleSubmit}
|
||||||
|
searchQuery={searchQuery}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user