Compare commits

..

No commits in common. "main" and "Organization_Management" have entirely different histories.

83 changed files with 1816 additions and 2054 deletions

View File

@ -9,274 +9,4 @@
} }
.table_header_border { .table_header_border {
border-bottom:2px solid var(--bs-table-border-color) ; border-bottom:2px solid var(--bs-table-border-color) ;
} }
.text-xxs { font-size: 0.55rem; } /* 8px */
.text-xs { font-size: 0.75rem; } /* 12px */
.text-sm { font-size: 0.875rem; } /* 14px */
.text-base { font-size: 1rem; } /* 16px */
.text-lg { font-size: 1.125rem; } /* 18px */
.text-xl { font-size: 1.25rem; } /* 20px */
.text-2xl { font-size: 1.5rem; } /* 24px */
.text-3xl { font-size: 1.875rem; } /* 30px */
.text-4xl { font-size: 2.25rem; } /* 36px */
.text-5xl { font-size: 3rem; } /* 48px */
.text-6xl { font-size: 3.75rem; } /* 60px */
.text-7xl { font-size: 4.5rem; } /* 72px */
.text-8xl { font-size: 6rem; } /* 96px */
.text-9xl { font-size: 8rem; } /* 128px */
/* */
.w-0 { width: 0px; }
.w-px { width: 1px; }
.w-1 { width: 0.25rem; } /* 4px */
.w-2 { width: 0.5rem; } /* 8px */
.w-3 { width: 0.75rem; } /* 12px */
.w-4 { width: 1rem; } /* 16px */
.w-5 { width: 1.25rem; } /* 20px */
.w-6 { width: 1.5rem; } /* 24px */
.w-8 { width: 2rem; } /* 32px */
.w-10 { width: 2.5rem; } /* 40px */
.w-12 { width: 3rem; } /* 48px */
.w-16 { width: 4rem; } /* 64px */
.w-20 { width: 5rem; } /* 80px */
.w-24 { width: 6rem; } /* 96px */
.w-32 { width: 8rem; } /* 128px */
.w-40 { width: 10rem; } /* 160px */
.w-48 { width: 12rem; } /* 192px */
.w-56 { width: 14rem; } /* 224px */
.w-64 { width: 16rem; } /* 256px */
.w-auto { width: auto; }
.w-full { width: 100%; }
.w-screen{ width: 100vw; }
.w-min { width: min-content; }
.w-max { width: max-content; }
.h-0 { height: 0px; }
.h-px { height: 1px; }
.h-1 { height: 0.25rem; } /* 4px */
.h-2 { height: 0.5rem; } /* 8px */
.h-3 { height: 0.75rem; } /* 12px */
.h-4 { height: 1rem; } /* 16px */
.h-5 { height: 1.25rem; } /* 20px */
.h-6 { height: 1.5rem; } /* 24px */
.h-8 { height: 2rem; } /* 32px */
.h-10 { height: 2.5rem; } /* 40px */
.h-12 { height: 3rem; } /* 48px */
.h-16 { height: 4rem; } /* 64px */
.h-20 { height: 5rem; } /* 80px */
.h-24 { height: 6rem; } /* 96px */
.h-32 { height: 8rem; } /* 128px */
.h-40 { height: 10rem; } /* 160px */
.h-48 { height: 12rem; } /* 192px */
.h-56 { height: 14rem; } /* 224px */
.h-64 { height: 16rem; } /* 256px */
.h-auto { height: auto; }
.h-full { height: 100%; }
.h-screen{ height: 100vh; }
.h-min { height: min-content; }
.h-max { height: max-content; }
/* ==========================
Base Font Sizes (mobile first)
========================== */
.text-xxs { font-size: 0.55rem; } /* 8px */
.text-xs { font-size: 0.75rem; } /* 12px */
.text-sm { font-size: 0.875rem; } /* 14px */
.text-base{ font-size: 1rem; } /* 16px */
.text-lg { font-size: 1.125rem; } /* 18px */
.text-xl { font-size: 1.25rem; } /* 20px */
.text-2xl { font-size: 1.5rem; } /* 24px */
.text-3xl { font-size: 1.875rem; } /* 30px */
.text-4xl { font-size: 2.25rem; } /* 36px */
.text-5xl { font-size: 3rem; } /* 48px */
.text-6xl { font-size: 3.75rem; } /* 60px */
.text-7xl { font-size: 4.5rem; } /* 72px */
.text-8xl { font-size: 6rem; } /* 96px */
.text-9xl { font-size: 8rem; } /* 128px */
/* ==========================
Base Heights
========================== */
.h-0 { height: 0; }
.h-px { height: 1px; }
.h-1 { height: 0.25rem; } /* 4px */
.h-2 { height: 0.5rem; } /* 8px */
.h-3 { height: 0.75rem; } /* 12px */
.h-4 { height: 1rem; } /* 16px */
.h-5 { height: 1.25rem; } /* 20px */
.h-6 { height: 1.5rem; } /* 24px */
.h-8 { height: 2rem; } /* 32px */
.h-10 { height: 2.5rem; } /* 40px */
.h-12 { height: 3rem; } /* 48px */
.h-16 { height: 4rem; } /* 64px */
.h-20 { height: 5rem; } /* 80px */
.h-24 { height: 6rem; } /* 96px */
.h-32 { height: 8rem; } /* 128px */
.h-40 { height: 10rem; } /* 160px */
.h-48 { height: 12rem; } /* 192px */
.h-56 { height: 14rem; } /* 224px */
.h-64 { height: 16rem; } /* 256px */
.h-full { height: 100%; }
.h-screen{ height: 100vh; }
/* ==========================
Base Widths
========================== */
.w-0 { width: 0; }
.w-px { width: 1px; }
.w-1 { width: 0.25rem; }
.w-2 { width: 0.5rem; }
.w-3 { width: 0.75rem; }
.w-4 { width: 1rem; }
.w-5 { width: 1.25rem; }
.w-6 { width: 1.5rem; }
.w-8 { width: 2rem; }
.w-10 { width: 2.5rem; }
.w-12 { width: 3rem; }
.w-16 { width: 4rem; }
.w-20 { width: 5rem; }
.w-24 { width: 6rem; }
.w-32 { width: 8rem; }
.w-40 { width: 10rem; }
.w-48 { width: 12rem; }
.w-56 { width: 14rem; }
.w-64 { width: 16rem; }
.w-full { width: 100%; }
.w-screen{ width: 100vw; }
/* ==========================
Responsive Variants
========================== */
@media (min-width: 576px) { /* sm */
/* Font */
.text-xxs-sm { font-size: 0.55rem; }
.text-xs-sm { font-size: 0.75rem; }
.text-sm-sm { font-size: 0.875rem; }
.text-base-sm{ font-size: 1rem; }
.text-lg-sm { font-size: 1.125rem; }
.text-xl-sm { font-size: 1.25rem; }
.text-2xl-sm{ font-size: 1.5rem; }
/* Height */
.h-1-sm{ height: 0.25rem; }
.h-2-sm{ height: 0.5rem; }
.h-3-sm{ height: 0.75rem; }
.h-4-sm{ height: 1rem; }
.h-5-sm{ height: 1.25rem; }
.h-6-sm{ height: 1.5rem; }
.h-8-sm{ height: 2rem; }
.h-10-sm{ height: 2.5rem; }
/* Width */
.w-1-sm{ width: 0.25rem; }
.w-2-sm{ width: 0.5rem; }
.w-3-sm{ width: 0.75rem; }
.w-4-sm{ width: 1rem; }
.w-5-sm{ width: 1.25rem; }
.w-6-sm{ width: 1.5rem; }
.w-8-sm{ width: 2rem; }
.w-10-sm{ width: 2.5rem; }
}
@media (min-width: 768px) { /* md */
/* Font */
.text-xxs-md { font-size: 0.55rem; }
.text-xs-md { font-size: 0.75rem; }
.text-sm-md { font-size: 0.875rem; }
.text-base-md{ font-size: 1rem; }
.text-lg-md { font-size: 1.125rem; }
.text-xl-md { font-size: 1.25rem; }
.text-2xl-md{ font-size: 1.5rem; }
/* Height */
.h-1-md{ height: 0.25rem; }
.h-2-md{ height: 0.5rem; }
.h-3-md{ height: 0.75rem; }
.h-4-md{ height: 1rem; }
.h-5-md{ height: 1.25rem; }
.h-6-md{ height: 1.5rem; }
.h-8-md{ height: 2rem; }
.h-10-md{ height: 2.5rem; }
/* Width */
.w-1-md{ width: 0.25rem; }
.w-2-md{ width: 0.5rem; }
.w-3-md{ width: 0.75rem; }
.w-4-md{ width: 1rem; }
.w-5-md{ width: 1.25rem; }
.w-6-md{ width: 1.5rem; }
.w-8-md{ width: 2rem; }
.w-10-md{ width: 2.5rem; }
}
@media (min-width: 992px) { /* lg */
/* Font */
.text-xxs-lg { font-size: 0.55rem; }
.text-xs-lg { font-size: 0.75rem; }
.text-sm-lg { font-size: 0.875rem; }
.text-base-lg{ font-size: 1rem; }
.text-lg-lg { font-size: 1.125rem; }
.text-xl-lg { font-size: 1.25rem; }
.text-2xl-lg{ font-size: 1.5rem; }
/* Height */
.h-1-lg{ height: 0.25rem; }
.h-2-lg{ height: 0.5rem; }
.h-3-lg{ height: 0.75rem; }
.h-4-lg{ height: 1rem; }
.h-5-lg{ height: 1.25rem; }
.h-6-lg{ height: 1.5rem; }
.h-8-lg{ height: 2rem; }
.h-10-lg{ height: 2.5rem; }
/* Width */
.w-1-lg{ width: 0.25rem; }
.w-2-lg{ width: 0.5rem; }
.w-3-lg{ width: 0.75rem; }
.w-4-lg{ width: 1rem; }
.w-5-lg{ width: 1.25rem; }
.w-6-lg{ width: 1.5rem; }
.w-8-lg{ width: 2rem; }
.w-10-lg{ width: 2.5rem; }
}
@media (min-width: 1200px) { /* xl */
/* Font */
.text-xxs-xl { font-size: 0.55rem; }
.text-xs-xl { font-size: 0.75rem; }
.text-sm-xl { font-size: 0.875rem; }
.text-base-xl{ font-size: 1rem; }
.text-lg-xl { font-size: 1.125rem; }
.text-xl-xl { font-size: 1.25rem; }
.text-2xl-xl{ font-size: 1.5rem; }
/* Height */
.h-1-xl{ height: 0.25rem; }
.h-2-xl{ height: 0.5rem; }
.h-3-xl{ height: 0.75rem; }
.h-4-xl{ height: 1rem; }
.h-5-xl{ height: 1.25rem; }
.h-6-xl{ height: 1.5rem; }
.h-8-xl{ height: 2rem; }
.h-10-xl{ height: 2.5rem; }
/* Width */
.w-1-xl{ width: 0.25rem; }
.w-2-xl{ width: 0.5rem; }
.w-3-xl{ width: 0.75rem; }
.w-4-xl{ width: 1rem; }
.w-5-xl{ width: 1.25rem; }
.w-6-xl{ width: 1.5rem; }
.w-8-xl{ width: 2rem; }
.w-10-xl{ width: 2.5rem; }
}

View File

@ -1,20 +1,17 @@
import React, { useEffect } from "react"; import React, { useEffect } from "react";
import { useOrganizationModal } from "./hooks/useOrganization"; import { useOrganizationModal } from "./hooks/useOrganization";
import OrganizationModal from "./components/Organization/OrganizationModal"; import OrganizationModal from "./components/Organization/OrganizationModal";
import { useAuthModal, useModal } from "./hooks/useAuth"; import { useAuthModal } from "./hooks/useAuth";
import SwitchTenant from "./pages/authentication/SwitchTenant"; import SwitchTenant from "./pages/authentication/SwitchTenant";
import ChangePasswordPage from "./pages/authentication/ChangePassword";
const ModalProvider = () => { const ModalProvider = () => {
const { isOpen, onClose } = useOrganizationModal(); const { isOpen, onClose } = useOrganizationModal();
const { isOpen: isAuthOpen } = useAuthModal(); const { isOpen: isAuthOpen } = useAuthModal();
const {isOpen:isChangePass} = useModal("ChangePassword")
return ( return (
<> <>
{isOpen && <OrganizationModal />} {isOpen && <OrganizationModal />}
{isAuthOpen && <SwitchTenant />} {isAuthOpen && <SwitchTenant />}
{isChangePass && <ChangePasswordPage /> }
</> </>
); );
}; };

View File

@ -12,7 +12,7 @@ import { useQueryClient } from "@tanstack/react-query";
import eventBus from "../../services/eventBus"; import eventBus from "../../services/eventBus";
import { useSelectedProject } from "../../slices/apiDataManager"; import { useSelectedProject } from "../../slices/apiDataManager";
const Attendance = ({ getRole, handleModalData, searchTerm, projectId, organizationId, }) => { const Attendance = ({ getRole, handleModalData, searchTerm, projectId, organizationId, includeInactive, date }) => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const navigate = useNavigate(); const navigate = useNavigate();
@ -24,7 +24,7 @@ const Attendance = ({ getRole, handleModalData, searchTerm, projectId, organizat
loading: attLoading, loading: attLoading,
recall: attrecall, recall: attrecall,
isFetching isFetching
} = useAttendance(selectedProject, organizationId); } = useAttendance(selectedProject, organizationId, includeInactive, date);
const filteredAttendance = ShowPending const filteredAttendance = ShowPending
? attendance?.filter( ? attendance?.filter(
(att) => att?.checkInTime !== null && att?.checkOutTime === null (att) => att?.checkInTime !== null && att?.checkOutTime === null

View File

@ -5,11 +5,7 @@ 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 DateRangePicker from "../common/DateRangePicker"; import DateRangePicker from "../common/DateRangePicker";
import { import { clearCacheKey, getCachedData, useSelectedProject } from "../../slices/apiDataManager";
clearCacheKey,
getCachedData,
useSelectedProject,
} from "../../slices/apiDataManager";
import eventBus from "../../services/eventBus"; import eventBus from "../../services/eventBus";
import AttendanceRepository from "../../repositories/AttendanceRepository"; import AttendanceRepository from "../../repositories/AttendanceRepository";
import { useAttendancesLogs } from "../../hooks/useAttendance"; import { useAttendancesLogs } from "../../hooks/useAttendance";
@ -37,142 +33,223 @@ const usePagination = (data, itemsPerPage) => {
}; };
}; };
const AttendanceLog = ({ handleModalData, searchTerm, organizationId }) => { const AttendanceLog = ({ handleModalData, searchTerm ,organizationId}) => {
const selectedProject = useSelectedProject(); // const selectedProject = useSelector(
const [dateRange, setDateRange] = useState({ startDate: "", endDate: "" }); // (store) => store.localVariables.projectId
const dispatch = useDispatch(); // );
const [loading, setLoading] = useState(false); const selectedProject = useSelectedProject();
const [showPending, setShowPending] = useState(false); const [dateRange, setDateRange] = useState({ startDate: "", endDate: "" });
const [isRefreshing, setIsRefreshing] = useState(false); const dispatch = useDispatch();
const [loading, setLoading] = useState(false);
const [showPending, setShowPending] = useState(false)
const today = new Date(); const [isRefreshing, setIsRefreshing] = useState(false);
today.setHours(0, 0, 0, 0); const [processedData, setProcessedData] = useState([]);
const yesterday = new Date(); const today = new Date();
yesterday.setDate(yesterday.getDate() - 1); today.setHours(0, 0, 0, 0);
const isSameDay = (dateStr) => { const yesterday = new Date();
if (!dateStr) return false; yesterday.setDate(yesterday.getDate() - 1);
const d = new Date(dateStr);
d.setHours(0, 0, 0, 0);
return d.getTime() === today.getTime();
};
const isBeforeToday = (dateStr) => { const isSameDay = (dateStr) => {
if (!dateStr) return false; if (!dateStr) return false;
const d = new Date(dateStr); const d = new Date(dateStr);
d.setHours(0, 0, 0, 0); d.setHours(0, 0, 0, 0);
return d.getTime() < today.getTime(); return d.getTime() === today.getTime();
}; };
const sortByName = (a, b) => { const isBeforeToday = (dateStr) => {
const nameA = (a.firstName + a.lastName).toLowerCase(); if (!dateStr) return false;
const nameB = (b.firstName + b.lastName).toLowerCase(); const d = new Date(dateStr);
return nameA.localeCompare(nameB); d.setHours(0, 0, 0, 0);
}; return d.getTime() < today.getTime();
};
const { data = [], isLoading, error, refetch, isFetching } = useAttendancesLogs( const sortByName = (a, b) => {
selectedProject, const nameA = a.firstName.toLowerCase() + a.lastName.toLowerCase();
dateRange.startDate, const nameB = b.firstName.toLowerCase() + b.lastName.toLowerCase();
dateRange.endDate, return nameA?.localeCompare(nameB);
organizationId };
);
const processedData = useMemo(() => { const {
const filteredData = showPending data = [],
? data.filter((item) => item.checkOutTime === null) isLoading,
: data; error,
refetch,
const group1 = filteredData.filter((d) => d.activity === 1 && isSameDay(d.checkInTime)).sort(sortByName); isFetching,
const group2 = filteredData.filter((d) => d.activity === 4 && isSameDay(d.checkOutTime)).sort(sortByName); } = useAttendancesLogs(
const group3 = filteredData.filter((d) => d.activity === 1 && isBeforeToday(d.checkInTime)).sort(sortByName); selectedProject,
const group4 = filteredData.filter((d) => d.activity === 4 && isBeforeToday(d.checkOutTime)); dateRange.startDate,
const group5 = filteredData.filter((d) => d.activity === 2 && isBeforeToday(d.checkOutTime)).sort(sortByName); dateRange.endDate,
const group6 = filteredData.filter((d) => d.activity === 5).sort(sortByName); organizationId
const sortedList = [...group1, ...group2, ...group3, ...group4, ...group5, ...group6];
const groupedByDate = sortedList.reduce((acc, item) => {
const date = (item.checkInTime || item.checkOutTime)?.split("T")[0];
if (date) {
acc[date] = acc[date] || [];
acc[date].push(item);
}
return acc;
}, {});
const sortedDates = Object.keys(groupedByDate).sort((a, b) => new Date(b) - new Date(a));
return sortedDates.flatMap((date) => groupedByDate[date]);
}, [data, showPending]);
const filteredSearchData = useMemo(() => {
if (!searchTerm) return processedData;
const lowercased = searchTerm.toLowerCase();
return processedData.filter((item) =>
`${item.firstName} ${item.lastName}`.toLowerCase().includes(lowercased)
); );
}, [processedData, searchTerm]); const filtering = (data) => {
const filteredData = showPending
? data.filter((item) => item.checkOutTime === null)
: data;
const { const group1 = filteredData
currentPage, .filter((d) => d.activity === 1 && isSameDay(d.checkInTime))
totalPages, .sort(sortByName);
currentItems: paginatedAttendances, const group2 = filteredData
paginate, .filter((d) => d.activity === 4 && isSameDay(d.checkOutTime))
resetPage, .sort(sortByName);
} = usePagination(filteredSearchData, 20); const group3 = filteredData
.filter((d) => d.activity === 1 && isBeforeToday(d.checkInTime))
.sort(sortByName);
const group4 = filteredData.filter(
(d) => d.activity === 4 && isBeforeToday(d.checkOutTime)
);
const group5 = filteredData
.filter((d) => d.activity === 2 && isBeforeToday(d.checkOutTime))
.sort(sortByName);
const group6 = filteredData
.filter((d) => d.activity === 5)
.sort(sortByName);
useEffect(() => { const sortedList = [
resetPage(); ...group1,
}, [filteredSearchData]); ...group2,
...group3,
...group4,
...group5,
...group6,
];
const handler = useCallback( // Group by date
(msg) => { const groupedByDate = sortedList.reduce((acc, item) => {
const { startDate, endDate } = dateRange; const date = (item.checkInTime || item.checkOutTime)?.split("T")[0];
const checkIn = msg.response.checkInTime.substring(0, 10); if (date) {
acc[date] = acc[date] || [];
acc[date].push(item);
}
return acc;
}, {});
if (selectedProject === msg.projectId && startDate <= checkIn && checkIn <= endDate) { const sortedDates = Object.keys(groupedByDate).sort(
queryClient.setQueriesData(["attendanceLogs"], (oldData) => { (a, b) => new Date(b) - new Date(a)
if (!oldData) { );
queryClient.invalidateQueries({ queryKey: ["attendanceLogs"] });
return; const finalData = sortedDates.flatMap((date) => groupedByDate[date]);
} setProcessedData(finalData);
return oldData.map((record) => };
record.id === msg.response.id ? { ...record, ...msg.response } : record
); useEffect(() => {
}); filtering(data);
resetPage(); }, [data, showPending]);
// New useEffect to handle search filtering
const filteredSearchData = useMemo(() => {
if (!searchTerm) {
return processedData;
} }
}, const lowercasedSearchTerm = searchTerm.toLowerCase();
[selectedProject, dateRange, resetPage] return processedData.filter((item) => {
); const fullName = `${item.firstName} ${item.lastName}`.toLowerCase();
return fullName.includes(lowercasedSearchTerm);
});
}, [processedData, searchTerm]);
useEffect(() => { // const filteredSearchData = useMemo(() => {
eventBus.on("attendance_log", handler); // let tempData = processedData;
return () => eventBus.off("attendance_log", handler);
}, [handler]);
const employeeHandler = useCallback( // if (searchTerm) {
(msg) => { // const lowercasedSearchTerm = searchTerm.toLowerCase();
const { startDate, endDate } = dateRange; // tempData = tempData.filter((item) => {
if (data.some((item) => item.employeeId == msg.employeeId)) { // const fullName = `${item.firstName} ${item.lastName}`.toLowerCase();
refetch(); // return fullName.includes(lowercasedSearchTerm);
} // });
}, // }
[data, refetch]
);
useEffect(() => { // if (filters?.selectedOrganization) {
eventBus.on("employee", employeeHandler); // tempData = tempData.filter(
return () => eventBus.off("employee", employeeHandler); // (item) => item.organization?.name === filters.selectedOrganization
}, [employeeHandler]); // );
// }
// if (filters?.selectedServices?.length > 0) {
// tempData = tempData.filter((item) =>
// filters.selectedServices.includes(item.service?.name)
// );
// }
// return tempData;
// }, [processedData, searchTerm, filters]);
const {
currentPage,
totalPages,
currentItems: paginatedAttendances,
paginate,
resetPage,
} = usePagination(filteredSearchData, 20);
useEffect(() => {
resetPage();
}, [filteredSearchData, resetPage]);
const handler = useCallback(
(msg) => {
const { startDate, endDate } = dateRange;
const checkIn = msg.response.checkInTime.substring(0, 10);
if (
selectedProject === msg.projectId &&
startDate <= checkIn &&
checkIn <= endDate
) {
queryClient.setQueriesData(["attendanceLogs"], (oldData) => {
if (!oldData) {
queryClient.invalidateQueries({ queryKey: ["attendanceLogs"] });
return;
}
const updatedAttendance = oldData.map((record) =>
record.id === msg.response.id
? { ...record, ...msg.response }
: record
);
filtering(updatedAttendance);
return updatedAttendance;
});
resetPage();
}
},
[selectedProject, dateRange, filtering, resetPage]
);
useEffect(() => {
eventBus.on("attendance_log", handler);
return () => eventBus.off("attendance_log", handler);
}, [handler]);
const employeeHandler = useCallback(
(msg) => {
const { startDate, endDate } = dateRange;
if (data.some((item) => item.employeeId == msg.employeeId)) {
// dispatch(
// fetchAttendanceData({
// ,
// fromDate: startDate,
// toDate: endDate,
// })
// );
refetch()
}
},
[selectedProject, dateRange, data, refetch]
);
useEffect(() => {
eventBus.on("employee", employeeHandler);
return () => eventBus.off("employee", employeeHandler);
}, [employeeHandler]);
return ( return (
<> <>
<div <div
className="dataTables_length text-start py-2 d-flex justify-content-between " className="dataTables_length text-start py-2 d-flex justify-content-between"
id="DataTables_Table_0_length" id="DataTables_Table_0_length"
> >
<div className="d-flex align-items-center my-0 "> <div className="d-flex align-items-center my-0 ">
@ -180,7 +257,7 @@ useEffect(() => {
onRangeChange={setDateRange} onRangeChange={setDateRange}
defaultStartDate={yesterday} defaultStartDate={yesterday}
/> />
<div className="form-check form-switch text-start ms-1 ms-md-2 align-items-center mb-0"> <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"
@ -193,16 +270,11 @@ useEffect(() => {
<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> </div>
<div <div className="table-responsive text-nowrap" style={{ minHeight: "200px" }}>
className="table-responsive text-nowrap"
style={{ minHeight: "200px" }}
>
{isLoading ? ( {isLoading ? (
<div <div className="d-flex justify-content-center align-items-center" style={{ height: "200px" }}>
className="d-flex justify-content-center align-items-center"
style={{ height: "200px" }}
>
<p className="text-secondary">Loading...</p> <p className="text-secondary">Loading...</p>
</div> </div>
) : filteredSearchData?.length > 0 ? ( ) : filteredSearchData?.length > 0 ? (
@ -215,8 +287,7 @@ useEffect(() => {
<th className="border-top-1">Date</th> <th className="border-top-1">Date</th>
<th>Organization</th> <th>Organization</th>
<th> <th>
<i className="bx bxs-down-arrow-alt text-success"></i>{" "} <i className="bx bxs-down-arrow-alt text-success"></i> Check-In
Check-In
</th> </th>
<th> <th>
<i className="bx bxs-up-arrow-alt text-danger"></i> Check-Out <i className="bx bxs-up-arrow-alt text-danger"></i> Check-Out
@ -232,9 +303,9 @@ useEffect(() => {
const previousAttendance = arr[index - 1]; const previousAttendance = arr[index - 1];
const previousDate = previousAttendance const previousDate = previousAttendance
? moment( ? moment(
previousAttendance.checkInTime || previousAttendance.checkInTime ||
previousAttendance.checkOutTime previousAttendance.checkOutTime
).format("YYYY-MM-DD") ).format("YYYY-MM-DD")
: null; : null;
if (!previousDate || currentDate !== previousDate) { if (!previousDate || currentDate !== previousDate) {
@ -273,7 +344,7 @@ useEffect(() => {
attendance.checkInTime || attendance.checkOutTime attendance.checkInTime || attendance.checkOutTime
).format("DD-MMM-YYYY")} ).format("DD-MMM-YYYY")}
</td> </td>
<td>{attendance.organizationName || "--"}</td> <td>{attendance.organizationName || "--"}</td>
<td>{convertShortTime(attendance.checkInTime)}</td> <td>{convertShortTime(attendance.checkInTime)}</td>
<td> <td>
{attendance.checkOutTime {attendance.checkOutTime
@ -295,12 +366,7 @@ useEffect(() => {
</tbody> </tbody>
</table> </table>
) : ( ) : (
<div className="my-12"> <div className="my-12"><span className="text-secondary">No data available for the selected date range. Please Select another date.</span></div>
<span className="text-secondary">
No data available for the selected date range. Please Select
another date.
</span>
</div>
)} )}
</div> </div>
{paginatedAttendances?.length == 0 && filteredSearchData?.length > 0 && ( {paginatedAttendances?.length == 0 && filteredSearchData?.length > 0 && (
@ -326,9 +392,8 @@ useEffect(() => {
(pageNumber) => ( (pageNumber) => (
<li <li
key={pageNumber} key={pageNumber}
className={`page-item ${ className={`page-item ${currentPage === pageNumber ? "active" : ""
currentPage === pageNumber ? "active" : "" }`}
}`}
> >
<button <button
className="page-link" className="page-link"
@ -340,9 +405,8 @@ useEffect(() => {
) )
)} )}
<li <li
className={`page-item ${ className={`page-item ${currentPage === totalPages ? "disabled" : ""
currentPage === totalPages ? "disabled" : "" }`}
}`}
> >
<button <button
className="page-link" className="page-link"

View File

@ -33,7 +33,7 @@ const createSchema = (modeldata) => {
const checkOut = new Date(checkIn); const checkOut = new Date(checkIn);
checkOut.setHours(hour, minute, 0, 0); checkOut.setHours(hour, minute, 0, 0);
return checkOut >= checkIn; return checkOut > checkIn;
} }
return true; return true;
}, { }, {
@ -96,12 +96,12 @@ const CheckInCheckOut = ({ modeldata, closeModal, handleSubmitForm }) => {
}; };
return ( return (
<form className="row p-2" onSubmit={handleSubmit(onSubmit)}> <form className="row g-2" onSubmit={handleSubmit(onSubmit)}>
<div className="col-12 d-flex justify-content-center mb-4"> <div className="col-12 d-flex justify-content-center">
<label className="fs-5 tex-semibold text-center"> <label className="fs-5 text-dark text-center">
{modeldata?.checkInTime && !modeldata?.checkOutTime {modeldata?.checkInTime && !modeldata?.checkOutTime
? "Check-Out " ? "Check-out :"
: "Check-In "} : "Check-in :"}
</label> </label>
</div> </div>
@ -120,7 +120,7 @@ const CheckInCheckOut = ({ modeldata, closeModal, handleSubmitForm }) => {
modeldata?.checkInTime && !modeldata?.checkOutTime modeldata?.checkInTime && !modeldata?.checkOutTime
? formatDate(modeldata?.checkInTime?.split("T")[0]) || "" ? formatDate(modeldata?.checkInTime?.split("T")[0]) || ""
: formatDate(today) : formatDate(today)
} }
disabled disabled
/> />
</div> </div>

View File

@ -1,43 +1,25 @@
import React, { useCallback, useEffect, useState, useMemo } from "react"; import React, { useCallback, useEffect, useState, useMemo } from "react";
import Avatar from "../common/Avatar"; import Avatar from "../common/Avatar";
import { convertShortTime, formatUTCToLocalTime } from "../../utils/dateUtils"; import { convertShortTime } from "../../utils/dateUtils";
import RegularizationActions from "./RegularizationActions"; import RegularizationActions from "./RegularizationActions";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
import { useRegularizationRequests } from "../../hooks/useAttendance"; import { useRegularizationRequests } from "../../hooks/useAttendance";
import moment from "moment"; import moment from "moment";
import usePagination from "../../hooks/usePagination"; import usePagination from "../../hooks/usePagination";
import eventBus from "../../services/eventBus"; import eventBus from "../../services/eventBus";
import { import { cacheData, clearCacheKey, useSelectedProject } from "../../slices/apiDataManager";
cacheData,
clearCacheKey,
useSelectedProject,
} from "../../slices/apiDataManager";
import { useQueryClient } from "@tanstack/react-query"; import { useQueryClient } from "@tanstack/react-query";
import Pagination from "../../components/common/Pagination";
const Regularization = ({ const Regularization = ({ handleRequest, searchTerm,projectId, organizationId, IncludeInActive }) => {
handleRequest,
searchTerm,
projectId,
organizationId,
IncludeInActive,
}) => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
// var selectedProject = useSelector((store) => store.localVariables.projectId); // var selectedProject = useSelector((store) => store.localVariables.projectId);
const selectedProject = useSelectedProject(); const selectedProject = useSelectedProject();
const [regularizesList, setregularizedList] = useState([]); const [regularizesList, setregularizedList] = useState([]);
const { regularizes, loading, error, refetch } = useRegularizationRequests( const { regularizes, loading, error, refetch } =
selectedProject, useRegularizationRequests(selectedProject, organizationId, IncludeInActive);
organizationId,
IncludeInActive
);
useEffect(() => { useEffect(() => {
if(!regularizes) return
if(regularizes?.length) {
setregularizedList(regularizes); setregularizedList(regularizes);
}
}, [regularizes]); }, [regularizes]);
const sortByName = (a, b) => { const sortByName = (a, b) => {
@ -72,15 +54,48 @@ const Regularization = ({
} }
const lowercasedSearchTerm = searchTerm.toLowerCase(); const lowercasedSearchTerm = searchTerm.toLowerCase();
return sortedList.filter((item) => { return sortedList.filter((item) => {
const fullName = `${item?.firstName} ${item?.lastName}`.toLowerCase(); const fullName = `${item.firstName} ${item.lastName}`.toLowerCase();
return fullName.includes(lowercasedSearchTerm); return fullName.includes(lowercasedSearchTerm);
}); });
}, [regularizesList, searchTerm]); }, [regularizesList, searchTerm]);
const { currentPage, totalPages, currentItems, paginate } = usePagination( // const filteredSearchData = useMemo(() => {
filteredSearchData, // let sortedList = [...regularizesList].sort(sortByName);
20
); // // Search filter
// if (searchTerm) {
// const lowercasedSearchTerm = searchTerm.toLowerCase();
// sortedList = sortedList.filter((item) => {
// const fullName = `${item.firstName} ${item.lastName}`.toLowerCase();
// return fullName.includes(lowercasedSearchTerm);
// });
// }
// // Organization filter
// if (filters?.selectedOrganization) {
// sortedList = sortedList.filter(
// (item) => item.organization?.name === filters.selectedOrganization
// );
// }
// // Services filter
// if (filters?.selectedServices?.length > 0) {
// sortedList = sortedList.filter((item) =>
// filters.selectedServices.includes(item.service?.name)
// );
// }
// return sortedList;
// }, [regularizesList, searchTerm, filters]);
const { currentPage, totalPages, currentItems, paginate } =
usePagination(filteredSearchData, 20);
// Reset pagination when the search term or data changes
useEffect(() => {
}, [filteredSearchData]);
useEffect(() => { useEffect(() => {
eventBus.on("regularization", handler); eventBus.on("regularization", handler);
@ -102,15 +117,9 @@ const Regularization = ({
}, [employeeHandler]); }, [employeeHandler]);
return ( return (
<div <div className="table-responsive text-nowrap pb-4" style={{ minHeight: "200px" }}>
className="table-responsive text-nowrap pb-4"
style={{ minHeight: "200px" }}
>
{loading ? ( {loading ? (
<div <div className="d-flex justify-content-center align-items-center" style={{ height: "200px" }}>
className="d-flex justify-content-center align-items-center"
style={{ height: "200px" }}
>
<p className="text-secondary">Loading...</p> <p className="text-secondary">Loading...</p>
</div> </div>
) : currentItems?.length > 0 ? ( ) : currentItems?.length > 0 ? (
@ -126,21 +135,18 @@ const Regularization = ({
<th> <th>
<i className="bx bxs-up-arrow-alt text-danger"></i>Check-Out <i className="bx bxs-up-arrow-alt text-danger"></i>Check-Out
</th> </th>
<th colSpan={2}>
Requested By
</th>
<th >
Requested At
</th>
<th>Action</th> <th>Action</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{currentItems?.map((att, index) => ( {currentItems?.map((att, index) => (
<tr key={index}> <tr key={index}>
<td colSpan={2}> <td colSpan={2}>
<div className="d-flex justify-content-start align-items-center"> <div className="d-flex justify-content-start align-items-center">
<Avatar firstName={att.firstName} lastName={att.lastName} /> <Avatar
firstName={att.firstName}
lastName={att.lastName}
/>
<div className="d-flex flex-column"> <div className="d-flex flex-column">
<a href="#" className="text-heading text-truncate"> <a href="#" className="text-heading text-truncate">
<span className="fw-normal"> <span className="fw-normal">
@ -156,23 +162,7 @@ const Regularization = ({
<td>{convertShortTime(att.checkInTime)}</td> <td>{convertShortTime(att.checkInTime)}</td>
<td> <td>
{att.requestedAt ? convertShortTime(att.checkOutTime) : "--"} {att.checkOutTime ? convertShortTime(att.checkOutTime) : "--"}
</td>
<td colSpan={2}>
{att.requestedBy ? ( <div className="d-flex justify-content-start align-items-center">
<Avatar firstName={att?.requestedBy?.firstName} lastName={att?.requestedBy?.lastName} />
<div className="d-flex flex-column">
<a href="#" className="text-heading text-truncate">
<span className="fw-normal">
{att?.requestedBy?.firstName} {att?.requestedBy?.lastName}
</span>
</a>
</div>
</div>):(<small>--</small>)}
</td>
<td>
{att?.requestedAt ? formatUTCToLocalTime(att.requestedAt,true) : "--"}
</td> </td>
<td className="text-center "> <td className="text-center ">
<RegularizationActions <RegularizationActions
@ -185,6 +175,7 @@ const Regularization = ({
))} ))}
</tbody> </tbody>
</table> </table>
) : ( ) : (
<div <div
className="d-flex justify-content-center align-items-center" className="d-flex justify-content-center align-items-center"
@ -197,7 +188,7 @@ const Regularization = ({
</span> </span>
</div> </div>
)} )}
{/* {!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" : ""}`}>
@ -235,14 +226,6 @@ const Regularization = ({
</li> </li>
</ul> </ul>
</nav> </nav>
)} */}
{totalPages > 0 && (
<Pagination
currentPage={currentPage}
totalPages={totalPages}
onPageChange={paginate}
/>
)} )}
</div> </div>
); );

View File

@ -0,0 +1,42 @@
import React, { createContext, useState, useContext } from "react";
import ChangePasswordPage from "../../pages/authentication/ChangePassword";
const ChangePasswordContext = createContext();
export const ChangePasswordProvider = ({ children }) => {
const [isChangePasswordOpen, setIsChangePasswordOpen] = useState(false);
const openChangePassword = () => setIsChangePasswordOpen(true);
const closeChangePassword = () => setIsChangePasswordOpen(false);
return (
<ChangePasswordContext.Provider
value={{ isChangePasswordOpen, openChangePassword, closeChangePassword }}
>
{children}
{isChangePasswordOpen && (
<>
{/* This is the main Bootstrap modal container */}
{/* It provides the fixed positioning and high z-index */}
<div
className="modal fade show" // 'fade' for animation, 'show' to make it visible
style={{ display: 'block' }} // Explicitly set display: block for immediate visibility
tabIndex="-1" // Makes the modal focusable
role="dialog" // ARIA role for accessibility
aria-labelledby="changePasswordModalLabel" // Link to a heading for accessibility
aria-modal="true" // Indicate it's a modal dialog
>
{/* The ChangePasswordPage component itself contains the modal-dialog and modal-content */}
<ChangePasswordPage onClose={closeChangePassword} />
</div>
{/* The modal backdrop */}
<div className="modal-backdrop fade show"></div>
</>
)}
</ChangePasswordContext.Provider>
);
};
export const useChangePassword = () => useContext(ChangePasswordContext);

View File

@ -1,5 +1,5 @@
import React, { useState } from "react"; import React, { useState } from "react";
import { useCurrentService } from "../../hooks/useProjects"; import { useCurrentService, useProjectInfra } from "../../hooks/useProjects";
import { useSelectedProject } from "../../slices/apiDataManager"; import { useSelectedProject } from "../../slices/apiDataManager";
import { FormProvider, useForm } from "react-hook-form"; import { FormProvider, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
@ -10,14 +10,15 @@ import {
import { DateRangePicker1 } from "../common/DateRangePicker"; import { DateRangePicker1 } from "../common/DateRangePicker";
import SelectMultiple from "../common/SelectMultiple"; import SelectMultiple from "../common/SelectMultiple";
import { localToUtc } from "../../utils/appUtils"; import { localToUtc } from "../../utils/appUtils";
import { useTaskFilter } from "../../hooks/useTasks";
const TaskReportFilterPanel = ({ handleFilter }) => { const TaskReportFilterPanel = ({ handleFilter }) => {
const [resetKey, setResetKey] = useState(0); const [resetKey, setResetKey] = useState(0);
const selectedProject = useSelectedProject(); const selectedProjec = useSelectedProject();
const selectedService = useCurrentService(); const selectedService = useCurrentService();
const { data } = useTaskFilter(selectedProject); const { projectInfra, isLoading, error, isFetched } = useProjectInfra(
selectedProjec,
selectedService
);
const methods = useForm({ const methods = useForm({
resolver: zodResolver(TaskReportFilterSchema), resolver: zodResolver(TaskReportFilterSchema),
defaultValues: TaskReportDefaultValue, defaultValues: TaskReportDefaultValue,
@ -31,19 +32,21 @@ const TaskReportFilterPanel = ({ handleFilter }) => {
} = methods; } = methods;
const onSubmit = (formData) => { const onSubmit = (formData) => {
const filterPayload = { console.log(formData)
...formData, const filterPayload = {
dateFrom: localToUtc(formData.dateFrom), startDate:localToUtc(formData.startDate),
dateTo: localToUtc(formData.dateTo), endDate:localToUtc(formData.endDate)
};
}
handleFilter(filterPayload); handleFilter(filterPayload);
}; };
const onClear = () => { const onClear =()=>{
setResetKey((prev) => prev + 1); setResetKey((prev) => prev + 1);
handleFilter(TaskReportDefaultValue); handleFilter(TaskReportDefaultValue)
reset(TaskReportDefaultValue); reset(TaskReportDefaultValue)
}; }
return ( return (
<FormProvider {...methods}> <FormProvider {...methods}>
<form onSubmit={handleSubmit(onSubmit)} className="p-2 text-start"> <form onSubmit={handleSubmit(onSubmit)} className="p-2 text-start">
@ -51,48 +54,34 @@ const TaskReportFilterPanel = ({ handleFilter }) => {
<label className="fw-semibold">Choose Date Range:</label> <label className="fw-semibold">Choose Date Range:</label>
<DateRangePicker1 <DateRangePicker1
placeholder="DD-MM-YYYY To DD-MM-YYYY" placeholder="DD-MM-YYYY To DD-MM-YYYY"
startField="dateFrom" startField="startDate"
endField="dateTo" endField="endDate"
resetSignal={resetKey} resetSignal={resetKey}
defaultRange={false} defaultRange={true}
maxDate={new Date()}
/> />
</div> </div>
<div className="row mb-2"> {/* <div className="row g-2">
<SelectMultiple <SelectMultiple
name="buildingIds" name="buildingIds"
label="Building" label="Projects"
options={data?.buildings} options={projectInfra}
labelKey="name" labelKey="buildingName"
valueKey="id" valueKey="id"
/> />
</div> </div>
<div className="row mb-2"> <div className="row g-2">
<SelectMultiple <SelectMultiple
name="floorIds" name="floorIds"
label="Floor" label="Floor"
options={data?.floors} options={projectInfra}
labelKey="name" labelKey="floorName"
valueKey="id" valueKey="id"
/> />
</div> </div> */}
<div className="row mb-2">
<SelectMultiple
name="activityIds"
label="Activities"
options={data?.activities}
labelKey="name"
valueKey="id"
/>
</div>
<div className="d-flex justify-content-end py-3 gap-2"> <div className="d-flex justify-content-end py-3 gap-2">
<button <button type="button" className="btn btn-label-secondary btn-sm" onClick={onClear}>
type="button"
className="btn btn-label-secondary btn-sm"
onClick={onClear}
>
Clear Clear
</button> </button>
<button type="submit" className="btn btn-primary btn-sm"> <button type="submit" className="btn btn-primary btn-sm">

View File

@ -192,7 +192,7 @@ const TaskReportList = () => {
if (isLoading) return <TaskReportListSkeleton />; if (isLoading) return <TaskReportListSkeleton />;
if (isError) return <div>Loading....</div>; if (isError) return <div>Loading....</div>;
return ( return (
<div className="mt-2 table-responsive text-nowrap"> <div className="mt-2">
<table className="table"> <table className="table">
<thead> <thead>
<tr> <tr>

View File

@ -1,17 +1,15 @@
import { z } from "zod"; import { z } from "zod";
export const TaskReportFilterSchema = z.object({ export const TaskReportFilterSchema = z.object({
buildingIds: z.array(z.string()).optional(), // buildingIds: z.array(z.string()).optional(),
floorIds: z.array(z.string()).optional(), // floorIds: z.array(z.string()).optional(),
activityIds: z.array(z.string()).optional(), startDate: z.string().optional(),
dateFrom: z.string().optional(), endDate: z.string().optional(),
dateTo: z.string().optional(),
}); });
export const TaskReportDefaultValue = { export const TaskReportDefaultValue = {
buildingIds:[], // buildingIds:[],
floorIds:[], // floorIds:[],
activityIds:[], startDate:null,
dateFrom:null, endDate:null
dateTo:null
} }

View File

@ -179,7 +179,7 @@ const ListViewContact = ({ data, Pagination }) => {
<tr style={{ height: "200px" }}> <tr style={{ height: "200px" }}>
<td <td
colSpan={contactList.length + 1} colSpan={contactList.length + 1}
className="text-center border-0 align-middle" className="text-center align-middle"
> >
No contacts found No contacts found
</td> </td>

View File

@ -23,7 +23,7 @@ import Label from "../common/Label";
const ManageContact = ({ contactId, closeModal }) => { const ManageContact = ({ contactId, closeModal }) => {
// fetch master data // fetch master data
const { buckets, loading: bucketsLoaging } = useBuckets(); const { buckets, loading: bucketsLoaging } = useBuckets();
const { data:projects, loading: projectLoading } = useProjects(); const { projects, loading: projectLoading } = useProjects();
const { contactCategory, loading: contactCategoryLoading } = const { contactCategory, loading: contactCategoryLoading } =
useContactCategory(); useContactCategory();
const { organizationList } = useOrganization(); const { organizationList } = useOrganization();

View File

@ -14,24 +14,28 @@ import { FormProvider, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod"; import { z } from "zod";
import { localToUtc } from "../../utils/appUtils"; import { localToUtc } from "../../utils/appUtils";
import { useParams } from "react-router-dom";
const EmpAttendance = () => { const EmpAttendance = ({ employee }) => {
const { employeeId } = useParams();
const [attendances, setAttendnaces] = useState([]); const [attendances, setAttendnaces] = useState([]);
const [selectedDate, setSelectedDate] = useState(""); const [selectedDate, setSelectedDate] = useState("");
const [isModalOpen, setIsModalOpen] = useState(false); const [isModalOpen, setIsModalOpen] = useState(false);
const [attendanceId, setAttendanecId] = useState(); const [attendanceId, setAttendanecId] = useState();
const methods = useForm({ const methods = useForm({
resolver: zodResolver(
z.object({
startDate: z.string(),
endDate: z.string(),
})
),
defaultValues: { defaultValues: {
startDate: moment().subtract(6, "days").format("DD-MM-YYYY"), startDate: "",
endDate: moment().format("DD-MM-YYYY"), endDate: "",
}, },
}); });
const { watch } = methods; const { control, register, handleSubmit, reset, watch } = methods;
const startDate = watch("startDate");
const [startDate, endDate] = watch(["startDate", "endDate"]); const endDate = watch("endDate");
const { const {
data = [], data = [],
isLoading: loading, isLoading: loading,
@ -40,21 +44,76 @@ const EmpAttendance = () => {
error, error,
refetch, refetch,
} = useAttendanceByEmployee( } = useAttendanceByEmployee(
employeeId, employee,
startDate ? localToUtc(startDate) : null, localToUtc(startDate),
endDate ? localToUtc(endDate) : null localToUtc(endDate)
); );
const dispatch = useDispatch(); const dispatch = useDispatch();
const sorted = [...data].sort(
const today = new Date();
today.setHours(0, 0, 0, 0);
const isSameDay = (dateStr) => {
if (!dateStr) return false;
const d = new Date(dateStr);
d.setHours(0, 0, 0, 0);
return d.getTime() === today.getTime();
};
const isBeforeToday = (dateStr) => {
if (!dateStr) return false;
const d = new Date(dateStr);
d.setHours(0, 0, 0, 0);
return d.getTime() < today.getTime();
};
const sortByName = (a, b) => {
const nameA = a.firstName.toLowerCase() + a.lastName.toLowerCase();
const nameB = b.firstName.toLowerCase() + b.lastName.toLowerCase();
return nameA?.localeCompare(nameB);
};
const group1 = data
.filter((d) => d.activity === 1 && isSameDay(d.checkInTime))
.sort(sortByName);
const group2 = data
.filter((d) => d.activity === 4 && isSameDay(d.checkOutTime))
.sort(sortByName);
const group3 = data
.filter((d) => d.activity === 1 && isBeforeToday(d.checkInTime))
.sort(sortByName);
const group4 = data
.filter((d) => d.activity === 4 && isBeforeToday(d.checkOutTime))
.sort(sortByName);
const group5 = data.filter((d) => d.activity === 5).sort(sortByName);
const uniqueMap = new Map();
[...group1, ...group2, ...group3, ...group4, ...group5].forEach((rec) => {
const date = moment(rec.checkInTime || rec.checkOutTime).format(
"YYYY-MM-DD"
);
const key = `${rec.employeeId}-${date}`;
const existing = uniqueMap.get(key);
if (
!existing ||
new Date(rec.checkInTime || rec.checkOutTime) >
new Date(existing.checkInTime || existing.checkOutTime)
) {
uniqueMap.set(key, rec);
}
});
const sortedFinalList = [...uniqueMap.values()].sort(
(a, b) => (a, b) =>
new Date(b?.checkInTime).getTime() - new Date(a?.checkInTime).getTime() new Date(b.checkInTime || b.checkOutTime) -
new Date(a.checkInTime || a.checkOutTime)
); );
console.log(sorted); const currentDate = new Date().toLocaleDateString("en-CA");
const { currentPage, totalPages, currentItems, paginate } = usePagination( const { currentPage, totalPages, currentItems, paginate } = usePagination(
sorted, sortedFinalList,
ITEMS_PER_PAGE ITEMS_PER_PAGE
); );
@ -64,6 +123,7 @@ const EmpAttendance = () => {
}; };
const closeModal = () => setIsModalOpen(false); const closeModal = () => setIsModalOpen(false);
const onSubmit = (formData) => {};
return ( return (
<> <>
{isModalOpen && ( {isModalOpen && (
@ -76,10 +136,20 @@ const EmpAttendance = () => {
className="dataTables_length text-start py-2 d-flex justify-content-between " className="dataTables_length text-start py-2 d-flex justify-content-between "
id="DataTables_Table_0_length" id="DataTables_Table_0_length"
> >
<div className="col-4 col-md-3 my-0 "> <div className="col-3 my-0 ">
<> <>
<FormProvider {...methods}> <FormProvider {...methods}>
<DateRangePicker1 /> <form
onSubmit={handleSubmit(onSubmit)}
className="p-2 text-start"
>
<DateRangePicker1
placeholder="DD-MM-YYYY To DD-MM-YYYY"
startField="startDate"
endField="endDate"
defaultRange={true}
/>
</form>
</FormProvider> </FormProvider>
</> </>
</div> </div>
@ -164,7 +234,7 @@ const EmpAttendance = () => {
</table> </table>
)} )}
</div> </div>
{!loading && data.length > 20 && ( {!loading && sortedFinalList.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 <li

View File

@ -1,13 +1,12 @@
import React, { useState, useEffect } from "react"; import React, { useState, useEffect } from "react";
import { useChangePassword } from "../../components/Context/ChangePasswordContext";
import GlobalModel from "../common/GlobalModel"; import GlobalModel from "../common/GlobalModel";
import ManageEmployee from "./ManageEmployee"; import ManageEmployee from "./ManageEmployee";
import { formatUTCToLocalTime } from "../../utils/dateUtils"; import { formatUTCToLocalTime } from "../../utils/dateUtils";
import { useModal } from "../../hooks/useAuth";
const EmpBanner = ({ profile, loggedInUser }) => { const EmpBanner = ({ profile, loggedInUser }) => {
const {onOpen} = useModal("ChangePassword") const { openChangePassword } = useChangePassword();
const [showModal, setShowModal] = useState(false); const [showModal, setShowModal] = useState(false);
return ( return (
@ -87,7 +86,7 @@ const EmpBanner = ({ profile, loggedInUser }) => {
</li> </li>
</ul> </ul>
<ul className="list-inline mb-0 d-flex align-items-center flex-wrap justify-content-sm-start justify-content-center mt-4"> <ul className="list-inline mb-0 d-flex align-items-center flex-wrap justify-content-sm-start justify-content-center mt-4">
{profile?.isActive && ( {profile?.isActive && ( // show only if active
<li className="list-inline-item"> <li className="list-inline-item">
<button <button
className="btn btn-sm btn-primary btn-block" className="btn btn-sm btn-primary btn-block"
@ -102,7 +101,7 @@ const EmpBanner = ({ profile, loggedInUser }) => {
{profile?.id === loggedInUser?.employeeInfo?.id && ( {profile?.id === loggedInUser?.employeeInfo?.id && (
<button <button
className="btn btn-sm btn-outline-primary btn-block" className="btn btn-sm btn-outline-primary btn-block"
onClick={onOpen} onClick={() => openChangePassword()}
> >
Change Password Change Password
</button> </button>

View File

@ -18,7 +18,7 @@ import { defatEmployeeObj, employeeSchema } from "./EmployeeSchema";
import { useOrganizationsList } from "../../hooks/useOrganization"; import { useOrganizationsList } from "../../hooks/useOrganization";
import { ITEMS_PER_PAGE } from "../../utils/constants"; import { ITEMS_PER_PAGE } from "../../utils/constants";
const ManageEmployee = ({ employeeId, onClosed }) => { const ManageEmployee = ({ employeeId, onClosed, IsAllEmployee }) => {
const dispatch = useDispatch(); const dispatch = useDispatch();
const { mutate: updateEmployee, isPending } = useUpdateEmployee(); const { mutate: updateEmployee, isPending } = useUpdateEmployee();
const { const {
@ -72,7 +72,7 @@ const ManageEmployee = ({ employeeId, onClosed }) => {
data.email = null; data.email = null;
} }
const payload = { ...data }; const payload = { ...data, IsAllEmployee };
if (employeeId) { if (employeeId) {
payload.id = employeeId; payload.id = employeeId;

View File

@ -117,7 +117,6 @@ const ExpenseFilterPanel = ({ onApply, handleGroupBy }) => {
endField="endDate" endField="endDate"
resetSignal={resetKey} resetSignal={resetKey}
defaultRange={false} defaultRange={false}
maxDate={new Date()}
/> />
</div> </div>

View File

@ -28,7 +28,6 @@ import moment from "moment";
import DatePicker from "../common/DatePicker"; import DatePicker from "../common/DatePicker";
import ErrorPage from "../../pages/ErrorPage"; import ErrorPage from "../../pages/ErrorPage";
import Label from "../common/Label"; import Label from "../common/Label";
import EmployeeSearchInput from "../common/EmployeeSearchInput";
const ManageExpense = ({ closeModal, expenseToEdit = null }) => { const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
const { const {
@ -58,7 +57,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
}); });
const selectedproject = watch("projectId"); const selectedproject = watch("projectId");
const { const {
projectNames, projectNames,
loading: projectLoading, loading: projectLoading,
@ -143,7 +142,8 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
}; };
useEffect(() => { useEffect(() => {
if (expenseToEdit && data) { if (expenseToEdit && data ) {
reset({ reset({
projectId: data.project.id || "", projectId: data.project.id || "",
expensesTypeId: data.expensesType.id || "", expensesTypeId: data.expensesType.id || "",
@ -156,7 +156,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
supplerName: data.supplerName || "", supplerName: data.supplerName || "",
amount: data.amount || "", amount: data.amount || "",
noOfPersons: data.noOfPersons || "", noOfPersons: data.noOfPersons || "",
gstNumber: data.gstNumber || "", gstNumber:data.gstNumber || "",
billAttachments: data.documents billAttachments: data.documents
? data.documents.map((doc) => ({ ? data.documents.map((doc) => ({
fileName: doc.fileName, fileName: doc.fileName,
@ -183,7 +183,8 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
const onSubmit = (fromdata) => { const onSubmit = (fromdata) => {
let payload = { let payload = {
...fromdata, ...fromdata,
transactionDate: localToUtc(fromdata.transactionDate), transactionDate: localToUtc(fromdata.transactionDate)
}; };
if (expenseToEdit) { if (expenseToEdit) {
const editPayload = { ...payload, id: data.id }; const editPayload = { ...payload, id: data.id };
@ -205,6 +206,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
if (StatusLoadding || projectLoading || ExpenseLoading || isLoading) if (StatusLoadding || projectLoading || ExpenseLoading || isLoading)
return <ExpenseSkeleton />; return <ExpenseSkeleton />;
return ( return (
<div className="container p-3"> <div className="container p-3">
<h5 className="m-0"> <h5 className="m-0">
@ -213,9 +215,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
<form id="expenseForm" onSubmit={handleSubmit(onSubmit)}> <form id="expenseForm" onSubmit={handleSubmit(onSubmit)}>
<div className="row my-2 text-start"> <div className="row my-2 text-start">
<div className="col-md-6"> <div className="col-md-6">
<Label className="form-label" required> <Label className="form-label" required>Select Project</Label>
Select Project
</Label>
<select <select
className="form-select form-select-sm" className="form-select form-select-sm"
{...register("projectId")} {...register("projectId")}
@ -296,11 +296,11 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
)} )}
</div> </div>
<div className="col-12 col-md-6 text-start"> <div className="col-md-6">
<Label htmlFor="paidById" className="form-label" required> <Label htmlFor="paidById" className="form-label" required>
Paid By Paid By
</Label> </Label>
{/* <select <select
className="form-select form-select-sm" className="form-select form-select-sm"
id="paymentModeId" id="paymentModeId"
{...register("paidById")} {...register("paidById")}
@ -321,14 +321,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
</select> </select>
{errors.paidById && ( {errors.paidById && (
<small className="danger-text">{errors.paidById.message}</small> <small className="danger-text">{errors.paidById.message}</small>
)} */} )}
<EmployeeSearchInput
control={control}
name="paidById"
projectId={null}
forAll={expenseToEdit ? true : false}
/>
</div> </div>
</div> </div>
@ -337,11 +330,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
<Label htmlFor="transactionDate" className="form-label" required> <Label htmlFor="transactionDate" className="form-label" required>
Transaction Date Transaction Date
</Label> </Label>
<DatePicker <DatePicker name="transactionDate" control={control} maxDate={new Date()}/>
name="transactionDate"
control={control}
maxDate={new Date()}
/>
{errors.transactionDate && ( {errors.transactionDate && (
<small className="danger-text"> <small className="danger-text">
@ -420,9 +409,9 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
</small> </small>
)} )}
</div> </div>
<div className="col-md-6"> <div className="col-md-6">
<label htmlFor="statusId" className="form-label "> <label htmlFor="statusId" className="form-label ">
GST Number GST Number
</label> </label>
<input <input
type="text" type="text"
@ -432,7 +421,9 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
{...register("gstNumber")} {...register("gstNumber")}
/> />
{errors.gstNumber && ( {errors.gstNumber && (
<small className="danger-text">{errors.gstNumber.message}</small> <small className="danger-text">
{errors.gstNumber.message}
</small>
)} )}
</div> </div>
@ -457,9 +448,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
<div className="row my-2 text-start"> <div className="row my-2 text-start">
<div className="col-md-12"> <div className="col-md-12">
<Label htmlFor="description" className="form-label" required> <Label htmlFor="description" className="form-label" required>Description</Label>
Description
</Label>
<textarea <textarea
id="description" id="description"
className="form-control form-control-sm" className="form-control form-control-sm"
@ -476,9 +465,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
<div className="row my-2 text-start"> <div className="row my-2 text-start">
<div className="col-md-12"> <div className="col-md-12">
<Label className="form-label" required> <Label className="form-label" required>Upload Bill </Label>
Upload Bill{" "}
</Label>
<div <div
className="border border-secondary border-dashed rounded p-4 text-center bg-textMuted position-relative" className="border border-secondary border-dashed rounded p-4 text-center bg-textMuted position-relative"
@ -562,7 +549,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
<div className="d-flex justify-content-end gap-3"> <div className="d-flex justify-content-end gap-3">
{" "} {" "}
<button <button
type="reset" type="reset"
disabled={isPending || createPending} disabled={isPending || createPending}
onClick={handleClose} onClick={handleClose}
@ -581,6 +568,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
? "Update" ? "Update"
: "Submit"} : "Submit"}
</button> </button>
</div> </div>
</form> </form>
</div> </div>

View File

@ -9,7 +9,7 @@ import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import { defaultActionValues, ExpenseActionScheam } from "./ExpenseSchema"; import { defaultActionValues, ExpenseActionScheam } from "./ExpenseSchema";
import { useExpenseContext } from "../../pages/Expense/ExpensePage"; import { useExpenseContext } from "../../pages/Expense/ExpensePage";
import { getColorNameFromHex, getIconByFileType, localToUtc } from "../../utils/appUtils"; import { getColorNameFromHex, getIconByFileType } from "../../utils/appUtils";
import { ExpenseDetailsSkeleton } from "./ExpenseSkeleton"; import { ExpenseDetailsSkeleton } from "./ExpenseSkeleton";
import { useHasUserPermission } from "../../hooks/useHasUserPermission"; import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { import {
@ -91,7 +91,9 @@ const ViewExpense = ({ ExpenseId }) => {
const onSubmit = (formData) => { const onSubmit = (formData) => {
const Payload = { const Payload = {
...formData, ...formData,
reimburseDate: localToUtc(formData.reimburseDate), reimburseDate: moment
.utc(formData.reimburseDate, "DD-MM-YYYY")
.toISOString(),
expenseId: ExpenseId, expenseId: ExpenseId,
comment: formData.comment, comment: formData.comment,
}; };
@ -396,7 +398,6 @@ const ViewExpense = ({ ExpenseId }) => {
name="reimburseDate" name="reimburseDate"
control={control} control={control}
minDate={data?.transactionDate} minDate={data?.transactionDate}
maxDate={new Date()}
/> />
{errors.reimburseDate && ( {errors.reimburseDate && (
<small className="danger-text"> <small className="danger-text">

View File

@ -12,13 +12,14 @@ import useMaster from "../../hooks/masterHook/useMaster";
import { useProfile } from "../../hooks/useProfile"; import { useProfile } from "../../hooks/useProfile";
import { useLocation, useNavigate, useParams } from "react-router-dom"; import { useLocation, useNavigate, useParams } from "react-router-dom";
import Avatar from "../../components/common/Avatar"; import Avatar from "../../components/common/Avatar";
import { useChangePassword } from "../Context/ChangePasswordContext";
import { useProjects } from "../../hooks/useProjects"; import { useProjects } from "../../hooks/useProjects";
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
import { useProjectName } from "../../hooks/useProjects"; import { useProjectName } from "../../hooks/useProjects";
import eventBus from "../../services/eventBus"; import eventBus from "../../services/eventBus";
import { useHasUserPermission } from "../../hooks/useHasUserPermission"; import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { MANAGE_PROJECT } from "../../utils/constants"; import { MANAGE_PROJECT } from "../../utils/constants";
import { useAuthModal, useLogout, useModal } from "../../hooks/useAuth"; import { useAuthModal, useLogout } from "../../hooks/useAuth";
const Header = () => { const Header = () => {
const { profile } = useProfile(); const { profile } = useProfile();
@ -27,7 +28,6 @@ const Header = () => {
const { data, loading } = useMaster(); const { data, loading } = useMaster();
const navigate = useNavigate(); const navigate = useNavigate();
const {onOpen} = useAuthModal() const {onOpen} = useAuthModal()
const { onOpen:changePass } = useModal("ChangePassword");
const HasManageProjectPermission = useHasUserPermission(MANAGE_PROJECT); const HasManageProjectPermission = useHasUserPermission(MANAGE_PROJECT);
const { mutate : logout,isPending:logouting} = useLogout() const { mutate : logout,isPending:logouting} = useLogout()
@ -97,7 +97,7 @@ const Header = () => {
} }
} }
const { openChangePassword } = useChangePassword();
useEffect(() => { useEffect(() => {
if ( if (
@ -189,8 +189,7 @@ const Header = () => {
className="navbar-nav-right d-flex align-items-center justify-content-between" className="navbar-nav-right d-flex align-items-center justify-content-between"
id="navbar-collapse" id="navbar-collapse"
> >
<div className="d-flex align-items-center"> {showProjectDropdown(location.pathname) && (
{showProjectDropdown(location.pathname) && (
<div className="align-items-center"> <div className="align-items-center">
<i className="rounded-circle bx bx-building-house bx-sm-lg bx-md me-2"></i> <i className="rounded-circle bx bx-building-house bx-sm-lg bx-md me-2"></i>
<div className="btn-group"> <div className="btn-group">
@ -248,7 +247,6 @@ const Header = () => {
</div> </div>
</div> </div>
)} )}
</div>
<ul className="navbar-nav flex-row align-items-center ms-md-auto"> <ul className="navbar-nav flex-row align-items-center ms-md-auto">
<li className="nav-item dropdown-shortcuts navbar-dropdown dropdown me-2 me-xl-0"> <li className="nav-item dropdown-shortcuts navbar-dropdown dropdown me-2 me-xl-0">
@ -424,7 +422,7 @@ const Header = () => {
<span className="align-middle">Settings</span> <span className="align-middle">Settings</span>
</a> </a>
</li> </li>
<li onClick={changePass}> <li onClick={openChangePassword}>
{" "} {" "}
<a <a
aria-label="go to profile" aria-label="go to profile"

View File

@ -10,15 +10,13 @@ import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import { spridSchema } from "./OrganizationSchema"; import { spridSchema } from "./OrganizationSchema";
import { OrgCardSkeleton } from "./OrganizationSkeleton"; import { OrgCardSkeleton } from "./OrganizationSkeleton";
import { useQueryClient } from "@tanstack/react-query";
// Zod schema: only allow exactly 4 digits // Zod schema: only allow exactly 4 digits
const OrgPickerFromSPId = ({ title, placeholder }) => { const OrgPickerFromSPId = ({ title, placeholder }) => {
const { onClose, startStep, flowType, onOpen, prevStep,orgData } = const { onClose, startStep, flowType, onOpen, prevStep } =
useOrganizationModal(); useOrganizationModal();
const clientQuery = useQueryClient()
const { const {
register, register,
handleSubmit, handleSubmit,
@ -37,11 +35,8 @@ const OrgPickerFromSPId = ({ title, placeholder }) => {
const onSubmit = (formdata) => { const onSubmit = (formdata) => {
setSPRID(formdata.spridSearchText); setSPRID(formdata.spridSearchText);
}; };
const handleCrateOrg = () => { const handleOrg = (orgId) => {};
clientQuery.removeQueries({queryKey:["organization"]})
onOpen({ startStep: 4,orgData:null })
};
const SP = watch("spridSearchText"); const SP = watch("spridSearchText");
return ( return (
<div className="d-block"> <div className="d-block">
@ -131,7 +126,7 @@ const OrgPickerFromSPId = ({ title, placeholder }) => {
<button <button
type="button" type="button"
className="btn btn-sm btn-primary mt-3" className="btn btn-sm btn-primary mt-3"
onClick={handleCrateOrg} onClick={() => onOpen({ startStep: 4 })}
> >
<i className="bx bx-plus-circle me-2"></i> <i className="bx bx-plus-circle me-2"></i>
Create New Organization Create New Organization

View File

@ -14,7 +14,7 @@ export const organizationSchema = z.object({
contactPerson: z.string().min(1, { message: "Person name required" }), contactPerson: z.string().min(1, { message: "Person name required" }),
address: z.string().min(1, { message: "Address is required!" }), address: z.string().min(1, { message: "Address is required!" }),
email: z email: z
.string().trim() .string()
.min(1, { message: "Email is required" }) .min(1, { message: "Email is required" })
.email("Invalid email address"), .email("Invalid email address"),
serviceIds: z serviceIds: z

View File

@ -23,7 +23,7 @@ const OrganizationsList = ({searchText}) => {
label: "Organization Name", label: "Organization Name",
getValue: (org) => ( getValue: (org) => (
<div className="d-flex gap-2 py-1 "> <div className="d-flex gap-2 py-1 ">
<i className="bx bx-buildings"></i> <i class="bx bx-buildings"></i>
<span <span
className="text-truncate d-inline-block " className="text-truncate d-inline-block "
style={{ maxWidth: "150px" }} style={{ maxWidth: "150px" }}
@ -142,7 +142,7 @@ const OrganizationsList = ({searchText}) => {
colSpan={organizationsColumns.length + 1} colSpan={organizationsColumns.length + 1}
className="text-center" className="text-center"
> >
<p className="fw-semibold">{isLoading ? "Loading....":"Not Found Organization"}</p> <p className="fw-semibold">Not Found</p>
</td> </td>
</tr> </tr>
)} )}

View File

@ -42,7 +42,7 @@ const AboutProject = () => {
{IsOpenModal && ( {IsOpenModal && (
<GlobalModel isOpen={IsOpenModal} closeModal={() => setIsOpenModal(false)}> <GlobalModel isOpen={IsOpenModal} closeModal={() => setIsOpenModal(false)}>
<ManageProjectInfo <ManageProjectInfo
project={projects_Details?.id} project={projects_Details}
handleSubmitForm={handleFormSubmit} handleSubmitForm={handleFormSubmit}
onClose={() => setIsOpenModal(false)} onClose={() => setIsOpenModal(false)}
isPending={isPending} isPending={isPending}

View File

@ -11,8 +11,7 @@ import { TasksRepository } from "../../repositories/ProjectRepository";
import showToast from "../../services/toastService"; import showToast from "../../services/toastService";
import { import {
useEmployeeForTaskAssign, useEmployeeForTaskAssign,
useProjectAssignedOrganizationsName, useProjectAssignedOrganizations,
useProjectAssignedServices,
useProjectDetails, useProjectDetails,
} from "../../hooks/useProjects"; } from "../../hooks/useProjects";
import eventBus from "../../services/eventBus"; import eventBus from "../../services/eventBus";
@ -96,9 +95,9 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
}, []); }, []);
const selectedProject = useSelectedProject(); const selectedProject = useSelectedProject();
const { data: serviceList, isLoading: isServiceLoading } = useProjectAssignedServices(selectedProject); const { data: serviceList, isLoading: isServiceLoading } = useServices();
const { data: organizationList, isLoading: isOrgLoading } = const { data: organizationList, isLoading: isOrgLoading } =
useProjectAssignedOrganizationsName(selectedProject); useProjectAssignedOrganizations(selectedProject);
const { data: employees, isLoading: isEmployeeLoading } = const { data: employees, isLoading: isEmployeeLoading } =
useEmployeeForTaskAssign( useEmployeeForTaskAssign(
selectedProject, selectedProject,
@ -275,7 +274,7 @@ const AssignTask = ({ assignData, onClose, setAssigned }) => {
) : ( ) : (
<> <>
<option value="">--Select Service--</option> <option value="">--Select Service--</option>
{serviceList?.map((service,index) => ( {serviceList?.data?.map((service,index) => (
<option key={`${service.id}-${index}`} value={service.id}> <option key={`${service.id}-${index}`} value={service.id}>
{service.name} {service.name}
</option> </option>

View File

@ -8,7 +8,7 @@ import {
useGroups, useGroups,
useWorkCategoriesMaster, useWorkCategoriesMaster,
} from "../../../hooks/masterHook/useMaster"; } from "../../../hooks/masterHook/useMaster";
import { useManageTask, useProjectAssignedOrganizationsName, useProjectAssignedServices } from "../../../hooks/useProjects"; import { useManageTask, useProjectAssignedOrganizations, useProjectAssignedServices } from "../../../hooks/useProjects";
import showToast from "../../../services/toastService"; import showToast from "../../../services/toastService";
import Label from "../../common/Label"; import Label from "../../common/Label";
import { useSelectedProject } from "../../../slices/apiDataManager"; import { useSelectedProject } from "../../../slices/apiDataManager";
@ -47,7 +47,7 @@ const TaskModel = ({ project, onSubmit, onClose }) => {
const projectId = useSelectedProject(); const projectId = useSelectedProject();
const { data: assignedServices, isLoading: servicesLoading } = useProjectAssignedServices(projectId); const { data: assignedServices, isLoading: servicesLoading } = useProjectAssignedServices(projectId);
const { data: assignedOrganizations, isLoading: orgLoading } = useProjectAssignedOrganizationsName(projectId); const { data: assignedOrganizations, isLoading: orgLoading } = useProjectAssignedOrganizations(projectId);

View File

@ -108,7 +108,7 @@ const WorkArea = ({ workArea, floor, forBuilding }) => {
<ProgressBar <ProgressBar
completedWork={formatNumber(workArea?.completedWork)} completedWork={formatNumber(workArea?.completedWork)}
plannedWork={formatNumber(workArea?.plannedWork)} plannedWork={formatNumber(workArea?.plannedWork)}
className="m-0 my-2 " height="6px"rounded showLabel={true} className="m-0 my-2 me-6 text-info"
/> />
</div> </div>
</div> </div>

View File

@ -327,7 +327,7 @@ const ManageProjectInfo = ({ project, onClose }) => {
<i className="bx bx-sm bx-info-circle"></i> Not found PMC and <i className="bx bx-sm bx-info-circle"></i> Not found PMC and
Pomoter, find through SPRID or create new Pomoter, find through SPRID or create new
</span> </span>
<small className="cursor-pointer" onClick={handleOrganizaioFinder} > <small className="cursor-pointer" onClick={handleOrganizaioFinder}>
<i className="bx bx-plus-circle text-primary"></i> <i className="bx bx-plus-circle text-primary"></i>
</small> </small>
</div> </div>
@ -367,14 +367,14 @@ const ManageProjectInfo = ({ project, onClose }) => {
className="btn btn-label-secondary btn-sm me-2" className="btn btn-label-secondary btn-sm me-2"
onClick={handleCancel} onClick={handleCancel}
aria-label="Close" aria-label="Close"
disabled={isPending || isCreating || loading} disabled={isPending || isCreating}
> >
Cancel Cancel
</button> </button>
<button <button
type="submit" type="submit"
className="btn btn-primary btn-sm" className="btn btn-primary btn-sm"
disabled={isPending || isCreating || loading} disabled={isPending || isCreating}
> >
{isPending||isCreating ? "Please Wait..." : project ? "Update" : "Submit"} {isPending||isCreating ? "Please Wait..." : project ? "Update" : "Submit"}
</button> </button>

View File

@ -132,15 +132,11 @@ const ProjectListView = ({
return ( return (
<div className="card page-min-h py-4 px-6 shadow-sm"> <div className="card page-min-h py-4 px-6 shadow-sm">
<div
className="table-responsive text-nowrap page-min-h"
>
<table className="table table-hover align-middle m-0"> <table className="table table-hover align-middle m-0">
<thead className="border-bottom "> <thead className="border-bottom">
<tr> <tr>
{projectColumns.map((col) => ( {projectColumns.map((col) => (
<th key={col.key} colSpan={col.colSpan} className={`${col.className} table_header_border`}> <th key={col.key} colSpan={col.colSpan} className={col.className}>
{col.label} {col.label}
</th> </th>
))} ))}
@ -221,7 +217,6 @@ const ProjectListView = ({
))} ))}
</tbody> </tbody>
</table> </table>
</div>
{isLoading && ( {isLoading && (
<div className="py-4"> <div className="py-4">

View File

@ -1,7 +1,6 @@
import React from "react"; import React from "react";
import { useProjectAssignedOrganizations } from "../../../hooks/useProjects"; import { useProjectAssignedOrganizations } from "../../../hooks/useProjects";
import { useSelectedProject } from "../../../slices/apiDataManager"; import { useSelectedProject } from "../../../slices/apiDataManager";
import { formatUTCToLocalTime } from "../../../utils/dateUtils";
const ProjectAssignedOrgs = () => { const ProjectAssignedOrgs = () => {
const selectedProject = useSelectedProject(); const selectedProject = useSelectedProject();
@ -48,33 +47,18 @@ const ProjectAssignedOrgs = () => {
), ),
align: "text-center", align: "text-center",
}, },
{
{ key: "isActive",
key: "organizationType", label: "Status",
label: "Organization Type",
getValue: (org) => ( getValue: (org) => (
<span <span
className="text-truncate d-inline-block" className={`text-truncate d-inline-block badge bg-label-${org.isActive ? "primary" :"secondary"}`}
style={{ maxWidth: "200px" }} style={{ maxWidth: "80px" }}
> >
{org?.organizationType || "N/A"} {org?.isActive ? "Active" : "Inactive"}
</span> </span>
), ),
align: "text-center", align: "text-start",
},
{
key: "assignedDate",
label: "Assigned Date",
getValue: (org) => (
<span
className="text-truncate d-inline-block"
style={{ maxWidth: "200px" }}
>
{/* {org?.assignedDate || "N/A"} */}
{formatUTCToLocalTime(org?.assignedDate)}
</span>
),
align: "text-center",
}, },
]; ];

View File

@ -2,7 +2,7 @@ import React, { useState } from "react";
import TeamEmployeeList from "./TeamEmployeeList"; import TeamEmployeeList from "./TeamEmployeeList";
import { useOrganization } from "../../../hooks/useDirectory"; import { useOrganization } from "../../../hooks/useDirectory";
import { useOrganizationsList } from "../../../hooks/useOrganization"; import { useOrganizationsList } from "../../../hooks/useOrganization";
import { useProjectAssignedOrganizationsName } from "../../../hooks/useProjects"; import { useProjectAssignedOrganizations } from "../../../hooks/useProjects";
import { useSelectedProject } from "../../../slices/apiDataManager"; import { useSelectedProject } from "../../../slices/apiDataManager";
const TeamAssignToProject = ({ closeModal }) => { const TeamAssignToProject = ({ closeModal }) => {
@ -10,13 +10,13 @@ const TeamAssignToProject = ({ closeModal }) => {
const [selectedOrg, setSelectedOrg] = useState(null); const [selectedOrg, setSelectedOrg] = useState(null);
const project = useSelectedProject(); const project = useSelectedProject();
const { data, isLoading, isError, error } = const { data, isLoading, isError, error } =
useProjectAssignedOrganizationsName(project); useProjectAssignedOrganizations(project);
return ( return (
<div className="container"> <div className="container">
<p className="fs-5 fs-seminbod ">Assign Employee To Project </p> <p className="fs-5 fs-seminbod ">Assign Employee To Project </p>
<div className="row align-items-center gx-5"> <div class="row align-items-center gx-5">
<div className="col"> <div class="col">
<div className="d-flex flex-grow-1 align-items-center gap-2"> <div className="d-flex flex-grow-1 align-items-center gap-2">
{isLoading ? ( {isLoading ? (
<select className="form-select form-select-sm w-100" disabled> <select className="form-select form-select-sm w-100" disabled>
@ -49,7 +49,7 @@ const TeamAssignToProject = ({ closeModal }) => {
)} )}
</div> </div>
</div> </div>
<div className="col"> <div class="col">
<div className="d-flex flex-grow-1 align-items-center gap-2"> <div className="d-flex flex-grow-1 align-items-center gap-2">
<label htmlFor="search" className="form-label mb-0 text-nowrap"> <label htmlFor="search" className="form-label mb-0 text-nowrap">
Search Employee Search Employee

View File

@ -2,14 +2,13 @@ import React, { useState, useEffect } from "react";
import Avatar from "../../common/Avatar"; import Avatar from "../../common/Avatar";
import { useDebounce } from "../../../utils/appUtils"; import { useDebounce } from "../../../utils/appUtils";
import { useSelectedProject } from "../../../slices/apiDataManager"; import { useSelectedProject } from "../../../slices/apiDataManager";
import { useOrganizationEmployees } from "../../../hooks/useOrganization";
import { import {
useEmployeesByProjectAllocated, useEmployeesByProjectAllocated,
useManageProjectAllocation, useManageProjectAllocation,
useProjectAssignedServices,
} from "../../../hooks/useProjects"; } from "../../../hooks/useProjects";
import useMaster, { useServices } from "../../../hooks/masterHook/useMaster"; import useMaster, { useServices } from "../../../hooks/masterHook/useMaster";
import showToast from "../../../services/toastService"; import showToast from "../../../services/toastService";
import { useOrganizationEmployees } from "../../../hooks/useOrganization";
const TeamEmployeeList = ({ organizationId, searchTerm, closeModal }) => { const TeamEmployeeList = ({ organizationId, searchTerm, closeModal }) => {
const selectedProject = useSelectedProject(); const selectedProject = useSelectedProject();
@ -30,7 +29,7 @@ const TeamEmployeeList = ({ organizationId, searchTerm, closeModal }) => {
useEmployeesByProjectAllocated(selectedProject, null); useEmployeesByProjectAllocated(selectedProject, null);
const { data: jobRoles } = useMaster(); const { data: jobRoles } = useMaster();
const { data: services } = useProjectAssignedServices(selectedProject); const { data: services } = useServices();
const [employees, setEmployees] = useState([]); const [employees, setEmployees] = useState([]);
@ -188,7 +187,7 @@ if (employees.length === 0) {
}`} }`}
> >
<option value="">Select Service</option> <option value="">Select Service</option>
{services?.map((s) => ( {services?.data?.map((s) => (
<option key={s.id} value={s.id}> <option key={s.id} value={s.id}>
{s.name} {s.name}
</option> </option>

View File

@ -93,26 +93,20 @@ const Teams = () => {
}; };
const filteredEmployees = useMemo(() => { const filteredEmployees = useMemo(() => {
if (!projectEmployees) return []; if (!projectEmployees || !searchTerm?.trim()) return projectEmployees;
let filtered = projectEmployees; const lower = searchTerm.toLowerCase();
if (activeEmployee) { return projectEmployees?.filter((emp) => {
filtered = projectEmployees.filter((emp) => !emp.isActive); const fullName = `${emp.firstName ?? ""} ${
} emp.lastName ?? ""
}`.toLowerCase();
// Apply search filter if present const joberole = getJobRole(emp?.jobRoleId)?.toLowerCase();
if (searchTerm?.trim()) {
const lower = searchTerm.toLowerCase();
filtered = filtered.filter((emp) => {
const fullName = `${emp.firstName ?? ""} ${emp.lastName ?? ""}`.toLowerCase();
const jobRole = getJobRole(emp?.jobRoleId)?.toLowerCase();
return fullName.includes(lower) || jobRole.includes(lower);
});
}
return filtered; return fullName?.includes(lower) || joberole?.includes(lower);
}, [projectEmployees, searchTerm, activeEmployee]); });
}, [projectEmployees, searchTerm]);
const handleSearch = (e) => setSearchTerm(e.target.value); const handleSearch = (e) => setSearchTerm(e.target.value);
const employeeHandler = useCallback( const employeeHandler = useCallback(
(msg) => { (msg) => {
@ -272,7 +266,7 @@ const Teams = () => {
className="text-heading text-truncate cursor-pointer" className="text-heading text-truncate cursor-pointer"
> >
<span className="fw-normal"> <span className="fw-normal">
{emp.firstName}{" "} {emp.firstName}
{emp.lastName} {emp.lastName}
</span> </span>
</a> </a>
@ -323,7 +317,7 @@ const Teams = () => {
{!employeeLodaing && filteredEmployees.length === 0 && ( {!employeeLodaing && filteredEmployees.length === 0 && (
<div className="text-center text-muted py-3 d-flex justify-content-center align-items-center py-12"> <div className="text-center text-muted py-3 d-flex justify-content-center align-items-center py-12">
<p> <p>
{activeEmployee {!activeEmployee
? "No active employees assigned to the project" ? "No active employees assigned to the project"
: "No inactive employees assigned to the project"} : "No inactive employees assigned to the project"}
</p> </p>

View File

@ -14,7 +14,7 @@ const SkeletonCell = ({ width = "100%", height = 20, style = {} }) => (
export const TenantTableSkeleton = ({ columns, rows = 5 }) => { export const TenantTableSkeleton = ({ columns, rows = 5 }) => {
return ( return (
<div className="p-2 mt-3"> <div className="card p-2 mt-3">
<div className="card-datatable text-nowrap table-responsive"> <div className="card-datatable text-nowrap table-responsive">
<table className="table border-top dataTable text-nowrap"> <table className="table border-top dataTable text-nowrap">
<thead> <thead>

View File

@ -137,7 +137,7 @@ const TenantsList = ({
return ( return (
<> <>
<div className="p-2 mt-3"> <div className="p-2 mt-3">
<div className=" text-nowrap table-responsive"> <div className="card-datatable text-nowrap table-responsive">
<table className="table border-top dataTable text-nowrap"> <table className="table border-top dataTable text-nowrap">
<thead> <thead>
<tr className="shadow-sm"> <tr className="shadow-sm">

View File

@ -1,39 +1,27 @@
import React, { useEffect, useRef } from "react"; import React, { useEffect, useRef } from "react";
import { useController, useFormContext, useWatch } from "react-hook-form"; import { useController, useFormContext, useWatch } from "react-hook-form";
import { useSelector } from "react-redux";
const DateRangePicker = ({ const DateRangePicker = ({
md=12, md,
sm=6, sm,
onRangeChange, onRangeChange,
DateDifference = 7, DateDifference = 7,
endDateMode = "yesterday", endDateMode = "yesterday",
}) => { }) => {
const inputRef = useRef(null); const inputRef = useRef(null);
const persistedRange = useSelector(
(store) => store.localVariables.attendance.defaultDateRange
);
useEffect(() => { useEffect(() => {
let startDate, endDate; const endDate = new Date();
if (endDateMode === "yesterday") {
if (persistedRange?.startDate && persistedRange?.endDate) { endDate.setDate(endDate.getDate() - 1);
startDate = new Date(persistedRange.startDate);
endDate = new Date(persistedRange.endDate);
} else {
endDate = new Date();
if (endDateMode === "yesterday") {
endDate.setDate(endDate.getDate() - 1);
}
endDate.setHours(0, 0, 0, 0);
startDate = new Date(endDate);
startDate.setDate(endDate.getDate() - (DateDifference - 1));
startDate.setHours(0, 0, 0, 0);
} }
const fp = flatpickr(inputRef.current, { endDate.setHours(0, 0, 0, 0);
const startDate = new Date(endDate);
startDate.setDate(endDate.getDate() - (DateDifference - 1));
startDate.setHours(0, 0, 0, 0);
const fp = flatpickr(inputRef.current, {
mode: "range", mode: "range",
dateFormat: "Y-m-d", dateFormat: "Y-m-d",
altInput: true, altInput: true,
@ -53,32 +41,32 @@ const DateRangePicker = ({
endDate: endDate.toLocaleDateString("en-CA"), endDate: endDate.toLocaleDateString("en-CA"),
}); });
return () => fp.destroy(); return () => {
}, [onRangeChange, DateDifference, endDateMode, persistedRange]); fp.destroy();
};
}, [onRangeChange, DateDifference, endDateMode]);
const handleIconClick = () => { const handleIconClick = () => {
if (inputRef.current?._flatpickr) { if (inputRef.current) {
inputRef.current._flatpickr.open(); inputRef.current._flatpickr.open(); // directly opens flatpickr
} }
}; };
return ( return (
<div className={`position-relative w-auto justify-content-center`}> <div className={`col-${sm} col-sm-${md} px-1`}>
<input <input
type="text" type="text"
className="form-control form-control-sm w-100 pe-8 " className="form-control form-control-sm ps-2 pe-5 me-4"
placeholder="From to End" placeholder="From to End"
id="flatpickr-range" id="flatpickr-range"
ref={inputRef} ref={inputRef}
/> />
<i
className="bx bx-calendar calendar-icon cursor-pointer position-absolute top-50 end-0 translate-middle-y me-2 "
onClick={handleIconClick}
/>
</div>
<i
className="bx bx-calendar calendar-icon cursor-pointer position-relative top-50 translate-middle-y " onClick={handleIconClick}
style={{ right: "22px", bottom: "-8px" }}
></i>
</div>
); );
}; };
@ -88,7 +76,6 @@ export default DateRangePicker;
export const DateRangePicker1 = ({ export const DateRangePicker1 = ({
startField = "startDate", startField = "startDate",
endField = "endDate", endField = "endDate",

View File

@ -4,13 +4,10 @@ import { useDebounce } from "../../utils/appUtils";
import { useController } from "react-hook-form"; import { useController } from "react-hook-form";
import Avatar from "./Avatar"; import Avatar from "./Avatar";
const EmployeeSearchInput = ({
control,
name,
projectId, const EmployeeSearchInput = ({ control, name, projectId,placeholder }) => {
placeholder,
forAll,
}) => {
const { const {
field: { onChange, value, ref }, field: { onChange, value, ref },
fieldState: { error }, fieldState: { error },
@ -20,20 +17,17 @@ const EmployeeSearchInput = ({
const [showDropdown, setShowDropdown] = useState(false); const [showDropdown, setShowDropdown] = useState(false);
const debouncedSearch = useDebounce(search, 500); const debouncedSearch = useDebounce(search, 500);
const { data: employees, isLoading } = useEmployeesName( const {
projectId, data: employees,
debouncedSearch, isLoading,
forAll } = useEmployeesName(projectId, debouncedSearch);
);
useEffect(() => { useEffect(() => {
if (value && employees?.data) { if (value && !search) {
const found = employees.data.find((emp) => emp.id === value); const found = employees?.data?.find((emp) => emp.id === value);
if (found && forAll) { if (found) setSearch(found.firstName + " " + found.lastName);
setSearch(found.firstName + " " + found.lastName);
}
} }
}, [value, employees?.data]); }, [value, employees]);
const handleSelect = (employee) => { const handleSelect = (employee) => {
onChange(employee.id); onChange(employee.id);
@ -52,7 +46,7 @@ const EmployeeSearchInput = ({
onChange={(e) => { onChange={(e) => {
setSearch(e.target.value); setSearch(e.target.value);
setShowDropdown(true); setShowDropdown(true);
onChange(""); onChange("");
}} }}
onFocus={() => { onFocus={() => {
if (search) setShowDropdown(true); if (search) setShowDropdown(true);
@ -67,27 +61,28 @@ const EmployeeSearchInput = ({
{isLoading ? ( {isLoading ? (
<li className="list-group-item"> <li className="list-group-item">
<a>Searching...</a> <a>Searching...</a>
</li> </li>
) : ( ) : (
employees?.data?.map((emp) => ( employees?.data?.map((emp) => (
<li <li
key={emp.id} key={emp.id}
className="list-group-item list-group-item-action py-1 px-1" className="list-group-item list-group-item-action py-1 px-1"
style={{ cursor: "pointer" }} style={{ cursor: "pointer" }}
onClick={() => handleSelect(emp)} onClick={() => handleSelect(emp)}
> >
<div className="d-flex align-items-center px-0"> <div className="d-flex align-items-center px-0">
<Avatar <Avatar
size="xs" size="xs"
classAvatar="m-0 me-2" classAvatar="m-0 me-2"
firstName={emp.firstName} firstName={emp.firstName}
lastName={emp.lastName} lastName={emp.lastName}
/> />
<span className="text-muted"> <span className="text-muted">
{`${emp?.firstName} ${emp?.lastName}`.trim()} {`${emp?.firstName} ${emp?.lastName}`.trim()}
</span> </span>
</div> </div>
</li> </li>
)) ))
)} )}
</ul> </ul>

View File

@ -3,65 +3,35 @@ import React from "react";
const ProgressBar = ({ const ProgressBar = ({
plannedWork = 100, plannedWork = 100,
completedWork = 0, completedWork = 0,
height = "6px", height = "8px",
className = "mb-4", className = "mb-4",
rounded = true, rounded = true,
showLabel = true,
}) => { }) => {
const getProgress = (planned, completed) => { const getProgress = (planned, completed) => {
if (!planned || planned === 0) return 0; if (!planned || planned === 0) return "0%";
return Math.min((completed / planned) * 100, 100); return `${Math.min((completed / planned) * 100, 100).toFixed(2)}%`;
}; };
const percentage = getProgress(plannedWork, completedWork); const progressStyle = {
width: getProgress(plannedWork, completedWork),
const progressBarStyle = {
width: ` ${percentage.toFixed(2)}%`,
transition: "width 0.4s ease",
};
const containerStyle = {
height,
display: "flex",
alignItems: "center",
gap: "8px",
}; };
return ( return (
<div <div
className={`d-flex align-items-center ${className}`} className={`progress ${className} ${rounded ? "rounded" : ""}`}
style={containerStyle} style={{ height }}
> >
<div className="flex-grow-1"> <div
<div className={`progress-bar ${rounded ? "rounded" : ""}`}
className={`progress ${rounded ? "rounded" : ""}`} role="progressbar"
style={{ height, backgroundColor: "#f0f0f0" }} style={progressStyle}
> aria-valuenow={completedWork}
<div aria-valuemin="0"
className={`progress-bar ${rounded ? "rounded" : ""}`} aria-valuemax={plannedWork}
role="progressbar" ></div>
style={progressBarStyle}
aria-valuenow={completedWork}
aria-valuemin="0"
aria-valuemax={plannedWork}
/>
</div>
</div>
{showLabel && (
<span
className="fw-semibold text-secondary"
style={{
minWidth: "45px",
textAlign: "right",
fontSize: "0.8rem",
}}
>
{percentage.toFixed(2)}%
</span>
)}
</div> </div>
); );
}; };
export default ProgressBar; export default ProgressBar;

View File

@ -1,143 +0,0 @@
import React, { useState } from "react";
import { useImageGalleryFilter } from "../../hooks/useImageGallery";
import { useSelectedProject } from "../../slices/apiDataManager";
import { FormProvider, useForm } from "react-hook-form";
import Label from "../common/Label";
import { DateRangePicker1 } from "../common/DateRangePicker";
import { zodResolver } from "@hookform/resolvers/zod";
import { defaultGalleryFilterValue, gallerySchema } from "./GallerySchema";
import SelectMultiple from "../common/SelectMultiple";
import { localToUtc } from "../../utils/appUtils";
const GalleryFilterPanel = ({ onApply }) => {
const selectedProject = useSelectedProject();
const [resetKey, setResetKey] = useState(0);
const { data, isLoading, isError, error } =
useImageGalleryFilter(selectedProject);
const closePanel = () => {
document.querySelector(".offcanvas.show .btn-close")?.click();
};
const methods = useForm({
resolver: zodResolver(gallerySchema),
defaultValues: defaultGalleryFilterValue,
});
const {
handleSubmit,
register,
setValue,reset,
formState: { errors },
} = methods;
const onSubmit = (formData) => {
onApply({
...formData,
startDate: localToUtc(formData.startDate),
endDate: localToUtc(formData.endDate),
});
closePanel()
};
const onClear=()=>{
reset(defaultGalleryFilterValue);
setResetKey((prev) => prev + 1);
closePanel()
}
if (isLoading) return <div>Loading....</div>;
if (isError) return <div>{error.message}</div>;
return (
<div className="d-block text-start">
<FormProvider {...methods}>
<form onSubmit={handleSubmit(onSubmit)}>
<div className="mb-2">
<Label>Select Date:</Label>
<DateRangePicker1
placeholder="DD-MM-YYYY To DD-MM-YYYY"
startField="startDate"
endField="endDate"
resetSignal={resetKey}
defaultRange={false}
maxDate={new Date()}
/>
</div>
<div className="mb-2">
<SelectMultiple
name="buildingIds"
label="Select building:"
options={data?.buildings}
labelKey="name"
valueKey="id"
/>
</div>
<div className="mb-2">
<SelectMultiple
name="floorIds"
label="Select Floor:"
options={data?.floors}
labelKey="name"
valueKey="id"
/>
</div>
<div className="mb-2">
<SelectMultiple
name="workAreaIds"
label="Select Work Area:"
options={data?.workAreas}
labelKey="name"
valueKey="id"
/>
</div>
<div className="mb-2">
<SelectMultiple
name="workCategoryIds"
label="Select Work Category:"
options={data?.workCategories}
labelKey="name"
valueKey="id"
/>
</div>
<div className="mb-2">
<SelectMultiple
name="activityIds"
label="Select Activity:"
options={data?.activities}
labelKey="name"
valueKey="id"
/>
</div>
<div className="mb-2">
<SelectMultiple
name="uploadedByIds"
label="Select Uploaded By:"
options={data?.UploadedBys}
labelKey="name"
valueKey="id"
/>
</div>
<div className="mb-2">
<SelectMultiple
name="serviceIds"
label="Select Service:"
options={data?.services}
labelKey="name"
valueKey="id"
/>
</div>
<div className="d-flex flex-row gap-3 justify-content-end">
<button className="btn btn-sm btn-label-secondary" onClick={onClear}>Cancel</button>
<button type="submit" className="btn btn-sm btn-primary">
Apply
</button>
</div>
</form>
</FormProvider>
</div>
);
};
export default GalleryFilterPanel;

View File

@ -1,25 +0,0 @@
import { z } from "zod";
export const gallerySchema = z.object({
buildingIds: z.array(z.string()).optional(),
floorIds: z.array(z.string()).optional(),
workAreaIds: z.array(z.string()).optional(),
activityIds: z.array(z.string()).optional(),
workCategoryIds: z.array(z.string()).optional(),
startDate: z.string().optional(),
endDate: z.string().optional(),
uploadedByIds: z.array(z.string()).optional(),
serviceIds: z.array(z.string()).optional(),
});
export const defaultGalleryFilterValue = {
buildingIds: [],
floorIds: [],
workAreaIds: [],
activityIds: [],
workCategoryIds:[],
startDate: null,
endDate: null,
uploadedByIds:[],
serviceIds: [],
};

View File

@ -1,169 +0,0 @@
import React, { useRef, useState, useCallback, useEffect } from "react";
import moment from "moment";
import Avatar from "../../components/common/Avatar";
import { useGalleryContext } from "../../pages/Gallary/ImageGallaryPage";
import useImageGallery from "../../hooks/useImageGallery";
import { useSelectedProject } from "../../slices/apiDataManager";
import { ITEMS_PER_PAGE } from "../../utils/constants";
import Pagination from "../common/Pagination";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
import Loader from "../common/Loader";
const ImageGalleryListView = ({filter}) => {
const [hoveredImage, setHoveredImage] = useState(null);
const selectedProject = useSelectedProject();
const [currentPage, setCurrentPage] = useState(1);
const { setOpenGallery } = useGalleryContext();
const { data, isLoading, isError, error } = useImageGallery(
selectedProject,
currentPage,
10,
filter
);
const paginate = (page) => {
if (page >= 1 && page <= (data?.totalPages ?? 1)) {
setCurrentPage(page);
}
};
if (!data?.data?.length && !isLoading) {
return (
<p className="text-center text-muted mt-5">
{selectedProject ? " No images match the selected filters.":"Please Select Project!"}
</p>
);
}
if (isLoading) {
return (
<div className="page-min-h d-flex justify-content-center align-items-center">
<Loader />
</div>
);
}
return (
<div className="main-content">
<div className="activity-section">
{data?.data?.map((batch) => {
if (!batch.documents?.length) return null;
const doc = batch.documents[0];
const userName = `${doc.uploadedBy?.firstName || ""} ${
doc.uploadedBy?.lastName || ""
}`.trim();
const date = formatUTCToLocalTime(doc.uploadedAt);
// const hasArrows = batch.documents.length > scrollThreshold;
return (
<div key={batch.batchId} className="grouped-section">
<div className="group-heading">
<div className="d-flex align-items-center mb-1">
<Avatar
size="xs"
firstName={doc.uploadedBy?.firstName}
lastName={doc.uploadedBy?.lastName}
className="me-2"
/>
<div className="d-flex flex-column align-items-start">
<strong className="user-name-text">{userName}</strong>
<span className="text-muted small">{date}</span>
</div>
</div>
<div className="location-line text-secondary">
<div className="d-flex align-items-center flex-wrap gap-1 text-secondary">
<span className="d-flex align-items-center">
<span>{batch.buildingName}</span>
<i className="bx bx-chevron-right " />
</span>
<span className="d-flex align-items-center">
<span>{batch.floorName}</span>
<i className="bx bx-chevron-right m" />
</span>
<span className="d-flex align-items-center ">
<span>{batch.workAreaName || "Unknown"}</span>
<i className="bx bx-chevron-right " />
<span>{batch.activityName}</span>
</span>
</div>
{batch.workCategoryName && (
<span className="badge bg-label-primary ms-2">
{batch.workCategoryName}
</span>
)}
</div>
</div>
<div className="image-group-wrapper">
{/* {hasArrows && (
<button className="scroll-arrow left-arrow" onClick={() => scrollLeft(batch.batchId)}>
</button>
)} */}
<div
className="image-group-horizontal"
// ref={(el) => (imageGroupRefs.current[batch.batchId] = el)}
>
{batch.documents.map((d, i) => {
const hoverDate = moment().format("DD MMMM, YYYY");
const hoverTime = moment(d.uploadedAt).format("hh:mm A");
return (
<div
key={d.id}
className="image-card"
onMouseEnter={() => setHoveredImage(d)}
onMouseLeave={() => setHoveredImage(null)}
onClick={() =>
setOpenGallery({
isOpen: true,
data: { data: batch, index: i },
})
}
>
<div className="image-wrapper">
<img src={d.url} alt={`Image ${i + 1}`} />
</div>
{hoveredImage === d && (
<div className="image-hover-description">
<p>
<strong>Date:</strong> {hoverDate}
</p>
<p>
<strong>Time:</strong> {hoverTime}
</p>
<p>
<strong>Activity:</strong> {batch.activityName}
</p>
</div>
)}
</div>
);
})}
</div>
{/* {hasArrows && (
<button className="scroll-arrow right-arrow" onClick={() => scrollRight(batch.batchId)}>
</button>
)} */}
</div>
</div>
);
})}
</div>
{data?.data?.length > 0 && (
<Pagination
currentPage={currentPage}
totalPages={data?.totalPages}
onPageChange={paginate}
/>
)}
</div>
);
};
export default ImageGalleryListView;

View File

@ -1,111 +0,0 @@
import React, { useState, useEffect } from "react";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
const ViewGallery = ({ batch, index }) => {
const [loading, setLoading] = useState(true);
const [currentIndex, setCurrentIndex] = useState(index);
console.log(batch);
useEffect(() => {
setCurrentIndex(index);
}, [index, batch]);
if (!batch || !batch.documents || batch.documents.length === 0) return null;
const image = batch.documents[currentIndex];
if (!image) return null;
const fullName = `${image.uploadedBy?.firstName || ""} ${
image.uploadedBy?.lastName || ""
}`.trim();
const date = formatUTCToLocalTime(image.uploadedAt);
const buildingName = batch.buildingName;
const floorName = batch.floorName;
const workAreaName = batch.workAreaName;
const activityName = batch.activityName;
const batchComment = batch.comment;
const handlePrev = () => {
setCurrentIndex((prevIndex) => Math.max(0, prevIndex - 1));
};
const handleNext = () => {
setCurrentIndex((prevIndex) =>
Math.min(batch.documents.length - 1, prevIndex + 1)
);
};
const hasPrev = currentIndex > 0;
const hasNext = currentIndex < batch.documents.length - 1;
return (
<div>
{loading && <p>Loading...</p>}
<div className="position-relative d-flex justify-content-center align-items-center">
{hasPrev && (
<button
className="btn btn-icon btn-outline-primary rounded-circle position-absolute start-0 top-50 translate-middle-y shadow"
onClick={handlePrev}
>
<i className="bx bx-chevron-left fs-4"></i>
</button>
)}
<img
src={image.url}
alt="Preview"
className="img-fluid rounded"
style={{
maxHeight: "500px",
width: "100%",
objectFit: "contain",
}}
onLoad={() => setLoading(false)}
/>
{hasNext && (
<button
className="btn btn-icon btn-outline-primary position-absolute end-0 top-50 translate-middle-y rounded-circle shadow"
onClick={handleNext}
>
<i className="bx bx-chevron-right fs-4"></i>
</button>
)}
</div>
{/* Details */}
<div className="mt-3 text-start small">
<p className="mb-1">
<i className="bx bxs-user me-2"></i>
<span className="text-muted">Uploaded By: </span>
<span className="fw-semibold">{fullName}</span>
</p>
<p className="mb-1">
<i className="bx bxs-calendar me-2"></i>
<span className="text-muted">Date: </span>
<span className="fw-semibold">{date}</span>
</p>
<p className="mb-1">
<i className="bx bx-map me-2"></i>
<span className="text-muted">Location: </span>
<span className="fw-semibold">
{buildingName} <i className="bx bx-chevron-right"></i> {floorName}{" "}
<i className="bx bx-chevron-right"></i> {workAreaName || "Unknown"}{" "}
<i className="bx bx-chevron-right"></i> {activityName}
</span>
</p>
<p className="mb-0">
<i className="bx bx-comment-dots me-2"></i>
<span className="text-muted">Comment: </span>
<span className="fw-semibold">{batchComment}</span>
</p>
</div>
</div>
);
};
export default ViewGallery;

View File

@ -41,6 +41,7 @@ const EditContactTag = ({ data, onClose }) => {
name: formData.name, name: formData.name,
description: formData.description, description: formData.description,
}; };
debugger
updateContactTag({ id: data?.id, payload }); updateContactTag({ id: data?.id, payload });
} }
// const onSubmit = (formdata) => { // const onSubmit = (formdata) => {

View File

@ -70,12 +70,12 @@ const MasterModal = ({ modaldata, closeModal }) => {
}; };
return ( return (
<div className="p-2 p-md-1"> <>
<div className="text-center"> <div className="text-center">
<p className="fs-5 fw-semibold" >{`${masterType, " ", modalType}`}</p> <p className="fs-5 fw-semibold" >{`${masterType, " ", modalType}`}</p>
</div> </div>
{ modalComponents[modalType] || null} { modalComponents[modalType] || null}
</div> </>
); );
}; };

View File

@ -37,6 +37,7 @@ const ServiceGroups = ({ service }) => {
<div className="w-100 my-2"> <div className="w-100 my-2">
<p className="fs-5 fw-semibold">Manage Service</p>
<div className="accordion" id="accordionExample"> <div className="accordion" id="accordionExample">
<div className="accordion-item active shadow-none"> <div className="accordion-item active shadow-none">
{/* Service Header */} {/* Service Header */}
@ -81,8 +82,8 @@ const ServiceGroups = ({ service }) => {
) : ( ) : (
<div className="accordion-body text-start m-0 p-0"> <div className="accordion-body text-start m-0 p-0">
<div className="dropdown-divider border"></div> <div className="dropdown-divider border"></div>
{!isLoading && groups?.data?.length === 0 && (<div className="text-center py-2"><p>No Group available.</p></div>)}
{groups && groups?.data?.map((group) => { {groups?.data?.map((group) => {
const isOpen = activeGroupId === group.id; const isOpen = activeGroupId === group.id;
return ( return (

View File

@ -570,6 +570,7 @@ export const useUpdateContactTag = (onSuccessCallback) => {
return useMutation({ return useMutation({
mutationFn: async ({ id, payload }) => { mutationFn: async ({ id, payload }) => {
debugger;
const response = await MasterRespository.updateContactTag(id, payload); const response = await MasterRespository.updateContactTag(id, payload);
return response.data; return response.data;
}, },
@ -703,13 +704,13 @@ export const useCreateService = (onSuccessCallback) => {
return useMutation({ return useMutation({
mutationFn: async (payload) => { mutationFn: async (payload) => {
debugger;
const resp = await MasterRespository.createService(payload); const resp = await MasterRespository.createService(payload);
debugger;
return resp.data; return resp.data;
}, },
onSuccess: (data) => { onSuccess: (data) => {
debugger;
queryClient.invalidateQueries({ queryKey: ["masterData", "Services"] }); queryClient.invalidateQueries({ queryKey: ["masterData", "Services"] });
showToast(data?.message || "Service added successfully", "success"); showToast(data?.message || "Service added successfully", "success");
@ -717,7 +718,7 @@ export const useCreateService = (onSuccessCallback) => {
if (onSuccessCallback) onSuccessCallback(data?.data); if (onSuccessCallback) onSuccessCallback(data?.data);
}, },
onError: (error) => { onError: (error) => {
debugger;
showToast( error?.response?.data?.message || error?.message || "Something went wrong", "error"); showToast( error?.response?.data?.message || error?.message || "Something went wrong", "error");
}, },
}); });
@ -758,7 +759,7 @@ export const useCreateActivityGroup = (onSuccessCallback) => {
queryClient.invalidateQueries({ queryClient.invalidateQueries({
queryKey: ["groups"], queryKey: ["groups"],
}); });
debugger
showToast( data?.message || showToast( data?.message ||
data?.response?.data?.message || "Activity Group created successfully.", data?.response?.data?.message || "Activity Group created successfully.",
"success" "success"

View File

@ -1,9 +1,5 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { import { cacheData, getCachedData, useSelectedProject } from "../slices/apiDataManager";
cacheData,
getCachedData,
useSelectedProject,
} from "../slices/apiDataManager";
import AttendanceRepository from "../repositories/AttendanceRepository"; import AttendanceRepository from "../repositories/AttendanceRepository";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import showToast from "../services/toastService"; import showToast from "../services/toastService";
@ -11,8 +7,11 @@ import { useDispatch, useSelector } from "react-redux";
import { store } from "../store/store"; import { store } from "../store/store";
import { setDefaultDateRange } from "../slices/localVariablesSlice"; import { setDefaultDateRange } from "../slices/localVariablesSlice";
// ----------------------------Query----------------------------- // ----------------------------Query-----------------------------
// export const useAttendance = (projectId) => { // export const useAttendance = (projectId) => {
// const dispatch = useDispatch() // const dispatch = useDispatch()
// const { // const {
@ -42,10 +41,7 @@ import { setDefaultDateRange } from "../slices/localVariablesSlice";
// }; // };
// }; // };
export const useAttendance = ( export const useAttendance = (projectId, organizationId, includeInactive = false, date = null) => {
projectId,
organizationId,
) => {
const dispatch = useDispatch(); const dispatch = useDispatch();
const { const {
@ -55,11 +51,13 @@ export const useAttendance = (
refetch: recall, refetch: recall,
isFetching, isFetching,
} = useQuery({ } = useQuery({
queryKey: ["attendance", projectId, organizationId], // include filters in cache key queryKey: ["attendance", projectId, organizationId, includeInactive, date], // include filters in cache key
queryFn: async () => { queryFn: async () => {
const response = await AttendanceRepository.getAttendance( const response = await AttendanceRepository.getAttendance(
projectId, projectId,
organizationId, organizationId,
includeInactive,
date
); );
return response.data; return response.data;
}, },
@ -72,17 +70,12 @@ export const useAttendance = (
return { attendance, loading, error, recall, isFetching }; return { attendance, loading, error, recall, isFetching };
}; };
export const useAttendancesLogs = ( export const useAttendancesLogs = (projectId, fromDate, toDate,organizationId) => {
projectId,
fromDate,
toDate,
organizationId
) => {
const dispatch = useDispatch(); const dispatch = useDispatch();
const enabled = !!projectId && !!fromDate && !!toDate; const enabled = !!projectId && !!fromDate && !!toDate;
const query = useQuery({ const query = useQuery({
queryKey: ["attendanceLogs", projectId, fromDate, toDate, organizationId], queryKey: ['attendanceLogs', projectId, fromDate, toDate,organizationId],
queryFn: async () => { queryFn: async () => {
const res = await AttendanceRepository.getAttendanceFilteredByDate( const res = await AttendanceRepository.getAttendanceFilteredByDate(
projectId, projectId,
@ -94,7 +87,7 @@ export const useAttendancesLogs = (
}, },
enabled, enabled,
}); });
useEffect(() => { useEffect(() => {
if (query.data && fromDate && toDate) { if (query.data && fromDate && toDate) {
dispatch( dispatch(
@ -108,6 +101,8 @@ export const useAttendancesLogs = (
return query; return query;
}; };
export const useEmployeeAttendacesLog = (id) => { export const useEmployeeAttendacesLog = (id) => {
const { const {
data: logs = [], data: logs = [],
@ -122,10 +117,7 @@ export const useEmployeeAttendacesLog = (id) => {
}, },
enabled: !!id, enabled: !!id,
onError: (error) => { onError: (error) => {
showToast( showToast(error.message || "Error while fetching Attendance Logs", "error");
error.message || "Error while fetching Attendance Logs",
"error"
);
}, },
}); });
@ -143,22 +135,40 @@ export const useAttendanceByEmployee = (employeeId, fromDate, toDate) => {
return useQuery({ return useQuery({
queryKey: ["employeeAttendance", employeeId, fromDate, toDate], queryKey: ["employeeAttendance", employeeId, fromDate, toDate],
queryFn: async () => { queryFn: async () => {
const res = await AttendanceRepository.getAttendanceByEmployee( const res = await AttendanceRepository.getAttendanceByEmployee(employeeId, fromDate, toDate);
employeeId,
fromDate,
toDate
);
return res.data; return res.data;
}, },
enabled, enabled: !!fromDate && !! toDate,
}); });
}; };
export const useRegularizationRequests = ( // export const useRegularizationRequests = (projectId) => {
projectId, // const {
organizationId, // data: regularizes = [],
IncludeInActive = false // isLoading: loading,
) => { // error,
// refetch,
// } = useQuery({
// queryKey: ["regularizedList", projectId],
// queryFn: async () => {
// const response = await AttendanceRepository.getRegularizeList(projectId);
// return response.data;
// },
// enabled: !!projectId,
// onError: (error) => {
// showToast(error.message || "Error while fetching Regularization Requests", "error");
// },
// });
// return {
// regularizes,
// loading,
// error,
// refetch,
// };
// };
export const useRegularizationRequests = (projectId, organizationId, IncludeInActive = false) => {
const dispatch = useDispatch(); const dispatch = useDispatch();
const { const {
@ -173,7 +183,7 @@ export const useRegularizationRequests = (
const response = await AttendanceRepository.getRegularizeList( const response = await AttendanceRepository.getRegularizeList(
projectId, projectId,
organizationId, organizationId,
IncludeInActive IncludeInActive,
); );
return response.data; return response.data;
}, },
@ -186,60 +196,48 @@ export const useRegularizationRequests = (
return { regularizes, loading, error, recall, isFetching }; return { regularizes, loading, error, recall, isFetching };
}; };
// -------------------Mutation-------------------------------------- // -------------------Mutation--------------------------------------
export const useMarkAttendance = () => { export const useMarkAttendance = () => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const selectedProject = useSelectedProject(); const selectedProject = useSelectedProject();
const selectedDateRange = useSelector( const selectedDateRange = useSelector((store)=>store.localVariables.defaultDateRange)
(store) => store.localVariables.attendance.defaultDateRange
);
const selectedOrganization = useSelector(
(store) => store.localVariables.attendance.SelectedOrg
);
return useMutation({ return useMutation({
mutationFn: async ({ payload, forWhichTab }) => { mutationFn: async ({payload,forWhichTab}) => {
const res = await AttendanceRepository.markAttendance(payload); const res = await AttendanceRepository.markAttendance(payload);
return res.data; return res.data;
}, },
onSuccess: (data, variables) => { onSuccess: (data,variables) => {
if (variables.forWhichTab == 1) { if(variables.forWhichTab == 1){
queryClient.setQueryData(["attendance", selectedProject,selectedOrganization], (oldData) => { queryClient.setQueryData(["attendance",selectedProject], (oldData) => {
if (!oldData) return oldData; if (!oldData) return oldData;
return oldData.map((emp) => return oldData.map((emp) =>
emp.employeeId === data.employeeId ? { ...emp, ...data } : emp emp.employeeId === data.employeeId ? { ...emp, ...data } : emp
);
});
} else if (variables.forWhichTab == 2) {
queryClient.setQueryData(
[
"attendanceLogs",
selectedProject,
selectedDateRange.startDate,
selectedDateRange.endDate,selectedOrganization
],
(oldData) => {
if (!oldData) return oldData;
return oldData.map((record) =>
record.id === data.id ? { ...record, ...data } : record
);
}
); );
queryClient.invalidateQueries({ queryKey: ["regularizedList"] }); });
} else }else if(variables.forWhichTab == 2){
queryClient.setQueryData( // queryClient.invalidateQueries({
["regularizedList", selectedProject], // queryKey: ["attendanceLogs"],
(oldData) => { // });
if (!oldData) return oldData; queryClient.setQueryData(["attendanceLogs",selectedProject,selectedDateRange.startDate,selectedDateRange.endDate], (oldData) => {
return oldData.filter((record) => record.id !== data.id); if (!oldData) return oldData;
} return oldData.map((record) =>
), record.id === data.id ? { ...record, ...data } : record
queryClient.invalidateQueries({ queryKey: ["attendanceLogs"] }); );
});
queryClient.invalidateQueries({queryKey:["regularizedList"]})
}else(
queryClient.setQueryData(["regularizedList",selectedProject], (oldData) => {
if (!oldData) return oldData;
return oldData.filter((record) => record.id !== data.id)
}),
queryClient.invalidateQueries({queryKey:["attendanceLogs"]})
)
if (variables.forWhichTab !== 3) if(variables.forWhichTab !== 3) showToast("Attendance marked successfully", "success");
showToast("Attendance marked successfully", "success");
}, },
onError: (error) => { onError: (error) => {
showToast(error.message || "Failed to mark attendance", "error"); showToast(error.message || "Failed to mark attendance", "error");

View File

@ -10,30 +10,9 @@ import AuthRepository from "../repositories/AuthRepository.jsx";
import { useDispatch, useSelector } from "react-redux"; import { useDispatch, useSelector } from "react-redux";
import { import {
closeAuthModal, closeAuthModal,
closeModal,
openAuthModal, openAuthModal,
openModal,
toggleModal,
} from "../slices/localVariablesSlice.jsx"; } from "../slices/localVariablesSlice.jsx";
import { removeSession } from "../utils/authUtils.js"; import { removeSession } from "../utils/authUtils.js";
import { cacheProfileData } from "../slices/apiDataManager.jsx";
// ----------------------------Modal--------------------------
export const useModal = (modalType) => {
const dispatch = useDispatch();
const isOpen = useSelector(
(state) => state.localVariables.modals[modalType]?.isOpen
);
const onOpen = (data = {}) => dispatch(openModal({ modalType, data }));
const onClose = () => dispatch(closeModal({ modalType }));
const onToggle = () => dispatch(toggleModal({ modalType }));
return { isOpen, onOpen, onClose, onToggle };
};
// -------------------APIHook-------------------------------------
export const useTenants = () => { export const useTenants = () => {
return useQuery({ return useQuery({
@ -83,34 +62,26 @@ export const useAuthModal = () => {
}; };
}; };
export const useLogout = () => { export const useLogout = () => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const naviget = useNavigate()
const dispatch = useDispatch()
return useMutation({ return useMutation({
mutationFn: async () => { mutationFn: async () => {
let payload = { let payload = { refreshToken: localStorage.getItem("refreshToken") || sessionStorage.getItem("refreshToken") };
refreshToken:
localStorage.getItem("refreshToken") ||
sessionStorage.getItem("refreshToken"),
};
return await AuthRepository.logout(payload); return await AuthRepository.logout(payload);
}, },
onSuccess: (data) => { onSuccess: (data) => {
queryClient.clear() removeSession()
removeSession();
dispatch(cacheProfileData(null))
// window.location.href = "/auth/login"; window.location.href = "/auth/login";
naviget("/auth/login",{replace:true})
if (onSuccessCallBack) onSuccessCallBack(); if (onSuccessCallBack) onSuccessCallBack();
}, },
onError: (error) => { onError: (error) => {
showToast(error.message || "Error while creating project", "error"); showToast(error.message || "Error while creating project", "error");
removeSession(); removeSession()
}, },
}); });
}; };

View File

@ -548,7 +548,6 @@ export const useUpdateNote = (onSuccessCallBack) => {
mutationFn: async ({ noteId, notePayload }) => mutationFn: async ({ noteId, notePayload }) =>
await DirectoryRepository.UpdateNote(noteId, notePayload), await DirectoryRepository.UpdateNote(noteId, notePayload),
onSuccess: (_, variables) => { onSuccess: (_, variables) => {
queryClient.invalidateQueries({ queryKey: ["Contact"] });
queryClient.invalidateQueries({ queryKey: ["Notes"] }); queryClient.invalidateQueries({ queryKey: ["Notes"] });
queryClient.invalidateQueries({ queryKey: ["ContactNotes"] }); queryClient.invalidateQueries({ queryKey: ["ContactNotes"] });
showToast("Note updated Successfully", "success"); showToast("Note updated Successfully", "success");

View File

@ -12,14 +12,14 @@ import { queryClient } from "../layouts/AuthLayout";
// Query --------------------------------------------------------------------------- // Query ---------------------------------------------------------------------------
export const useEmployee = (employeeId) => { export const useEmployee = (employeeId) => {
return useQuery({ return useQuery({
queryKey: ["employeeProfile", employeeId], queryKey: ["employeeProfile", employeeId],
queryFn: async () => { queryFn: async () => {
const res = await EmployeeRepository.getEmployeeProfile(employeeId); const res = await EmployeeRepository.getEmployeeProfile(employeeId)
return res.data; return res.data;
}, },
enabled: !!employeeId, enabled:!!employeeId
}); });
}; };
export const useAllEmployees = (showInactive) => { export const useAllEmployees = (showInactive) => {
@ -137,6 +137,7 @@ export const useEmployeesAllOrByProjectId = (
return res.data; return res.data;
} }
}; };
const { const {
data: employees = [], data: employees = [],
isLoading, isLoading,
@ -157,18 +158,6 @@ export const useEmployeesAllOrByProjectId = (
}; };
}; };
// New Employee get list by CureentOrganization
export const useEmployeesByOrganization = (showInactive) => {
return useQuery({
queryKey: ["employeesByOrganization", showInactive],
queryFn: async () => {
const res = await EmployeeRepository.getAllEmployeeList(showInactive);
return res.data;
},
});
};
// ManageEmployee.jsx // ManageEmployee.jsx
export const useEmployeeProfile = (employeeId) => { export const useEmployeeProfile = (employeeId) => {
const isEnabled = !!employeeId; const isEnabled = !!employeeId;
@ -195,11 +184,11 @@ export const useEmployeeProfile = (employeeId) => {
}; };
}; };
export const useEmployeesName = (projectId, search, allEmployee) => { export const useEmployeesName = (projectId, search) => {
return useQuery({ return useQuery({
queryKey: ["employees", projectId, search, allEmployee], queryKey: ["employees", projectId, search],
queryFn: async () => queryFn: async () =>
await EmployeeRepository.getEmployeeName(projectId, search, allEmployee), await EmployeeRepository.getEmployeeName(projectId, search),
staleTime: 5 * 60 * 1000, // Optional: cache for 5 minutes staleTime: 5 * 60 * 1000, // Optional: cache for 5 minutes
}); });
@ -219,6 +208,9 @@ export const useEmployeesNameByProject = (projectId) => {
// Mutation------------------------------------------------------------------ // Mutation------------------------------------------------------------------
export const useUpdateEmployee = () => { export const useUpdateEmployee = () => {
const selectedProject = useSelector( const selectedProject = useSelector(
(store) => store.localVariables.projectId (store) => store.localVariables.projectId
@ -233,7 +225,7 @@ export const useUpdateEmployee = () => {
const isAllEmployee = variables.IsAllEmployee; const isAllEmployee = variables.IsAllEmployee;
// Cache invalidation // Cache invalidation
queryClient.invalidateQueries({ queryKey: ["employeeProfile", id] }); queryClient.invalidateQueries({ queryKey: ["employeeProfile",id] });
queryClient.invalidateQueries({ queryKey: ["allEmployees"] }); queryClient.invalidateQueries({ queryKey: ["allEmployees"] });
// queryClient.invalidateQueries(['employeeProfile', id]); // queryClient.invalidateQueries(['employeeProfile', id]);
queryClient.invalidateQueries({ queryKey: ["projectEmployees"] }); queryClient.invalidateQueries({ queryKey: ["projectEmployees"] });
@ -255,6 +247,7 @@ export const useUpdateEmployee = () => {
}); });
}; };
export const useSuspendEmployee = ({ export const useSuspendEmployee = ({
setIsDeleteModalOpen, setIsDeleteModalOpen,
setemployeeLodaing, setemployeeLodaing,
@ -307,6 +300,7 @@ export const useSuspendEmployee = ({
}); });
}; };
export const useUpdateEmployeeRoles = ({ export const useUpdateEmployeeRoles = ({
onClose, onClose,
resetForm, resetForm,
@ -340,4 +334,4 @@ export const useUpdateEmployeeRoles = ({
isError: mutation.isError, isError: mutation.isError,
error: mutation.error, error: mutation.error,
}; };
}; };

View File

@ -1,52 +1,116 @@
import { useState, useCallback } from "react"; import { useState, useCallback } from "react";
// import { ImageGalleryAPI } from "../repositories/ImageGalleyRepository"; // import { ImageGalleryAPI } from "../repositories/ImageGalleyRepository";
import { ImageGalleryRepository } from "../repositories/ImageGalleryAPI"; import { ImageGalleryAPI } from "../repositories/ImageGalleryAPI";
// const PAGE_SIZE = 10;
// const useImageGallery = (selectedProjectId) => {
// const [images, setImages] = useState([]);
// const [allImagesData, setAllImagesData] = useState([]);
// const [pageNumber, setPageNumber] = useState(1);
// const [hasMore, setHasMore] = useState(true);
// const [loading, setLoading] = useState(false);
// const [loadingMore, setLoadingMore] = useState(false);
// const fetchImages = useCallback(async (page = 1, filters = {}, reset = false) => {
// if (!selectedProjectId) return;
// try {
// if (page === 1) {
// setLoading(true);
// } else {
// setLoadingMore(true);
// }
// const res = await ImageGalleryAPI.ImagesGet(
// selectedProjectId,
// filters,
// page,
// PAGE_SIZE
// );
// const newBatches = res.data || [];
// const receivedCount = newBatches.length;
// setImages((prev) => {
// if (page === 1 || reset) return newBatches;
// const uniqueNew = newBatches.filter(
// (batch) => !prev.some((b) => b.batchId === batch.batchId)
// );
// return [...prev, ...uniqueNew];
// });
// setAllImagesData((prev) => {
// if (page === 1 || reset) return newBatches;
// const uniqueAll = newBatches.filter(
// (batch) => !prev.some((b) => b.batchId === batch.batchId)
// );
// return [...prev, ...uniqueAll];
// });
// setHasMore(receivedCount === PAGE_SIZE);
// } catch (error) {
// console.error("Error fetching images:", error);
// if (page === 1) {
// setImages([]);
// setAllImagesData([]);
// }
// setHasMore(false);
// } finally {
// setLoading(false);
// setLoadingMore(false);
// }
// }, [selectedProjectId]);
// const resetGallery = useCallback(() => {
// setImages([]);
// setAllImagesData([]);
// setPageNumber(1);
// setHasMore(true);
// }, []);
// return {
// images,
// allImagesData,
// pageNumber,
// setPageNumber,
// hasMore,
// loading,
// loadingMore,
// fetchImages,
// resetGallery,
// };
// };
// export default useImageGallery;
import { useInfiniteQuery } from "@tanstack/react-query";
import { useInfiniteQuery, useQuery } from "@tanstack/react-query"; const PAGE_SIZE = 10;
const useImageGallery = (selectedProjectId, filters) => {
const hasFilters = filters && Object.values(filters).some(
value => Array.isArray(value) ? value.length > 0 : value !== null && value !== ""
);
const cleanFilter = (filter) => { return useInfiniteQuery({
const cleaned = { ...filter }; queryKey: ["imageGallery", selectedProjectId, hasFilters ? filters : null],
["buildingIds", "floorIds", "workAreaIds", "activityIds","workCategoryIds","uploadedByIds","serviceIds"].forEach((key) => {
if (Array.isArray(cleaned[key]) && cleaned[key].length === 0) {
delete cleaned[key];
}
});
return cleaned;
};;
const useImageGallery = (selectedProjectId,pageNumber, pageSize, filters) => {
return useQuery({
queryKey: ["imageGallery", selectedProjectId, pageNumber, pageSize,filters],
enabled: !!selectedProjectId, enabled: !!selectedProjectId,
getNextPageParam: (lastPage, allPages) => {
queryFn: async () => { if (!lastPage?.data?.length) return undefined;
const cleanedFilter = cleanFilter(filters) return allPages.length + 1;
const res = await ImageGalleryRepository.ImagesGet( },
queryFn: async ({ pageParam = 1 }) => {
const res = await ImageGalleryAPI.ImagesGet(
selectedProjectId, selectedProjectId,
pageNumber, hasFilters ? filters : undefined,
pageSize, pageParam,
cleanedFilter PAGE_SIZE
); );
return res.data; return res;
}, },
}); });
}; };
export default useImageGallery; export default useImageGallery;
export const useImageGalleryFilter = (project)=>{
return useQuery({
queryKey:["imageGalleryFlter",project],
queryFn:async() => {
const response = await ImageGalleryRepository.getImageGalleryFilter(project);
return response.data;
},
})
}

View File

@ -24,7 +24,7 @@ export const useOrganizationModal = () => {
dispatch( dispatch(
openOrgModal({ openOrgModal({
isOpen: true, isOpen: true,
orgData: options.hasOwnProperty("orgData") ? options.orgData : orgData, orgData: options.orgData ?? orgData ?? null,
startStep: options.startStep ?? startStep ?? 1, startStep: options.startStep ?? startStep ?? 1,
prevStep: options.prevStep ?? prevStep ?? 1, prevStep: options.prevStep ?? prevStep ?? 1,
flowType: options.flowType ?? flowType ?? "default", flowType: options.flowType ?? flowType ?? "default",
@ -138,12 +138,8 @@ export const useAssignOrgToProject = (onSuccessCallback) => {
useClient.invalidateQueries({ useClient.invalidateQueries({
queryKey: ["projectAssignedOrganiztions"], queryKey: ["projectAssignedOrganiztions"],
}); });
useClient.invalidateQueries({
queryKey: ["projectAssignedOrganiztionsName"],
});
useClient.invalidateQueries({ useClient.invalidateQueries({
queryKey: ["projectAssignedServices", projectId], queryKey: ["projectAssignedOrganization", projectId],
}); });
showToast("Organization successfully", "success"); showToast("Organization successfully", "success");
if (onSuccessCallback) onSuccessCallback(); if (onSuccessCallback) onSuccessCallback();
@ -185,8 +181,6 @@ export const useUpdateOrganization = (onSuccessCallback) => {
await OrganizationRepository.updateOrganizaion(orgId,payload), await OrganizationRepository.updateOrganizaion(orgId,payload),
onSuccess: (_, variables) => { onSuccess: (_, variables) => {
useClient.invalidateQueries({ queryKey: ["organizationList"] }); useClient.invalidateQueries({ queryKey: ["organizationList"] });
useClient.invalidateQueries({ queryKey: ["projectAssignedOrganiztionsName"] });
showToast("Organization Updated successfully", "success"); showToast("Organization Updated successfully", "success");
if (onSuccessCallback) onSuccessCallback(); if (onSuccessCallback) onSuccessCallback();
}, },

View File

@ -14,6 +14,7 @@ export const useProjectAccess = (projectId) => {
const canView = useHasUserPermission(VIEW_PROJECTS); const canView = useHasUserPermission(VIEW_PROJECTS);
const loading = isLoading || !isFetched; const loading = isLoading || !isFetched;
debugger
useEffect(() => { useEffect(() => {
if (projectId && !loading && !canView) { if (projectId && !loading && !canView) {
showToast("You don't have permission to view project details", "warning"); showToast("You don't have permission to view project details", "warning");

View File

@ -294,21 +294,9 @@ export const useProjectAssignedOrganizations = (projectId) => {
enabled: !!projectId, enabled: !!projectId,
}); });
}; };
export const useProjectAssignedOrganizationsName = (projectId) => {
return useQuery({
queryKey: ["projectAssignedOrganiztionsName", projectId],
queryFn: async () => {
const resp = await ProjectRepository.getProjectAssignedOrganizationsName(
projectId
);
return resp.data;
},
enabled: !!projectId,
});
};
export const useProjectAssignedServices = (projectId) => { export const useProjectAssignedServices = (projectId) => {
return useQuery({ return useQuery({
queryKey: ["projectAssignedServices", projectId], queryKey: ["projectAssignedOrganization", projectId],
queryFn: async () => { queryFn: async () => {
const resp = await ProjectRepository.getProjectAssignedServices( const resp = await ProjectRepository.getProjectAssignedServices(
projectId projectId

View File

@ -8,30 +8,11 @@ import { useSelector } from "react-redux";
// ---------Query--------------------------------- // ---------Query---------------------------------
export const useTaskList = (projectId, pageSize, pageNumber, serviceId, filter) => {
const cleanFilter = (filter) => {
const cleaned = { ...filter };
["buildingIds", "floorIds", "activityIds"].forEach((key) => {
if (Array.isArray(cleaned[key]) && cleaned[key].length === 0) {
delete cleaned[key];
}
});
return cleaned;
};
export const useTaskList = (
projectId,
pageSize,
pageNumber,
serviceId,
filter
) => {
return useQuery({ return useQuery({
queryKey: ["taskList", projectId, pageSize, pageNumber, serviceId, filter], queryKey: ["taskList", projectId, pageSize, pageNumber, serviceId, filter],
queryFn: async () => { queryFn: async () => {
const cleanedFilter = cleanFilter(filter)
const response = await TasksRepository.getTaskList( const response = await TasksRepository.getTaskList(
projectId, projectId,
pageSize, pageSize,
@ -41,21 +22,11 @@ export const useTaskList = (
); );
return response.data; return response.data;
}, },
enabled: !!projectId,
});
};
export const useTaskFilter = (projectId) => {
return useQuery({
queryKey: ["taskFilter", projectId],
queryFn: async () => {
const resp = await TasksRepository.getTaskListFilter(projectId);
return resp.data;
},
enabled:!!projectId enabled:!!projectId
}); });
}; };
export const useTaskById = (TaskId) => { export const useTaskById = (TaskId) => {
const { const {
data: Task = null, data: Task = null,

View File

@ -5,13 +5,19 @@ import App from './App.tsx'
import { Provider } from 'react-redux'; import { Provider } from 'react-redux';
import { store } from './store/store'; import { store } from './store/store';
import { ChangePasswordProvider } from './components/Context/ChangePasswordContext.jsx';
import { ModalProvider1 } from './pages/Gallary/ModalContext.jsx';
createRoot(document.getElementById('root')!).render( createRoot(document.getElementById('root')!).render(
// <StrictMode> // <StrictMode>
// <MasterDataProvider> // <MasterDataProvider>
<Provider store={ store }> <Provider store={ store }>
<ChangePasswordProvider >
<ModalProvider1>
<App /> <App />
</ModalProvider1>
</ChangePasswordProvider>
</Provider> </Provider>
// </StrictMode>, // </StrictMode>,

View File

@ -12,14 +12,11 @@ import Attendance from "../../components/Activities/Attendance";
import Regularization from "../../components/Activities/Regularization"; import Regularization from "../../components/Activities/Regularization";
import { useAttendance } from "../../hooks/useAttendance"; import { useAttendance } from "../../hooks/useAttendance";
import { useDispatch, useSelector } from "react-redux"; import { useDispatch, useSelector } from "react-redux";
import { setOrganization, setProjectId } from "../../slices/localVariablesSlice"; import { setProjectId } from "../../slices/localVariablesSlice";
import { useHasUserPermission } from "../../hooks/useHasUserPermission"; import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { REGULARIZE_ATTENDANCE } from "../../utils/constants"; import { REGULARIZE_ATTENDANCE } from "../../utils/constants";
import eventBus from "../../services/eventBus"; import eventBus from "../../services/eventBus";
import { import { useProjectAssignedOrganizations, useProjectName } from "../../hooks/useProjects";
useProjectAssignedOrganizationsName,
useProjectName,
} from "../../hooks/useProjects";
import GlobalModel from "../../components/common/GlobalModel"; import GlobalModel from "../../components/common/GlobalModel";
import CheckCheckOutmodel from "../../components/Activities/CheckCheckOutForm"; import CheckCheckOutmodel from "../../components/Activities/CheckCheckOutForm";
import AttendLogs from "../../components/Activities/AttendLogs"; import AttendLogs from "../../components/Activities/AttendLogs";
@ -47,7 +44,7 @@ const AttendancePage = () => {
}); });
const { data: organizations = [], isLoading: orgLoading } = const { data: organizations = [], isLoading: orgLoading } =
useProjectAssignedOrganizationsName(selectedProject); useProjectAssignedOrganizations(selectedProject);
const [formData, setFormData] = useState({ const [formData, setFormData] = useState({
markTime: "", markTime: "",
@ -59,8 +56,7 @@ const AttendancePage = () => {
if (selectedProject == null) { if (selectedProject == null) {
dispatch(setProjectId(projectNames[0]?.id)); dispatch(setProjectId(projectNames[0]?.id));
} }
dispatch(setOrganization(appliedFilters?.selectedOrganization)) }, []);
}, [appliedFilters?.selectedOrganization]);
const getRole = (roleId) => { const getRole = (roleId) => {
if (!empRoles) return "Unassigned"; if (!empRoles) return "Unassigned";
@ -105,11 +101,11 @@ const AttendancePage = () => {
{(modelConfig?.action === 0 || {(modelConfig?.action === 0 ||
modelConfig?.action === 1 || modelConfig?.action === 1 ||
modelConfig?.action === 2) && ( modelConfig?.action === 2) && (
<CheckCheckOutmodel <CheckCheckOutmodel
modeldata={modelConfig} modeldata={modelConfig}
closeModal={closeModal} closeModal={closeModal}
/> />
)} )}
{/* For view logs */} {/* For view logs */}
{modelConfig?.action === 6 && ( {modelConfig?.action === 6 && (
<AttendLogs Id={modelConfig?.id} closeModal={closeModal} /> <AttendLogs Id={modelConfig?.id} closeModal={closeModal} />
@ -131,16 +127,15 @@ const AttendancePage = () => {
<div className="nav-align-top nav-tabs-shadow "> <div className="nav-align-top nav-tabs-shadow ">
{/* Tabs */} {/* Tabs */}
<div className="nav-align-top nav-tabs-shadow bg-white border-bottom pt-5"> <div className="nav-align-top nav-tabs-shadow bg-white border-bottom pt-5">
<div className="row align-items-center g-0 mb-3 mb-md-0 mx-1 mx-sm-5"> <div className="row align-items-center g-0 mb-3 mb-md-0 mx-5">
{/* Tabs */} {/* Tabs */}
<div className="col-12 col-md"> <div className="col-12 col-md">
<ul className="nav nav-tabs" role="tablist"> <ul className="nav nav-tabs" role="tablist">
<li className="nav-item"> <li className="nav-item">
<button <button
type="button" type="button"
className={`nav-link ${ className={`nav-link ${activeTab === "all" ? "active" : ""
activeTab === "all" ? "active" : "" } fs-6`}
} fs-6`}
onClick={() => handleTabChange("all")} onClick={() => handleTabChange("all")}
data-bs-toggle="tab" data-bs-toggle="tab"
data-bs-target="#navs-top-home" data-bs-target="#navs-top-home"
@ -151,9 +146,8 @@ const AttendancePage = () => {
<li className="nav-item"> <li className="nav-item">
<button <button
type="button" type="button"
className={`nav-link ${ className={`nav-link ${activeTab === "logs" ? "active" : ""
activeTab === "logs" ? "active" : "" } fs-6`}
} fs-6`}
onClick={() => handleTabChange("logs")} onClick={() => handleTabChange("logs")}
data-bs-toggle="tab" data-bs-toggle="tab"
data-bs-target="#navs-top-profile" data-bs-target="#navs-top-profile"
@ -165,9 +159,8 @@ const AttendancePage = () => {
<li className={`nav-item ${!DoRegularized ? "d-none" : ""}`}> <li className={`nav-item ${!DoRegularized ? "d-none" : ""}`}>
<button <button
type="button" type="button"
className={`nav-link ${ className={`nav-link ${activeTab === "regularization" ? "active" : ""
activeTab === "regularization" ? "active" : "" } fs-6`}
} fs-6`}
onClick={() => handleTabChange("regularization")} onClick={() => handleTabChange("regularization")}
data-bs-toggle="tab" data-bs-toggle="tab"
data-bs-target="#navs-top-messages" data-bs-target="#navs-top-messages"
@ -181,10 +174,9 @@ const AttendancePage = () => {
{/* Search + Organization filter */} {/* Search + Organization filter */}
<div className="col-12 col-md-auto mt-2 mt-md-0 ms-md-auto d-flex gap-2 align-items-center"> <div className="col-12 col-md-auto mt-2 mt-md-0 ms-md-auto d-flex gap-2 align-items-center">
{/* Organization Dropdown */} {/* Organization Dropdown */}
<div className="row"> <select
<div className="col-12 col-sm-6 mb-2 mb-sm-0">
<select
className="form-select form-select-sm" className="form-select form-select-sm"
style={{ minWidth: "180px" }}
value={appliedFilters.selectedOrganization} value={appliedFilters.selectedOrganization}
onChange={(e) => onChange={(e) =>
setAppliedFilters((prev) => ({ setAppliedFilters((prev) => ({
@ -195,28 +187,25 @@ const AttendancePage = () => {
disabled={orgLoading} disabled={orgLoading}
> >
<option value="">All Organizations</option> <option value="">All Organizations</option>
{organizations?.map((org, ind) => ( {organizations?.map((org) => (
<option key={`${org.id}-${ind}`} value={org.id}> <option key={org.id} value={org.id}>
{org.name} {org.name}
</option> </option>
))} ))}
</select> </select>
</div>
<div className="col-12 col-sm-6"> {/* Search Input */}
{/* Search Input */}
<input <input
type="text" type="text"
className="form-control form-control-sm" className="form-control form-control-sm"
placeholder="Search Employee..." placeholder="Search Employee..."
value={searchTerm} value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)} onChange={(e) => setSearchTerm(e.target.value)}
style={{ minWidth: "200px" }}
/> />
</div>
</div>
</div> </div>
</div> </div>
</div> </div>

View File

@ -8,8 +8,6 @@ import ReportTask from "../../components/Activities/ReportTask";
import TaskReportFilterPanel from "../../components/DailyProgressRport/TaskReportFilterPanel"; import TaskReportFilterPanel from "../../components/DailyProgressRport/TaskReportFilterPanel";
import { useFab } from "../../Context/FabContext"; import { useFab } from "../../Context/FabContext";
import SubTask from "../../components/Activities/SubTask"; import SubTask from "../../components/Activities/SubTask";
import { useProjectAssignedServices } from "../../hooks/useProjects";
import { useSelectedProject } from "../../slices/apiDataManager";
const DailyProgrssContext = createContext(); const DailyProgrssContext = createContext();
export const useDailyProgrssContext = () => { export const useDailyProgrssContext = () => {
@ -23,11 +21,10 @@ export const useDailyProgrssContext = () => {
}; };
const DailyProgrssReport = () => { const DailyProgrssReport = () => {
const selectedProject = useSelectedProject()
const [service, setService] = useState(""); const [service, setService] = useState("");
const [filter,setFilter] = useState('') const [filter,setFilter] = useState('')
const { setOffcanvasContent, setShowTrigger } = useFab(); const { setOffcanvasContent, setShowTrigger } = useFab();
const { data, isLoading, isError, error } = useProjectAssignedServices(selectedProject); const { data, isLoading, isError, error } = useServices();
const [modal, setModal] = useState({ type: null, data: null }); const [modal, setModal] = useState({ type: null, data: null });
@ -89,7 +86,7 @@ const DailyProgrssReport = () => {
/> />
<div className="card card-fullscreen p-5"> <div className="card card-fullscreen p-5">
{data?.length > 0 && (<div className="col-sm-4 col-md-3 col-12"> <div className="col-sm-4 col-md-3 col-12">
<select <select
className="form-select form-select-sm" className="form-select form-select-sm"
value={service ?? ""} value={service ?? ""}
@ -102,7 +99,7 @@ const DailyProgrssReport = () => {
<option value=""> <option value="">
All Services All Services
</option> </option>
{data?.map((service) => ( {data?.data?.map((service) => (
<option key={service.id} value={service.id}> <option key={service.id} value={service.id}>
{service.name} {service.name}
</option> </option>
@ -110,7 +107,7 @@ const DailyProgrssReport = () => {
</> </>
)} )}
</select> </select>
</div>)} </div>
<div> <div>
<TaskReportList /> <TaskReportList />
</div> </div>

View File

@ -60,12 +60,12 @@ const ContactFilterPanel = ({ onApply, clearFilter }) => {
<div className="d-flex justify-content-end py-3 gap-2"> <div className="d-flex justify-content-end py-3 gap-2">
<button <button
type="button" type="button"
className="btn btn-label-secondary btn-sm" className="btn btn-label-secondary btn-xs"
onClick={handleClose} onClick={handleClose}
> >
Clear Clear
</button> </button>
<button type="submit" className="btn btn-primary btn-sm"> <button type="submit" className="btn btn-primary btn-xs">
Apply Apply
</button> </button>
</div> </div>

View File

@ -162,33 +162,29 @@ export default function DirectoryPage({ IsPage = true, projectId = null }) {
</ul> </ul>
</div> </div>
<div className="mb-1 px-md-2 px-0 py-3"> <div className="mb-1 px-2 py-3">
<div className="row"> <div className="d-flex align-items-center justify-content-between">
<div className="col-12 col-md-10 mb-2"> <div className="d-flex align-items-center gap-3">
{activeTab === "notes" && ( {activeTab === "notes" && (
<div className="col-8 col-md-3"> <input
<input
type="search" type="search"
className="form-control form-control-sm" className="form-control form-control-sm"
placeholder="Search notes..." placeholder="Search notes..."
value={searchNote} value={searchNote}
onChange={(e) => setSearchNote(e.target.value)} onChange={(e) => setSearchNote(e.target.value)}
/> />
</div>
)} )}
{activeTab === "contacts" && ( {activeTab === "contacts" && (
<div className="d-flex align-items-center gap-3"> <div className="d-flex align-items-center gap-3">
<div className="col-12 col-md-8 d-flex flex-row gap-2"> <div className="d-flex gap-2 align-items-center">
<div className="col-7 col-md-4"> <input
<input
type="search" type="search"
className="form-control form-control-sm" className="form-control form-control-sm"
placeholder="Search contacts..." placeholder="Search contacts..."
value={searchContact} value={searchContact}
onChange={(e) => setsearchContact(e.target.value)} onChange={(e) => setsearchContact(e.target.value)}
/> />
</div>
<button <button
className={`btn btn-sm p-1 ${ className={`btn btn-sm p-1 ${
!gridView ? "btn-primary" : "btn-outline-primary" !gridView ? "btn-primary" : "btn-outline-primary"
@ -206,7 +202,9 @@ export default function DirectoryPage({ IsPage = true, projectId = null }) {
> >
<i className="bx bx-grid-alt"></i> <i className="bx bx-grid-alt"></i>
</button> </button>
<div className="form-check form-switch d-flex align-items-center d-none d-md-flex"> </div>
<div className="form-check form-switch d-flex align-items-center">
<input <input
type="checkbox" type="checkbox"
className="form-check-input" className="form-check-input"
@ -222,30 +220,11 @@ export default function DirectoryPage({ IsPage = true, projectId = null }) {
{showActive ? "Active" : "Inactive"} Contacts {showActive ? "Active" : "Inactive"} Contacts
</label> </label>
</div> </div>
</div>
</div> </div>
)} )}
</div> </div>
<div className="col-12 col-md-2 d-flex justify-content-end align-items-center gap-2">
<div className={`form-check form-switch d-flex align-items-center ${activeTab === "contacts" ? " d-flex d-md-none m-0":"d-none" }`}> <div className="btn-group">
<input
type="checkbox"
className="form-check-input"
role="switch"
id="inactiveEmployeesCheckbox"
checked={showActive}
onChange={(e) => setShowActive(e.target.checked)}
/>
<label
className="form-check-label ms-2"
htmlFor="inactiveEmployeesCheckbox"
>
{showActive ? "Active" : "Inactive"} Contacts
</label>
</div>
<div className=" btn-group">
<button <button
className="btn btn-sm btn-label-secondary dropdown-toggle" className="btn btn-sm btn-label-secondary dropdown-toggle"
type="button" type="button"
@ -265,8 +244,6 @@ export default function DirectoryPage({ IsPage = true, projectId = null }) {
</li> </li>
</ul> </ul>
</div> </div>
</div>
</div> </div>
</div> </div>
</div> </div>

View File

@ -60,12 +60,12 @@ const NoteFilterPanel = ({ onApply, clearFilter }) => {
<div className="d-flex justify-content-end py-3 gap-2"> <div className="d-flex justify-content-end py-3 gap-2">
<button <button
type="button" type="button"
className="btn btn-label-secondary btn-sm" className="btn btn-label-secondary btn-xs"
onClick={handleClose} onClick={handleClose}
> >
Clear Clear
</button> </button>
<button type="submit" className="btn btn-primary btn-sm"> <button type="submit" className="btn btn-primary btn-xs">
Apply Apply
</button> </button>
</div> </div>

View File

@ -0,0 +1,499 @@
import React, { useState, useEffect, useRef, useCallback } from "react";
import "./ImageGallery.css";
import moment from "moment";
import { useDispatch, useSelector } from "react-redux";
import { useModal } from "./ModalContext";
import ImagePop from "./ImagePop";
import Avatar from "../../components/common/Avatar";
import DateRangePicker from "../../components/common/DateRangePicker";
import eventBus from "../../services/eventBus";
import Breadcrumb from "../../components/common/Breadcrumb";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
import useImageGallery from "../../hooks/useImageGallery";
import { useProjectName } from "../../hooks/useProjects";
import { setProjectId } from "../../slices/localVariablesSlice";
const SCROLL_THRESHOLD = 5;
const ImageGallery = () => {
const selectedProjectId = useSelector(
(store) => store.localVariables.projectId
);
const dispatch = useDispatch();
const { projectNames } = useProjectName();
// Auto-select a project on mount
useEffect(() => {
if (!selectedProjectId && projectNames?.length) {
dispatch(setProjectId(projectNames[0].id));
}
}, [selectedProjectId, projectNames, dispatch]);
// Filter states
const [selectedFilters, setSelectedFilters] = useState({
building: [],
floor: [],
activity: [],
uploadedBy: [],
workCategory: [],
workArea: [],
startDate: "",
endDate: "",
});
const [appliedFilters, setAppliedFilters] = useState({
buildingIds: null,
floorIds: null,
activityIds: null,
uploadedByIds: null,
workCategoryIds: null,
workAreaIds: null,
startDate: null,
endDate: null,
});
const [collapsedFilters, setCollapsedFilters] = useState({
dateRange: false,
building: false,
floor: false,
activity: false,
uploadedBy: false,
workCategory: false,
workArea: false,
});
const [isFilterPanelOpen, setIsFilterPanelOpen] = useState(false);
const [hoveredImage, setHoveredImage] = useState(null);
const imageGroupRefs = useRef({});
const loaderRef = useRef(null);
const filterPanelRef = useRef(null);
const filterButtonRef = useRef(null);
const { openModal } = useModal();
const {
data,
fetchNextPage,
hasNextPage,
isLoading,
isFetchingNextPage,
refetch,
} = useImageGallery(selectedProjectId, appliedFilters);
const images = data?.pages.flatMap((page) => page.data) || [];
useEffect(() => {
const handleClick = (e) => {
if (
filterPanelRef.current &&
!filterPanelRef.current.contains(e.target) &&
filterButtonRef.current &&
!filterButtonRef.current.contains(e.target)
) {
setIsFilterPanelOpen(false);
}
};
document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, []);
useEffect(() => {
if (selectedProjectId) refetch();
}, [selectedProjectId, appliedFilters, refetch]);
useEffect(() => {
const handler = (data) => {
if (data.projectId === selectedProjectId) refetch();
};
eventBus.on("image_gallery", handler);
return () => eventBus.off("image_gallery", handler);
}, [selectedProjectId, refetch]);
useEffect(() => {
if (!loaderRef.current) return;
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting && hasNextPage && !isFetchingNextPage && !isLoading) {
fetchNextPage();
}
},
{ rootMargin: "200px", threshold: 0.1 }
);
observer.observe(loaderRef.current);
return () => {
if (loaderRef.current) {
observer.unobserve(loaderRef.current);
}
};
}, [hasNextPage, isFetchingNextPage, isLoading, fetchNextPage]);
// Utility: derive filter options
const getUniqueValues = useCallback(
(idKey, nameKey) => {
const m = new Map();
images.forEach((batch) => {
const id = idKey === "floorIds" ? batch.floorIds : batch[idKey];
if (id && batch[nameKey] && !m.has(id)) {
m.set(id, batch[nameKey]);
}
});
return [...m.entries()].sort((a, b) => a[1].localeCompare(b[1]));
},
[images]
);
const getUploadedBy = useCallback(() => {
const m = new Map();
images.forEach((batch) => {
batch.documents.forEach((doc) => {
const name = `${doc.uploadedBy?.firstName || ""} ${
doc.uploadedBy?.lastName || ""
}`.trim();
if (doc.uploadedBy?.id && name && !m.has(doc.uploadedBy.id)) {
m.set(doc.uploadedBy.id, name);
}
});
});
return [...m.entries()].sort((a, b) => a[1].localeCompare(b[1]));
}, [images]);
const buildings = getUniqueValues("buildingId", "buildingName");
const floors = getUniqueValues("floorIds", "floorName");
const activities = getUniqueValues("activityId", "activityName");
const workAreas = getUniqueValues("workAreaId", "workAreaName");
const workCategories = getUniqueValues("workCategoryId", "workCategoryName");
const uploadedByUsers = getUploadedBy();
const toggleFilter = useCallback((type, id, name) => {
setSelectedFilters((prev) => {
const arr = prev[type];
const exists = arr.some(([x]) => x === id);
const updated = exists
? arr.filter(([x]) => x !== id)
: [...arr, [id, name]];
return { ...prev, [type]: updated };
});
}, []);
const setDateRange = useCallback(({ startDate, endDate }) => {
setSelectedFilters((prev) => ({
...prev,
startDate: startDate || "",
endDate: endDate || "",
}));
}, []);
const toggleCollapse = useCallback((type) => {
setCollapsedFilters((prev) => ({ ...prev, [type]: !prev[type] }));
}, []);
const handleApplyFilters = useCallback(() => {
const payload = {
buildingIds: selectedFilters.building.map(([x]) => x) || null,
floorIds: selectedFilters.floor.map(([x]) => x) || null,
activityIds: selectedFilters.activity.map(([x]) => x) || null,
uploadedByIds: selectedFilters.uploadedBy.map(([x]) => x) || null,
workCategoryIds: selectedFilters.workCategory.map(([x]) => x) || null,
workAreaIds: selectedFilters.workArea.map(([x]) => x) || null,
startDate: selectedFilters.startDate || null,
endDate: selectedFilters.endDate || null,
};
const changed = Object.keys(payload).some((key) => {
const oldVal = appliedFilters[key],
newVal = payload[key];
return Array.isArray(oldVal)
? oldVal.length !== newVal.length ||
oldVal.some((x) => !newVal.includes(x))
: oldVal !== newVal;
});
if (changed) setAppliedFilters(payload);
}, [selectedFilters, appliedFilters]);
const handleClear = useCallback(() => {
setSelectedFilters({
building: [],
floor: [],
activity: [],
uploadedBy: [],
workCategory: [],
workArea: [],
startDate: "",
endDate: "",
});
setAppliedFilters({
buildingIds: null,
floorIds: null,
activityIds: null,
uploadedByIds: null,
workCategoryIds: null,
workAreaIds: null,
startDate: null,
endDate: null,
});
}, []);
const scrollLeft = useCallback(
(key) =>
imageGroupRefs.current[key]?.scrollBy({ left: -200, behavior: "smooth" }),
[]
);
const scrollRight = useCallback(
(key) =>
imageGroupRefs.current[key]?.scrollBy({ left: 200, behavior: "smooth" }),
[]
);
const renderCategory = (label, items, type) => (
<div
className={`dropdown my-2 ${collapsedFilters[type] ? "collapsed" : ""}`}
>
<div
className="dropdown-header bg-label-primary"
onClick={() => toggleCollapse(type)}
>
<strong>{label}</strong>
<div className="header-controls">
{((type === "dateRange" &&
(selectedFilters.startDate || selectedFilters.endDate)) ||
(type !== "dateRange" && selectedFilters[type]?.length > 0)) && (
<button
className="clear-button"
onClick={(e) => {
e.stopPropagation();
setSelectedFilters((prev) => ({
...prev,
[type]: type === "dateRange" ? "" : [],
...(type === "dateRange" && { startDate: "", endDate: "" }),
}));
}}
>
Clear
</button>
)}
<span className="collapse-icon">
{collapsedFilters[type] ? "+" : "-"}
</span>
</div>
</div>
{!collapsedFilters[type] && (
<div className="dropdown-content">
{type === "dateRange" ? (
<DateRangePicker
onRangeChange={setDateRange}
endDateMode="today"
startDate={selectedFilters.startDate}
endDate={selectedFilters.endDate}
/>
) : (
items.map(([id, name]) => (
<label key={id}>
<input
type="checkbox"
checked={selectedFilters[type].some(([x]) => x === id)}
onChange={() => toggleFilter(type, id, name)}
/>
{name}
</label>
))
)}
</div>
)}
</div>
);
return (
<div
className={`gallery-container container-fluid ${
isFilterPanelOpen ? "filter-panel-open-end" : ""
}`}
>
<Breadcrumb data={[{ label: "Home", link: "/" }, { label: "Gallery" }]} />
<div className="main-content">
<button
className={`filter-button btn-primary ${
isFilterPanelOpen ? "closed-icon" : ""
}`}
onClick={() => setIsFilterPanelOpen((p) => !p)}
ref={filterButtonRef}
>
{isFilterPanelOpen ? (
<i className="fa-solid fa-times fs-5" />
) : (
<i className="bx bx-slider-alt ms-1" />
)}
</button>
<div className="activity-section">
{isLoading ? (
<div className="text-center">
<p>Loading...</p>
</div>
) : images.length ? (
images.map((batch) => {
const doc = batch.documents[0];
const userName = `${doc.uploadedBy?.firstName || ""} ${
doc.uploadedBy?.lastName || ""
}`.trim();
const date = formatUTCToLocalTime(doc.uploadedAt);
const hasArrows = batch.documents.length > SCROLL_THRESHOLD;
return (
<div key={batch.batchId} className="grouped-section">
<div className="group-heading">
{/* Uploader Info */}
<div className="d-flex align-items-center mb-1">
<Avatar
size="xs"
firstName={doc.uploadedBy?.firstName}
lastName={doc.uploadedBy?.lastName}
className="me-2"
/>
<div className="d-flex flex-column align-items-start">
<strong className="user-name-text">{userName}</strong>
<span className="text-muted small">{date}</span>
</div>
</div>
{/* Location Info */}
<div className="location-line text-secondary">
<div className="d-flex align-items-center flex-wrap gap-1 text-secondary">
{" "}
<span className="d-flex align-items-center">
<span>{batch.buildingName}</span>
<i className="bx bx-chevron-right " />
</span>
<span className="d-flex align-items-center">
<span>{batch.floorName}</span>
<i className="bx bx-chevron-right m" />
</span>
<span className="d-flex align-items-center ">
<span>{batch.workAreaName || "Unknown"}</span>
<i className="bx bx-chevron-right " />
<span>{batch.activityName}</span>
</span>
</div>
{batch.workCategoryName && (
<span className="badge bg-label-primary ms-2">
{batch.workCategoryName}
</span>
)}
</div>
</div>
<div className="image-group-wrapper">
{hasArrows && (
<button
className="scroll-arrow left-arrow"
onClick={() => scrollLeft(batch.batchId)}
>
</button>
)}
<div
className="image-group-horizontal"
ref={(el) => (imageGroupRefs.current[batch.batchId] = el)}
>
{batch.documents.map((d, i) => {
const hoverDate = moment(d.uploadedAt).format(
"DD MMMM, YYYY"
);
const hoverTime = moment(d.uploadedAt).format(
"hh:mm A"
);
return (
<div
key={d.id}
className="image-card"
onClick={() =>
openModal(
<ImagePop batch={batch} initialIndex={i} />
)
}
onMouseEnter={() => setHoveredImage(d)}
onMouseLeave={() => setHoveredImage(null)}
>
<div className="image-wrapper">
<img src={d.url} alt={`Image ${i + 1}`} />
</div>
{hoveredImage === d && (
<div className="image-hover-description">
<p>
<strong>Date:</strong> {hoverDate}
</p>
<p>
<strong>Time:</strong> {hoverTime}
</p>
<p>
<strong>Activity:</strong>{" "}
{batch.activityName}
</p>
</div>
)}
</div>
);
})}
</div>
{hasArrows && (
<button
className="scroll-arrow right-arrow"
onClick={() => scrollRight(batch.batchId)}
>
<i className="bx bx-chevron-right"></i>
</button>
)}
</div>
</div>
);
})
) : (
<p className="text-center text-muted mt-5">
No images match the selected filters.
</p>
)}
<div ref={loaderRef}>
{isFetchingNextPage && hasNextPage && <p>Loading...</p>}
{!hasNextPage && !isLoading && images.length > 0 && (
<p className="text-muted">
You've reached the end of the images.
</p>
)}
</div>
</div>
</div>
<div
className={`offcanvas offcanvas-end ${isFilterPanelOpen ? "show" : ""}`}
ref={filterPanelRef}
>
<div className="offcanvas-header">
<h5>Filters</h5>
<button
className="btn-close"
onClick={() => setIsFilterPanelOpen(false)}
/>
</div>
<div className="filter-actions mt-auto mx-2">
<button className="btn btn-secondary btn-xs" onClick={handleClear}>
Clear All
</button>
<button
className="btn btn-primary btn-xs"
onClick={handleApplyFilters}
>
Apply Filters
</button>
</div>
<div className="offcanvas-body d-flex flex-column">
{renderCategory("Date Range", [], "dateRange")}
{renderCategory("Building", buildings, "building")}
{renderCategory("Floor", floors, "floor")}
{renderCategory("Work Area", workAreas, "workArea")}
{renderCategory("Activity", activities, "activity")}
{renderCategory("Uploaded By (User)", uploadedByUsers, "uploadedBy")}
{renderCategory("Work Category", workCategories, "workCategory")}
</div>
</div>
</div>
);
};
export default ImageGallery;

View File

@ -1,126 +0,0 @@
import React, {
useState,
useEffect,
useRef,
useContext,
createContext,
} from "react";
import { useDispatch, useSelector } from "react-redux";
import moment from "moment";
import eventBus from "../../services/eventBus";
import Breadcrumb from "../../components/common/Breadcrumb";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
import useImageGallery from "../../hooks/useImageGallery";
import {
useProjectAssignedServices,
useProjectName,
} from "../../hooks/useProjects";
import { setProjectId } from "../../slices/localVariablesSlice";
import ImageGalleryListView from "../../components/gallary/ImageGalleryListView";
import "../../components/gallary/ImageGallery.css";
import { useSelectedProject } from "../../slices/apiDataManager";
import GlobalModel from "../../components/common/GlobalModel";
import ViewGallery from "../../components/gallary/ViewGallery";
import { useFab } from "../../Context/FabContext";
import GalleryFilterPanel from "../../components/gallary/GalleryFilterPanel";
const GalleryContext = createContext();
export const useGalleryContext = () => {
let context = useContext(GalleryContext);
if (!context) {
throw new Error("Error");
}
return context;
};
const ImageGalleryPage = () => {
const [filter,setFilter] = useState()
const selectedProjectId = useSelectedProject();
const { projectNames } = useProjectName();
const [openGallery, setOpenGallery] = useState({ isOpen: false, data: null });
const { data: assignedServices = [], isLoading } =
useProjectAssignedServices(selectedProjectId);
const [selectedService, setSelectedService] = useState("");
const handleServiceChange = (e) => {
setSelectedService(e.target.value);
};
const contextMessager = {
setOpenGallery,
};
const { setOffcanvasContent, setShowTrigger } = useFab();
useEffect(()=>{
setShowTrigger(true);
setOffcanvasContent("Gallery Filter",<GalleryFilterPanel onApply={setFilter}/>);
return ()=>{
setOffcanvasContent("",null)
setShowTrigger(false);
}
},[])
return (
<GalleryContext.Provider value={contextMessager}>
<div className="container-fluid">
<Breadcrumb
data={[{ label: "Home", link: "/" }, { label: "Gallery" }]}
/>
<div className="card page-min-h p-2">
{/* {selectedProjectId && (
<div className="d-flex flex-row w-20 pb-2">
{!isLoading && assignedServices?.length === 0 ? (
<span className="badge bg-label-secondary">
Not service assiged yet
</span>
) : (
<select className="form-select form-select-sm">
<option>Select Service</option>
{isLoading ? (
<option>Loading...</option>
) : assignedServices.length === 1 ? (
<span className="badge bg-label-secondary">
{assignedServices[0].name}
</span>
) : (
assignedServices?.map((service) => (
<option key={service.id} value={service?.id}>
{service?.name}
</option>
))
)}
</select>
)}
</div>
)} */}
<ImageGalleryListView filter={filter}/>
</div>
{openGallery?.isOpen && (
<GlobalModel
isOpen={openGallery?.isOpen}
closeModal={() => setOpenGallery({ isOpen: false, data: null })}
>
<ViewGallery
batch={openGallery?.data?.data}
index={openGallery?.data?.index}
/>
</GlobalModel>
)}
</div>
</GalleryContext.Provider>
);
};
export default ImageGalleryPage;

View File

@ -0,0 +1,111 @@
import React, { useState, useEffect } from "react";
import "./ImagePop.css";
import { useModal } from "./ModalContext";
import moment from "moment";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
const ImagePop = ({ batch, initialIndex = 0 }) => {
const { closeModal } = useModal();
const [currentIndex, setCurrentIndex] = useState(initialIndex);
// Effect to update currentIndex if the initialIndex prop changes
useEffect(() => {
setCurrentIndex(initialIndex);
}, [initialIndex, batch]);
// If no batch or documents are provided, don't render
if (!batch || !batch.documents || batch.documents.length === 0) return null;
// Get the current image document from the batch's documents array
const image = batch.documents[currentIndex];
// Fallback if for some reason the image at the current index doesn't exist
if (!image) return null;
// Format details for display from the individual image document
const fullName = `${image.uploadedBy?.firstName || ""} ${
image.uploadedBy?.lastName || ""
}`.trim();
const date = formatUTCToLocalTime(image.uploadedAt);
// Location and category details from the 'batch' object (as previously corrected)
const buildingName = batch.buildingName;
const floorName = batch.floorName;
const workAreaName = batch.workAreaName;
const activityName = batch.activityName;
const batchComment = batch.comment;
// Handler for navigating to the previous image
const handlePrev = () => {
setCurrentIndex((prevIndex) => Math.max(0, prevIndex - 1));
};
// Handler for navigating to the next image
const handleNext = () => {
setCurrentIndex((prevIndex) =>
Math.min(batch.documents.length - 1, prevIndex + 1)
);
};
// Determine if previous/next buttons should be enabled/visible
const hasPrev = currentIndex > 0;
const hasNext = currentIndex < batch.documents.length - 1;
return (
<div className="image-modal-overlay">
<div className="image-modal-content">
<i className="bx bx-x close-button" onClick={closeModal}></i>
{hasPrev && (
<button className="nav-button prev-button" onClick={handlePrev}>
<i className="bx bx-chevron-left"></i>
</button>
)}
<div className="image-container">
<img src={image.url} alt="Preview" className="modal-image" />
</div>
{hasNext && (
<button className="nav-button next-button" onClick={handleNext}>
<i className="bx bx-chevron-right"></i>
</button>
)}
<div className="image-details">
<div className="flex alig-items-center">
{" "}
<i className="bx bxs-user"></i>{" "}
<span className="text-muted">Uploaded By : </span>{" "}
<span className="text-secondary">{fullName}</span>
</div>
<div className="flex alig-items-center">
{" "}
<i className="bx bxs-calendar"></i>{" "}
<span className="text-muted">Date : </span>{" "}
<span className="text-secondary"> {date}</span>
</div>
<div className="flex alig-items-center">
{" "}
<i className="bx bx-map"></i>{" "}
<span className="text-muted">Uploaded By : </span>{" "}
<span className="text-secondary">
{buildingName} <i className="bx bx-chevron-right"></i> {floorName}{" "}
<i className="bx bx-chevron-right"></i>
{workAreaName || "Unknown"}{" "}
<i className="bx bx-chevron-right"></i> {activityName}
</span>
</div>
<div className="flex alig-items-center">
{" "}
<i className="bx bx-comment-dots"></i>{" "}
<span className="text-muted">comment : </span>{" "}
<span className="text-secondary">{batchComment}</span>
</div>
</div>
</div>
</div>
);
};
export default ImagePop;

View File

@ -0,0 +1,23 @@
import React, { createContext, useContext, useState } from "react";
const ModalContext = createContext();
export const ModalProvider1 = ({ children }) => {
const [modalContent, setModalContent] = useState(null);
const openModal = (content) => setModalContent(content);
const closeModal = () => setModalContent(null);
return (
<ModalContext.Provider value={{ openModal, closeModal }}>
{children}
{modalContent && (
<div className="global-modal-wrapper">
{modalContent}
</div>
)}
</ModalContext.Provider>
);
};
export const useModal = () => useContext(ModalContext);

View File

@ -6,8 +6,6 @@ import showToast from "../../services/toastService";
import AuthRepository from "../../repositories/AuthRepository"; import AuthRepository from "../../repositories/AuthRepository";
import "./page-auth.css"; import "./page-auth.css";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
import Modal from "../../components/common/Modal";
import { useModal } from "../../hooks/useAuth";
// --- Zod Schema for validation --- // --- Zod Schema for validation ---
const ChangePasswordSchema = z const ChangePasswordSchema = z
@ -30,15 +28,13 @@ const ChangePasswordSchema = z
path: ["confirmPassword"], path: ["confirmPassword"],
}); });
const ChangePasswordPage = () => { const ChangePasswordPage = ({ onClose }) => {
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [hideOldPass, setHideOldPass] = useState(true); const [hideOldPass, setHideOldPass] = useState(true);
const [hideNewPass, setHideNewPass] = useState(true); const [hideNewPass, setHideNewPass] = useState(true);
const [hideConfirmPass, setHideConfirmPass] = useState(true); const [hideConfirmPass, setHideConfirmPass] = useState(true);
const loggedUser = useSelector((store) => store.globalVariables.loginUser); const loggedUser = useSelector((store) => store.globalVariables.loginUser);
const { isOpen, onClose } = useModal("ChangePassword");
const { const {
register, register,
handleSubmit, handleSubmit,
@ -68,14 +64,25 @@ const ChangePasswordPage = () => {
} }
}; };
const bodyContxt = ( return (
<div
className="modal d-flex align-items-center justify-content-center show"
<div className="row"> tabIndex="-1"
role="dialog"
style={{ backgroundColor: "rgba(0,0,0,0.5)" }}
>
<div className="modal-dialog" role="document">
<div className="modal-content p-10 rounded shadow bg-white position-relative">
<button
type="button"
className="btn-close"
data-bs-dismiss="modal" aria-label="Close"
onClick={onClose} // Use onClick to trigger onClose function
style={{ position: "absolute", top: "15px", right: "15px" }} // Example positioning
></button>
<h5 className="mb-2">Change Password</h5> <h5 className="mb-2">Change Password</h5>
<p className="mb-4 text-black"> <p className="mb-4" style={{ fontSize: "14px" }}>
Enter old and new password to update. Enter old and new password to update.
</p> </p>
@ -168,7 +175,7 @@ const ChangePasswordPage = () => {
)} )}
</div> </div>
<div className="d-flex justify-content-center pt-2 text-muted small text-black"> <div className="d-flex justify-content-center pt-2 text-muted small">
Your password must have at least 8 characters and include a lower Your password must have at least 8 characters and include a lower
case letter, an uppercase letter, a number, and a special case letter, an uppercase letter, a number, and a special
character. character.
@ -193,11 +200,9 @@ const ChangePasswordPage = () => {
</div> </div>
</form> </form>
</div> </div>
</div>
</div>
); );
return <Modal isOpen={isOpen} onClose={onClose} body={bodyContxt} />;
}; };
export default ChangePasswordPage; export default ChangePasswordPage;

View File

@ -6,7 +6,6 @@ import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod"; import { z } from "zod";
import { AuthWrapper } from "./AuthWrapper"; import { AuthWrapper } from "./AuthWrapper";
import { removeSession } from "../../utils/authUtils";
const LoginPage = () => { const LoginPage = () => {
const navigate = useNavigate(); const navigate = useNavigate();
@ -45,11 +44,9 @@ const LoginPage = () => {
if (data.rememberMe) { if (data.rememberMe) {
localStorage.setItem("jwtToken", response.data.token); localStorage.setItem("jwtToken", response.data.token);
localStorage.setItem("refreshToken", response.data.refreshToken); localStorage.setItem("refreshToken", response.data.refreshToken);
removeSession("session")
} else { } else {
sessionStorage.setItem("jwtToken", response.data.token); sessionStorage.setItem("jwtToken", response.data.token);
sessionStorage.setItem("refreshToken", response.data.refreshToken); sessionStorage.setItem("refreshToken", response.data.refreshToken);
removeSession("local")
} }
setLoading(false); setLoading(false);
navigate("/auth/switch/org"); navigate("/auth/switch/org");

View File

@ -86,7 +86,7 @@ const SwitchTenant = () => {
<button <button
className={` ${currentTenant === tenant.id ? "badge bg-label-primary w-50" :"btn btn-primary btn-sm mt-2 align-self-start" }`} className={` ${currentTenant === tenant.id ? "badge bg-label-primary w-50" :"btn btn-primary btn-sm mt-2 align-self-start" }`}
onClick={() => handleTenantselection(tenant?.id)} onClick={() => handleTenantselection(tenant?.id)}
disabled={isPending && pendingTenant === tenant.id || currentTenant === tenant.id || isPending} disabled={isPending && pendingTenant === tenant.id || currentTenant === tenant.id }
> >
{currentTenant === tenant.id ? "Active Tenant" :isPending && pendingTenant === tenant.id {currentTenant === tenant.id ? "Active Tenant" :isPending && pendingTenant === tenant.id
? "Please Wait.." ? "Please Wait.."

View File

@ -7,7 +7,6 @@ import Breadcrumb from "../../components/common/Breadcrumb";
import ManageEmp from "../../components/Employee/ManageRole"; import ManageEmp from "../../components/Employee/ManageRole";
import { import {
useEmployeesAllOrByProjectId, useEmployeesAllOrByProjectId,
useEmployeesByOrganization,
useSuspendEmployee, useSuspendEmployee,
} from "../../hooks/useEmployees"; } from "../../hooks/useEmployees";
import { useProjectName, useProjects } from "../../hooks/useProjects"; import { useProjectName, useProjects } from "../../hooks/useProjects";
@ -37,7 +36,6 @@ import GlobalModel from "../../components/common/GlobalModel";
import usePagination from "../../hooks/usePagination"; import usePagination from "../../hooks/usePagination";
import { setProjectId } from "../../slices/localVariablesSlice"; import { setProjectId } from "../../slices/localVariablesSlice";
import { useHasUserPermission } from "../../hooks/useHasUserPermission"; import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import Pagination from "../../components/common/Pagination";
const EmployeeList = () => { const EmployeeList = () => {
const selectedProjectId = useSelector( const selectedProjectId = useSelector(
@ -48,14 +46,15 @@ const EmployeeList = () => {
const dispatch = useDispatch(); const dispatch = useDispatch();
const [showInactive, setShowInactive] = useState(false); const [showInactive, setShowInactive] = useState(false);
const [showAllEmployees, setShowAllEmployees] = useState(false);
const Manage_Employee = useHasUserPermission(MANAGE_EMPLOYEES); const Manage_Employee = useHasUserPermission(MANAGE_EMPLOYEES);
const { const { employees, loading, setLoading, error, recallEmployeeData } =
data: employees, useEmployeesAllOrByProjectId(
isLoading: loading, showAllEmployees,
error, selectedProjectId,
refetch: recallEmployeeData, showInactive
} = useEmployeesByOrganization(showInactive); );
const [employeeList, setEmployeeList] = useState([]); const [employeeList, setEmployeeList] = useState([]);
const [modelConfig, setModelConfig] = useState(); const [modelConfig, setModelConfig] = useState();
@ -71,6 +70,7 @@ const EmployeeList = () => {
const [selectedEmpFordelete, setSelectedEmpFordelete] = useState(null); const [selectedEmpFordelete, setSelectedEmpFordelete] = useState(null);
const [employeeLodaing, setemployeeLodaing] = useState(false); const [employeeLodaing, setemployeeLodaing] = useState(false);
const ViewTeamMember = useHasUserPermission(VIEW_TEAM_MEMBERS); const ViewTeamMember = useHasUserPermission(VIEW_TEAM_MEMBERS);
const ViewAllEmployee = useHasUserPermission(VIEW_ALL_EMPLOYEES);
const { mutate: suspendEmployee, isPending: empLodaing } = useSuspendEmployee( const { mutate: suspendEmployee, isPending: empLodaing } = useSuspendEmployee(
{ {
setIsDeleteModalOpen, setIsDeleteModalOpen,
@ -157,7 +157,7 @@ const EmployeeList = () => {
const handleAllEmployeesToggle = (e) => { const handleAllEmployeesToggle = (e) => {
const isChecked = e.target.checked; const isChecked = e.target.checked;
setShowInactive(false); setShowInactive(false);
// setShowAllEmployees(isChecked); setShowAllEmployees(isChecked);
}; };
const handleEmployeeModel = (id) => { const handleEmployeeModel = (id) => {
@ -205,16 +205,25 @@ const EmployeeList = () => {
setCurrentPage((prevPage) => (prevPage !== 1 ? 1 : prevPage)); setCurrentPage((prevPage) => (prevPage !== 1 ? 1 : prevPage));
} }
}, [loading, employees, selectedProjectId, showInactive]); }, [loading, employees, selectedProjectId, showAllEmployees]);
useEffect(() => {
if (!showAllEmployees) {
recallEmployeeData(showInactive, selectedProjectId);
}
}, [selectedProjectId, showInactive, showAllEmployees, recallEmployeeData]);
const handler = useCallback( const handler = useCallback(
(msg) => { (msg) => {
if (employees.some((item) => item.id == msg.employeeId)) { if (employees.some((item) => item.id == msg.employeeId)) {
setEmployeeList([]); setEmployeeList([]);
recallEmployeeData(showInactive); recallEmployeeData(
showInactive,
showAllEmployees ? null : selectedProjectId
); // Use selectedProjectId here
} }
}, },
[employees, showInactive, showInactive, selectedProjectId] // Add all relevant dependencies [employees, showInactive, showAllEmployees, selectedProjectId] // Add all relevant dependencies
); );
useEffect(() => { useEffect(() => {
@ -245,6 +254,7 @@ const EmployeeList = () => {
<ManageEmployee <ManageEmployee
employeeId={selectedEmployeeId} employeeId={selectedEmployeeId}
onClosed={() => setShowModal(false)} onClosed={() => setShowModal(false)}
IsAllEmployee={showAllEmployees}
/> />
</GlobalModel> </GlobalModel>
)} )}
@ -283,39 +293,59 @@ const EmployeeList = () => {
{ViewTeamMember ? ( {ViewTeamMember ? (
// <div className="row"> // <div className="row">
<div className="card p-1 page-min-h"> <div className="card p-1">
<div className="card-datatable table-responsive pt-5 mx-5 py-10"> <div className="card-datatable table-responsive pt-5 mx-5 py-10">
<div <div
id="DataTables_Table_0_wrapper" id="DataTables_Table_0_wrapper"
className="dataTables_wrapper dt-bootstrap5 no-footer" className="dataTables_wrapper dt-bootstrap5 no-footer"
style={{ width: "100%" }}
> >
<div className="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-3"> <div className="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-3">
{/* Switches: All Employees + Inactive */} {/* Switches: All Employees + Inactive */}
<div className="d-flex flex-wrap align-items-center gap-3"> <div className="d-flex flex-wrap align-items-center gap-3">
{/* All Employees Switch */} {/* All Employees Switch */}
{ViewAllEmployee && (
<div className="form-check form-switch text-start">
<input
type="checkbox"
className="form-check-input"
role="switch"
id="allEmployeesCheckbox"
checked={showAllEmployees}
onChange={handleAllEmployeesToggle}
/>
<label
className="form-check-label ms-0"
htmlFor="allEmployeesCheckbox"
>
Show All Employees
</label>
</div>
)}
{/* Show Inactive Employees Switch */} {/* Show Inactive Employees Switch */}
{showAllEmployees && (
<div className="form-check form-switch text-start"> <div className="form-check form-switch text-start">
<input <input
type="checkbox" type="checkbox"
className="form-check-input" className="form-check-input"
role="switch" role="switch"
id="inactiveEmployeesCheckbox" id="inactiveEmployeesCheckbox"
checked={showInactive} checked={showInactive}
onChange={(e) => setShowInactive(e.target.checked)} onChange={(e) => setShowInactive(e.target.checked)}
/> />
<label <label
className="form-check-label ms-0" className="form-check-label ms-0"
htmlFor="inactiveEmployeesCheckbox" htmlFor="inactiveEmployeesCheckbox"
> >
Show Inactive Employees Show Inactive Employees
</label> </label>
</div> </div>
)}
</div> </div>
{/* Right side: Search + Export + Add Employee */} {/* Right side: Search + Export + Add Employee */}
<div className="d-flex flex-wrap align-items-center justify-content-start justify-content-md-end gap-3 flex-grow-1"> <div className="d-flex flex-wrap align-items-center justify-content-end gap-3 flex-grow-1">
{/* Search Input - ALWAYS ENABLED */} {/* Search Input - ALWAYS ENABLED */}
<div className="dataTables_filter"> <div className="dataTables_filter">
<label className="mb-0"> <label className="mb-0">
@ -401,6 +431,7 @@ const EmployeeList = () => {
className="datatables-users table border-top dataTable no-footer dtr-column text-nowrap" className="datatables-users table border-top dataTable no-footer dtr-column text-nowrap"
id="DataTables_Table_0" id="DataTables_Table_0"
aria-describedby="DataTables_Table_0_info" aria-describedby="DataTables_Table_0_info"
style={{ width: "100%" }}
ref={tableRef} ref={tableRef}
> >
<thead> <thead>
@ -491,27 +522,28 @@ const EmployeeList = () => {
</td> </td>
</tr> </tr>
)} )}
{/* Conditional messages for no data or no search results */}
{!loading && {!loading &&
displayData?.length === 0 && displayData?.length === 0 &&
(!searchText ) ? ( searchText &&
!showAllEmployees ? (
<tr> <tr>
<td colSpan={8} className="border-0 py-3"> <td colSpan={8}>
<div className="py-4"> <small className="muted">
No Data Found '{searchText}' employee not found
</div> </small>{" "}
</td> </td>
</tr> </tr>
) : null} ) : null}
{!loading &&
{!loading &&
displayData?.length === 0 && displayData?.length === 0 &&
(searchText ) ? ( (!searchText || showAllEmployees) ? (
<tr> <tr>
<td colSpan={8} className="border-0 py-3"> <td
<div className="py-4"> colSpan={8}
{`No match record found ${searchText} `} style={{ paddingTop: "20px", textAlign: "center" }}
</div> >
No Data Found
</td> </td>
</tr> </tr>
) : null} ) : null}
@ -665,12 +697,55 @@ const EmployeeList = () => {
</tbody> </tbody>
</table> </table>
{displayData?.length > 0 && ( <div style={{ width: "1%" }}></div>
<Pagination
currentPage={currentPage} {/* Pagination */}
totalPages={totalPages} {!loading && displayData.length > ITEMS_PER_PAGE && (
onPageChange={paginate} <nav aria-label="Page">
/> <ul className="pagination pagination-sm justify-content-end py-1">
<li
className={`page-item ${
currentPage === 1 ? "disabled" : ""
}`}
>
<button
className="page-link btn-xs"
onClick={() => paginate(currentPage - 1)}
>
&laquo;
</button>
</li>
{[...Array(totalPages)]?.map((_, index) => (
<li
key={index}
className={`page-item ${
currentPage === index + 1 ? "active" : ""
}`}
>
<button
className="page-link"
onClick={() => paginate(index + 1)}
>
{index + 1}
</button>
</li>
))}
<li
className={`page-item ${
currentPage === totalPages ? "disabled" : ""
}`}
>
<button
className="page-link"
onClick={() => paginate(currentPage + 1)}
>
&raquo;
</button>
</li>
</ul>
</nav>
)} )}
</div> </div>
</div> </div>

View File

@ -65,7 +65,7 @@ const EmployeeProfile = () => {
case "attendance": { case "attendance": {
return ( return (
<> <>
<EmpAttendance /> <EmpAttendance employee={employeeId} />
</> </>
); );
} }

View File

@ -103,7 +103,7 @@ const MasterPage = () => {
if (menuErrorFlag || isMasterError) if (menuErrorFlag || isMasterError)
return ( return (
<div className="d-flex flex-column align-items-center justify-content-center py-1 py-md-5"> <div className="d-flex flex-column align-items-center justify-content-center py-5">
<h4 className="mb-3"> <h4 className="mb-3">
<i className="fa-solid fa-triangle-exclamation fs-5" /> Oops, an error <i className="fa-solid fa-triangle-exclamation fs-5" /> Oops, an error
occurred occurred
@ -161,17 +161,21 @@ const MasterPage = () => {
data={[{ label: "Home", link: "/dashboard" }, { label: "Masters" }]} data={[{ label: "Home", link: "/dashboard" }, { label: "Masters" }]}
/> />
<div className="row page-min-h"> <div className="row">
<div className="card"> <div className="card">
<div <div
className="card-datatable table-responsive py-2 py-md-10 mx-1 mx-md-5 " className="card-datatable table-responsive py-10 mx-5 "
style={{ overflow: "hidden" }} style={{ overflow: "hidden" }}
> >
<div className="row mb-2"> <div className="row mb-2">
<div className="col-12 col-md-3"> <div className="col-md-3 col-sm-6">
<select <select
className="form-select py-1 px-2" className="form-select py-1 px-2"
style={{
fontSize: "0.875rem",
height: "32px",
width: "190px",
}}
value={selectedMaster} value={selectedMaster}
onChange={(e) => dispatch(changeMaster(e.target.value))} onChange={(e) => dispatch(changeMaster(e.target.value))}
> >
@ -186,8 +190,8 @@ const MasterPage = () => {
)} )}
</select> </select>
</div> </div>
<div className="col-12 col-md-9 d-flex justify-content-end align-items-center gap-2 mt-2 mt-md-0"> <div className="col-md-9 col-sm-6 d-flex justify-content-end align-items-center gap-2">
<div className="col-6 col-md-3"> <div className="w-25">
<input <input
type="search" type="search"
className="form-control form-control-sm" className="form-control form-control-sm"
@ -203,8 +207,8 @@ const MasterPage = () => {
handleModalData(selectedMaster, null, selectedMaster) handleModalData(selectedMaster, null, selectedMaster)
} }
> >
<i className="bx bx-plus-circle me-2"></i> <span className="d-none d-md-inline-block">Add{" "} <i className="bx bx-plus-circle me-2"></i>Add{" "}
{selectedMaster}</span> {selectedMaster}
</button> </button>
)} )}
</div> </div>

View File

@ -92,8 +92,7 @@ const MasterTable = ({ data, columns, loading, handleModalData }) => {
{" "} {" "}
{selectedMaster === "Activity" ? "Activity" : "Name"} {selectedMaster === "Activity" ? "Activity" : "Name"}
</th> </th>
<th className="text-start d-none d-md-table-cell"> <th className="text-start">
{" "} {" "}
{selectedMaster === "Activity" {selectedMaster === "Activity"
? "Unit" ? "Unit"
@ -109,12 +108,12 @@ const MasterTable = ({ data, columns, loading, handleModalData }) => {
<tbody> <tbody>
{currentItems.length > 0 ? ( {currentItems.length > 0 ? (
currentItems.map((item, index) => ( currentItems.map((item, index) => (
<tr key={index} > <tr key={index}>
<td style={{ width: "20px" }} className="py-3"> <td style={{ width: "20px" }}>
<i className="bx bx-right-arrow-alt"></i> <i className="bx bx-right-arrow-alt"></i>
</td> </td>
{updatedColumns.map((col) => ( {updatedColumns.map((col) => (
<td className={`text-start mx-2 py-3 ${col.key === "description" && "d-none d-md-table-cell"}`} key={col.key} > <td className="text-start mx-2" key={col.key}>
{col.key === "description" ? ( {col.key === "description" ? (
item[col.key] !== undefined && item[col.key] !== undefined &&
item[col.key] !== null ? ( item[col.key] !== null ? (
@ -134,7 +133,7 @@ const MasterTable = ({ data, columns, loading, handleModalData }) => {
)} )}
</td> </td>
))} ))}
<td className={!hasMasterPermission ? "d-none" : "py-3"}> <td className={!hasMasterPermission ? "d-none" : ""}>
{(selectedMaster === "Application Role" || {(selectedMaster === "Application Role" ||
selectedMaster === "Work Category") && selectedMaster === "Work Category") &&
item?.isSystem ? ( item?.isSystem ? (

View File

@ -11,12 +11,11 @@ const EmployeeRepository = {
// deleteEmployee: ( id ) => api.delete( `/users/${ id }` ), // deleteEmployee: ( id ) => api.delete( `/users/${ id }` ),
getEmployeeProfile: (id) => api.get(`/api/employee/profile/get/${id}`), getEmployeeProfile: (id) => api.get(`/api/employee/profile/get/${id}`),
deleteEmployee: (id,active) => api.delete(`/api/employee/${id}?active=${active}`), deleteEmployee: (id,active) => api.delete(`/api/employee/${id}?active=${active}`),
getEmployeeName: (projectId, search,allEmployee) => { getEmployeeName: (projectId, search) => {
const params = new URLSearchParams(); const params = new URLSearchParams();
if (projectId) params.append("projectId", projectId); if (projectId) params.append("projectId", projectId);
if (search) params.append("searchString", search); if (search) params.append("searchString", search);
if(allEmployee) params.append("allEmployee",allEmployee)
const query = params.toString(); const query = params.toString();
return api.get(`/api/Employee/basic${query ? `?${query}` : ""}`); return api.get(`/api/Employee/basic${query ? `?${query}` : ""}`);

View File

@ -1,12 +1,8 @@
import { api } from "../utils/axiosClient"; import { api } from "../utils/axiosClient";
export const ImageGalleryRepository = { export const ImageGalleryAPI = {
ImagesGet: (projectId, pageNumber, pageSize,filter) => { ImagesGet: (projectId, filter, pageNumber, pageSize) => {
const payloadJsonString = JSON.stringify(filter); const payloadJsonString = JSON.stringify(filter);
return api.get(`/api/image/images/${projectId}?pageNumber=${pageNumber}&pageSize=${pageSize}&filter=${payloadJsonString}`); return api.get(`/api/image/images/${projectId}?filter=${payloadJsonString}&pageNumber=${pageNumber}&pageSize=${pageSize}`);
}, },
getImageGalleryFilter:(projectId)=>api.get(`/api/Image/filter/${projectId}`)
}; };

View File

@ -6,19 +6,19 @@ const ProjectRepository = {
api.get(`/api/project/details/${projetid}`), api.get(`/api/project/details/${projetid}`),
getProjectAllocation: (projectId, serviceId, organizationId, employeeStatus) => { getProjectAllocation: (projectId, serviceId, organizationId, employeeStatus) => {
let url = `/api/project/allocation/${projectId}`; let url = `/api/project/allocation/${projectId}`;
const params = []; const params = [];
if (organizationId) params.push(`organizationId=${organizationId}`); if (organizationId) params.push(`organizationId=${organizationId}`);
if (serviceId) params.push(`serviceId=${serviceId}`); if (serviceId) params.push(`serviceId=${serviceId}`);
if (employeeStatus !== undefined) params.push(`includeInactive=${employeeStatus}`); if (employeeStatus !== undefined) params.push(`includeInactive=${employeeStatus}`);
if (params.length > 0) { if (params.length > 0) {
url += `?${params.join("&")}`; url += `?${params.join("&")}`;
} }
return api.get(url); return api.get(url);
}, },
getEmployeesByProject: (projectId) => getEmployeesByProject: (projectId) =>
@ -43,13 +43,12 @@ const ProjectRepository = {
projectNameList: () => api.get("/api/project/list/basic"), projectNameList: () => api.get("/api/project/list/basic"),
getProjectDetails: (id) => api.get(`/api/project/details/${id}`), getProjectDetails: (id) => api.get(`/api/project/details/${id}`),
getProjectInfraByproject: (projectId, serviceId) => { getProjectInfraByproject: (projectId, serviceId) => {
let url = `/api/project/infra-details/${projectId}`; let url = `/api/project/infra-details/${projectId}`;
if (serviceId) {
url = `${url}?serviceId=${serviceId}`;
}
if (serviceId) {
url + `?serviceId=${serviceId}`;
}
return api.get(url); return api.get(url);
}, },
getProjectTasksByWorkArea: (workAreaId, serviceId) => { getProjectTasksByWorkArea: (workAreaId, serviceId) => {
@ -85,8 +84,6 @@ const ProjectRepository = {
api.get(`/api/Project/get/assigned/services/${projectId}`), api.get(`/api/Project/get/assigned/services/${projectId}`),
getProjectAssignedOrganizations: (projectId) => getProjectAssignedOrganizations: (projectId) =>
api.get(`/api/Project/get/assigned/organization/${projectId}`), api.get(`/api/Project/get/assigned/organization/${projectId}`),
getProjectAssignedOrganizationsName: (projectId) =>
api.get(`/api/Project/get/assigned/organization/dropdown/${projectId}`),
getEmployeeForTaskAssign: (projectId, serviceId, organizationId) => { getEmployeeForTaskAssign: (projectId, serviceId, organizationId) => {
let url = `/api/Project/get/task/team/${projectId}`; let url = `/api/Project/get/task/team/${projectId}`;

View File

@ -16,8 +16,6 @@ export const TasksRepository = {
return api.get(url); return api.get(url);
}, },
getTaskListFilter:(projectId)=>api.get(`/api/task/filter/${projectId}`),
getTaskById: (id) => api.get(`/api/task/get/${id}`), getTaskById: (id) => api.get(`/api/task/get/${id}`),
reportTask: (data) => api.post("api/task/report", data), reportTask: (data) => api.post("api/task/report", data),
taskComments: (data) => api.post("api/task/comment", data), taskComments: (data) => api.post("api/task/comment", data),

View File

@ -22,6 +22,7 @@ import Inventory from "../pages/project/Inventory";
import AttendancePage from "../pages/Activities/AttendancePage"; import AttendancePage from "../pages/Activities/AttendancePage";
import TaskPlannng from "../pages/Activities/TaskPlannng"; import TaskPlannng from "../pages/Activities/TaskPlannng";
import Reports from "../pages/reports/Reports"; import Reports from "../pages/reports/Reports";
import ImageGallary from "../pages/Gallary/ImageGallary";
import MasterPage from "../pages/master/MasterPage"; import MasterPage from "../pages/master/MasterPage";
import Support from "../pages/support/Support"; import Support from "../pages/support/Support";
import Documentation from "../pages/support/Documentation"; import Documentation from "../pages/support/Documentation";
@ -52,7 +53,6 @@ import TenantSelectionPage from "../pages/authentication/TenantSelectionPage";
import DailyProgrssReport from "../pages/DailyProgressReport/DailyProgrssReport"; import DailyProgrssReport from "../pages/DailyProgressReport/DailyProgrssReport";
import ProjectPage from "../pages/project/ProjectPage"; import ProjectPage from "../pages/project/ProjectPage";
import { ComingSoonPage } from "../pages/Misc/ComingSoonPage"; import { ComingSoonPage } from "../pages/Misc/ComingSoonPage";
import ImageGalleryPage from "../pages/Gallary/ImageGallaryPage";
const router = createBrowserRouter( const router = createBrowserRouter(
[ [
{ {
@ -93,7 +93,7 @@ const router = createBrowserRouter(
{ path: "/activities/records/:projectId?", element: <DailyProgrssReport /> }, { path: "/activities/records/:projectId?", element: <DailyProgrssReport /> },
{ path: "/activities/task", element: <TaskPlannng /> }, { path: "/activities/task", element: <TaskPlannng /> },
{ path: "/activities/reports", element: <Reports /> }, { path: "/activities/reports", element: <Reports /> },
{ path: "/gallary", element: <ImageGalleryPage /> }, { path: "/gallary", element: <ComingSoonPage /> },
{ path: "/expenses", element: <ExpensePage /> }, { path: "/expenses", element: <ExpensePage /> },
{ path: "/masters", element: <MasterPage /> }, { path: "/masters", element: <MasterPage /> },
{ path: "/tenants", element: <TenantPage /> }, { path: "/tenants", element: <TenantPage /> },

View File

@ -59,7 +59,7 @@ const attemptTokenRefresh = async (storedRefreshToken) => {
return true; return true;
} catch (error) { } catch (error) {
removeSession() console.error("Token refresh failed:", error);
return false; return false;
} }
}; };

View File

@ -8,7 +8,7 @@ import showToast from "./toastService";
import eventBus from "./eventBus"; import eventBus from "./eventBus";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
import { clearApiCacheKey } from "../slices/apiCacheSlice"; import { clearApiCacheKey } from "../slices/apiCacheSlice";
import { BASE_URL } from "../utils/constants"; import {BASE_URL} from "../utils/constants";
import { queryClient } from "../layouts/AuthLayout"; import { queryClient } from "../layouts/AuthLayout";
const base_Url = BASE_URL; const base_Url = BASE_URL;
let connection = null; let connection = null;
@ -32,108 +32,103 @@ export function startSignalR(loggedUser) {
.toISOString() .toISOString()
.split("T")[0]; .split("T")[0];
connection.on("NotificationEventHandler", (data) => { connection.on("NotificationEventHandler", (data) => {
const { loggedInUserId, keyword, response, employeeList, numberOfImages } = if (data.loggedInUserId != loggedUser?.employeeInfo.id) {
data; // console.log("Notification received:", data);
const loggedInId = loggedUser?.employeeInfo?.id; // if action taken on attendance module
if (data.keyword == "Attendance") {
const checkIn = data.response.checkInTime.substring(0, 10);
if (today === checkIn) {
eventBus.emit("attendance", data);
}
var onlyDate = Number(checkIn.substring(8, 10));
if (loggedInUserId === loggedInId) return; var afterTwoDay =
checkIn.substring(0, 8) + (onlyDate + 2).toString().padStart(2, "0");
// ---- Handlers for invalidate or remove ---- if (
const queryInvalidators = { afterTwoDay <= today &&
Expanse: () => { (data.response.activity == 4 || data.response.activity == 5)
queryClient.invalidateQueries({ queryKey: ["Expenses"] }), ) {
queryClient.invalidateQueries({ queryKey: ["Expense"] }); eventBus.emit("regularization", data);
}, }
Create_Project: () => queryClient.invalidateQueries(["projectslist"]), eventBus.emit("attendance_log", data);
Update_Project: () => queryClient.invalidateQueries(["projectslist"]), }
Infra: () => queryClient.removeQueries({ queryKey: ["ProjectInfra"] }), if(data.keyword == "Expanse"){
Task_Report: () => queryClient.invalidateQueries({ queryKey: ["Infra"] }), queryClient.invalidateQueries({queryKey:["Expenses"]})
WorkItem: () => }
queryClient.invalidateQueries({ queryKey: ["WorkItems"] }), // if create or update project
Directory_Notes: () => {
queryClient.invalidateQueries({ queryKey: ["directoryNotes"] });
queryClient.invalidateQueries({ queryKey: ["Notes"] });
},
Directory_Buckets: () => {
queryClient.invalidateQueries({ queryKey: ["bucketList"] });
},
Directory: () => {
queryClient.invalidateQueries({ queryKey: ["contacts"] });
queryClient.invalidateQueries({ queryKey: ["Contact"] });
queryClient.invalidateQueries({ queryKey: ["ContactProfile"] });
},
};
// ---- Keyword based event emitters ----
const emitters = {
employee: () => eventBus.emit("employee", data),
project: () => eventBus.emit("project", data),
infra: () => eventBus.emit("infra", data),
assign_project_all: () => eventBus.emit("assign_project_all", data),
image_gallery: () => eventBus.emit("image_gallery", data),
};
// ---- Handle Attendance ----
if (keyword === "Attendance") {
const checkIn = response.checkInTime.substring(0, 10);
if (today === checkIn) eventBus.emit("attendance", data);
const onlyDate = Number(checkIn.substring(8, 10));
const afterTwoDay = checkIn.substring(0,8) + (onlyDate + 2).toString().padStart(2, "0");
if ( if (
afterTwoDay <= today && data.keyword == "Create_Project" ||
(response.activity === 4 || response.activity === 5) data.keyword == "Update_Project"
) { ) {
eventBus.emit("regularization", data); // clearCacheKey("projectslist");
queryClient.invalidateQueries(['projectslist']);
eventBus.emit("project", data);
} }
eventBus.emit("attendance_log", data);
}
// ---- Invalidate/Remove cache by keywords ---- // if assign or deassign employee to any project
if (queryInvalidators[keyword]) { if (data.keyword == "Assign_Project") {
queryInvalidators[keyword](); if (
} data.employeeList.some((item) => item === loggedUser?.employeeInfo.id)
) {
// ---- Project creation/update ---- try {
if (keyword === "Create_Project" || keyword === "Update_Project") { cacheData("hasReceived", false);
emitters.project(); eventBus.emit("assign_project_one", data);
} } catch (e) {
// console.error("Error in cacheData:", e);
// ---- Assign/deassign project ---- }
if (keyword === "Assign_Project") { }
if (employeeList?.includes(loggedInId)) { eventBus.emit("assign_project_all", data);
try { }
cacheData("hasReceived", false); // if created or updated infra
eventBus.emit("assign_project_one", data); if (data.keyword == "Infra") {
} catch {} queryClient.removeQueries({queryKey:["ProjectInfra"]})
// eventBus.emit("infra", data);
}
if (data.keyword == "Task_Report") {
queryClient.removeQueries({queryKey:["Infra"]})
// eventBus.emit("infra", data);
} }
emitters.assign_project_all();
}
// ---- Employee update ---- if ( data.keyword == "WorkItem" )
if (keyword === "Employee") { {
clearCacheKey("Attendance"); queryClient.removeQueries({queryKey:["WorkItems"]})
clearCacheKey("regularizedList"); }
clearCacheKey("AttendanceLogs");
queryClient.invalidateQueries(["allEmployee", true]); // if created or updated Employee
queryClient.invalidateQueries(["allEmployee", false]); if (data.keyword == "Employee") {
queryClient.invalidateQueries(["employeeProfile", response?.employeeId]); // clearCacheKey("employeeListByProject");
queryClient.invalidateQueries(["employeeListByProject"]); // clearCacheKey("allEmployeeList");
// clearCacheKey("allInactiveEmployeeList");
// clearCacheKey("employeeProfile");
clearCacheKey("Attendance");
clearCacheKey("regularizedList")
clearCacheKey("AttendanceLogs")
emitters.employee(); // ---we can do also----
} // queryClient.removeQueries(['allEmployee', true]);
// but best practies is refetch
queryClient.invalidateQueries(['allEmployee', true]);
queryClient.invalidateQueries(['allEmployee', false]);
queryClient.invalidateQueries(['employeeProfile', data.response?.employeeId]);
queryClient.invalidateQueries(['employeeListByProject']); // optional if scope
eventBus.emit("employee", data);
}
// ---- Image related events ---- if (data.keyword == "Task_Report") {
if ( if(data.numberOfImages > 0){
["Task_Report", "Task_Comment"].includes(keyword) && eventBus.emit("image_gallery", data);
numberOfImages > 0 }
) { }
emitters.image_gallery(); if (data.keyword == "Task_Comment") {
if(data.numberOfImages > 0){
eventBus.emit("image_gallery", data);
}
}
} }
}); });
connection.start(); connection
.start();
} }
export function stopSignalR() { export function stopSignalR() {

View File

@ -4,18 +4,10 @@ const localVariablesSlice = createSlice({
name: "localVariables", name: "localVariables",
initialState: { initialState: {
selectedMaster: "Application Role", selectedMaster: "Application Role",
// Attendances regularizationCount: 0,
attendance: { defaultDateRange: {
regularizationCount: 0, startDate: null,
defaultDateRange: { startDate: null, endDate: null }, endDate: null,
SelectedOrg: "",
},
// Modal for all simple pass Name
modals: {
auth: { isOpen: false },
organization: { isOpen: false },
}, },
projectId: null, projectId: null,
reload: false, reload: false,
@ -36,18 +28,9 @@ const localVariablesSlice = createSlice({
changeMaster: (state, action) => { changeMaster: (state, action) => {
state.selectedMaster = action.payload; state.selectedMaster = action.payload;
}, },
// ATTENDANCE
updateRegularizationCount: (state, action) => { updateRegularizationCount: (state, action) => {
state.attendance.regularizationCount = action.payload; state.regularizationCount = action.payload;
}, },
setDefaultDateRange: (state, action) => {
state.attendance.defaultDateRange = action.payload;
},
setOrganization: (state, action) => {
state.attendance.SelectedOrg = action.payload;
},
setProjectId: (state, action) => { setProjectId: (state, action) => {
localStorage.setItem("project", null); localStorage.setItem("project", null);
state.projectId = action.payload; state.projectId = action.payload;
@ -56,6 +39,10 @@ const localVariablesSlice = createSlice({
refreshData: (state, action) => { refreshData: (state, action) => {
state.reload = action.payload; state.reload = action.payload;
}, },
setDefaultDateRange: (state, action) => {
state.defaultDateRange = action.payload;
},
openOrgModal: (state, action) => { openOrgModal: (state, action) => {
state.OrganizationModal.isOpen = true; state.OrganizationModal.isOpen = true;
state.OrganizationModal.orgData = action.payload?.orgData || null; state.OrganizationModal.orgData = action.payload?.orgData || null;
@ -83,19 +70,6 @@ const localVariablesSlice = createSlice({
closeAuthModal: (state, action) => { closeAuthModal: (state, action) => {
state.AuthModal.isOpen = false; state.AuthModal.isOpen = false;
}, },
openModal: (state, action) => {
const { modalType, data } = action.payload;
state.modals[modalType] = { isOpen: true, ...data };
},
closeModal: (state, action) => {
const { modalType } = action.payload;
state.modals[modalType] = { ...state.modals[modalType], isOpen: false };
},
toggleModal: (state, action) => {
const { modalType } = action.payload;
state.modals[modalType].isOpen = !state.modals[modalType].isOpen;
},
}, },
}); });
@ -110,6 +84,5 @@ export const {
toggleOrgModal, toggleOrgModal,
openAuthModal, openAuthModal,
closeAuthModal, closeAuthModal,
setOrganization,openModal, closeModal, toggleModal
} = localVariablesSlice.actions; } = localVariablesSlice.actions;
export default localVariablesSlice.reducer; export default localVariablesSlice.reducer;

View File

@ -69,69 +69,15 @@ export const normalizeAllowedContentTypes = (allowedContentType) => {
return allowedContentType.split(","); return allowedContentType.split(",");
return []; return [];
}; };
export function localToUtc(dateString) { export function localToUtc(localDateString) {
if (!dateString || typeof dateString !== "string") return null; if (!localDateString || typeof localDateString !== "string") return null;
const parts = dateString.trim().split("-"); const [year, month, day] = localDateString.trim().split("-");
if (parts.length !== 3) return null;
let day, month, year; if (!year || !month || !day) return null;
if (parts[0].length === 4) {
// Format: yyyy-mm-dd const date = new Date(Number(year), Number(month) - 1, Number(day), 0, 0, 0);
[year, month, day] = parts;
} else { return isNaN(date.getTime()) ? null : date.toISOString();
// Format: dd-mm-yyyy
[day, month, year] = parts;
} }
if (!day || !month || !year) return null;
const date = new Date(
Date.UTC(Number(year), Number(month) - 1, Number(day), 0, 0, 0)
);
return isNaN(date.getTime()) ? null : date.toISOString();
}
/**
* Flexible number formatter for currency, numbers, or percentages.
*
* @param {number} amount - The value to format.
* @param {Object} options - Formatting options.
* @param {"currency"|"number"|"percent"} [options.type="number"] - Type of format.
* @param {string} [options.currency="INR"] - Currency code (only used when type="currency").
* @param {string} [options.locale="en-US"] - Locale for formatting.
* @param {"short"|"long"|"standard"} [options.notation="compact"] - Display style for large numbers.
* @param {number} [options.minimumFractionDigits=0] - Minimum decimal places.
* @param {number} [options.maximumFractionDigits=2] - Maximum decimal places.
* @returns {string} Formatted number string.
*/
export const formatFigure = (
amount,
{
type = "number",
currency = "INR",
locale = "en-US",
notation = "compact",
compactDisplay = "short",
minimumFractionDigits = 0,
maximumFractionDigits = 2,
} = {}
) => {
if (amount == null || isNaN(amount)) return "-";
const formatterOptions = {
style: type === "currency" ? "currency" : type === "percent" ? "percent" : "decimal",
notation: notation,
compactDisplay,
minimumFractionDigits,
maximumFractionDigits,
};
if (type === "currency") {
formatterOptions.currency = currency;
}
return new Intl.NumberFormat(locale, formatterOptions).format(amount);
};

View File

@ -1,14 +1,7 @@
export const removeSession = (target = "all") => { export const removeSession = () => {
const keys = ["jwtToken", "refreshToken", "ctnt"]; localStorage.removeItem("jwtToken");
localStorage.removeItem("refreshToken");
if (target === "local") { sessionStorage.removeItem("jwtToken");
keys.forEach((key) => localStorage.removeItem(key)); sessionStorage.removeItem("refreshToken");
} else if (target === "session") { localStorage.removeItem("ctnt");
keys.forEach((key) => sessionStorage.removeItem(key)); };
} else if (target === "all") {
keys.forEach((key) => {
localStorage.removeItem(key);
sessionStorage.removeItem(key);
});
}
};

View File

@ -3,11 +3,6 @@ export const DURATION_TIME = 10; // minutes
export const ITEMS_PER_PAGE = 20; export const ITEMS_PER_PAGE = 20;
export const OTP_EXPIRY_SECONDS = 300; // OTP time export const OTP_EXPIRY_SECONDS = 300; // OTP time
export const BASE_URL = process.env.VITE_BASE_URL;
// export const BASE_URL = "https://api.marcoaiot.com";
export const MANAGE_MASTER = "588a8824-f924-4955-82d8-fc51956cf323"; export const MANAGE_MASTER = "588a8824-f924-4955-82d8-fc51956cf323";
export const VIEW_MASTER = "5ffbafe0-7ab0-48b1-bb50-c1bf76b65f9d"; export const VIEW_MASTER = "5ffbafe0-7ab0-48b1-bb50-c1bf76b65f9d";
@ -147,3 +142,6 @@ export const PROJECT_STATUS = [
]; ];
export const DEFAULT_EMPTY_STATUS_ID = "00000000-0000-0000-0000-000000000000"; export const DEFAULT_EMPTY_STATUS_ID = "00000000-0000-0000-0000-000000000000";
export const BASE_URL = process.env.VITE_BASE_URL;
// export const BASE_URL = "https://api.marcoaiot.com";