Merge branch 'Issues_July_4W' of https://git.marcoaiot.com/admin/marco.pms.web into Issues_July_4W
This commit is contained in:
commit
254aaf1977
@ -4,7 +4,7 @@ import Avatar from "../common/Avatar";
|
||||
import { convertShortTime } from "../../utils/dateUtils";
|
||||
import RenderAttendanceStatus from "./RenderAttendanceStatus";
|
||||
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 { clearCacheKey, getCachedData } from "../../slices/apiDataManager";
|
||||
import eventBus from "../../services/eventBus";
|
||||
@ -12,16 +12,25 @@ 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);
|
||||
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 startIndex = (currentPage - 1) * itemsPerPage;
|
||||
const endIndex = startIndex + itemsPerPage;
|
||||
return data.slice(startIndex, endIndex);
|
||||
}, [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), []);
|
||||
|
||||
return {
|
||||
@ -35,21 +44,44 @@ const usePagination = (data, itemsPerPage) => {
|
||||
|
||||
const AttendanceLog = ({
|
||||
handleModalData,
|
||||
projectId,
|
||||
setshowOnlyCheckout,
|
||||
showOnlyCheckout,
|
||||
searchQuery,
|
||||
}) => {
|
||||
const selectedProject = useSelector(
|
||||
(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 [loading, setLoading] = useState(false);
|
||||
const [showPending,setShowPending] = useState(false)
|
||||
|
||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||
const [processedData, setProcessedData] = useState([]);
|
||||
const { data: attendanceLogsData, loading: logsLoading, isFetching: logsFetching } = useSelector(
|
||||
(state) => state.attendanceLogs
|
||||
);
|
||||
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
const [isRefreshing, setIsRefreshing] = useState(false); // Local state for refresh spinner
|
||||
|
||||
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();
|
||||
yesterday.setDate(yesterday.getDate() - 1);
|
||||
|
||||
@ -67,28 +99,49 @@ const AttendanceLog = ({
|
||||
return d.getTime() < today.getTime();
|
||||
};
|
||||
|
||||
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);
|
||||
}, []);
|
||||
|
||||
const {
|
||||
data = [],
|
||||
isLoading,
|
||||
error,
|
||||
refetch,
|
||||
isFetching,
|
||||
} = useAttendancesLogs(
|
||||
selectedProject,
|
||||
dateRange.startDate,
|
||||
dateRange.endDate
|
||||
);
|
||||
const filtering = (data) => {
|
||||
const filteredData = showPending
|
||||
? data.filter((item) => item.checkOutTime === null)
|
||||
: data;
|
||||
// Effect to fetch attendance data when dateRange or projectId changes
|
||||
useEffect(() => {
|
||||
const { startDate, endDate } = dateRange;
|
||||
dispatch(
|
||||
fetchAttendanceData({
|
||||
projectId,
|
||||
fromDate: startDate,
|
||||
toDate: endDate,
|
||||
})
|
||||
);
|
||||
setIsRefreshing(false); // Reset refreshing state after fetch attempt
|
||||
}, [dateRange, projectId, dispatch, isRefreshing]); // isRefreshing is a dependency because it triggers a re-fetch
|
||||
|
||||
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
|
||||
.filter((d) => d.activity === 1 && isSameDay(d.checkInTime))
|
||||
.sort(sortByName);
|
||||
@ -119,7 +172,10 @@ const AttendanceLog = ({
|
||||
|
||||
// Group by date
|
||||
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) {
|
||||
acc[date] = acc[date] || [];
|
||||
acc[date].push(item);
|
||||
@ -131,13 +187,9 @@ const AttendanceLog = ({
|
||||
(a, b) => new Date(b) - new Date(a)
|
||||
);
|
||||
|
||||
const finalData = sortedDates.flatMap((date) => groupedByDate[date]);
|
||||
setProcessedData(finalData);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
filtering(data);
|
||||
}, [data, showPending]);
|
||||
// Create the final sorted array
|
||||
return sortedDates.flatMap((date) => groupedByDate[date]);
|
||||
}, [attendanceLogsData, showOnlyCheckout, searchQuery, isSameDay, isBeforeToday, sortByName]);
|
||||
|
||||
const {
|
||||
currentPage,
|
||||
@ -147,40 +199,46 @@ const AttendanceLog = ({
|
||||
resetPage,
|
||||
} = usePagination(processedData, 20);
|
||||
|
||||
// Effect to reset pagination when search query or showOnlyCheckout changes
|
||||
useEffect(() => {
|
||||
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(
|
||||
(msg) => {
|
||||
// Check if the event is relevant to the current project and date range
|
||||
const { startDate, endDate } = dateRange;
|
||||
const checkIn = msg.response.checkInTime.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
|
||||
);
|
||||
})
|
||||
const eventDate = (msg.response.checkInTime || msg.response.checkOutTime)?.substring(0, 10);
|
||||
|
||||
filtering(updatedAttendance);
|
||||
resetPage();
|
||||
// Only refetch if the event relates to the currently viewed project and date range
|
||||
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(() => {
|
||||
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;
|
||||
@ -204,6 +262,11 @@ 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
|
||||
@ -213,35 +276,40 @@ const AttendanceLog = ({
|
||||
<div className="d-flex align-items-center my-0 ">
|
||||
<DateRangePicker
|
||||
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">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="form-check-input"
|
||||
role="switch"
|
||||
disabled={isFetching}
|
||||
disabled={logsFetching}
|
||||
id="inactiveEmployeesCheckbox"
|
||||
checked={showPending}
|
||||
onChange={(e) => setShowPending(e.target.checked)}
|
||||
checked={showOnlyCheckout}
|
||||
onChange={(e) => setshowOnlyCheckout(e.target.checked)}
|
||||
/>
|
||||
<label className="form-check-label ms-0">Show Pending</label>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-md-2 m-0 text-end">
|
||||
<i
|
||||
className={`bx bx-refresh cursor-pointer fs-4 ${
|
||||
isFetching ? "spin" : ""
|
||||
}`}
|
||||
className={`bx bx-refresh cursor-pointer fs-4 ${logsLoading || isRefreshing ? "spin" : ""
|
||||
}`}
|
||||
title="Refresh"
|
||||
onClick={() => refetch()}
|
||||
onClick={handleRefreshClick}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="table-responsive text-nowrap">
|
||||
{isLoading ? (
|
||||
<div><p className="text-secondary">Loading...</p></div>
|
||||
) : data?.length > 0 ? (
|
||||
<div
|
||||
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 ? (
|
||||
<table className="table mb-0">
|
||||
<thead>
|
||||
<tr>
|
||||
@ -267,9 +335,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) {
|
||||
@ -287,7 +355,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
|
||||
@ -329,13 +397,15 @@ const AttendanceLog = ({
|
||||
</tbody>
|
||||
</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>
|
||||
{paginatedAttendances?.length == 0 && data?.length > 0 && (
|
||||
<div className="my-4"><span className="text-secondary">No Pending Record Available !</span></div>
|
||||
)}
|
||||
{processedData.length > 10 && (
|
||||
{!logsLoading && !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" : ""}`}>
|
||||
@ -382,4 +452,4 @@ const AttendanceLog = ({
|
||||
);
|
||||
};
|
||||
|
||||
export default AttendanceLog;
|
||||
export default AttendanceLog;
|
||||
|
@ -17,68 +17,73 @@ const Regularization = ({ handleRequest }) => {
|
||||
const { regularizes, loading, error, refetch } =
|
||||
useRegularizationRequests(selectedProject);
|
||||
|
||||
// Update regularizesList when regularizes data changes
|
||||
useEffect(() => {
|
||||
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 sortByName = useCallback((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) {
|
||||
// const updatedAttendance = regularizes?.filter(
|
||||
// (item) => item.id !== msg.response.id
|
||||
// );
|
||||
// cacheData("regularizedList", {
|
||||
// data: updatedAttendance,
|
||||
// projectId: selectedProject,
|
||||
// });
|
||||
// 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"] });
|
||||
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);
|
||||
cacheData("regularizedList", {
|
||||
data: updatedAttendance,
|
||||
projectId: selectedProject,
|
||||
});
|
||||
// Refetch to get the latest data from the source, ensuring consistency
|
||||
refetch();
|
||||
}
|
||||
},
|
||||
[selectedProject, regularizes]
|
||||
[selectedProject, regularizesList, refetch] // Added regularizesList and refetch to dependencies
|
||||
);
|
||||
|
||||
const filteredData = [...regularizesList]?.sort(sortByName);
|
||||
|
||||
const { currentPage, totalPages, currentItems, paginate } = usePagination(
|
||||
filteredData,
|
||||
20
|
||||
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
|
||||
refetch();
|
||||
}
|
||||
},
|
||||
[regularizes, refetch] // Added refetch to dependencies
|
||||
);
|
||||
|
||||
// Event bus listeners
|
||||
useEffect(() => {
|
||||
eventBus.on("regularization", handler);
|
||||
return () => eventBus.off("regularization", handler);
|
||||
}, [handler]);
|
||||
|
||||
const employeeHandler = useCallback(
|
||||
(msg) => {
|
||||
if (regularizes.some((item) => item.employeeId == msg.employeeId)) {
|
||||
refetch();
|
||||
}
|
||||
},
|
||||
[regularizes]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
eventBus.on("employee", employeeHandler);
|
||||
return () => eventBus.off("employee", 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 (
|
||||
<div className="table-responsive text-nowrap pb-4">
|
||||
{loading ? (
|
||||
@ -144,7 +149,7 @@ const Regularization = ({ handleRequest }) => {
|
||||
{!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)}
|
||||
|
@ -1,10 +1,8 @@
|
||||
import React, { useState, useEffect, useCallback } from "react";
|
||||
import {
|
||||
cacheData,
|
||||
clearCacheKey,
|
||||
getCachedData,
|
||||
getCachedProfileData,
|
||||
} from "../../slices/apiDataManager";
|
||||
} from "../../slices/apiDataManager"; // clearCacheKey and getCachedData are not used
|
||||
import Breadcrumb from "../../components/common/Breadcrumb";
|
||||
import AttendanceLog from "../../components/Activities/AttendcesLogs";
|
||||
import Attendance from "../../components/Activities/Attendance";
|
||||
@ -30,102 +28,194 @@ import { useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
const AttendancePage = () => {
|
||||
const [activeTab, setActiveTab] = useState("all");
|
||||
const [ShowPending, setShowPending] = useState(false);
|
||||
const queryClient = useQueryClient();
|
||||
const loginUser = getCachedProfileData();
|
||||
var selectedProject = useSelector((store) => store.localVariables.projectId);
|
||||
const [showPending, setShowPending] = useState(false);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
// const loginUser = getCachedProfileData(); // Declared but not used
|
||||
const selectedProject = useSelector((store) => store.localVariables.projectId);
|
||||
const dispatch = useDispatch();
|
||||
// const {
|
||||
// attendance,
|
||||
// loading: attLoading,
|
||||
// recall: attrecall,
|
||||
// } = useAttendance(selectedProject);
|
||||
|
||||
const {
|
||||
attendance,
|
||||
loading: attLoading,
|
||||
// recall: attrecall, // Declared but not used in the current logic
|
||||
} = useAttendance(selectedProject);
|
||||
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 [modelConfig, setModelConfig] = useState();
|
||||
const [modelConfig, setModelConfig] = useState(null); // Initialize with null for clarity
|
||||
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({
|
||||
markTime: "",
|
||||
description: "",
|
||||
date: new Date().toLocaleDateString(),
|
||||
});
|
||||
// FormData is declared but not used in the provided snippet's logic
|
||||
// const [formData, setFormData] = useState({
|
||||
// markTime: "",
|
||||
// description: "",
|
||||
// date: new Date().toLocaleDateString(),
|
||||
// });
|
||||
|
||||
// const handler = useCallback(
|
||||
// (msg) => {
|
||||
// if (selectedProject == msg.projectId) {
|
||||
// const updatedAttendance = attendances.map((item) =>
|
||||
// item.employeeId === msg.response.employeeId
|
||||
// ? { ...item, ...msg.response }
|
||||
// : item
|
||||
// );
|
||||
// queryClient.setQueryData(["attendance", selectedProject], (oldData) => {
|
||||
// if (!oldData) return oldData;
|
||||
// return oldData.map((emp) =>
|
||||
// emp.employeeId === data.employeeId ? { ...emp, ...data } : emp
|
||||
// );
|
||||
// });
|
||||
// }
|
||||
// },
|
||||
// [selectedProject, attrecall]
|
||||
// );
|
||||
const handler = useCallback(
|
||||
(msg) => {
|
||||
if (selectedProject === msg.projectId) {
|
||||
const updatedAttendance = attendances
|
||||
? attendances.map((item) =>
|
||||
item.employeeId === msg.response.employeeId
|
||||
? { ...item, ...msg.response }
|
||||
: item
|
||||
)
|
||||
: [msg.response];
|
||||
|
||||
// const employeeHandler = useCallback(
|
||||
// (msg) => {
|
||||
// if (attendances.some((item) => item.employeeId == msg.employeeId)) {
|
||||
// attrecall();
|
||||
// }
|
||||
// },
|
||||
// [selectedProject, attendances]
|
||||
// );
|
||||
useEffect(() => {
|
||||
if (selectedProject == null) {
|
||||
dispatch(setProjectId(projectNames[0]?.id));
|
||||
cacheData("Attendance", {
|
||||
data: updatedAttendance,
|
||||
projectId: selectedProject, // Corrected key from selectedProject to projectId for consistency
|
||||
});
|
||||
setAttendances(updatedAttendance);
|
||||
}
|
||||
},
|
||||
[selectedProject, attendances]
|
||||
);
|
||||
|
||||
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) => {
|
||||
if (!empRoles) return "Unassigned";
|
||||
if (!roleId) return "Unassigned";
|
||||
const role = empRoles.find((b) => b.id == roleId);
|
||||
return role ? role.role : "Unassigned";
|
||||
};
|
||||
const handleSubmit = useCallback((formData) => {
|
||||
dispatch(markCurrentAttendance(formData))
|
||||
.then((action) => {
|
||||
if (action.payload && action.payload.employeeId) {
|
||||
const updatedAttendance = attendances
|
||||
? attendances.map((item) =>
|
||||
item.employeeId === action.payload.employeeId
|
||||
? { ...item, ...action.payload }
|
||||
: item
|
||||
)
|
||||
: [action.payload];
|
||||
|
||||
const openModel = () => {
|
||||
setIsCreateModalOpen(true);
|
||||
};
|
||||
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");
|
||||
});
|
||||
}, [dispatch, attendances, selectedProject]);
|
||||
|
||||
const handleModalData = (employee) => {
|
||||
setModelConfig(employee);
|
||||
};
|
||||
|
||||
const closeModal = () => {
|
||||
setModelConfig(null);
|
||||
setIsCreateModalOpen(false);
|
||||
};
|
||||
|
||||
const handleToggle = (event) => {
|
||||
setShowOnlyCheckout(event.target.checked);
|
||||
};
|
||||
const handleToggle = useCallback((event) => {
|
||||
setShowPending(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(() => {
|
||||
if (modelConfig !== null) {
|
||||
openModel();
|
||||
}
|
||||
}, [modelConfig, isCreateModalOpen]);
|
||||
}, [modelConfig, openModel]); // Added openModel to dependency array
|
||||
|
||||
// useEffect(() => {
|
||||
// eventBus.on("attendance", handler);
|
||||
// return () => eventBus.off("attendance", handler);
|
||||
// }, [handler]);
|
||||
useEffect(() => {
|
||||
setAttendances(attendance);
|
||||
}, [attendance]);
|
||||
|
||||
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 (
|
||||
<>
|
||||
{/* {isCreateModalOpen && modelConfig && (
|
||||
@ -174,47 +264,55 @@ const AttendancePage = () => {
|
||||
{ label: "Attendance", link: null },
|
||||
]}
|
||||
></Breadcrumb>
|
||||
<div className="nav-align-top nav-tabs-shadow" >
|
||||
<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>
|
||||
<div className="nav-align-top nav-tabs-shadow">
|
||||
<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"
|
||||
placeholder="Search employee..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
</ul>
|
||||
<div className="tab-content attedanceTabs py-0 px-1 px-sm-3" >
|
||||
{activeTab === "all" && (
|
||||
@ -222,19 +320,39 @@ const AttendancePage = () => {
|
||||
<Attendance
|
||||
handleModalData={handleModalData}
|
||||
getRole={getRole}
|
||||
setshowOnlyCheckout={setShowPending}
|
||||
showOnlyCheckout={showPending}
|
||||
/>
|
||||
</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
|
||||
handleModalData={handleModalData}
|
||||
projectId={selectedProject}
|
||||
setshowOnlyCheckout={setShowPending}
|
||||
showOnlyCheckout={showPending}
|
||||
searchQuery={searchQuery}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{activeTab === "regularization" && DoRegularized && (
|
||||
<div className="tab-pane fade show active py-0">
|
||||
<Regularization />
|
||||
<Regularization
|
||||
handleRequest={handleSubmit}
|
||||
searchQuery={searchQuery}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
Loading…
x
Reference in New Issue
Block a user