Changes in during a merge

This commit is contained in:
Kartik Sharma 2025-07-26 13:28:47 +05:30
parent aa5998bc11
commit 699c349ba5
5 changed files with 574 additions and 761 deletions

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,14 +325,7 @@ const AttendanceLog = ({
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{(logsLoading || isRefreshing) && ( // Use logsLoading and isRefreshing {paginatedAttendances.reduce((acc, attendance, index, arr) => {
<tr>
<td colSpan={6}>Loading...</td>
</tr>
)}
{!logsLoading && // Use logsLoading
!isRefreshing && // Use isRefreshing
paginatedAttendances.reduce((acc, attendance, index, arr) => {
const currentDate = moment( const currentDate = moment(
attendance.checkInTime || attendance.checkOutTime attendance.checkInTime || attendance.checkOutTime
).format("YYYY-MM-DD"); ).format("YYYY-MM-DD");
@ -368,20 +394,15 @@ const AttendanceLog = ({
</tbody> </tbody>
</table> </table>
) : ( ) : (
!logsLoading && // Use logsLoading
!isRefreshing && ( // Use isRefreshing
<div <div
className="d-flex justify-content-center align-items-center text-muted" className="d-flex justify-content-center align-items-center text-muted w-100"
style={{ style={{ height: "200px" }} // Added height for better visual during no data
width: "100%",
}}
> >
No employee logs. No employee logs.
</div> </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" : ""}`}>

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)}

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,
@ -234,7 +234,7 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
<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,
@ -262,7 +262,8 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
<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 ${
selectedRoles.includes("all") || selectedRoles.length === 0
? "text-secondary" ? "text-secondary"
: "text-primary" : "text-primary"
}`} }`}
@ -291,16 +292,14 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
</span> </span>
)} )}
{/* Dropdown Menu */} {/* Dropdown Menu - Corrected: Removed duplicate ul block */}
<ul <ul className="dropdown-menu p-2 text-capitalize" style={{ maxHeight: "300px", overflowY: "auto" }}>
className="dropdown-menu p-2 text-capitalize " <li> {/* Changed key="all" to a unique key if possible, or keep it if "all" is a unique identifier */}
>
<li key="all">
<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="checkboxAllRoles" // Unique ID
value="all" value="all"
checked={selectedRoles.includes("all")} checked={selectedRoles.includes("all")}
onChange={(e) => handleRoleChange(e, e.target.value)} onChange={(e) => handleRoleChange(e, e.target.value)}
@ -317,7 +316,7 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
<input <input
className="form-check-input" className="form-check-input"
type="checkbox" type="checkbox"
id={`checkboxRole-${role.id}`} id={`checkboxRole-${role.id}`} // Unique ID
value={role.id} value={role.id}
checked={selectedRoles.includes(String(role.id))} checked={selectedRoles.includes(String(role.id))}
onChange={(e) => handleRoleChange(e, e.target.value)} onChange={(e) => handleRoleChange(e, e.target.value)}
@ -330,118 +329,18 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
))} ))}
</ul> </ul>
</div> </div>
<ul
className="dropdown-menu p-2 text-capitalize"
style={{ maxHeight: "300px", overflowY: "auto" }}
>
<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>
<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>
{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 <input
type="text" type="text"
className="form-control form-control-sm ms-auto mb-2 mt-2" className="form-control form-control-sm ms-auto mb-2 mt-2"
placeholder="Search employees or roles..." placeholder="Search employees or roles..."
value={searchTerm} value={searchTerm}
onChange={handleSearchChange} onChange={handleSearchChange}
style={{ maxWidth: '200px' }} style={{ maxWidth: "200px" }}
/> />
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<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
);
<div <div
className="col-12 mt-2" className="col-12 mt-2"
style={{ maxHeight: "280px", overflowY: "auto", overflowX: "hidden" }} style={{ maxHeight: "280px", overflowY: "auto", overflowX: "hidden" }}
@ -472,7 +371,7 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
{...field} {...field}
className="form-check-input me-1 mt-1" className="form-check-input me-1 mt-1"
type="checkbox" type="checkbox"
id={`employee-${emp?.id}`} id={`employee-${emp?.id}`} // Unique ID
value={emp.id} value={emp.id}
checked={field.value?.includes(emp.id)} checked={field.value?.includes(emp.id)}
onChange={(e) => { onChange={(e) => {
@ -532,10 +431,11 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
className="badge rounded-pill bg-label-primary d-inline-flex align-items-center me-1 mb-1" className="badge rounded-pill bg-label-primary d-inline-flex align-items-center me-1 mb-1"
> >
{emp.firstName} {emp.lastName} {emp.firstName} {emp.lastName}
<p {/* Changed p tag to button for semantic correctness and accessibility */}
<button
type="button" type="button"
className=" btn-close-white p-0 m-0" className="btn-close btn-close-white ms-1" // Added ms-1 for spacing, removed p-0 m-0
aria-label="Close" aria-label="Remove employee" // More descriptive aria-label
onClick={() => { onClick={() => {
const updatedSelected = watch( const updatedSelected = watch(
"selectedEmployees" "selectedEmployees"
@ -547,8 +447,8 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
trigger("selectedEmployees"); trigger("selectedEmployees");
}} }}
> >
<i className="icon-base bx bx-x icon-md "></i> <i className="icon-base bx bx-x icon-md"></i>
</p> </button>
</span> </span>
) )
); );
@ -568,12 +468,12 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
<div className="form-check form-check-inline mt-3 px-1"> <div className="form-check form-check-inline mt-3 px-1">
<label <label
className="form-text text-dark align-items-center d-flex" className="form-text text-dark align-items-center d-flex"
htmlFor="inlineCheckbox1" htmlFor="inlineCheckbox1" // This htmlFor isn't linked to a checkbox in this context
> >
Pending Task of Activity : Pending Task of Activity :
<label <label
className="form-check-label fs-7 ms-4" className="form-check-label fs-7 ms-4"
htmlFor="inlineCheckbox1" htmlFor="inlineCheckbox1" // This htmlFor isn't linked to a checkbox in this context
> >
<strong> <strong>
{assignData?.workItem?.plannedWork - {assignData?.workItem?.plannedWork -
@ -620,7 +520,7 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
<div className="form-check form-check-inline mt-2 px-1 mb-2 text-start"> <div className="form-check form-check-inline mt-2 px-1 mb-2 text-start">
<label <label
className="text-dark text-start d-flex align-items-center flex-wrap form-text" className="text-dark text-start d-flex align-items-center flex-wrap form-text"
htmlFor="inlineCheckbox1" htmlFor="targetForTodayInput" // Added a unique htmlFor for clarity
> >
<span>Target for Today</span>&nbsp; <span>Target for Today</span>&nbsp;
<span style={{ marginLeft: "46px" }}>:</span> <span style={{ marginLeft: "46px" }}>:</span>
@ -639,14 +539,17 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
type="text" type="text"
className="form-control form-control-sm" className="form-control form-control-sm"
{...field} {...field}
id="defaultFormControlInput" id="defaultFormControlInput" // Consider a more descriptive ID if used elsewhere
aria-describedby="defaultFormControlHelp" aria-describedby="defaultFormControlHelp"
/> />
<span style={{ paddingLeft: "6px", whiteSpace: "nowrap" }}> <span style={{ paddingLeft: "6px", whiteSpace: "nowrap" }}>
<u> { <u>
{" "}
{
assignData?.workItem?.activityMaster assignData?.workItem?.activityMaster
?.unitOfMeasurement ?.unitOfMeasurement
}</u> }
</u>
</span> </span>
<div <div
style={{ style={{
@ -702,8 +605,7 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
</div> </div>
<label <label
className="form-text fs-7 m-1 text-lg text-dark" className="form-text fs-7 m-1 text-dark" // Removed duplicate htmlFor and text-lg
htmlFor="descriptionTextarea"
htmlFor="descriptionTextarea" htmlFor="descriptionTextarea"
> >
Description Description
@ -715,8 +617,7 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
<textarea <textarea
{...field} {...field}
className="form-control" className="form-control"
id="descriptionTextarea" id="descriptionTextarea" // Unique ID
id="descriptionTextarea"
rows="2" rows="2"
/> />
)} )}
@ -748,7 +649,6 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
</form> </form>
</div> </div>
</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,17 +118,12 @@ 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) =>
@ -136,7 +131,7 @@ const AttendancePage = () => {
? { ...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>
)} )}