Refactor_Expenses #321

Merged
pramod.mahajan merged 249 commits from Refactor_Expenses into hotfix/MasterActivity 2025-08-01 13:14:59 +00:00
5 changed files with 574 additions and 761 deletions
Showing only changes of commit 699c349ba5 - Show all commits

View File

@ -4,12 +4,14 @@ 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, setAttendanceData } 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 eventBus from "../../services/eventBus"; import eventBus from "../../services/eventBus";
// Custom hook for pagination
const usePagination = (data, itemsPerPage) => { const usePagination = (data, itemsPerPage) => {
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
// Ensure data is an array before accessing length
const totalItems = Array.isArray(data) ? data.length : 0; const totalItems = Array.isArray(data) ? data.length : 0;
const maxPage = Math.ceil(totalItems / itemsPerPage); const maxPage = Math.ceil(totalItems / itemsPerPage);
@ -28,7 +30,6 @@ const usePagination = (data, itemsPerPage) => {
} }
}, [maxPage]); }, [maxPage]);
// Ensure resetPage is returned by the hook
const resetPage = useCallback(() => setCurrentPage(1), []); const resetPage = useCallback(() => setCurrentPage(1), []);
return { return {
@ -44,22 +45,29 @@ const AttendanceLog = ({
handleModalData, handleModalData,
projectId, projectId,
setshowOnlyCheckout, setshowOnlyCheckout,
showOnlyCheckout, // Prop for showPending state showOnlyCheckout,
searchQuery, // Prop for search query 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();
// Get data, loading, and fetching state from the Redux store's attendanceLogs slice
const { data: attendanceLogsData, loading: logsLoading, isFetching: logsFetching } = useSelector( const { data: attendanceLogsData, loading: logsLoading, isFetching: logsFetching } = useSelector(
(state) => state.attendanceLogs // Assuming your slice is named 'attendanceLogs' (state) => state.attendanceLogs
); );
const [isRefreshing, setIsRefreshing] = useState(false); // Local state for refresh spinner const [isRefreshing, setIsRefreshing] = useState(false); // Local state for refresh spinner
// Memoize today and yesterday dates to prevent re-creation on every render
const today = useMemo(() => { const today = useMemo(() => {
const d = new Date(); const d = new Date();
d.setHours(0, 0, 0, 0); d.setHours(0, 0, 0, 0);
@ -69,6 +77,7 @@ const AttendanceLog = ({
const yesterday = useMemo(() => { const yesterday = useMemo(() => {
const d = new Date(); const d = new Date();
d.setDate(d.getDate() - 1); d.setDate(d.getDate() - 1);
d.setHours(0, 0, 0, 0); // Set to start of day for accurate comparison
return d; return d;
}, []); }, []);
@ -92,7 +101,7 @@ const AttendanceLog = ({
return nameA.localeCompare(nameB); return nameA.localeCompare(nameB);
}, []); }, []);
// Effect to fetch attendance data when dateRange or projectId changes // Effect to fetch attendance data when dateRange or projectId changes, or when refreshed
useEffect(() => { useEffect(() => {
const { startDate, endDate } = dateRange; const { startDate, endDate } = dateRange;
dispatch( dispatch(
@ -102,21 +111,26 @@ const AttendanceLog = ({
toDate: endDate, toDate: endDate,
}) })
); );
setIsRefreshing(false); // Reset refreshing state after fetch attempt // Reset refreshing state only after the dispatch, assuming fetchAttendanceData
}, [dateRange, projectId, dispatch, isRefreshing]); // isRefreshing is a dependency because it triggers a re-fetch // will eventually update logsLoading/logsFetching
const timer = setTimeout(() => { // Give Redux time to update
setIsRefreshing(false);
}, 500); // Small delay to show spinner for a bit longer
return () => clearTimeout(timer);
}, [dateRange, projectId, dispatch, isRefreshing]);
const processedData = useMemo(() => { const processedData = useMemo(() => {
let filteredData = showOnlyCheckout // Use the prop directly let filteredData = showOnlyCheckout
? attendanceLogsData.filter((item) => item.checkOutTime === null) // Use attendanceLogsData ? (attendanceLogsData || []).filter((item) => item.checkOutTime === null) // Ensure attendanceLogsData is an array
: attendanceLogsData; // Use attendanceLogsData : (attendanceLogsData || []); // Ensure attendanceLogsData is an array
// Apply search query filter // Apply search query filter
if (searchQuery) { if (searchQuery) {
const lowerCaseSearchQuery = searchQuery.toLowerCase(); const lowerCaseSearchQuery = searchQuery.toLowerCase();
filteredData = filteredData.filter((att) => { filteredData = filteredData.filter((att) => {
// Construct a full name from available parts, filtering out null/undefined
const fullName = [att.firstName, att.middleName, att.lastName] const fullName = [att.firstName, att.middleName, att.lastName]
.filter(Boolean) // This removes null, undefined, or empty string parts .filter(Boolean)
.join(" ") .join(" ")
.toLowerCase(); .toLowerCase();
@ -128,6 +142,7 @@ const AttendanceLog = ({
}); });
} }
// 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);
@ -158,7 +173,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);
@ -172,46 +190,56 @@ const AttendanceLog = ({
// Create the final sorted array // Create the final sorted array
return sortedDates.flatMap((date) => groupedByDate[date]); return sortedDates.flatMap((date) => groupedByDate[date]);
}, [attendanceLogsData, showOnlyCheckout, searchQuery, isSameDay, isBeforeToday, sortByName]); // Added attendanceLogsData to dependencies }, [attendanceLogsData, showOnlyCheckout, searchQuery, isSameDay, isBeforeToday, sortByName]);
const { const {
currentPage, currentPage,
totalPages, totalPages,
currentItems: paginatedAttendances, currentItems: paginatedAttendances,
paginate, paginate,
resetPage, // Destructure resetPage here resetPage,
} = usePagination(processedData, 20); } = usePagination(processedData, 20);
// Effect to reset pagination when search query changes // Effect to reset pagination when search query or showOnlyCheckout changes
useEffect(() => { useEffect(() => {
resetPage(); resetPage();
}, [searchQuery, resetPage]); // Add resetPage to dependencies }, [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);
// Only refetch if the event relates to the currently viewed project and date range
if ( if (
projectId === msg.projectId && projectId === msg.projectId &&
startDate <= checkIn && eventDate &&
checkIn <= endDate eventDate >= startDate && // Ensure eventDate is within the current range
eventDate <= endDate
) { ) {
const updatedAttendance = data.map((item) => // Trigger a re-fetch of attendance data to get the latest state
item.id === msg.response.id dispatch(
? { ...item, ...msg.response } fetchAttendanceData({
: item projectId,
fromDate: startDate,
toDate: endDate,
})
); );
dispatch(setAttendanceData(updatedAttendance)); // Update Redux store
} }
}, },
[projectId, dateRange, data, dispatch] [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;
@ -233,7 +261,7 @@ const AttendanceLog = ({
const handleRefreshClick = () => { const handleRefreshClick = () => {
setIsRefreshing(true); // Set refreshing state to true setIsRefreshing(true); // Set refreshing state to true
// The useEffect for fetching data will trigger because isRefreshing is a dependency // The useEffect for fetching data will automatically trigger due to isRefreshing dependency
}; };
return ( return (
@ -245,27 +273,27 @@ 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={logsFetching} // Use logsFetching from Redux store disabled={logsFetching}
id="inactiveEmployeesCheckbox" id="inactiveEmployeesCheckbox"
checked={showOnlyCheckout} // Use the prop directly checked={showOnlyCheckout}
onChange={(e) => setshowOnlyCheckout(e.target.checked)} // Use the prop setter 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 ${logsLoading || isRefreshing ? "spin" : "" // Use logsLoading for overall loading, isRefreshing for local spinner className={`bx bx-refresh cursor-pointer fs-4 ${logsLoading || isRefreshing ? "spin" : ""
}`} }`}
title="Refresh" title="Refresh"
onClick={handleRefreshClick} // Call the new handler onClick={handleRefreshClick}
/> />
</div> </div>
</div> </div>
@ -273,7 +301,12 @@ const AttendanceLog = ({
className="table-responsive text-nowrap" className="table-responsive text-nowrap"
style={{ minHeight: "200px", display: 'flex' }} style={{ minHeight: "200px", display: 'flex' }}
> >
{processedData && processedData.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>
@ -292,96 +325,84 @@ const AttendanceLog = ({
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{(logsLoading || isRefreshing) && ( // Use logsLoading and isRefreshing {paginatedAttendances.reduce((acc, attendance, index, arr) => {
<tr> const currentDate = moment(
<td colSpan={6}>Loading...</td> attendance.checkInTime || attendance.checkOutTime
</tr> ).format("YYYY-MM-DD");
)} const previousAttendance = arr[index - 1];
{!logsLoading && // Use logsLoading const previousDate = previousAttendance
!isRefreshing && // Use isRefreshing ? moment(
paginatedAttendances.reduce((acc, attendance, index, arr) => { previousAttendance.checkInTime ||
const currentDate = moment( previousAttendance.checkOutTime
attendance.checkInTime || attendance.checkOutTime ).format("YYYY-MM-DD")
).format("YYYY-MM-DD"); : null;
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( acc.push(
<tr key={attendance.id || index}> <tr
<td colSpan={2}> key={`header-${currentDate}`}
<div className="d-flex justify-content-start align-items-center"> className="table-row-header"
<Avatar >
firstName={attendance.firstName} <td colSpan={6} className="text-start">
lastName={attendance.lastName} <strong>
/> {moment(currentDate).format("DD-MM-YYYY")}
<div className="d-flex flex-column"> </strong>
<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> </td>
</tr> </tr>
); );
return acc; }
}, [])} 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;
}, [])}
</tbody> </tbody>
</table> </table>
) : ( ) : (
!logsLoading && // Use logsLoading <div
!isRefreshing && ( // Use isRefreshing className="d-flex justify-content-center align-items-center text-muted w-100"
<div style={{ height: "200px" }} // Added height for better visual during no data
className="d-flex justify-content-center align-items-center text-muted" >
style={{ No employee logs.
width: "100%", </div>
}}
>
No employee logs.
</div>
)
)} )}
</div> </div>
{!logsLoading && !isRefreshing && processedData.length > 20 && ( // Use logsLoading and isRefreshing {!logsLoading && !isRefreshing && processedData.length > 20 && (
<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" : ""}`}>
@ -426,4 +447,4 @@ const AttendanceLog = ({
); );
}; };
export default AttendanceLog; export default AttendanceLog;

View File

@ -14,41 +14,45 @@ const Regularization = ({ handleRequest, searchQuery }) => {
const [regularizesList, setRegularizedList] = useState([]); const [regularizesList, setRegularizedList] = useState([]);
const { regularizes, loading, refetch } = useRegularizationRequests(selectedProject); const { regularizes, loading, refetch } = 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 + a.lastName).toLowerCase(); const nameA = (a.firstName + a.lastName).toLowerCase();
const nameB = (b.firstName + 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(item => item.id !== msg.response.id); // 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", { cacheData("regularizedList", {
data: updatedAttendance, data: updatedAttendance,
projectId: selectedProject, projectId: selectedProject,
}); });
// Refetch to get the latest data from the source, ensuring consistency
refetch(); refetch();
} }
}, },
[selectedProject, regularizes] [selectedProject, regularizesList, refetch] // Added regularizesList and refetch to dependencies
); );
const employeeHandler = useCallback( const employeeHandler = useCallback(
(msg) => { (msg) => {
if (regularizes.some((item) => item.employeeId == msg.employeeId)) { // If any regularization request belongs to the updated employee, refetch
if (regularizes?.some((item) => item.employeeId === msg.employeeId)) { // Use strict equality
refetch(); refetch();
} }
}, },
[regularizes] [regularizes, refetch] // Added refetch to dependencies
); );
useEffect(() => { // Event bus listeners
useEffect(() => { useEffect(() => {
eventBus.on("regularization", handler); eventBus.on("regularization", handler);
return () => eventBus.off("regularization", handler); return () => eventBus.off("regularization", handler);
@ -59,7 +63,7 @@ const Regularization = ({ handleRequest, searchQuery }) => {
return () => eventBus.off("employee", employeeHandler); return () => eventBus.off("employee", employeeHandler);
}, [employeeHandler]); }, [employeeHandler]);
// Search filter logic added here // Search filter logic
const filteredData = [...regularizesList] const filteredData = [...regularizesList]
?.filter((item) => { ?.filter((item) => {
if (!searchQuery) return true; if (!searchQuery) return true;
@ -144,7 +148,7 @@ const Regularization = ({ handleRequest, searchQuery }) => {
{!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)}
@ -179,4 +183,4 @@ const Regularization = ({ handleRequest, searchQuery }) => {
); );
}; };
export default Regularization; export default Regularization;

View File

@ -41,20 +41,6 @@ const Header = () => {
"b74da4c2-d07e-46f2-9919-e75e49b12731", // Active "b74da4c2-d07e-46f2-9919-e75e49b12731", // Active
]; ];
const isDirectoryPath = /^\/directory$/.test(location.pathname);
const isProjectPath = /^\/projects$/.test(location.pathname);
const isDashboard =
/^\/dashboard$/.test(location.pathname) || /^\/$/.test(location.pathname);
// Define the specific project status IDs you want to filter by
// Changed to explicitly include only 'Active', 'On Hold', 'In Progress'
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
"b74da4c2-d07e-46f2-9919-e75e49b12731", // Active
];
const getRole = (roles, joRoleId) => { const getRole = (roles, joRoleId) => {
if (!Array.isArray(roles)) return "User"; if (!Array.isArray(roles)) return "User";
let role = roles.find((role) => role.id === joRoleId); let role = roles.find((role) => role.id === joRoleId);

View File

@ -89,7 +89,7 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
// Changed to an array to hold multiple selected roles // Changed to an array to hold multiple selected roles
const [selectedRoles, setSelectedRoles] = useState(["all"]); const [selectedRoles, setSelectedRoles] = useState(["all"]);
// Changed to an array to hold multiple selected roles // Changed to an array to hold multiple selected roles
const [selectedRoles, setSelectedRoles] = useState(["all"]); // const [selectedRoles, setSelectedRoles] = useState(["all"]);
const [displayedSelection, setDisplayedSelection] = useState(""); const [displayedSelection, setDisplayedSelection] = useState("");
const { const {
handleSubmit, handleSubmit,
@ -228,367 +228,337 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
}; };
return ( return (
<div className="fs-5 text-dark text-center d-flex align-items-center justify-content-center flex-wrap"> <div className="fs-5 text-dark text-center d-flex align-items-center justify-content-center flex-wrap">
<p className="align-items-center flex-wrap m-0 ">Assign Task</p> <p className="align-items-center flex-wrap m-0 ">Assign Task</p>
<div className="container my-3"> <div className="container my-3">
<div className="mb-1"> <div className="mb-1">
<p className="mb-0"> <p className="mb-0">
<span className="text-dark text-start d-flex align-items-center flex-wrap form-text"> <span className="text-dark text-start d-flex align-items-center flex-wrap form-text">
<span className="me-2 m-0 font-bold">Work Location :</span> <span className="me-2 m-0 fw-bold">Work Location :</span> {/* Changed font-bold to fw-bold */}
{[ {[
assignData?.building?.buildingName, assignData?.building?.buildingName,
assignData?.floor?.floorName, assignData?.floor?.floorName,
assignData?.workArea?.areaName, assignData?.workArea?.areaName,
assignData?.workItem?.activityMaster?.activityName, assignData?.workItem?.activityMaster?.activityName,
] ]
.filter(Boolean) // Filter out any undefined/null values .filter(Boolean) // Filter out any undefined/null values
.map((item, index, array) => ( .map((item, index, array) => (
<span key={index} className="d-flex align-items-center"> <span key={index} className="d-flex align-items-center">
{item} {item}
{index < array.length - 1 && ( {index < array.length - 1 && (
<i className="bx bx-chevron-right mx-2"></i> <i className="bx bx-chevron-right mx-2"></i>
)} )}
</span> </span>
))} ))}
</span> </span>
</p> </p>
<form onSubmit={handleSubmit(onSubmit)}> <form onSubmit={handleSubmit(onSubmit)}>
<div className="form-label text-start"> <div className="form-label text-start">
<div className="row mb-1"> <div className="row mb-1">
<div className="col-12"> <div className="col-12">
<div className="form-text text-start"> <div className="form-text text-start">
<div className="d-flex align-items-center form-text fs-7"> <div className="d-flex align-items-center form-text fs-7">
<span className="text-dark">Select Team</span> <span className="text-dark">Select Team</span>
<div className="dropdown position-relative d-inline-block"> <div className="dropdown position-relative d-inline-block">
<a <a
className={`dropdown-toggle hide-arrow cursor-pointer ${selectedRoles.includes("all") || selectedRoles.length === 0 className={`dropdown-toggle hide-arrow cursor-pointer ${
? "text-secondary" selectedRoles.includes("all") || selectedRoles.length === 0
: "text-primary" ? "text-secondary"
}`} : "text-primary"
data-bs-toggle="dropdown" }`}
role="button" data-bs-toggle="dropdown"
aria-expanded="false" role="button"
> aria-expanded="false"
<i className="bx bx-slider-alt ms-2"></i> >
</a> <i className="bx bx-slider-alt ms-2"></i>
</a>
{/* Badge */} {/* Badge */}
{selectedRolesCount > 0 && ( {selectedRolesCount > 0 && (
<span <span
className="position-absolute top-0 start-100 translate-middle badge rounded-circle bg-warning text-white" className="position-absolute top-0 start-100 translate-middle badge rounded-circle bg-warning text-white"
style={{ style={{
fontSize: "0.65rem", fontSize: "0.65rem",
minWidth: "18px", minWidth: "18px",
height: "18px", height: "18px",
padding: "0", padding: "0",
lineHeight: "18px", lineHeight: "18px",
textAlign: "center", textAlign: "center",
zIndex: 10, zIndex: 10,
}} }}
>
{selectedRolesCount}
</span>
)}
{/* Dropdown Menu */}
<ul
className="dropdown-menu p-2 text-capitalize "
>
<li key="all">
<div className="form-check dropdown-item py-0">
<input
className="form-check-input"
type="checkbox"
id="checkboxAllRoles"
value="all"
checked={selectedRoles.includes("all")}
onChange={(e) => handleRoleChange(e, e.target.value)}
/>
<label className="form-check-label ms-2" htmlFor="checkboxAllRoles">
All Roles
</label>
</div>
</li>
{jobRolesForDropdown?.map((role) => (
<li key={role.id}>
<div className="form-check dropdown-item py-0">
<input
className="form-check-input"
type="checkbox"
id={`checkboxRole-${role.id}`}
value={role.id}
checked={selectedRoles.includes(String(role.id))}
onChange={(e) => handleRoleChange(e, e.target.value)}
/>
<label className="form-check-label ms-2" htmlFor={`checkboxRole-${role.id}`}>
{role.name}
</label>
</div>
</li>
))}
</ul>
</div>
<ul
className="dropdown-menu p-2 text-capitalize"
style={{ maxHeight: "300px", overflowY: "auto" }}
> >
<li key="all"> {selectedRolesCount}
</span>
)}
{/* Dropdown Menu - Corrected: Removed duplicate ul block */}
<ul className="dropdown-menu p-2 text-capitalize" style={{ maxHeight: "300px", overflowY: "auto" }}>
<li> {/* Changed key="all" to a unique key if possible, or keep it if "all" is a unique identifier */}
<div className="form-check dropdown-item py-0">
<input
className="form-check-input"
type="checkbox"
id="checkboxAllRoles" // Unique ID
value="all"
checked={selectedRoles.includes("all")}
onChange={(e) => handleRoleChange(e, e.target.value)}
/>
<label className="form-check-label ms-2" htmlFor="checkboxAllRoles">
All Roles
</label>
</div>
</li>
{jobRolesForDropdown?.map((role) => (
<li key={role.id}>
<div className="form-check dropdown-item py-0"> <div className="form-check dropdown-item py-0">
<input <input
className="form-check-input" className="form-check-input"
type="checkbox" type="checkbox"
id="checkboxAllRoles" id={`checkboxRole-${role.id}`} // Unique ID
value="all" value={role.id}
checked={selectedRoles.includes("all")} checked={selectedRoles.includes(String(role.id))}
onChange={(e) => onChange={(e) => handleRoleChange(e, e.target.value)}
handleRoleChange(e, e.target.value)
}
/> />
<label <label className="form-check-label ms-2" htmlFor={`checkboxRole-${role.id}`}>
className="form-check-label ms-2" {role.name}
htmlFor="checkboxAllRoles"
>
All Roles
</label>
</div>
<div className="form-check dropdown-item py-0">
<input
className="form-check-input"
type="checkbox"
id="checkboxAllRoles"
value="all"
checked={selectedRoles.includes("all")}
onChange={(e) =>
handleRoleChange(e, e.target.value)
}
/>
<label
className="form-check-label ms-2"
htmlFor="checkboxAllRoles"
>
All Roles
</label> </label>
</div> </div>
</li> </li>
{jobRolesForDropdown?.map((role) => ( ))}
<li key={role.id}> </ul>
<div className="form-check dropdown-item py-0">
<input
className="form-check-input"
type="checkbox"
id={`checkboxRole-${role.id}`}
value={role.id}
checked={selectedRoles.includes(String(role.id))}
onChange={(e) =>
handleRoleChange(e, e.target.value)
}
/>
<label
className="form-check-label ms-2"
htmlFor={`checkboxRole-${role.id}`}
>
{role.name}
</label>
</div>
{jobRolesForDropdown?.map((role) => (
<li key={role.id}>
<div className="form-check dropdown-item py-0">
<input
className="form-check-input"
type="checkbox"
id={`checkboxRole-${role.id}`}
value={role.id}
checked={selectedRoles.includes(String(role.id))}
onChange={(e) =>
handleRoleChange(e, e.target.value)
}
/>
<label
className="form-check-label ms-2"
htmlFor={`checkboxRole-${role.id}`}
>
{role.name}
</label>
</div>
</li>
))}
</ul>
<input
type="text"
className="form-control form-control-sm ms-auto mb-2 mt-2"
placeholder="Search employees or roles..."
value={searchTerm}
onChange={handleSearchChange}
style={{ maxWidth: '200px' }}
/>
</div>
</div> </div>
<input
type="text"
className="form-control form-control-sm ms-auto mb-2 mt-2"
placeholder="Search employees or roles..."
value={searchTerm}
onChange={handleSearchChange}
style={{ maxWidth: "200px" }}
/>
</div> </div>
</div> </div>
<div </div>
className="col-12 mt-2" </div>
style={{ maxHeight: "280px", overflowY: "auto", overflowX: "hidden" }} <div
> className="col-12 mt-2"
{selectedRoles?.length > 0 && ( style={{ maxHeight: "280px", overflowY: "auto", overflowX: "hidden" }}
<div className="row"> >
{employeeLoading ? ( {selectedRoles?.length > 0 && (
<div className="col-12"> <div className="row">
<p className="text-center">Loading employees...</p> {employeeLoading ? (
</div> <div className="col-12">
) : filteredEmployees?.length > 0 ? ( <p className="text-center">Loading employees...</p>
filteredEmployees.map((emp) => {
const jobRole = jobRoleData?.find(
(role) => role?.id === emp?.jobRoleId
);
<div
className="col-12 mt-2"
style={{ maxHeight: "280px", overflowY: "auto", overflowX: "hidden" }}
>
{selectedRoles?.length > 0 && (
<div className="row">
{employeeLoading ? (
<div className="col-12">
<p className="text-center">Loading employees...</p>
</div>
) : filteredEmployees?.length > 0 ? (
filteredEmployees.map((emp) => {
const jobRole = jobRoleData?.find(
(role) => role?.id === emp?.jobRoleId
);
return (
<div
key={emp.id}
className="col-6 col-md-4 col-lg-3 mb-3"
>
<div className="form-check d-flex align-items-start">
<Controller
name="selectedEmployees"
control={control}
render={({ field }) => (
<input
{...field}
className="form-check-input me-1 mt-1"
type="checkbox"
id={`employee-${emp?.id}`}
value={emp.id}
checked={field.value?.includes(emp.id)}
onChange={(e) => {
handleCheckboxChange(e, emp);
}}
/>
)}
/>
<div className="flex-grow-1">
<p
className="mb-0"
style={{ fontSize: "13px" }}
>
{emp.firstName} {emp.lastName}
</p>
<small
className="text-muted"
style={{ fontSize: "11px" }}
>
{loading ? (
<span className="placeholder-glow">
<span className="placeholder col-6"></span>
</span>
) : (
jobRole?.name || "Unknown Role"
)}
</small>
</div>
</div>
</div>
);
})
) : (
<div className="col-12">
<p className="text-center">
No employees found for the selected role(s).
</p>
</div>
)}
</div> </div>
)} ) : filteredEmployees?.length > 0 ? (
</div> filteredEmployees.map((emp) => {
const jobRole = jobRoleData?.find(
(role) => role?.id === emp?.jobRoleId
);
<div return (
className="col-12 h-25 overflow-auto" <div
style={{ maxHeight: "200px" }} key={emp.id}
> className="col-6 col-md-4 col-lg-3 mb-3"
{watch("selectedEmployees")?.length > 0 && ( >
<div className="mt-1"> <div className="form-check d-flex align-items-start">
<div className="text-start px-2"> <Controller
{watch("selectedEmployees")?.map((empId) => { name="selectedEmployees"
const emp = employees.find((emp) => emp.id === empId); control={control}
return ( render={({ field }) => (
emp && ( <input
<span {...field}
key={empId} className="form-check-input me-1 mt-1"
className="badge rounded-pill bg-label-primary d-inline-flex align-items-center me-1 mb-1" type="checkbox"
id={`employee-${emp?.id}`} // Unique ID
value={emp.id}
checked={field.value?.includes(emp.id)}
onChange={(e) => {
handleCheckboxChange(e, emp);
}}
/>
)}
/>
<div className="flex-grow-1">
<p
className="mb-0"
style={{ fontSize: "13px" }}
> >
{emp.firstName} {emp.lastName} {emp.firstName} {emp.lastName}
<p </p>
type="button" <small
className=" btn-close-white p-0 m-0" className="text-muted"
aria-label="Close" style={{ fontSize: "11px" }}
onClick={() => { >
const updatedSelected = watch( {loading ? (
"selectedEmployees" <span className="placeholder-glow">
).filter((id) => id !== empId); <span className="placeholder col-6"></span>
setValue( </span>
"selectedEmployees", ) : (
updatedSelected jobRole?.name || "Unknown Role"
); )}
trigger("selectedEmployees"); </small>
}} </div>
> </div>
<i className="icon-base bx bx-x icon-md "></i> </div>
</p> );
</span> })
) ) : (
); <div className="col-12">
})} <p className="text-center">
</div> No employees found for the selected role(s).
</p>
</div> </div>
)} )}
</div> </div>
)}
</div>
{!loading && errors.selectedEmployees && ( <div
<div className="danger-text mt-1"> className="col-12 h-25 overflow-auto"
<p>{errors.selectedEmployees.message}</p>{" "} style={{ maxHeight: "200px" }}
>
{watch("selectedEmployees")?.length > 0 && (
<div className="mt-1">
<div className="text-start px-2">
{watch("selectedEmployees")?.map((empId) => {
const emp = employees.find((emp) => emp.id === empId);
return (
emp && (
<span
key={empId}
className="badge rounded-pill bg-label-primary d-inline-flex align-items-center me-1 mb-1"
>
{emp.firstName} {emp.lastName}
{/* Changed p tag to button for semantic correctness and accessibility */}
<button
type="button"
className="btn-close btn-close-white ms-1" // Added ms-1 for spacing, removed p-0 m-0
aria-label="Remove employee" // More descriptive aria-label
onClick={() => {
const updatedSelected = watch(
"selectedEmployees"
).filter((id) => id !== empId);
setValue(
"selectedEmployees",
updatedSelected
);
trigger("selectedEmployees");
}}
>
<i className="icon-base bx bx-x icon-md"></i>
</button>
</span>
)
);
})}
</div> </div>
)} </div>
)}
</div>
<div className="col-md text-start mx-0 px-0"> {!loading && errors.selectedEmployees && (
<div className="form-check form-check-inline mt-3 px-1"> <div className="danger-text mt-1">
<label <p>{errors.selectedEmployees.message}</p>{" "}
className="form-text text-dark align-items-center d-flex" </div>
htmlFor="inlineCheckbox1" )}
<div className="col-md text-start mx-0 px-0">
<div className="form-check form-check-inline mt-3 px-1">
<label
className="form-text text-dark align-items-center d-flex"
htmlFor="inlineCheckbox1" // This htmlFor isn't linked to a checkbox in this context
>
Pending Task of Activity :
<label
className="form-check-label fs-7 ms-4"
htmlFor="inlineCheckbox1" // This htmlFor isn't linked to a checkbox in this context
>
<strong>
{assignData?.workItem?.plannedWork -
assignData?.workItem?.completedWork}
</strong>{" "}
<u>
{
assignData?.workItem?.activityMaster
?.unitOfMeasurement
}
</u>
</label>
<div style={{ display: "flex", alignItems: "center" }}>
<div
ref={infoRef}
tabIndex="0"
className="d-flex align-items-center avatar-group justify-content-center ms-2"
data-bs-toggle="popover"
data-bs-trigger="focus"
data-bs-placement="right"
data-bs-html="true"
style={{ cursor: "pointer" }}
> >
Pending Task of Activity : &nbsp;
<label <svg
className="form-check-label fs-7 ms-4" xmlns="http://www.w3.org/2000/svg"
htmlFor="inlineCheckbox1" width="13"
height="13"
fill="currentColor"
className="bi bi-info-circle"
viewBox="0 0 16 16"
> >
<strong> <path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z" />
{assignData?.workItem?.plannedWork - <path d="m8.93 6.588-2.29.287-.082.38.45.083c.294.07.352.176.288.469l-.738 3.468c-.194.897.105 1.319.547 1.11l1.91-2.011c.241-.256.384-.592.287-.984-.172-.439-.58-.827-1.13-.967a.664.664 0 0 1-.58-.309l-.15-.241-.002-.002zM8 4c-.535 0-.943.372-.943.836 0 .464.408.836.943.836.535 0 .943-.372.943-.836 0-.464-.408-.836-.943-.836z" />
assignData?.workItem?.completedWork} </svg>
</strong>{" "} </div>
</div>
</label>
</div>
</div>
{/* Target for Today input and validation */}
<div className="col-md text-start mx-0 px-0">
<div className="form-check form-check-inline mt-2 px-1 mb-2 text-start">
<label
className="text-dark text-start d-flex align-items-center flex-wrap form-text"
htmlFor="targetForTodayInput" // Added a unique htmlFor for clarity
>
<span>Target for Today</span>&nbsp;
<span style={{ marginLeft: "46px" }}>:</span>
</label>
</div>
<div
className="form-check form-check-inline col-sm-3 mt-2"
style={{ marginLeft: "-28px" }}
>
<Controller
name="plannedTask"
control={control}
render={({ field }) => (
<div className="d-flex align-items-center gap-1 ">
<input
type="text"
className="form-control form-control-sm"
{...field}
id="defaultFormControlInput" // Consider a more descriptive ID if used elsewhere
aria-describedby="defaultFormControlHelp"
/>
<span style={{ paddingLeft: "6px", whiteSpace: "nowrap" }}>
<u> <u>
{" "}
{ {
assignData?.workItem?.activityMaster assignData?.workItem?.activityMaster
?.unitOfMeasurement ?.unitOfMeasurement
} }
</u> </u>
</label> </span>
<div style={{ display: "flex", alignItems: "center" }}> <div
style={{
display: "flex",
alignItems: "center",
}}
>
<div <div
ref={infoRef} ref={infoRef1}
tabIndex="0" tabIndex="0"
className="d-flex align-items-center avatar-group justify-content-center ms-2" className="d-flex align-items-center avatar-group justify-content-center ms-2"
data-bs-toggle="popover" data-bs-toggle="popover"
@ -611,144 +581,74 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
</svg> </svg>
</div> </div>
</div> </div>
</label>
</div>
</div>
{/* Target for Today input and validation */}
<div className="col-md text-start mx-0 px-0">
<div className="form-check form-check-inline mt-2 px-1 mb-2 text-start">
<label
className="text-dark text-start d-flex align-items-center flex-wrap form-text"
htmlFor="inlineCheckbox1"
>
<span>Target for Today</span>&nbsp;
<span style={{ marginLeft: "46px" }}>:</span>
</label>
</div>
<div
className="form-check form-check-inline col-sm-3 mt-2"
style={{ marginLeft: "-28px" }}
>
<Controller
name="plannedTask"
control={control}
render={({ field }) => (
<div className="d-flex align-items-center gap-1 ">
<input
type="text"
className="form-control form-control-sm"
{...field}
id="defaultFormControlInput"
aria-describedby="defaultFormControlHelp"
/>
<span style={{ paddingLeft: "6px", whiteSpace: "nowrap" }}>
<u> {
assignData?.workItem?.activityMaster
?.unitOfMeasurement
}</u>
</span>
<div
style={{
display: "flex",
alignItems: "center",
}}
>
<div
ref={infoRef1}
tabIndex="0"
className="d-flex align-items-center avatar-group justify-content-center ms-2"
data-bs-toggle="popover"
data-bs-trigger="focus"
data-bs-placement="right"
data-bs-html="true"
style={{ cursor: "pointer" }}
>
&nbsp;
<svg
xmlns="http://www.w3.org/2000/svg"
width="13"
height="13"
fill="currentColor"
className="bi bi-info-circle"
viewBox="0 0 16 16"
>
<path d="M8 15A7 7 0 1 1 8 1a7 7 0 0 1 0 14zm0 1A8 8 0 1 0 8 0a8 8 0 0 0 0 16z" />
<path d="m8.93 6.588-2.29.287-.082.38.45.083c.294.07.352.176.288.469l-.738 3.468c-.194.897.105 1.319.547 1.11l1.91-2.011c.241-.256.384-.592.287-.984-.172-.439-.58-.827-1.13-.967a.664.664 0 0 1-.58-.309l-.15-.241-.002-.002zM8 4c-.535 0-.943.372-.943.836 0 .464.408.836.943.836.535 0 .943-.372.943-.836 0-.464-.408-.836-.943-.836z" />
</svg>
</div>
</div>
</div>
)}
/>
</div>
{errors.plannedTask && (
<div className="danger-text mt-1">
{errors.plannedTask.message}
</div> </div>
)} )}
{isHelpVisible && (
<div
className="position-absolute bg-white border p-2 rounded shadow"
style={{ zIndex: 10, marginLeft: "10px" }}
>
<p className="mb-0">
Enter the target value for today's task.
</p>
</div>
)}
</div>
<label
className="form-text fs-7 m-1 text-lg text-dark"
htmlFor="descriptionTextarea"
htmlFor="descriptionTextarea"
>
Description
</label>
<Controller
name="description"
control={control}
render={({ field }) => (
<textarea
{...field}
className="form-control"
id="descriptionTextarea"
id="descriptionTextarea"
rows="2"
/>
)}
/> />
{errors.description && (
<div className="danger-text">{errors.description.message}</div>
)}
</div> </div>
<div className="col-12 d-flex justify-content-center align-items-center gap-sm-6 gap-8 text-center mt-1"> {errors.plannedTask && (
<button <div className="danger-text mt-1">
type="submit" {errors.plannedTask.message}
className="btn btn-sm btn-primary " </div>
disabled={isSubmitting || loading} )}
{isHelpVisible && (
<div
className="position-absolute bg-white border p-2 rounded shadow"
style={{ zIndex: 10, marginLeft: "10px" }}
> >
{isSubmitting ? "Please Wait" : "Submit"} <p className="mb-0">
</button> Enter the target value for today's task.
<button </p>
type="reset" </div>
className="btn btn-sm btn-label-secondary" )}
data-bs-dismiss="modal" </div>
aria-label="Close"
onClick={closedModel} <label
disabled={isSubmitting || loading} className="form-text fs-7 m-1 text-dark" // Removed duplicate htmlFor and text-lg
> htmlFor="descriptionTextarea"
Cancel >
</button> Description
</div> </label>
</form> <Controller
name="description"
control={control}
render={({ field }) => (
<textarea
{...field}
className="form-control"
id="descriptionTextarea" // Unique ID
rows="2"
/>
)}
/>
{errors.description && (
<div className="danger-text">{errors.description.message}</div>
)}
</div> </div>
</div>
<div className="col-12 d-flex justify-content-center align-items-center gap-sm-6 gap-8 text-center mt-1">
<button
type="submit"
className="btn btn-sm btn-primary "
disabled={isSubmitting || loading}
>
{isSubmitting ? "Please Wait" : "Submit"}
</button>
<button
type="reset"
className="btn btn-sm btn-label-secondary"
data-bs-dismiss="modal"
aria-label="Close"
onClick={closedModel}
disabled={isSubmitting || loading}
>
Cancel
</button>
</div>
</form>
</div> </div>
); </div>
</div> );
}; };
export default AssignTask; export default AssignTask;

View File

@ -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";
@ -23,63 +21,61 @@ import { useProjectName } from "../../hooks/useProjects";
const AttendancePage = () => { const AttendancePage = () => {
const [activeTab, setActiveTab] = useState("all"); const [activeTab, setActiveTab] = useState("all");
const [showPending, setShowPending] = useState(false); // Renamed for consistency const [showPending, setShowPending] = useState(false);
const [searchQuery, setSearchQuery] = useState(""); const [searchQuery, setSearchQuery] = useState("");
const [showPending, setShowPending] = useState(false); // Renamed for consistency // const loginUser = getCachedProfileData(); // Declared but not used
const [searchQuery, setSearchQuery] = useState("");
const loginUser = getCachedProfileData();
const selectedProject = useSelector((store) => store.localVariables.projectId);
const dispatch = useDispatch();
const selectedProject = useSelector((store) => store.localVariables.projectId); const selectedProject = useSelector((store) => store.localVariables.projectId);
const dispatch = useDispatch(); const dispatch = useDispatch();
const { const {
attendance, attendance,
loading: attLoading, loading: attLoading,
recall: attrecall, // recall: attrecall, // Declared but not used in the current logic
} = useAttendance(selectedProject); // Corrected typo: useAttendace to useAttendance } = 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
// FormData is declared but not used in the provided snippet's logic
// const [formData, setFormData] = useState({
const [formData, setFormData] = useState({ // markTime: "",
markTime: "", // description: "",
description: "", // date: new Date().toLocaleDateString(),
date: new Date().toLocaleDateString(), // });
});
const handler = useCallback( const handler = useCallback(
(msg) => { (msg) => {
if (selectedProject === msg.projectId) { if (selectedProject === msg.projectId) {
// Ensure attendances is not null before mapping
const updatedAttendance = attendances const updatedAttendance = attendances
? attendances.map((item) => ? attendances.map((item) =>
item.employeeId === msg.response.employeeId item.employeeId === msg.response.employeeId
? { ...item, ...msg.response } ? { ...item, ...msg.response }
: item : item
) )
: [msg.response]; // If attendances is null, initialize with new response : [msg.response];
cacheData("Attendance", { cacheData("Attendance", {
data: updatedAttendance, data: updatedAttendance,
projectId: selectedProject, projectId: selectedProject, // Corrected key from selectedProject to projectId for consistency
}); });
setAttendances(updatedAttendance); setAttendances(updatedAttendance);
} }
}, },
[selectedProject, attendances] // Removed attrecall as it's not a direct dependency for this state update [selectedProject, attendances]
); );
const employeeHandler = useCallback( const employeeHandler = useCallback(
(msg) => { (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)) { if (attendances?.some((item) => item.employeeId === msg.employeeId)) {
AttendanceRepository.getAttendance(selectedProject) AttendanceRepository.getAttendance(selectedProject)
.then((response) => { .then((response) => {
cacheData("Attendance", { data: response.data, selectedProject }); cacheData("Attendance", { data: response.data, projectId: selectedProject }); // Corrected key
setAttendances(response.data); setAttendances(response.data);
}) })
.catch((error) => { .catch((error) => {
@ -90,25 +86,29 @@ const AttendancePage = () => {
[selectedProject, attendances] [selectedProject, attendances]
); );
const getRole = (roleId) => { // The `getRole` function has a duplicate line: `const role = empRoles.find((b) => b.id === roleId);`
if (!empRoles) return "Unassigned"; // 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"; if (!roleId) return "Unassigned";
const role = empRoles.find((b) => b.id === roleId); const role = empRoles.find((b) => b.id === roleId);
const role = empRoles.find((b) => b.id === roleId);
return role ? role.role : "Unassigned"; return role ? role.role : "Unassigned";
}; }, [empRoles]);
const openModel = () => { const openModel = useCallback(() => {
setIsCreateModalOpen(true); setIsCreateModalOpen(true);
}; }, []);
const handleModalData = (employee) => { const handleModalData = useCallback((employee) => {
setModelConfig(employee); setModelConfig(employee);
}; }, []);
const closeModal = () => { const closeModal = useCallback(() => {
setModelConfig(null); setModelConfig(null);
setIsCreateModalOpen(false); 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"); const modalElement = document.getElementById("check-Out-modal");
if (modalElement) { if (modalElement) {
modalElement.classList.remove("show"); modalElement.classList.remove("show");
@ -118,25 +118,20 @@ const AttendancePage = () => {
if (modalBackdrop) { if (modalBackdrop) {
modalBackdrop.remove(); modalBackdrop.remove();
} }
const modalBackdrop = document.querySelector(".modal-backdrop");
if (modalBackdrop) {
modalBackdrop.remove();
}
} }
}; }, []);
const handleSubmit = (formData) => { const handleSubmit = useCallback((formData) => {
dispatch(markCurrentAttendance(formData)) dispatch(markCurrentAttendance(formData))
.then((action) => { .then((action) => {
// Check if payload and employeeId exist before mapping
if (action.payload && action.payload.employeeId) { if (action.payload && action.payload.employeeId) {
const updatedAttendance = attendances const updatedAttendance = attendances
? attendances.map((item) => ? attendances.map((item) =>
item.employeeId === action.payload.employeeId item.employeeId === action.payload.employeeId
? { ...item, ...action.payload } ? { ...item, ...action.payload }
: item : item
) )
: [action.payload]; // If attendances is null, initialize with new payload : [action.payload];
cacheData("Attendance", { cacheData("Attendance", {
data: updatedAttendance, data: updatedAttendance,
@ -151,45 +146,33 @@ const AttendancePage = () => {
.catch((error) => { .catch((error) => {
showToast(error.message, "error"); showToast(error.message, "error");
}); });
}; }, [dispatch, attendances, selectedProject]);
const handleToggle = (event) => { const handleToggle = useCallback((event) => {
setShowPending(event.target.checked); setShowPending(event.target.checked);
setShowPending(event.target.checked); }, []);
};
// Use useProjectName hook to get projectNames and set selected project
const { projectNames } = useProjectName();
useEffect(() => { useEffect(() => {
if (selectedProject === null && projectNames.length > 0) { if (selectedProject === null && projectNames.length > 0) {
dispatch(setProjectId(projectNames[0]?.id)); dispatch(setProjectId(projectNames[0]?.id));
} }
}, [selectedProject, projectNames, dispatch]); }, [selectedProject, projectNames, dispatch]);
// Open modal when modelConfig is set
if (selectedProject === null && projectNames.length > 0) {
dispatch(setProjectId(projectNames[0]?.id));
}
}, [selectedProject, projectNames, dispatch]);
// Open modal when modelConfig is set
useEffect(() => { useEffect(() => {
if (modelConfig !== null) { if (modelConfig !== null) {
openModel(); openModel();
} }
}, [modelConfig]); // Removed isCreateModalOpen from here as it's set by openModel() }, [modelConfig, openModel]); // Added openModel to dependency array
useEffect(() => { useEffect(() => {
setAttendances(attendance); setAttendances(attendance);
}, [attendance]); }, [attendance]);
// Filter and search logic for the 'Today's' tab (Attendance component)
const filteredAndSearchedTodayAttendance = useCallback(() => {
let currentData = attendances;
// Filter and search logic for the 'Today's' tab (Attendance component)
const filteredAndSearchedTodayAttendance = useCallback(() => { const filteredAndSearchedTodayAttendance = useCallback(() => {
let currentData = attendances; let currentData = attendances;
if (showPending) {
currentData = currentData?.filter(
if (showPending) { if (showPending) {
currentData = currentData?.filter( currentData = currentData?.filter(
(att) => att?.checkInTime !== null && att?.checkOutTime === null (att) => att?.checkInTime !== null && att?.checkOutTime === null
@ -199,33 +182,8 @@ const AttendancePage = () => {
if (searchQuery) { if (searchQuery) {
const lowerCaseSearchQuery = searchQuery.toLowerCase(); const lowerCaseSearchQuery = searchQuery.toLowerCase();
currentData = currentData?.filter((att) => { currentData = currentData?.filter((att) => {
// Combine first, middle, and last names for a comprehensive search
const fullName = [att.firstName, att.middleName, att.lastName] const fullName = [att.firstName, att.middleName, att.lastName]
.filter(Boolean) // Remove null or undefined parts .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
);
}
if (searchQuery) {
const lowerCaseSearchQuery = searchQuery.toLowerCase();
currentData = currentData?.filter((att) => {
// Combine first, middle, and last names for a comprehensive search
const fullName = [att.firstName, att.middleName, att.lastName]
.filter(Boolean) // Remove null or undefined parts
.join(" ") .join(" ")
.toLowerCase(); .toLowerCase();
@ -250,6 +208,7 @@ const AttendancePage = () => {
eventBus.on("employee", employeeHandler); eventBus.on("employee", employeeHandler);
return () => eventBus.off("employee", employeeHandler); return () => eventBus.off("employee", employeeHandler);
}, [employeeHandler]); }, [employeeHandler]);
return ( return (
<> <>
{isCreateModalOpen && modelConfig && ( {isCreateModalOpen && modelConfig && (
@ -317,60 +276,10 @@ const AttendancePage = () => {
<div className="p-2"> <div className="p-2">
<input <input
type="text" type="text"
className="form-control form-control-sm" // Bootstrap small size input className="form-control form-control-sm"
placeholder="Search employee..." placeholder="Search employee..."
value={searchQuery} value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)} onChange={(e) => setSearchQuery(e.target.value)}
// style={{ width: "200px", height: "30px" }} // Optional: further reduce width/height
/>
</div>
<ul className="nav nav-tabs d-flex justify-content-between align-items-center" role="tablist">
<div className="d-flex">
<li className="nav-item">
<button
type="button"
className={`nav-link ${activeTab === "all" ? "active" : ""} fs-6`}
onClick={() => setActiveTab("all")}
data-bs-toggle="tab"
data-bs-target="#navs-top-home"
>
Today's
</button>
</li>
<li className="nav-item">
<button
type="button"
className={`nav-link ${activeTab === "logs" ? "active" : ""} fs-6`}
onClick={() => setActiveTab("logs")}
data-bs-toggle="tab"
data-bs-target="#navs-top-profile"
>
Logs
</button>
</li>
<li className={`nav-item ${!DoRegularized && "d-none"}`}>
<button
type="button"
className={`nav-link ${activeTab === "regularization" ? "active" : ""
} fs-6`}
onClick={() => setActiveTab("regularization")}
data-bs-toggle="tab"
data-bs-target="#navs-top-messages"
>
Regularization
</button>
</li>
</div>
{/* Search Box remains here */}
<div className="p-2">
<input
type="text"
className="form-control form-control-sm" // Bootstrap small size input
placeholder="Search employee..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
// style={{ width: "200px", height: "30px" }} // Optional: further reduce width/height
/> />
</div> </div>
@ -392,13 +301,12 @@ const AttendancePage = () => {
{!attLoading && filteredAndSearchedTodayAttendance()?.length === 0 && ( {!attLoading && filteredAndSearchedTodayAttendance()?.length === 0 && (
<p> <p>
{" "} {" "}
{showPending
{showPending {showPending
? "No Pending Available" ? "No Pending Available"
: "No Employee assigned yet."}{" "} : "No Employee assigned yet."}{" "}
</p> </p>
)} )}
</div> </>
)} )}
{activeTab === "logs" && ( {activeTab === "logs" && (
<div className="tab-pane fade show active py-0"> <div className="tab-pane fade show active py-0">
@ -407,9 +315,7 @@ const AttendancePage = () => {
projectId={selectedProject} projectId={selectedProject}
setshowOnlyCheckout={setShowPending} setshowOnlyCheckout={setShowPending}
showOnlyCheckout={showPending} showOnlyCheckout={showPending}
searchQuery={searchQuery} // Pass search query to AttendanceLog searchQuery={searchQuery}
showOnlyCheckout={showPending}
searchQuery={searchQuery} // Pass search query to AttendanceLog
/> />
</div> </div>
)} )}
@ -417,11 +323,7 @@ const AttendancePage = () => {
<div className="tab-pane fade show active py-0"> <div className="tab-pane fade show active py-0">
<Regularization <Regularization
handleRequest={handleSubmit} handleRequest={handleSubmit}
searchQuery={searchQuery} // Pass it here searchQuery={searchQuery}
/>
<Regularization
handleRequest={handleSubmit}
searchQuery={searchQuery} // Pass it here
/> />
</div> </div>
)} )}