diff --git a/src/components/Activities/Attendance.jsx b/src/components/Activities/Attendance.jsx
index 16315099..fed34f34 100644
--- a/src/components/Activities/Attendance.jsx
+++ b/src/components/Activities/Attendance.jsx
@@ -6,27 +6,34 @@ import RenderAttendanceStatus from "./RenderAttendanceStatus";
import usePagination from "../../hooks/usePagination";
import { useNavigate } from "react-router-dom";
import { ITEMS_PER_PAGE } from "../../utils/constants";
-import { useAttendance } from "../../hooks/useAttendance"; // This hook is already providing data
+import { useAttendance } from "../../hooks/useAttendance";
import { useSelector } from "react-redux";
import { useQueryClient } from "@tanstack/react-query";
import eventBus from "../../services/eventBus";
-const Attendance = ({ getRole, handleModalData, attendance: filteredAndSearchedAttendanceFromParent, showOnlyCheckout, setshowOnlyCheckout }) => {
+const Attendance = ({ getRole, handleModalData }) => {
const queryClient = useQueryClient();
+ const [loading, setLoading] = useState(false);
const navigate = useNavigate();
const [todayDate, setTodayDate] = useState(new Date());
-
+ const [ShowPending, setShowPending] = useState(false);
const selectedProject = useSelector(
(store) => store.localVariables.projectId
);
const {
+ attendance,
loading: attLoading,
recall: attrecall,
isFetching
- } = useAttendance(selectedProject); // Keep this hook to manage recall and fetching status
+ } = useAttendance(selectedProject);
+ const filteredAttendance = ShowPending
+ ? attendance?.filter(
+ (att) => att?.checkInTime !== null && att?.checkOutTime === null
+ )
+ : attendance;
- const attendanceList = Array.isArray(filteredAndSearchedAttendanceFromParent)
- ? filteredAndSearchedAttendanceFromParent
+ const attendanceList = Array.isArray(filteredAttendance)
+ ? filteredAttendance
: [];
const sortByName = (a, b) => {
@@ -34,7 +41,6 @@ const Attendance = ({ getRole, handleModalData, attendance: filteredAndSearchedA
const nameB = (b.firstName + b.lastName).toLowerCase();
return nameA?.localeCompare(nameB);
};
-
const group1 = attendanceList
.filter((d) => d.activity === 1 || d.activity === 4)
.sort(sortByName);
@@ -42,39 +48,36 @@ const Attendance = ({ getRole, handleModalData, attendance: filteredAndSearchedA
.filter((d) => d.activity === 0)
.sort(sortByName);
- const finalFilteredDataForPagination = [...group1, ...group2];
-
+ const filteredData = [...group1, ...group2];
const { currentPage, totalPages, currentItems, paginate } = usePagination(
- finalFilteredDataForPagination, // Use the data that's already been searched and grouped
+ filteredData,
ITEMS_PER_PAGE
);
const handler = useCallback(
(msg) => {
- if (selectedProject === msg.projectId) {
+ if (selectedProject == msg.projectId) {
queryClient.setQueryData(["attendance", selectedProject], (oldData) => {
if (!oldData) {
- queryClient.invalidateQueries({ queryKey: ["attendance"] });
- return; // Exit to avoid mapping on undefined oldData
- }
+ queryClient.invalidateQueries({queryKey:["attendance"]})
+ };
return oldData.map((record) =>
record.employeeId === msg.response.employeeId ? { ...record, ...msg.response } : record
);
});
}
},
- [selectedProject, queryClient] // Added queryClient to dependencies
+ [selectedProject, attrecall]
);
const employeeHandler = useCallback(
(msg) => {
- if (attrecall) { // Check if attrecall function exists
+ if (attendances.some((item) => item.employeeId == msg.employeeId)) {
attrecall();
}
},
- [attrecall] // Dependency should be attrecall, not `selectedProject` or `attendance` here
+ [selectedProject, attendance]
);
-
useEffect(() => {
eventBus.on("attendance", handler);
return () => eventBus.off("attendance", handler);
@@ -97,14 +100,13 @@ const Attendance = ({ getRole, handleModalData, attendance: filteredAndSearchedA
role="switch"
id="inactiveEmployeesCheckbox"
disabled={isFetching}
- checked={showOnlyCheckout} // Use prop for checked state
- onChange={(e) => setshowOnlyCheckout(e.target.checked)} // Use prop for onChange
+ checked={ShowPending}
+ onChange={(e) => setShowPending(e.target.checked)}
/>
Show Pending
- {/* Use `filteredAndSearchedAttendanceFromParent` for the initial check of data presence */}
- {Array.isArray(filteredAndSearchedAttendanceFromParent) && filteredAndSearchedAttendanceFromParent.length > 0 ? (
+ {Array.isArray(attendance) && attendance.length > 0 ? (
<>
@@ -122,7 +124,7 @@ const Attendance = ({ getRole, handleModalData, attendance: filteredAndSearchedA
- {currentItems && currentItems.length > 0 ? ( // Check currentItems length before mapping
+ {currentItems &&
currentItems
.sort((a, b) => {
const checkInA = a?.checkInTime
@@ -179,22 +181,18 @@ const Attendance = ({ getRole, handleModalData, attendance: filteredAndSearchedA
/>
- ))
- ) : (
-
-
- No matching records found.
-
-
+ ))}
+ {!attendance && (
+ No employees assigned to the project!
)}
- {!attLoading && finalFilteredDataForPagination.length > ITEMS_PER_PAGE && ( // Use the data before pagination for total count check
+ {!loading && filteredData.length > 20 && (
@@ -240,16 +238,14 @@ const Attendance = ({ getRole, handleModalData, attendance: filteredAndSearchedA
Loading...
) : (
- {/* Check the actual prop passed for initial data presence */}
- {Array.isArray(filteredAndSearchedAttendanceFromParent) && filteredAndSearchedAttendanceFromParent.length === 0
- ? ""
- : "Attendance data unavailable."}
+ {Array.isArray(attendance)
+ ? "No employees assigned to the project"
+ : "Attendance data unavailable"}
)}
- {/* This condition should check `currentItems` or `finalFilteredDataForPagination` */}
- {currentItems?.length === 0 && finalFilteredDataForPagination.length > 0 && showOnlyCheckout && (
- No Pending Record Available for your search!
+ {currentItems?.length == 0 && attendance.length > 0 && (
+ No Pending Record Available !
)}
>
diff --git a/src/components/Activities/AttendcesLogs.jsx b/src/components/Activities/AttendcesLogs.jsx
index c410ee01..0a28ffd3 100644
--- a/src/components/Activities/AttendcesLogs.jsx
+++ b/src/components/Activities/AttendcesLogs.jsx
@@ -4,31 +4,24 @@ 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 } from "../../slices/apiSlice/attedanceLogsSlice";
import DateRangePicker from "../common/DateRangePicker";
+import { clearCacheKey, getCachedData } from "../../slices/apiDataManager";
import eventBus from "../../services/eventBus";
+import AttendanceRepository from "../../repositories/AttendanceRepository";
+import { useAttendancesLogs } from "../../hooks/useAttendance";
+import { queryClient } from "../../layouts/AuthLayout";
const usePagination = (data, itemsPerPage) => {
const [currentPage, setCurrentPage] = useState(1);
- const totalItems = Array.isArray(data) ? data.length : 0;
- const maxPage = Math.ceil(totalItems / itemsPerPage);
-
+ const maxPage = Math.ceil(data.length / itemsPerPage);
const currentItems = useMemo(() => {
- if (!Array.isArray(data) || data.length === 0) {
- return [];
- }
const startIndex = (currentPage - 1) * itemsPerPage;
const endIndex = startIndex + itemsPerPage;
return data.slice(startIndex, endIndex);
}, [data, currentPage, itemsPerPage]);
- const paginate = useCallback((pageNumber) => {
- if (pageNumber > 0 && pageNumber <= maxPage) {
- setCurrentPage(pageNumber);
- }
- }, [maxPage]);
-
- // Ensure resetPage is returned by the hook
+ const paginate = useCallback((pageNumber) => setCurrentPage(pageNumber), []);
const resetPage = useCallback(() => setCurrentPage(1), []);
return {
@@ -42,91 +35,60 @@ const usePagination = (data, itemsPerPage) => {
const AttendanceLog = ({
handleModalData,
- projectId,
- setshowOnlyCheckout,
- showOnlyCheckout,
- searchQuery, // Prop for search query
}) => {
+ const selectedProject = useSelector(
+ (store) => store.localVariables.projectId
+ );
const [dateRange, setDateRange] = useState({ startDate: "", endDate: "" });
const dispatch = useDispatch();
- const { data, loading, error } = useSelector((store) => store.attendanceLogs);
+ const [loading, setLoading] = useState(false);
+ const [showPending,setShowPending] = useState(false)
+
const [isRefreshing, setIsRefreshing] = useState(false);
+ const [processedData, setProcessedData] = useState([]);
- const today = useMemo(() => {
- const d = new Date();
- d.setHours(0, 0, 0, 0);
- return d;
- }, []);
+ const today = new Date();
+ today.setHours(0, 0, 0, 0);
- const yesterday = useMemo(() => {
- const d = new Date();
- d.setDate(d.getDate() - 1);
- return d;
- }, []);
+ const yesterday = new Date();
+ yesterday.setDate(yesterday.getDate() - 1);
- const isSameDay = useCallback((dateStr) => {
+ const isSameDay = (dateStr) => {
if (!dateStr) return false;
const d = new Date(dateStr);
d.setHours(0, 0, 0, 0);
return d.getTime() === today.getTime();
- }, [today]);
+ };
- const isBeforeToday = useCallback((dateStr) => {
+ const isBeforeToday = (dateStr) => {
if (!dateStr) return false;
const d = new Date(dateStr);
d.setHours(0, 0, 0, 0);
return d.getTime() < today.getTime();
- }, [today]);
+ };
- const sortByName = useCallback((a, b) => {
- const nameA = `${a.firstName || ""} ${a.lastName || ""}`.toLowerCase();
- const nameB = `${b.firstName || ""} ${b.lastName || ""}`.toLowerCase();
- return nameA.localeCompare(nameB);
- }, []);
+ const sortByName = (a, b) => {
+ const nameA = a.firstName.toLowerCase() + a.lastName.toLowerCase();
+ const nameB = b.firstName.toLowerCase() + b.lastName.toLowerCase();
+ return nameA?.localeCompare(nameB);
+ };
- useEffect(() => {
- const { startDate, endDate } = dateRange;
- dispatch(
- fetchAttendanceData({
- projectId,
- fromDate: startDate,
- toDate: endDate,
- })
- );
- setIsRefreshing(false);
- }, [dateRange, projectId, dispatch, isRefreshing]);
-
- const processedData = useMemo(() => {
- let filteredData = showOnlyCheckout
+ const {
+ data = [],
+ isLoading,
+ error,
+ refetch,
+ isFetching,
+ } = useAttendancesLogs(
+ selectedProject,
+ dateRange.startDate,
+ dateRange.endDate
+ );
+ const filtering = (data) => {
+ const filteredData = showPending
? data.filter((item) => item.checkOutTime === null)
: data;
- // Apply search query filter
- if (searchQuery) {
- const lowerCaseSearchQuery = searchQuery.toLowerCase().trim(); // Trim whitespace
-
- filteredData = filteredData.filter((att) => {
- // Option 1: Combine firstName, middleName, lastName
- const fullName = [att.firstName, att.middleName, att.lastName]
- .filter(Boolean) // This removes null, undefined, or empty string parts
- .join(" ")
- .toLowerCase();
-
- // Option 2: Check `employeeName` if it exists and is reliable
- const employeeName = att.employeeName?.toLowerCase() || "";
-
- // Option 3: Check `employeeId`
- const employeeId = att.employeeId?.toLowerCase() || "";
-
- // Check if the search query is included in any of the relevant fields
- return (
- fullName.includes(lowerCaseSearchQuery) ||
- employeeName.includes(lowerCaseSearchQuery) ||
- employeeId.includes(lowerCaseSearchQuery)
- );
- });
- }
-
const group1 = filteredData
.filter((d) => d.activity === 1 && isSameDay(d.checkInTime))
.sort(sortByName);
@@ -165,46 +127,53 @@ const AttendanceLog = ({
return acc;
}, {});
- // Sort dates in descending order
const sortedDates = Object.keys(groupedByDate).sort(
(a, b) => new Date(b) - new Date(a)
);
- // Create the final sorted array
- return sortedDates.flatMap((date) => groupedByDate[date]);
- }, [data, showOnlyCheckout, searchQuery, isSameDay, isBeforeToday, sortByName]);
+ const finalData = sortedDates.flatMap((date) => groupedByDate[date]);
+ setProcessedData(finalData);
+ };
+
+ useEffect(() => {
+ filtering(data);
+ }, [data, showPending]);
const {
currentPage,
totalPages,
currentItems: paginatedAttendances,
paginate,
- resetPage, // Destructure resetPage here
+ resetPage,
} = usePagination(processedData, 20);
- // Effect to reset pagination when search query changes
useEffect(() => {
resetPage();
- }, [searchQuery, resetPage]); // Add resetPage to dependencies
+ }, [processedData, resetPage]);
const handler = useCallback(
(msg) => {
const { startDate, endDate } = dateRange;
const checkIn = msg.response.checkInTime.substring(0, 10);
if (
- projectId === msg.projectId &&
+ selectedProject === msg.projectId &&
startDate <= checkIn &&
checkIn <= endDate
) {
- const updatedAttendance = data.map((item) =>
- item.id === msg.response.id
- ? { ...item, ...msg.response }
- : item
+ queryClient.setQueriesData(["attendanceLogs"],(oldData)=>{
+ if(!oldData) {
+ queryClient.invalidateQueries({queryKey:["attendanceLogs"]})
+ }
+ return oldData.map((record) =>
+ record.id === msg.response.id ? { ...record, ...msg.response } : record
);
- dispatch(setAttendanceData(updatedAttendance)); // Update Redux store
+ })
+
+ filtering(updatedAttendance);
+ resetPage();
}
},
- [projectId, dateRange, data, dispatch]
+ [selectedProject, dateRange, data, filtering, resetPage]
);
useEffect(() => {
@@ -215,15 +184,19 @@ const AttendanceLog = ({
const employeeHandler = useCallback(
(msg) => {
const { startDate, endDate } = dateRange;
- dispatch(
- fetchAttendanceData({
- projectId,
- fromDate: startDate,
- toDate: endDate,
- })
- );
+ if (data.some((item) => item.employeeId == msg.employeeId)) {
+ // dispatch(
+ // fetchAttendanceData({
+ // ,
+ // fromDate: startDate,
+ // toDate: endDate,
+ // })
+ // );
+
+ refetch()
+ }
},
- [projectId, dateRange, dispatch]
+ [selectedProject, dateRange, data]
);
useEffect(() => {
@@ -247,27 +220,28 @@ const AttendanceLog = ({
type="checkbox"
className="form-check-input"
role="switch"
+ disabled={isFetching}
id="inactiveEmployeesCheckbox"
- checked={showOnlyCheckout}
- onChange={(e) => setshowOnlyCheckout(e.target.checked)}
+ checked={showPending}
+ onChange={(e) => setShowPending(e.target.checked)}
/>
Show Pending
setIsRefreshing(true)}
+ onClick={() => refetch()}
/>
-
- {processedData && processedData.length > 0 ? (
+
+ {isLoading ? (
+
+ ) : data?.length > 0 ? (
@@ -286,96 +260,82 @@ const AttendanceLog = ({
- {(loading || isRefreshing) && (
-
- Loading...
-
- )}
- {!loading &&
- !isRefreshing &&
- paginatedAttendances.reduce((acc, attendance, index, arr) => {
- const currentDate = moment(
- attendance.checkInTime || attendance.checkOutTime
- ).format("YYYY-MM-DD");
- const previousAttendance = arr[index - 1];
- const previousDate = previousAttendance
- ? moment(
+ {paginatedAttendances.reduce((acc, attendance, index, arr) => {
+ const currentDate = moment(
+ attendance.checkInTime || attendance.checkOutTime
+ ).format("YYYY-MM-DD");
+ const previousAttendance = arr[index - 1];
+ const previousDate = previousAttendance
+ ? moment(
previousAttendance.checkInTime ||
- previousAttendance.checkOutTime
+ previousAttendance.checkOutTime
).format("YYYY-MM-DD")
- : null;
+ : null;
- if (!previousDate || currentDate !== previousDate) {
- acc.push(
-
-
-
- {moment(currentDate).format("DD-MM-YYYY")}
-
-
-
- );
- }
+ if (!previousDate || currentDate !== previousDate) {
acc.push(
-
-
-
-
-
- {moment(
- attendance.checkInTime || attendance.checkOutTime
- ).format("DD-MMM-YYYY")}
-
- {convertShortTime(attendance.checkInTime)}
-
- {attendance.checkOutTime
- ? convertShortTime(attendance.checkOutTime)
- : "--"}
-
-
-
+
+
+
+ {moment(currentDate).format("DD-MM-YYYY")}
+
);
- return acc;
- }, [])}
+ }
+ acc.push(
+
+
+
+
+
+ {moment(
+ attendance.checkInTime || attendance.checkOutTime
+ ).format("DD-MMM-YYYY")}
+
+ {convertShortTime(attendance.checkInTime)}
+
+ {attendance.checkOutTime
+ ? convertShortTime(attendance.checkOutTime)
+ : "--"}
+
+
+
+
+
+ );
+ return acc;
+ }, [])}
) : (
- !loading &&
- !isRefreshing && (
-
- No employee logs.
-
- )
+
No Record Available !
)}
- {!loading && !isRefreshing && processedData.length > 20 && (
+ {paginatedAttendances?.length == 0 && data?.length > 0 && (
+
No Pending Record Available !
+ )}
+ {processedData.length > 10 && (
@@ -390,8 +350,9 @@ const AttendanceLog = ({
(pageNumber) => (
{
- return z
- .object({
- markTime: z.string().nonempty({ message: "Time is required" }),
- description: z
- .string()
- .max(200, "Description should be less than 200 characters")
- .optional(),
- })
- .refine((data) => {
- if (modeldata?.checkInTime && !modeldata?.checkOutTime) {
- const checkIn = new Date(modeldata.checkInTime);
- const [time, modifier] = data.markTime.split(" ");
- const [hourStr, minuteStr] = time.split(":");
- let hour = parseInt(hourStr, 10);
- const minute = parseInt(minuteStr, 10);
-
- if (modifier === "PM" && hour !== 12) hour += 12;
- if (modifier === "AM" && hour === 12) hour = 0;
-
- const checkOut = new Date(checkIn);
- checkOut.setHours(hour, minute, 0, 0);
-
- return checkOut > checkIn;
- }
- return true;
- }, {
- message: "Checkout time must be later than check-in time",
- path: ["markTime"],
- });
-};
-
-
-const CheckCheckOutmodel = ({ modeldata, closeModal, handleSubmitForm, }) => {
-
- const projectId = useSelector((store) => store.localVariables.projectId)
- const {mutate:MarkAttendance} = useMarkAttendance()
+const CheckCheckOutmodel = ({ modeldata, closeModal, handleSubmitForm }) => {
+ const projectId = useSelector((store) => store.localVariables.projectId);
+ const { mutate: MarkAttendance } = useMarkAttendance();
const [isLoading, setIsLoading] = useState(false);
const coords = usePositionTracker();
- const dispatch = useDispatch()
- const today = new Date().toISOString().split('T')[0];
+ const dispatch = useDispatch();
+ const today = new Date().toISOString().split("T")[0];
- const formatDate = (dateString) => {
+ const formatDate = (dateString) => {
if (!dateString) {
- return '';
+ return "";
}
- const [year, month, day] = dateString.split('-');
+ const [year, month, day] = dateString.split("-");
return `${day}-${month}-${year}`;
};
- // const {
- // register,
- // handleSubmit,
- // formState: { errors },
- // reset,
- // setValue,
- // } = useForm({
- // resolver: zodResolver(schema),
- // mode: "onChange"
- // });
-
const {
- register,
- handleSubmit,
- formState: { errors },
- reset,
- setValue,
-} = useForm({
- resolver: zodResolver(createSchema(modeldata)),
- mode: "onChange",
-});
-
+ register,
+ handleSubmit,
+ formState: { errors },
+ reset,
+ setValue,
+ } = useForm({
+ resolver: zodResolver(schema),
+ mode: "onChange",
+ });
const onSubmit = (data) => {
- let record = { ...data, date: new Date().toLocaleDateString(), latitude: coords.latitude, longitude: coords.longitude, employeeId: modeldata.employeeId, action: modeldata.action, id: modeldata?.id || null }
- if (modeldata.forWhichTab === 1) {
- handleSubmitForm(record)
- } else {
-
- dispatch(markAttendance(record))
- .unwrap()
- .then((data) => {
-
- // showToast("Attendance Marked Successfully", "success");
- // })
- // .catch((error) => {
-
- // showToast(error, "error");
-
- });
- }
-
- closeModal()
+ let record = {
+ ...data,
+ date: new Date().toLocaleDateString(),
+ latitude: coords.latitude,
+ longitude: coords.longitude,
+ employeeId: modeldata.employeeId,
+ action: modeldata.action,
+ id: modeldata?.id || null,
+ };
+ const payload = {
+ Id: modeldata?.id || null,
+ comment: data.description,
+ employeeID: modeldata.employeeId,
+ projectId: projectId,
+ date: new Date().toISOString(),
+ markTime: data.markTime,
+ latitude: coords.latitude.toString(),
+ longitude: coords.longitude.toString(),
+ action: modeldata.action,
+ image: null,
+ };
+ MarkAttendance({ payload, forWhichTab: modeldata.forWhichTab });
+ closeModal();
};
return (
-
-
-
- )
-}
-
+ );
+};
export default CheckCheckOutmodel;
-
const schemaReg = z.object({
- description: z.string().min(1, { message: "please give reason!" })
+ description: z.string().min(1, { message: "please give reason!" }),
});
-
-
export const Regularization = ({ modeldata, closeModal, handleSubmitForm }) => {
const [isLoading, setIsLoading] = useState(false);
const coords = usePositionTracker();
@@ -210,21 +167,22 @@ export const Regularization = ({ modeldata, closeModal, handleSubmitForm }) => {
const getCurrentDate = () => {
const today = new Date();
- return today.toLocaleDateString('en-CA');
+ return today.toLocaleDateString("en-CA");
};
-
const onSubmit = (data) => {
- let record = { ...data, date: new Date().toLocaleDateString(), latitude: coords.latitude, longitude: coords.longitude, }
- handleSubmitForm(record)
- closeModal()
+ let record = {
+ ...data,
+ date: new Date().toLocaleDateString(),
+ latitude: coords.latitude,
+ longitude: coords.longitude,
+ };
+ handleSubmitForm(record);
+ closeModal();
};
return (
-
-
-
- )
-}
\ No newline at end of file
+ );
+};
diff --git a/src/components/Activities/Regularization.jsx b/src/components/Activities/Regularization.jsx
index 6c0edfac..839553de 100644
--- a/src/components/Activities/Regularization.jsx
+++ b/src/components/Activities/Regularization.jsx
@@ -7,37 +7,56 @@ import { useRegularizationRequests } from "../../hooks/useAttendance";
import moment from "moment";
import usePagination from "../../hooks/usePagination";
import eventBus from "../../services/eventBus";
-import { cacheData } from "../../slices/apiDataManager";
+import { cacheData, clearCacheKey } from "../../slices/apiDataManager";
+import { useQueryClient } from "@tanstack/react-query";
-const Regularization = ({ handleRequest, searchQuery }) => {
- const selectedProject = useSelector((store) => store.localVariables.projectId);
- const [regularizesList, setRegularizedList] = useState([]);
- const { regularizes, loading, refetch } = useRegularizationRequests(selectedProject);
+const Regularization = ({ handleRequest }) => {
+ const queryClient = useQueryClient();
+ var selectedProject = useSelector((store) => store.localVariables.projectId);
+ const [regularizesList, setregularizedList] = useState([]);
+ const { regularizes, loading, error, refetch } =
+ useRegularizationRequests(selectedProject);
useEffect(() => {
- setRegularizedList(regularizes);
+ setregularizedList(regularizes);
}, [regularizes]);
const sortByName = (a, b) => {
- const nameA = (a.firstName + a.lastName).toLowerCase();
- const nameB = (b.firstName + b.lastName).toLowerCase();
- return nameA.localeCompare(nameB);
+ const nameA = a.firstName.toLowerCase() + a.lastName.toLowerCase();
+ const nameB = b.firstName.toLowerCase() + b.lastName.toLowerCase();
+ return nameA?.localeCompare(nameB);
};
const handler = useCallback(
(msg) => {
if (selectedProject == msg.projectId) {
- const updatedAttendance = regularizes?.filter(item => item.id !== msg.response.id);
- cacheData("regularizedList", {
- data: updatedAttendance,
- projectId: selectedProject,
- });
- refetch();
+
+
+ queryClient.setQueryData(
+ ["regularizedList", selectedProject],
+ (oldData) => {
+ if (!oldData) {
+ queryClient.invalidateQueries({ queryKey: ["regularizedList"] });
+ }
+ return oldData.filter((record) => record.id !== msg.response.id);
+ }
+ ),
+ queryClient.invalidateQueries({ queryKey: ["attendanceLogs"] });
}
},
[selectedProject, regularizes]
);
-
+
+ const filteredData = [...regularizesList]?.sort(sortByName);
+
+ const { currentPage, totalPages, currentItems, paginate } = usePagination(
+ filteredData,
+ 20
+ );
+ useEffect(() => {
+ eventBus.on("regularization", handler);
+ return () => eventBus.off("regularization", handler);
+ }, [handler]);
const employeeHandler = useCallback(
(msg) => {
@@ -48,57 +67,41 @@ const Regularization = ({ handleRequest, searchQuery }) => {
[regularizes]
);
- useEffect(() => {
- eventBus.on("regularization", handler);
- return () => eventBus.off("regularization", handler);
- }, [handler]);
-
useEffect(() => {
eventBus.on("employee", employeeHandler);
return () => eventBus.off("employee", employeeHandler);
}, [employeeHandler]);
- // ✅ Search filter logic added here
- const filteredData = [...regularizesList]
- ?.filter((item) => {
- if (!searchQuery) return true;
- const lowerSearch = searchQuery.toLowerCase();
- const fullName = `${item.firstName || ""} ${item.lastName || ""}`.toLowerCase();
-
- return (
- item.firstName?.toLowerCase().includes(lowerSearch) ||
- item.lastName?.toLowerCase().includes(lowerSearch) ||
- fullName.includes(lowerSearch) ||
- item.employeeId?.toLowerCase().includes(lowerSearch)
- );
- })
- .sort(sortByName);
-
- const { currentPage, totalPages, currentItems, paginate } = usePagination(filteredData, 20);
-
return (
-
-
-
- Name
- Date
-
- Check-In
-
-
- Check-Out
-
- Action
-
-
-
- {!loading && currentItems?.length > 0 ? (
- currentItems.map((att, index) => (
+ {loading ? (
+
+ ) : currentItems?.length > 0 ? (
+
+
+
+ Name
+ Date
+
+ Check-In
+
+
+ Check-Out
+
+ Action
+
+
+
+ {currentItems?.map((att, index) => (
- ))
- ) : (
-
-
- {loading ? "Loading..." : "No Record Found"}
-
-
- )}
-
-
-
+ ))}
+
+
+ ) : (
+
+ {" "}
+ No Requests Found !
+
+ )}
{!loading && totalPages > 1 && (
@@ -154,18 +148,25 @@ const Regularization = ({ handleRequest, searchQuery }) => {
{[...Array(totalPages)].map((_, index) => (
- paginate(index + 1)}>
+ paginate(index + 1)}
+ >
{index + 1}
))}
paginate(currentPage + 1)}
>
»
diff --git a/src/pages/Activities/AttendancePage.jsx b/src/pages/Activities/AttendancePage.jsx
index b3224bde..65917c3f 100644
--- a/src/pages/Activities/AttendancePage.jsx
+++ b/src/pages/Activities/AttendancePage.jsx
@@ -8,35 +8,32 @@ import {
import Breadcrumb from "../../components/common/Breadcrumb";
import AttendanceLog from "../../components/Activities/AttendcesLogs";
import Attendance from "../../components/Activities/Attendance";
-import AttendanceModel from "../../components/Activities/AttendanceModel";
-import showToast from "../../services/toastService";
import Regularization from "../../components/Activities/Regularization";
import { useAttendance } from "../../hooks/useAttendance";
import { useDispatch, useSelector } from "react-redux";
import { setProjectId } from "../../slices/localVariablesSlice";
-import { markCurrentAttendance } from "../../slices/apiSlice/attendanceAllSlice";
+import { hasUserPermission } from "../../utils/authUtils";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { REGULARIZE_ATTENDANCE } from "../../utils/constants";
import eventBus from "../../services/eventBus";
-import AttendanceRepository from "../../repositories/AttendanceRepository";
import { useProjectName } from "../../hooks/useProjects";
+import GlobalModel from "../../components/common/GlobalModel";
+import CheckCheckOutmodel from "../../components/Activities/CheckCheckOutForm";
+import AttendLogs from "../../components/Activities/AttendLogs";
+import { useQueryClient } from "@tanstack/react-query";
const AttendancePage = () => {
const [activeTab, setActiveTab] = useState("all");
- const [showPending, setShowPending] = useState(false);
- const [searchQuery, setSearchQuery] = useState("");
+ const [ShowPending, setShowPending] = useState(false);
+ const queryClient = useQueryClient();
const loginUser = getCachedProfileData();
- const selectedProject = useSelector((store) => store.localVariables.projectId);
+ var selectedProject = useSelector((store) => store.localVariables.projectId);
const dispatch = useDispatch();
- const {
- attendance,
- loading: attLoading,
- recall: attrecall,
- } = useAttendance(selectedProject);
+
const [attendances, setAttendances] = useState();
const [empRoles, setEmpRoles] = useState(null);
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
- const [modelConfig, setModelConfig] = useState(null); // Initialize as null
+ const [modelConfig, setModelConfig] = useState();
const DoRegularized = useHasUserPermission(REGULARIZE_ATTENDANCE);
const { projectNames, loading: projectLoading, fetchData } = useProjectName();
@@ -46,172 +43,67 @@ const AttendancePage = () => {
date: new Date().toLocaleDateString(),
});
- const handler = useCallback(
- (msg) => {
- if (selectedProject === msg.projectId) {
- const updatedAttendance = attendances
- ? attendances.map((item) =>
- item.employeeId === msg.response.employeeId
- ? { ...item, ...msg.response }
- : item
- )
- : [msg.response];
-
- cacheData("Attendance", {
- data: updatedAttendance,
- projectId: selectedProject,
- });
- setAttendances(updatedAttendance);
- }
- },
- [selectedProject, attendances]
- );
-
- const employeeHandler = useCallback(
- (msg) => {
- // This logic seems fine for refetching if an employee ID exists in current attendances
- if (attendances?.some((item) => item.employeeId === msg.employeeId)) {
- AttendanceRepository.getAttendance(selectedProject)
- .then((response) => {
- cacheData("Attendance", { data: response.data, selectedProject });
- setAttendances(response.data);
- })
- .catch((error) => {
- console.error(error);
- });
- }
- },
- [selectedProject, attendances]
- );
+ useEffect(() => {
+ if (selectedProject == null) {
+ dispatch(setProjectId(projectNames[0]?.id));
+ }
+ }, []);
const getRole = (roleId) => {
if (!empRoles) return "Unassigned";
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";
};
- // Simplified and moved modal opening logic
- const handleModalData = useCallback((employee) => {
- setModelConfig(employee);
- setIsCreateModalOpen(true); // Open the modal directly when data is set
- }, []);
-
- const closeModal = useCallback(() => {
- setModelConfig(null);
- setIsCreateModalOpen(false);
- // Directly manipulating the DOM is generally not recommended in React.
- // React handles modal visibility via state. If you must, ensure it's
- // for external libraries or for very specific, controlled reasons.
- // For a typical Bootstrap modal, just setting `isCreateModalOpen` to false
- // should be enough if the modal component itself handles the Bootstrap classes.
- const modalElement = document.getElementById("check-Out-modal");
- if (modalElement) {
- modalElement.classList.remove("show");
- modalElement.style.display = "none";
- document.body.classList.remove("modal-open");
- const modalBackdrop = document.querySelector(".modal-backdrop");
- if (modalBackdrop) {
- modalBackdrop.remove();
- }
- }
- }, []);
-
- const handleSubmit = useCallback((formData) => {
- dispatch(markCurrentAttendance(formData))
- .then((action) => {
- if (action.payload && action.payload.employeeId) {
- const updatedAttendance = attendances
- ? attendances.map((item) =>
- item.employeeId === action.payload.employeeId
- ? { ...item, ...action.payload }
- : item
- )
- : [action.payload];
-
- cacheData("Attendance", {
- data: updatedAttendance,
- projectId: selectedProject,
- });
- setAttendances(updatedAttendance);
- showToast("Attendance Marked Successfully", "success");
- } else {
- showToast("Failed to mark attendance: Invalid response", "error");
- }
- })
- .catch((error) => {
- showToast(error.message, "error");
- });
- }, [dispatch, attendances, selectedProject]);
-
-
- const handleToggle = (event) => {
- setShowPending(event.target.checked);
+ const openModel = () => {
+ setIsCreateModalOpen(true);
};
+ const handleModalData = (employee) => {
+ setModelConfig(employee);
+ };
+
+ const closeModal = () => {
+ setModelConfig(null);
+ setIsCreateModalOpen(false);
+ };
+
+ const handleToggle = (event) => {
+ setShowOnlyCheckout(event.target.checked);
+ };
+
+
useEffect(() => {
- if (selectedProject === null && projectNames.length > 0) {
- dispatch(setProjectId(projectNames[0]?.id));
+ if (modelConfig !== null) {
+ openModel();
}
- }, [selectedProject, projectNames, dispatch]);
-
- useEffect(() => {
- setAttendances(attendance);
- }, [attendance]);
-
- const filteredAndSearchedTodayAttendance = useCallback(() => {
- let currentData = attendances;
-
- if (showPending) {
- currentData = currentData?.filter(
- (att) => att?.checkInTime !== null && att?.checkOutTime === null
- );
- }
-
- if (searchQuery) {
- const lowerCaseSearchQuery = searchQuery.toLowerCase();
- currentData = currentData?.filter((att) => {
- const fullName = [att.firstName, att.middleName, att.lastName]
- .filter(Boolean)
- .join(" ")
- .toLowerCase();
-
- return (
- att.employeeName?.toLowerCase().includes(lowerCaseSearchQuery) ||
- att.employeeId?.toLowerCase().includes(lowerCaseSearchQuery) ||
- fullName.includes(lowerCaseSearchQuery)
- );
- });
- }
- return currentData;
- }, [attendances, showPending, searchQuery]);
-
- useEffect(() => {
- eventBus.on("attendance", handler);
- return () => eventBus.off("attendance", handler);
- }, [handler]);
-
- useEffect(() => {
- eventBus.on("employee", employeeHandler);
- return () => eventBus.off("employee", employeeHandler);
- }, [employeeHandler]);
+ }, [modelConfig, isCreateModalOpen]);
return (
<>
{isCreateModalOpen && modelConfig && (
-
+ {(modelConfig?.action === 0 ||
+ modelConfig?.action === 1 ||
+ modelConfig?.action === 2) && (
+
+ )}
+ {/* For view logs */}
+ {modelConfig?.action === 6 && (
+
+ )}
+ {modelConfig?.action === 7 && (
+
+ )}
+
)}
@@ -221,106 +113,69 @@ const AttendancePage = () => {
{ label: "Attendance", link: null },
]}
>
-
-
-
-
- setActiveTab("all")}
- data-bs-toggle="tab"
- data-bs-target="#navs-top-home"
- >
- Today's
-
-
-
- setActiveTab("logs")}
- data-bs-toggle="tab"
- data-bs-target="#navs-top-profile"
- >
- Logs
-
-
-
- setActiveTab("regularization")}
- data-bs-toggle="tab"
- data-bs-target="#navs-top-messages"
- >
- Regularization
-
-
-
-
- setSearchQuery(e.target.value)}
- />
-
+
+
+
+ setActiveTab("all")}
+ data-bs-toggle="tab"
+ data-bs-target="#navs-top-home"
+ >
+ Today's
+
+
+
+ setActiveTab("logs")}
+ data-bs-toggle="tab"
+ data-bs-target="#navs-top-profile"
+ >
+ Logs
+
+
+
+ setActiveTab("regularization")}
+ data-bs-toggle="tab"
+ data-bs-target="#navs-top-messages"
+ >
+ Regularization
+
+
-
+
{activeTab === "all" && (
- <>
- {!attLoading && (
- )}
- {!attLoading && filteredAndSearchedTodayAttendance()?.length === 0 && (
-
- {" "}
- {showPending
- ? "No Pending Available"
- : "No Employee assigned yet."}{" "}
-
- )}
- >
)}
-
{activeTab === "logs" && (
)}
-
{activeTab === "regularization" && DoRegularized && (
-
+
)}
-
- {!attLoading && !attendances &&
Not Found }
@@ -328,4 +183,4 @@ const AttendancePage = () => {
);
};
-export default AttendancePage;
\ No newline at end of file
+export default AttendancePage;