Compare commits
73 Commits
main
...
Kartik_Bug
Author | SHA1 | Date | |
---|---|---|---|
8357fa9b22 | |||
006ca21e1d | |||
bb2d7b8923 | |||
c921dbff09 | |||
e84da2dcb0 | |||
4ba7c72e78 | |||
9939973d8d | |||
e17c2064ac | |||
9580c9234c | |||
44b3f842f2 | |||
9de0b1a0df | |||
fbb68a4488 | |||
2ee7b292e7 | |||
c1a8b87a2c | |||
24501b3c76 | |||
ef00516256 | |||
f867a692ed | |||
85b4b830d3 | |||
c1c333008f | |||
5370d0eb9d | |||
5cbd6c427a | |||
5057738d8b | |||
063bbee681 | |||
3dc667db73 | |||
2f2c31db9f | |||
0dc540eec2 | |||
fc7c33ee54 | |||
eeb886ec36 | |||
210b01513e | |||
2fe297c6b6 | |||
ffd7f15488 | |||
7f33d5e6bd | |||
108ca1cc96 | |||
0b1a276898 | |||
6246dbd23f | |||
af3bf11beb | |||
2e5951d9d1 | |||
cdc5e32554 | |||
bc047a84fc | |||
0511ed6d82 | |||
bc933f4c64 | |||
bd3645aae6 | |||
2f2215ab8a | |||
071f862743 | |||
040331e27d | |||
db2730c02b | |||
9df813698d | |||
6ba018399c | |||
1e49cf17a2 | |||
ab5e0b2f79 | |||
7c9d2ddeb1 | |||
f0f579beae | |||
b53e6284b9 | |||
b1c23aab4d | |||
4a05e67ff0 | |||
87d13d0f77 | |||
997971629f | |||
18ac8e11bd | |||
78808ecac0 | |||
3553a7b521 | |||
aca96c60ae | |||
25f4f1e7a7 | |||
0c1889e1c1 | |||
9884943907 | |||
2531d91209 | |||
49b597c833 | |||
2aae7194b7 | |||
ae772d925a | |||
c1e5ff4043 | |||
2aff3b9e80 | |||
4e48478fbc | |||
4ea1e06a9c | |||
4ddb8415cc |
@ -9,4 +9,88 @@
|
||||
}
|
||||
.table_header_border {
|
||||
border-bottom:2px solid var(--bs-table-border-color) ;
|
||||
}
|
||||
}
|
||||
.text-gary-80 {
|
||||
color:var(--bs-gray-500)
|
||||
}
|
||||
|
||||
.text-royalblue{
|
||||
color: #1796e3;
|
||||
}
|
||||
|
||||
.text-md {
|
||||
font-size: 2rem;
|
||||
}
|
||||
|
||||
.text-md-b {
|
||||
font-weight: normal;
|
||||
}
|
||||
.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; }
|
||||
|
3
public/assets/vendor/css/core.css
vendored
3
public/assets/vendor/css/core.css
vendored
@ -32573,4 +32573,7 @@ body:not(.modal-open) .layout-content-navbar .layout-navbar {
|
||||
}
|
||||
.text-red{
|
||||
color:var(--bs-red)
|
||||
}
|
||||
.bg-gray {
|
||||
background:var(--bs-body-color)
|
||||
}
|
@ -6,7 +6,12 @@ import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
|
||||
import { queryClient } from "./layouts/AuthLayout";
|
||||
import ModalProvider from "./ModalProvider";
|
||||
|
||||
|
||||
window.addEventListener("unhandledrejection", (event) => {
|
||||
if (event.reason?.message?.includes("Failed to fetch")) {
|
||||
event.preventDefault();
|
||||
console.debug("Network issue (fetch failed) - suppressed");
|
||||
}
|
||||
});
|
||||
|
||||
const App = () => {
|
||||
return (
|
||||
|
@ -1,17 +1,20 @@
|
||||
import React, { useEffect } from "react";
|
||||
import { useOrganizationModal } from "./hooks/useOrganization";
|
||||
import OrganizationModal from "./components/Organization/OrganizationModal";
|
||||
import { useAuthModal } from "./hooks/useAuth";
|
||||
import { useAuthModal, useModal } from "./hooks/useAuth";
|
||||
import SwitchTenant from "./pages/authentication/SwitchTenant";
|
||||
import { ProjectModal } from "./components/Project/ManageProjectInfo";
|
||||
|
||||
const ModalProvider = () => {
|
||||
const { isOpen, onClose } = useOrganizationModal();
|
||||
const { isOpen: isAuthOpen } = useAuthModal();
|
||||
const {isOpen:isOpenProject} = useModal("ManageProject")
|
||||
|
||||
return (
|
||||
<>
|
||||
{isOpen && <OrganizationModal />}
|
||||
{isAuthOpen && <SwitchTenant />}
|
||||
{isOpenProject && <ProjectModal/>}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
@ -123,15 +123,19 @@ const AttendLogs = ({ Id }) => {
|
||||
}, []);
|
||||
return (
|
||||
<div className="table-responsive">
|
||||
<div className="text-start">
|
||||
<div className="mb-3">
|
||||
<h5 className="fw-bold mb-4">Attendance Logs</h5>
|
||||
{logs && !loading && (
|
||||
<p>
|
||||
Attendance logs for{" "}
|
||||
{logs[0]?.employee?.firstName + " " + logs[0]?.employee?.lastName}{" "}
|
||||
on {formatUTCToLocalTime(logs[0]?.activityTime)}
|
||||
<p className="mb-0 text-start">
|
||||
Showing logs for{" "}
|
||||
<strong>
|
||||
{logs[0]?.employee?.firstName + " " + logs[0]?.employee?.lastName}
|
||||
</strong>{" "}
|
||||
on <strong>{formatUTCToLocalTime(logs[0]?.activityTime)}</strong>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{loading && <p>Loading..</p>}
|
||||
{logs && logs.length > 0 && (
|
||||
<>
|
||||
@ -142,9 +146,9 @@ const AttendLogs = ({ Id }) => {
|
||||
<table className="table table-sm mb-0">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Activity</th>
|
||||
<th>Date</th>
|
||||
<th>Time</th>
|
||||
<th>Activity</th>
|
||||
<th>Location</th>
|
||||
<th>Recored By</th>
|
||||
<th>Description</th>
|
||||
@ -156,11 +160,16 @@ const AttendLogs = ({ Id }) => {
|
||||
.sort((a, b) => b.id - a.id)
|
||||
.map((log, index) => (
|
||||
<tr key={index}>
|
||||
<td>{formatUTCToLocalTime(log.activityTime)}</td>
|
||||
<td>{convertShortTime(log.activityTime)}</td>
|
||||
<td>
|
||||
<td>
|
||||
{whichActivityPerform(log.activity, log.activityTime)}
|
||||
</td>
|
||||
<td>
|
||||
<div className="py-2">
|
||||
{formatUTCToLocalTime(log.activityTime)}
|
||||
</div>
|
||||
</td>
|
||||
<td>{convertShortTime(log.activityTime)}</td>
|
||||
|
||||
<td>
|
||||
{log?.latitude != 0 ? (
|
||||
<i
|
||||
@ -179,9 +188,8 @@ const AttendLogs = ({ Id }) => {
|
||||
)}
|
||||
</td>
|
||||
<td className="text-wrap">
|
||||
{`${log?.updatedByEmployee?.firstName ?? ""} ${
|
||||
log?.updatedByEmployee?.lastName ?? ""
|
||||
}`}
|
||||
{`${log?.updatedByEmployee?.firstName ?? ""} ${log?.updatedByEmployee?.lastName ?? ""
|
||||
}`}
|
||||
</td>
|
||||
<td className="text-wrap" colSpan={3}>
|
||||
{log?.comment?.length > 50
|
||||
|
@ -11,6 +11,7 @@ import { useSelector } from "react-redux";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import eventBus from "../../services/eventBus";
|
||||
import { useSelectedProject } from "../../slices/apiDataManager";
|
||||
import Pagination from "../common/Pagination";
|
||||
|
||||
const Attendance = ({ getRole, handleModalData, searchTerm, projectId, organizationId, includeInactive, date }) => {
|
||||
const queryClient = useQueryClient();
|
||||
@ -108,6 +109,8 @@ const Attendance = ({ getRole, handleModalData, searchTerm, projectId, organizat
|
||||
return () => eventBus.off("employee", employeeHandler);
|
||||
}, [employeeHandler]);
|
||||
|
||||
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
@ -138,7 +141,7 @@ const Attendance = ({ getRole, handleModalData, searchTerm, projectId, organizat
|
||||
<tr className="border-top-1">
|
||||
<th colSpan={2}>Name</th>
|
||||
<th>Role</th>
|
||||
<th>Organization</th>
|
||||
{/* <th>Organization</th> */}
|
||||
<th>
|
||||
<i className="bx bxs-down-arrow-alt text-success"></i>
|
||||
Check-In
|
||||
@ -187,7 +190,7 @@ const Attendance = ({ getRole, handleModalData, searchTerm, projectId, organizat
|
||||
</td>
|
||||
|
||||
<td>{item.jobRoleName}</td>
|
||||
<td>{item.organizationName || "--"}</td>
|
||||
{/* <td>{item.organizationName || "--"}</td> */}
|
||||
|
||||
<td>
|
||||
{item.checkInTime
|
||||
@ -226,46 +229,12 @@ const Attendance = ({ getRole, handleModalData, searchTerm, projectId, organizat
|
||||
|
||||
|
||||
{!loading && finalFilteredData.length > ITEMS_PER_PAGE && (
|
||||
<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)}
|
||||
>
|
||||
«
|
||||
</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)}
|
||||
>
|
||||
»
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
|
||||
<Pagination
|
||||
currentPage={currentPage}
|
||||
totalPages={totalPages}
|
||||
onPageChange={paginate}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
|
@ -11,6 +11,8 @@ import AttendanceRepository from "../../repositories/AttendanceRepository";
|
||||
import { useAttendancesLogs } from "../../hooks/useAttendance";
|
||||
import { queryClient } from "../../layouts/AuthLayout";
|
||||
import { ITEMS_PER_PAGE } from "../../utils/constants";
|
||||
import Pagination from "../common/Pagination";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
const usePagination = (data, itemsPerPage) => {
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
@ -33,7 +35,7 @@ const usePagination = (data, itemsPerPage) => {
|
||||
};
|
||||
};
|
||||
|
||||
const AttendanceLog = ({ handleModalData, searchTerm ,organizationId}) => {
|
||||
const AttendanceLog = ({ handleModalData, searchTerm, organizationId }) => {
|
||||
// const selectedProject = useSelector(
|
||||
// (store) => store.localVariables.projectId
|
||||
// );
|
||||
@ -45,6 +47,7 @@ const AttendanceLog = ({ handleModalData, searchTerm ,organizationId}) => {
|
||||
|
||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||
const [processedData, setProcessedData] = useState([]);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const today = new Date();
|
||||
today.setHours(0, 0, 0, 0);
|
||||
@ -84,10 +87,10 @@ const AttendanceLog = ({ handleModalData, searchTerm ,organizationId}) => {
|
||||
dateRange.endDate,
|
||||
organizationId
|
||||
);
|
||||
const filtering = (data) => {
|
||||
const filtering = useCallback((dataToFilter) => {
|
||||
const filteredData = showPending
|
||||
? data.filter((item) => item.checkOutTime === null)
|
||||
: data;
|
||||
? dataToFilter.filter((item) => item.checkOutTime === null)
|
||||
: dataToFilter;
|
||||
|
||||
const group1 = filteredData
|
||||
.filter((d) => d.activity === 1 && isSameDay(d.checkInTime))
|
||||
@ -108,14 +111,7 @@ const AttendanceLog = ({ handleModalData, searchTerm ,organizationId}) => {
|
||||
.filter((d) => d.activity === 5)
|
||||
.sort(sortByName);
|
||||
|
||||
const sortedList = [
|
||||
...group1,
|
||||
...group2,
|
||||
...group3,
|
||||
...group4,
|
||||
...group5,
|
||||
...group6,
|
||||
];
|
||||
const sortedList = [...group1, ...group2, ...group3, ...group4, ...group5, ...group6];
|
||||
|
||||
// Group by date
|
||||
const groupedByDate = sortedList.reduce((acc, item) => {
|
||||
@ -133,11 +129,15 @@ const AttendanceLog = ({ handleModalData, searchTerm ,organizationId}) => {
|
||||
|
||||
const finalData = sortedDates.flatMap((date) => groupedByDate[date]);
|
||||
setProcessedData(finalData);
|
||||
};
|
||||
}, [showPending]);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
useEffect(() => {
|
||||
if (data?.length) {
|
||||
filtering(data);
|
||||
}, [data, showPending]);
|
||||
}
|
||||
}, [data, showPending]);
|
||||
|
||||
|
||||
// New useEffect to handle search filtering
|
||||
const filteredSearchData = useMemo(() => {
|
||||
@ -151,31 +151,6 @@ const AttendanceLog = ({ handleModalData, searchTerm ,organizationId}) => {
|
||||
});
|
||||
}, [processedData, searchTerm]);
|
||||
|
||||
// const filteredSearchData = useMemo(() => {
|
||||
// let tempData = processedData;
|
||||
|
||||
// if (searchTerm) {
|
||||
// const lowercasedSearchTerm = searchTerm.toLowerCase();
|
||||
// tempData = tempData.filter((item) => {
|
||||
// const fullName = `${item.firstName} ${item.lastName}`.toLowerCase();
|
||||
// return fullName.includes(lowercasedSearchTerm);
|
||||
// });
|
||||
// }
|
||||
|
||||
// if (filters?.selectedOrganization) {
|
||||
// tempData = tempData.filter(
|
||||
// (item) => item.organization?.name === filters.selectedOrganization
|
||||
// );
|
||||
// }
|
||||
|
||||
// if (filters?.selectedServices?.length > 0) {
|
||||
// tempData = tempData.filter((item) =>
|
||||
// filters.selectedServices.includes(item.service?.name)
|
||||
// );
|
||||
// }
|
||||
|
||||
// return tempData;
|
||||
// }, [processedData, searchTerm, filters]);
|
||||
|
||||
|
||||
const {
|
||||
@ -246,18 +221,19 @@ const AttendanceLog = ({ handleModalData, searchTerm ,organizationId}) => {
|
||||
return () => eventBus.off("employee", employeeHandler);
|
||||
}, [employeeHandler]);
|
||||
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className="dataTables_length text-start py-2 d-flex justify-content-between"
|
||||
id="DataTables_Table_0_length"
|
||||
>
|
||||
<div className="d-flex align-items-center my-0 ">
|
||||
<div className="d-flex align-items-center my-0 ms-sm-8 ">
|
||||
<DateRangePicker
|
||||
onRangeChange={setDateRange}
|
||||
defaultStartDate={yesterday}
|
||||
/>
|
||||
<div className="form-check form-switch text-start m-0 ms-5">
|
||||
<div className="form-check form-switch text-start ms-1 ms-md-5 align-items-center mb-0">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="form-check-input"
|
||||
@ -270,11 +246,11 @@ const AttendanceLog = ({ handleModalData, searchTerm ,organizationId}) => {
|
||||
<label className="form-check-label ms-0">Show Pending</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
</div>
|
||||
<div className="table-responsive text-nowrap" style={{ minHeight: "200px" }}>
|
||||
<div className="table-responsive text-nowrap " >
|
||||
{isLoading ? (
|
||||
<div className="d-flex justify-content-center align-items-center" style={{ height: "200px" }}>
|
||||
<div className="d-flex justify-content-center align-items-center">
|
||||
<p className="text-secondary">Loading...</p>
|
||||
</div>
|
||||
) : filteredSearchData?.length > 0 ? (
|
||||
@ -285,7 +261,8 @@ const AttendanceLog = ({ handleModalData, searchTerm ,organizationId}) => {
|
||||
Name
|
||||
</th>
|
||||
<th className="border-top-1">Date</th>
|
||||
<th>Organization</th>
|
||||
{/* <th>Organization</th> */}
|
||||
|
||||
<th>
|
||||
<i className="bx bxs-down-arrow-alt text-success"></i> Check-In
|
||||
</th>
|
||||
@ -331,7 +308,12 @@ const AttendanceLog = ({ handleModalData, searchTerm ,organizationId}) => {
|
||||
lastName={attendance.lastName}
|
||||
/>
|
||||
<div className="d-flex flex-column">
|
||||
<a href="#" className="text-heading text-truncate">
|
||||
<a
|
||||
onClick={() =>
|
||||
navigate(`/employee/${attendance.employeeId}?for=attendance`)
|
||||
}
|
||||
className="text-heading text-truncate cursor-pointer"
|
||||
>
|
||||
<span className="fw-normal">
|
||||
{attendance.firstName} {attendance.lastName}
|
||||
</span>
|
||||
@ -344,7 +326,7 @@ const AttendanceLog = ({ handleModalData, searchTerm ,organizationId}) => {
|
||||
attendance.checkInTime || attendance.checkOutTime
|
||||
).format("DD-MMM-YYYY")}
|
||||
</td>
|
||||
<td>{attendance.organizationName || "--"}</td>
|
||||
{/* <td>{attendance.organizationName || "--"}</td> */}
|
||||
<td>{convertShortTime(attendance.checkInTime)}</td>
|
||||
<td>
|
||||
{attendance.checkOutTime
|
||||
@ -366,7 +348,7 @@ const AttendanceLog = ({ handleModalData, searchTerm ,organizationId}) => {
|
||||
</tbody>
|
||||
</table>
|
||||
) : (
|
||||
<div className="my-12"><span className="text-secondary">No data available for the selected date range. Please Select another date.</span></div>
|
||||
<div className="my-12"><span className="text-secondary">No data for this date range. Please choose another.</span></div>
|
||||
)}
|
||||
</div>
|
||||
{paginatedAttendances?.length == 0 && filteredSearchData?.length > 0 && (
|
||||
@ -378,45 +360,11 @@ const AttendanceLog = ({ handleModalData, searchTerm ,organizationId}) => {
|
||||
</div>
|
||||
)}
|
||||
{filteredSearchData.length > ITEMS_PER_PAGE && (
|
||||
<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)}
|
||||
>
|
||||
«
|
||||
</button>
|
||||
</li>
|
||||
{Array.from({ length: totalPages }, (_, i) => i + 1).map(
|
||||
(pageNumber) => (
|
||||
<li
|
||||
key={pageNumber}
|
||||
className={`page-item ${currentPage === pageNumber ? "active" : ""
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
className="page-link"
|
||||
onClick={() => paginate(pageNumber)}
|
||||
>
|
||||
{pageNumber}
|
||||
</button>
|
||||
</li>
|
||||
)
|
||||
)}
|
||||
<li
|
||||
className={`page-item ${currentPage === totalPages ? "disabled" : ""
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
className="page-link"
|
||||
onClick={() => paginate(currentPage + 1)}
|
||||
>
|
||||
»
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
<Pagination
|
||||
currentPage={currentPage}
|
||||
totalPages={totalPages}
|
||||
onPageChange={paginate}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
|
@ -1,4 +1,4 @@
|
||||
import React, { useState } from "react";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { z } from "zod";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
@ -9,6 +9,7 @@ import showToast from "../../services/toastService";
|
||||
import { checkIfCurrentDate } from "../../utils/dateUtils";
|
||||
import { useMarkAttendance } from "../../hooks/useAttendance";
|
||||
import { useSelectedProject } from "../../slices/apiDataManager";
|
||||
import { useProjectName } from "../../hooks/useProjects";
|
||||
|
||||
const createSchema = (modeldata) => {
|
||||
return z
|
||||
@ -19,31 +20,36 @@ const createSchema = (modeldata) => {
|
||||
.max(200, "Description should be less than 200 characters")
|
||||
.optional(),
|
||||
})
|
||||
.refine((data) => {
|
||||
if (modeldata?.checkInTime && !modeldata?.checkOutTime) {
|
||||
const checkIn = new Date(modeldata.checkInTime);
|
||||
const [time, modifier] = data.markTime.split(" ");
|
||||
const [hourStr, minuteStr] = time.split(":");
|
||||
let hour = parseInt(hourStr, 10);
|
||||
const minute = parseInt(minuteStr, 10);
|
||||
.refine(
|
||||
(data) => {
|
||||
if (modeldata?.checkInTime && !modeldata?.checkOutTime) {
|
||||
const checkIn = new Date(modeldata.checkInTime);
|
||||
const [time, modifier] = data.markTime.split(" ");
|
||||
const [hourStr, minuteStr] = time.split(":");
|
||||
let hour = parseInt(hourStr, 10);
|
||||
const minute = parseInt(minuteStr, 10);
|
||||
|
||||
if (modifier === "PM" && hour !== 12) hour += 12;
|
||||
if (modifier === "AM" && hour === 12) hour = 0;
|
||||
if (modifier === "PM" && hour !== 12) hour += 12;
|
||||
if (modifier === "AM" && hour === 12) hour = 0;
|
||||
|
||||
const checkOut = new Date(checkIn);
|
||||
checkOut.setHours(hour, minute, 0, 0);
|
||||
const checkOut = new Date(checkIn);
|
||||
checkOut.setHours(hour, minute, 0, 0);
|
||||
|
||||
return checkOut > checkIn;
|
||||
return checkOut >= checkIn;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
{
|
||||
message: "Checkout time must be later than check-in time",
|
||||
path: ["markTime"],
|
||||
}
|
||||
return true;
|
||||
}, {
|
||||
message: "Checkout time must be later than check-in time",
|
||||
path: ["markTime"],
|
||||
});
|
||||
);
|
||||
};
|
||||
|
||||
const CheckInCheckOut = ({ modeldata, closeModal, handleSubmitForm }) => {
|
||||
const [currentProject, setCurrentProject] = useState(null);
|
||||
const projectId = useSelectedProject();
|
||||
const { projectNames, loading } = useProjectName();
|
||||
const { mutate: MarkAttendance } = useMarkAttendance();
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const coords = usePositionTracker();
|
||||
@ -95,17 +101,24 @@ const CheckInCheckOut = ({ modeldata, closeModal, handleSubmitForm }) => {
|
||||
closeModal();
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (projectId && projectNames) {
|
||||
setCurrentProject(
|
||||
projectNames?.find((project) => project.id === projectId)
|
||||
);
|
||||
}
|
||||
}, [projectNames, projectId, loading]);
|
||||
|
||||
return (
|
||||
<form className="row g-2" onSubmit={handleSubmit(onSubmit)}>
|
||||
<div className="col-12 d-flex justify-content-center">
|
||||
<form className="row p-2" onSubmit={handleSubmit(onSubmit)}>
|
||||
<div className="col-12 d-flex justify-content-center mt-2">
|
||||
<label className="fs-5 text-dark text-center">
|
||||
{modeldata?.checkInTime && !modeldata?.checkOutTime
|
||||
? "Check-out :"
|
||||
: "Check-in :"}
|
||||
? `Check out for ${currentProject?.name}`
|
||||
: `Check In for ${currentProject?.name}`}
|
||||
</label>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="col-6 col-md-6 text-start">
|
||||
<label className="form-label" htmlFor="checkInDate">
|
||||
{modeldata?.checkInTime && !modeldata?.checkOutTime
|
||||
@ -207,7 +220,7 @@ export const Regularization = ({ modeldata, closeModal, handleSubmitForm }) => {
|
||||
};
|
||||
|
||||
return (
|
||||
<form className="row g-2" onSubmit={handleSubmit(onSubmit)}>
|
||||
<form className="row " onSubmit={handleSubmit(onSubmit)}>
|
||||
<div className="col-12 col-md-12">
|
||||
<p>Regularize Attendance</p>
|
||||
<label className="form-label" htmlFor="description">
|
||||
|
@ -9,18 +9,32 @@ import usePagination from "../../hooks/usePagination";
|
||||
import eventBus from "../../services/eventBus";
|
||||
import { cacheData, clearCacheKey, useSelectedProject } from "../../slices/apiDataManager";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import Pagination from "../common/Pagination";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { employee } from "../../data/masters";
|
||||
|
||||
const Regularization = ({ handleRequest, searchTerm,projectId, organizationId, IncludeInActive }) => {
|
||||
const Regularization = ({ handleRequest, searchTerm, projectId, organizationId, IncludeInActive }) => {
|
||||
const queryClient = useQueryClient();
|
||||
// var selectedProject = useSelector((store) => store.localVariables.projectId);
|
||||
const selectedProject = useSelectedProject();
|
||||
const [regularizesList, setregularizedList] = useState([]);
|
||||
const navigate = useNavigate();
|
||||
const { regularizes, loading, error, refetch } =
|
||||
useRegularizationRequests(selectedProject, organizationId, IncludeInActive);
|
||||
|
||||
useEffect(() => {
|
||||
setregularizedList(regularizes);
|
||||
}, [regularizes]);
|
||||
useEffect(() => {
|
||||
if (regularizes && regularizes.length) {
|
||||
setregularizedList((prev) => {
|
||||
const prevIds = prev.map((i) => i.id).join(",");
|
||||
const newIds = regularizes.map((i) => i.id).join(",");
|
||||
if (prevIds !== newIds) {
|
||||
return regularizes;
|
||||
}
|
||||
return prev;
|
||||
});
|
||||
}
|
||||
}, [regularizes]);
|
||||
|
||||
|
||||
const sortByName = (a, b) => {
|
||||
const nameA = a.firstName.toLowerCase() + a.lastName.toLowerCase();
|
||||
@ -116,6 +130,7 @@ const Regularization = ({ handleRequest, searchTerm,projectId, organizationId, I
|
||||
return () => eventBus.off("employee", employeeHandler);
|
||||
}, [employeeHandler]);
|
||||
|
||||
|
||||
return (
|
||||
<div className="table-responsive text-nowrap pb-4" style={{ minHeight: "200px" }}>
|
||||
{loading ? (
|
||||
@ -128,13 +143,16 @@ const Regularization = ({ handleRequest, searchTerm,projectId, organizationId, I
|
||||
<tr>
|
||||
<th colSpan={2}>Name</th>
|
||||
<th>Date</th>
|
||||
<th>Organization</th>
|
||||
{/* <th>Organization</th> */}
|
||||
<th>
|
||||
<i className="bx bxs-down-arrow-alt text-success"></i>Check-In
|
||||
</th>
|
||||
<th>
|
||||
<i className="bx bxs-up-arrow-alt text-danger"></i>Check-Out
|
||||
</th>
|
||||
|
||||
<th>Request By</th>
|
||||
<th>Requested At</th>
|
||||
<th>Action</th>
|
||||
</tr>
|
||||
</thead>
|
||||
@ -148,7 +166,17 @@ const Regularization = ({ handleRequest, searchTerm,projectId, organizationId, I
|
||||
lastName={att.lastName}
|
||||
/>
|
||||
<div className="d-flex flex-column">
|
||||
<a href="#" className="text-heading text-truncate">
|
||||
{/* <a href="#" className="text-heading text-truncate">
|
||||
<span className="fw-normal">
|
||||
{att.firstName} {att.lastName}
|
||||
</span>
|
||||
</a> */}
|
||||
<a
|
||||
onClick={() =>
|
||||
navigate(`/employee/${att.employeeId}?for=attendance`)
|
||||
}
|
||||
className="text-heading text-truncate cursor-pointer"
|
||||
>
|
||||
<span className="fw-normal">
|
||||
{att.firstName} {att.lastName}
|
||||
</span>
|
||||
@ -156,14 +184,25 @@ const Regularization = ({ handleRequest, searchTerm,projectId, organizationId, I
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
|
||||
<td>{moment(att.checkOutTime).format("DD-MMM-YYYY")}</td>
|
||||
|
||||
<td>{att.organizationName || "--"}</td>
|
||||
{/* <td>{att.organizationName || "--"}</td> */}
|
||||
|
||||
<td>{convertShortTime(att.checkInTime)}</td>
|
||||
<td>
|
||||
{att.checkOutTime ? convertShortTime(att.checkOutTime) : "--"}
|
||||
</td>
|
||||
<td>
|
||||
{att.requestedBy
|
||||
? `${att.requestedBy?.firstName} ${att.requestedBy?.lastName}`
|
||||
: "--"}
|
||||
</td>
|
||||
<td>
|
||||
{att.requestedAt
|
||||
? moment(att.requestedAt).format("DD-MMM-YYYY")
|
||||
: "--"}
|
||||
</td>
|
||||
<td className="text-center ">
|
||||
<RegularizationActions
|
||||
attendanceData={att}
|
||||
@ -189,43 +228,11 @@ const Regularization = ({ handleRequest, searchTerm,projectId, organizationId, I
|
||||
</div>
|
||||
)}
|
||||
{!loading && totalPages > 1 && (
|
||||
<nav aria-label="Page ">
|
||||
<ul className="pagination pagination-sm justify-content-end py-1 mt-3">
|
||||
<li className={`page-item ${currentPage === 1 ? "disabled" : ""}`}>
|
||||
<button
|
||||
className="page-link btn-xs"
|
||||
onClick={() => paginate(currentPage - 1)}
|
||||
>
|
||||
«
|
||||
</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)}
|
||||
>
|
||||
»
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
<Pagination
|
||||
currentPage={currentPage}
|
||||
totalPages={totalPages}
|
||||
onPageChange={paginate}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
@ -2,7 +2,7 @@ import React, { useState, useMemo } from "react";
|
||||
import ApexChart from "../Charts/Circle";
|
||||
import { useProjects } from "../../hooks/useProjects";
|
||||
import { useDashboard_AttendanceData } from "../../hooks/useDashboard_Data";
|
||||
import { useSelectedProject } from "../../hooks/useSelectedProject"; // ✅ your custom hook
|
||||
import { useSelectedProject } from "../../hooks/useSelectedProject";
|
||||
|
||||
const Attendance = () => {
|
||||
const { projects } = useProjects();
|
||||
@ -31,7 +31,7 @@ const selectedProjectId = useSelectedProject()
|
||||
<div className="card-header mb-1 pb-0">
|
||||
<div className="d-flex flex-wrap justify-content-between align-items-center">
|
||||
<div className="card-title mb-0 text-start">
|
||||
<h5 className="mb-1">Attendance</h5>
|
||||
<h5 className="mb-1 card-title">Attendance</h5>
|
||||
<p className="card-subtitle">Daily Attendance Data</p>
|
||||
</div>
|
||||
|
||||
|
@ -1,205 +0,0 @@
|
||||
import React, { useState, useMemo } from "react";
|
||||
import { useSelector } from "react-redux";
|
||||
import ReactApexChart from "react-apexcharts";
|
||||
import { useAttendanceOverviewData } from "../../hooks/useDashboard_Data";
|
||||
import flatColors from "../Charts/flatColor";
|
||||
import ChartSkeleton from "../Charts/Skelton";
|
||||
|
||||
const formatDate = (dateStr) => {
|
||||
const date = new Date(dateStr);
|
||||
return date.toLocaleDateString("en-GB", {
|
||||
day: "2-digit",
|
||||
month: "long",
|
||||
});
|
||||
};
|
||||
|
||||
const AttendanceOverview = () => {
|
||||
const [dayRange, setDayRange] = useState(7);
|
||||
const [view, setView] = useState("chart");
|
||||
|
||||
const projectId = useSelector((store) => store.localVariables.projectId);
|
||||
const { attendanceOverviewData, loading, error } = useAttendanceOverviewData(
|
||||
projectId,
|
||||
dayRange
|
||||
);
|
||||
|
||||
const { tableData, roles, dates } = useMemo(() => {
|
||||
const map = new Map();
|
||||
|
||||
attendanceOverviewData.forEach((entry) => {
|
||||
const date = formatDate(entry.date);
|
||||
if (!map.has(date)) map.set(date, {});
|
||||
map.get(date)[entry.role.trim()] = entry.present;
|
||||
});
|
||||
|
||||
const uniqueRoles = [
|
||||
...new Set(attendanceOverviewData.map((e) => e.role.trim())),
|
||||
];
|
||||
const sortedDates = [...map.keys()];
|
||||
const data = sortedDates.map((date) => {
|
||||
const row = { date };
|
||||
uniqueRoles.forEach((role) => {
|
||||
row[role] = map.get(date)?.[role] ?? 0;
|
||||
});
|
||||
return row;
|
||||
});
|
||||
|
||||
return {
|
||||
tableData: data,
|
||||
roles: uniqueRoles,
|
||||
dates: sortedDates,
|
||||
};
|
||||
}, [attendanceOverviewData]);
|
||||
|
||||
const chartSeries = roles.map((role) => ({
|
||||
name: role,
|
||||
data: tableData.map((row) => row[role]),
|
||||
}));
|
||||
|
||||
const chartOptions = {
|
||||
chart: {
|
||||
type: "bar",
|
||||
stacked: true,
|
||||
height: 400,
|
||||
toolbar: { show: false },
|
||||
},
|
||||
plotOptions: {
|
||||
bar: {
|
||||
borderRadius: 2,
|
||||
columnWidth: "60%",
|
||||
},
|
||||
},
|
||||
xaxis: {
|
||||
categories: tableData.map((row) => row.date),
|
||||
},
|
||||
yaxis: {
|
||||
show: true,
|
||||
axisBorder: {
|
||||
show: true,
|
||||
color: "#78909C",
|
||||
offsetX: 0,
|
||||
offsetY: 0,
|
||||
},
|
||||
axisTicks: {
|
||||
show: true,
|
||||
borderType: "solid",
|
||||
color: "#78909C",
|
||||
width: 6,
|
||||
offsetX: 0,
|
||||
offsetY: 0,
|
||||
},
|
||||
},
|
||||
legend: {
|
||||
position: "bottom",
|
||||
},
|
||||
fill: {
|
||||
opacity: 1,
|
||||
},
|
||||
colors: roles.map((_, i) => flatColors[i % flatColors.length]),
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-white p-4 rounded shadow d-flex flex-column">
|
||||
{/* Header */}
|
||||
<div className="d-flex justify-content-between align-items-center mb-3">
|
||||
<div className="card-title mb-0 text-start">
|
||||
<h5 className="mb-1 fw-bold">Attendance Overview</h5>
|
||||
<p className="card-subtitle">Role-wise present count</p>
|
||||
</div>
|
||||
<div className="d-flex gap-2">
|
||||
<select
|
||||
className="form-select form-select-sm"
|
||||
value={dayRange}
|
||||
onChange={(e) => setDayRange(Number(e.target.value))}
|
||||
>
|
||||
<option value={7}>Last 7 Days</option>
|
||||
<option value={15}>Last 15 Days</option>
|
||||
<option value={30}>Last 30 Days</option>
|
||||
</select>
|
||||
<button
|
||||
className={`btn btn-sm p-1 ${
|
||||
view === "chart" ? "btn-primary" : "btn-outline-primary"
|
||||
}`}
|
||||
onClick={() => setView("chart")}
|
||||
title="Chart View"
|
||||
>
|
||||
<i className="bx bx-bar-chart-alt-2"></i>
|
||||
</button>
|
||||
<button
|
||||
className={`btn btn-sm p-1 ${
|
||||
view === "table" ? "btn-primary" : "btn-outline-primary"
|
||||
}`}
|
||||
onClick={() => setView("table")}
|
||||
title="Table View"
|
||||
>
|
||||
<i className="bx bx-list-ul fs-5"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-grow-1 d-flex align-items-center justify-content-center">
|
||||
{loading ? (
|
||||
<ChartSkeleton />
|
||||
) : error ? (
|
||||
<p className="text-danger">{error}</p>
|
||||
) : view === "chart" ? (
|
||||
<div className="w-100">
|
||||
<ReactApexChart
|
||||
options={chartOptions}
|
||||
series={chartSeries}
|
||||
type="bar"
|
||||
height={400}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className="table-responsive w-100"
|
||||
style={{ maxHeight: "350px", overflowY: "auto" }}
|
||||
>
|
||||
<table className="table table-bordered table-sm text-start align-middle mb-0">
|
||||
<thead
|
||||
className="table-light"
|
||||
style={{ position: "sticky", top: 0, zIndex: 1 }}
|
||||
>
|
||||
<tr>
|
||||
<th style={{ background: "#f8f9fa", textTransform: "none" }}>
|
||||
Role
|
||||
</th>
|
||||
{dates.map((date, idx) => (
|
||||
<th
|
||||
key={idx}
|
||||
style={{ background: "#f8f9fa", textTransform: "none" }}
|
||||
>
|
||||
{date}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
<tbody>
|
||||
{roles.map((role) => (
|
||||
<tr key={role}>
|
||||
<td>{role}</td>
|
||||
{tableData.map((row, idx) => {
|
||||
const value = row[role];
|
||||
const cellStyle =
|
||||
value > 0 ? { backgroundColor: "#d5d5d5" } : {};
|
||||
return (
|
||||
<td key={idx} style={cellStyle}>
|
||||
{value}
|
||||
</td>
|
||||
);
|
||||
})}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AttendanceOverview;
|
137
src/components/Dashboard/AttendanceOverview.jsx
Normal file
137
src/components/Dashboard/AttendanceOverview.jsx
Normal file
@ -0,0 +1,137 @@
|
||||
import React, { useState, useMemo } from "react";
|
||||
import { useSelector } from "react-redux";
|
||||
import ReactApexChart from "react-apexcharts";
|
||||
import { useAttendanceOverviewData } from "../../hooks/useDashboard_Data";
|
||||
import flatColors from "../Charts/flatColor";
|
||||
import ChartSkeleton from "../Charts/Skelton";
|
||||
import { useSelectedProject } from "../../slices/apiDataManager";
|
||||
import { formatDate_DayMonth } from "../../utils/dateUtils";
|
||||
|
||||
|
||||
|
||||
const AttendanceOverview = () => {
|
||||
const [dayRange, setDayRange] = useState(7);
|
||||
const [view, setView] = useState("chart");
|
||||
const selectedProject = useSelectedProject();
|
||||
|
||||
const { data: attendanceOverviewData, isLoading, isError, error } = useAttendanceOverviewData(
|
||||
selectedProject,
|
||||
dayRange
|
||||
);
|
||||
|
||||
// Use empty array while loading
|
||||
const attendanceData = attendanceOverviewData || [];
|
||||
|
||||
const { tableData, roles, dates } = useMemo(() => {
|
||||
if (!attendanceData || attendanceData.length === 0) {
|
||||
return { tableData: [], roles: [], dates: [] };
|
||||
}
|
||||
|
||||
const map = new Map();
|
||||
|
||||
attendanceData.forEach((entry) => {
|
||||
const date = formatDate_DayMonth(entry.date);
|
||||
if (!map.has(date)) map.set(date, {});
|
||||
map.get(date)[entry.role.trim()] = entry.present;
|
||||
});
|
||||
|
||||
const uniqueRoles = [...new Set(attendanceData.map((e) => e.role.trim()))];
|
||||
const sortedDates = [...map.keys()];
|
||||
|
||||
const tableData = sortedDates.map((date) => {
|
||||
const row = { date };
|
||||
uniqueRoles.forEach((role) => {
|
||||
row[role] = map.get(date)?.[role] ?? 0;
|
||||
});
|
||||
return row;
|
||||
});
|
||||
|
||||
return { tableData, roles: uniqueRoles, dates: sortedDates };
|
||||
}, [attendanceData]);
|
||||
|
||||
const chartSeries = roles.map((role) => ({
|
||||
name: role,
|
||||
data: tableData.map((row) => row[role]),
|
||||
}));
|
||||
|
||||
const chartOptions = {
|
||||
chart: { type: "bar", stacked: true, height: 400, toolbar: { show: false } },
|
||||
plotOptions: { bar: { borderRadius: 2, columnWidth: "60%" } },
|
||||
xaxis: { categories: tableData.map((row) => row.date) },
|
||||
yaxis: { show: true, axisBorder: { show: true, color: "#78909C" }, axisTicks: { show: true, color: "#78909C", width: 6 } },
|
||||
legend: { position: "bottom" },
|
||||
fill: { opacity: 1 },
|
||||
colors: roles.map((_, i) => flatColors[i % flatColors.length]),
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="bg-white p-4 rounded shadow d-flex flex-column position-relative " >
|
||||
{/* Optional subtle loading overlay */}
|
||||
{isLoading && (
|
||||
<div className="position-absolute w-100 h-100 d-flex align-items-center justify-content-center bg-white bg-opacity-50 z-index-1">
|
||||
<span>Loading...</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Header */}
|
||||
<div className="d-flex justify-content-between align-items-center mb-3">
|
||||
<div className="card-title mb-0 text-start">
|
||||
<h5 className="mb-1 card-title">Attendance Overview</h5>
|
||||
<p className="card-subtitle">Role-wise present count</p>
|
||||
</div>
|
||||
<div className="d-flex gap-2">
|
||||
<select className="form-select form-select-sm" value={dayRange} onChange={(e) => setDayRange(Number(e.target.value))}>
|
||||
<option value={7}>Last 7 Days</option>
|
||||
<option value={15}>Last 15 Days</option>
|
||||
<option value={30}>Last 30 Days</option>
|
||||
</select>
|
||||
<button className={`btn btn-sm p-1 ${view === "chart" ? "btn-primary" : "btn-outline-primary"}`} onClick={() => setView("chart")} title="Chart View">
|
||||
<i className="bx bx-bar-chart-alt-2"></i>
|
||||
</button>
|
||||
<button className={`btn btn-sm p-1 ${view === "table" ? "btn-primary" : "btn-outline-primary"}`} onClick={() => setView("table")} title="Table View">
|
||||
<i className="bx bx-list-ul fs-5"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-grow-1 d-flex align-items-center justify-content-center ">
|
||||
{!isLoading && (!attendanceData || attendanceData.length === 0) ? (
|
||||
<div
|
||||
className="text-muted fw-semibold d-flex align-items-center justify-content-center"
|
||||
style={{ minHeight: "250px" }}>No data found</div>
|
||||
) : view === "chart" ? (
|
||||
<div className="w-100">
|
||||
<ReactApexChart options={chartOptions} series={chartSeries} type="bar" height={300} />
|
||||
</div>
|
||||
) : (
|
||||
<div className="table-responsive w-100" style={{ maxHeight: "350px", overflowY: "auto" }}>
|
||||
<table className="table table-bordered table-sm text-start align-middle mb-0">
|
||||
<thead className="table-light" style={{ position: "sticky", top: 0, zIndex: 1 }}>
|
||||
<tr>
|
||||
<th style={{ background: "#f8f9fa", textTransform: "none" }}>Role</th>
|
||||
{dates.map((date, idx) => (
|
||||
<th key={idx} style={{ background: "#f8f9fa", textTransform: "none" }}>{date}</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{roles.map((role) => (
|
||||
<tr key={role}>
|
||||
<td>{role}</td>
|
||||
{tableData.map((row, idx) => {
|
||||
const value = row[role];
|
||||
return <td key={idx} style={value > 0 ? { backgroundColor: "#d5d5d5" } : {}}>{value}</td>;
|
||||
})}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AttendanceOverview;
|
@ -1,69 +1,63 @@
|
||||
import React from "react";
|
||||
import { useSelector } from "react-redux";
|
||||
import {
|
||||
useDashboardProjectsCardData,
|
||||
useDashboardTeamsCardData,
|
||||
useDashboardTasksCardData,
|
||||
useAttendanceOverviewData
|
||||
} from "../../hooks/useDashboard_Data";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { useDispatch, useSelector } from "react-redux";
|
||||
// import {
|
||||
// useDashboardProjectsCardData,
|
||||
// useDashboardTeamsCardData,
|
||||
// useDashboardTasksCardData,
|
||||
// useAttendanceOverviewData
|
||||
// } from "../../hooks/useDashboard_Data";
|
||||
|
||||
import Projects from "./Projects";
|
||||
import Teams from "./Teams";
|
||||
import TasksCard from "./Tasks";
|
||||
import ProjectCompletionChart from "./ProjectCompletionChart";
|
||||
import ProjectProgressChart from "./ProjectProgressChart";
|
||||
import ProjectOverview from "../Project/ProjectOverview";
|
||||
import AttendanceOverview from "./AttendanceChart";
|
||||
// import Projects from "./Projects";
|
||||
// import Teams from "./Teams";
|
||||
// import TasksCard from "./Tasks";
|
||||
// import ProjectCompletionChart from "./ProjectCompletionChart";
|
||||
// import ProjectProgressChart from "./ProjectProgressChart";
|
||||
// import ProjectOverview from "../Project/ProjectOverview";
|
||||
import AttendanceOverview from "./AttendanceOverview";
|
||||
import { useSelectedProject } from "../../slices/apiDataManager";
|
||||
import { useProjectName } from "../../hooks/useProjects";
|
||||
import ExpenseAnalysis from "./ExpenseAnalysis";
|
||||
import ExpenseStatus from "./ExpenseStatus";
|
||||
import ExpenseByProject from "./ExpenseByProject";
|
||||
|
||||
const Dashboard = () => {
|
||||
const { projectsCardData } = useDashboardProjectsCardData();
|
||||
const { teamsCardData } = useDashboardTeamsCardData();
|
||||
const { tasksCardData } = useDashboardTasksCardData();
|
||||
// const { projectsCardData } = useDashboardProjectsCardData();
|
||||
// const { teamsCardData } = useDashboardTeamsCardData();
|
||||
// const { tasksCardData } = useDashboardTasksCardData();
|
||||
|
||||
// Get the selected project ID from Redux store
|
||||
const projectId = useSelector((store) => store.localVariables.projectId);
|
||||
const isAllProjectsSelected = projectId === null;
|
||||
// Get the selected project ID from Redux store
|
||||
const projectId = useSelector((store) => store.localVariables.projectId);
|
||||
const isAllProjectsSelected = projectId === null;
|
||||
|
||||
return (
|
||||
<div className="container-fluid mt-5">
|
||||
<div className="row gy-4">
|
||||
{isAllProjectsSelected && (
|
||||
<div className="col-sm-6 col-lg-4">
|
||||
<Projects projectsCardData={projectsCardData} />
|
||||
</div>
|
||||
)}
|
||||
return (
|
||||
<div className="container-fluid py-5">
|
||||
<div className="row mb-6 g-6">
|
||||
<div className="col-12 col-xl-8">
|
||||
<div className="card h-100">
|
||||
<ExpenseAnalysis />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={`${!isAllProjectsSelected ? "col-sm-6 col-lg-6" : "col-sm-6 col-lg-4"}`}>
|
||||
<Teams teamsCardData={teamsCardData} />
|
||||
</div>
|
||||
<div className="col-12 col-xl-4 col-md-6">
|
||||
<div className="card ">
|
||||
<ExpenseStatus />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={`${!isAllProjectsSelected ? "col-sm-6 col-lg-6" : "col-sm-6 col-lg-4"}`}>
|
||||
<TasksCard tasksCardData={tasksCardData} />
|
||||
</div>
|
||||
<div className="row ">
|
||||
{!isAllProjectsSelected && (
|
||||
<div className="col-12 col-md-6 mb-sm-0 mb-4 ">
|
||||
<AttendanceOverview />
|
||||
</div>
|
||||
)}
|
||||
<div className="col-12 col-md-6">
|
||||
<ExpenseByProject />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isAllProjectsSelected && (
|
||||
<div className="col-xxl-6 col-lg-6">
|
||||
<ProjectCompletionChart />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isAllProjectsSelected && (
|
||||
<div className="col-xxl-6 col-lg-6">
|
||||
<ProjectOverview />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="col-xxl-6 col-lg-6">
|
||||
<ProjectProgressChart />
|
||||
</div>
|
||||
{!isAllProjectsSelected && (
|
||||
<div className="col-xxl-6 col-lg-6">
|
||||
<AttendanceOverview /> {/* ✅ Removed unnecessary projectId prop */}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
);
|
||||
};
|
||||
|
||||
export default Dashboard;
|
||||
export default Dashboard;
|
||||
|
151
src/components/Dashboard/ExpenseAnalysis.jsx
Normal file
151
src/components/Dashboard/ExpenseAnalysis.jsx
Normal file
@ -0,0 +1,151 @@
|
||||
import React, { useEffect, useMemo } from "react";
|
||||
import Chart from "react-apexcharts";
|
||||
import { useExpenseAnalysis } from "../../hooks/useDashboard_Data";
|
||||
import { useSelectedProject } from "../../slices/apiDataManager";
|
||||
import { DateRangePicker1 } from "../common/DateRangePicker";
|
||||
import { FormProvider, useForm } from "react-hook-form";
|
||||
import { formatCurrency, localToUtc } from "../../utils/appUtils";
|
||||
|
||||
const ExpenseAnalysis = () => {
|
||||
const projectId = useSelectedProject();
|
||||
|
||||
const methods = useForm({
|
||||
defaultValues: { startDate: "", endDate: "" },
|
||||
});
|
||||
|
||||
const { watch } = methods;
|
||||
const [startDate, endDate] = watch(["startDate", "endDate"]);
|
||||
|
||||
const { data, isLoading, isError, error, isFetching } = useExpenseAnalysis(
|
||||
projectId,
|
||||
startDate ? localToUtc(startDate) : null,
|
||||
endDate ? localToUtc(endDate) : null
|
||||
);
|
||||
|
||||
if (isError) return <div>{error.message}</div>;
|
||||
|
||||
const report = data?.report ?? [];
|
||||
const { labels, series, total } = useMemo(() => {
|
||||
const labels = report.map((item) => item.projectName);
|
||||
const series = report.map((item) => item.totalApprovedAmount || 0);
|
||||
const total = formatCurrency(data?.totalAmount || 0);
|
||||
return { labels, series, total };
|
||||
}, [report, data?.totalAmount]);
|
||||
|
||||
const donutOptions = {
|
||||
chart: { type: "donut" },
|
||||
labels,
|
||||
legend: { show: false },
|
||||
dataLabels: { enabled: true, formatter: (val) => `${val.toFixed(0)}%` },
|
||||
colors: ["#7367F0", "#28C76F", "#FF9F43", "#EA5455", "#00CFE8", "#FF78B8"],
|
||||
plotOptions: {
|
||||
pie: {
|
||||
donut: {
|
||||
size: "70%",
|
||||
labels: {
|
||||
show: true,
|
||||
total: {
|
||||
show: true,
|
||||
label: "Total",
|
||||
fontSize: "16px",
|
||||
formatter: () => `${total}`,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
responsive: [
|
||||
{
|
||||
breakpoint: 576, // mobile breakpoint
|
||||
options: {
|
||||
chart: { width: "100%" },
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Header */}
|
||||
<div className="card-header d-flex flex-column flex-sm-row justify-content-between align-items-start align-items-sm-center gap-2">
|
||||
<div className="text-start w-100">
|
||||
<h5 className="mb-1 card-title">Expense Breakdown</h5>
|
||||
<p className="card-subtitle mb-0">Category Wise Expense Breakdown</p>
|
||||
</div>
|
||||
|
||||
<div className="text-start text-sm-end w-75">
|
||||
<FormProvider {...methods}>
|
||||
<DateRangePicker1 />
|
||||
</FormProvider>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Card body */}
|
||||
<div className="card-body position-relative">
|
||||
{isLoading && (
|
||||
<div
|
||||
className="d-flex justify-content-center align-items-center"
|
||||
style={{ height: "200px" }}
|
||||
>
|
||||
<span>Loading...</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isLoading && report.length === 0 && (
|
||||
<div className="text-center py-5 text-muted">No data found</div>
|
||||
)}
|
||||
|
||||
{!isLoading && report.length > 0 && (
|
||||
<>
|
||||
{isFetching && (
|
||||
<div className="position-absolute top-0 start-0 w-100 h-100 d-flex justify-content-center align-items-center bg-white bg-opacity-75">
|
||||
<span>Loading...</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="d-flex justify-content-center mb-3">
|
||||
<Chart
|
||||
options={donutOptions}
|
||||
series={series}
|
||||
type="donut"
|
||||
width="100%"
|
||||
height={320}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="mb-2 w-100">
|
||||
<div className="row g-2">
|
||||
{report.map((item, idx) => (
|
||||
<div
|
||||
className="col-12 col-sm-6 d-flex align-items-start"
|
||||
key={idx}
|
||||
>
|
||||
<div className="avatar me-2">
|
||||
<span
|
||||
className="avatar-initial rounded-2"
|
||||
style={{
|
||||
backgroundColor:
|
||||
donutOptions.colors[idx % donutOptions.colors.length],
|
||||
}}
|
||||
>
|
||||
<i className="bx bx-receipt fs-4"></i>
|
||||
</span>
|
||||
</div>
|
||||
<div className="d-flex flex-column gap-1 text-start">
|
||||
<small className="fw-semibold">{item.projectName}</small>
|
||||
<span className="fw-semibold text-muted ms-1">
|
||||
{formatCurrency(item.totalApprovedAmount)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default ExpenseAnalysis;
|
164
src/components/Dashboard/ExpenseByProject.jsx
Normal file
164
src/components/Dashboard/ExpenseByProject.jsx
Normal file
@ -0,0 +1,164 @@
|
||||
import React, { useState, useEffect } from "react";
|
||||
import Chart from "react-apexcharts";
|
||||
import { useExpenseType } from "../../hooks/masterHook/useMaster";
|
||||
import { useSelector } from "react-redux";
|
||||
import { useExpenseDataByProject } from "../../hooks/useDashboard_Data";
|
||||
import { formatCurrency } from "../../utils/appUtils";
|
||||
import { formatDate_DayMonth } from "../../utils/dateUtils";
|
||||
|
||||
const ExpenseByProject = () => {
|
||||
const projectId = useSelector((store) => store.localVariables.projectId);
|
||||
const [range, setRange] = useState("12M");
|
||||
const [selectedType, setSelectedType] = useState("");
|
||||
const [viewMode, setViewMode] = useState("Category");
|
||||
const [chartData, setChartData] = useState({ categories: [], data: [] });
|
||||
|
||||
const { ExpenseTypes, loading: typeLoading } = useExpenseType();
|
||||
|
||||
const { data: expenseApiData, isLoading } = useExpenseDataByProject(
|
||||
projectId,
|
||||
selectedType,
|
||||
range === "All" ? null : parseInt(range)
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (expenseApiData) {
|
||||
const categories = expenseApiData.map((item) =>
|
||||
formatDate_DayMonth(item.monthName, item.year)
|
||||
);
|
||||
const data = expenseApiData.map((item) => item.total);
|
||||
setChartData({ categories, data });
|
||||
} else {
|
||||
setChartData({ categories: [], data: [] });
|
||||
}
|
||||
}, [expenseApiData]);
|
||||
|
||||
const getSelectedTypeName = () => {
|
||||
if (!selectedType) return "All Types";
|
||||
const found = ExpenseTypes.find((t) => t.id === selectedType);
|
||||
return found ? found.name : "All Types";
|
||||
};
|
||||
|
||||
const options = {
|
||||
chart: { type: "bar", toolbar: { show: false } },
|
||||
plotOptions: {
|
||||
bar: { horizontal: false, columnWidth: "55%", borderRadius: 4 },
|
||||
},
|
||||
dataLabels: { enabled: true, formatter: (val) => formatCurrency(val) },
|
||||
xaxis: {
|
||||
categories: chartData.categories,
|
||||
labels: { style: { fontSize: "12px" }, rotate: -45 },
|
||||
},
|
||||
tooltip: {
|
||||
y: {
|
||||
formatter: (val) => `${formatCurrency(val)} (${getSelectedTypeName()})`,
|
||||
},
|
||||
},
|
||||
|
||||
annotations: { xaxis: [{ x: 0, strokeDashArray: 0 }] },
|
||||
fill: { opacity: 1 },
|
||||
colors: ["#2196f3"],
|
||||
};
|
||||
|
||||
const series = [
|
||||
{
|
||||
name: getSelectedTypeName(),
|
||||
data: chartData.data,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="card shadow-sm rounded ">
|
||||
{/* Header */}
|
||||
<div className="card-header">
|
||||
<div className="d-flex justify-content-start align-items-center mb-3 mt-3">
|
||||
<div>
|
||||
<h5 className="mb-1 me-6 card-title">Monthly Expense -</h5>
|
||||
<p className="card-subtitle me-5 mb-0">Detailed project expenses</p>
|
||||
</div>
|
||||
<div className="btn-group mb-4 ms-n8">
|
||||
<button
|
||||
className="btn btn-sm dropdown-toggle fs-5"
|
||||
type="button"
|
||||
data-bs-toggle="dropdown"
|
||||
aria-expanded="false"
|
||||
>
|
||||
{viewMode}
|
||||
</button>
|
||||
<ul className="dropdown-menu dropdown-menu-end ">
|
||||
<li>
|
||||
<button
|
||||
className="dropdown-item"
|
||||
onClick={() => {
|
||||
setViewMode("Category");
|
||||
setSelectedType("");
|
||||
}}
|
||||
>
|
||||
Category
|
||||
</button>
|
||||
</li>
|
||||
<li>
|
||||
<button
|
||||
className="dropdown-item"
|
||||
onClick={() => {
|
||||
setViewMode("Project");
|
||||
setSelectedType("");
|
||||
}}
|
||||
>
|
||||
Project
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Range Buttons + Expense Dropdown */}
|
||||
<div className="d-flex align-items-center flex-wrap ">
|
||||
{["1M", "3M", "6M", "12M", "All"].map((item) => (
|
||||
<button
|
||||
key={item}
|
||||
className={`border-0 px-2 py-1 text-sm rounded ${range === item
|
||||
? "text-white bg-primary"
|
||||
: "text-body bg-transparent"
|
||||
}`}
|
||||
style={{ cursor: "pointer", transition: "all 0.2s ease" }}
|
||||
onClick={() => setRange(item)}
|
||||
>
|
||||
{item}
|
||||
</button>
|
||||
))}
|
||||
{viewMode === "Category" && (
|
||||
<select
|
||||
className="form-select form-select-sm ms-auto mb-3 mt-1 mt-sm-0"
|
||||
value={selectedType}
|
||||
onChange={(e) => setSelectedType(e.target.value)}
|
||||
disabled={typeLoading}
|
||||
style={{ maxWidth: "200px" }}
|
||||
>
|
||||
<option value="">All Types</option>
|
||||
{ExpenseTypes.map((type) => (
|
||||
<option key={type.id} value={type.id}>
|
||||
{type.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Chart */}
|
||||
<div className="card-body bg-white text-dark p-3 rounded" style={{ minHeight: "210px" }}>
|
||||
{isLoading ? (
|
||||
<p>Loading chart...</p>
|
||||
) : !expenseApiData || expenseApiData.length === 0 ? (
|
||||
<div className="text-center text-muted py-5">No data found</div>
|
||||
) : (
|
||||
<Chart options={options} series={series} type="bar" height={235} />
|
||||
)}
|
||||
</div>
|
||||
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ExpenseByProject;
|
156
src/components/Dashboard/ExpenseStatus.jsx
Normal file
156
src/components/Dashboard/ExpenseStatus.jsx
Normal file
@ -0,0 +1,156 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { useExpense } from "../../hooks/useExpense";
|
||||
import { useExpenseStatus } from "../../hooks/useDashboard_Data";
|
||||
import { useSelectedProject } from "../../slices/apiDataManager";
|
||||
import { useProjectName } from "../../hooks/useProjects";
|
||||
import { countDigit, formatCurrency } from "../../utils/appUtils";
|
||||
import { EXPENSE_MANAGE, EXPENSE_STATUS } from "../../utils/constants";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
|
||||
|
||||
const ExpenseStatus = () => {
|
||||
const [projectName, setProjectName] = useState("All Project");
|
||||
const selectedProject = useSelectedProject();
|
||||
const { projectNames, loading } = useProjectName();
|
||||
const { data, isPending, error } = useExpenseStatus(selectedProject);
|
||||
const navigate = useNavigate();
|
||||
const isManageExpense = useHasUserPermission(EXPENSE_MANAGE)
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedProject && projectNames?.length) {
|
||||
const project = projectNames.find((p) => p.id === selectedProject);
|
||||
setProjectName(project?.name || "All Project");
|
||||
} else {
|
||||
setProjectName("All Project");
|
||||
}
|
||||
}, [projectNames, selectedProject]);
|
||||
|
||||
const handleNavigate = (status) => {
|
||||
if (selectedProject) {
|
||||
navigate(`/expenses/${status}/${selectedProject}`);
|
||||
} else {
|
||||
navigate(`/expenses/${status}`);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<div className="card-header d-flex justify-content-between text-start ">
|
||||
<div className="m-0">
|
||||
<h5 className="card-title mb-1">Expense - By Status</h5>
|
||||
<p className="card-subtitle m-0 ">{projectName}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="card-body ">
|
||||
|
||||
<div className="report-list text-start">
|
||||
{[
|
||||
{
|
||||
title: "Pending Payment",
|
||||
count: data?.processPending?.count || 0,
|
||||
amount: data?.processPending?.totalAmount || 0,
|
||||
icon: "bx bx-rupee",
|
||||
iconColor: "text-primary",
|
||||
status: EXPENSE_STATUS.payment_pending,
|
||||
},
|
||||
{
|
||||
title: "Pending Approve",
|
||||
count: data?.approvePending?.count || 0,
|
||||
amount: data?.approvePending?.totalAmount || 0,
|
||||
icon: "fa-solid fa-check",
|
||||
iconColor: "text-warning",
|
||||
status: EXPENSE_STATUS.approve_pending,
|
||||
},
|
||||
{
|
||||
title: "Pending Review",
|
||||
count: data?.reviewPending?.count || 0,
|
||||
amount: data?.reviewPending?.totalAmount || 0,
|
||||
icon: "bx bx-search-alt-2",
|
||||
iconColor: "text-secondary",
|
||||
status: EXPENSE_STATUS.review_pending,
|
||||
},
|
||||
{
|
||||
title: "Draft",
|
||||
count: data?.draft?.count || 0,
|
||||
amount: data?.draft?.totalAmount || 0,
|
||||
icon: "bx bx-file-blank",
|
||||
iconColor: "text-info",
|
||||
status: EXPENSE_STATUS.daft,
|
||||
},
|
||||
].map((item, idx) => (
|
||||
<div
|
||||
key={idx}
|
||||
className="report-list-item rounded-2 mb-4 bg-lighter px-2 py-1 cursor-pointer"
|
||||
onClick={() => handleNavigate(item?.status)}
|
||||
>
|
||||
<div className="d-flex align-items-center">
|
||||
<div className="report-list-icon shadow-xs me-2">
|
||||
<span className="d-inline-flex align-items-center justify-content-center rounded-circle border p-2">
|
||||
<i className={`${item?.icon} ${item?.iconColor} bx-lg`}></i>
|
||||
</span>
|
||||
</div>
|
||||
<div className="d-flex justify-content-between align-items-center w-100 flex-wrap gap-2">
|
||||
<div className="d-flex flex-column gap-2">
|
||||
<span className="fw-bold">{item?.title}</span>
|
||||
{item?.amount ? (
|
||||
<small className="mb-0 text-primary">
|
||||
{formatCurrency(item?.amount)}
|
||||
</small>
|
||||
) : (
|
||||
<small className="mb-0 text-primary">{formatCurrency(0)}</small>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<small
|
||||
className={`text-royalblue ${countDigit(item?.count || 0) >= 3 ? "text-xl" : "text-2xl"
|
||||
} text-gray-500`}
|
||||
>
|
||||
{item?.count || 0}
|
||||
</small>
|
||||
<small className="text-muted fs-semibold text-royalblue text-md">
|
||||
<i className="bx bx-chevron-right"></i>
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className=" py-0 text-start mb-2">
|
||||
{isManageExpense && (
|
||||
<div
|
||||
className="d-flex justify-content-between align-items-center cursor-pointer"
|
||||
onClick={() => handleNavigate(EXPENSE_STATUS.process_pending)}
|
||||
>
|
||||
<div className="d-block">
|
||||
<span
|
||||
className={`fs-semibold d-block ${countDigit(data?.totalAmount || 0) > 3 ? "text-base" : "text-lg"
|
||||
}`}
|
||||
>
|
||||
Project Spendings:
|
||||
</span>{" "}
|
||||
<small className="d-block text-xxs text-gary-80">
|
||||
(All Processed Payments)
|
||||
</small>
|
||||
</div>
|
||||
<div className="d-flex align-items-center gap-2">
|
||||
<span
|
||||
className={`text-end text-royalblue ${countDigit(data?.totalAmount || 0) > 3 ? "text-" : "text-3xl"
|
||||
} text-md`}
|
||||
>
|
||||
{formatCurrency(data?.totalAmount || 0)}
|
||||
</span>
|
||||
<small className="text-muted fs-semibold text-royalblue text-md">
|
||||
<i className="bx bx-chevron-right"></i>
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default ExpenseStatus;
|
@ -19,8 +19,11 @@ const AssignedBucket = ({ selectedBucket, handleClose }) => {
|
||||
}
|
||||
}, [selectedBucket, employeesList]);
|
||||
|
||||
const { mutate: AssignEmployee, isPending } = useAssignEmpToBucket(() =>
|
||||
const { mutate: AssignEmployee, isPending } = useAssignEmpToBucket(() =>{
|
||||
setSelectedEmployees([])
|
||||
handleClose()
|
||||
}
|
||||
|
||||
);
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
|
@ -4,8 +4,9 @@ import Pagination from "../common/Pagination";
|
||||
import { useDirectoryContext } from "../../pages/Directory/DirectoryPage";
|
||||
import { useActiveInActiveContact } from "../../hooks/useDirectory";
|
||||
import ConfirmModal from "../common/ConfirmModal";
|
||||
import Loader from "../common/Loader";
|
||||
|
||||
const ListViewContact = ({ data, Pagination }) => {
|
||||
const ListViewContact = ({ data, Pagination, isLoading }) => {
|
||||
const { showActive, setManageContact, setContactOpen } =
|
||||
useDirectoryContext();
|
||||
const [deleteContact, setDeleteContact] = useState({
|
||||
@ -85,6 +86,8 @@ const ListViewContact = ({ data, Pagination }) => {
|
||||
ActiveInActive({ contactId: contactId, contactStatus: !showActive });
|
||||
};
|
||||
|
||||
if(isLoading) return <Loader/>
|
||||
if(!data|| data.length === 0)return <div className="text-center py-12">No Contact Found</div>
|
||||
return (
|
||||
<>
|
||||
<ConfirmModal
|
||||
@ -97,103 +100,97 @@ const ListViewContact = ({ data, Pagination }) => {
|
||||
paramData={deleteContact.contactId}
|
||||
isOpen={deleteContact.Open}
|
||||
/>
|
||||
<div className="card ">
|
||||
<div className="card page-min-h">
|
||||
<div
|
||||
className="card-datatable table-responsive"
|
||||
id="horizontal-example"
|
||||
>
|
||||
<div className="dataTables_wrapper no-footer mx-5 pb-2">
|
||||
<table className="table dataTable text-nowrap">
|
||||
<thead>
|
||||
<tr className="table_header_border">
|
||||
{contactList?.map((col) => (
|
||||
<th key={col.key} className={col.align}>
|
||||
{col.label}
|
||||
|
||||
{data && (
|
||||
<div className="dataTables_wrapper no-footer mx-5 pb-2">
|
||||
<table className="table dataTable text-nowrap">
|
||||
<thead>
|
||||
<tr className="table_header_border">
|
||||
{contactList?.map((col) => (
|
||||
<th key={col.key} className={col.align}>
|
||||
{col.label}
|
||||
</th>
|
||||
))}
|
||||
<th className="sticky-action-column bg-white text-center">
|
||||
Action
|
||||
</th>
|
||||
))}
|
||||
<th className="sticky-action-column bg-white text-center">
|
||||
Action
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody >
|
||||
{Array.isArray(data) && data.length > 0 ? (
|
||||
data.map((row, i) => (
|
||||
<tr
|
||||
key={i}
|
||||
style={{ background: `${!showActive ? "#f8f6f6" : ""}` }}
|
||||
>
|
||||
{contactList.map((col) => (
|
||||
<td key={col.key} className={col.align}>
|
||||
{col.getValue(row)}
|
||||
</td>
|
||||
))}
|
||||
<td className="text-center">
|
||||
{showActive ? (
|
||||
<div className="d-flex justify-content-center gap-2">
|
||||
<i
|
||||
className="bx bx-show text-primary cursor-pointer"
|
||||
onClick={() =>
|
||||
setContactOpen({ contact: row, Open: true })
|
||||
}
|
||||
></i>
|
||||
|
||||
<i
|
||||
className="bx bx-edit text-secondary cursor-pointer"
|
||||
onClick={() =>
|
||||
setManageContact({
|
||||
isOpen: true,
|
||||
contactId: row.id,
|
||||
})
|
||||
}
|
||||
></i>
|
||||
|
||||
<i
|
||||
className="bx bx-trash text-danger cursor-pointer"
|
||||
onClick={() =>
|
||||
setDeleteContact({
|
||||
contactId: row.id,
|
||||
Open: true,
|
||||
})
|
||||
}
|
||||
></i>
|
||||
</div>
|
||||
) : (
|
||||
<i
|
||||
className={`bx ${
|
||||
isPending && activeContact === row.id
|
||||
? "bx-loader-alt bx-spin"
|
||||
: "bx-recycle"
|
||||
} me-1 text-primary cursor-pointer`}
|
||||
title="Restore"
|
||||
onClick={() => {
|
||||
setActiveContact(row.id);
|
||||
handleActiveInactive(row.id);
|
||||
}}
|
||||
></i>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
) : (
|
||||
<tr style={{ height: "200px" }}>
|
||||
<td
|
||||
colSpan={contactList.length + 1}
|
||||
className="text-center align-middle"
|
||||
>
|
||||
No contacts found
|
||||
</td>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{Array.isArray(data) && data.length > 0 && (
|
||||
data.map((row, i) => (
|
||||
<tr
|
||||
key={i}
|
||||
style={{
|
||||
background: `${!showActive ? "#f8f6f6" : ""}`,
|
||||
}}
|
||||
>
|
||||
{contactList.map((col) => (
|
||||
<td key={col.key} className={col.align}>
|
||||
{col.getValue(row)}
|
||||
</td>
|
||||
))}
|
||||
<td className="text-center">
|
||||
{showActive ? (
|
||||
<div className="d-flex justify-content-center gap-2">
|
||||
<i
|
||||
className="bx bx-show text-primary cursor-pointer"
|
||||
onClick={() =>
|
||||
setContactOpen({ contact: row, Open: true })
|
||||
}
|
||||
></i>
|
||||
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
{Pagination && (
|
||||
<div className="d-flex justify-content-start">
|
||||
{Pagination}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<i
|
||||
className="bx bx-edit text-secondary cursor-pointer"
|
||||
onClick={() =>
|
||||
setManageContact({
|
||||
isOpen: true,
|
||||
contactId: row.id,
|
||||
})
|
||||
}
|
||||
></i>
|
||||
|
||||
<i
|
||||
className="bx bx-trash text-danger cursor-pointer"
|
||||
onClick={() =>
|
||||
setDeleteContact({
|
||||
contactId: row.id,
|
||||
Open: true,
|
||||
})
|
||||
}
|
||||
></i>
|
||||
</div>
|
||||
) : (
|
||||
<i
|
||||
className={`bx ${
|
||||
isPending && activeContact === row.id
|
||||
? "bx-loader-alt bx-spin"
|
||||
: "bx-recycle"
|
||||
} me-1 text-primary cursor-pointer`}
|
||||
title="Restore"
|
||||
onClick={() => {
|
||||
setActiveContact(row.id);
|
||||
handleActiveInactive(row.id);
|
||||
}}
|
||||
></i>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
) }
|
||||
</tbody>
|
||||
</table>
|
||||
{Pagination && (
|
||||
<div className="d-flex justify-content-start">{Pagination}</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
|
@ -23,7 +23,7 @@ import Label from "../common/Label";
|
||||
const ManageContact = ({ contactId, closeModal }) => {
|
||||
// fetch master data
|
||||
const { buckets, loading: bucketsLoaging } = useBuckets();
|
||||
const { projects, loading: projectLoading } = useProjects();
|
||||
const { data: projects, loading: projectLoading } = useProjects();
|
||||
const { contactCategory, loading: contactCategoryLoading } =
|
||||
useContactCategory();
|
||||
const { organizationList } = useOrganization();
|
||||
@ -205,13 +205,14 @@ const ManageContact = ({ contactId, closeModal }) => {
|
||||
<Label htmlFor={"organization"} required>
|
||||
Organization
|
||||
</Label>
|
||||
<InputSuggestions
|
||||
organizationList={organizationList}
|
||||
value={watch("organization") || ""}
|
||||
onChange={(val) => setValue("organization", val, { shouldValidate: true })}
|
||||
error={errors.organization?.message}
|
||||
/>
|
||||
|
||||
<InputSuggestions
|
||||
organizationList={organizationList}
|
||||
value={watch("organization") || ""}
|
||||
onChange={(val) =>
|
||||
setValue("organization", val, { shouldValidate: true })
|
||||
}
|
||||
error={errors.organization?.message}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -394,6 +395,7 @@ const ManageContact = ({ contactId, closeModal }) => {
|
||||
labelKey="name"
|
||||
valueKey="id"
|
||||
IsLoading={projectLoading}
|
||||
|
||||
/>
|
||||
{errors.projectIds && (
|
||||
<small className="danger-text">{errors.projectIds.message}</small>
|
||||
@ -408,6 +410,7 @@ const ManageContact = ({ contactId, closeModal }) => {
|
||||
label="Tags"
|
||||
options={contactTags}
|
||||
isRequired={true}
|
||||
require
|
||||
/>
|
||||
{errors.tags && (
|
||||
<small className="danger-text">{errors.tags.message}</small>
|
||||
@ -417,7 +420,7 @@ const ManageContact = ({ contactId, closeModal }) => {
|
||||
{/* Buckets */}
|
||||
<div className="row">
|
||||
<div className="col-md-12 mt-1 text-start">
|
||||
<label className="form-label ">Select Bucket</label>
|
||||
<Label required>Select Bucket</Label>
|
||||
<ul className="d-flex flex-wrap px-1 list-unstyled mb-0">
|
||||
{bucketsLoaging && <p>Loading...</p>}
|
||||
{buckets?.map((item) => (
|
||||
@ -450,7 +453,7 @@ const ManageContact = ({ contactId, closeModal }) => {
|
||||
</div>
|
||||
|
||||
{/* Address + Description */}
|
||||
<div className="col-12 text-start">
|
||||
<div className="col-12 text-start mb-2">
|
||||
<label className="form-label">Address</label>
|
||||
<textarea
|
||||
className="form-control form-control-sm"
|
||||
@ -459,7 +462,7 @@ const ManageContact = ({ contactId, closeModal }) => {
|
||||
/>
|
||||
</div>
|
||||
<div className="col-12 text-start">
|
||||
<label className="form-label">Description</label>
|
||||
<Label required>Description</Label>
|
||||
<textarea
|
||||
className="form-control form-control-sm"
|
||||
rows="2"
|
||||
@ -479,10 +482,13 @@ const ManageContact = ({ contactId, closeModal }) => {
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button className="btn btn-sm btn-primary" type="submit" disabled={isPending}>
|
||||
<button
|
||||
className="btn btn-sm btn-primary"
|
||||
type="submit"
|
||||
disabled={isPending}
|
||||
>
|
||||
{isPending ? "Please Wait..." : "Submit"}
|
||||
</button>
|
||||
|
||||
</div>
|
||||
</form>
|
||||
</FormProvider>
|
||||
|
94
src/components/Documents/DocumentFilterChips.jsx
Normal file
94
src/components/Documents/DocumentFilterChips.jsx
Normal file
@ -0,0 +1,94 @@
|
||||
import React, { useMemo } from "react";
|
||||
import moment from "moment";
|
||||
|
||||
const DocumentFilterChips = ({ filters, filterData, removeFilterChip }) => {
|
||||
// Normalize structure: handle both "filterData.data" and plain "filterData"
|
||||
const data = filterData?.data || filterData || {};
|
||||
|
||||
const filterChips = useMemo(() => {
|
||||
const chips = [];
|
||||
|
||||
const buildGroup = (ids, list, label, key) => {
|
||||
if (!ids?.length) return;
|
||||
const items = ids.map((id) => ({
|
||||
id,
|
||||
name: list?.find((item) => item.id === id)?.name || id,
|
||||
}));
|
||||
chips.push({ key, label, items });
|
||||
};
|
||||
|
||||
// Build chips using normalized data
|
||||
buildGroup(filters.uploadedByIds, data.uploadedBy || [], "Uploaded By", "uploadedByIds");
|
||||
buildGroup(filters.documentCategoryIds, data.documentCategory || [], "Category", "documentCategoryIds");
|
||||
buildGroup(filters.documentTypeIds, data.documentType || [], "Type", "documentTypeIds");
|
||||
buildGroup(filters.documentTagIds, data.documentTag || [], "Tags", "documentTagIds");
|
||||
|
||||
if (filters.statusIds?.length) {
|
||||
const items = filters.statusIds.map((status) => ({
|
||||
id: status,
|
||||
name:
|
||||
status === true
|
||||
? "Verified"
|
||||
: status === false
|
||||
? "Rejected"
|
||||
: "Pending",
|
||||
}));
|
||||
chips.push({ key: "statusIds", label: "Status", items });
|
||||
}
|
||||
|
||||
if (filters.startDate || filters.endDate) {
|
||||
const start = filters.startDate ? moment(filters.startDate).format("DD-MM-YYYY") : "";
|
||||
const end = filters.endDate ? moment(filters.endDate).format("DD-MM-YYYY") : "";
|
||||
chips.push({
|
||||
key: "dateRange",
|
||||
label: "Date Range",
|
||||
items: [{ id: "dateRange", name: `${start} - ${end}` }],
|
||||
});
|
||||
}
|
||||
|
||||
return chips;
|
||||
}, [filters, filterData]);
|
||||
|
||||
if (!filterChips.length) return null;
|
||||
|
||||
|
||||
return (
|
||||
<div className="row my-2">
|
||||
<div className="col-12">
|
||||
<div className="d-flex flex-wrap align-items-start gap-1">
|
||||
{filterChips.map((chip) => (
|
||||
<div
|
||||
key={chip.key}
|
||||
className="d-flex align-items-center flex-wrap px-2 py-1"
|
||||
style={{ fontSize: "0.9rem" }}
|
||||
>
|
||||
<span className="fw-semibold me-2">{chip.label}:</span>
|
||||
<div className="d-flex flex-wrap align-items-center gap-1">
|
||||
{chip.items.map((item) => (
|
||||
<span
|
||||
key={item.id}
|
||||
className="d-flex align-items-center bg-light rounded px-2 py-1 text-xs"
|
||||
>
|
||||
<span>{item.name}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="btn-close btn-close-white btn-sm ms-2"
|
||||
style={{
|
||||
filter: "invert(1) grayscale(1)",
|
||||
opacity: 0.7,
|
||||
fontSize: "0.6rem",
|
||||
}}
|
||||
onClick={() => removeFilterChip(chip.key, item.id)}
|
||||
/>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default DocumentFilterChips;
|
@ -1,4 +1,4 @@
|
||||
import React, { useState } from "react";
|
||||
import React, { useEffect, useState, useMemo, useImperativeHandle, forwardRef } from "react";
|
||||
import { useDocumentFilterEntities } from "../../hooks/useDocument";
|
||||
import { FormProvider, useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
@ -9,16 +9,34 @@ import {
|
||||
import { DateRangePicker1 } from "../common/DateRangePicker";
|
||||
import SelectMultiple from "../common/SelectMultiple";
|
||||
import moment from "moment";
|
||||
import { useParams } from "react-router-dom";
|
||||
|
||||
const DocumentFilterPanel = ({ entityTypeId, onApply }) => {
|
||||
const DocumentFilterPanel = forwardRef(
|
||||
({ entityTypeId, onApply, setFilterdata }, ref) => {
|
||||
const [resetKey, setResetKey] = useState(0);
|
||||
const { status } = useParams();
|
||||
|
||||
const { data, isError, isLoading, error } =
|
||||
useDocumentFilterEntities(entityTypeId);
|
||||
|
||||
//changes
|
||||
|
||||
const dynamicDocumentFilterDefaultValues = useMemo(() => {
|
||||
return {
|
||||
...DocumentFilterDefaultValues,
|
||||
uploadedByIds: DocumentFilterDefaultValues.uploadedByIds || [],
|
||||
documentCategoryIds: DocumentFilterDefaultValues.documentCategoryIds || [],
|
||||
documentTypeIds: DocumentFilterDefaultValues.documentTypeIds || [],
|
||||
documentTagIds: DocumentFilterDefaultValues.documentTagIds || [],
|
||||
startDate: DocumentFilterDefaultValues.startDate,
|
||||
endDate: DocumentFilterDefaultValues.endDate,
|
||||
};
|
||||
|
||||
}, [status]);
|
||||
|
||||
const methods = useForm({
|
||||
resolver: zodResolver(DocumentFilterSchema),
|
||||
defaultValues: DocumentFilterDefaultValues,
|
||||
defaultValues: dynamicDocumentFilterDefaultValues,
|
||||
});
|
||||
|
||||
const { handleSubmit, reset, setValue, watch } = methods;
|
||||
@ -32,6 +50,24 @@ const DocumentFilterPanel = ({ entityTypeId, onApply }) => {
|
||||
document.querySelector(".offcanvas.show .btn-close")?.click();
|
||||
};
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
resetFieldValue: (name, value) => {
|
||||
if (value !== undefined) {
|
||||
setValue(name, value);
|
||||
} else {
|
||||
reset({ ...methods.getValues(), [name]: DocumentFilterDefaultValues[name] });
|
||||
}
|
||||
},
|
||||
getValues: methods.getValues, // optional, to read current filter state
|
||||
}));
|
||||
|
||||
//changes
|
||||
useEffect(() => {
|
||||
if (data && setFilterdata) {
|
||||
setFilterdata(data);
|
||||
}
|
||||
}, [data, setFilterdata]);
|
||||
|
||||
const onSubmit = (values) => {
|
||||
onApply({
|
||||
...values,
|
||||
@ -63,6 +99,8 @@ const DocumentFilterPanel = ({ entityTypeId, onApply }) => {
|
||||
documentTag = [],
|
||||
} = data?.data || {};
|
||||
|
||||
|
||||
|
||||
return (
|
||||
<FormProvider {...methods}>
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
@ -73,18 +111,16 @@ const DocumentFilterPanel = ({ entityTypeId, onApply }) => {
|
||||
<div className="d-inline-flex border rounded-pill overflow-hidden shadow-none">
|
||||
<button
|
||||
type="button"
|
||||
className={`btn px-2 py-1 rounded-0 text-tiny ${
|
||||
isUploadedAt ? "active btn-secondary text-white" : ""
|
||||
}`}
|
||||
className={`btn px-2 py-1 rounded-0 text-tiny ${isUploadedAt ? "active btn-secondary text-white" : ""
|
||||
}`}
|
||||
onClick={() => setValue("isUploadedAt", true)}
|
||||
>
|
||||
Uploaded On
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`btn px-2 py-1 rounded-0 text-tiny ${
|
||||
!isUploadedAt ? "active btn-secondary text-white" : ""
|
||||
}`}
|
||||
className={`btn px-2 py-1 rounded-0 text-tiny ${!isUploadedAt ? "active btn-secondary text-white" : ""
|
||||
}`}
|
||||
onClick={() => setValue("isUploadedAt", false)}
|
||||
>
|
||||
Updated On
|
||||
@ -189,18 +225,18 @@ const DocumentFilterPanel = ({ entityTypeId, onApply }) => {
|
||||
<div className="d-flex justify-content-end py-3 gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-label-secondary btn-xs"
|
||||
className="btn btn-label-secondary btn-sm"
|
||||
onClick={onClear}
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
<button type="submit" className="btn btn-primary btn-xs">
|
||||
<button type="submit" className="btn btn-primary btn-sm">
|
||||
Apply
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</FormProvider>
|
||||
);
|
||||
};
|
||||
});
|
||||
|
||||
export default DocumentFilterPanel;
|
||||
|
@ -17,54 +17,56 @@ const SkeletonCell = ({
|
||||
/>
|
||||
);
|
||||
|
||||
export const DocumentTableSkeleton = ({ rows = 5 }) => {
|
||||
export const DocumentTableSkeleton = ({ rows = 10 }) => {
|
||||
return (
|
||||
<table className="card-body table border-top dataTable no-footer dtr-column text-nowrap">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="text-start">Name</th>
|
||||
<th className="text-start">Document Type</th>
|
||||
<th className="text-start">Uploaded By</th>
|
||||
<th className="text-center">Uploaded on</th>
|
||||
<th className="text-center">Status</th>
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
<table className="card-body table border-top dataTable no-footer dtr-column text-nowrap">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="text-start">Name</th>
|
||||
<th className="text-start">Document Type</th>
|
||||
<th className="text-start">Uploaded By</th>
|
||||
<th className="text-center">Uploaded on</th>
|
||||
<th className="text-center">Status</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{[...Array(rows)].map((_, idx) => (
|
||||
<tr key={idx} className={idx % 2 === 0 ? "odd" : "even"}>
|
||||
{/* Name */}
|
||||
<td className="text-start">
|
||||
<SkeletonCell width="120px" height={16} />
|
||||
</td>
|
||||
|
||||
<tbody>
|
||||
{[...Array(rows)].map((_, idx) => (
|
||||
<tr key={idx} className={idx % 2 === 0 ? "odd" : "even"}>
|
||||
{/* Name */}
|
||||
<td className="text-start">
|
||||
<SkeletonCell width="120px" height={16} />
|
||||
</td>
|
||||
{/* Document Type */}
|
||||
<td className="text-start">
|
||||
<SkeletonCell width="100px" height={16} />
|
||||
</td>
|
||||
|
||||
{/* Document Type */}
|
||||
<td className="text-start">
|
||||
<SkeletonCell width="100px" height={16} />
|
||||
</td>
|
||||
|
||||
{/* Uploaded By (Avatar + Name) */}
|
||||
<td className="text-start">
|
||||
<div className="d-flex align-items-center gap-2">
|
||||
<SkeletonCell width="30px" height={30} className="rounded-circle" />
|
||||
<SkeletonCell width="80px" height={16} />
|
||||
</div>
|
||||
</td>
|
||||
|
||||
{/* Uploaded on */}
|
||||
<td className="text-center">
|
||||
{/* Uploaded By (Avatar + Name) */}
|
||||
<td className="text-start">
|
||||
<div className="d-flex align-items-center gap-2">
|
||||
<SkeletonCell
|
||||
width="30px"
|
||||
height={30}
|
||||
className="rounded-circle"
|
||||
/>
|
||||
<SkeletonCell width="80px" height={16} />
|
||||
</td>
|
||||
</div>
|
||||
</td>
|
||||
|
||||
{/* Status */}
|
||||
<td className="text-center">
|
||||
<SkeletonCell width="70px" height={20} className="rounded" />
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
{/* Uploaded on */}
|
||||
<td className="text-center">
|
||||
<SkeletonCell width="80px" height={16} />
|
||||
</td>
|
||||
|
||||
{/* Status */}
|
||||
<td className="text-center">
|
||||
<SkeletonCell width="70px" height={20} className="rounded" />
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
);
|
||||
};
|
||||
|
@ -1,4 +1,4 @@
|
||||
import React, { createContext, useContext, useEffect, useState } from "react";
|
||||
import React, { createContext, useContext, useEffect, useRef, useState } from "react";
|
||||
import GlobalModel from "../common/GlobalModel";
|
||||
import NewDocument from "./ManageDocument";
|
||||
import { DOCUMENTS_ENTITIES, UPLOAD_DOCUMENT } from "../../utils/constants";
|
||||
@ -17,6 +17,7 @@ import ViewDocument from "./ViewDocument";
|
||||
import DocumentViewerModal from "./DocumentViewerModal";
|
||||
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
|
||||
import { useProfile } from "../../hooks/useProfile";
|
||||
import DocumentFilterChips from "./DocumentFilterChips";
|
||||
|
||||
// Context
|
||||
export const DocumentContext = createContext();
|
||||
@ -51,12 +52,14 @@ const Documents = ({ Document_Entity, Entity }) => {
|
||||
const [isSelf, setIsSelf] = useState(false);
|
||||
const [searchText, setSearchText] = useState("");
|
||||
const [isActive, setIsActive] = useState(true);
|
||||
const [filters, setFilter] = useState();
|
||||
const [filters, setFilter] = useState(DocumentFilterDefaultValues);
|
||||
const [isRefetching, setIsRefetching] = useState(false);
|
||||
const [refetchFn, setRefetchFn] = useState(null);
|
||||
const [DocumentEntity, setDocumentEntity] = useState(Document_Entity);
|
||||
const { employeeId } = useParams();
|
||||
const [OpenDocument, setOpenDocument] = useState(false);
|
||||
const [filterData, setFilterdata] = useState(DocumentFilterDefaultValues);
|
||||
const updatedRef = useRef();
|
||||
const [ManageDoc, setManageDoc] = useState({
|
||||
document: null,
|
||||
isOpen: false,
|
||||
@ -92,7 +95,7 @@ const Documents = ({ Document_Entity, Entity }) => {
|
||||
setShowTrigger(true);
|
||||
setOffcanvasContent(
|
||||
"Document Filters",
|
||||
<DocumentFilterPanel entityTypeId={DocumentEntity} onApply={setFilter} />
|
||||
<DocumentFilterPanel entityTypeId={DocumentEntity} onApply={setFilter} setFilterdata={setFilterdata} ref={updatedRef} />
|
||||
);
|
||||
|
||||
return () => {
|
||||
@ -115,13 +118,40 @@ const Documents = ({ Document_Entity, Entity }) => {
|
||||
setDocumentEntity(Document_Entity);
|
||||
}
|
||||
}, [Document_Entity]);
|
||||
|
||||
|
||||
const removeFilterChip = (key, id) => {
|
||||
const updatedFilters = { ...filters };
|
||||
if (Array.isArray(updatedFilters[key])) {
|
||||
updatedFilters[key] = updatedFilters[key].filter((v) => v !== id);
|
||||
updatedRef.current?.resetFieldValue(key,updatedFilters[key]);
|
||||
}
|
||||
else if (key === "dateRange") {
|
||||
updatedFilters.startDate = null;
|
||||
updatedFilters.endDate = null;
|
||||
updatedRef.current?.resetFieldValue("startDate",null);
|
||||
updatedRef.current?.resetFieldValue("endDate",null);
|
||||
}
|
||||
else {
|
||||
updatedFilters[key] = null;
|
||||
}
|
||||
|
||||
setFilter(updatedFilters);
|
||||
|
||||
return updatedFilters;
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
return (
|
||||
<DocumentContext.Provider value={contextValues}>
|
||||
<div className="mt-5">
|
||||
<div className="card page-min-h d-flex p-2">
|
||||
<div className="mt-2">
|
||||
<div className="card page-min-h d-flex p-5">
|
||||
<DocumentFilterChips filters={filters} filterData={filterData} removeFilterChip={removeFilterChip} />
|
||||
<div className="row align-items-center">
|
||||
{/* Search */}
|
||||
<div className="d-flex col-8 col-md-8 col-lg-4 mb-md-0 align-items-center">
|
||||
<div className="d-flex flex-row gap-2 col-12 col-md-8 col-lg-4 mb-md-0 align-items-center mb-2">
|
||||
<div className="d-flex">
|
||||
{" "}
|
||||
<input
|
||||
@ -149,7 +179,7 @@ const Documents = ({ Document_Entity, Entity }) => {
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="col-6 col-md-6 col-lg-8 text-end">
|
||||
<div className="col-12 col-md-6 col-lg-8 text-end">
|
||||
{(isSelf || canUploadDocument) && (
|
||||
<button
|
||||
className="btn btn-sm btn-primary me-3"
|
||||
@ -231,4 +261,4 @@ const Documents = ({ Document_Entity, Entity }) => {
|
||||
);
|
||||
};
|
||||
|
||||
export default Documents;
|
||||
export default Documents;
|
@ -65,7 +65,7 @@ const DocumentsList = ({
|
||||
setIsRefetching(isFetching);
|
||||
}, [isFetching, setIsRefetching]);
|
||||
|
||||
const { setManageDoc, setViewDoc } = useDocumentContext();
|
||||
const { setManageDoc, setViewDoc,removeFilterChip } = useDocumentContext();
|
||||
const { mutate: ActiveInActive, isPending } = useActiveInActiveDocument();
|
||||
|
||||
const paginate = (page) => {
|
||||
@ -82,9 +82,9 @@ const DocumentsList = ({
|
||||
if (isLoading || isFetching) return <DocumentTableSkeleton />;
|
||||
if (isError)
|
||||
return <div>Error: {error?.message || "Something went wrong"}</div>;
|
||||
if (isInitialEmpty) return <div>No documents found yet.</div>;
|
||||
if (isSearchEmpty) return <div>No results found for "{debouncedSearch}"</div>;
|
||||
if (isFilterEmpty) return <div>No documents match your filter.</div>;
|
||||
if (isInitialEmpty) return <div className="py-12 my-12">No documents found yet.</div>;
|
||||
if (isSearchEmpty) return <div className="py-12 my-12">No results found for "{debouncedSearch}"</div>;
|
||||
if (isFilterEmpty) return <div className="py-12 my-12">No documents match your filter.</div>;
|
||||
|
||||
const handleDelete = () => {
|
||||
ActiveInActive(
|
||||
@ -180,10 +180,10 @@ const DocumentsList = ({
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="table-responsive">
|
||||
<div className="table-responsive p-2">
|
||||
<table className="table border-top dataTable text-nowrap">
|
||||
<thead>
|
||||
<tr className="shadow-sm">
|
||||
<thead className="">
|
||||
<tr className="py-2 ">
|
||||
{DocumentColumns.map((col) => (
|
||||
<th key={col.key} className={`sorting ${col.align}`}>
|
||||
{col.label}
|
||||
|
@ -99,7 +99,7 @@ const EmpAttendance = ({ employee }) => {
|
||||
if (
|
||||
!existing ||
|
||||
new Date(rec.checkInTime || rec.checkOutTime) >
|
||||
new Date(existing.checkInTime || existing.checkOutTime)
|
||||
new Date(existing.checkInTime || existing.checkOutTime)
|
||||
) {
|
||||
uniqueMap.set(key, rec);
|
||||
}
|
||||
@ -123,7 +123,7 @@ const EmpAttendance = ({ employee }) => {
|
||||
};
|
||||
const closeModal = () => setIsModalOpen(false);
|
||||
|
||||
const onSubmit = (formData) => {};
|
||||
const onSubmit = (formData) => { };
|
||||
return (
|
||||
<>
|
||||
{isModalOpen && (
|
||||
@ -131,7 +131,7 @@ const EmpAttendance = ({ employee }) => {
|
||||
<AttendLogs Id={attendanceId} />
|
||||
</GlobalModel>
|
||||
)}
|
||||
<div className="card px-4 mt-5 py-2 " style={{ minHeight: "500px" }}>
|
||||
<div className="card px-4 mt-2 py-2 page-min-h ">
|
||||
<div
|
||||
className="dataTables_length text-start py-2 d-flex justify-content-between "
|
||||
id="DataTables_Table_0_length"
|
||||
@ -152,20 +152,14 @@ const EmpAttendance = ({ employee }) => {
|
||||
</form>
|
||||
</FormProvider>
|
||||
</>
|
||||
</div>
|
||||
<div className="col-md-2 m-0 text-end">
|
||||
<i
|
||||
className={`bx bx-refresh cursor-pointer fs-4 ${
|
||||
isFetching ? "spin" : ""
|
||||
}`}
|
||||
data-toggle="tooltip"
|
||||
title="Refresh"
|
||||
onClick={() => refetch()}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="table-responsive text-nowrap">
|
||||
{!loading && data.length === 0 && <span>No employee logs</span>}
|
||||
{!loading && data.length === 0 && (
|
||||
<span style={{ fontSize: "0.9rem" }}>
|
||||
No attendance record found in selected date range
|
||||
</span>
|
||||
)}
|
||||
{isError && <div className="text-center">{error.message}</div>}
|
||||
{loading && !data && <div className="text-center">Loading...</div>}
|
||||
{data && data.length > 0 && (
|
||||
@ -250,9 +244,8 @@ const EmpAttendance = ({ employee }) => {
|
||||
{[...Array(totalPages)].map((_, index) => (
|
||||
<li
|
||||
key={index}
|
||||
className={`page-item ${
|
||||
currentPage === index + 1 ? "active" : ""
|
||||
}`}
|
||||
className={`page-item ${currentPage === index + 1 ? "active" : ""
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
className="page-link "
|
||||
@ -263,9 +256,8 @@ const EmpAttendance = ({ employee }) => {
|
||||
</li>
|
||||
))}
|
||||
<li
|
||||
className={`page-item ${
|
||||
currentPage === totalPages ? "disabled" : ""
|
||||
}`}
|
||||
className={`page-item ${currentPage === totalPages ? "disabled" : ""
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
className="page-link "
|
||||
|
@ -12,11 +12,11 @@ const EmpDashboard = ({ profile }) => {
|
||||
return (
|
||||
<>
|
||||
<div className="row">
|
||||
<div className="col-12 col-sm-6 pt-5">
|
||||
<div className="col-12 col-sm-6 pt-2">
|
||||
{" "}
|
||||
<EmpOverview profile={profile}></EmpOverview>
|
||||
</div>
|
||||
<div className="col col-sm-6 pt-5">
|
||||
{/* <div className="col col-sm-6 pt-5">
|
||||
<div className="card ">
|
||||
<div className="card-body">
|
||||
<small className="card-text text-uppercase text-body-secondary small text-start d-block">
|
||||
@ -29,7 +29,6 @@ const EmpDashboard = ({ profile }) => {
|
||||
className="d-flex mb-4 align-items-start flex-wrap"
|
||||
key={project.id}
|
||||
>
|
||||
{/* Project Info */}
|
||||
<div className="flex-grow-1">
|
||||
<div className="d-flex flex-wrap align-items-center justify-content-between gap-2">
|
||||
<div className="d-flex">
|
||||
@ -70,7 +69,6 @@ const EmpDashboard = ({ profile }) => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Dates */}
|
||||
|
||||
</div>
|
||||
</li>
|
||||
@ -79,7 +77,7 @@ const EmpDashboard = ({ profile }) => {
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div> */}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
@ -24,7 +24,7 @@ const EmployeeNav = ({ onPillClick, activePill }) => {
|
||||
icon: "bx bx-file",
|
||||
label: "Documents",
|
||||
},
|
||||
{ key: "activities", icon: "bx bx-grid-alt", label: "Activities" },
|
||||
// { key: "activities", icon: "bx bx-grid-alt", label: "Activities" },
|
||||
].filter(Boolean);
|
||||
return (
|
||||
<div className="col-md-12">
|
||||
|
@ -90,7 +90,7 @@ export const employeeSchema =
|
||||
.min(1, { message: "Phone Number is required" })
|
||||
.regex(mobileNumberRegex, { message: "Invalid phone number " }),
|
||||
jobRoleId: z.string().min(1, { message: "Role is required" }),
|
||||
organizationId:z.string().min(1,{message:"Organization is required"}),
|
||||
// organizationId:z.string().min(1,{message:"Organization is required"}), // hide temp. for version 1
|
||||
hasApplicationAccess:z.boolean().default(false),
|
||||
}).refine((data) => {
|
||||
if (data.hasApplicationAccess) {
|
||||
@ -119,6 +119,6 @@ export const defatEmployeeObj = {
|
||||
permanentAddress: "",
|
||||
phoneNumber: "",
|
||||
jobRoleId: null,
|
||||
organizationId:"",
|
||||
// organizationId:"",
|
||||
hasApplicationAccess:false
|
||||
}
|
@ -15,18 +15,18 @@ import {
|
||||
import Label from "../common/Label";
|
||||
import DatePicker from "../common/DatePicker";
|
||||
import { defatEmployeeObj, employeeSchema } from "./EmployeeSchema";
|
||||
import { useOrganizationsList } from "../../hooks/useOrganization";
|
||||
// import { useOrganizationsList } from "../../hooks/useOrganization";
|
||||
import { ITEMS_PER_PAGE } from "../../utils/constants";
|
||||
|
||||
const ManageEmployee = ({ employeeId, onClosed, IsAllEmployee }) => {
|
||||
const dispatch = useDispatch();
|
||||
const { mutate: updateEmployee, isPending } = useUpdateEmployee();
|
||||
const {
|
||||
data: organzationList,
|
||||
isLoading,
|
||||
isError,
|
||||
error: EempError,
|
||||
} = useOrganizationsList(ITEMS_PER_PAGE, 1, true);
|
||||
// const {
|
||||
// data: organzationList,
|
||||
// isLoading,
|
||||
// isError,
|
||||
// error: EempError,
|
||||
// } = useOrganizationsList(ITEMS_PER_PAGE, 1, true);
|
||||
const {
|
||||
employee,
|
||||
error,
|
||||
@ -113,7 +113,7 @@ const ManageEmployee = ({ employeeId, onClosed, IsAllEmployee }) => {
|
||||
permanentAddress: currentEmployee.permanentAddress || "",
|
||||
phoneNumber: currentEmployee.phoneNumber || "",
|
||||
jobRoleId: currentEmployee.jobRoleId?.toString() || "",
|
||||
organizationId: currentEmployee.organizationId || "",
|
||||
// organizationId: currentEmployee.organizationId || "", // Hide temp. for version 1
|
||||
hasApplicationAccess: currentEmployee.hasApplicationAccess || false,
|
||||
}
|
||||
: {}
|
||||
@ -413,9 +413,10 @@ const ManageEmployee = ({ employeeId, onClosed, IsAllEmployee }) => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* -------------- */}
|
||||
|
||||
<div className="row mb-3">
|
||||
<div className="col-sm-6">
|
||||
{/* -------------- Temp hide for Version---------------*/}
|
||||
{/* <div className="col-sm-6">
|
||||
<Label className="form-text text-start" required>
|
||||
Organization
|
||||
</Label>
|
||||
@ -446,9 +447,10 @@ const ManageEmployee = ({ employeeId, onClosed, IsAllEmployee }) => {
|
||||
{errors.organizationId.message}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div> */}
|
||||
{/* --------------------------------------------------- */}
|
||||
|
||||
<div className="col-sm-6 d-flex align-items-center mt-2">
|
||||
<div className="col-12 d-flex align-items-center mt-2">
|
||||
<label className="form-check-label d-flex align-items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
@ -584,15 +586,14 @@ const ManageEmployee = ({ employeeId, onClosed, IsAllEmployee }) => {
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="row text-end">
|
||||
<div className="col-sm-12">
|
||||
<div className="d-flex flex-row gap-3 justify-content-end">
|
||||
<button
|
||||
aria-label="manage employee"
|
||||
type="reset"
|
||||
className="btn btn-sm btn-label-secondary me-2"
|
||||
disabled={isPending}
|
||||
onClick={()=>onClosed()}
|
||||
>
|
||||
Clear
|
||||
Close
|
||||
</button>
|
||||
<button
|
||||
aria-label="manage employee"
|
||||
@ -600,9 +601,8 @@ const ManageEmployee = ({ employeeId, onClosed, IsAllEmployee }) => {
|
||||
className="btn btn-sm btn-primary"
|
||||
disabled={isPending}
|
||||
>
|
||||
{isPending ? "Please Wait..." : employeeId ? "Update" : "Create"}
|
||||
{isPending ? "Please Wait..." : employeeId ? "Update" : "Submit"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</>
|
||||
|
50
src/components/Expenses/ActiveFilters.jsx
Normal file
50
src/components/Expenses/ActiveFilters.jsx
Normal file
@ -0,0 +1,50 @@
|
||||
const ActiveFilters = ({ filters, optionsLookup = {}, onRemove }) => {
|
||||
const entries = Object.entries(filters || {});
|
||||
|
||||
return (
|
||||
<div className="d-flex flex-wrap gap-2">
|
||||
{entries.map(([key, value]) => {
|
||||
if (!value || (Array.isArray(value) && value.length === 0)) return null;
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((v) => {
|
||||
const label = optionsLookup[key]?.[v] || v;
|
||||
return (
|
||||
<span
|
||||
key={`${key}-${v}`}
|
||||
className="badge bg-label-primary cursor-pointer"
|
||||
onClick={() => onRemove(key, v)}
|
||||
>
|
||||
{label} <i className="bx bx-x ms-1"></i>
|
||||
</span>
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
if (typeof value === "boolean") {
|
||||
return (
|
||||
<span
|
||||
key={key}
|
||||
className="badge bg-label-success cursor-pointer"
|
||||
onClick={() => onRemove(key)}
|
||||
>
|
||||
{key}: {value ? "Yes" : "No"} <i className="bx bx-x ms-1"></i>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<span className="badge bg-primary">
|
||||
{data?.startDate && data?.endDate
|
||||
? `${formatUTCToLocalTime(
|
||||
data.startDate
|
||||
)} - ${formatUTCToLocalTime(data.endDate)}`
|
||||
: "No dates"}
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ActiveFilters;
|
89
src/components/Expenses/ExpenseFilterChips.jsx
Normal file
89
src/components/Expenses/ExpenseFilterChips.jsx
Normal file
@ -0,0 +1,89 @@
|
||||
import React, { useMemo } from "react";
|
||||
|
||||
const ExpenseFilterChips = ({ filters, filterData, removeFilterChip }) => {
|
||||
// Build chips from filters
|
||||
const filterChips = useMemo(() => {
|
||||
const chips = [];
|
||||
|
||||
const buildGroup = (ids, list, label, key) => {
|
||||
if (!ids?.length) return;
|
||||
const items = ids.map((id) => ({
|
||||
id,
|
||||
name: list.find((item) => item.id === id)?.name || id,
|
||||
}));
|
||||
chips.push({ key, label, items });
|
||||
};
|
||||
|
||||
buildGroup(filters.projectIds, filterData.projects, "Project", "projectIds");
|
||||
buildGroup(filters.createdByIds, filterData.createdBy, "Submitted By", "createdByIds");
|
||||
buildGroup(filters.paidById, filterData.paidBy, "Paid By", "paidById");
|
||||
buildGroup(filters.statusIds, filterData.status, "Status", "statusIds");
|
||||
buildGroup(filters.ExpenseTypeIds, filterData.expensesType, "Category", "ExpenseTypeIds");
|
||||
|
||||
if (filters.startDate || filters.endDate) {
|
||||
const start = filters.startDate
|
||||
? new Date(filters.startDate).toLocaleDateString()
|
||||
: "";
|
||||
const end = filters.endDate
|
||||
? new Date(filters.endDate).toLocaleDateString()
|
||||
: "";
|
||||
chips.push({
|
||||
key: "dateRange",
|
||||
label: "Date Range",
|
||||
items: [{ id: "dateRange", name: `${start} - ${end}` }],
|
||||
});
|
||||
}
|
||||
|
||||
return chips;
|
||||
}, [filters, filterData]);
|
||||
|
||||
if (!filterChips.length) return null;
|
||||
|
||||
return (
|
||||
<div className="row">
|
||||
<div className="col-12">
|
||||
<div className="d-flex flex-wrap align-items-start gap-1 text-start">
|
||||
{filterChips.map((chip) => (
|
||||
<div
|
||||
key={chip.key}
|
||||
className="d-flex align-items-center flex-wrap px-2 py-1 "
|
||||
style={{ fontSize: "0.9rem", maxWidth: "100%" }}
|
||||
>
|
||||
{/* Chip Label */}
|
||||
<span className="fw-semibold me-2">{chip.label}:</span>
|
||||
|
||||
{/* Chip Items */}
|
||||
<div className="d-flex flex-wrap align-items-center gap-1">
|
||||
{chip.items.map((item) => (
|
||||
<span
|
||||
key={item.id}
|
||||
className="d-flex align-items-center bg-light rounded px-2 py-1 text-xs"
|
||||
>
|
||||
<span>{item.name}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="btn-close btn-close-white btn-sm ms-2"
|
||||
style={{
|
||||
filter: "invert(1) grayscale(1)",
|
||||
opacity: 0.7,
|
||||
fontSize: "0.6rem",
|
||||
}}
|
||||
onClick={() => removeFilterChip(chip.key, item.id)}
|
||||
/>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
);
|
||||
};
|
||||
|
||||
export default ExpenseFilterChips;
|
||||
|
||||
|
@ -1,4 +1,4 @@
|
||||
import React, { useEffect, useState, useMemo } from "react";
|
||||
import React, {forwardRef, useEffect,useImperativeHandle, useState, useMemo } from "react";
|
||||
import { FormProvider, useForm, Controller } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { defaultFilter, SearchSchema } from "./ExpenseSchema";
|
||||
@ -13,9 +13,11 @@ import { useSelector } from "react-redux";
|
||||
import moment from "moment";
|
||||
import { useExpenseFilter } from "../../hooks/useExpense";
|
||||
import { ExpenseFilterSkeleton } from "./ExpenseSkeleton";
|
||||
import { useLocation } from "react-router-dom";
|
||||
import { useLocation, useNavigate, useParams } from "react-router-dom";
|
||||
|
||||
const ExpenseFilterPanel = ({ onApply, handleGroupBy }) => {
|
||||
const ExpenseFilterPanel = forwardRef(({ onApply, handleGroupBy, setFilterdata }, ref) => {
|
||||
const { status } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const selectedProjectId = useSelector(
|
||||
(store) => store.localVariables.projectId
|
||||
);
|
||||
@ -29,17 +31,31 @@ const ExpenseFilterPanel = ({ onApply, handleGroupBy }) => {
|
||||
{ id: "submittedBy", name: "Submitted By" },
|
||||
{ id: "project", name: "Project" },
|
||||
{ id: "paymentMode", name: "Payment Mode" },
|
||||
{ id: "expensesType", name: "Expense Type" },
|
||||
{ id: "expensesType", name: "Expense Category" },
|
||||
{ id: "createdAt", name: "Submitted Date" },
|
||||
].sort((a, b) => a.name.localeCompare(b.name));
|
||||
}, []);
|
||||
|
||||
const [selectedGroup, setSelectedGroup] = useState(groupByList[0]);
|
||||
const [selectedGroup, setSelectedGroup] = useState(groupByList[6]);
|
||||
const [resetKey, setResetKey] = useState(0);
|
||||
|
||||
const dynamicDefaultFilter = useMemo(() => {
|
||||
return {
|
||||
...defaultFilter,
|
||||
statusIds: status ? [status] : defaultFilter.statusIds || [],
|
||||
projectIds: defaultFilter.projectIds || [],
|
||||
createdByIds: defaultFilter.createdByIds || [],
|
||||
paidById: defaultFilter.paidById || [],
|
||||
ExpenseTypeIds: defaultFilter.ExpenseTypeIds || [],
|
||||
isTransactionDate: defaultFilter.isTransactionDate ?? true,
|
||||
startDate: defaultFilter.startDate,
|
||||
endDate: defaultFilter.endDate,
|
||||
};
|
||||
}, [status]);
|
||||
|
||||
const methods = useForm({
|
||||
resolver: zodResolver(SearchSchema),
|
||||
defaultValues: defaultFilter,
|
||||
defaultValues: dynamicDefaultFilter,
|
||||
});
|
||||
|
||||
const { control, handleSubmit, reset, setValue, watch } = methods;
|
||||
@ -49,11 +65,30 @@ const ExpenseFilterPanel = ({ onApply, handleGroupBy }) => {
|
||||
document.querySelector(".offcanvas.show .btn-close")?.click();
|
||||
};
|
||||
|
||||
// Change here
|
||||
useEffect(() => {
|
||||
if (data && setFilterdata) {
|
||||
setFilterdata(data);
|
||||
}
|
||||
}, [data, setFilterdata]);
|
||||
|
||||
const handleGroupChange = (e) => {
|
||||
const group = groupByList.find((g) => g.id === e.target.value);
|
||||
if (group) setSelectedGroup(group);
|
||||
};
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
resetFieldValue: (name, value) => {
|
||||
// Reset specific field
|
||||
if (value !== undefined) {
|
||||
setValue(name, value);
|
||||
} else {
|
||||
reset({ ...methods.getValues(), [name]: defaultFilter[name] });
|
||||
}
|
||||
},
|
||||
getValues: methods.getValues, // optional, to read current filter state
|
||||
}));
|
||||
|
||||
const onSubmit = (formData) => {
|
||||
onApply({
|
||||
...formData,
|
||||
@ -71,17 +106,55 @@ const ExpenseFilterPanel = ({ onApply, handleGroupBy }) => {
|
||||
onApply(defaultFilter);
|
||||
handleGroupBy(groupByList[0].id);
|
||||
closePanel();
|
||||
if (status) {
|
||||
navigate("/expenses", { replace: true });
|
||||
}
|
||||
};
|
||||
|
||||
// Close popup when navigating to another component
|
||||
const location = useLocation();
|
||||
useEffect(() => {
|
||||
closePanel();
|
||||
}, [location]);
|
||||
|
||||
const [appliedStatusId, setAppliedStatusId] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!status) return;
|
||||
|
||||
if (status !== appliedStatusId && data) {
|
||||
const filterWithStatus = {
|
||||
...dynamicDefaultFilter,
|
||||
startDate: dynamicDefaultFilter.startDate
|
||||
? moment
|
||||
.utc(dynamicDefaultFilter.startDate, "DD-MM-YYYY")
|
||||
.toISOString()
|
||||
: undefined,
|
||||
endDate: dynamicDefaultFilter.endDate
|
||||
? moment.utc(dynamicDefaultFilter.endDate, "DD-MM-YYYY").toISOString()
|
||||
: undefined,
|
||||
};
|
||||
|
||||
onApply(filterWithStatus);
|
||||
handleGroupBy(selectedGroup.id);
|
||||
|
||||
setAppliedStatusId(status);
|
||||
}
|
||||
}, [
|
||||
status,
|
||||
data,
|
||||
dynamicDefaultFilter,
|
||||
onApply,
|
||||
handleGroupBy,
|
||||
selectedGroup.id,
|
||||
appliedStatusId,
|
||||
]);
|
||||
|
||||
if (isLoading || isFetching) return <ExpenseFilterSkeleton />;
|
||||
if (isError && isFetched)
|
||||
return <div>Something went wrong Here- {error.message} </div>;
|
||||
|
||||
|
||||
|
||||
return (
|
||||
<>
|
||||
<FormProvider {...methods}>
|
||||
@ -92,18 +165,16 @@ const ExpenseFilterPanel = ({ onApply, handleGroupBy }) => {
|
||||
<div className="d-inline-flex border rounded-pill mb-1 overflow-hidden shadow-none">
|
||||
<button
|
||||
type="button"
|
||||
className={`btn px-2 py-1 rounded-0 text-tiny ${
|
||||
isTransactionDate ? "active btn-primary text-white" : ""
|
||||
}`}
|
||||
className={`btn px-2 py-1 rounded-0 text-tiny ${isTransactionDate ? "active btn-primary text-white" : ""
|
||||
}`}
|
||||
onClick={() => setValue("isTransactionDate", true)}
|
||||
>
|
||||
Transaction Date
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={`btn px-2 py-1 rounded-0 text-tiny ${
|
||||
!isTransactionDate ? "active btn-primary text-white" : ""
|
||||
}`}
|
||||
className={`btn px-2 py-1 rounded-0 text-tiny ${!isTransactionDate ? "active btn-primary text-white" : ""
|
||||
}`}
|
||||
onClick={() => setValue("isTransactionDate", false)}
|
||||
>
|
||||
Submitted Date
|
||||
@ -117,6 +188,7 @@ const ExpenseFilterPanel = ({ onApply, handleGroupBy }) => {
|
||||
endField="endDate"
|
||||
resetSignal={resetKey}
|
||||
defaultRange={false}
|
||||
maxDate={new Date()}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@ -142,6 +214,13 @@ const ExpenseFilterPanel = ({ onApply, handleGroupBy }) => {
|
||||
labelKey={(item) => item.name}
|
||||
valueKey="id"
|
||||
/>
|
||||
<SelectMultiple
|
||||
name="ExpenseTypeIds"
|
||||
label="Category :"
|
||||
options={data.expensesType}
|
||||
labelKey={(item) => item.name}
|
||||
valueKey="id"
|
||||
/>
|
||||
|
||||
<div className="mb-3">
|
||||
<label className="form-label">Status :</label>
|
||||
@ -213,6 +292,6 @@ const ExpenseFilterPanel = ({ onApply, handleGroupBy }) => {
|
||||
</FormProvider>
|
||||
</>
|
||||
);
|
||||
};
|
||||
});
|
||||
|
||||
export default ExpenseFilterPanel;
|
||||
export default ExpenseFilterPanel;
|
@ -10,20 +10,29 @@ import {
|
||||
EXPENSE_REJECTEDBY,
|
||||
ITEMS_PER_PAGE,
|
||||
} from "../../utils/constants";
|
||||
import { getColorNameFromHex, useDebounce } from "../../utils/appUtils";
|
||||
import {
|
||||
formatCurrency,
|
||||
getColorNameFromHex,
|
||||
useDebounce,
|
||||
} from "../../utils/appUtils";
|
||||
import { ExpenseTableSkeleton } from "./ExpenseSkeleton";
|
||||
import ConfirmModal from "../common/ConfirmModal";
|
||||
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
|
||||
import { useSelector } from "react-redux";
|
||||
import ExpenseFilterChips from "./ExpenseFilterChips";
|
||||
import { defaultFilter } from "./ExpenseSchema";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
|
||||
const [deletingId, setDeletingId] = useState(null);
|
||||
const [IsDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
|
||||
const { setViewExpense, setManageExpenseModal } = useExpenseContext();
|
||||
const { setViewExpense, setManageExpenseModal, filterData, removeFilterChip } = useExpenseContext();
|
||||
const IsExpenseEditable = useHasUserPermission();
|
||||
const IsExpesneApprpve = useHasUserPermission(APPROVE_EXPENSE);
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const debouncedSearch = useDebounce(searchText, 500);
|
||||
const navigate = useNavigate();
|
||||
|
||||
|
||||
const { mutate: DeleteExpense, isPending } = useDeleteExpense();
|
||||
const { data, isLoading, isError, isInitialLoading, error } = useExpenseList(
|
||||
@ -59,40 +68,60 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
|
||||
const groupByField = (items, field) => {
|
||||
return items.reduce((acc, item) => {
|
||||
let key;
|
||||
let displayField;
|
||||
|
||||
switch (field) {
|
||||
case "transactionDate":
|
||||
key = item.transactionDate?.split("T")[0];
|
||||
key = item?.transactionDate?.split("T")[0];
|
||||
displayField = "Transaction Date";
|
||||
break;
|
||||
case "status":
|
||||
key = item.status?.displayName || "Unknown";
|
||||
key = item?.status?.displayName || "Unknown";
|
||||
displayField = "Status";
|
||||
break;
|
||||
case "submittedBy":
|
||||
key = `${item.createdBy?.firstName ?? ""} ${
|
||||
item.createdBy?.lastName ?? ""
|
||||
}`.trim();
|
||||
key = `${item?.createdBy?.firstName ?? ""} ${item.createdBy?.lastName ?? ""
|
||||
}`.trim();
|
||||
displayField = "Submitted By";
|
||||
break;
|
||||
case "project":
|
||||
key = item.project?.name || "Unknown Project";
|
||||
key = item?.project?.name || "Unknown Project";
|
||||
displayField = "Project";
|
||||
break;
|
||||
case "paymentMode":
|
||||
key = item.paymentMode?.name || "Unknown Mode";
|
||||
key = item?.paymentMode?.name || "Unknown Mode";
|
||||
displayField = "Payment Mode";
|
||||
break;
|
||||
case "expensesType":
|
||||
key = item.expensesType?.name || "Unknown Type";
|
||||
key = item?.expensesType?.name || "Unknown Type";
|
||||
displayField = "Expense Category";
|
||||
break;
|
||||
case "createdAt":
|
||||
key = item.createdAt?.split("T")[0] || "Unknown Type";
|
||||
key = item?.createdAt?.split("T")[0] || "Unknown Date";
|
||||
displayField = "Created Date";
|
||||
break;
|
||||
default:
|
||||
key = "Others";
|
||||
displayField = "Others";
|
||||
}
|
||||
if (!acc[key]) acc[key] = [];
|
||||
acc[key].push(item);
|
||||
|
||||
const groupKey = `${field}_${key}`; // unique key for object property
|
||||
if (!acc[groupKey]) {
|
||||
acc[groupKey] = { key, displayField, items: [] };
|
||||
}
|
||||
|
||||
acc[groupKey].items.push(item);
|
||||
return acc;
|
||||
}, {});
|
||||
};
|
||||
|
||||
const expenseColumns = [
|
||||
{
|
||||
key: "expenseUId",
|
||||
label: "Expense Id",
|
||||
getValue: (e) => e.expenseUId || "N/A",
|
||||
align: "text-start mx-2",
|
||||
},
|
||||
{
|
||||
key: "expensesType",
|
||||
label: "Expense Type",
|
||||
@ -110,11 +139,11 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
|
||||
label: "Submitted By",
|
||||
align: "text-start",
|
||||
getValue: (e) =>
|
||||
`${e.createdBy?.firstName ?? ""} ${
|
||||
e.createdBy?.lastName ?? ""
|
||||
}`.trim() || "N/A",
|
||||
`${e.createdBy?.firstName ?? ""} ${e.createdBy?.lastName ?? ""
|
||||
}`.trim() || "N/A",
|
||||
customRender: (e) => (
|
||||
<div className="d-flex align-items-center">
|
||||
<div className="d-flex align-items-center cursor-pointer"
|
||||
onClick={() => navigate(`/employee/${e.createdBy?.id}`)}>
|
||||
<Avatar
|
||||
size="xs"
|
||||
classAvatar="m-0"
|
||||
@ -122,9 +151,8 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
|
||||
lastName={e.createdBy?.lastName}
|
||||
/>
|
||||
<span className="text-truncate">
|
||||
{`${e.createdBy?.firstName ?? ""} ${
|
||||
e.createdBy?.lastName ?? ""
|
||||
}`.trim() || "N/A"}
|
||||
{`${e.createdBy?.firstName ?? ""} ${e.createdBy?.lastName ?? ""
|
||||
}`.trim() || "N/A"}
|
||||
</span>
|
||||
</div>
|
||||
),
|
||||
@ -138,11 +166,7 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
|
||||
{
|
||||
key: "amount",
|
||||
label: "Amount",
|
||||
getValue: (e) => (
|
||||
<>
|
||||
<i className="bx bx-rupee b-xs"></i> {e?.amount}
|
||||
</>
|
||||
),
|
||||
getValue: (e) => <>{formatCurrency(e?.amount)}</>,
|
||||
isAlwaysVisible: true,
|
||||
align: "text-end",
|
||||
},
|
||||
@ -152,9 +176,8 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
|
||||
align: "text-center",
|
||||
getValue: (e) => (
|
||||
<span
|
||||
className={`badge bg-label-${
|
||||
getColorNameFromHex(e?.status?.color) || "secondary"
|
||||
}`}
|
||||
className={`badge bg-label-${getColorNameFromHex(e?.status?.color) || "secondary"
|
||||
}`}
|
||||
>
|
||||
{e.status?.name || "Unknown"}
|
||||
</span>
|
||||
@ -162,27 +185,32 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
|
||||
},
|
||||
];
|
||||
|
||||
if (isInitialLoading) return <ExpenseTableSkeleton />;
|
||||
if (isError) return <div>{error.message}</div>;
|
||||
if (isInitialLoading && !data) return <ExpenseTableSkeleton />;
|
||||
if (isError) return <div>{error?.message}</div>;
|
||||
|
||||
const grouped = groupBy
|
||||
? groupByField(data?.data ?? [], groupBy)
|
||||
: { All: data?.data ?? [] };
|
||||
const IsGroupedByDate = ["transactionDate", "createdAt"].includes(groupBy);
|
||||
const IsGroupedByDate = [
|
||||
{ key: "transactionDate", displayField: "Transaction Date" },
|
||||
{ key: "createdAt", displayField: "created Date" },
|
||||
]?.includes(groupBy);
|
||||
|
||||
const canEditExpense = (expense) => {
|
||||
return (
|
||||
(expense.status.id === EXPENSE_DRAFT ||
|
||||
EXPENSE_REJECTEDBY.includes(expense.status.id)) &&
|
||||
expense.createdBy?.id === SelfId
|
||||
(expense?.status?.id === EXPENSE_DRAFT ||
|
||||
EXPENSE_REJECTEDBY.includes(expense?.status?.id)) &&
|
||||
expense?.createdBy?.id === SelfId
|
||||
);
|
||||
};
|
||||
|
||||
const canDetetExpense = (expense) => {
|
||||
return (
|
||||
expense.status.id === EXPENSE_DRAFT && expense.createdBy.id === SelfId
|
||||
expense?.status?.id === EXPENSE_DRAFT && expense?.createdBy?.id === SelfId
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
return (
|
||||
<>
|
||||
{IsDeleteModalOpen && (
|
||||
@ -198,11 +226,21 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="card px-0 px-sm-4">
|
||||
<div className="card page-min-h px-sm-4">
|
||||
{/* Filter Chips */}
|
||||
<ExpenseFilterChips
|
||||
filters={filters}
|
||||
filterData={filterData}
|
||||
removeFilterChip={removeFilterChip}
|
||||
groupBy={groupBy}
|
||||
/>
|
||||
<div
|
||||
className="card-datatable table-responsive "
|
||||
id="horizontal-example"
|
||||
>
|
||||
|
||||
|
||||
|
||||
<div className="dataTables_wrapper no-footer px-2 ">
|
||||
<table className="table border-top dataTable text-nowrap">
|
||||
<thead>
|
||||
@ -226,18 +264,24 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
|
||||
</thead>
|
||||
<tbody>
|
||||
{Object.keys(grouped).length > 0 ? (
|
||||
Object.entries(grouped).map(([group, expenses]) => (
|
||||
<React.Fragment key={group}>
|
||||
Object.values(grouped).map(({ key, displayField, items }) => (
|
||||
<React.Fragment key={key}>
|
||||
<tr className="tr-group text-dark">
|
||||
<td colSpan={8} className="text-start">
|
||||
<strong>
|
||||
{IsGroupedByDate
|
||||
? formatUTCToLocalTime(group)
|
||||
: group}
|
||||
</strong>
|
||||
<div className="d-flex align-items-center">
|
||||
{" "}
|
||||
<small className="fs-6 py-1">
|
||||
{displayField} :{" "}
|
||||
</small>{" "}
|
||||
<small className="fs-6 ms-3">
|
||||
{IsGroupedByDate
|
||||
? formatUTCToLocalTime(key)
|
||||
: key}
|
||||
</small>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
{expenses.map((expense) => (
|
||||
{items?.map((expense) => (
|
||||
<tr key={expense.id}>
|
||||
{expenseColumns.map(
|
||||
(col) =>
|
||||
@ -263,27 +307,61 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
|
||||
})
|
||||
}
|
||||
></i>
|
||||
{canEditExpense(expense) && (
|
||||
<i
|
||||
className="bx bx-edit text-secondary cursor-pointer"
|
||||
onClick={() =>
|
||||
setManageExpenseModal({
|
||||
IsOpen: true,
|
||||
expenseId: expense.id,
|
||||
})
|
||||
}
|
||||
></i>
|
||||
)}
|
||||
{canDetetExpense(expense) &&
|
||||
canEditExpense(expense) && (
|
||||
<div className="dropdown z-2">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-xs btn-icon btn-text-secondary rounded-pill dropdown-toggle hide-arrow p-0 m-0"
|
||||
data-bs-toggle="dropdown"
|
||||
aria-expanded="false"
|
||||
>
|
||||
<i
|
||||
className="bx bx-dots-vertical-rounded text-muted p-0"
|
||||
data-bs-toggle="tooltip"
|
||||
data-bs-offset="0,8"
|
||||
data-bs-placement="top"
|
||||
data-bs-custom-class="tooltip-dark"
|
||||
title="More Action"
|
||||
></i>
|
||||
</button>
|
||||
<ul className="dropdown-menu dropdown-menu-end w-auto">
|
||||
{canDetetExpense(expense) && (
|
||||
<li
|
||||
onClick={() =>
|
||||
setManageExpenseModal({
|
||||
IsOpen: true,
|
||||
expenseId: expense.id,
|
||||
})
|
||||
}
|
||||
>
|
||||
<a className="dropdown-item px-2 cursor-pointer py-1">
|
||||
<i className="bx bx-edit text-primary bx-xs me-2"></i>
|
||||
<span className="align-left ">
|
||||
Modify
|
||||
</span>
|
||||
</a>
|
||||
</li>
|
||||
)}
|
||||
|
||||
{canDetetExpense(expense) && (
|
||||
<i
|
||||
className="bx bx-trash text-danger cursor-pointer"
|
||||
onClick={() => {
|
||||
setIsDeleteModalOpen(true);
|
||||
setDeletingId(expense.id);
|
||||
}}
|
||||
></i>
|
||||
)}
|
||||
{canDetetExpense(expense) && (
|
||||
<li
|
||||
onClick={() => {
|
||||
setIsDeleteModalOpen(true);
|
||||
setDeletingId(expense.id);
|
||||
}}
|
||||
>
|
||||
<a className="dropdown-item px-2 cursor-pointer py-1">
|
||||
<i className="bx bx-trash text-danger bx-xs me-2"></i>
|
||||
<span className="align-left">
|
||||
Delete
|
||||
</span>
|
||||
</a>
|
||||
</li>
|
||||
)}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
@ -292,8 +370,10 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
|
||||
))
|
||||
) : (
|
||||
<tr>
|
||||
<td colSpan={8} className="text-center py-4">
|
||||
No Expense Found
|
||||
<td colSpan={8} className="text-center border-0 ">
|
||||
<div className="py-8">
|
||||
<p>No Expense Found</p>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
|
@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { localToUtc } from "../../utils/appUtils";
|
||||
|
||||
const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB
|
||||
const ALLOWED_TYPES = [
|
||||
@ -17,15 +18,12 @@ export const ExpenseSchema = (expenseTypes) => {
|
||||
.min(1, { message: "Expense type is required" }),
|
||||
paymentModeId: z.string().min(1, { message: "Payment mode is required" }),
|
||||
paidById: z.string().min(1, { message: "Employee name is required" }),
|
||||
transactionDate: z
|
||||
.string()
|
||||
.min(1, { message: "Date is required" })
|
||||
,
|
||||
transactionDate: z.string().min(1, { message: "Date is required" }),
|
||||
transactionId: z.string().optional(),
|
||||
description: z.string().min(1, { message: "Description is required" }),
|
||||
location: z.string().min(1, { message: "Location is required" }),
|
||||
supplerName: z.string().min(1, { message: "Supplier name is required" }),
|
||||
gstNumber :z.string().optional(),
|
||||
gstNumber: z.string().optional(),
|
||||
amount: z.coerce
|
||||
.number({
|
||||
invalid_type_error: "Amount is required and must be a number",
|
||||
@ -54,8 +52,6 @@ export const ExpenseSchema = (expenseTypes) => {
|
||||
})
|
||||
)
|
||||
.nonempty({ message: "At least one file attachment is required" }),
|
||||
|
||||
|
||||
})
|
||||
.refine(
|
||||
(data) => {
|
||||
@ -68,9 +64,14 @@ export const ExpenseSchema = (expenseTypes) => {
|
||||
path: ["paidById"],
|
||||
}
|
||||
)
|
||||
.superRefine((data, ctx) => {
|
||||
const expenseType = expenseTypes.find((et) => et.id === data.expensesTypeId);
|
||||
if (expenseType?.noOfPersonsRequired && (!data.noOfPersons || data.noOfPersons < 1)) {
|
||||
.superRefine((data, ctx) => {
|
||||
const expenseType = expenseTypes.find(
|
||||
(et) => et.id === data.expensesTypeId
|
||||
);
|
||||
if (
|
||||
expenseType?.noOfPersonsRequired &&
|
||||
(!data.noOfPersons || data.noOfPersons < 1)
|
||||
) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "No. of Persons is required and must be at least 1",
|
||||
@ -92,12 +93,14 @@ export const defaultExpense = {
|
||||
supplerName: "",
|
||||
amount: "",
|
||||
noOfPersons: "",
|
||||
gstNumber:"",
|
||||
gstNumber: "",
|
||||
billAttachments: [],
|
||||
};
|
||||
|
||||
|
||||
export const ExpenseActionScheam = (isReimbursement = false) => {
|
||||
export const ExpenseActionScheam = (
|
||||
isReimbursement = false,
|
||||
transactionDate
|
||||
) => {
|
||||
return z
|
||||
.object({
|
||||
comment: z.string().min(1, { message: "Please leave comment" }),
|
||||
@ -122,6 +125,15 @@ export const ExpenseActionScheam = (isReimbursement = false) => {
|
||||
message: "Reimburse Date is required",
|
||||
});
|
||||
}
|
||||
// let reimburse_Date = localToUtc(data.reimburseDate);
|
||||
// if (transactionDate > reimburse_Date) {
|
||||
// ctx.addIssue({
|
||||
// code: z.ZodIssueCode.custom,
|
||||
// path: ["reimburseDate"],
|
||||
// message:
|
||||
// "Reimburse Date must be greater than or equal to Expense created Date",
|
||||
// });
|
||||
// }
|
||||
if (!data.reimburseById) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
@ -133,7 +145,7 @@ export const ExpenseActionScheam = (isReimbursement = false) => {
|
||||
});
|
||||
};
|
||||
|
||||
export const defaultActionValues = {
|
||||
export const defaultActionValues = {
|
||||
comment: "",
|
||||
statusId: "",
|
||||
|
||||
@ -142,13 +154,12 @@ export const ExpenseActionScheam = (isReimbursement = false) => {
|
||||
reimburseById: null,
|
||||
};
|
||||
|
||||
|
||||
|
||||
export const SearchSchema = z.object({
|
||||
projectIds: z.array(z.string()).optional(),
|
||||
statusIds: z.array(z.string()).optional(),
|
||||
createdByIds: z.array(z.string()).optional(),
|
||||
paidById: z.array(z.string()).optional(),
|
||||
ExpenseTypeIds: z.array(z.string()).optional(),
|
||||
startDate: z.string().optional(),
|
||||
endDate: z.string().optional(),
|
||||
isTransactionDate: z.boolean().default(true),
|
||||
@ -159,8 +170,8 @@ export const defaultFilter = {
|
||||
statusIds: [],
|
||||
createdByIds: [],
|
||||
paidById: [],
|
||||
ExpenseTypeIds: [],
|
||||
isTransactionDate: true,
|
||||
startDate: null,
|
||||
endDate: null,
|
||||
};
|
||||
|
||||
|
@ -28,6 +28,7 @@ import moment from "moment";
|
||||
import DatePicker from "../common/DatePicker";
|
||||
import ErrorPage from "../../pages/ErrorPage";
|
||||
import Label from "../common/Label";
|
||||
import EmployeeSearchInput from "../common/EmployeeSearchInput";
|
||||
|
||||
const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
|
||||
const {
|
||||
@ -57,7 +58,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
|
||||
});
|
||||
|
||||
const selectedproject = watch("projectId");
|
||||
|
||||
|
||||
const {
|
||||
projectNames,
|
||||
loading: projectLoading,
|
||||
@ -142,8 +143,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (expenseToEdit && data ) {
|
||||
|
||||
if (expenseToEdit && data) {
|
||||
reset({
|
||||
projectId: data.project.id || "",
|
||||
expensesTypeId: data.expensesType.id || "",
|
||||
@ -156,7 +156,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
|
||||
supplerName: data.supplerName || "",
|
||||
amount: data.amount || "",
|
||||
noOfPersons: data.noOfPersons || "",
|
||||
gstNumber:data.gstNumber || "",
|
||||
gstNumber: data.gstNumber || "",
|
||||
billAttachments: data.documents
|
||||
? data.documents.map((doc) => ({
|
||||
fileName: doc.fileName,
|
||||
@ -183,8 +183,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
|
||||
const onSubmit = (fromdata) => {
|
||||
let payload = {
|
||||
...fromdata,
|
||||
transactionDate: localToUtc(fromdata.transactionDate)
|
||||
|
||||
transactionDate: localToUtc(fromdata.transactionDate),
|
||||
};
|
||||
if (expenseToEdit) {
|
||||
const editPayload = { ...payload, id: data.id };
|
||||
@ -206,7 +205,6 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
|
||||
if (StatusLoadding || projectLoading || ExpenseLoading || isLoading)
|
||||
return <ExpenseSkeleton />;
|
||||
|
||||
|
||||
return (
|
||||
<div className="container p-3">
|
||||
<h5 className="m-0">
|
||||
@ -215,7 +213,9 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
|
||||
<form id="expenseForm" onSubmit={handleSubmit(onSubmit)}>
|
||||
<div className="row my-2 text-start">
|
||||
<div className="col-md-6">
|
||||
<Label className="form-label" required>Select Project</Label>
|
||||
<Label className="form-label" required>
|
||||
Select Project
|
||||
</Label>
|
||||
<select
|
||||
className="form-select form-select-sm"
|
||||
{...register("projectId")}
|
||||
@ -296,7 +296,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="col-md-6">
|
||||
{/* <div className="col-md-6">
|
||||
<Label htmlFor="paidById" className="form-label" required>
|
||||
Paid By
|
||||
</Label>
|
||||
@ -322,6 +322,16 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
|
||||
{errors.paidById && (
|
||||
<small className="danger-text">{errors.paidById.message}</small>
|
||||
)}
|
||||
</div> */}
|
||||
|
||||
<div className="col-12 col-md-6 text-start">
|
||||
<label className="form-label">Paid By </label>
|
||||
<EmployeeSearchInput
|
||||
control={control}
|
||||
name="paidById"
|
||||
projectId={null}
|
||||
forAll={expenseToEdit ? true :false}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@ -330,7 +340,11 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
|
||||
<Label htmlFor="transactionDate" className="form-label" required>
|
||||
Transaction Date
|
||||
</Label>
|
||||
<DatePicker name="transactionDate" control={control} maxDate={new Date()}/>
|
||||
<DatePicker
|
||||
name="transactionDate"
|
||||
control={control}
|
||||
maxDate={new Date()}
|
||||
/>
|
||||
|
||||
{errors.transactionDate && (
|
||||
<small className="danger-text">
|
||||
@ -409,9 +423,9 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
|
||||
</small>
|
||||
)}
|
||||
</div>
|
||||
<div className="col-md-6">
|
||||
<div className="col-md-6">
|
||||
<label htmlFor="statusId" className="form-label ">
|
||||
GST Number
|
||||
GST Number
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
@ -421,9 +435,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
|
||||
{...register("gstNumber")}
|
||||
/>
|
||||
{errors.gstNumber && (
|
||||
<small className="danger-text">
|
||||
{errors.gstNumber.message}
|
||||
</small>
|
||||
<small className="danger-text">{errors.gstNumber.message}</small>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@ -448,7 +460,9 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
|
||||
|
||||
<div className="row my-2 text-start">
|
||||
<div className="col-md-12">
|
||||
<Label htmlFor="description" className="form-label" required>Description</Label>
|
||||
<Label htmlFor="description" className="form-label" required>
|
||||
Description
|
||||
</Label>
|
||||
<textarea
|
||||
id="description"
|
||||
className="form-control form-control-sm"
|
||||
@ -465,7 +479,9 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
|
||||
|
||||
<div className="row my-2 text-start">
|
||||
<div className="col-md-12">
|
||||
<Label className="form-label" required>Upload Bill </Label>
|
||||
<Label className="form-label" required>
|
||||
Upload Bill{" "}
|
||||
</Label>
|
||||
|
||||
<div
|
||||
className="border border-secondary border-dashed rounded p-4 text-center bg-textMuted position-relative"
|
||||
@ -549,7 +565,7 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
|
||||
|
||||
<div className="d-flex justify-content-end gap-3">
|
||||
{" "}
|
||||
<button
|
||||
<button
|
||||
type="reset"
|
||||
disabled={isPending || createPending}
|
||||
onClick={handleClose}
|
||||
@ -568,7 +584,6 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
|
||||
? "Update"
|
||||
: "Submit"}
|
||||
</button>
|
||||
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
@ -9,7 +9,7 @@ import { useForm } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { defaultActionValues, ExpenseActionScheam } from "./ExpenseSchema";
|
||||
import { useExpenseContext } from "../../pages/Expense/ExpensePage";
|
||||
import { getColorNameFromHex, getIconByFileType } from "../../utils/appUtils";
|
||||
import { getColorNameFromHex, getIconByFileType, localToUtc } from "../../utils/appUtils";
|
||||
import { ExpenseDetailsSkeleton } from "./ExpenseSkeleton";
|
||||
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
|
||||
import {
|
||||
@ -38,7 +38,7 @@ const ViewExpense = ({ ExpenseId }) => {
|
||||
const IsReview = useHasUserPermission(REVIEW_EXPENSE);
|
||||
const [imageLoaded, setImageLoaded] = useState({});
|
||||
const { setDocumentView } = useExpenseContext();
|
||||
const ActionSchema = ExpenseActionScheam(IsPaymentProcess) ?? z.object({});
|
||||
const ActionSchema = ExpenseActionScheam(IsPaymentProcess,data?.createdAt) ?? z.object({});
|
||||
const navigate = useNavigate();
|
||||
const {
|
||||
register,
|
||||
@ -91,9 +91,7 @@ const ViewExpense = ({ ExpenseId }) => {
|
||||
const onSubmit = (formData) => {
|
||||
const Payload = {
|
||||
...formData,
|
||||
reimburseDate: moment
|
||||
.utc(formData.reimburseDate, "DD-MM-YYYY")
|
||||
.toISOString(),
|
||||
reimburseDate:localToUtc(formData.reimburseDate),
|
||||
expenseId: ExpenseId,
|
||||
comment: formData.comment,
|
||||
};
|
||||
@ -108,14 +106,12 @@ const ViewExpense = ({ ExpenseId }) => {
|
||||
|
||||
return (
|
||||
<form className="container px-3" onSubmit={handleSubmit(onSubmit)}>
|
||||
<div className="row mb-3">
|
||||
<div className="col-12 mb-3">
|
||||
<h5 className="fw-semibold">Expense Details</h5>
|
||||
<div className="row mb-1">
|
||||
<div className="col-12 mb-1">
|
||||
<h5 className="fw-semibold m-0">Expense Details</h5>
|
||||
<hr />
|
||||
</div>
|
||||
<div className="text-start mb-2">
|
||||
<div className="text-muted">{data?.description}</div>
|
||||
</div>
|
||||
<div className="col-12 text-start fw-semibold my-2">{data?.expenseUId}</div>
|
||||
{/* Row 1 */}
|
||||
<div className="col-md-6 mb-3">
|
||||
<div className="d-flex">
|
||||
@ -279,7 +275,7 @@ const ViewExpense = ({ ExpenseId }) => {
|
||||
className="form-label me-2 mb-0 fw-semibold"
|
||||
style={{ minWidth: "130px" }}
|
||||
>
|
||||
Paid By:
|
||||
Paid By :
|
||||
</label>
|
||||
<div className="d-flex align-items-center ">
|
||||
<Avatar
|
||||
@ -296,6 +292,11 @@ const ViewExpense = ({ ExpenseId }) => {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="text-start my-1">
|
||||
<label className="fw-semibold form-label">Description : </label>
|
||||
<div className="text-muted">{data?.description}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="col-12 text-start">
|
||||
@ -397,7 +398,8 @@ const ViewExpense = ({ ExpenseId }) => {
|
||||
<DatePicker
|
||||
name="reimburseDate"
|
||||
control={control}
|
||||
minDate={data?.transactionDate}
|
||||
minDate={data?.createdAt}
|
||||
maxDate={new Date()}
|
||||
/>
|
||||
{errors.reimburseDate && (
|
||||
<small className="danger-text">
|
||||
@ -410,7 +412,7 @@ const ViewExpense = ({ ExpenseId }) => {
|
||||
<EmployeeSearchInput
|
||||
control={control}
|
||||
name="reimburseById"
|
||||
projectId={null}
|
||||
projectId={null}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
@ -1,3 +1,4 @@
|
||||
import { useCallback, useEffect, useState, useMemo } from "react";
|
||||
import getGreetingMessage from "../../utils/greetingHandler";
|
||||
import {
|
||||
cacheData,
|
||||
@ -14,121 +15,103 @@ import { useLocation, useNavigate, useParams } from "react-router-dom";
|
||||
import Avatar from "../../components/common/Avatar";
|
||||
import { useChangePassword } from "../Context/ChangePasswordContext";
|
||||
import { useProjects } from "../../hooks/useProjects";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { useProjectName } from "../../hooks/useProjects";
|
||||
import eventBus from "../../services/eventBus";
|
||||
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
|
||||
import { MANAGE_PROJECT } from "../../utils/constants";
|
||||
import { ALLOW_PROJECTSTATUS_ID, MANAGE_PROJECT, UUID_REGEX } from "../../utils/constants";
|
||||
import { useAuthModal, useLogout } from "../../hooks/useAuth";
|
||||
|
||||
const Header = () => {
|
||||
const { profile } = useProfile();
|
||||
const { data: masterData } = useMaster();
|
||||
const location = useLocation();
|
||||
const dispatch = useDispatch();
|
||||
const { data, loading } = useMaster();
|
||||
const navigate = useNavigate();
|
||||
const {onOpen} = useAuthModal()
|
||||
|
||||
const { mutate: logout, isPending: logouting } = useLogout();
|
||||
const { onOpen } = useAuthModal();
|
||||
const { openChangePassword } = useChangePassword();
|
||||
const HasManageProjectPermission = useHasUserPermission(MANAGE_PROJECT);
|
||||
const { mutate : logout,isPending:logouting} = useLogout()
|
||||
|
||||
const isDashboardPath =
|
||||
/^\/dashboard$/.test(location.pathname) || /^\/$/.test(location.pathname);
|
||||
const isProjectPath = /^\/projects$/.test(location.pathname);
|
||||
const pathname = location.pathname;
|
||||
|
||||
const showProjectDropdown = (pathname) => {
|
||||
const isDirectoryPath = /^\/directory$/.test(pathname);
|
||||
// ======= MEMO CHECKS =======
|
||||
const isDashboardPath = pathname === "/" || pathname === "/dashboard";
|
||||
const isProjectPath = pathname === "/projects";
|
||||
const isDirectory = pathname === "/directory";
|
||||
const isEmployeeList = pathname === "/employees";
|
||||
const isMasters = pathname === "/masters";
|
||||
// const isExpense = pathname === "/expenses";
|
||||
const isEmployeeProfile = UUID_REGEX.test(pathname);
|
||||
|
||||
// const isProfilePage = /^\/employee$/.test(location.pathname);
|
||||
const isProfilePage =
|
||||
/^\/employee\/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(
|
||||
pathname
|
||||
);
|
||||
const isExpensePage = /^\/expenses$/.test(pathname);
|
||||
const hideDropPaths =
|
||||
isDirectory || isEmployeeList || isMasters || isEmployeeProfile;
|
||||
|
||||
return !(isDirectoryPath || isProfilePage || isExpensePage);
|
||||
};
|
||||
const allowedProjectStatusIds = [
|
||||
"603e994b-a27f-4e5d-a251-f3d69b0498ba",
|
||||
"cdad86aa-8a56-4ff4-b633-9c629057dfef",
|
||||
"b74da4c2-d07e-46f2-9919-e75e49b12731",
|
||||
];
|
||||
|
||||
const getRole = (roles, joRoleId) => {
|
||||
if (!Array.isArray(roles)) return "User";
|
||||
let role = roles.find((role) => role.id === joRoleId);
|
||||
return role ? role.name : "User";
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
const handleProfilePage = () => {
|
||||
navigate(`/employee/${profile?.employeeInfo?.id}`);
|
||||
};
|
||||
const showProjectDropdown = !hideDropPaths;
|
||||
|
||||
// ===== Project Names & Selected Project =====
|
||||
const { projectNames, loading: projectLoading, fetchData } = useProjectName();
|
||||
|
||||
const selectedProject = useSelectedProject();
|
||||
|
||||
const projectsForDropdown = isDashboardPath
|
||||
? projectNames
|
||||
: projectNames?.filter((project) =>
|
||||
allowedProjectStatusIds.includes(project.projectStatusId)
|
||||
);
|
||||
const projectsForDropdown = useMemo(
|
||||
() =>
|
||||
isDashboardPath
|
||||
? projectNames
|
||||
: projectNames?.filter((project) =>
|
||||
ALLOW_PROJECTSTATUS_ID.includes(project.projectStatusId)
|
||||
),
|
||||
[projectNames, isDashboardPath]
|
||||
);
|
||||
|
||||
let currentProjectDisplayName;
|
||||
if (projectLoading) {
|
||||
currentProjectDisplayName = "Loading...";
|
||||
} else if (!projectNames || projectNames.length === 0) {
|
||||
currentProjectDisplayName = "No Projects Assigned";
|
||||
} else if (projectNames.length === 1) {
|
||||
currentProjectDisplayName = projectNames[0].name;
|
||||
} else {
|
||||
if (selectedProject === null) {
|
||||
currentProjectDisplayName = "All Projects";
|
||||
} else {
|
||||
const selectedProjectObj = projectNames.find(
|
||||
(p) => p?.id === selectedProject
|
||||
);
|
||||
currentProjectDisplayName = selectedProjectObj
|
||||
? selectedProjectObj.name
|
||||
: "All Projects";
|
||||
}
|
||||
}
|
||||
const currentProjectDisplayName = useMemo(() => {
|
||||
if (projectLoading) return "Loading...";
|
||||
if (!projectNames?.length) return "No Projects Assigned";
|
||||
if (projectNames.length === 1) return projectNames[0].name;
|
||||
if (selectedProject === null) return "All Projects";
|
||||
const selectedObj = projectNames.find((p) => p.id === selectedProject);
|
||||
return selectedObj
|
||||
? selectedObj.name
|
||||
: projectNames[0]?.name || "No Projects Assigned";
|
||||
}, [projectLoading, projectNames, selectedProject]);
|
||||
|
||||
const { openChangePassword } = useChangePassword();
|
||||
// ===== Role Helper =====
|
||||
const getRole = (roles, joRoleId) => {
|
||||
if (!Array.isArray(roles)) return "User";
|
||||
return roles.find((r) => r.id === joRoleId)?.name || "User";
|
||||
};
|
||||
|
||||
// ===== Navigate to Profile =====
|
||||
const handleProfilePage = () =>
|
||||
navigate(`/employee/${profile?.employeeInfo?.id}`);
|
||||
|
||||
// ===== Set default project on load =====
|
||||
useEffect(() => {
|
||||
if (
|
||||
projectNames &&
|
||||
projectNames.length > 0 &&
|
||||
projectNames?.length &&
|
||||
selectedProject === undefined &&
|
||||
!getCachedData("hasReceived")
|
||||
) {
|
||||
if (projectNames.length === 1) {
|
||||
dispatch(setProjectId(projectNames[0]?.id || null));
|
||||
dispatch(setProjectId(projectNames[0].id || null));
|
||||
} else {
|
||||
if (isDashboardPath) {
|
||||
dispatch(setProjectId(null));
|
||||
} else {
|
||||
const firstAllowedProject = projectNames.find((project) =>
|
||||
allowedProjectStatusIds.includes(project.projectStatusId)
|
||||
const firstAllowed = projectNames.find((project) =>
|
||||
ALLOW_PROJECTSTATUS_ID.includes(project.projectStatusId)
|
||||
);
|
||||
dispatch(setProjectId(firstAllowedProject?.id || null));
|
||||
dispatch(setProjectId(firstAllowed?.id || null));
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [projectNames, selectedProject, dispatch, isDashboardPath]);
|
||||
|
||||
// ===== Event Handlers =====
|
||||
const handler = useCallback(
|
||||
async (data) => {
|
||||
if (!HasManageProjectPermission) {
|
||||
await fetchData();
|
||||
const projectExist = data.projectIds.some(
|
||||
(item) => item === selectedProject
|
||||
);
|
||||
if (projectExist) {
|
||||
if (data.projectIds?.includes(selectedProject)) {
|
||||
cacheData("hasReceived", false);
|
||||
}
|
||||
}
|
||||
@ -138,14 +121,15 @@ const Header = () => {
|
||||
|
||||
const newProjectHandler = useCallback(
|
||||
async (msg) => {
|
||||
if (HasManageProjectPermission && msg.keyword === "Create_Project") {
|
||||
await fetchData();
|
||||
} else if (projectNames?.some((item) => item.id === msg.response.id)) {
|
||||
if (
|
||||
msg.keyword === "Create_Project" ||
|
||||
projectNames?.some((p) => p.id === msg.response?.id)
|
||||
) {
|
||||
await fetchData();
|
||||
cacheData("hasReceived", false);
|
||||
}
|
||||
cacheData("hasReceived", false);
|
||||
},
|
||||
[HasManageProjectPermission, projectNames, fetchData]
|
||||
[projectNames, fetchData]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
@ -162,10 +146,10 @@ const Header = () => {
|
||||
};
|
||||
}, [handler, newProjectHandler]);
|
||||
|
||||
const handleProjectChange = (project) => {
|
||||
dispatch(setProjectId(project));
|
||||
|
||||
if (isProjectPath && project !== null) {
|
||||
// ===== Project Change =====
|
||||
const handleProjectChange = (projectId) => {
|
||||
dispatch(setProjectId(projectId));
|
||||
if (isProjectPath && projectId !== null) {
|
||||
navigate("/projects/details");
|
||||
}
|
||||
};
|
||||
@ -177,7 +161,7 @@ const Header = () => {
|
||||
className="layout-navbar container-fluid mb-3 navbar navbar-expand-xl navbar-detached align-items-center bg-navbar-theme"
|
||||
id="layout-navbar"
|
||||
>
|
||||
<div className="layout-menu-toggle navbar-nav align-items-xl-center me-3 me-xl-0 d-xl-none">
|
||||
<div className="layout-menu-toggle navbar-nav align-items-xl-center me-2 me-xl-0 d-xl-none">
|
||||
<a
|
||||
aria-label="toggle for sidebar"
|
||||
className="nav-item nav-link px-0 me-xl-4"
|
||||
@ -189,13 +173,14 @@ const Header = () => {
|
||||
className="navbar-nav-right d-flex align-items-center justify-content-between"
|
||||
id="navbar-collapse"
|
||||
>
|
||||
{showProjectDropdown(location.pathname) && (
|
||||
<div className="align-items-center">
|
||||
<i className="rounded-circle bx bx-building-house bx-sm-lg bx-md me-2"></i>
|
||||
<div className="btn-group">
|
||||
{showProjectDropdown && (
|
||||
<div className="d-flex align-items-center">
|
||||
<i className="rounded-circle bx bx-building-house bx-sm"></i>
|
||||
|
||||
<div className="btn-group w-100">
|
||||
{shouldShowDropdown ? (
|
||||
<button
|
||||
className={`btn btn-sm-sm btn-xl dropdown-toggle px-1`}
|
||||
className="btn btn-sm btn-block dropdown-toggle text-truncate fs-6"
|
||||
type="button"
|
||||
data-bs-toggle="dropdown"
|
||||
aria-expanded="false"
|
||||
@ -203,7 +188,7 @@ const Header = () => {
|
||||
{currentProjectDisplayName}
|
||||
</button>
|
||||
) : (
|
||||
<span className="btn btn-sm-sm btn-xl px-1">
|
||||
<span className="btn btn-sm btn-block text-truncate">
|
||||
{currentProjectDisplayName}
|
||||
</span>
|
||||
)}
|
||||
@ -213,18 +198,16 @@ const Header = () => {
|
||||
projectsForDropdown.length > 0 && (
|
||||
<ul
|
||||
className="dropdown-menu"
|
||||
style={{ overflow: "auto", maxHeight: "300px" }}
|
||||
style={{ overflowY: "auto", maxHeight: "300px" }}
|
||||
>
|
||||
{isDashboardPath && (
|
||||
<li>
|
||||
<button
|
||||
className="dropdown-item"
|
||||
onClick={() => handleProjectChange(null)}
|
||||
>
|
||||
All Projects
|
||||
</button>
|
||||
</li>
|
||||
)}
|
||||
|
||||
<li>
|
||||
<button
|
||||
className="dropdown-item"
|
||||
onClick={() => handleProjectChange(null)}
|
||||
>All Project</button>
|
||||
</li>
|
||||
|
||||
{[...projectsForDropdown]
|
||||
.sort((a, b) => a?.name?.localeCompare(b.name))
|
||||
.map((project) => (
|
||||
@ -249,112 +232,9 @@ const Header = () => {
|
||||
)}
|
||||
|
||||
<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">
|
||||
<a
|
||||
className="nav-link dropdown-toggle hide-arrow"
|
||||
data-bs-toggle="dropdown"
|
||||
data-bs-auto-close="true"
|
||||
aria-expanded="false"
|
||||
>
|
||||
<i className="icon-base bx bx-grid-alt icon-md"></i>
|
||||
</a>
|
||||
<div className="dropdown-menu dropdown-menu-end p-0">
|
||||
<div className="dropdown-menu-header border-bottom">
|
||||
<div className="dropdown-header d-flex align-items-center py-3">
|
||||
<h6 className="mb-0 me-auto">Shortcuts</h6>
|
||||
<a
|
||||
className="dropdown-shortcuts-add py-2 cusror-pointer"
|
||||
data-bs-toggle="tooltip"
|
||||
data-bs-placement="top"
|
||||
aria-label="Add shortcuts"
|
||||
data-bs-original-title="Add shortcuts"
|
||||
>
|
||||
<i className="icon-base bx bx-plus-circle text-heading"></i>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<div className="dropdown-shortcuts-list scrollable-container ps">
|
||||
<div className="row row-bordered overflow-visible g-0">
|
||||
<div className="dropdown-shortcuts-item col">
|
||||
<a
|
||||
onClick={() => navigate(`/dashboard`)}
|
||||
className="text-heading text-truncate cursor-pointer"
|
||||
>
|
||||
<span className="dropdown-shortcuts-icon rounded-circle mb-3">
|
||||
<i className="icon-base bx bx-home icon-26px text-heading"></i>
|
||||
</span>
|
||||
Dashboard
|
||||
</a>
|
||||
<small>User Dashboard</small>
|
||||
</div>
|
||||
<div className="dropdown-shortcuts-item col">
|
||||
<a
|
||||
onClick={() => navigate(`/projects`)}
|
||||
className="text-heading text-truncate cursor-pointer"
|
||||
>
|
||||
<span className="dropdown-shortcuts-icon rounded-circle mb-3">
|
||||
<i className="icon-base bx bx-building-house icon-26px text-heading"></i>
|
||||
</span>
|
||||
Projects
|
||||
</a>
|
||||
<small>Projects List</small>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row row-bordered overflow-visible g-0">
|
||||
<div className="dropdown-shortcuts-item col">
|
||||
<a
|
||||
onClick={() => navigate(`/employees`)}
|
||||
className="text-heading text-truncate cursor-pointer"
|
||||
>
|
||||
<span className="dropdown-shortcuts-icon rounded-circle mb-3">
|
||||
<i className="icon-base bx bxs-user-account icon-26px text-heading"></i>
|
||||
</span>
|
||||
Employees
|
||||
</a>
|
||||
<small>Manage Employees</small>
|
||||
</div>
|
||||
<div className="dropdown-shortcuts-item col">
|
||||
<a
|
||||
onClick={() => navigate(`/activities/attendance`)}
|
||||
className="text-heading text-truncate cursor-pointer"
|
||||
>
|
||||
<span className="dropdown-shortcuts-icon rounded-circle mb-3">
|
||||
<i className="icon-base bx bx-user-check icon-26px text-heading"></i>
|
||||
</span>
|
||||
Attendance
|
||||
</a>
|
||||
<small>Manage Attendance</small>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row row-bordered overflow-visible g-0">
|
||||
<div className="dropdown-shortcuts-item col">
|
||||
<a
|
||||
onClick={() => navigate(`/activities/task`)}
|
||||
className="text-heading text-truncate cursor-pointer"
|
||||
>
|
||||
<span className="dropdown-shortcuts-icon rounded-circle mb-3">
|
||||
<i className="icon-base bx bxs-wrench icon-26px text-heading"></i>
|
||||
</span>
|
||||
Allocate Work
|
||||
</a>
|
||||
<small>Work Allocations</small>
|
||||
</div>
|
||||
<div className="dropdown-shortcuts-item col">
|
||||
<a
|
||||
onClick={() => navigate(`/activities/records`)}
|
||||
className="text-heading text-truncate cursor-pointer"
|
||||
>
|
||||
<span className="dropdown-shortcuts-icon rounded-circle mb-3">
|
||||
<i className="icon-base bx bx-list-ul icon-26px text-heading"></i>
|
||||
</span>
|
||||
Daily Work Log
|
||||
</a>
|
||||
<small>Daily Work Allocations</small>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</li>
|
||||
{/* {HasManageProjectPermission && ( */}
|
||||
|
||||
{/* )} */}
|
||||
<li className="nav-item navbar-dropdown dropdown-user dropdown">
|
||||
<a
|
||||
aria-label="dropdown profile avatar"
|
||||
@ -386,7 +266,7 @@ const Header = () => {
|
||||
{profile?.employeeInfo?.firstName}
|
||||
</span>
|
||||
<small className="text-muted">
|
||||
{getRole(data, profile?.employeeInfo?.joRoleId)}
|
||||
{getRole(masterData, profile?.employeeInfo?.joRoleId)}
|
||||
</small>
|
||||
</div>
|
||||
</div>
|
||||
@ -395,15 +275,13 @@ const Header = () => {
|
||||
<li>
|
||||
<div className="dropdown-divider"></div>
|
||||
</li>
|
||||
<li onClick={()=>onOpen()}>
|
||||
{/* <li onClick={() => onOpen()}>
|
||||
{" "}
|
||||
<a
|
||||
className="dropdown-item cusor-pointer"
|
||||
>
|
||||
<a className="dropdown-item cusor-pointer">
|
||||
<i className="bx bx-transfer-alt me-2"></i>
|
||||
<span className="align-middle">Switch Workspace</span>
|
||||
</a>
|
||||
</li>
|
||||
</li> */}
|
||||
<li onClick={handleProfilePage}>
|
||||
<a
|
||||
aria-label="go to profile"
|
||||
@ -433,7 +311,6 @@ const Header = () => {
|
||||
</a>
|
||||
</li>
|
||||
|
||||
|
||||
<li>
|
||||
<div className="dropdown-divider"></div>
|
||||
</li>
|
||||
@ -441,10 +318,17 @@ const Header = () => {
|
||||
<a
|
||||
aria-label="click to log out"
|
||||
className="dropdown-item cusor-pointer"
|
||||
onClick={()=>logout()}
|
||||
onClick={() => logout()}
|
||||
>
|
||||
{logouting ? "Please Wait":<> <i className="bx bx-log-out me-2"></i>
|
||||
<span className="align-middle">SignOut</span></>}
|
||||
{logouting ? (
|
||||
"Please Wait"
|
||||
) : (
|
||||
<>
|
||||
{" "}
|
||||
<i className="bx bx-log-out me-2"></i>
|
||||
<span className="align-middle">SignOut</span>
|
||||
</>
|
||||
)}
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
@ -454,4 +338,4 @@ const Header = () => {
|
||||
</nav>
|
||||
);
|
||||
};
|
||||
export default Header;
|
||||
export default Header;
|
||||
|
@ -42,7 +42,7 @@ const AboutProject = () => {
|
||||
{IsOpenModal && (
|
||||
<GlobalModel isOpen={IsOpenModal} closeModal={() => setIsOpenModal(false)}>
|
||||
<ManageProjectInfo
|
||||
project={projects_Details}
|
||||
project={projects_Details?.id}
|
||||
handleSubmitForm={handleFormSubmit}
|
||||
onClose={() => setIsOpenModal(false)}
|
||||
isPending={isPending}
|
||||
|
@ -5,7 +5,11 @@ import { zodResolver } from "@hookform/resolvers/zod";
|
||||
|
||||
import Label from "../common/Label";
|
||||
import DatePicker from "../common/DatePicker";
|
||||
import { useCreateProject, useProjectDetails, useUpdateProject } from "../../hooks/useProjects";
|
||||
import {
|
||||
useCreateProject,
|
||||
useProjectDetails,
|
||||
useUpdateProject,
|
||||
} from "../../hooks/useProjects";
|
||||
|
||||
import {
|
||||
DEFAULT_EMPTY_STATUS_ID,
|
||||
@ -17,6 +21,8 @@ import {
|
||||
useOrganizationsList,
|
||||
} from "../../hooks/useOrganization";
|
||||
import { localToUtc } from "../../utils/appUtils";
|
||||
import Modal from "../common/Modal";
|
||||
import { useModal } from "../../hooks/useAuth";
|
||||
|
||||
const currentDate = new Date().toLocaleDateString("en-CA");
|
||||
const formatDate = (date) => {
|
||||
@ -32,18 +38,24 @@ const formatDate = (date) => {
|
||||
const ManageProjectInfo = ({ project, onClose }) => {
|
||||
const [addressLength, setAddressLength] = useState(0);
|
||||
const maxAddressLength = 500;
|
||||
const { onOpen, startStep, flowType } = useOrganizationModal();
|
||||
const { onOpen, startStep, flowType } = useModal("ManageProject");
|
||||
|
||||
const ACTIVE_STATUS_ID = "b74da4c2-d07e-46f2-9919-e75e49b12731";
|
||||
|
||||
const { projects_Details, loading } = useProjectDetails(project);
|
||||
const { data, isLoading, isError, error } = useOrganizationsList(
|
||||
ITEMS_PER_PAGE,
|
||||
1,
|
||||
true
|
||||
// const { data, isLoading, isError, error } = useOrganizationsList(
|
||||
// ITEMS_PER_PAGE,
|
||||
// 1,
|
||||
// true
|
||||
// );
|
||||
const { mutate: UpdateProject, isPending } = useUpdateProject(() => {
|
||||
onClose?.();
|
||||
});
|
||||
const { mutate: CeateProject, isPending: isCreating } = useCreateProject(
|
||||
() => {
|
||||
onClose?.();
|
||||
}
|
||||
);
|
||||
const { mutate: UpdateProject, isPending } = useUpdateProject(() => {onClose?.()});
|
||||
const {mutate:CeateProject,isPending:isCreating} = useCreateProject(()=>{onClose?.()})
|
||||
|
||||
const {
|
||||
register,
|
||||
@ -70,11 +82,11 @@ const ManageProjectInfo = ({ project, onClose }) => {
|
||||
projectStatusId:
|
||||
String(projects_Details?.projectStatus?.id) ||
|
||||
DEFAULT_EMPTY_STATUS_IDF,
|
||||
promoterId: projects_Details?.promoter?.id || "",
|
||||
pmcId: projects_Details?.pmc?.id || "",
|
||||
// promoterId: projects_Details?.promoter?.id || "", // hide temp. for version 1
|
||||
// pmcId: projects_Details?.pmc?.id || "",
|
||||
});
|
||||
setAddressLength(projects_Details?.projectAddress?.length || 0);
|
||||
}, [project, projects_Details, reset,data]);
|
||||
}, [project, projects_Details, reset]);
|
||||
|
||||
const onSubmitForm = (formData) => {
|
||||
if (project) {
|
||||
@ -85,13 +97,13 @@ const ManageProjectInfo = ({ project, onClose }) => {
|
||||
id: project,
|
||||
};
|
||||
UpdateProject({ projectId: project, payload: payload });
|
||||
}else{
|
||||
let payload = {
|
||||
} else {
|
||||
let payload = {
|
||||
...formData,
|
||||
startDate: localToUtc(formData.startDate),
|
||||
endDate: localToUtc(formData.endDate),
|
||||
};
|
||||
CeateProject(payload)
|
||||
CeateProject(payload);
|
||||
}
|
||||
};
|
||||
|
||||
@ -104,7 +116,6 @@ const ManageProjectInfo = ({ project, onClose }) => {
|
||||
onOpen({ startStep: 2, flowType: "default" });
|
||||
};
|
||||
|
||||
|
||||
return (
|
||||
<div className="p-sm-2 p-2">
|
||||
<div className="text-center mb-2">
|
||||
@ -254,7 +265,7 @@ const ManageProjectInfo = ({ project, onClose }) => {
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="col-12 ">
|
||||
{/* <div className="col-12 ">
|
||||
<label className="form-label" htmlFor="modalEditUserStatus">
|
||||
Promoter
|
||||
</label>
|
||||
@ -330,7 +341,7 @@ const ManageProjectInfo = ({ project, onClose }) => {
|
||||
<small className="cursor-pointer" onClick={handleOrganizaioFinder}>
|
||||
<i className="bx bx-plus-circle text-primary"></i>
|
||||
</small>
|
||||
</div>
|
||||
</div> */}
|
||||
|
||||
<div className="col-12 col-md-12">
|
||||
<Label htmlFor="projectAddress" required>
|
||||
@ -376,7 +387,11 @@ const ManageProjectInfo = ({ project, onClose }) => {
|
||||
className="btn btn-primary btn-sm"
|
||||
disabled={isPending || isCreating}
|
||||
>
|
||||
{isPending||isCreating ? "Please Wait..." : project ? "Update" : "Submit"}
|
||||
{isPending || isCreating
|
||||
? "Please Wait..."
|
||||
: project
|
||||
? "Update"
|
||||
: "Submit"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
@ -385,3 +400,15 @@ const ManageProjectInfo = ({ project, onClose }) => {
|
||||
};
|
||||
|
||||
export default ManageProjectInfo;
|
||||
|
||||
export const ProjectModal = () => {
|
||||
const { isOpen, data, closeModal } = useProjectModal();
|
||||
|
||||
return (
|
||||
<Modal
|
||||
isOpen={isOpen}
|
||||
body={<ManageProjectInfo project={data} onClose={closeModal} />}
|
||||
onClose={closeModal}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
@ -35,6 +35,7 @@ const ProjectCard = ({ project }) => {
|
||||
|
||||
const handleViewProject = () => {
|
||||
dispatch(setProjectId(project.id));
|
||||
localStorage.setItem("lastActiveProjectTab","profile")
|
||||
navigate(`/projects/details`);
|
||||
};
|
||||
const handleViewActivities = () => {
|
||||
@ -54,7 +55,7 @@ const ProjectCard = ({ project }) => {
|
||||
style={{ fontSize: "xx-large" }}
|
||||
></i>
|
||||
</div>
|
||||
<div className="me-2">
|
||||
<div className="me-2 text-start">
|
||||
<h5
|
||||
className="mb-0 stretched-link text-heading text-start"
|
||||
onClick={handleViewProject}
|
||||
@ -66,7 +67,7 @@ const ProjectCard = ({ project }) => {
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className={`ms-auto ${!ManageProject && "d-none"}`}>
|
||||
<div className={`ms-auto `}>
|
||||
<div className="dropdown z-2">
|
||||
<button
|
||||
type="button"
|
||||
@ -106,12 +107,6 @@ const ProjectCard = ({ project }) => {
|
||||
<span className="align-left">Modify</span>
|
||||
</a>
|
||||
</li>
|
||||
<li onClick={handleViewActivities}>
|
||||
<a className="dropdown-item">
|
||||
<i className="bx bx-task me-2"></i>
|
||||
<span className="align-left">Activities</span>
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
@ -1,70 +1,62 @@
|
||||
import React from 'react'
|
||||
import { useProjects } from '../../hooks/useProjects'
|
||||
import Loader from '../common/Loader'
|
||||
import ProjectCard from './ProjectCard'
|
||||
|
||||
const ProjectCardView = ({currentItems,setCurrentPage,totalPages }) => {
|
||||
|
||||
import React from "react";
|
||||
import { useProjects } from "../../hooks/useProjects";
|
||||
import Loader from "../common/Loader";
|
||||
import ProjectCard from "./ProjectCard";
|
||||
|
||||
const ProjectCardView = ({ currentItems, setCurrentPage, totalPages }) => {
|
||||
return (
|
||||
<div className="row page-min-h">
|
||||
{currentItems.length === 0 && (
|
||||
<p className="text-center text-muted">No projects found.</p>
|
||||
)}
|
||||
|
||||
<div className="row page-min-h">
|
||||
{currentItems.map((project) => (
|
||||
<ProjectCard key={project.id} project={project} />
|
||||
))}
|
||||
|
||||
{ currentItems.length === 0 && (
|
||||
<p className="text-center text-muted">No projects found.</p>
|
||||
)}
|
||||
|
||||
{currentItems.map((project) => (
|
||||
<ProjectCard
|
||||
key={project.id}
|
||||
project={project}
|
||||
/>
|
||||
))}
|
||||
|
||||
|
||||
{ totalPages > 1 && (
|
||||
<nav>
|
||||
<ul className="pagination pagination-sm justify-content-end py-2">
|
||||
<li className={`page-item ${currentPage === 1 && "disabled"}`}>
|
||||
<button
|
||||
className="page-link"
|
||||
onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
|
||||
>
|
||||
«
|
||||
</button>
|
||||
</li>
|
||||
{[...Array(totalPages)].map((_, i) => (
|
||||
<li
|
||||
key={i}
|
||||
className={`page-item ${currentPage === i + 1 && "active"}`}
|
||||
>
|
||||
<button
|
||||
className="page-link"
|
||||
onClick={() => setCurrentPage(i + 1)}
|
||||
>
|
||||
{i + 1}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
{totalPages > 1 && (
|
||||
<nav>
|
||||
<ul className="pagination pagination-sm justify-content-end py-2">
|
||||
<li className={`page-item ${currentPage === 1 && "disabled"}`}>
|
||||
<button
|
||||
className="page-link"
|
||||
onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
|
||||
>
|
||||
«
|
||||
</button>
|
||||
</li>
|
||||
{[...Array(totalPages)].map((_, i) => (
|
||||
<li
|
||||
className={`page-item ${currentPage === totalPages && "disabled"
|
||||
}`}
|
||||
key={i}
|
||||
className={`page-item ${currentPage === i + 1 && "active"}`}
|
||||
>
|
||||
<button
|
||||
className="page-link"
|
||||
onClick={() =>
|
||||
setCurrentPage((p) => Math.min(totalPages, p + 1))
|
||||
}
|
||||
onClick={() => setCurrentPage(i + 1)}
|
||||
>
|
||||
»
|
||||
{i + 1}
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
)}
|
||||
</div>
|
||||
|
||||
)
|
||||
}
|
||||
))}
|
||||
<li
|
||||
className={`page-item ${
|
||||
currentPage === totalPages && "disabled"
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
className="page-link"
|
||||
onClick={() =>
|
||||
setCurrentPage((p) => Math.min(totalPages, p + 1))
|
||||
}
|
||||
>
|
||||
»
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ProjectCardView
|
||||
export default ProjectCardView;
|
||||
|
@ -26,9 +26,8 @@ const ProjectListView = ({
|
||||
const navigate = useNavigate();
|
||||
const { setMangeProject } = useProjectContext();
|
||||
// const { data, isLoading, isError, error } = useProjects();
|
||||
|
||||
// check Permissions
|
||||
const canManageProject = useHasUserPermission(MANAGE_PROJECT);
|
||||
// const canManageProject = useHasUserPermission(MANAGE_PROJECT);
|
||||
|
||||
const projectColumns = [
|
||||
{
|
||||
@ -125,154 +124,156 @@ const ProjectListView = ({
|
||||
},
|
||||
];
|
||||
|
||||
const handleViewActivities = (project) => {
|
||||
dispatch(setProjectId(project));
|
||||
navigate(`/activities/records?project=${project}`);
|
||||
};
|
||||
// const handleViewActivities = (project) => {
|
||||
// dispatch(setProjectId(project));
|
||||
// navigate(`/activities/records?project=${project}`);
|
||||
// };
|
||||
|
||||
const handleMoveDetails = (project) => {
|
||||
dispatch(setProjectId(project));
|
||||
localStorage.setItem("lastActiveProjectTab", "profile")
|
||||
navigate("/projects/details");
|
||||
};
|
||||
return (
|
||||
<div className="card page-min-h py-4 px-6 shadow-sm">
|
||||
<table className="table table-hover align-middle m-0">
|
||||
<thead className="border-bottom">
|
||||
<tr>
|
||||
{projectColumns.map((col) => (
|
||||
<th key={col.key} colSpan={col.colSpan} className={col.className}>
|
||||
{col.label}
|
||||
</th>
|
||||
))}
|
||||
<th className="text-center py-3">Action</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{currentItems?.map((project) => (
|
||||
<tr key={project.id}>
|
||||
<div className="table-responsive text-nowrap">
|
||||
<table className="table table-hover align-middle m-0">
|
||||
<thead className="border-bottom">
|
||||
<tr>
|
||||
{projectColumns.map((col) => (
|
||||
<td
|
||||
key={col.key}
|
||||
colSpan={col.colSpan}
|
||||
className={`${col.className} py-5`}
|
||||
style={{ paddingTop: "20px", paddingBottom: "20px" }}
|
||||
>
|
||||
{col.getValue
|
||||
? col.getValue(project)
|
||||
: project[col.key] || "N/A"}
|
||||
</td>
|
||||
<th key={col.key} colSpan={col.colSpan} className={col.className}>
|
||||
{col.label}
|
||||
</th>
|
||||
))}
|
||||
<td
|
||||
className={`mx-2 ${
|
||||
canManageProject ? "d-sm-table-cell" : "d-none"
|
||||
}`}
|
||||
>
|
||||
<div className="dropdown z-2">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-icon btn-text-secondary rounded-pill dropdown-toggle hide-arrow p-0"
|
||||
data-bs-toggle="dropdown"
|
||||
aria-expanded="false"
|
||||
<th className="text-center py-3">Action</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{currentItems?.map((project) => (
|
||||
<tr key={project.id}>
|
||||
{projectColumns.map((col) => (
|
||||
<td
|
||||
key={col.key}
|
||||
colSpan={col.colSpan}
|
||||
className={`${col.className} py-5`}
|
||||
style={{ paddingTop: "20px", paddingBottom: "20px" }}
|
||||
>
|
||||
<i
|
||||
className="bx bx-dots-vertical-rounded bx-sm text-muted"
|
||||
data-bs-toggle="tooltip"
|
||||
data-bs-offset="0,8"
|
||||
data-bs-placement="top"
|
||||
data-bs-custom-class="tooltip-dark"
|
||||
title="More Action"
|
||||
></i>
|
||||
</button>
|
||||
<ul className="dropdown-menu dropdown-menu-end">
|
||||
<li>
|
||||
<a
|
||||
aria-label="click to View details"
|
||||
className="dropdown-item cursor-pointer"
|
||||
>
|
||||
<i className="bx bx-detail me-2"></i>
|
||||
<span className="align-left">View details</span>
|
||||
</a>
|
||||
</li>
|
||||
{col.getValue
|
||||
? col.getValue(project)
|
||||
: project[col.key] || "N/A"}
|
||||
</td>
|
||||
))}
|
||||
<td className={`mx-2 ${"d-sm-table-cell"}`}>
|
||||
<div className="dropdown z-2">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-icon btn-text-secondary rounded-pill dropdown-toggle hide-arrow p-0"
|
||||
data-bs-toggle="dropdown"
|
||||
aria-expanded="false"
|
||||
>
|
||||
<i
|
||||
className="bx bx-dots-vertical-rounded bx-sm text-muted"
|
||||
data-bs-toggle="tooltip"
|
||||
data-bs-offset="0,8"
|
||||
data-bs-placement="top"
|
||||
data-bs-custom-class="tooltip-dark"
|
||||
title="More Action"
|
||||
></i>
|
||||
</button>
|
||||
<ul className="dropdown-menu dropdown-menu-end">
|
||||
<li onClick={() => handleMoveDetails(project.id)}>
|
||||
<a
|
||||
aria-label="click to View details"
|
||||
className="dropdown-item cursor-pointer"
|
||||
>
|
||||
<i className="bx bx-detail me-2"></i>
|
||||
<span className="align-left">View details</span>
|
||||
</a>
|
||||
</li>
|
||||
|
||||
<li>
|
||||
<a
|
||||
className="dropdown-item cursor-pointer"
|
||||
onClick={() =>
|
||||
setMangeProject({
|
||||
isOpen: true,
|
||||
Project: project.id,
|
||||
})
|
||||
}
|
||||
>
|
||||
<i className="bx bx-pencil me-2"></i>
|
||||
<span className="align-left">Modify</span>
|
||||
</a>
|
||||
</li>
|
||||
<li onClick={() => handleViewActivities(project.id)}>
|
||||
<li>
|
||||
<a
|
||||
className="dropdown-item cursor-pointer"
|
||||
onClick={() =>
|
||||
setMangeProject({
|
||||
isOpen: true,
|
||||
Project: project.id,
|
||||
})
|
||||
}
|
||||
>
|
||||
<i className="bx bx-pencil me-2"></i>
|
||||
<span className="align-left">Modify</span>
|
||||
</a>
|
||||
</li>
|
||||
{/* <li onClick={() => handleViewActivities(project.id)}>
|
||||
<a className="dropdown-item cursor-pointer">
|
||||
<i className="bx bx-task me-2"></i>
|
||||
<span className="align-left">Activities</span>
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</li> */}
|
||||
</ul>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
{isLoading && (
|
||||
<div className="py-4">
|
||||
{" "}
|
||||
{isLoading && <p className="text-center">Loading...</p>}
|
||||
{!isLoading && filteredProjects.length === 0 && (
|
||||
{isLoading && (
|
||||
<div className="py-4">
|
||||
{" "}
|
||||
{isLoading && <p className="text-center">Loading...</p>}
|
||||
{!isLoading && filteredProjects.length === 0 && (
|
||||
<p className="text-center text-muted">No projects found.</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{!isLoading && currentItems.length === 0 && (
|
||||
<div className="py-6">
|
||||
<p className="text-center text-muted">No projects found.</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{!isLoading && currentItems.length === 0 && (
|
||||
<div className="py-6">
|
||||
<p className="text-center text-muted">No projects found.</p>
|
||||
</div>
|
||||
)}
|
||||
{!isLoading && totalPages > 1 && (
|
||||
<nav>
|
||||
<ul className="pagination pagination-sm justify-content-end py-2">
|
||||
<li className={`page-item ${currentPage === 1 && "disabled"}`}>
|
||||
<button
|
||||
className="page-link"
|
||||
onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
|
||||
>
|
||||
«
|
||||
</button>
|
||||
</li>
|
||||
{[...Array(totalPages)].map((_, i) => (
|
||||
</div>
|
||||
)}
|
||||
{!isLoading && totalPages > 1 && (
|
||||
<nav>
|
||||
<ul className="pagination pagination-sm justify-content-end py-2">
|
||||
<li className={`page-item ${currentPage === 1 && "disabled"}`}>
|
||||
<button
|
||||
className="page-link"
|
||||
onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
|
||||
>
|
||||
«
|
||||
</button>
|
||||
</li>
|
||||
{[...Array(totalPages)].map((_, i) => (
|
||||
<li
|
||||
key={i}
|
||||
className={`page-item ${currentPage === i + 1 && "active"}`}
|
||||
>
|
||||
<button
|
||||
className="page-link"
|
||||
onClick={() => setCurrentPage(i + 1)}
|
||||
>
|
||||
{i + 1}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
<li
|
||||
key={i}
|
||||
className={`page-item ${currentPage === i + 1 && "active"}`}
|
||||
className={`page-item ${currentPage === totalPages && "disabled"
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
className="page-link"
|
||||
onClick={() => setCurrentPage(i + 1)}
|
||||
onClick={() =>
|
||||
setCurrentPage((p) => Math.min(totalPages, p + 1))
|
||||
}
|
||||
>
|
||||
{i + 1}
|
||||
»
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
<li
|
||||
className={`page-item ${
|
||||
currentPage === totalPages && "disabled"
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
className="page-link"
|
||||
onClick={() =>
|
||||
setCurrentPage((p) => Math.min(totalPages, p + 1))
|
||||
}
|
||||
>
|
||||
»
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
)}
|
||||
</ul>
|
||||
</nav>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
@ -27,13 +27,13 @@ const ProjectNav = ({ onPillClick, activePill }) => {
|
||||
|
||||
const ProjectTab = [
|
||||
{ key: "profile", icon: "bx bx-user", label: "Profile" },
|
||||
{ key: "teams", icon: "bx bx-group", label: "Teams" },
|
||||
{
|
||||
key: "infra",
|
||||
icon: "bx bx-grid-alt",
|
||||
label: "Infrastructure",
|
||||
hidden: !(HasViewInfraStructure || HasManageInfra || HasManageTask),
|
||||
},
|
||||
// { key: "teams", icon: "bx bx-group", label: "Teams" },
|
||||
// {
|
||||
// key: "infra",
|
||||
// icon: "bx bx-grid-alt",
|
||||
// label: "Infrastructure",
|
||||
// hidden: !(HasViewInfraStructure || HasManageInfra || HasManageTask),
|
||||
// },
|
||||
{
|
||||
key: "directory",
|
||||
icon: "bx bxs-contact",
|
||||
@ -41,8 +41,8 @@ const ProjectNav = ({ onPillClick, activePill }) => {
|
||||
hidden: !(DirAdmin || DireManager || DirUser),
|
||||
},
|
||||
{ key: "documents", icon: "bx bx-folder-open", label: "Documents",hidden:!(isViewDocuments || isModifyDocument || isUploadDocument) },
|
||||
{ key: "organization", icon: "bx bx-buildings", label: "Organization"},
|
||||
{ key: "setting", icon: "bx bxs-cog", label: "Setting",hidden:!isManageTeam },
|
||||
// { key: "organization", icon: "bx bx-buildings", label: "Organization"},
|
||||
// { key: "setting", icon: "bx bxs-cog", label: "Setting",hidden:!isManageTeam },
|
||||
];
|
||||
return (
|
||||
<div className="nav-align-top">
|
||||
|
@ -11,8 +11,8 @@ export const projectDefault = {
|
||||
startDate: currentDate.toISOString().split("T")[0],
|
||||
endDate: currentDate.toISOString().split("T")[0],
|
||||
projectStatusId: DEFAULT_EMPTY_STATUS_ID,
|
||||
promoterId: "",
|
||||
pmcId: "",
|
||||
// promoterId: "",
|
||||
// pmcId: "",
|
||||
};
|
||||
|
||||
|
||||
@ -39,8 +39,8 @@ export const projectSchema = z
|
||||
.min(1, { message: "End Date is required" })
|
||||
.default(projectDefault),
|
||||
projectStatusId: z.string().min(1, { message: "Status is required" }),
|
||||
promoterId: z.string().min(1, { message: "Promoter is required" }),
|
||||
pmcId: z.string().min(1, { message: "PMC is required" }),
|
||||
// promoterId: z.string().min(1, { message: "Promoter is required" }),
|
||||
// pmcId: z.string().min(1, { message: "PMC is required" }),
|
||||
})
|
||||
.refine(
|
||||
(data) => {
|
||||
|
@ -8,12 +8,14 @@ import { orgSize, reference } from "../../utils/constants";
|
||||
import moment from "moment";
|
||||
import { useGlobalServices } from "../../hooks/masterHook/useMaster";
|
||||
import SelectMultiple from "../common/SelectMultiple";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
|
||||
const OrganizationInfo = ({ onNext, onPrev, onSubmitTenant }) => {
|
||||
const { data, isError, isLoading: industryLoading } = useIndustries();
|
||||
const [logoPreview, setLogoPreview] = useState(null);
|
||||
const [logoName, setLogoName] = useState("");
|
||||
const { data: services, isLoading: serviceLoading } = useGlobalServices();
|
||||
const navigate = useNavigate()
|
||||
const {
|
||||
register,
|
||||
control,
|
||||
@ -29,8 +31,8 @@ const OrganizationInfo = ({ onNext, onPrev, onSubmitTenant }) => {
|
||||
error,
|
||||
isPending,
|
||||
} = useCreateTenant(() => {
|
||||
debugger
|
||||
onNext()
|
||||
// onNext()
|
||||
navigate("/tenants");
|
||||
});
|
||||
|
||||
const handleNext = async () => {
|
||||
@ -134,7 +136,6 @@ const OrganizationInfo = ({ onNext, onPrev, onSubmitTenant }) => {
|
||||
control={control}
|
||||
placeholder="DD-MM-YYYY"
|
||||
maxDate={new Date()}
|
||||
className={errors.onBoardingDate ? "is-invalid" : ""}
|
||||
/>
|
||||
{errors.onBoardingDate && (
|
||||
<div className="invalid-feedback">
|
||||
|
@ -1,5 +1,7 @@
|
||||
import React, { useEffect, useRef } from "react";
|
||||
import { useController, useFormContext, useWatch } from "react-hook-form";
|
||||
import { useSelector } from "react-redux";
|
||||
|
||||
const DateRangePicker = ({
|
||||
md,
|
||||
sm,
|
||||
@ -9,18 +11,28 @@ const DateRangePicker = ({
|
||||
}) => {
|
||||
const inputRef = useRef(null);
|
||||
|
||||
const persistedRange = useSelector(
|
||||
(store) => store.localVariables.attendance.defaultDateRange
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const endDate = new Date();
|
||||
if (endDateMode === "yesterday") {
|
||||
endDate.setDate(endDate.getDate() - 1);
|
||||
let startDate, endDate;
|
||||
|
||||
if (persistedRange?.startDate && persistedRange?.endDate) {
|
||||
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);
|
||||
}
|
||||
|
||||
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",
|
||||
dateFormat: "Y-m-d",
|
||||
@ -41,31 +53,29 @@ const DateRangePicker = ({
|
||||
endDate: endDate.toLocaleDateString("en-CA"),
|
||||
});
|
||||
|
||||
return () => {
|
||||
fp.destroy();
|
||||
};
|
||||
}, [onRangeChange, DateDifference, endDateMode]);
|
||||
return () => fp.destroy();
|
||||
}, [onRangeChange, DateDifference, endDateMode, persistedRange]);
|
||||
|
||||
const handleIconClick = () => {
|
||||
if (inputRef.current) {
|
||||
inputRef.current._flatpickr.open(); // directly opens flatpickr
|
||||
if (inputRef.current?._flatpickr) {
|
||||
inputRef.current._flatpickr.open();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`col-${sm} col-sm-${md} px-1`}>
|
||||
<div className={`position-relative w-auto justify-content-center`}>
|
||||
<input
|
||||
type="text"
|
||||
className="form-control form-control-sm ps-2 pe-5 me-4"
|
||||
className="form-control form-control-sm w-100 pe-8 "
|
||||
placeholder="From to End"
|
||||
id="flatpickr-range"
|
||||
ref={inputRef}
|
||||
/>
|
||||
|
||||
<i
|
||||
className="bx bx-calendar calendar-icon cursor-pointer position-relative top-50 translate-middle-y " onClick={handleIconClick}
|
||||
style={{ right: "22px", bottom: "-8px" }}
|
||||
></i>
|
||||
className="bx bx-calendar calendar-icon cursor-pointer position-absolute top-50 end-0 translate-middle-y me-2 "
|
||||
onClick={handleIconClick}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@ -76,6 +86,7 @@ export default DateRangePicker;
|
||||
|
||||
|
||||
|
||||
|
||||
export const DateRangePicker1 = ({
|
||||
startField = "startDate",
|
||||
endField = "endDate",
|
||||
@ -118,7 +129,7 @@ export const DateRangePicker1 = ({
|
||||
mode: "range",
|
||||
dateFormat: "d-m-Y",
|
||||
allowInput: allowText,
|
||||
maxDate ,
|
||||
maxDate,
|
||||
onChange: (selectedDates) => {
|
||||
if (selectedDates.length === 2) {
|
||||
const [start, end] = selectedDates;
|
||||
@ -148,19 +159,19 @@ export const DateRangePicker1 = ({
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (resetSignal !== undefined) {
|
||||
if (defaultRange) {
|
||||
applyDefaultDates();
|
||||
} else {
|
||||
setValue(startField, "", { shouldValidate: true });
|
||||
setValue(endField, "", { shouldValidate: true });
|
||||
if (resetSignal !== undefined) {
|
||||
if (defaultRange) {
|
||||
applyDefaultDates();
|
||||
} else {
|
||||
setValue(startField, "", { shouldValidate: true });
|
||||
setValue(endField, "", { shouldValidate: true });
|
||||
|
||||
if (inputRef.current?._flatpickr) {
|
||||
inputRef.current._flatpickr.clear();
|
||||
if (inputRef.current?._flatpickr) {
|
||||
inputRef.current._flatpickr.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}, [resetSignal, defaultRange, setValue, startField, endField]);
|
||||
}, [resetSignal, defaultRange, setValue, startField, endField]);
|
||||
|
||||
|
||||
const start = getValues(startField);
|
||||
@ -171,7 +182,7 @@ export const DateRangePicker1 = ({
|
||||
<div className={`position-relative ${className}`}>
|
||||
<input
|
||||
type="text"
|
||||
className="form-control form-control-sm"
|
||||
className="form-control form-control-sm ps-2 pe-5 me-4 cursor-pointer"
|
||||
placeholder={placeholder}
|
||||
defaultValue={formattedValue}
|
||||
ref={(el) => {
|
||||
|
@ -4,10 +4,13 @@ import { useDebounce } from "../../utils/appUtils";
|
||||
import { useController } from "react-hook-form";
|
||||
import Avatar from "./Avatar";
|
||||
|
||||
|
||||
|
||||
|
||||
const EmployeeSearchInput = ({ control, name, projectId,placeholder }) => {
|
||||
const EmployeeSearchInput = ({
|
||||
control,
|
||||
name,
|
||||
projectId,
|
||||
placeholder,
|
||||
forAll,
|
||||
}) => {
|
||||
const {
|
||||
field: { onChange, value, ref },
|
||||
fieldState: { error },
|
||||
@ -17,17 +20,20 @@ const EmployeeSearchInput = ({ control, name, projectId,placeholder }) => {
|
||||
const [showDropdown, setShowDropdown] = useState(false);
|
||||
const debouncedSearch = useDebounce(search, 500);
|
||||
|
||||
const {
|
||||
data: employees,
|
||||
isLoading,
|
||||
} = useEmployeesName(projectId, debouncedSearch);
|
||||
const { data: employees, isLoading } = useEmployeesName(
|
||||
projectId,
|
||||
debouncedSearch,
|
||||
forAll
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (value && !search) {
|
||||
const found = employees?.data?.find((emp) => emp.id === value);
|
||||
if (found) setSearch(found.firstName + " " + found.lastName);
|
||||
if (value && employees?.data) {
|
||||
const found = employees.data.find((emp) => emp.id === value);
|
||||
if (found && forAll) {
|
||||
setSearch(found.firstName + " " + found.lastName);
|
||||
}
|
||||
}
|
||||
}, [value, employees]);
|
||||
}, [value, employees?.data]);
|
||||
|
||||
const handleSelect = (employee) => {
|
||||
onChange(employee.id);
|
||||
@ -46,7 +52,7 @@ const EmployeeSearchInput = ({ control, name, projectId,placeholder }) => {
|
||||
onChange={(e) => {
|
||||
setSearch(e.target.value);
|
||||
setShowDropdown(true);
|
||||
onChange("");
|
||||
onChange("");
|
||||
}}
|
||||
onFocus={() => {
|
||||
if (search) setShowDropdown(true);
|
||||
@ -61,28 +67,27 @@ const EmployeeSearchInput = ({ control, name, projectId,placeholder }) => {
|
||||
{isLoading ? (
|
||||
<li className="list-group-item">
|
||||
<a>Searching...</a>
|
||||
|
||||
</li>
|
||||
) : (
|
||||
employees?.data?.map((emp) => (
|
||||
<li
|
||||
key={emp.id}
|
||||
className="list-group-item list-group-item-action py-1 px-1"
|
||||
style={{ cursor: "pointer" }}
|
||||
onClick={() => handleSelect(emp)}
|
||||
>
|
||||
<div className="d-flex align-items-center px-0">
|
||||
<Avatar
|
||||
size="xs"
|
||||
classAvatar="m-0 me-2"
|
||||
firstName={emp.firstName}
|
||||
lastName={emp.lastName}
|
||||
/>
|
||||
<span className="text-muted">
|
||||
{`${emp?.firstName} ${emp?.lastName}`.trim()}
|
||||
</span>
|
||||
</div>
|
||||
</li>
|
||||
<li
|
||||
key={emp.id}
|
||||
className="list-group-item list-group-item-action py-1 px-1"
|
||||
style={{ cursor: "pointer" }}
|
||||
onClick={() => handleSelect(emp)}
|
||||
>
|
||||
<div className="d-flex align-items-center px-0">
|
||||
<Avatar
|
||||
size="xs"
|
||||
classAvatar="m-0 me-2"
|
||||
firstName={emp.firstName}
|
||||
lastName={emp.lastName}
|
||||
/>
|
||||
<span className="text-muted">
|
||||
{`${emp?.firstName} ${emp?.lastName}`.trim()}
|
||||
</span>
|
||||
</div>
|
||||
</li>
|
||||
))
|
||||
)}
|
||||
</ul>
|
||||
|
@ -4,21 +4,26 @@ import { createPortal } from "react-dom";
|
||||
import "./MultiSelectDropdown.css";
|
||||
import Label from "./Label";
|
||||
|
||||
|
||||
|
||||
|
||||
const SelectMultiple = ({
|
||||
name,
|
||||
options = [],
|
||||
label = "Select options",
|
||||
labelKey = "name",
|
||||
labelKey = "name",
|
||||
valueKey = "id",
|
||||
placeholder = "Please select...",
|
||||
IsLoading = false,required = false
|
||||
IsLoading = false,
|
||||
required = false,
|
||||
}) => {
|
||||
const { setValue, watch,register } = useFormContext();
|
||||
useEffect(() => {
|
||||
register(name, { value: [] });
|
||||
}, [register, name]);
|
||||
const { setValue, watch, register } = useFormContext();
|
||||
|
||||
const selectedValues = watch(name) || [];
|
||||
useEffect(() => {
|
||||
register(name, { value: [] });
|
||||
}, [register, name]);
|
||||
|
||||
const selectedValues = watch(name) || [];
|
||||
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [searchText, setSearchText] = useState("");
|
||||
@ -60,18 +65,20 @@ const selectedValues = watch(name) || [];
|
||||
const updated = selectedValues.includes(value)
|
||||
? selectedValues.filter((v) => v !== value)
|
||||
: [...selectedValues, value];
|
||||
|
||||
setValue(name, updated, { shouldValidate: true });
|
||||
};
|
||||
|
||||
const filteredOptions = (options || []).filter((item) => {
|
||||
const label = getLabel(item);
|
||||
return (
|
||||
typeof label === "string" &&
|
||||
label.toLowerCase().includes(searchText.toLowerCase())
|
||||
);
|
||||
});
|
||||
const label = getLabel(item);
|
||||
return typeof label === "string" && label.toLowerCase().includes(searchText.toLowerCase());
|
||||
});
|
||||
|
||||
// Sort filtered options in ascending order
|
||||
const sortedOptions = filteredOptions.sort((a, b) => {
|
||||
const labelA = getLabel(a).toString().toLowerCase();
|
||||
const labelB = getLabel(b).toString().toLowerCase();
|
||||
return labelA.localeCompare(labelB);
|
||||
});
|
||||
|
||||
const dropdownElement = (
|
||||
<div
|
||||
@ -101,7 +108,7 @@ const selectedValues = watch(name) || [];
|
||||
/>
|
||||
</div>
|
||||
|
||||
{filteredOptions.map((item) => {
|
||||
{sortedOptions.map((item) => {
|
||||
const labelVal = getLabel(item);
|
||||
const valueVal = item[valueKey];
|
||||
const isChecked = selectedValues.includes(valueVal);
|
||||
@ -124,12 +131,12 @@ const selectedValues = watch(name) || [];
|
||||
);
|
||||
})}
|
||||
|
||||
{!IsLoading && filteredOptions.length === 0 && (
|
||||
{!IsLoading && sortedOptions.length === 0 && (
|
||||
<div className="multi-select-dropdown-Not-found" style={{ padding: 8 }}>
|
||||
<label className="text-muted">Not Found {`'${searchText}'`}</label>
|
||||
</div>
|
||||
)}
|
||||
{IsLoading && filteredOptions.length === 0 && (
|
||||
{IsLoading && sortedOptions.length === 0 && (
|
||||
<div className="multi-select-dropdown-Not-found" style={{ padding: 8 }}>
|
||||
<label className="text-muted">Loading...</label>
|
||||
</div>
|
||||
@ -140,19 +147,14 @@ const selectedValues = watch(name) || [];
|
||||
return (
|
||||
<>
|
||||
<div ref={containerRef} className="multi-select-dropdown-container" style={{ position: "relative" }}>
|
||||
<label className="form-label mb-1">{label}</label>
|
||||
<Label className={name} required={required}></Label>
|
||||
<Label required={required}>{label}</Label>
|
||||
|
||||
<div
|
||||
className="multi-select-dropdown-header"
|
||||
onClick={() => setIsOpen((prev) => !prev)}
|
||||
style={{ cursor: "pointer" }}
|
||||
>
|
||||
<span
|
||||
className={
|
||||
selectedValues.length > 0 ? "placeholder-style-selected" : "placeholder-style"
|
||||
}
|
||||
>
|
||||
<span className={selectedValues.length > 0 ? "placeholder-style-selected" : "placeholder-style"}>
|
||||
<div className="selected-badges-container">
|
||||
{selectedValues.length > 0 ? (
|
||||
selectedValues.map((val) => {
|
||||
|
@ -2,7 +2,7 @@ import { useFormContext, useWatch } from "react-hook-form";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import Label from "./Label";
|
||||
|
||||
const TagInput = ({ label, name, placeholder, color = "#e9ecef", options = [] }) => {
|
||||
const TagInput = ({ label, name, placeholder, color = "#e9ecef", options = [],require = false }) => {
|
||||
const { setValue, watch } = useFormContext();
|
||||
const tags = watch(name) || [];
|
||||
const [input, setInput] = useState("");
|
||||
@ -65,9 +65,9 @@ const handleChange = (e) => {
|
||||
|
||||
return (
|
||||
<>
|
||||
<label htmlFor={name} className="form-label">
|
||||
<Label required={require}>
|
||||
{label}
|
||||
</label>
|
||||
</Label>
|
||||
|
||||
<div
|
||||
className="form-control form-control-sm p-1"
|
||||
|
@ -37,7 +37,6 @@ const ServiceGroups = ({ service }) => {
|
||||
|
||||
<div className="w-100 my-2">
|
||||
|
||||
<p className="fs-5 fw-semibold">Manage Service</p>
|
||||
<div className="accordion" id="accordionExample">
|
||||
<div className="accordion-item active shadow-none">
|
||||
{/* Service Header */}
|
||||
|
@ -12,38 +12,9 @@ import { setDefaultDateRange } from "../slices/localVariablesSlice";
|
||||
// ----------------------------Query-----------------------------
|
||||
|
||||
|
||||
// export const useAttendance = (projectId) => {
|
||||
// const dispatch = useDispatch()
|
||||
// const {
|
||||
// data: attendance = [],
|
||||
// isLoading: loading,
|
||||
// error,
|
||||
// refetch: recall,
|
||||
// isFetching
|
||||
// } = useQuery({
|
||||
// queryKey: ["attendance", projectId],
|
||||
// queryFn: async () => {
|
||||
// const response = await AttendanceRepository.getAttendance(projectId);
|
||||
// return response.data;
|
||||
// },
|
||||
// enabled: !!projectId,
|
||||
// onError: (error) => {
|
||||
// showToast(error.message || "Error while fetching Attendance", "error");
|
||||
// },
|
||||
// });
|
||||
|
||||
// return {
|
||||
// attendance,
|
||||
// loading,
|
||||
// error,
|
||||
// recall,
|
||||
// isFetching
|
||||
// };
|
||||
// };
|
||||
|
||||
export const useAttendance = (projectId, organizationId, includeInactive = false, date = null) => {
|
||||
const dispatch = useDispatch();
|
||||
|
||||
// queryKey: ["attendance", projectId, organizationId, includeInactive, date],
|
||||
const {
|
||||
data: attendance = [],
|
||||
isLoading: loading,
|
||||
@ -51,7 +22,7 @@ export const useAttendance = (projectId, organizationId, includeInactive = false
|
||||
refetch: recall,
|
||||
isFetching,
|
||||
} = useQuery({
|
||||
queryKey: ["attendance", projectId, organizationId, includeInactive, date], // include filters in cache key
|
||||
queryKey: ["attendance", projectId ],
|
||||
queryFn: async () => {
|
||||
const response = await AttendanceRepository.getAttendance(
|
||||
projectId,
|
||||
@ -61,7 +32,6 @@ export const useAttendance = (projectId, organizationId, includeInactive = false
|
||||
);
|
||||
return response.data;
|
||||
},
|
||||
enabled: !!projectId, // only run if projectId exists
|
||||
onError: (error) => {
|
||||
showToast(error.message || "Error while fetching Attendance", "error");
|
||||
},
|
||||
@ -72,7 +42,6 @@ export const useAttendance = (projectId, organizationId, includeInactive = false
|
||||
|
||||
export const useAttendancesLogs = (projectId, fromDate, toDate,organizationId) => {
|
||||
const dispatch = useDispatch();
|
||||
const enabled = !!projectId && !!fromDate && !!toDate;
|
||||
|
||||
const query = useQuery({
|
||||
queryKey: ['attendanceLogs', projectId, fromDate, toDate,organizationId],
|
||||
@ -85,7 +54,6 @@ export const useAttendancesLogs = (projectId, fromDate, toDate,organizationId) =
|
||||
);
|
||||
return res.data;
|
||||
},
|
||||
enabled,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
@ -142,31 +110,6 @@ export const useAttendanceByEmployee = (employeeId, fromDate, toDate) => {
|
||||
});
|
||||
};
|
||||
|
||||
// export const useRegularizationRequests = (projectId) => {
|
||||
// const {
|
||||
// data: regularizes = [],
|
||||
// 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();
|
||||
@ -178,7 +121,7 @@ export const useRegularizationRequests = (projectId, organizationId, IncludeInAc
|
||||
refetch: recall,
|
||||
isFetching,
|
||||
} = useQuery({
|
||||
queryKey: ["regularizedList", projectId, organizationId, IncludeInActive], // include filters in cache key
|
||||
queryKey: ["regularizedList", projectId, organizationId, IncludeInActive],
|
||||
queryFn: async () => {
|
||||
const response = await AttendanceRepository.getRegularizeList(
|
||||
projectId,
|
||||
@ -187,7 +130,6 @@ export const useRegularizationRequests = (projectId, organizationId, IncludeInAc
|
||||
);
|
||||
return response.data;
|
||||
},
|
||||
enabled: !!projectId, // only run if projectId exists
|
||||
onError: (error) => {
|
||||
showToast(error.message || "Error while fetching regularizes", "error");
|
||||
},
|
||||
@ -218,10 +160,11 @@ export const useMarkAttendance = () => {
|
||||
emp.employeeId === data.employeeId ? { ...emp, ...data } : emp
|
||||
);
|
||||
});
|
||||
// queryClient.invalidateQueries({queryKey:["attendance"]})
|
||||
}else if(variables.forWhichTab == 2){
|
||||
// queryClient.invalidateQueries({
|
||||
// queryKey: ["attendanceLogs"],
|
||||
// });
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ["attendanceLogs"],
|
||||
});
|
||||
queryClient.setQueryData(["attendanceLogs",selectedProject,selectedDateRange.startDate,selectedDateRange.endDate], (oldData) => {
|
||||
if (!oldData) return oldData;
|
||||
return oldData.map((record) =>
|
||||
|
@ -14,6 +14,23 @@ import {
|
||||
} from "../slices/localVariablesSlice.jsx";
|
||||
import { removeSession } from "../utils/authUtils.js";
|
||||
|
||||
|
||||
|
||||
// ----------------------------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 };
|
||||
};
|
||||
|
||||
export const useTenants = () => {
|
||||
return useQuery({
|
||||
queryKey: ["tenantlist"],
|
||||
|
@ -155,32 +155,32 @@ export const useDashboard_Data = ({ days, FromDate, projectId }) => {
|
||||
// };
|
||||
|
||||
|
||||
export const useAttendanceOverviewData = (projectId, days) => {
|
||||
const [attendanceOverviewData, setAttendanceOverviewData] = useState([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
// export const useAttendanceOverviewData = (projectId, days) => {
|
||||
// const [attendanceOverviewData, setAttendanceOverviewData] = useState([]);
|
||||
// const [loading, setLoading] = useState(false);
|
||||
// const [error, setError] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
if (!projectId || !days) return;
|
||||
const fetchAttendanceOverview = async () => {
|
||||
setLoading(true);
|
||||
setError("");
|
||||
// useEffect(() => {
|
||||
// if (!projectId || !days) return;
|
||||
// const fetchAttendanceOverview = async () => {
|
||||
// setLoading(true);
|
||||
// setError("");
|
||||
|
||||
try {
|
||||
const response = await GlobalRepository.getAttendanceOverview(projectId, days);
|
||||
setAttendanceOverviewData(response.data);
|
||||
} catch (err) {
|
||||
setError("Failed to fetch attendance overview data.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
// try {
|
||||
// const response = await GlobalRepository.getAttendanceOverview(projectId, days);
|
||||
// setAttendanceOverviewData(response.data);
|
||||
// } catch (err) {
|
||||
// setError("Failed to fetch attendance overview data.");
|
||||
// } finally {
|
||||
// setLoading(false);
|
||||
// }
|
||||
// };
|
||||
|
||||
fetchAttendanceOverview();
|
||||
}, [projectId, days]);
|
||||
// fetchAttendanceOverview();
|
||||
// }, [projectId, days]);
|
||||
|
||||
return { attendanceOverviewData, loading, error };
|
||||
};
|
||||
// return { attendanceOverviewData, loading, error };
|
||||
// };
|
||||
|
||||
|
||||
// -------------------Query----------------------------
|
||||
@ -232,16 +232,17 @@ export const useDashboardTasksCardData = (projectId) => {
|
||||
}
|
||||
})
|
||||
}
|
||||
// export const useAttendanceOverviewData = (projectId, days) => {
|
||||
// return useQuery({
|
||||
// queryKey:["dashboardAttendanceOverView",projectId],
|
||||
// queryFn:async()=> {
|
||||
export const useAttendanceOverviewData = (projectId, days) => {
|
||||
return useQuery({
|
||||
queryKey:["dashboardAttendanceOverView",projectId,days],
|
||||
queryFn:async()=> {
|
||||
|
||||
// const resp = await GlobalRepository.getAttendanceOverview(projectId, days);
|
||||
// return resp.data;
|
||||
// }
|
||||
// })
|
||||
// }
|
||||
const resp = await GlobalRepository.getAttendanceOverview(projectId, days);
|
||||
return resp.data;
|
||||
},
|
||||
enabled:!!projectId
|
||||
})
|
||||
}
|
||||
|
||||
export const useDashboardProjectsCardData = () => {
|
||||
return useQuery({
|
||||
@ -252,4 +253,44 @@ export const useDashboardProjectsCardData = () => {
|
||||
return resp.data;
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export const useExpenseAnalysis = (projectId, startDate, endDate) => {
|
||||
const hasBothDates = !!startDate && !!endDate;
|
||||
const noDatesSelected = !startDate && !endDate;
|
||||
|
||||
const shouldFetch =
|
||||
noDatesSelected ||
|
||||
hasBothDates;
|
||||
return useQuery({
|
||||
queryKey: ["expenseAnalysis", projectId, startDate, endDate],
|
||||
queryFn: async () => {
|
||||
const resp = await GlobalRepository.getExpenseData(projectId, startDate, endDate);
|
||||
return resp.data;
|
||||
},
|
||||
enabled:shouldFetch,
|
||||
refetchOnWindowFocus: true, // refetch when you come back
|
||||
refetchOnMount: "always", // always refetch on remount
|
||||
staleTime: 0,
|
||||
});
|
||||
};
|
||||
export const useExpenseStatus = (projectId)=>{
|
||||
return useQuery({
|
||||
queryKey:["expense_stauts",projectId],
|
||||
queryFn: async()=>{
|
||||
const resp = await GlobalRepository.getExpenseStatus(projectId);
|
||||
return resp.data;
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export const useExpenseDataByProject = (projectId, categoryId, months) => {
|
||||
return useQuery({
|
||||
queryKey: ["expenseByProject", projectId, categoryId, months],
|
||||
queryFn: async () => {
|
||||
const resp = await GlobalRepository.getExpenseDataByProject(projectId, categoryId, months);
|
||||
return resp.data;
|
||||
},
|
||||
|
||||
});
|
||||
};
|
@ -399,7 +399,6 @@ export const useUpdateBucket = (onSuccessCallBack) => {
|
||||
mutationFn: async ({ bucketId, BucketPayload }) =>
|
||||
await DirectoryRepository.UpdateBuckets(bucketId, BucketPayload),
|
||||
onSuccess: (_, variables) => {
|
||||
debugger;
|
||||
queryClient.invalidateQueries({ queryKey: ["bucketList"] });
|
||||
showToast("Bucket updated successfully", "success");
|
||||
if (onSuccessCallBack) onSuccessCallBack();
|
||||
@ -415,7 +414,7 @@ export const useUpdateBucket = (onSuccessCallBack) => {
|
||||
});
|
||||
};
|
||||
|
||||
export const useAssignEmpToBucket = () => {
|
||||
export const useAssignEmpToBucket = (onSuccessCallBack) => {
|
||||
return useMutation({
|
||||
mutationFn: async ({ bucketId, EmployeePayload }) =>
|
||||
await DirectoryRepository.AssignedBuckets(bucketId, EmployeePayload),
|
||||
@ -464,6 +463,7 @@ export const useCreateContact = (onSuccessCallBack) => {
|
||||
await DirectoryRepository.CreateContact(contactPayload),
|
||||
onSuccess: (_, variables) => {
|
||||
queryClient.invalidateQueries({ queryKey: ["contacts"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["bucketList"] });
|
||||
showToast("Contact created Successfully", "success");
|
||||
if (onSuccessCallBack) onSuccessCallBack();
|
||||
},
|
||||
@ -483,6 +483,7 @@ export const useUpdateContact = (onSuccessCallBack) => {
|
||||
mutationFn: async ({ contactId, contactPayload }) =>
|
||||
await DirectoryRepository.UpdateContact(contactId, contactPayload),
|
||||
onSuccess: (_, variables) => {
|
||||
queryClient.invalidateQueries({ queryKey: ["Contact"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["contacts"] });
|
||||
showToast("Contact updated Successfully", "success");
|
||||
if (onSuccessCallBack) onSuccessCallBack();
|
||||
|
@ -120,7 +120,7 @@ export const useUploadDocument = (onSuccessCallBack) => {
|
||||
DocumentRepository.uploadDocument(DocumentPayload),
|
||||
onSuccess: (data, variables) => {
|
||||
queryClient.invalidateQueries({ queryKey: ["DocumentList"] });
|
||||
|
||||
queryClient.invalidateQueries({ queryKey: ["Document"] });
|
||||
if (onSuccessCallBack) onSuccessCallBack();
|
||||
},
|
||||
onError: (error) => {
|
||||
@ -141,7 +141,7 @@ export const useUpdateDocument = (onSuccessCallBack) => {
|
||||
onSuccess: (data, variables) => {
|
||||
const { documentId } = variables;
|
||||
queryClient.invalidateQueries({ queryKey: ["DocumentList"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["Document", documentId] });
|
||||
queryClient.invalidateQueries({ queryKey: ["Document"] });
|
||||
if (onSuccessCallBack) onSuccessCallBack();
|
||||
},
|
||||
onError: (error) => {
|
||||
@ -187,6 +187,7 @@ export const useActiveInActiveDocument = ()=>{
|
||||
onSuccess: (data, variables) => {
|
||||
const {isActive} = variables;
|
||||
queryClient.invalidateQueries({ queryKey: ["DocumentList"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["Document"] });
|
||||
showToast(`Document ${isActive ? "restored":"Deleted"} successfully`,"success")
|
||||
},
|
||||
onError: (error) => {
|
||||
|
@ -12,14 +12,14 @@ import { queryClient } from "../layouts/AuthLayout";
|
||||
// Query ---------------------------------------------------------------------------
|
||||
|
||||
export const useEmployee = (employeeId) => {
|
||||
return useQuery({
|
||||
return useQuery({
|
||||
queryKey: ["employeeProfile", employeeId],
|
||||
queryFn: async () => {
|
||||
const res = await EmployeeRepository.getEmployeeProfile(employeeId)
|
||||
const res = await EmployeeRepository.getEmployeeProfile(employeeId);
|
||||
return res.data;
|
||||
},
|
||||
enabled:!!employeeId
|
||||
});
|
||||
enabled: !!employeeId,
|
||||
});
|
||||
};
|
||||
|
||||
export const useAllEmployees = (showInactive) => {
|
||||
@ -184,11 +184,11 @@ export const useEmployeeProfile = (employeeId) => {
|
||||
};
|
||||
};
|
||||
|
||||
export const useEmployeesName = (projectId, search) => {
|
||||
export const useEmployeesName = (projectId, search,forAll) => {
|
||||
return useQuery({
|
||||
queryKey: ["employees", projectId, search],
|
||||
queryKey: ["employees", projectId, search,forAll],
|
||||
queryFn: async () =>
|
||||
await EmployeeRepository.getEmployeeName(projectId, search),
|
||||
await EmployeeRepository.getEmployeeName(projectId, search,forAll),
|
||||
|
||||
staleTime: 5 * 60 * 1000, // Optional: cache for 5 minutes
|
||||
});
|
||||
@ -208,9 +208,6 @@ export const useEmployeesNameByProject = (projectId) => {
|
||||
|
||||
// Mutation------------------------------------------------------------------
|
||||
|
||||
|
||||
|
||||
|
||||
export const useUpdateEmployee = () => {
|
||||
const selectedProject = useSelector(
|
||||
(store) => store.localVariables.projectId
|
||||
@ -218,14 +215,15 @@ export const useUpdateEmployee = () => {
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: (employeeData) =>
|
||||
EmployeeRepository.manageEmployee(employeeData),
|
||||
mutationFn: async (employeeData) =>
|
||||
await EmployeeRepository.manageEmployee(employeeData),
|
||||
onSuccess: (_, variables) => {
|
||||
debugger;
|
||||
const id = variables?.id || variables?.employeeId;
|
||||
const isAllEmployee = variables.IsAllEmployee;
|
||||
|
||||
// Cache invalidation
|
||||
queryClient.invalidateQueries({ queryKey: ["employeeProfile",id] });
|
||||
queryClient.invalidateQueries({ queryKey: ["employeeProfile"] });
|
||||
queryClient.invalidateQueries({ queryKey: ["allEmployees"] });
|
||||
// queryClient.invalidateQueries(['employeeProfile', id]);
|
||||
queryClient.invalidateQueries({ queryKey: ["projectEmployees"] });
|
||||
@ -247,7 +245,6 @@ export const useUpdateEmployee = () => {
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
export const useSuspendEmployee = ({
|
||||
setIsDeleteModalOpen,
|
||||
setemployeeLodaing,
|
||||
@ -300,7 +297,6 @@ export const useSuspendEmployee = ({
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
export const useUpdateEmployeeRoles = ({
|
||||
onClose,
|
||||
resetForm,
|
||||
@ -334,4 +330,4 @@ export const useUpdateEmployeeRoles = ({
|
||||
isError: mutation.isError,
|
||||
error: mutation.error,
|
||||
};
|
||||
};
|
||||
};
|
||||
|
@ -10,7 +10,7 @@ import moment from "moment";
|
||||
const cleanFilter = (filter) => {
|
||||
const cleaned = { ...filter };
|
||||
|
||||
["projectIds", "statusIds", "createdByIds", "paidById"].forEach((key) => {
|
||||
["projectIds", "statusIds", "createdByIds", "paidById","ExpenseTypeIds"].forEach((key) => {
|
||||
if (Array.isArray(cleaned[key]) && cleaned[key].length === 0) {
|
||||
delete cleaned[key];
|
||||
}
|
||||
|
@ -8,19 +8,20 @@ export const useHasUserPermission = (permission) => {
|
||||
data: projectPermissions = [],
|
||||
isLoading,
|
||||
isError,
|
||||
} = useAllProjectLevelPermissions(selectedProject);
|
||||
|
||||
} = useAllProjectLevelPermissions();
|
||||
// set selectedProject to call api- selectedProject
|
||||
if (isLoading || !permission) return false;
|
||||
|
||||
const globalPerms = profile?.featurePermissions ?? [];
|
||||
const projectPerms = projectPermissions ?? [];
|
||||
if (selectedProject) {
|
||||
if (projectPerms.length === 0) {
|
||||
return projectPerms.includes(permission);
|
||||
} else {
|
||||
return projectPerms.includes(permission);
|
||||
}
|
||||
} else {
|
||||
return globalPerms.includes(permission);
|
||||
}
|
||||
// const projectPerms = projectPermissions ?? [];
|
||||
// if (selectedProject) {
|
||||
// if (projectPerms.length === 0) {
|
||||
// return projectPerms.includes(permission);
|
||||
// } else {
|
||||
// return projectPerms.includes(permission);
|
||||
// }
|
||||
// } else {
|
||||
// return globalPerms.includes(permission);
|
||||
// }
|
||||
return globalPerms.includes(permission);
|
||||
};
|
||||
|
@ -14,7 +14,6 @@ export const useProjectAccess = (projectId) => {
|
||||
const canView = useHasUserPermission(VIEW_PROJECTS);
|
||||
|
||||
const loading = isLoading || !isFetched;
|
||||
debugger
|
||||
useEffect(() => {
|
||||
if (projectId && !loading && !canView) {
|
||||
showToast("You don't have permission to view project details", "warning");
|
||||
|
@ -3,7 +3,7 @@ import { cacheData, getCachedData } from "../slices/apiDataManager";
|
||||
import ProjectRepository from "../repositories/ProjectRepository";
|
||||
import { useProfile } from "./useProfile";
|
||||
import { useDispatch, useSelector } from "react-redux";
|
||||
import { setProjectId } from "../slices/localVariablesSlice";
|
||||
import { setProjectId } from "../slices/localVariablesSlice";
|
||||
import EmployeeList from "../components/Directory/EmployeeList";
|
||||
import eventBus from "../services/eventBus";
|
||||
import {
|
||||
@ -12,12 +12,26 @@ import {
|
||||
useQuery,
|
||||
useQueryClient,
|
||||
} from "@tanstack/react-query";
|
||||
|
||||
|
||||
import showToast from "../services/toastService";
|
||||
|
||||
export const useCurrentService = () => {
|
||||
return useSelector((store) => store.globalVariables.selectedServiceId);
|
||||
};
|
||||
|
||||
// export const useProjectModal = () => {
|
||||
// const dispatch = useDispatch();
|
||||
// const { isOpen, data } = useSelector((state) => state.localVariables.ProjectModal);
|
||||
|
||||
// return {
|
||||
// isOpen,
|
||||
// data,
|
||||
// openModal: (payload = null) => dispatch(openProjectModal(payload)),
|
||||
// closeModal: () => dispatch(closeProjectModal()),
|
||||
// };
|
||||
// };
|
||||
|
||||
// ------------------------------Query-------------------
|
||||
|
||||
export const useProjects = () => {
|
||||
|
@ -6,6 +6,7 @@ import { useDispatch } from "react-redux";
|
||||
import { setCurrentTenant } from "../slices/globalVariablesSlice";
|
||||
import { ITEMS_PER_PAGE } from "../utils/constants";
|
||||
import moment from "moment";
|
||||
import { queryClient } from "../layouts/AuthLayout";
|
||||
|
||||
const cleanFilter = (filter) => {
|
||||
const cleaned = { ...filter };
|
||||
@ -71,6 +72,7 @@ export const useSubscriptionPlan = (freq) => {
|
||||
// ------------Mutation---------------------
|
||||
|
||||
export const useCreateTenant = (onSuccessCallback) => {
|
||||
const clinet = queryClient()
|
||||
const dispatch = useDispatch();
|
||||
return useMutation({
|
||||
mutationFn: async (tenantPayload) => {
|
||||
@ -87,6 +89,9 @@ export const useCreateTenant = (onSuccessCallback) => {
|
||||
operationMode = 2; // tenant exists but subscription not added yet
|
||||
}
|
||||
|
||||
clinet.invalidateQueries({queryKey:["Tenants"]})
|
||||
|
||||
|
||||
dispatch(setCurrentTenant({ operationMode, data }));
|
||||
|
||||
if (onSuccessCallback) onSuccessCallback();
|
||||
|
@ -70,7 +70,8 @@ const AttendancePage = () => {
|
||||
};
|
||||
|
||||
const handleModalData = (employee) => {
|
||||
setModelConfig(employee);
|
||||
setModelConfig(employee);
|
||||
if (employee !== null) setIsCreateModalOpen(true);
|
||||
};
|
||||
|
||||
const closeModal = () => {
|
||||
@ -78,11 +79,7 @@ const AttendancePage = () => {
|
||||
setIsCreateModalOpen(false);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (modelConfig !== null) {
|
||||
openModel();
|
||||
}
|
||||
}, [modelConfig, isCreateModalOpen]);
|
||||
|
||||
|
||||
// Handler to change tab and reset search term
|
||||
const handleTabChange = (tabName) => {
|
||||
@ -127,7 +124,7 @@ const AttendancePage = () => {
|
||||
<div className="nav-align-top nav-tabs-shadow ">
|
||||
{/* Tabs */}
|
||||
<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-5">
|
||||
<div className="row align-items-center g-0 mb-3 mb-md-0 mx-2 mx-sm-5">
|
||||
{/* Tabs */}
|
||||
<div className="col-12 col-md">
|
||||
<ul className="nav nav-tabs" role="tablist">
|
||||
@ -174,7 +171,7 @@ const AttendancePage = () => {
|
||||
{/* 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">
|
||||
{/* Organization Dropdown */}
|
||||
<select
|
||||
{/* <select
|
||||
className="form-select form-select-sm"
|
||||
style={{ minWidth: "180px" }}
|
||||
value={appliedFilters.selectedOrganization}
|
||||
@ -192,7 +189,7 @@ const AttendancePage = () => {
|
||||
{org.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</select> */}
|
||||
|
||||
{/* Search Input */}
|
||||
<input
|
||||
@ -210,41 +207,36 @@ const AttendancePage = () => {
|
||||
</div>
|
||||
|
||||
<div className="tab-content attedanceTabs py-0 px-1 px-sm-3 pb-10">
|
||||
{selectedProject ? (
|
||||
<>
|
||||
{activeTab === "all" && (
|
||||
<div className="tab-pane fade show active py-0 mx-5">
|
||||
<Attendance
|
||||
handleModalData={handleModalData}
|
||||
getRole={getRole}
|
||||
searchTerm={searchTerm}
|
||||
organizationId={appliedFilters.selectedOrganization}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{activeTab === "logs" && (
|
||||
<div className="tab-pane fade show active py-0">
|
||||
<AttendanceLog
|
||||
handleModalData={handleModalData}
|
||||
searchTerm={searchTerm}
|
||||
organizationId={appliedFilters.selectedOrganization}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{activeTab === "regularization" && DoRegularized && (
|
||||
<div className="tab-pane fade show active py-0">
|
||||
<Regularization
|
||||
searchTerm={searchTerm}
|
||||
organizationId={appliedFilters.selectedOrganization}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<div className="py-2">
|
||||
<small>Please Select Project!</small>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<>
|
||||
{activeTab === "all" && (
|
||||
<div className="tab-pane fade show active py-0 mx-5">
|
||||
<Attendance
|
||||
handleModalData={handleModalData}
|
||||
getRole={getRole}
|
||||
searchTerm={searchTerm}
|
||||
organizationId={appliedFilters.selectedOrganization}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{activeTab === "logs" && (
|
||||
<div className="tab-pane fade show active py-0">
|
||||
<AttendanceLog
|
||||
handleModalData={handleModalData}
|
||||
searchTerm={searchTerm}
|
||||
organizationId={appliedFilters.selectedOrganization}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{activeTab === "regularization" && DoRegularized && (
|
||||
<div className="tab-pane fade show active py-0">
|
||||
<Regularization
|
||||
searchTerm={searchTerm}
|
||||
organizationId={appliedFilters.selectedOrganization}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
@ -9,18 +9,24 @@ import { defaultContactFilter } from "../../components/Directory/DirectorySchema
|
||||
import { useDebounce } from "../../utils/appUtils";
|
||||
import Pagination from "../../components/common/Pagination";
|
||||
import ListViewContact from "../../components/Directory/ListViewContact";
|
||||
import { CardViewContactSkeleton, ListViewContactSkeleton } from "../../components/Directory/DirectoryPageSkeleton";
|
||||
import {
|
||||
CardViewContactSkeleton,
|
||||
ListViewContactSkeleton,
|
||||
} from "../../components/Directory/DirectoryPageSkeleton";
|
||||
import Loader from "../../components/common/Loader";
|
||||
|
||||
// Utility function to format contacts for CSV export
|
||||
const formatExportData = (contacts) => {
|
||||
return contacts.map(contact => ({
|
||||
Email: contact.contactEmails?.map(e => e.emailAddress).join(", ") || "",
|
||||
Phone: contact.contactPhones?.map(p => p.phoneNumber).join(", ") || "",
|
||||
Created: contact.createdAt ? new Date(contact.createdAt).toLocaleString() : "",
|
||||
return contacts.map((contact) => ({
|
||||
Email: contact.contactEmails?.map((e) => e.emailAddress).join(", ") || "",
|
||||
Phone: contact.contactPhones?.map((p) => p.phoneNumber).join(", ") || "",
|
||||
Created: contact.createdAt
|
||||
? new Date(contact.createdAt).toLocaleString()
|
||||
: "",
|
||||
Location: contact.address || "",
|
||||
Organization: contact.organization || "",
|
||||
Category: contact.contactCategory?.name || "",
|
||||
Tags: contact.tags?.map(t => t.name).join(", ") || "",
|
||||
Tags: contact.tags?.map((t) => t.name).join(", ") || "",
|
||||
Buckets: contact.bucketIds?.join(", ") || "",
|
||||
}));
|
||||
};
|
||||
@ -75,8 +81,21 @@ const ContactsPage = ({ projectId, searchText, onExport }) => {
|
||||
<div className="row mt-5">
|
||||
{gridView ? (
|
||||
<>
|
||||
{isLoading && (
|
||||
<div>
|
||||
<Loader />
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
{data?.data?.length === 0 && (<div className="py-12 ">
|
||||
{searchText ? `No contact found for "${searchText}"`:"No contacts found" }
|
||||
</div>)}
|
||||
{data?.data?.map((contact) => (
|
||||
<div key={contact.id} className="col-12 col-sm-6 col-md-4 col-lg-4 mb-4">
|
||||
<div
|
||||
key={contact.id}
|
||||
className="col-12 col-sm-6 col-md-4 col-lg-4 mb-4"
|
||||
>
|
||||
<CardViewContact IsActive={showActive} contact={contact} />
|
||||
</div>
|
||||
))}
|
||||
@ -95,6 +114,7 @@ const ContactsPage = ({ projectId, searchText, onExport }) => {
|
||||
<div className="col-12">
|
||||
<ListViewContact
|
||||
data={data?.data}
|
||||
isLoading={isLoading}
|
||||
Pagination={
|
||||
<Pagination
|
||||
currentPage={currentPage}
|
||||
|
@ -19,9 +19,15 @@ import BucketList from "../../components/Directory/BucketList";
|
||||
import { MainDirectoryPageSkeleton } from "../../components/Directory/DirectoryPageSkeleton";
|
||||
import ContactProfile from "../../components/Directory/ContactProfile";
|
||||
import GlobalModel from "../../components/common/GlobalModel";
|
||||
import { exportToCSV } from "../../utils/exportUtils";
|
||||
import ConfirmModal from "../../components/common/ConfirmModal";
|
||||
import { useSelectedProject } from "../../slices/apiDataManager";
|
||||
import {
|
||||
exportToCSV,
|
||||
exportToExcel,
|
||||
exportToPDF,
|
||||
exportToPDF1,
|
||||
printTable,
|
||||
} from "../../utils/tableExportUtils";
|
||||
|
||||
const NotesPage = lazy(() => import("./NotesPage"));
|
||||
const ContactsPage = lazy(() => import("./ContactsPage"));
|
||||
@ -44,7 +50,7 @@ export default function DirectoryPage({ IsPage = true, projectId = null }) {
|
||||
const [searchNote, setSearchNote] = useState("");
|
||||
const [activeTab, setActiveTab] = useState("notes");
|
||||
const { setActions } = useFab();
|
||||
const [gridView, setGridView] = useState(false);
|
||||
const [gridView, setGridView] = useState(true);
|
||||
const [isOpenBucket, setOpenBucket] = useState(false);
|
||||
const [isManageContact, setManageContact] = useState({
|
||||
isOpen: false,
|
||||
@ -64,11 +70,49 @@ export default function DirectoryPage({ IsPage = true, projectId = null }) {
|
||||
const [ContactData, setContactData] = useState([]);
|
||||
|
||||
const handleExport = (type) => {
|
||||
if (activeTab === "notes" && type === "csv") {
|
||||
exportToCSV(notesData, "notes.csv");
|
||||
}
|
||||
if (activeTab === "contacts" && type === "csv") {
|
||||
exportToCSV(ContactData, "contact.csv");
|
||||
let exportData = activeTab === "notes" ? notesData : ContactData;
|
||||
if (!exportData?.length) return;
|
||||
|
||||
switch (type) {
|
||||
case "csv":
|
||||
exportToCSV(exportData, activeTab === "notes" ? "Notes" : "Contacts");
|
||||
break;
|
||||
case "excel":
|
||||
exportToExcel(exportData, activeTab === "notes" ? "Notes" : "Contacts");
|
||||
break;
|
||||
case "pdf":
|
||||
if (activeTab === "notes") {
|
||||
exportToPDF1(exportData, "Notes");
|
||||
} else {
|
||||
// Columns for Contacts PDF
|
||||
const columns = [
|
||||
"Email",
|
||||
"Phone",
|
||||
"Organization",
|
||||
"Category",
|
||||
"Tags",
|
||||
];
|
||||
|
||||
// Sanitize and trim long text to avoid PDF overflow
|
||||
const sanitizedData = exportData.map((item) => ({
|
||||
Email: (item.Email || "").slice(0, 40),
|
||||
Phone: (item.Phone || "").slice(0, 20),
|
||||
Organization: (item.Organization || "").slice(0, 30),
|
||||
Category: (item.Category || "").slice(0, 20),
|
||||
Tags: (item.Tags || "").slice(0, 40),
|
||||
}));
|
||||
|
||||
// Export with proper spacing
|
||||
exportToPDF(sanitizedData, "Contacts", columns, {
|
||||
columnWidths: [200, 120, 180, 120, 200], // Adjust widths per column
|
||||
fontSizeHeader: 12,
|
||||
fontSizeRow: 10,
|
||||
rowHeight: 25,
|
||||
});
|
||||
}
|
||||
break;
|
||||
default:
|
||||
console.warn("Unsupported export type");
|
||||
}
|
||||
};
|
||||
|
||||
@ -133,7 +177,7 @@ export default function DirectoryPage({ IsPage = true, projectId = null }) {
|
||||
]}
|
||||
></Breadcrumb>
|
||||
)}
|
||||
<div className="card">
|
||||
<div className="card ">
|
||||
<div className="d-flex-row px-2">
|
||||
<div className="d-flex justify-content-between align-items-center mb-1">
|
||||
<ul className="nav nav-tabs">
|
||||
@ -160,95 +204,152 @@ export default function DirectoryPage({ IsPage = true, projectId = null }) {
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div className="mb-1 px-2 py-3">
|
||||
<div className="d-flex align-items-center justify-content-between">
|
||||
<div className="d-flex align-items-center gap-3">
|
||||
{activeTab === "notes" && (
|
||||
<input
|
||||
type="search"
|
||||
className="form-control form-control-sm"
|
||||
placeholder="Search notes..."
|
||||
value={searchNote}
|
||||
onChange={(e) => setSearchNote(e.target.value)}
|
||||
/>
|
||||
)}
|
||||
<div className="mb-1 px-2 py-3">
|
||||
<div className="d-flex align-items-center justify-content-between">
|
||||
<div className="d-flex align-items-center gap-3">
|
||||
{activeTab === "notes" && (
|
||||
<input
|
||||
type="search"
|
||||
className="form-control form-control-sm"
|
||||
placeholder="Search notes..."
|
||||
value={searchNote}
|
||||
onChange={(e) => setSearchNote(e.target.value)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{activeTab === "contacts" && (
|
||||
<div className="d-flex align-items-center gap-3">
|
||||
<div className="d-flex gap-2 align-items-center">
|
||||
<input
|
||||
type="search"
|
||||
className="form-control form-control-sm"
|
||||
placeholder="Search contacts..."
|
||||
value={searchContact}
|
||||
onChange={(e) => setsearchContact(e.target.value)}
|
||||
/>
|
||||
{activeTab === "contacts" && (
|
||||
<div className="d-flex align-items-center gap-3">
|
||||
<div className="d-flex gap-2 align-items-center">
|
||||
<input
|
||||
type="search"
|
||||
className="form-control form-control-sm"
|
||||
placeholder="Search contacts..."
|
||||
value={searchContact}
|
||||
onChange={(e) => setsearchContact(e.target.value)}
|
||||
/>
|
||||
<div className="d-none d-md-flex gap-2">
|
||||
{" "}
|
||||
<button
|
||||
className={`btn btn-sm p-1 ${
|
||||
gridView
|
||||
? " btn-primary"
|
||||
: " btn-outline-primary"
|
||||
}`}
|
||||
onClick={() => setGridView(true)}
|
||||
>
|
||||
<i className="bx bx-grid-alt"></i>
|
||||
</button>
|
||||
<button
|
||||
className={`btn btn-sm p-1 ${
|
||||
!gridView
|
||||
? "btn-primary"
|
||||
: "btn-outline-primary"
|
||||
}`}
|
||||
onClick={() => setGridView(false)}
|
||||
>
|
||||
<i className="bx bx-list-ul"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="dropdown z-2">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-icon p-0 m-0"
|
||||
data-bs-toggle="dropdown"
|
||||
aria-expanded="false"
|
||||
title="More Actions"
|
||||
>
|
||||
<i className="bx bx-dots-vertical-rounded text-muted bx-md"></i>
|
||||
</button>
|
||||
|
||||
<ul className="dropdown-menu dropdown-menu-end shadow-sm ">
|
||||
{activeTab === "contacts" && (
|
||||
<li className="dropdown-item d-flex align-items-center">
|
||||
<div className="form-check form-switch mb-0">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="form-check-input"
|
||||
role="switch"
|
||||
id="inactiveContactsSwitch"
|
||||
checked={showActive}
|
||||
onChange={(e) =>
|
||||
setShowActive(e.target.checked)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<span>
|
||||
{showActive
|
||||
? "Active Contacts"
|
||||
: "Inactive Contacts"}
|
||||
</span>
|
||||
</li>
|
||||
)}
|
||||
<li>
|
||||
<button
|
||||
className={`btn btn-sm p-1 ${
|
||||
!gridView ? "btn-primary" : "btn-outline-primary"
|
||||
}`}
|
||||
onClick={() => setGridView(false)}
|
||||
className="dropdown-item d-flex align-items-center gap-2"
|
||||
onClick={() => handleExport("csv")}
|
||||
>
|
||||
<i className="bx bx-list-ul"></i>
|
||||
<i className="bx bx-file"></i>
|
||||
<span>Export to CSV</span>
|
||||
</button>
|
||||
|
||||
</li>
|
||||
<li>
|
||||
<button
|
||||
className={`btn btn-sm p-1 ${
|
||||
gridView ? " btn-primary" : " btn-outline-primary"
|
||||
className="dropdown-item d-flex align-items-center gap-2"
|
||||
onClick={() => handleExport("excel")}
|
||||
>
|
||||
<i className="bx bx-spreadsheet"></i>
|
||||
<span>Export to Excel</span>
|
||||
</button>
|
||||
</li>
|
||||
<li>
|
||||
<button
|
||||
className="dropdown-item d-flex align-items-center gap-2"
|
||||
onClick={() => handleExport("pdf")}
|
||||
>
|
||||
<i className="bx bxs-file-pdf"></i>
|
||||
<span>Export to PDF</span>
|
||||
</button>
|
||||
</li>
|
||||
<li className={`d-block d-md-none ${activeTab === "contacts" ? "d-block":"d-none"}`}>
|
||||
<span
|
||||
className={`dropdown-item ${
|
||||
gridView ? " text-primary" : ""
|
||||
}`}
|
||||
onClick={() => setGridView(true)}
|
||||
>
|
||||
<i className="bx bx-grid-alt"></i>
|
||||
</button>
|
||||
</div>
|
||||
<i className="bx bx-grid-alt"></i> Card View
|
||||
</span>
|
||||
</li>
|
||||
|
||||
<div className="form-check form-switch d-flex align-items-center">
|
||||
<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"
|
||||
<li className={` d-block d-md-none ${activeTab === "contacts" ? "d-block":"d-none"}`}>
|
||||
<span
|
||||
className={`dropdown-item ${
|
||||
!gridView ? "text-primary" : ""
|
||||
}`}
|
||||
onClick={() => setGridView(false)}
|
||||
>
|
||||
{showActive ? "Active" : "Inactive"} Contacts
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<i className="bx bx-list-ul"></i> List View
|
||||
</span>
|
||||
</li>
|
||||
|
||||
<div className="btn-group">
|
||||
<button
|
||||
className="btn btn-sm btn-label-secondary dropdown-toggle"
|
||||
type="button"
|
||||
data-bs-toggle="dropdown"
|
||||
aria-expanded="false"
|
||||
>
|
||||
<i className="bx bx-export me-2 bx-sm"></i>Export
|
||||
</button>
|
||||
<ul className="dropdown-menu">
|
||||
<li>
|
||||
<a
|
||||
className="dropdown-item cursor-pointer"
|
||||
onClick={() => handleExport("csv")}
|
||||
>
|
||||
<i className="bx bx-file me-1"></i> CSV
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
{/* Divider */}
|
||||
{activeTab === "contacts" && (
|
||||
<li>
|
||||
<hr className="dropdown-divider" />
|
||||
</li>
|
||||
)}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Suspense fallback={<MainDirectoryPageSkeleton />}>
|
||||
{activeTab === "notes" && (
|
||||
|
@ -60,12 +60,12 @@ const NoteFilterPanel = ({ onApply, clearFilter }) => {
|
||||
<div className="d-flex justify-content-end py-3 gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-label-secondary btn-xs"
|
||||
className="btn btn-label-secondary btn-sm"
|
||||
onClick={handleClose}
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
<button type="submit" className="btn btn-primary btn-xs">
|
||||
<button type="submit" className="btn btn-primary btn-sm">
|
||||
Apply
|
||||
</button>
|
||||
</div>
|
||||
|
@ -42,7 +42,7 @@ const NotesPage = ({ projectId, searchText, onExport }) => {
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 🔹 Format data for export
|
||||
// Format data for export
|
||||
const formatExportData = (notes) => {
|
||||
return notes.map((n) => ({
|
||||
ContactName: n.contactName || "",
|
||||
@ -59,7 +59,7 @@ const NotesPage = ({ projectId, searchText, onExport }) => {
|
||||
}));
|
||||
};
|
||||
|
||||
// 🔹 Pass formatted notes to parent for export
|
||||
// Pass formatted notes to parent for export
|
||||
useEffect(() => {
|
||||
if (data?.data && onExport) {
|
||||
onExport(formatExportData(data.data));
|
||||
|
@ -1,17 +1,16 @@
|
||||
import React, { createContext, useContext, useState, useEffect } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import React, { createContext, useContext, useState, useEffect, useRef } from "react";
|
||||
import { useForm, useFormContext } from "react-hook-form";
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useSelector } from "react-redux";
|
||||
|
||||
import ExpenseList from "../../components/Expenses/ExpenseList";
|
||||
import ViewExpense from "../../components/Expenses/ViewExpense";
|
||||
import Breadcrumb from "../../components/common/Breadcrumb";
|
||||
import GlobalModel from "../../components/common/GlobalModel";
|
||||
import PreviewDocument from "../../components/Expenses/PreviewDocument";
|
||||
import ExpenseList from "../../components/Expenses/ExpenseList";
|
||||
import ViewExpense from "../../components/Expenses/ViewExpense";
|
||||
import ManageExpense from "../../components/Expenses/ManageExpense";
|
||||
import ExpenseFilterPanel from "../../components/Expenses/ExpenseFilterPanel";
|
||||
import ExpenseFilterChips from "../../components/Expenses/ExpenseFilterChips";
|
||||
|
||||
// Context & Hooks
|
||||
import { useFab } from "../../Context/FabContext";
|
||||
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
|
||||
import {
|
||||
@ -20,11 +19,8 @@ import {
|
||||
VIEW_SELF_EXPENSE,
|
||||
} from "../../utils/constants";
|
||||
|
||||
// Schema & Defaults
|
||||
import {
|
||||
defaultFilter,
|
||||
SearchSchema,
|
||||
} from "../../components/Expenses/ExpenseSchema";
|
||||
import { defaultFilter, SearchSchema } from "../../components/Expenses/ExpenseSchema";
|
||||
import PreviewDocument from "../../components/Expenses/PreviewDocument";
|
||||
|
||||
// Context
|
||||
export const ExpenseContext = createContext();
|
||||
@ -41,10 +37,10 @@ const ExpensePage = () => {
|
||||
(store) => store.localVariables.projectId
|
||||
);
|
||||
|
||||
const [filters, setFilter] = useState();
|
||||
const [filters, setFilters] = useState(defaultFilter);
|
||||
const [groupBy, setGroupBy] = useState("transactionDate");
|
||||
const [searchText, setSearchText] = useState("");
|
||||
|
||||
const filterPanelRef = useRef();
|
||||
const [ManageExpenseModal, setManageExpenseModal] = useState({
|
||||
IsOpen: null,
|
||||
expenseId: null,
|
||||
@ -64,18 +60,31 @@ const ExpensePage = () => {
|
||||
const IsViewAll = useHasUserPermission(VIEW_ALL_EXPNESE);
|
||||
const IsViewSelf = useHasUserPermission(VIEW_SELF_EXPENSE);
|
||||
|
||||
|
||||
const { setOffcanvasContent, setShowTrigger } = useFab();
|
||||
|
||||
const methods = useForm({
|
||||
resolver: zodResolver(SearchSchema),
|
||||
defaultValues: defaultFilter,
|
||||
});
|
||||
|
||||
const { reset } = methods;
|
||||
|
||||
const clearFilter = () => {
|
||||
setFilter(defaultFilter);
|
||||
reset();
|
||||
const [filterData, setFilterdata] = useState(defaultFilter);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
const removeFilterChip = (key, id) => {
|
||||
setFilters((prev) => {
|
||||
const updated = { ...prev };
|
||||
if (Array.isArray(updated[key])) {
|
||||
updated[key] = updated[key].filter((v) => v !== id);
|
||||
filterPanelRef.current?.resetFieldValue(key, updated[key]);
|
||||
} else if (key === "dateRange") {
|
||||
updated.startDate = null;
|
||||
updated.endDate = null;
|
||||
filterPanelRef.current?.resetFieldValue("startDate", null);
|
||||
filterPanelRef.current?.resetFieldValue("endDate", null);
|
||||
}
|
||||
return updated;
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
@ -84,9 +93,10 @@ const ExpensePage = () => {
|
||||
setOffcanvasContent(
|
||||
"Expense Filters",
|
||||
<ExpenseFilterPanel
|
||||
onApply={setFilter}
|
||||
ref={filterPanelRef}
|
||||
onApply={setFilters}
|
||||
handleGroupBy={setGroupBy}
|
||||
clearFilter={clearFilter}
|
||||
setFilterdata={setFilterdata}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@ -101,6 +111,8 @@ const ExpensePage = () => {
|
||||
setViewExpense,
|
||||
setManageExpenseModal,
|
||||
setDocumentView,
|
||||
filterData,
|
||||
removeFilterChip
|
||||
};
|
||||
|
||||
return (
|
||||
@ -115,20 +127,18 @@ const ExpensePage = () => {
|
||||
<div className="card my-3 px-sm-4 px-0">
|
||||
<div className="card-body py-2 px-3">
|
||||
<div className="row align-items-center">
|
||||
<div className="col-6 ">
|
||||
<div className="d-flex align-items-center">
|
||||
<input
|
||||
type="search"
|
||||
className="form-control form-control-sm w-auto"
|
||||
placeholder="Search Expense"
|
||||
aria-describedby="search-label"
|
||||
value={searchText}
|
||||
onChange={(e) => setSearchText(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="col-6">
|
||||
<input
|
||||
type="search"
|
||||
className="form-control form-control-sm w-auto"
|
||||
placeholder="Search Expense"
|
||||
value={searchText}
|
||||
onChange={(e) => setSearchText(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="col-6 text-end mt-2 mt-sm-0">
|
||||
<div className="col-6 text-end mt-2 mt-sm-0">
|
||||
|
||||
{IsCreatedAble && (
|
||||
<button
|
||||
className="btn btn-sm btn-primary"
|
||||
@ -151,6 +161,8 @@ const ExpensePage = () => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<ExpenseList
|
||||
filters={filters}
|
||||
groupBy={groupBy}
|
||||
@ -161,7 +173,7 @@ const ExpensePage = () => {
|
||||
<div className="card text-center py-1">
|
||||
<i className="fa-solid fa-triangle-exclamation fs-5" />
|
||||
<p>
|
||||
Access Denied: You don't have permission to perform this action !
|
||||
Access Denied: You don't have permission to perform this action!
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
@ -5,37 +5,37 @@ const SwaperBlogContent = ({
|
||||
ContentAlign = "right",
|
||||
}) => {
|
||||
return (
|
||||
<div class="swiper-slide">
|
||||
<div class="card h-100">
|
||||
<div class="card-body text-body d-flex flex-column justify-content-between h-100">
|
||||
<div class="mb-4">
|
||||
<div className="swiper-slide">
|
||||
<div className="card h-100">
|
||||
<div className="card-body text-body d-flex flex-column justify-content-between h-100">
|
||||
<div className="mb-4">
|
||||
<img
|
||||
src={ImageUrl}
|
||||
alt="client logo"
|
||||
class="client-logo img-fluid"
|
||||
className="client-logo img-fluid"
|
||||
style={{ width: "580px", height: "100px" }}
|
||||
/>
|
||||
<h5>{Title}</h5>
|
||||
</div>
|
||||
<p>{Body}</p>
|
||||
<div class="text-warning mb-4">
|
||||
<i class="bx bxs-star"></i>
|
||||
<i class="bx bxs-star"></i>
|
||||
<i class="bx bxs-star"></i>
|
||||
<i class="bx bxs-star"></i>
|
||||
<i class="bx bxs-star"></i>
|
||||
<div className="text-warning mb-4">
|
||||
<i className="bx bxs-star"></i>
|
||||
<i className="bx bxs-star"></i>
|
||||
<i className="bx bxs-star"></i>
|
||||
<i className="bx bxs-star"></i>
|
||||
<i className="bx bxs-star"></i>
|
||||
</div>
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="avatar me-3 avatar-sm">
|
||||
<div className="d-flex align-items-center">
|
||||
<div className="avatar me-3 avatar-sm">
|
||||
<img
|
||||
src="../../assets/img/avatars/1.png"
|
||||
alt="Avatar"
|
||||
class="rounded-circle"
|
||||
className="rounded-circle"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<h6 class="mb-0">Cecilia Payne</h6>
|
||||
<p class="small text-muted mb-0">CEO of Airbnb</p>
|
||||
<h6 className="mb-0">Cecilia Payne</h6>
|
||||
<p className="small text-muted mb-0">CEO of Airbnb</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
@ -127,7 +127,7 @@ const TenantPage = () => {
|
||||
<div className="p-0">
|
||||
<div className="row align-items-center">
|
||||
{/* Search */}
|
||||
<div className="col-6 col-md-6 col-lg-2 mb-md-0">
|
||||
<div className="col-6 col-md-6 col-lg-3 mb-md-0">
|
||||
<input
|
||||
type="search"
|
||||
value={searchText}
|
||||
@ -138,7 +138,7 @@ const TenantPage = () => {
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="col-6 col-md-6 col-lg-10 text-end">
|
||||
<div className="col-6 col-md-6 col-lg-9 text-end">
|
||||
<button
|
||||
className="btn btn-sm btn-primary"
|
||||
type="button"
|
||||
|
@ -41,21 +41,24 @@ const LoginPage = () => {
|
||||
password: data.password,
|
||||
};
|
||||
const response = await AuthRepository.login(userCredential);
|
||||
if (data.rememberMe) {
|
||||
localStorage.setItem("jwtToken", response.data.token);
|
||||
localStorage.setItem("refreshToken", response.data.refreshToken);
|
||||
} else {
|
||||
sessionStorage.setItem("jwtToken", response.data.token);
|
||||
sessionStorage.setItem("refreshToken", response.data.refreshToken);
|
||||
}
|
||||
// if (data.rememberMe) {
|
||||
// localStorage.setItem("jwtToken", response.data.token);
|
||||
// localStorage.setItem("refreshToken", response.data.refreshToken);
|
||||
// } else {
|
||||
// sessionStorage.setItem("jwtToken", response.data.token);
|
||||
// sessionStorage.setItem("refreshToken", response.data.refreshToken);
|
||||
// }
|
||||
setLoading(false);
|
||||
navigate("/auth/switch/org");
|
||||
localStorage.setItem("jwtToken", response.data.token);
|
||||
localStorage.setItem("refreshToken", response.data.refreshToken);
|
||||
navigate("/dashboard",{ replace: true });
|
||||
} else {
|
||||
await AuthRepository.sendOTP({ email: data.username });
|
||||
showToast("OTP has been sent to your email.", "success");
|
||||
localStorage.setItem("otpUsername", data.username);
|
||||
localStorage.setItem("otpSentTime", now.toString());
|
||||
navigate("/auth/login-otp");
|
||||
// navigate("/auth/login-otp");
|
||||
navigate("/dashboard",{ replace: true });
|
||||
}
|
||||
} catch (err) {
|
||||
showToast("Invalid username or password.", "error");
|
||||
|
@ -36,31 +36,26 @@ import GlobalModel from "../../components/common/GlobalModel";
|
||||
import usePagination from "../../hooks/usePagination";
|
||||
import { setProjectId } from "../../slices/localVariablesSlice";
|
||||
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
|
||||
import Pagination from "../../components/common/Pagination";
|
||||
|
||||
const EmployeeList = () => {
|
||||
const selectedProjectId = useSelector(
|
||||
(store) => store.localVariables.projectId
|
||||
);
|
||||
const { projectNames, loading: projectLoading, fetchData } = useProjectName();
|
||||
// const selectedProjectId = useSelector(
|
||||
// (store) => store.localVariables.projectId
|
||||
// );
|
||||
// const { projectNames, loading: projectLoading, fetchData } = useProjectName();
|
||||
|
||||
const dispatch = useDispatch();
|
||||
|
||||
const [showInactive, setShowInactive] = useState(false);
|
||||
const [showAllEmployees, setShowAllEmployees] = useState(false);
|
||||
const [showAllEmployees, setShowAllEmployees] = useState(true);
|
||||
const Manage_Employee = useHasUserPermission(MANAGE_EMPLOYEES);
|
||||
|
||||
const { employees, loading, setLoading, error, recallEmployeeData } =
|
||||
useEmployeesAllOrByProjectId(
|
||||
showAllEmployees,
|
||||
selectedProjectId,
|
||||
showInactive
|
||||
);
|
||||
useEmployeesAllOrByProjectId(showAllEmployees, null, showInactive);
|
||||
|
||||
const [employeeList, setEmployeeList] = useState([]);
|
||||
const [modelConfig, setModelConfig] = useState();
|
||||
const [EmpForManageRole, setEmpForManageRole] = useState(null);
|
||||
// const [currentPage, setCurrentPage] = useState(1);
|
||||
// const [itemsPerPage] = useState(ITEMS_PER_PAGE);
|
||||
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
|
||||
const [searchText, setSearchText] = useState("");
|
||||
const [filteredData, setFilteredData] = useState([]);
|
||||
@ -78,11 +73,11 @@ const EmployeeList = () => {
|
||||
}
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedProjectId === null) {
|
||||
dispatch(setProjectId(projectNames[0]?.id));
|
||||
}
|
||||
}, [selectedProjectId]);
|
||||
// useEffect(() => {
|
||||
// if (selectedProjectId === null) {
|
||||
// dispatch(setProjectId(projectNames[0]?.id));
|
||||
// }
|
||||
// }, [selectedProjectId]);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const applySearchFilter = (data, text) => {
|
||||
@ -136,16 +131,53 @@ const EmployeeList = () => {
|
||||
const handleExport = (type) => {
|
||||
if (!currentItems || currentItems.length === 0) return;
|
||||
|
||||
// Map and format employee data for export
|
||||
const exportData = currentItems.map((item) => ({
|
||||
"First Name": item.firstName || "",
|
||||
"Middle Name": item.middleName || "",
|
||||
"Last Name": item.lastName || "",
|
||||
"Email": item.email || "",
|
||||
"Gender": item.gender || "",
|
||||
"Birth Date": item.birthdate
|
||||
? moment(item.birthdate).format("DD-MMM-YYYY")
|
||||
: "",
|
||||
"Joining Date": item.joiningDate
|
||||
? moment(item.joiningDate).format("DD-MMM-YYYY")
|
||||
: "",
|
||||
"Permanent Address": item.permanentAddress || "",
|
||||
"Current Address": item.currentAddress || "",
|
||||
"Phone Number": item.phoneNumber || "",
|
||||
"Emergency Phone Number": item.emergencyPhoneNumber || "",
|
||||
"Emergency Contact Person": item.emergencyContactPerson || "",
|
||||
"Is Active": item.isActive ? "Active" : "Inactive",
|
||||
"Job Role": item.jobRole || "",
|
||||
}));
|
||||
|
||||
switch (type) {
|
||||
case "csv":
|
||||
exportToCSV(currentItems, "employees");
|
||||
exportToCSV(exportData, "employees");
|
||||
break;
|
||||
case "excel":
|
||||
exportToExcel(currentItems, "employees");
|
||||
exportToExcel(exportData, "employees");
|
||||
break;
|
||||
case "pdf":
|
||||
exportToPDF(currentItems, "employees");
|
||||
exportToPDF(
|
||||
currentItems.map((item) => ({
|
||||
Name: `${item.firstName || ""} ${item.lastName || ""}`.trim(),
|
||||
Email: item.email || "",
|
||||
"Phone Number": item.phoneNumber || "",
|
||||
"Job Role": item.jobRole || "",
|
||||
"Joining Date": item.joiningDate
|
||||
? moment(item.joiningDate).format("DD-MMM-YYYY")
|
||||
: "",
|
||||
"Gender": item.gender || "",
|
||||
Status: item.isActive ? "Active" : "Inactive",
|
||||
})),
|
||||
"employees",
|
||||
["Name", "Email", "Phone Number", "Job Role", "Joining Date", "Gender", "Status"]
|
||||
);
|
||||
break;
|
||||
|
||||
case "print":
|
||||
printTable(tableRef.current);
|
||||
break;
|
||||
@ -176,12 +208,10 @@ const EmployeeList = () => {
|
||||
useEffect(() => {
|
||||
if (!loading && Array.isArray(employees)) {
|
||||
const sorted = [...employees].sort((a, b) => {
|
||||
const nameA = `${a.firstName || ""}${a.middleName || ""}${
|
||||
a.lastName || ""
|
||||
}`.toLowerCase();
|
||||
const nameB = `${b.firstName || ""}${b.middleName || ""}${
|
||||
b.lastName || ""
|
||||
}`.toLowerCase();
|
||||
const nameA = `${a.firstName || ""}${a.middleName || ""}${a.lastName || ""
|
||||
}`.toLowerCase();
|
||||
const nameB = `${b.firstName || ""}${b.middleName || ""}${b.lastName || ""
|
||||
}`.toLowerCase();
|
||||
return nameA?.localeCompare(nameB);
|
||||
});
|
||||
|
||||
@ -205,25 +235,16 @@ const EmployeeList = () => {
|
||||
|
||||
setCurrentPage((prevPage) => (prevPage !== 1 ? 1 : prevPage));
|
||||
}
|
||||
}, [loading, employees, selectedProjectId, showAllEmployees]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!showAllEmployees) {
|
||||
recallEmployeeData(showInactive, selectedProjectId);
|
||||
}
|
||||
}, [selectedProjectId, showInactive, showAllEmployees, recallEmployeeData]);
|
||||
}, [loading, employees, showAllEmployees]);
|
||||
|
||||
const handler = useCallback(
|
||||
(msg) => {
|
||||
if (employees.some((item) => item.id == msg.employeeId)) {
|
||||
setEmployeeList([]);
|
||||
recallEmployeeData(
|
||||
showInactive,
|
||||
showAllEmployees ? null : selectedProjectId
|
||||
); // Use selectedProjectId here
|
||||
recallEmployeeData(showInactive, null, showAllEmployees);
|
||||
}
|
||||
},
|
||||
[employees, showInactive, showAllEmployees, selectedProjectId] // Add all relevant dependencies
|
||||
[employees, showInactive, showAllEmployees]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
@ -268,9 +289,8 @@ const EmployeeList = () => {
|
||||
? "Suspend Employee"
|
||||
: "Reactivate Employee"
|
||||
}
|
||||
message={`Are you sure you want to ${
|
||||
selectedEmpFordelete?.isActive ? "suspend" : "reactivate"
|
||||
} this employee?`}
|
||||
message={`Are you sure you want to ${selectedEmpFordelete?.isActive ? "suspend" : "reactivate"
|
||||
} this employee?`}
|
||||
onSubmit={(id) =>
|
||||
suspendEmployee({
|
||||
employeeId: id,
|
||||
@ -293,18 +313,16 @@ const EmployeeList = () => {
|
||||
|
||||
{ViewTeamMember ? (
|
||||
// <div className="row">
|
||||
<div className="card p-1">
|
||||
<div className="card-datatable table-responsive pt-5 mx-5 py-10">
|
||||
<div
|
||||
id="DataTables_Table_0_wrapper"
|
||||
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">
|
||||
{/* Switches: All Employees + Inactive */}
|
||||
<div className="d-flex flex-wrap align-items-center gap-3">
|
||||
{/* All Employees Switch */}
|
||||
{ViewAllEmployee && (
|
||||
<div className="card page-min-h ">
|
||||
<div
|
||||
id="DataTables_Table_0_wrapper"
|
||||
className="dataTables_wrapper dt-bootstrap5 no-footer p-1 pt-5 mx-5 py-10"
|
||||
>
|
||||
<div className="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-3">
|
||||
{/* Switches: All Employees + Inactive */}
|
||||
<div className="d-flex flex-wrap align-items-center gap-3">
|
||||
{/* All Employees Switch */}
|
||||
{/* {ViewAllEmployee && (
|
||||
<div className="form-check form-switch text-start">
|
||||
<input
|
||||
type="checkbox"
|
||||
@ -321,112 +339,97 @@ const EmployeeList = () => {
|
||||
Show All Employees
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
)} */}
|
||||
|
||||
{/* Show Inactive Employees Switch */}
|
||||
{showAllEmployees && (
|
||||
<div className="form-check form-switch text-start">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="form-check-input"
|
||||
role="switch"
|
||||
id="inactiveEmployeesCheckbox"
|
||||
checked={showInactive}
|
||||
onChange={(e) => setShowInactive(e.target.checked)}
|
||||
/>
|
||||
<label
|
||||
className="form-check-label ms-0"
|
||||
htmlFor="inactiveEmployeesCheckbox"
|
||||
>
|
||||
Show Inactive Employees
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
{/* Show Inactive Employees Switch */}
|
||||
{/* {showAllEmployees && ( */}
|
||||
<div className="dataTables_filter">
|
||||
<label className="mb-0">
|
||||
<input
|
||||
type="search"
|
||||
value={searchText}
|
||||
onChange={handleSearch}
|
||||
className="form-control form-control-sm"
|
||||
placeholder="Search Employee"
|
||||
aria-controls="DataTables_Table_0"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{/* Right side: Search + Export + Add Employee */}
|
||||
<div className="d-flex flex-wrap align-items-center justify-content-end gap-3 flex-grow-1">
|
||||
{/* Search Input - ALWAYS ENABLED */}
|
||||
<div className="dataTables_filter">
|
||||
<label className="mb-0">
|
||||
<input
|
||||
type="search"
|
||||
value={searchText}
|
||||
onChange={handleSearch}
|
||||
className="form-control form-control-sm"
|
||||
placeholder="Search Employee"
|
||||
aria-controls="DataTables_Table_0"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
{/* )} */}
|
||||
</div>
|
||||
|
||||
{/* Export Dropdown */}
|
||||
<div className="dropdown">
|
||||
<button
|
||||
aria-label="Click me"
|
||||
className="btn btn-sm btn-label-secondary dropdown-toggle"
|
||||
type="button"
|
||||
data-bs-toggle="dropdown"
|
||||
aria-expanded="false"
|
||||
>
|
||||
<i className="bx bx-export me-2 bx-sm"></i>Export
|
||||
</button>
|
||||
<ul className="dropdown-menu">
|
||||
<li>
|
||||
<a
|
||||
className="dropdown-item"
|
||||
href="#"
|
||||
onClick={() => handleExport("print")}
|
||||
>
|
||||
<i className="bx bx-printer me-1"></i> Print
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a
|
||||
className="dropdown-item"
|
||||
href="#"
|
||||
onClick={() => handleExport("csv")}
|
||||
>
|
||||
<i className="bx bx-file me-1"></i> CSV
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a
|
||||
className="dropdown-item"
|
||||
href="#"
|
||||
onClick={() => handleExport("excel")}
|
||||
>
|
||||
<i className="bx bxs-file-export me-1"></i> Excel
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a
|
||||
className="dropdown-item"
|
||||
href="#"
|
||||
onClick={() => handleExport("pdf")}
|
||||
>
|
||||
<i className="bx bxs-file-pdf me-1"></i> PDF
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
{/* Right side: Search + Add Employee + Options */}
|
||||
<div className="d-flex flex-wrap align-items-center justify-content-end flex-grow-1">
|
||||
{/* Add Employee Button */}
|
||||
{Manage_Employee && (
|
||||
<button
|
||||
className="btn btn-sm btn-primary"
|
||||
type="button"
|
||||
onClick={() => handleEmployeeModel(null)}
|
||||
>
|
||||
<i className="bx bx-plus-circle me-2"></i>
|
||||
<span className="d-none d-md-inline-block">
|
||||
Add New Employee
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Add Employee Button */}
|
||||
{Manage_Employee && (
|
||||
<button
|
||||
className="btn btn-sm btn-primary"
|
||||
type="button"
|
||||
onClick={() => handleEmployeeModel(null)}
|
||||
>
|
||||
<i className="bx bx-plus-circle me-2"></i>
|
||||
<span className="d-none d-md-inline-block">
|
||||
Add New Employee
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
{/* 3-Dots Dropdown (New Combined Menu) */}
|
||||
<div className="dropdown">
|
||||
<button
|
||||
className="btn btn-icon me-1"
|
||||
type="button"
|
||||
data-bs-toggle="dropdown"
|
||||
aria-expanded="false"
|
||||
>
|
||||
<i className="bx bx-dots-vertical-rounded bx-md"></i>
|
||||
</button>
|
||||
<ul className="dropdown-menu dropdown-menu-end shadow-sm " style={{ minWidth: "220px" }}>
|
||||
|
||||
<li className="dropdown-item d-flex align-items-center justify-content-between">
|
||||
<div className="form-check form-switch mb-0">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="form-check-input"
|
||||
role="switch"
|
||||
id="inactiveEmployeesCheckboxMenu"
|
||||
checked={showInactive}
|
||||
onChange={(e) => setShowInactive(e.target.checked)}
|
||||
/>
|
||||
</div>
|
||||
<span className="ms-0">Show Inactive Employees</span>
|
||||
</li>
|
||||
|
||||
|
||||
<li><hr className="dropdown-divider" /></li>
|
||||
|
||||
<li>
|
||||
<button className="dropdown-item" onClick={() => handleExport("print")}>
|
||||
<i className="bx bx-printer me-2"></i> Print
|
||||
</button>
|
||||
</li>
|
||||
<li>
|
||||
<button className="dropdown-item" onClick={() => handleExport("csv")}>
|
||||
<i className="bx bx-file me-2"></i> CSV
|
||||
</button>
|
||||
</li>
|
||||
<li>
|
||||
<button className="dropdown-item" onClick={() => handleExport("excel")}>
|
||||
<i className="bx bxs-file-export me-2"></i> Excel
|
||||
</button>
|
||||
</li>
|
||||
<li>
|
||||
<button className="dropdown-item" onClick={() => handleExport("pdf")}>
|
||||
<i className="bx bxs-file-pdf me-2"></i> PDF
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div className="table-responsive text-nowrap">
|
||||
<table
|
||||
className="datatables-users table border-top dataTable no-footer dtr-column text-nowrap"
|
||||
id="DataTables_Table_0"
|
||||
@ -502,9 +505,8 @@ const EmployeeList = () => {
|
||||
Status
|
||||
</th>
|
||||
<th
|
||||
className={`sorting_disabled ${
|
||||
!Manage_Employee && "d-none"
|
||||
}`}
|
||||
className={`sorting_disabled ${!Manage_Employee && "d-none"
|
||||
}`}
|
||||
rowSpan="1"
|
||||
colSpan="1"
|
||||
style={{ width: "50px" }}
|
||||
@ -524,26 +526,24 @@ const EmployeeList = () => {
|
||||
)}
|
||||
{/* Conditional messages for no data or no search results */}
|
||||
{!loading &&
|
||||
displayData?.length === 0 &&
|
||||
searchText &&
|
||||
!showAllEmployees ? (
|
||||
displayData?.length === 0 &&
|
||||
searchText ? (
|
||||
<tr>
|
||||
<td colSpan={8}>
|
||||
<small className="muted">
|
||||
'{searchText}' employee not found
|
||||
</small>{" "}
|
||||
<td colSpan={8} className="border-0">
|
||||
<div className="py-12">
|
||||
<small className="muted">
|
||||
'{searchText}' employee not found
|
||||
</small>{" "}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
) : null}
|
||||
{!loading &&
|
||||
displayData?.length === 0 &&
|
||||
(!searchText || showAllEmployees) ? (
|
||||
displayData?.length === 0 &&
|
||||
(!searchText) ? (
|
||||
<tr>
|
||||
<td
|
||||
colSpan={8}
|
||||
style={{ paddingTop: "20px", textAlign: "center" }}
|
||||
>
|
||||
No Data Found
|
||||
<td colSpan={8} className="border-0">
|
||||
<div className="py-12">{showInactive ? "No In-active Employeee Found" : "No Employeee Found"}</div>
|
||||
</td>
|
||||
</tr>
|
||||
) : null}
|
||||
@ -561,9 +561,7 @@ const EmployeeList = () => {
|
||||
></Avatar>
|
||||
<div className="d-flex flex-column">
|
||||
<a
|
||||
onClick={() =>
|
||||
navigate(`/employee/${item.id}`)
|
||||
}
|
||||
onClick={() => navigate(`/employee/${item.id}`)}
|
||||
className="text-heading text-truncate cursor-pointer"
|
||||
>
|
||||
<span className="fw-normal">
|
||||
@ -581,9 +579,7 @@ const EmployeeList = () => {
|
||||
{item.email}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-truncate text-italic">
|
||||
-
|
||||
</span>
|
||||
<span className="text-truncate text-italic">-</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="text-start d-none d-sm-table-cell">
|
||||
@ -599,9 +595,10 @@ const EmployeeList = () => {
|
||||
</span>
|
||||
</td>
|
||||
|
||||
<td className=" d-none d-md-table-cell">
|
||||
{moment(item.joiningDate)?.format("DD-MMM-YYYY")}
|
||||
<td className="d-none d-md-table-cell">
|
||||
{item.joiningDate ? moment(item.joiningDate).format("DD-MMM-YYYY") : "NA"}
|
||||
</td>
|
||||
|
||||
<td>
|
||||
{showInactive ? (
|
||||
<span
|
||||
@ -648,8 +645,7 @@ const EmployeeList = () => {
|
||||
handleEmployeeModel(item.id)
|
||||
}
|
||||
>
|
||||
<i className="bx bx-edit bx-sm"></i>{" "}
|
||||
Edit
|
||||
<i className="bx bx-edit bx-sm"></i> Edit
|
||||
</button>
|
||||
|
||||
{/* Suspend only when active */}
|
||||
@ -672,8 +668,8 @@ const EmployeeList = () => {
|
||||
setEmpForManageRole(item.id)
|
||||
}
|
||||
>
|
||||
<i className="bx bx-cog bx-sm"></i>{" "}
|
||||
Manage Role
|
||||
<i className="bx bx-cog bx-sm"></i> Manage
|
||||
Role
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
@ -696,58 +692,17 @@ const EmployeeList = () => {
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<div style={{ width: "1%" }}></div>
|
||||
|
||||
{/* Pagination */}
|
||||
{!loading && displayData.length > ITEMS_PER_PAGE && (
|
||||
<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)}
|
||||
>
|
||||
«
|
||||
</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)}
|
||||
>
|
||||
»
|
||||
</button>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
)}
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
{displayData.length > 0 && (
|
||||
<Pagination
|
||||
currentPage={currentPage}
|
||||
totalPages={totalPages}
|
||||
onPageChange={paginate}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
|
@ -161,8 +161,8 @@ const MasterPage = () => {
|
||||
data={[{ label: "Home", link: "/dashboard" }, { label: "Masters" }]}
|
||||
/>
|
||||
|
||||
<div className="row">
|
||||
<div className="card">
|
||||
|
||||
<div className="card page-min-h">
|
||||
<div
|
||||
className="card-datatable table-responsive py-10 mx-5 "
|
||||
style={{ overflow: "hidden" }}
|
||||
@ -221,7 +221,6 @@ const MasterPage = () => {
|
||||
handleModalData={handleModalData}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</MasterContext.Provider>
|
||||
|
@ -109,11 +109,11 @@ const MasterTable = ({ data, columns, loading, handleModalData }) => {
|
||||
{currentItems.length > 0 ? (
|
||||
currentItems.map((item, index) => (
|
||||
<tr key={index}>
|
||||
<td style={{ width: "20px" }}>
|
||||
<i className="bx bx-right-arrow-alt"></i>
|
||||
<td style={{ width: "20px", }} className="py-5">
|
||||
<div className="py-2 px-3"><i className="bx bx-right-arrow-alt"></i></div>
|
||||
</td>
|
||||
{updatedColumns.map((col) => (
|
||||
<td className="text-start mx-2" key={col.key}>
|
||||
<td className="text-start mx-2 p-3" key={col.key} style={{ padding: "12px 16px" }} >
|
||||
{col.key === "description" ? (
|
||||
item[col.key] !== undefined &&
|
||||
item[col.key] !== null ? (
|
||||
|
@ -15,12 +15,12 @@ import { useProjectDetails, useProjectName } from "../../hooks/useProjects";
|
||||
import { ComingSoonPage } from "../Misc/ComingSoonPage";
|
||||
import eventBus from "../../services/eventBus";
|
||||
import ProjectProgressChart from "../../components/Dashboard/ProjectProgressChart";
|
||||
import AttendanceOverview from "../../components/Dashboard/AttendanceChart";
|
||||
import AttendanceOverview from "../../components/Dashboard/AttendanceOverview";
|
||||
import { setProjectId } from "../../slices/localVariablesSlice";
|
||||
import ProjectDocuments from "../../components/Project/ProjectDocuments";
|
||||
import ProjectSetting from "../../components/Project/ProjectSetting";
|
||||
import DirectoryPage from "../Directory/DirectoryPage";
|
||||
import { useProjectAccess } from "../../hooks/useProjectAccess";
|
||||
import { useProjectAccess } from "../../hooks/useProjectAccess";
|
||||
|
||||
import "./ProjectDetails.css";
|
||||
import ProjectOrganizations from "../../components/Project/ProjectOrganizations";
|
||||
@ -30,10 +30,13 @@ const ProjectDetails = () => {
|
||||
const dispatch = useDispatch();
|
||||
|
||||
const { projectNames } = useProjectName();
|
||||
const { projects_Details, loading: projectLoading, refetch } =
|
||||
useProjectDetails(projectId);
|
||||
const {
|
||||
projects_Details,
|
||||
loading: projectLoading,
|
||||
refetch,
|
||||
} = useProjectDetails(projectId);
|
||||
|
||||
const { canView, loading: permsLoading } = useProjectAccess(projectId);
|
||||
// const { canView, loading: permsLoading } = useProjectAccess(projectId);
|
||||
|
||||
useEffect(() => {
|
||||
if (!projectId && projectNames.length > 0) {
|
||||
@ -47,7 +50,10 @@ const ProjectDetails = () => {
|
||||
|
||||
const handler = useCallback(
|
||||
(msg) => {
|
||||
if (msg.keyword === "Update_Project" && projects_Details?.id === msg.response.id) {
|
||||
if (
|
||||
msg.keyword === "Update_Project" &&
|
||||
projects_Details?.id === msg.response.id
|
||||
) {
|
||||
refetch();
|
||||
}
|
||||
},
|
||||
@ -64,7 +70,7 @@ const ProjectDetails = () => {
|
||||
localStorage.setItem("lastActiveProjectTab", pillKey);
|
||||
};
|
||||
|
||||
if (projectLoading || permsLoading || !projects_Details) {
|
||||
if (projectLoading || !projects_Details) {
|
||||
return <Loader />;
|
||||
}
|
||||
|
||||
@ -75,13 +81,10 @@ const ProjectDetails = () => {
|
||||
<div className="row">
|
||||
<div className="col-lg-4 col-md-5 mt-2">
|
||||
<AboutProject />
|
||||
<ProjectOverview project={projectId} />
|
||||
{/* <ProjectOverview project={projectId} /> */}
|
||||
</div>
|
||||
<div className="col-lg-8 col-md-7 mt-5">
|
||||
<ProjectProgressChart ShowAllProject="false" DefaultRange="1M" />
|
||||
<div className="mt-5">
|
||||
<AttendanceOverview />
|
||||
</div>
|
||||
<div className="col-lg-8 col-md-7 mt-2">
|
||||
<AttendanceOverview />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
@ -1,6 +1,10 @@
|
||||
import React, { createContext, useContext, useEffect, useState } from "react";
|
||||
import Breadcrumb from "../../components/common/Breadcrumb";
|
||||
import { ITEMS_PER_PAGE, MANAGE_PROJECT, PROJECT_STATUS } from "../../utils/constants";
|
||||
import {
|
||||
ITEMS_PER_PAGE,
|
||||
MANAGE_PROJECT,
|
||||
PROJECT_STATUS,
|
||||
} from "../../utils/constants";
|
||||
import ProjectListView from "../../components/Project/ProjectListView";
|
||||
import GlobalModel from "../../components/common/GlobalModel";
|
||||
import ManageProjectInfo from "../../components/Project/ManageProjectInfo";
|
||||
@ -95,9 +99,18 @@ const ProjectPage = () => {
|
||||
}
|
||||
}, [data, isLoading, selectedStatuses]);
|
||||
|
||||
|
||||
if(isLoading) return <div className="page-min-h"><Loader/></div>
|
||||
if(isError) return <div className="page-min-h d-flex justify-content-center align-items-center"><p>{error.message}</p></div>
|
||||
if (isLoading)
|
||||
return (
|
||||
<div className="page-min-h">
|
||||
<Loader />
|
||||
</div>
|
||||
);
|
||||
if (isError)
|
||||
return (
|
||||
<div className="page-min-h d-flex justify-content-center align-items-center">
|
||||
<p>{error.message}</p>
|
||||
</div>
|
||||
);
|
||||
return (
|
||||
<ProjectContext.Provider value={contextDispatcher}>
|
||||
<div className="container-fluid">
|
||||
@ -181,7 +194,8 @@ const ProjectPage = () => {
|
||||
</div>
|
||||
|
||||
<div>
|
||||
{HasManageProject && ( <button
|
||||
{/* {HasManageProject && ( */}
|
||||
<button
|
||||
className="btn btn-sm btn-primary"
|
||||
type="button"
|
||||
onClick={() =>
|
||||
@ -192,7 +206,8 @@ const ProjectPage = () => {
|
||||
<span className="d-none d-md-inline-block">
|
||||
Add New Project
|
||||
</span>
|
||||
</button>)}
|
||||
</button>
|
||||
{/* )} */}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@ -209,7 +224,11 @@ const ProjectPage = () => {
|
||||
isLoading={isLoading}
|
||||
/>
|
||||
) : (
|
||||
<ProjectCardView currentItems={currentItems} setCurrentPage={setCurrentPage} totalPages={totalPages} />
|
||||
<ProjectCardView
|
||||
currentItems={currentItems}
|
||||
setCurrentPage={setCurrentPage}
|
||||
totalPages={totalPages}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* ------------------ */}
|
||||
|
@ -2,51 +2,58 @@ import { api } from "../utils/axiosClient";
|
||||
|
||||
const AttendanceRepository = {
|
||||
markAttendance: (data) => api.post("/api/attendance/record", data),
|
||||
|
||||
getAttendance: (projectId, organizationId, includeInactive,date) => {
|
||||
let url = `/api/attendance/project/team?projectId=${projectId}`;
|
||||
|
||||
getAttendance: (projectId, organizationId, includeInactive, date) => {
|
||||
let url = `/api/attendance/project/team`;
|
||||
|
||||
const params = [];
|
||||
if (projectId) params.push(`projectId=${projectId}`);
|
||||
if (organizationId) params.push(`organizationId=${organizationId}`);
|
||||
if (includeInactive) params.push(`includeInactive=${includeInactive}`);
|
||||
if (date) params.push(`date=${date}`);
|
||||
|
||||
if (params.length > 0) {
|
||||
url += `&${params.join("&")}`; }
|
||||
url += `?${params.join("&")}`;
|
||||
}
|
||||
|
||||
return api.get(url);
|
||||
},
|
||||
|
||||
getAttendanceFilteredByDate: (projectId, fromDate, toDate,organizationId) => {
|
||||
let url = `api/Attendance/project/log?projectId=${projectId}`;
|
||||
if (fromDate) {
|
||||
url += `&dateFrom=${fromDate}`;
|
||||
getAttendanceFilteredByDate: (projectId, fromDate, toDate, organizationId) => {
|
||||
let url = `api/attendance/project/log`;
|
||||
|
||||
const params = [];
|
||||
if (projectId) params.push(`projectId=${projectId}`);
|
||||
if (fromDate) params.push(`dateFrom=${fromDate}`);
|
||||
if (toDate) params.push(`dateTo=${toDate}`);
|
||||
if (organizationId) params.push(`organizationId=${organizationId}`);
|
||||
|
||||
if (params.length > 0) {
|
||||
url += `?${params.join("&")}`;
|
||||
}
|
||||
|
||||
if (toDate) {
|
||||
url += `&dateTo=${toDate}`;
|
||||
}
|
||||
if (organizationId) {
|
||||
url += `&organizationId=${organizationId}`;
|
||||
}
|
||||
return api.get(url);
|
||||
},
|
||||
|
||||
|
||||
getAttendanceLogs: (id) => api.get(`api/attendance/log/attendance/${id}`),
|
||||
|
||||
getRegularizeList: (projectId, organizationId, IncludeInActive) => {
|
||||
let url = `/api/attendance/regularize?projectId=${projectId}`;
|
||||
getRegularizeList: (projectId, organizationId, IncludeInActive) => {
|
||||
let url = `/api/attendance/regularize`;
|
||||
|
||||
const params = [];
|
||||
if (projectId) params.push(`projectId=${projectId}`);
|
||||
if (organizationId) params.push(`organizationId=${organizationId}`);
|
||||
if (IncludeInActive) params.push(`IncludeInActive=${IncludeInActive}`);
|
||||
|
||||
if (params.length > 0) {
|
||||
url += `&${params.join("&")}`; }
|
||||
url += `?${params.join("&")}`;
|
||||
}
|
||||
|
||||
return api.get(url);
|
||||
},
|
||||
|
||||
|
||||
getAttendanceByEmployee: (employeeId, fromDate, toDate) => {
|
||||
let url = `api/Attendance/log/employee/${employeeId}?`;
|
||||
if (fromDate) {
|
||||
|
@ -2,12 +2,12 @@ import { api } from "../utils/axiosClient";
|
||||
|
||||
const AuthRepository = {
|
||||
// Public routes (no auth token required)
|
||||
login: (data) => api.postPublic("/api/auth/login", data),
|
||||
login: (data) => api.postPublic("/api/auth/login/v1", data),
|
||||
refreshToken: (data) => api.postPublic("/api/auth/refresh-token", data),
|
||||
forgotPassword: (data) => api.postPublic("/api/auth/forgot-password", data),
|
||||
resetPassword: (data) => api.postPublic("/api/auth/reset-password", data),
|
||||
sendOTP: (data) => api.postPublic("/api/auth/send-otp", data),
|
||||
verifyOTP: (data) => api.postPublic("/api/auth/login-otp", data),
|
||||
verifyOTP: (data) => api.postPublic("/api/auth/login-otp/v1", data),
|
||||
register: (data) => api.postPublic("/api/auth/register", data),
|
||||
sendMail: (data) => api.postPublic("/api/auth/sendmail", data),
|
||||
|
||||
|
@ -10,16 +10,17 @@ const EmployeeRepository = {
|
||||
updateEmployee: (id, data) => api.put(`/users/${id}`, data),
|
||||
// deleteEmployee: ( id ) => api.delete( `/users/${ id }` ),
|
||||
getEmployeeProfile: (id) => api.get(`/api/employee/profile/get/${id}`),
|
||||
deleteEmployee: (id,active) => api.delete(`/api/employee/${id}?active=${active}`),
|
||||
getEmployeeName: (projectId, search) => {
|
||||
const params = new URLSearchParams();
|
||||
deleteEmployee: (id, active) => api.delete(`/api/employee/${id}?active=${active}`),
|
||||
getEmployeeName: (projectId, search, allEmployee) => {
|
||||
const params = new URLSearchParams();
|
||||
|
||||
if (projectId) params.append("projectId", projectId);
|
||||
if (search) params.append("searchString", search);
|
||||
if (projectId) params.append("projectId", projectId);
|
||||
if (search) params.append("searchString", search);
|
||||
if (allEmployee) params.append("sendAll", allEmployee)
|
||||
|
||||
const query = params.toString();
|
||||
return api.get(`/api/Employee/basic${query ? `?${query}` : ""}`);
|
||||
}
|
||||
const query = params.toString();
|
||||
return api.get(`/api/Employee/basic${query ? `?${query}` : ""}`);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
|
@ -41,7 +41,56 @@ const GlobalRepository = {
|
||||
return api.get(url);
|
||||
},
|
||||
|
||||
getAttendanceOverview:(projectId,days)=>api.get(`/api/dashboard/attendance-overview/${projectId}?days=${days}`)
|
||||
getAttendanceOverview:(projectId,days)=>api.get(`/api/dashboard/attendance-overview/${projectId}?days=${days}`),
|
||||
|
||||
|
||||
getExpenseData: (projectId, startDate, endDate) => {
|
||||
let url = `api/Dashboard/expense/type`
|
||||
|
||||
const queryParams = [];
|
||||
|
||||
if (projectId) {
|
||||
queryParams.push(`projectId=${projectId}`);
|
||||
}
|
||||
|
||||
if (startDate) {
|
||||
queryParams.push(`startDate=${startDate}`);
|
||||
}
|
||||
if (endDate) {
|
||||
queryParams.push(`endDate=${endDate}`);
|
||||
}
|
||||
|
||||
if (queryParams.length > 0) {
|
||||
url += `?${queryParams.join("&")}`;
|
||||
}
|
||||
|
||||
return api.get(url );
|
||||
},
|
||||
|
||||
getExpenseStatus:(projectId)=>api.get(`/api/Dashboard/expense/pendings${projectId ? `?projectId=${projectId}`:""}`),
|
||||
|
||||
getExpenseDataByProject: (projectId, categoryId, months) => {
|
||||
let url = `api/Dashboard/expense/monthly`
|
||||
|
||||
const queryParams = [];
|
||||
|
||||
if (projectId) {
|
||||
queryParams.push(`projectId=${projectId}`);
|
||||
}
|
||||
|
||||
if (categoryId) {
|
||||
queryParams.push(`categoryId=${categoryId}`);
|
||||
}
|
||||
if (months) {
|
||||
queryParams.push(`months=${months}`);
|
||||
}
|
||||
|
||||
if (queryParams.length > 0) {
|
||||
url += `?${queryParams.join("&")}`;
|
||||
}
|
||||
|
||||
return api.get(url);
|
||||
},
|
||||
|
||||
};
|
||||
|
||||
|
@ -94,7 +94,7 @@ const router = createBrowserRouter(
|
||||
{ path: "/activities/task", element: <TaskPlannng /> },
|
||||
{ path: "/activities/reports", element: <Reports /> },
|
||||
{ path: "/gallary", element: <ComingSoonPage /> },
|
||||
{ path: "/expenses", element: <ExpensePage /> },
|
||||
{ path: "/expenses/:status?/:project?", element: <ExpensePage /> },
|
||||
{ path: "/masters", element: <MasterPage /> },
|
||||
{ path: "/tenants", element: <TenantPage /> },
|
||||
{ path: "/tenants/new-tenant", element: <CreateTenant /> },
|
||||
|
@ -59,7 +59,7 @@ const attemptTokenRefresh = async (storedRefreshToken) => {
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Token refresh failed:", error);
|
||||
removeSession()
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
@ -22,7 +22,7 @@ export function startSignalR(loggedUser) {
|
||||
accessTokenFactory: () => jwtToken,
|
||||
transport: signalR.HttpTransportType.LongPolling,
|
||||
withCredentials: false,
|
||||
})
|
||||
})
|
||||
.withAutomaticReconnect()
|
||||
.build();
|
||||
const todayDate = new Date();
|
||||
@ -32,100 +32,104 @@ export function startSignalR(loggedUser) {
|
||||
.toISOString()
|
||||
.split("T")[0];
|
||||
connection.on("NotificationEventHandler", (data) => {
|
||||
if (data.loggedInUserId != loggedUser?.employeeInfo.id) {
|
||||
// console.log("Notification received:", data);
|
||||
// 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));
|
||||
const { loggedInUserId, keyword, response, employeeList, numberOfImages } = data;
|
||||
const loggedInId = loggedUser?.employeeInfo?.id;
|
||||
|
||||
var afterTwoDay =
|
||||
checkIn.substring(0, 8) + (onlyDate + 2).toString().padStart(2, "0");
|
||||
if (
|
||||
afterTwoDay <= today &&
|
||||
(data.response.activity == 4 || data.response.activity == 5)
|
||||
) {
|
||||
eventBus.emit("regularization", data);
|
||||
}
|
||||
eventBus.emit("attendance_log", data);
|
||||
}
|
||||
if(data.keyword == "Expanse"){
|
||||
queryClient.invalidateQueries({queryKey:["Expenses"]})
|
||||
}
|
||||
// if create or update project
|
||||
if (
|
||||
data.keyword == "Create_Project" ||
|
||||
data.keyword == "Update_Project"
|
||||
) {
|
||||
// clearCacheKey("projectslist");
|
||||
queryClient.invalidateQueries(['projectslist']);
|
||||
eventBus.emit("project", data);
|
||||
}
|
||||
if (loggedInUserId === loggedInId) return;
|
||||
|
||||
// if assign or deassign employee to any project
|
||||
if (data.keyword == "Assign_Project") {
|
||||
if (
|
||||
data.employeeList.some((item) => item === loggedUser?.employeeInfo.id)
|
||||
) {
|
||||
try {
|
||||
cacheData("hasReceived", false);
|
||||
eventBus.emit("assign_project_one", data);
|
||||
} catch (e) {
|
||||
// console.error("Error in cacheData:", e);
|
||||
}
|
||||
}
|
||||
eventBus.emit("assign_project_all", data);
|
||||
}
|
||||
// if created or updated infra
|
||||
if (data.keyword == "Infra") {
|
||||
queryClient.removeQueries({queryKey:["ProjectInfra"]})
|
||||
// eventBus.emit("infra", data);
|
||||
}
|
||||
if (data.keyword == "Task_Report") {
|
||||
queryClient.removeQueries({queryKey:["Infra"]})
|
||||
// eventBus.emit("infra", data);
|
||||
}
|
||||
|
||||
if ( data.keyword == "WorkItem" )
|
||||
{
|
||||
queryClient.removeQueries({queryKey:["WorkItems"]})
|
||||
}
|
||||
|
||||
// if created or updated Employee
|
||||
if (data.keyword == "Employee") {
|
||||
// clearCacheKey("employeeListByProject");
|
||||
// clearCacheKey("allEmployeeList");
|
||||
// clearCacheKey("allInactiveEmployeeList");
|
||||
// clearCacheKey("employeeProfile");
|
||||
clearCacheKey("Attendance");
|
||||
clearCacheKey("regularizedList")
|
||||
clearCacheKey("AttendanceLogs")
|
||||
|
||||
// ---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);
|
||||
}
|
||||
|
||||
if (data.keyword == "Task_Report") {
|
||||
if(data.numberOfImages > 0){
|
||||
eventBus.emit("image_gallery", data);
|
||||
}
|
||||
}
|
||||
if (data.keyword == "Task_Comment") {
|
||||
if(data.numberOfImages > 0){
|
||||
eventBus.emit("image_gallery", data);
|
||||
}
|
||||
}
|
||||
// ---- Handlers for invalidate or remove ----
|
||||
const queryInvalidators = {
|
||||
Expanse: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["Expenses"] }),
|
||||
queryClient.invalidateQueries({ queryKey: ["Expense"] })
|
||||
},
|
||||
Create_Project: () => queryClient.invalidateQueries(["projectslist"]),
|
||||
Update_Project: () => queryClient.invalidateQueries(["projectslist"]),
|
||||
Infra: () => queryClient.removeQueries({ queryKey: ["ProjectInfra"] }),
|
||||
Task_Report: () => queryClient.invalidateQueries({ queryKey: ["Infra"] }),
|
||||
WorkItem: () => queryClient.invalidateQueries({ queryKey: ["WorkItems"] }),
|
||||
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 (
|
||||
afterTwoDay <= today &&
|
||||
(response.activity === 4 || response.activity === 5)
|
||||
) {
|
||||
eventBus.emit("regularization", data);
|
||||
}
|
||||
eventBus.emit("attendance_log", data);
|
||||
}
|
||||
|
||||
// ---- Invalidate/Remove cache by keywords ----
|
||||
if (queryInvalidators[keyword]) {
|
||||
queryInvalidators[keyword]();
|
||||
}
|
||||
|
||||
// ---- Project creation/update ----
|
||||
if (keyword === "Create_Project" || keyword === "Update_Project") {
|
||||
emitters.project();
|
||||
}
|
||||
|
||||
// ---- Assign/deassign project ----
|
||||
if (keyword === "Assign_Project") {
|
||||
if (employeeList?.includes(loggedInId)) {
|
||||
try {
|
||||
cacheData("hasReceived", false);
|
||||
eventBus.emit("assign_project_one", data);
|
||||
} catch {}
|
||||
}
|
||||
emitters.assign_project_all();
|
||||
}
|
||||
|
||||
// ---- Employee update ----
|
||||
if (keyword === "Employee") {
|
||||
clearCacheKey("Attendance");
|
||||
clearCacheKey("regularizedList");
|
||||
clearCacheKey("AttendanceLogs");
|
||||
|
||||
queryClient.invalidateQueries(["allEmployee", true]);
|
||||
queryClient.invalidateQueries(["allEmployee", false]);
|
||||
queryClient.invalidateQueries(["employeeProfile", response?.employeeId]);
|
||||
queryClient.invalidateQueries(["employeeListByProject"]);
|
||||
|
||||
emitters.employee();
|
||||
}
|
||||
|
||||
// ---- Image related events ----
|
||||
if (["Task_Report", "Task_Comment"].includes(keyword) && numberOfImages > 0) {
|
||||
emitters.image_gallery();
|
||||
}
|
||||
});
|
||||
|
||||
connection
|
||||
.start();
|
||||
|
@ -4,10 +4,18 @@ const localVariablesSlice = createSlice({
|
||||
name: "localVariables",
|
||||
initialState: {
|
||||
selectedMaster: "Application Role",
|
||||
regularizationCount: 0,
|
||||
defaultDateRange: {
|
||||
startDate: null,
|
||||
endDate: null,
|
||||
// Attendances
|
||||
attendance: {
|
||||
regularizationCount: 0,
|
||||
defaultDateRange: { startDate: null, endDate: null },
|
||||
SelectedOrg: "",
|
||||
},
|
||||
|
||||
// Modal for all simple pass Name
|
||||
|
||||
modals: {
|
||||
auth: { isOpen: false },
|
||||
organization: { isOpen: false },
|
||||
},
|
||||
projectId: null,
|
||||
reload: false,
|
||||
@ -28,9 +36,18 @@ const localVariablesSlice = createSlice({
|
||||
changeMaster: (state, action) => {
|
||||
state.selectedMaster = action.payload;
|
||||
},
|
||||
|
||||
// ─── ATTENDANCE ─────────────────────────
|
||||
updateRegularizationCount: (state, action) => {
|
||||
state.regularizationCount = action.payload;
|
||||
state.attendance.regularizationCount = action.payload;
|
||||
},
|
||||
setDefaultDateRange: (state, action) => {
|
||||
state.attendance.defaultDateRange = action.payload;
|
||||
},
|
||||
setOrganization: (state, action) => {
|
||||
state.attendance.SelectedOrg = action.payload;
|
||||
},
|
||||
|
||||
setProjectId: (state, action) => {
|
||||
localStorage.setItem("project", null);
|
||||
state.projectId = action.payload;
|
||||
@ -39,10 +56,6 @@ const localVariablesSlice = createSlice({
|
||||
refreshData: (state, action) => {
|
||||
state.reload = action.payload;
|
||||
},
|
||||
setDefaultDateRange: (state, action) => {
|
||||
state.defaultDateRange = action.payload;
|
||||
},
|
||||
|
||||
openOrgModal: (state, action) => {
|
||||
state.OrganizationModal.isOpen = true;
|
||||
state.OrganizationModal.orgData = action.payload?.orgData || null;
|
||||
@ -70,6 +83,19 @@ const localVariablesSlice = createSlice({
|
||||
closeAuthModal: (state, action) => {
|
||||
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;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@ -84,5 +110,6 @@ export const {
|
||||
toggleOrgModal,
|
||||
openAuthModal,
|
||||
closeAuthModal,
|
||||
setOrganization,openModal, closeModal, toggleModal
|
||||
} = localVariablesSlice.actions;
|
||||
export default localVariablesSlice.reducer;
|
||||
export default localVariablesSlice.reducer;
|
||||
|
@ -1,5 +1,5 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { format, parseISO } from "date-fns";
|
||||
import { parseISO, formatISO } from "date-fns";
|
||||
export const formatFileSize = (bytes) => {
|
||||
if (bytes < 1024) return bytes + " B";
|
||||
else if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + " KB";
|
||||
@ -69,15 +69,41 @@ export const normalizeAllowedContentTypes = (allowedContentType) => {
|
||||
return allowedContentType.split(",");
|
||||
return [];
|
||||
};
|
||||
export function localToUtc(localDateString) {
|
||||
if (!localDateString || typeof localDateString !== "string") return null;
|
||||
export function localToUtc(dateString) {
|
||||
if (!dateString || typeof dateString !== "string") return null;
|
||||
|
||||
const [year, month, day] = localDateString.trim().split("-");
|
||||
const parts = dateString.trim().split("-");
|
||||
if (parts.length !== 3) return null;
|
||||
|
||||
if (!year || !month || !day) return null;
|
||||
let day, month, year;
|
||||
|
||||
if (parts[0].length === 4) {
|
||||
// Format: yyyy-mm-dd
|
||||
[year, month, day] = parts;
|
||||
} else {
|
||||
// Format: dd-mm-yyyy
|
||||
[day, month, year] = parts;
|
||||
}
|
||||
|
||||
const date = new Date(Number(year), Number(month) - 1, Number(day), 0, 0, 0);
|
||||
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();
|
||||
}
|
||||
|
||||
export const formatCurrency = (amount, currency = "INR", locale = "en-US") => {
|
||||
return new Intl.NumberFormat(locale, {
|
||||
style: "currency",
|
||||
notation: "compact",
|
||||
compactDisplay: "short",
|
||||
currency: currency,
|
||||
minimumFractionDigits: 0,
|
||||
maximumFractionDigits: 2,
|
||||
}).format(amount);
|
||||
};
|
||||
|
||||
export const countDigit = (num) => {
|
||||
return Math.abs(num).toString().length;
|
||||
};
|
||||
|
@ -4,6 +4,7 @@ import axiosRetry from "axios-retry";
|
||||
import showToast from "../services/toastService";
|
||||
import { startSignalR, stopSignalR } from "../services/signalRService";
|
||||
import { BASE_URL } from "./constants";
|
||||
import { removeSession } from "./authUtils";
|
||||
const base_Url = BASE_URL;
|
||||
|
||||
export const axiosClient = axios.create({
|
||||
@ -77,8 +78,10 @@ axiosClient.interceptors.response.use(
|
||||
if (
|
||||
!refreshToken ||
|
||||
error.response.data?.errors === "Invalid or expired refresh token."
|
||||
|
||||
) {
|
||||
redirectToLogin();
|
||||
removeSession()
|
||||
return Promise.reject(error);
|
||||
}
|
||||
|
||||
@ -107,6 +110,7 @@ axiosClient.interceptors.response.use(
|
||||
originalRequest.headers["Authorization"] = `Bearer ${token}`;
|
||||
return axiosClient(originalRequest);
|
||||
} catch (refreshError) {
|
||||
removeSession()
|
||||
redirectToLogin();
|
||||
return Promise.reject(refreshError);
|
||||
}
|
||||
|
@ -1,3 +1,8 @@
|
||||
export const BASE_URL = process.env.VITE_BASE_URL;
|
||||
|
||||
// export const BASE_URL = "https://api.marcoaiot.com";
|
||||
|
||||
|
||||
export const THRESH_HOLD = 48; // hours
|
||||
export const DURATION_TIME = 10; // minutes
|
||||
export const ITEMS_PER_PAGE = 20;
|
||||
@ -140,8 +145,26 @@ export const PROJECT_STATUS = [
|
||||
label: "Completed",
|
||||
},
|
||||
];
|
||||
|
||||
|
||||
export const EXPENSE_STATUS = {
|
||||
daft:"297e0d8f-f668-41b5-bfea-e03b354251c8",
|
||||
review_pending:"6537018f-f4e9-4cb3-a210-6c3b2da999d7",
|
||||
payment_pending:"f18c5cfd-7815-4341-8da2-2c2d65778e27",
|
||||
approve_pending:"4068007f-c92f-4f37-a907-bc15fe57d4d8",
|
||||
process_pending:"61578360-3a49-4c34-8604-7b35a3787b95"
|
||||
|
||||
}
|
||||
|
||||
export const UUID_REGEX =
|
||||
/^\/employee\/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
|
||||
|
||||
export const ALLOW_PROJECTSTATUS_ID = [
|
||||
"603e994b-a27f-4e5d-a251-f3d69b0498ba",
|
||||
"cdad86aa-8a56-4ff4-b633-9c629057dfef",
|
||||
"b74da4c2-d07e-46f2-9919-e75e49b12731",
|
||||
];
|
||||
|
||||
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";
|
||||
|
@ -1,5 +1,6 @@
|
||||
import moment from "moment";
|
||||
import { ActiveTenant } from "./constants";
|
||||
import {format} from 'date-fns'
|
||||
|
||||
export const getDateDifferenceInDays = (startDate, endDate) => {
|
||||
if (!startDate || !endDate) {
|
||||
@ -93,6 +94,15 @@ export const getCompletionPercentage = (completedWork, plannedWork)=> {
|
||||
return clamped.toFixed(2);
|
||||
}
|
||||
|
||||
export const formatDate_DayMonth = (monthName, year) => {
|
||||
if (!monthName || !year) return "";
|
||||
try {
|
||||
const shortMonth = monthName.substring(0, 3);
|
||||
return `${shortMonth} ${year}`;
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
};
|
||||
export const getTenantStatus =(statusId)=>{
|
||||
return ActiveTenant === statusId ? " bg-label-success":"bg-label-secondary"
|
||||
}
|
@ -1,27 +0,0 @@
|
||||
// utils/exportUtils.js
|
||||
export const exportToCSV = (data, filename = "export.csv") => {
|
||||
if (!data || data.length === 0) return;
|
||||
|
||||
const headers = Object.keys(data[0]);
|
||||
const csvRows = [];
|
||||
|
||||
// Add headers
|
||||
csvRows.push(headers.join(","));
|
||||
|
||||
// Add values
|
||||
data.forEach(row => {
|
||||
const values = headers.map(header => `"${row[header] ?? ""}"`);
|
||||
csvRows.push(values.join(","));
|
||||
});
|
||||
|
||||
// Create CSV Blob
|
||||
const csvContent = csvRows.join("\n");
|
||||
const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
|
||||
|
||||
// Create download link
|
||||
const link = document.createElement("a");
|
||||
const url = URL.createObjectURL(blob);
|
||||
link.setAttribute("href", url);
|
||||
link.setAttribute("download", filename);
|
||||
link.click();
|
||||
};
|
@ -40,112 +40,57 @@ export const exportToExcel = (data, fileName = "data") => {
|
||||
* @param {Array} data - Array of objects to export
|
||||
* @param {string} fileName - File name for the PDF (optional)
|
||||
*/
|
||||
export const exportToPDF = async (data, fileName = "data") => {
|
||||
const sanitizeText = (text) => {
|
||||
if (!text) return "";
|
||||
// Replace all non-ASCII characters with "?" or remove them
|
||||
return text.replace(/[^\x00-\x7F]/g, "?");
|
||||
};
|
||||
|
||||
export const exportToPDF = async (data, fileName = "data", columns = null, options = {}) => {
|
||||
if (!data || data.length === 0) return;
|
||||
|
||||
// Create a new PDF document
|
||||
const pdfDoc = await PDFDocument.create();
|
||||
const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
|
||||
|
||||
// Set up the font
|
||||
const font = await pdfDoc.embedFont(StandardFonts.Helvetica); // Use Helvetica font
|
||||
|
||||
// Calculate column widths dynamically based on data content
|
||||
const headers = Object.keys(data[0]);
|
||||
const rows = data.map(item => headers.map(header => item[header] || ''));
|
||||
// Default options
|
||||
const {
|
||||
columnWidths = [], // array of widths per column
|
||||
fontSizeHeader = 12,
|
||||
fontSizeRow = 10,
|
||||
rowHeight = 25,
|
||||
} = options;
|
||||
|
||||
const getMaxColumnWidth = (columnIndex) => {
|
||||
let maxWidth = font.widthOfTextAtSize(headers[columnIndex], 12);
|
||||
rows.forEach(row => {
|
||||
const cellText = row[columnIndex].toString();
|
||||
maxWidth = Math.max(maxWidth, font.widthOfTextAtSize(cellText, 10));
|
||||
const pageWidth = 1000;
|
||||
const pageHeight = 600;
|
||||
let page = pdfDoc.addPage([pageWidth, pageHeight]);
|
||||
const margin = 30;
|
||||
let y = pageHeight - margin;
|
||||
|
||||
const headers = columns || Object.keys(data[0]);
|
||||
|
||||
// Draw headers
|
||||
headers.forEach((header, i) => {
|
||||
const x = margin + (columnWidths[i] ? columnWidths.slice(0, i).reduce((a, b) => a + b, 0) : i * 150);
|
||||
page.drawText(header, { x, y, font, size: fontSizeHeader });
|
||||
});
|
||||
y -= rowHeight;
|
||||
|
||||
// Draw rows
|
||||
data.forEach(row => {
|
||||
headers.forEach((header, i) => {
|
||||
const x = margin + (columnWidths[i] ? columnWidths.slice(0, i).reduce((a, b) => a + b, 0) : i * 150);
|
||||
const text = row[header] || '';
|
||||
page.drawText(text, { x, y, font, size: fontSizeRow });
|
||||
});
|
||||
return maxWidth + 10; // Padding for better spacing
|
||||
};
|
||||
y -= rowHeight;
|
||||
|
||||
const columnWidths = headers.map((_, index) => getMaxColumnWidth(index));
|
||||
const tableX = 30; // X-coordinate for the table start
|
||||
const rowHeight = 20; // Height of each row (can be adjusted)
|
||||
const maxPageHeight = 750; // Max available height for content (before a new page is added)
|
||||
const pageMargin = 30; // Margin from the top of the page
|
||||
|
||||
let tableY = maxPageHeight; // Start Y position for the table
|
||||
const maxPageWidth = 600; // Max available width for content (before a new page is added)
|
||||
|
||||
// Add the headers and rows to the page
|
||||
const addHeadersToPage = (page, scaleFactor) => {
|
||||
let xPosition = tableX;
|
||||
headers.forEach((header, index) => {
|
||||
page.drawText(header, {
|
||||
x: xPosition,
|
||||
y: tableY,
|
||||
font,
|
||||
size: 12 * scaleFactor, // Scale the header font size
|
||||
color: rgb(0, 0, 0),
|
||||
});
|
||||
xPosition += columnWidths[index] * scaleFactor; // Adjust X position based on scaling
|
||||
});
|
||||
tableY -= rowHeight; // Move down after adding headers
|
||||
};
|
||||
|
||||
// Add a new page and reset the table position
|
||||
const addNewPage = (scaleFactor) => {
|
||||
const page = pdfDoc.addPage([600, 800]);
|
||||
tableY = maxPageHeight; // Reset Y position for the new page
|
||||
addHeadersToPage(page, scaleFactor); // Re-add headers to the new page
|
||||
return page;
|
||||
};
|
||||
|
||||
// Create the first page and add headers
|
||||
let page = pdfDoc.addPage([600, 800]);
|
||||
|
||||
// Check if the content fits within the page width, scale if necessary
|
||||
const checkPageWidth = (row) => {
|
||||
let totalWidth = columnWidths.reduce((acc, width) => acc + width, 0);
|
||||
let scaleFactor = 1;
|
||||
if (totalWidth > maxPageWidth) {
|
||||
scaleFactor = maxPageWidth / totalWidth; // Scale down if necessary
|
||||
if (y < margin) {
|
||||
page = pdfDoc.addPage([pageWidth, pageHeight]);
|
||||
y = pageHeight - margin;
|
||||
}
|
||||
|
||||
return scaleFactor;
|
||||
};
|
||||
|
||||
// Function to check for page breaks when adding a new row
|
||||
const checkPageBreak = () => {
|
||||
if (tableY - rowHeight < pageMargin) {
|
||||
page = addNewPage(scaleFactor); // Add a new page if there is no space for the next row
|
||||
}
|
||||
};
|
||||
|
||||
// Add rows to the PDF with pagination and horizontal scaling
|
||||
rows.forEach(row => {
|
||||
checkPageBreak(); // Check for page break before adding each row
|
||||
|
||||
const scaleFactor = checkPageWidth(row); // Get the scaling factor for the row
|
||||
|
||||
// Add headers to the first page and each new page with the same scale factor
|
||||
if (tableY === maxPageHeight) {
|
||||
addHeadersToPage(page, scaleFactor); // Add headers only on the first page
|
||||
}
|
||||
|
||||
let xPosition = tableX;
|
||||
row.forEach((value, index) => {
|
||||
page.drawText(value.toString(), {
|
||||
x: xPosition,
|
||||
y: tableY,
|
||||
font,
|
||||
size: 10 * scaleFactor, // Scale the font size
|
||||
color: rgb(0, 0, 0),
|
||||
});
|
||||
xPosition += columnWidths[index] * scaleFactor; // Adjust X position based on scaling
|
||||
});
|
||||
|
||||
tableY -= rowHeight; // Move down to the next row position
|
||||
});
|
||||
|
||||
// Serialize the document to bytes
|
||||
const pdfBytes = await pdfDoc.save();
|
||||
|
||||
// Trigger a download of the PDF
|
||||
const blob = new Blob([pdfBytes], { type: 'application/pdf' });
|
||||
const link = document.createElement('a');
|
||||
link.href = URL.createObjectURL(blob);
|
||||
@ -153,15 +98,110 @@ export const exportToPDF = async (data, fileName = "data") => {
|
||||
link.click();
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Export JSON data to PDF in a card-style format
|
||||
* @param {Array} data - Array of objects to export
|
||||
* @param {string} fileName - File name for the PDF (optional)
|
||||
*/
|
||||
export const exportToPDF1 = async (data, fileName = "data") => {
|
||||
if (!data || data.length === 0) return;
|
||||
|
||||
const pdfDoc = await PDFDocument.create();
|
||||
const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
|
||||
const boldFont = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
|
||||
|
||||
const pageWidth = 600;
|
||||
const pageHeight = 800;
|
||||
const margin = 30;
|
||||
const cardSpacing = 20;
|
||||
const cardPadding = 10;
|
||||
let page = pdfDoc.addPage([pageWidth, pageHeight]);
|
||||
let y = pageHeight - margin;
|
||||
|
||||
for (const item of data) {
|
||||
const title = item.ContactName || "";
|
||||
const subtitle = `by ${item.CreatedBy || ""} on ${item.CreatedAt || ""}`;
|
||||
const body = item.Note || "";
|
||||
|
||||
const cardHeight = 80 + (body.length / 60) * 14; // approximate height for body text
|
||||
|
||||
if (y - cardHeight < margin) {
|
||||
page = pdfDoc.addPage([pageWidth, pageHeight]);
|
||||
y = pageHeight - margin;
|
||||
}
|
||||
|
||||
// Draw card border
|
||||
page.drawRectangle({
|
||||
x: margin,
|
||||
y: y - cardHeight,
|
||||
width: pageWidth - 2 * margin,
|
||||
height: cardHeight,
|
||||
borderColor: rgb(0.7, 0.7, 0.7),
|
||||
borderWidth: 1,
|
||||
color: rgb(1, 1, 1),
|
||||
});
|
||||
|
||||
// Draw title
|
||||
page.drawText(title, {
|
||||
x: margin + cardPadding,
|
||||
y: y - 20,
|
||||
font: boldFont,
|
||||
size: 12,
|
||||
color: rgb(0.1, 0.1, 0.1),
|
||||
});
|
||||
|
||||
// Draw subtitle
|
||||
page.drawText(subtitle, {
|
||||
x: margin + cardPadding,
|
||||
y: y - 35,
|
||||
font,
|
||||
size: 10,
|
||||
color: rgb(0.4, 0.4, 0.4),
|
||||
});
|
||||
|
||||
// Draw body text (wrap manually)
|
||||
const lines = body.match(/(.|[\r\n]){1,80}/g) || [];
|
||||
lines.forEach((line, i) => {
|
||||
page.drawText(line, {
|
||||
x: margin + cardPadding,
|
||||
y: y - 50 - i * 12,
|
||||
font,
|
||||
size: 10,
|
||||
color: rgb(0.2, 0.2, 0.2),
|
||||
});
|
||||
});
|
||||
|
||||
y -= cardHeight + cardSpacing;
|
||||
}
|
||||
|
||||
const pdfBytes = await pdfDoc.save();
|
||||
const blob = new Blob([pdfBytes], { type: 'application/pdf' });
|
||||
const link = document.createElement('a');
|
||||
link.href = URL.createObjectURL(blob);
|
||||
link.download = `${fileName}.pdf`;
|
||||
link.click();
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Print the HTML table by accepting the table element or a reference.
|
||||
* @param {HTMLElement} table - The table element (or ref) to print
|
||||
*/
|
||||
export const printTable = (table) => {
|
||||
if (table) {
|
||||
const newWindow = window.open("", "", "width=600,height=600"); // Open a new window
|
||||
const clone = table.cloneNode(true);
|
||||
// Remove last column (Actions) from all rows
|
||||
clone.querySelectorAll("tr").forEach((row) => {
|
||||
row.removeChild(row.lastElementChild);
|
||||
});
|
||||
|
||||
// Inject styles for the table and body
|
||||
const newWindow = window.open("", "", "width=600,height=600");
|
||||
newWindow.document.write("<html><head><title>Print Table</title>");
|
||||
const style = document.createElement('style');
|
||||
style.innerHTML = `
|
||||
@ -171,16 +211,14 @@ export const printTable = (table) => {
|
||||
th { background-color: #f2f2f2; }
|
||||
`;
|
||||
newWindow.document.head.appendChild(style);
|
||||
|
||||
|
||||
newWindow.document.write("</head><body>");
|
||||
newWindow.document.write(table.outerHTML); // Write the table HTML to the new window
|
||||
newWindow.document.write(clone.outerHTML);
|
||||
newWindow.document.write("</body></html>");
|
||||
|
||||
newWindow.document.close(); // Close the document stream
|
||||
|
||||
// Wait for the document to load before triggering print
|
||||
newWindow.document.close();
|
||||
newWindow.onload = () => {
|
||||
newWindow.print(); // Trigger the print dialog after the content is loaded
|
||||
newWindow.print();
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user