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 RenderAttendanceStatus from "./RenderAttendanceStatus";
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 eventBus from "../../services/eventBus";
// Custom hook for pagination
const usePagination = (data, itemsPerPage) => {
const [currentPage, setCurrentPage] = useState(1);
// Ensure data is an array before accessing length
const totalItems = Array.isArray(data) ? data.length : 0;
const maxPage = Math.ceil(totalItems / itemsPerPage);
@ -28,7 +30,6 @@ const usePagination = (data, itemsPerPage) => {
}
}, [maxPage]);
// Ensure resetPage is returned by the hook
const resetPage = useCallback(() => setCurrentPage(1), []);
return {
@ -44,22 +45,29 @@ const AttendanceLog = ({
handleModalData,
projectId,
setshowOnlyCheckout,
showOnlyCheckout, // Prop for showPending state
searchQuery, // Prop for search query
showOnlyCheckout,
searchQuery,
}) => {
const selectedProject = useSelector(
(store) => store.localVariables.projectId
);
const [dateRange, setDateRange] = useState({ startDate: "", endDate: "" });
// Initialize date range with sensible defaults, e.g., last 7 days or current day
const defaultEndDate = moment().format("YYYY-MM-DD");
const defaultStartDate = moment().subtract(6, 'days').format("YYYY-MM-DD"); // Last 7 days including today
const [dateRange, setDateRange] = useState({
startDate: defaultStartDate,
endDate: defaultEndDate
});
const dispatch = useDispatch();
// Get data, loading, and fetching state from the Redux store's attendanceLogs slice
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
// Memoize today and yesterday dates to prevent re-creation on every render
const today = useMemo(() => {
const d = new Date();
d.setHours(0, 0, 0, 0);
@ -69,6 +77,7 @@ const AttendanceLog = ({
const yesterday = useMemo(() => {
const d = new Date();
d.setDate(d.getDate() - 1);
d.setHours(0, 0, 0, 0); // Set to start of day for accurate comparison
return d;
}, []);
@ -92,7 +101,7 @@ const AttendanceLog = ({
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(() => {
const { startDate, endDate } = dateRange;
dispatch(
@ -102,21 +111,26 @@ const AttendanceLog = ({
toDate: endDate,
})
);
setIsRefreshing(false); // Reset refreshing state after fetch attempt
}, [dateRange, projectId, dispatch, isRefreshing]); // isRefreshing is a dependency because it triggers a re-fetch
// Reset refreshing state only after the dispatch, assuming fetchAttendanceData
// 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(() => {
let filteredData = showOnlyCheckout // Use the prop directly
? attendanceLogsData.filter((item) => item.checkOutTime === null) // Use attendanceLogsData
: attendanceLogsData; // Use attendanceLogsData
let filteredData = showOnlyCheckout
? (attendanceLogsData || []).filter((item) => item.checkOutTime === null) // Ensure attendanceLogsData is an array
: (attendanceLogsData || []); // Ensure attendanceLogsData is an array
// Apply search query filter
if (searchQuery) {
const lowerCaseSearchQuery = searchQuery.toLowerCase();
filteredData = filteredData.filter((att) => {
// Construct a full name from available parts, filtering out null/undefined
const fullName = [att.firstName, att.middleName, att.lastName]
.filter(Boolean) // This removes null, undefined, or empty string parts
.filter(Boolean)
.join(" ")
.toLowerCase();
@ -128,6 +142,7 @@ const AttendanceLog = ({
});
}
// Grouping and sorting logic remains mostly the same, ensuring 'filteredData' is used
const group1 = filteredData
.filter((d) => d.activity === 1 && isSameDay(d.checkInTime))
.sort(sortByName);
@ -158,7 +173,10 @@ const AttendanceLog = ({
// Group by date
const groupedByDate = sortedList.reduce((acc, item) => {
const date = (item.checkInTime || item.checkOutTime)?.split("T")[0];
// Use checkInTime for activity 1, and checkOutTime for others or if checkInTime is null
const dateString = item.activity === 1 ? item.checkInTime : item.checkOutTime;
const date = dateString ? moment(dateString).format("YYYY-MM-DD") : null;
if (date) {
acc[date] = acc[date] || [];
acc[date].push(item);
@ -172,46 +190,56 @@ const AttendanceLog = ({
// Create the final sorted array
return sortedDates.flatMap((date) => groupedByDate[date]);
}, [attendanceLogsData, showOnlyCheckout, searchQuery, isSameDay, isBeforeToday, sortByName]); // Added attendanceLogsData to dependencies
}, [attendanceLogsData, showOnlyCheckout, searchQuery, isSameDay, isBeforeToday, sortByName]);
const {
currentPage,
totalPages,
currentItems: paginatedAttendances,
paginate,
resetPage, // Destructure resetPage here
resetPage,
} = usePagination(processedData, 20);
// Effect to reset pagination when search query changes
// Effect to reset pagination when search query or showOnlyCheckout changes
useEffect(() => {
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(
(msg) => {
// Check if the event is relevant to the current project and date range
const { startDate, endDate } = dateRange;
const checkIn = msg.response.checkInTime.substring(0, 10);
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 (
projectId === msg.projectId &&
startDate <= checkIn &&
checkIn <= endDate
eventDate &&
eventDate >= startDate && // Ensure eventDate is within the current range
eventDate <= endDate
) {
const updatedAttendance = data.map((item) =>
item.id === msg.response.id
? { ...item, ...msg.response }
: item
// Trigger a re-fetch of attendance data to get the latest state
dispatch(
fetchAttendanceData({
projectId,
fromDate: startDate,
toDate: endDate,
})
);
dispatch(setAttendanceData(updatedAttendance)); // Update Redux store
}
},
[projectId, dateRange, data, dispatch]
[projectId, dateRange, dispatch]
);
useEffect(() => {
eventBus.on("attendance_log", handler);
return () => eventBus.off("attendance_log", handler);
}, [handler]);
// Handler for 'employee' event from eventBus (already triggers a refetch)
const employeeHandler = useCallback(
(msg) => {
const { startDate, endDate } = dateRange;
@ -233,7 +261,7 @@ const AttendanceLog = ({
const handleRefreshClick = () => {
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 (
@ -245,27 +273,27 @@ const AttendanceLog = ({
<div className="d-flex align-items-center my-0 ">
<DateRangePicker
onRangeChange={setDateRange}
defaultStartDate={yesterday}
defaultStartDate={yesterday.toLocaleDateString("en-CA")} // Pass default as string YYYY-MM-DD
/>
<div className="form-check form-switch text-start m-0 ms-5">
<input
type="checkbox"
className="form-check-input"
role="switch"
disabled={logsFetching} // Use logsFetching from Redux store
disabled={logsFetching}
id="inactiveEmployeesCheckbox"
checked={showOnlyCheckout} // Use the prop directly
onChange={(e) => setshowOnlyCheckout(e.target.checked)} // Use the prop setter
checked={showOnlyCheckout}
onChange={(e) => setshowOnlyCheckout(e.target.checked)}
/>
<label className="form-check-label ms-0">Show Pending</label>
</div>
</div>
<div className="col-md-2 m-0 text-end">
<i
className={`bx bx-refresh cursor-pointer fs-4 ${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"
onClick={handleRefreshClick} // Call the new handler
onClick={handleRefreshClick}
/>
</div>
</div>
@ -273,7 +301,12 @@ const AttendanceLog = ({
className="table-responsive text-nowrap"
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">
<thead>
<tr>
@ -292,14 +325,7 @@ const AttendanceLog = ({
</tr>
</thead>
<tbody>
{(logsLoading || isRefreshing) && ( // Use logsLoading and isRefreshing
<tr>
<td colSpan={6}>Loading...</td>
</tr>
)}
{!logsLoading && // Use logsLoading
!isRefreshing && // Use isRefreshing
paginatedAttendances.reduce((acc, attendance, index, arr) => {
{paginatedAttendances.reduce((acc, attendance, index, arr) => {
const currentDate = moment(
attendance.checkInTime || attendance.checkOutTime
).format("YYYY-MM-DD");
@ -368,20 +394,15 @@ const AttendanceLog = ({
</tbody>
</table>
) : (
!logsLoading && // Use logsLoading
!isRefreshing && ( // Use isRefreshing
<div
className="d-flex justify-content-center align-items-center text-muted"
style={{
width: "100%",
}}
className="d-flex justify-content-center align-items-center text-muted w-100"
style={{ height: "200px" }} // Added height for better visual during no data
>
No employee logs.
</div>
)
)}
</div>
{!logsLoading && !isRefreshing && processedData.length > 20 && ( // Use logsLoading and isRefreshing
{!logsLoading && !isRefreshing && processedData.length > 20 && (
<nav aria-label="Page ">
<ul className="pagination pagination-sm justify-content-end py-1">
<li className={`page-item ${currentPage === 1 ? "disabled" : ""}`}>

View File

@ -14,41 +14,45 @@ const Regularization = ({ handleRequest, searchQuery }) => {
const [regularizesList, setRegularizedList] = useState([]);
const { regularizes, loading, refetch } = useRegularizationRequests(selectedProject);
// Update regularizesList when regularizes data changes
useEffect(() => {
setRegularizedList(regularizes);
}, [regularizes]);
const sortByName = (a, b) => {
const sortByName = useCallback((a, b) => {
const nameA = (a.firstName + a.lastName).toLowerCase();
const nameB = (b.firstName + b.lastName).toLowerCase();
return nameA.localeCompare(nameB);
};
}, []);
const handler = useCallback(
(msg) => {
if (selectedProject == msg.projectId) {
const updatedAttendance = regularizes?.filter(item => item.id !== msg.response.id);
if (selectedProject === msg.projectId) { // Use strict equality for comparison
// Filter out the updated item to effectively remove it from the list
// as it's likely been processed (approved/rejected)
const updatedAttendance = regularizesList?.filter(item => item.id !== msg.response.id);
cacheData("regularizedList", {
data: updatedAttendance,
projectId: selectedProject,
});
// Refetch to get the latest data from the source, ensuring consistency
refetch();
}
},
[selectedProject, regularizes]
[selectedProject, regularizesList, refetch] // Added regularizesList and refetch to dependencies
);
const employeeHandler = useCallback(
(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();
}
},
[regularizes]
[regularizes, refetch] // Added refetch to dependencies
);
useEffect(() => {
// Event bus listeners
useEffect(() => {
eventBus.on("regularization", handler);
return () => eventBus.off("regularization", handler);
@ -59,7 +63,7 @@ const Regularization = ({ handleRequest, searchQuery }) => {
return () => eventBus.off("employee", employeeHandler);
}, [employeeHandler]);
// Search filter logic added here
// Search filter logic
const filteredData = [...regularizesList]
?.filter((item) => {
if (!searchQuery) return true;
@ -144,7 +148,7 @@ const Regularization = ({ handleRequest, searchQuery }) => {
{!loading && totalPages > 1 && (
<nav aria-label="Page ">
<ul className="pagination pagination-sm justify-content-end py-1 mt-3">
<li className={`page-item ${currentPage === 1 ? "disabled" : ""}`}>
<li className={`page-item  ${currentPage === 1 ? "disabled" : ""}`}>
<button
className="page-link btn-xs"
onClick={() => paginate(currentPage - 1)}

View File

@ -41,20 +41,6 @@ const Header = () => {
"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) => {
if (!Array.isArray(roles)) return "User";
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
const [selectedRoles, setSelectedRoles] = useState(["all"]);
// Changed to an array to hold multiple selected roles
const [selectedRoles, setSelectedRoles] = useState(["all"]);
// const [selectedRoles, setSelectedRoles] = useState(["all"]);
const [displayedSelection, setDisplayedSelection] = useState("");
const {
handleSubmit,
@ -234,7 +234,7 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
<div className="mb-1">
<p className="mb-0">
<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?.floor?.floorName,
@ -262,7 +262,8 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
<span className="text-dark">Select Team</span>
<div className="dropdown position-relative d-inline-block">
<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-primary"
}`}
@ -291,16 +292,14 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
</span>
)}
{/* Dropdown Menu */}
<ul
className="dropdown-menu p-2 text-capitalize "
>
<li key="all">
{/* 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"
id="checkboxAllRoles" // Unique ID
value="all"
checked={selectedRoles.includes("all")}
onChange={(e) => handleRoleChange(e, e.target.value)}
@ -317,7 +316,7 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
<input
className="form-check-input"
type="checkbox"
id={`checkboxRole-${role.id}`}
id={`checkboxRole-${role.id}`} // Unique ID
value={role.id}
checked={selectedRoles.includes(String(role.id))}
onChange={(e) => handleRoleChange(e, e.target.value)}
@ -330,118 +329,18 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
))}
</ul>
</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
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' }}
style={{ maxWidth: "200px" }}
/>
</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
className="col-12 mt-2"
style={{ maxHeight: "280px", overflowY: "auto", overflowX: "hidden" }}
@ -472,7 +371,7 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
{...field}
className="form-check-input me-1 mt-1"
type="checkbox"
id={`employee-${emp?.id}`}
id={`employee-${emp?.id}`} // Unique ID
value={emp.id}
checked={field.value?.includes(emp.id)}
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"
>
{emp.firstName} {emp.lastName}
<p
{/* Changed p tag to button for semantic correctness and accessibility */}
<button
type="button"
className=" btn-close-white p-0 m-0"
aria-label="Close"
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"
@ -547,8 +447,8 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
trigger("selectedEmployees");
}}
>
<i className="icon-base bx bx-x icon-md "></i>
</p>
<i className="icon-base bx bx-x icon-md"></i>
</button>
</span>
)
);
@ -568,12 +468,12 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
<div className="form-check form-check-inline mt-3 px-1">
<label
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 :
<label
className="form-check-label fs-7 ms-4"
htmlFor="inlineCheckbox1"
htmlFor="inlineCheckbox1" // This htmlFor isn't linked to a checkbox in this context
>
<strong>
{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">
<label
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 style={{ marginLeft: "46px" }}>:</span>
@ -639,14 +539,17 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
type="text"
className="form-control form-control-sm"
{...field}
id="defaultFormControlInput"
id="defaultFormControlInput" // Consider a more descriptive ID if used elsewhere
aria-describedby="defaultFormControlHelp"
/>
<span style={{ paddingLeft: "6px", whiteSpace: "nowrap" }}>
<u> {
<u>
{" "}
{
assignData?.workItem?.activityMaster
?.unitOfMeasurement
}</u>
}
</u>
</span>
<div
style={{
@ -702,8 +605,7 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
</div>
<label
className="form-text fs-7 m-1 text-lg text-dark"
htmlFor="descriptionTextarea"
className="form-text fs-7 m-1 text-dark" // Removed duplicate htmlFor and text-lg
htmlFor="descriptionTextarea"
>
Description
@ -715,8 +617,7 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
<textarea
{...field}
className="form-control"
id="descriptionTextarea"
id="descriptionTextarea"
id="descriptionTextarea" // Unique ID
rows="2"
/>
)}
@ -748,7 +649,6 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
</form>
</div>
</div>
</div>
);
</div> );
};
export default AssignTask;

View File

@ -1,10 +1,8 @@
import React, { useState, useEffect, useCallback } from "react";
import {
cacheData,
clearCacheKey,
getCachedData,
getCachedProfileData,
} from "../../slices/apiDataManager";
} from "../../slices/apiDataManager"; // clearCacheKey and getCachedData are not used
import Breadcrumb from "../../components/common/Breadcrumb";
import AttendanceLog from "../../components/Activities/AttendcesLogs";
import Attendance from "../../components/Activities/Attendance";
@ -23,63 +21,61 @@ import { useProjectName } from "../../hooks/useProjects";
const AttendancePage = () => {
const [activeTab, setActiveTab] = useState("all");
const [showPending, setShowPending] = useState(false); // Renamed for consistency
const [showPending, setShowPending] = useState(false);
const [searchQuery, setSearchQuery] = useState("");
const [showPending, setShowPending] = useState(false); // Renamed for consistency
const [searchQuery, setSearchQuery] = useState("");
const loginUser = getCachedProfileData();
const selectedProject = useSelector((store) => store.localVariables.projectId);
const dispatch = useDispatch();
// const loginUser = getCachedProfileData(); // Declared but not used
const selectedProject = useSelector((store) => store.localVariables.projectId);
const dispatch = useDispatch();
const {
attendance,
loading: attLoading,
recall: attrecall,
} = useAttendance(selectedProject); // Corrected typo: useAttendace to useAttendance
// recall: attrecall, // Declared but not used in the current logic
} = useAttendance(selectedProject);
const [attendances, setAttendances] = useState();
const [empRoles, setEmpRoles] = useState(null);
const [empRoles, setEmpRoles] = useState(null); // This state is declared but never populated or used
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
const [modelConfig, setModelConfig] = useState();
const [modelConfig, setModelConfig] = useState(null); // Initialize with null for clarity
const DoRegularized = useHasUserPermission(REGULARIZE_ATTENDANCE);
const { projectNames, loading: projectLoading, fetchData } = useProjectName();
// const { projectNames, loading: projectLoading, fetchData } = useProjectName(); // loading and fetchData are not used directly here
const [formData, setFormData] = useState({
markTime: "",
description: "",
date: new Date().toLocaleDateString(),
});
// FormData is declared but not used in the provided snippet's logic
// const [formData, setFormData] = useState({
// markTime: "",
// description: "",
// date: new Date().toLocaleDateString(),
// });
const handler = useCallback(
(msg) => {
if (selectedProject === msg.projectId) {
// Ensure attendances is not null before mapping
const updatedAttendance = attendances
? attendances.map((item) =>
item.employeeId === msg.response.employeeId
? { ...item, ...msg.response }
: item
)
: [msg.response]; // If attendances is null, initialize with new response
: [msg.response];
cacheData("Attendance", {
data: updatedAttendance,
projectId: selectedProject,
projectId: selectedProject, // Corrected key from selectedProject to projectId for consistency
});
setAttendances(updatedAttendance);
}
},
[selectedProject, attendances] // Removed attrecall as it's not a direct dependency for this state update
[selectedProject, attendances]
);
const employeeHandler = useCallback(
(msg) => {
// This logic fetches all attendance when an employee event occurs,
// which might be inefficient if only a single employee's data needs updating.
// Consider a more granular update if performance is an issue.
if (attendances?.some((item) => item.employeeId === msg.employeeId)) {
AttendanceRepository.getAttendance(selectedProject)
.then((response) => {
cacheData("Attendance", { data: response.data, selectedProject });
cacheData("Attendance", { data: response.data, projectId: selectedProject }); // Corrected key
setAttendances(response.data);
})
.catch((error) => {
@ -90,25 +86,29 @@ const AttendancePage = () => {
[selectedProject, attendances]
);
const getRole = (roleId) => {
if (!empRoles) return "Unassigned";
// The `getRole` function has a duplicate line: `const role = empRoles.find((b) => b.id === roleId);`
// Also, `empRoles` is declared but never set. If this function is meant to be used,
// `empRoles` needs to be fetched and set in the state.
const getRole = useCallback((roleId) => {
if (!empRoles) return "Unassigned"; // empRoles is always null with current code
if (!roleId) return "Unassigned";
const role = empRoles.find((b) => b.id === roleId);
const role = empRoles.find((b) => b.id === roleId);
return role ? role.role : "Unassigned";
};
}, [empRoles]);
const openModel = () => {
const openModel = useCallback(() => {
setIsCreateModalOpen(true);
};
}, []);
const handleModalData = (employee) => {
const handleModalData = useCallback((employee) => {
setModelConfig(employee);
};
}, []);
const closeModal = () => {
const closeModal = useCallback(() => {
setModelConfig(null);
setIsCreateModalOpen(false);
// Directly manipulating DOM is generally discouraged in React.
// Consider using React state to control modal visibility.
const modalElement = document.getElementById("check-Out-modal");
if (modalElement) {
modalElement.classList.remove("show");
@ -118,17 +118,12 @@ const AttendancePage = () => {
if (modalBackdrop) {
modalBackdrop.remove();
}
const modalBackdrop = document.querySelector(".modal-backdrop");
if (modalBackdrop) {
modalBackdrop.remove();
}
}
};
}, []);
const handleSubmit = (formData) => {
const handleSubmit = useCallback((formData) => {
dispatch(markCurrentAttendance(formData))
.then((action) => {
// Check if payload and employeeId exist before mapping
if (action.payload && action.payload.employeeId) {
const updatedAttendance = attendances
? attendances.map((item) =>
@ -136,7 +131,7 @@ const AttendancePage = () => {
? { ...item, ...action.payload }
: item
)
: [action.payload]; // If attendances is null, initialize with new payload
: [action.payload];
cacheData("Attendance", {
data: updatedAttendance,
@ -151,45 +146,33 @@ const AttendancePage = () => {
.catch((error) => {
showToast(error.message, "error");
});
};
}, [dispatch, attendances, selectedProject]);
const handleToggle = (event) => {
const handleToggle = useCallback((event) => {
setShowPending(event.target.checked);
setShowPending(event.target.checked);
};
}, []);
// Use useProjectName hook to get projectNames and set selected project
const { projectNames } = useProjectName();
useEffect(() => {
if (selectedProject === null && projectNames.length > 0) {
dispatch(setProjectId(projectNames[0]?.id));
}
}, [selectedProject, projectNames, dispatch]);
// 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(() => {
if (modelConfig !== null) {
openModel();
}
}, [modelConfig]); // Removed isCreateModalOpen from here as it's set by openModel()
}, [modelConfig, openModel]); // Added openModel to dependency array
useEffect(() => {
setAttendances(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(() => {
let currentData = attendances;
if (showPending) {
currentData = currentData?.filter(
if (showPending) {
currentData = currentData?.filter(
(att) => att?.checkInTime !== null && att?.checkOutTime === null
@ -199,33 +182,8 @@ const AttendancePage = () => {
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(" ")
.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
.filter(Boolean)
.join(" ")
.toLowerCase();
@ -250,6 +208,7 @@ const AttendancePage = () => {
eventBus.on("employee", employeeHandler);
return () => eventBus.off("employee", employeeHandler);
}, [employeeHandler]);
return (
<>
{isCreateModalOpen && modelConfig && (
@ -317,60 +276,10 @@ const AttendancePage = () => {
<div className="p-2">
<input
type="text"
className="form-control form-control-sm" // Bootstrap small size input
className="form-control form-control-sm"
placeholder="Search employee..."
value={searchQuery}
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>
@ -392,13 +301,12 @@ const AttendancePage = () => {
{!attLoading && filteredAndSearchedTodayAttendance()?.length === 0 && (
<p>
{" "}
{showPending
{showPending
? "No Pending Available"
: "No Employee assigned yet."}{" "}
</p>
)}
</div>
</>
)}
{activeTab === "logs" && (
<div className="tab-pane fade show active py-0">
@ -407,9 +315,7 @@ const AttendancePage = () => {
projectId={selectedProject}
setshowOnlyCheckout={setShowPending}
showOnlyCheckout={showPending}
searchQuery={searchQuery} // Pass search query to AttendanceLog
showOnlyCheckout={showPending}
searchQuery={searchQuery} // Pass search query to AttendanceLog
searchQuery={searchQuery}
/>
</div>
)}
@ -417,11 +323,7 @@ const AttendancePage = () => {
<div className="tab-pane fade show active py-0">
<Regularization
handleRequest={handleSubmit}
searchQuery={searchQuery} // Pass it here
/>
<Regularization
handleRequest={handleSubmit}
searchQuery={searchQuery} // Pass it here
searchQuery={searchQuery}
/>
</div>
)}