Compare commits

..

71 Commits

Author SHA1 Message Date
df41f4c82d Adding Chips in Directory Contact and Notes Page. 2025-10-11 10:30:15 +05:30
bb2d7b8923 added pading in check-in check-out form 2025-10-10 19:54:20 +05:30
c921dbff09 fixed u 2025-10-10 17:49:14 +05:30
e84da2dcb0 Merge pull request 'Kartik_Task_1459 :- Adding Export Excel and PDF in Directory.' (#469) from Kartik_Task_1459 into OnFieldWork_V1
Reviewed-on: #469
Merged
2025-10-10 11:24:30 +00:00
4ba7c72e78 Removing ExportUtils.js file. 2025-10-10 11:24:30 +00:00
9939973d8d Adding Excel and PDF export in Directory. 2025-10-10 11:24:30 +00:00
e17c2064ac Merge pull request 'UI updation in Expense Breakdown' (#471) from Kartik_Bug#1463 into OnFieldWork_V1
Reviewed-on: #471
Merged
2025-10-10 11:24:02 +00:00
9580c9234c UI updation in Expense Breakdown 2025-10-10 11:24:02 +00:00
44b3f842f2 Correction in Date Ranger in Attendance Logs. 2025-10-10 16:36:39 +05:30
9de0b1a0df Project List view UI implementation. 2025-10-10 16:00:52 +05:30
fbb68a4488 Correction in DataRangePicker for date range box and Calender. 2025-10-10 15:24:34 +05:30
c1a8b87a2c Merge branch 'OnFieldWork_V1' of https://git.marcoaiot.com/admin/marco.pms.web into OnFieldWork_V1 2025-10-10 12:48:42 +05:30
24501b3c76 persist date 2025-10-10 12:48:37 +05:30
ef00516256 Changes in Dashboard weidget Attendance and Monthly weidget when no data show. 2025-10-10 12:11:12 +05:30
f867a692ed fixed : whenever open modal that not come exiten data 2025-10-09 18:49:14 +05:30
85b4b830d3 Merge pull request 'Kartik_Enhancement#1448 : Document filters chips' (#468) from Kartik_Enhancement#1448 into OnFieldWork_V1
Reviewed-on: #468
Merged
2025-10-09 12:57:36 +00:00
c1c333008f added document filter chips 2025-10-09 12:57:36 +00:00
5370d0eb9d Adding Chips in Document. 2025-10-09 12:57:36 +00:00
5cbd6c427a Adding Chips in Document. 2025-10-09 12:57:36 +00:00
5057738d8b Merge pull request 'Directory tab inside Project Profile page not displayed properly (tab within tab issue)' (#464) from Kartik_Bug#1408 into OnFieldWork_V1
Reviewed-on: #464
2025-10-09 12:56:40 +00:00
063bbee681 Changes directory View. 2025-10-09 12:56:40 +00:00
3dc667db73 Directory tab inside Project Profile page not displayed properly (tab within tab issue) 2025-10-09 12:56:40 +00:00
2f2c31db9f Merge pull request 'Added 3-dots menu in the Employee Module with ‘Show Inactive Employees’ and Export functionalities inside the menu.' (#466) from Kartik_Enhancement#1433 into OnFieldWork_V1
Reviewed-on: #466
merged
2025-10-09 12:55:56 +00:00
0dc540eec2 Added 3-dots menu in the Employee Module with ‘Show Inactive Employees’ and Export functionalities inside the menu. 2025-10-09 12:55:56 +00:00
fc7c33ee54 added right status variable name 2025-10-09 17:51:27 +05:30
eeb886ec36 Removing consol.log in regularize 2025-10-09 14:58:11 +05:30
210b01513e Removing Project name column in Attendance Logs and Regularize. 2025-10-09 14:56:00 +05:30
2fe297c6b6 Adding 2 columns in Regularize column Request at and Requested by 2025-10-09 10:27:13 +05:30
ffd7f15488 Merge pull request 'Attendance Tab Should Display All Records for Each Employee' (#465) from Kartik_Bug#1425 into OnFieldWork_V1
Reviewed-on: #465
Merged
2025-10-08 13:38:09 +00:00
7f33d5e6bd Attendance Tab Should Display All Records for Each Employee 2025-10-08 13:38:09 +00:00
108ca1cc96 Merge pull request 'Adding NA and updation in Excel,PDF and Print functionality in Employee list.' (#463) from Kartik_Bug#1436 into OnFieldWork_V1
Reviewed-on: #463
Merged
2025-10-08 13:37:48 +00:00
0b1a276898 Adding NA and updation in Excel,PDF and Print functionality in Employee list. 2025-10-08 13:37:48 +00:00
6246dbd23f Merge pull request 'Missing title in View popup' (#462) from Kartik#Enhancement#1444 into OnFieldWork_V1
Reviewed-on: #462
Merged
2025-10-08 13:37:18 +00:00
af3bf11beb Missing title in View popup 2025-10-08 13:37:18 +00:00
2e5951d9d1 Merge pull request 'Expense Type label to be renamed to Expense Category.' (#461) from Kartik_Enhancement#1446 into OnFieldWork_V1
Reviewed-on: #461
Merged
2025-10-08 13:37:02 +00:00
cdc5e32554 Expense Type label to be renamed to Expense Category. 2025-10-08 13:37:02 +00:00
bc047a84fc Adding processpending in ExpenseStatus. 2025-10-08 18:49:24 +05:30
0511ed6d82 Changes in Attendance module for all projects. 2025-10-08 13:52:06 +05:30
bc933f4c64 Adding Search box in Expense Paid by dropdown. 2025-10-08 11:29:51 +05:30
bd3645aae6 In Modify project add project.id on UseProjectDetails 2025-10-08 10:58:31 +05:30
2f2215ab8a Merge pull request 'OnField_Issues_Oct_2W' (#455) from OnField_Issues_Oct_2W into OnFieldWork_V1
Reviewed-on: #455
Merged
2025-10-07 04:10:40 +00:00
071f862743 Incorrect navigation when viewing project details 2025-10-07 04:10:40 +00:00
040331e27d Removing the dropdown from the Masters page. 2025-10-07 04:10:40 +00:00
db2730c02b Employee Click Should Navigate to Profile Page from Attendance Page 2025-10-07 04:10:40 +00:00
9df813698d Merge pull request 'Adding_Chips_Expense' (#451) from Adding_Chips_Expense into OnFieldWork_V1
Reviewed-on: #451
Merged
2025-10-06 13:47:36 +00:00
6ba018399c Merge branch 'OnFieldWork_V1' of https://git.marcoaiot.com/admin/marco.pms.web into Adding_Chips_Expense 2025-10-06 19:06:33 +05:30
1e49cf17a2 addd dropdown at expense table action 2025-10-04 16:25:28 +05:30
ab5e0b2f79 Merge branch 'OnFieldWork_V1' of https://git.marcoaiot.com/admin/marco.pms.web into Adding_Chips_Expense 2025-10-04 16:12:07 +05:30
7c9d2ddeb1 Added Chips in Expense filter. 2025-10-04 16:06:26 +05:30
f0f579beae fixed dashbord card size 2025-10-04 15:47:07 +05:30
b53e6284b9 Merge branch 'OnFieldWork_V1' of https://git.marcoaiot.com/admin/marco.pms.web into OnFieldWork_V1 2025-10-04 14:13:43 +05:30
b1c23aab4d added expens group fied Name 2025-10-04 14:13:09 +05:30
4a05e67ff0 Adding dropdown in ExpenseFilter. 2025-10-04 14:12:20 +05:30
87d13d0f77 Changes in Monthly Expense weidget. 2025-10-04 12:20:59 +05:30
997971629f addd Expense By project 2025-10-04 11:08:19 +05:30
18ac8e11bd added expense filte at api url level 2025-10-04 10:50:14 +05:30
78808ecac0 added Expensebstatus widget, fixed small bugs 2025-10-03 19:07:44 +05:30
3553a7b521 change class to className 2025-10-03 10:57:55 +05:30
aca96c60ae removed console and comment 2025-10-02 13:24:36 +05:30
25f4f1e7a7 added expense analysis card inisde dashboard 2025-10-02 13:10:14 +05:30
0c1889e1c1 added Ellipsis Pagination 2025-10-01 22:45:31 +05:30
9884943907 addded imported field added 2025-10-01 18:45:26 +05:30
2531d91209 fixed dashboard graph 2025-10-01 16:21:08 +05:30
49b597c833 fixed expense date, added project name at check in checkout modal 2025-10-01 15:34:19 +05:30
2aae7194b7 implemented singlR 2025-10-01 13:00:38 +05:30
ae772d925a remove project permissions 2025-10-01 10:13:52 +05:30
c1e5ff4043 remove dashboard 2025-09-30 23:39:41 +05:30
2aff3b9e80 changed logins api 2025-09-30 19:35:01 +05:30
4e48478fbc update attendnace and expense 2025-09-30 19:31:24 +05:30
4ea1e06a9c hide project infra, setting, Organization, and show only all employees and inactive employee 2025-09-30 18:16:29 +05:30
4ddb8415cc added gobal create project,change paid by at expense create 2025-09-30 17:27:20 +05:30
130 changed files with 4874 additions and 3728 deletions

View File

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

View File

@ -32573,4 +32573,7 @@ body:not(.modal-open) .layout-content-navbar .layout-navbar {
} }
.text-red{ .text-red{
color:var(--bs-red) color:var(--bs-red)
}
.bg-gray {
background:var(--bs-body-color)
} }

View File

@ -6,7 +6,12 @@ import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import { queryClient } from "./layouts/AuthLayout"; import { queryClient } from "./layouts/AuthLayout";
import ModalProvider from "./ModalProvider"; 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 = () => { const App = () => {
return ( return (

View File

@ -3,18 +3,18 @@ import { useOrganizationModal } from "./hooks/useOrganization";
import OrganizationModal from "./components/Organization/OrganizationModal"; import OrganizationModal from "./components/Organization/OrganizationModal";
import { useAuthModal, useModal } from "./hooks/useAuth"; import { useAuthModal, useModal } from "./hooks/useAuth";
import SwitchTenant from "./pages/authentication/SwitchTenant"; import SwitchTenant from "./pages/authentication/SwitchTenant";
import ChangePasswordPage from "./pages/authentication/ChangePassword"; import { ProjectModal } from "./components/Project/ManageProjectInfo";
const ModalProvider = () => { const ModalProvider = () => {
const { isOpen, onClose } = useOrganizationModal(); const { isOpen, onClose } = useOrganizationModal();
const { isOpen: isAuthOpen } = useAuthModal(); const { isOpen: isAuthOpen } = useAuthModal();
const {isOpen:isChangePass} = useModal("ChangePassword") const {isOpen:isOpenProject} = useModal("ManageProject")
return ( return (
<> <>
{isOpen && <OrganizationModal />} {isOpen && <OrganizationModal />}
{isAuthOpen && <SwitchTenant />} {isAuthOpen && <SwitchTenant />}
{isChangePass && <ChangePasswordPage /> } {isOpenProject && <ProjectModal/>}
</> </>
); );
}; };

View File

@ -123,15 +123,19 @@ const AttendLogs = ({ Id }) => {
}, []); }, []);
return ( return (
<div className="table-responsive"> <div className="table-responsive">
<div className="text-start"> <div className="mb-3">
<h5 className="fw-bold mb-4">Attendance Logs</h5>
{logs && !loading && ( {logs && !loading && (
<p> <p className="mb-0 text-start">
Attendance logs for{" "} Showing logs for{" "}
{logs[0]?.employee?.firstName + " " + logs[0]?.employee?.lastName}{" "} <strong>
on {formatUTCToLocalTime(logs[0]?.activityTime)} {logs[0]?.employee?.firstName + " " + logs[0]?.employee?.lastName}
</strong>{" "}
on <strong>{formatUTCToLocalTime(logs[0]?.activityTime)}</strong>
</p> </p>
)} )}
</div> </div>
{loading && <p>Loading..</p>} {loading && <p>Loading..</p>}
{logs && logs.length > 0 && ( {logs && logs.length > 0 && (
<> <>
@ -142,9 +146,9 @@ const AttendLogs = ({ Id }) => {
<table className="table table-sm mb-0"> <table className="table table-sm mb-0">
<thead> <thead>
<tr> <tr>
<th>Activity</th>
<th>Date</th> <th>Date</th>
<th>Time</th> <th>Time</th>
<th>Activity</th>
<th>Location</th> <th>Location</th>
<th>Recored By</th> <th>Recored By</th>
<th>Description</th> <th>Description</th>
@ -156,11 +160,16 @@ const AttendLogs = ({ Id }) => {
.sort((a, b) => b.id - a.id) .sort((a, b) => b.id - a.id)
.map((log, index) => ( .map((log, index) => (
<tr key={index}> <tr key={index}>
<td>{formatUTCToLocalTime(log.activityTime)}</td> <td>
<td>{convertShortTime(log.activityTime)}</td>
<td>
{whichActivityPerform(log.activity, log.activityTime)} {whichActivityPerform(log.activity, log.activityTime)}
</td> </td>
<td>
<div className="py-2">
{formatUTCToLocalTime(log.activityTime)}
</div>
</td>
<td>{convertShortTime(log.activityTime)}</td>
<td> <td>
{log?.latitude != 0 ? ( {log?.latitude != 0 ? (
<i <i
@ -179,9 +188,8 @@ const AttendLogs = ({ Id }) => {
)} )}
</td> </td>
<td className="text-wrap"> <td className="text-wrap">
{`${log?.updatedByEmployee?.firstName ?? ""} ${ {`${log?.updatedByEmployee?.firstName ?? ""} ${log?.updatedByEmployee?.lastName ?? ""
log?.updatedByEmployee?.lastName ?? "" }`}
}`}
</td> </td>
<td className="text-wrap" colSpan={3}> <td className="text-wrap" colSpan={3}>
{log?.comment?.length > 50 {log?.comment?.length > 50

View File

@ -11,8 +11,9 @@ import { useSelector } from "react-redux";
import { useQueryClient } from "@tanstack/react-query"; import { useQueryClient } from "@tanstack/react-query";
import eventBus from "../../services/eventBus"; import eventBus from "../../services/eventBus";
import { useSelectedProject } from "../../slices/apiDataManager"; import { useSelectedProject } from "../../slices/apiDataManager";
import Pagination from "../common/Pagination";
const Attendance = ({ getRole, handleModalData, searchTerm, projectId, organizationId, }) => { const Attendance = ({ getRole, handleModalData, searchTerm, projectId, organizationId, includeInactive, date }) => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const navigate = useNavigate(); const navigate = useNavigate();
@ -24,7 +25,7 @@ const Attendance = ({ getRole, handleModalData, searchTerm, projectId, organizat
loading: attLoading, loading: attLoading,
recall: attrecall, recall: attrecall,
isFetching isFetching
} = useAttendance(selectedProject, organizationId); } = useAttendance(selectedProject, organizationId, includeInactive, date);
const filteredAttendance = ShowPending const filteredAttendance = ShowPending
? attendance?.filter( ? attendance?.filter(
(att) => att?.checkInTime !== null && att?.checkOutTime === null (att) => att?.checkInTime !== null && att?.checkOutTime === null
@ -108,6 +109,8 @@ const Attendance = ({ getRole, handleModalData, searchTerm, projectId, organizat
return () => eventBus.off("employee", employeeHandler); return () => eventBus.off("employee", employeeHandler);
}, [employeeHandler]); }, [employeeHandler]);
return ( return (
<> <>
<div <div
@ -138,7 +141,7 @@ const Attendance = ({ getRole, handleModalData, searchTerm, projectId, organizat
<tr className="border-top-1"> <tr className="border-top-1">
<th colSpan={2}>Name</th> <th colSpan={2}>Name</th>
<th>Role</th> <th>Role</th>
<th>Organization</th> {/* <th>Organization</th> */}
<th> <th>
<i className="bx bxs-down-arrow-alt text-success"></i> <i className="bx bxs-down-arrow-alt text-success"></i>
Check-In Check-In
@ -187,7 +190,7 @@ const Attendance = ({ getRole, handleModalData, searchTerm, projectId, organizat
</td> </td>
<td>{item.jobRoleName}</td> <td>{item.jobRoleName}</td>
<td>{item.organizationName || "--"}</td> {/* <td>{item.organizationName || "--"}</td> */}
<td> <td>
{item.checkInTime {item.checkInTime
@ -226,46 +229,12 @@ const Attendance = ({ getRole, handleModalData, searchTerm, projectId, organizat
{!loading && finalFilteredData.length > ITEMS_PER_PAGE && ( {!loading && finalFilteredData.length > ITEMS_PER_PAGE && (
<nav aria-label="Page ">
<ul className="pagination pagination-sm justify-content-end py-1"> <Pagination
<li currentPage={currentPage}
className={`page-item ${currentPage === 1 ? "disabled" : "" totalPages={totalPages}
}`} onPageChange={paginate}
> />
<button
className="page-link btn-xs"
onClick={() => paginate(currentPage - 1)}
>
&laquo;
</button>
</li>
{[...Array(totalPages)].map((_, index) => (
<li
key={index}
className={`page-item ${currentPage === index + 1 ? "active" : ""
}`}
>
<button
className="page-link "
onClick={() => paginate(index + 1)}
>
{index + 1}
</button>
</li>
))}
<li
className={`page-item ${currentPage === totalPages ? "disabled" : ""
}`}
>
<button
className="page-link "
onClick={() => paginate(currentPage + 1)}
>
&raquo;
</button>
</li>
</ul>
</nav>
)} )}
</> </>
) : ( ) : (

View File

@ -5,16 +5,14 @@ import { convertShortTime } from "../../utils/dateUtils";
import RenderAttendanceStatus from "./RenderAttendanceStatus"; import RenderAttendanceStatus from "./RenderAttendanceStatus";
import { useSelector, useDispatch } from "react-redux"; import { useSelector, useDispatch } from "react-redux";
import DateRangePicker from "../common/DateRangePicker"; import DateRangePicker from "../common/DateRangePicker";
import { import { clearCacheKey, getCachedData, useSelectedProject } from "../../slices/apiDataManager";
clearCacheKey,
getCachedData,
useSelectedProject,
} from "../../slices/apiDataManager";
import eventBus from "../../services/eventBus"; import eventBus from "../../services/eventBus";
import AttendanceRepository from "../../repositories/AttendanceRepository"; import AttendanceRepository from "../../repositories/AttendanceRepository";
import { useAttendancesLogs } from "../../hooks/useAttendance"; import { useAttendancesLogs } from "../../hooks/useAttendance";
import { queryClient } from "../../layouts/AuthLayout"; import { queryClient } from "../../layouts/AuthLayout";
import { ITEMS_PER_PAGE } from "../../utils/constants"; import { ITEMS_PER_PAGE } from "../../utils/constants";
import Pagination from "../common/Pagination";
import { useNavigate } from "react-router-dom";
const usePagination = (data, itemsPerPage) => { const usePagination = (data, itemsPerPage) => {
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
@ -38,149 +36,204 @@ const usePagination = (data, itemsPerPage) => {
}; };
const AttendanceLog = ({ handleModalData, searchTerm, organizationId }) => { const AttendanceLog = ({ handleModalData, searchTerm, organizationId }) => {
const selectedProject = useSelectedProject(); // const selectedProject = useSelector(
const [dateRange, setDateRange] = useState({ startDate: "", endDate: "" }); // (store) => store.localVariables.projectId
const dispatch = useDispatch(); // );
const [loading, setLoading] = useState(false); const selectedProject = useSelectedProject();
const [showPending, setShowPending] = useState(false); const [dateRange, setDateRange] = useState({ startDate: "", endDate: "" });
const [isRefreshing, setIsRefreshing] = useState(false); const dispatch = useDispatch();
const [loading, setLoading] = useState(false);
const [showPending, setShowPending] = useState(false)
const today = new Date(); const [isRefreshing, setIsRefreshing] = useState(false);
today.setHours(0, 0, 0, 0); const [processedData, setProcessedData] = useState([]);
const navigate = useNavigate();
const yesterday = new Date(); const today = new Date();
yesterday.setDate(yesterday.getDate() - 1); today.setHours(0, 0, 0, 0);
const isSameDay = (dateStr) => { const yesterday = new Date();
if (!dateStr) return false; yesterday.setDate(yesterday.getDate() - 1);
const d = new Date(dateStr);
d.setHours(0, 0, 0, 0);
return d.getTime() === today.getTime();
};
const isBeforeToday = (dateStr) => { const isSameDay = (dateStr) => {
if (!dateStr) return false; if (!dateStr) return false;
const d = new Date(dateStr); const d = new Date(dateStr);
d.setHours(0, 0, 0, 0); d.setHours(0, 0, 0, 0);
return d.getTime() < today.getTime(); return d.getTime() === today.getTime();
}; };
const sortByName = (a, b) => { const isBeforeToday = (dateStr) => {
const nameA = (a.firstName + a.lastName).toLowerCase(); if (!dateStr) return false;
const nameB = (b.firstName + b.lastName).toLowerCase(); const d = new Date(dateStr);
return nameA.localeCompare(nameB); d.setHours(0, 0, 0, 0);
}; return d.getTime() < today.getTime();
};
const { data = [], isLoading, error, refetch, isFetching } = useAttendancesLogs( const sortByName = (a, b) => {
selectedProject, const nameA = a.firstName.toLowerCase() + a.lastName.toLowerCase();
dateRange.startDate, const nameB = b.firstName.toLowerCase() + b.lastName.toLowerCase();
dateRange.endDate, return nameA?.localeCompare(nameB);
organizationId };
);
const processedData = useMemo(() => { const {
const filteredData = showPending data = [],
? data.filter((item) => item.checkOutTime === null) isLoading,
: data; error,
refetch,
isFetching,
} = useAttendancesLogs(
selectedProject,
dateRange.startDate,
dateRange.endDate,
organizationId
);
const filtering = useCallback((dataToFilter) => {
const filteredData = showPending
? dataToFilter.filter((item) => item.checkOutTime === null)
: dataToFilter;
const group1 = filteredData.filter((d) => d.activity === 1 && isSameDay(d.checkInTime)).sort(sortByName); const group1 = filteredData
const group2 = filteredData.filter((d) => d.activity === 4 && isSameDay(d.checkOutTime)).sort(sortByName); .filter((d) => d.activity === 1 && isSameDay(d.checkInTime))
const group3 = filteredData.filter((d) => d.activity === 1 && isBeforeToday(d.checkInTime)).sort(sortByName); .sort(sortByName);
const group4 = filteredData.filter((d) => d.activity === 4 && isBeforeToday(d.checkOutTime)); const group2 = filteredData
const group5 = filteredData.filter((d) => d.activity === 2 && isBeforeToday(d.checkOutTime)).sort(sortByName); .filter((d) => d.activity === 4 && isSameDay(d.checkOutTime))
const group6 = filteredData.filter((d) => d.activity === 5).sort(sortByName); .sort(sortByName);
const group3 = filteredData
.filter((d) => d.activity === 1 && isBeforeToday(d.checkInTime))
.sort(sortByName);
const group4 = filteredData.filter(
(d) => d.activity === 4 && isBeforeToday(d.checkOutTime)
);
const group5 = filteredData
.filter((d) => d.activity === 2 && isBeforeToday(d.checkOutTime))
.sort(sortByName);
const group6 = filteredData
.filter((d) => d.activity === 5)
.sort(sortByName);
const sortedList = [...group1, ...group2, ...group3, ...group4, ...group5, ...group6]; const sortedList = [...group1, ...group2, ...group3, ...group4, ...group5, ...group6];
const groupedByDate = sortedList.reduce((acc, item) => { // Group by date
const date = (item.checkInTime || item.checkOutTime)?.split("T")[0]; const groupedByDate = sortedList.reduce((acc, item) => {
if (date) { const date = (item.checkInTime || item.checkOutTime)?.split("T")[0];
acc[date] = acc[date] || []; if (date) {
acc[date].push(item); acc[date] = acc[date] || [];
} acc[date].push(item);
return acc; }
}, {}); return acc;
}, {});
const sortedDates = Object.keys(groupedByDate).sort((a, b) => new Date(b) - new Date(a)); const sortedDates = Object.keys(groupedByDate).sort(
return sortedDates.flatMap((date) => groupedByDate[date]); (a, b) => new Date(b) - new Date(a)
);
const finalData = sortedDates.flatMap((date) => groupedByDate[date]);
setProcessedData(finalData);
}, [showPending]);
useEffect(() => {
if (data?.length) {
filtering(data);
}
}, [data, showPending]); }, [data, showPending]);
const filteredSearchData = useMemo(() => {
if (!searchTerm) return processedData;
const lowercased = searchTerm.toLowerCase(); // New useEffect to handle search filtering
return processedData.filter((item) => const filteredSearchData = useMemo(() => {
`${item.firstName} ${item.lastName}`.toLowerCase().includes(lowercased) if (!searchTerm) {
return processedData;
}
const lowercasedSearchTerm = searchTerm.toLowerCase();
return processedData.filter((item) => {
const fullName = `${item.firstName} ${item.lastName}`.toLowerCase();
return fullName.includes(lowercasedSearchTerm);
});
}, [processedData, searchTerm]);
const {
currentPage,
totalPages,
currentItems: paginatedAttendances,
paginate,
resetPage,
} = usePagination(filteredSearchData, 20);
useEffect(() => {
resetPage();
}, [filteredSearchData, resetPage]);
const handler = useCallback(
(msg) => {
const { startDate, endDate } = dateRange;
const checkIn = msg.response.checkInTime.substring(0, 10);
if (
selectedProject === msg.projectId &&
startDate <= checkIn &&
checkIn <= endDate
) {
queryClient.setQueriesData(["attendanceLogs"], (oldData) => {
if (!oldData) {
queryClient.invalidateQueries({ queryKey: ["attendanceLogs"] });
return;
}
const updatedAttendance = oldData.map((record) =>
record.id === msg.response.id
? { ...record, ...msg.response }
: record
);
filtering(updatedAttendance);
return updatedAttendance;
});
resetPage();
}
},
[selectedProject, dateRange, filtering, resetPage]
); );
}, [processedData, searchTerm]);
const { useEffect(() => {
currentPage, eventBus.on("attendance_log", handler);
totalPages, return () => eventBus.off("attendance_log", handler);
currentItems: paginatedAttendances, }, [handler]);
paginate,
resetPage,
} = usePagination(filteredSearchData, 20);
useEffect(() => { const employeeHandler = useCallback(
resetPage(); (msg) => {
}, [filteredSearchData]); const { startDate, endDate } = dateRange;
if (data.some((item) => item.employeeId == msg.employeeId)) {
// dispatch(
// fetchAttendanceData({
// ,
// fromDate: startDate,
// toDate: endDate,
// })
// );
const handler = useCallback( refetch()
(msg) => { }
const { startDate, endDate } = dateRange; },
const checkIn = msg.response.checkInTime.substring(0, 10); [selectedProject, dateRange, data, refetch]
);
if (selectedProject === msg.projectId && startDate <= checkIn && checkIn <= endDate) {
queryClient.setQueriesData(["attendanceLogs"], (oldData) => {
if (!oldData) {
queryClient.invalidateQueries({ queryKey: ["attendanceLogs"] });
return;
}
return oldData.map((record) =>
record.id === msg.response.id ? { ...record, ...msg.response } : record
);
});
resetPage();
}
},
[selectedProject, dateRange, resetPage]
);
useEffect(() => {
eventBus.on("attendance_log", handler);
return () => eventBus.off("attendance_log", handler);
}, [handler]);
const employeeHandler = useCallback(
(msg) => {
const { startDate, endDate } = dateRange;
if (data.some((item) => item.employeeId == msg.employeeId)) {
refetch();
}
},
[data, refetch]
);
useEffect(() => {
eventBus.on("employee", employeeHandler);
return () => eventBus.off("employee", employeeHandler);
}, [employeeHandler]);
useEffect(() => {
eventBus.on("employee", employeeHandler);
return () => eventBus.off("employee", employeeHandler);
}, [employeeHandler]);
return ( return (
<> <>
<div <div
className="dataTables_length text-start py-2 d-flex justify-content-between " className="dataTables_length text-start py-2 d-flex justify-content-between"
id="DataTables_Table_0_length" id="DataTables_Table_0_length"
> >
<div className="d-flex align-items-center my-0 "> <div className="d-flex align-items-center my-0 ms-sm-8 ">
<DateRangePicker <DateRangePicker
onRangeChange={setDateRange} onRangeChange={setDateRange}
defaultStartDate={yesterday} defaultStartDate={yesterday}
/> />
<div className="form-check form-switch text-start ms-1 ms-md-2 align-items-center mb-0"> <div className="form-check form-switch text-start ms-1 ms-md-5 align-items-center mb-0">
<input <input
type="checkbox" type="checkbox"
className="form-check-input" className="form-check-input"
@ -193,16 +246,11 @@ useEffect(() => {
<label className="form-check-label ms-0">Show Pending</label> <label className="form-check-label ms-0">Show Pending</label>
</div> </div>
</div> </div>
</div> </div>
<div <div className="table-responsive text-nowrap " >
className="table-responsive text-nowrap"
style={{ minHeight: "200px" }}
>
{isLoading ? ( {isLoading ? (
<div <div className="d-flex justify-content-center align-items-center">
className="d-flex justify-content-center align-items-center"
style={{ height: "200px" }}
>
<p className="text-secondary">Loading...</p> <p className="text-secondary">Loading...</p>
</div> </div>
) : filteredSearchData?.length > 0 ? ( ) : filteredSearchData?.length > 0 ? (
@ -213,10 +261,10 @@ useEffect(() => {
Name Name
</th> </th>
<th className="border-top-1">Date</th> <th className="border-top-1">Date</th>
<th>Organization</th> {/* <th>Organization</th> */}
<th> <th>
<i className="bx bxs-down-arrow-alt text-success"></i>{" "} <i className="bx bxs-down-arrow-alt text-success"></i> Check-In
Check-In
</th> </th>
<th> <th>
<i className="bx bxs-up-arrow-alt text-danger"></i> Check-Out <i className="bx bxs-up-arrow-alt text-danger"></i> Check-Out
@ -232,9 +280,9 @@ useEffect(() => {
const previousAttendance = arr[index - 1]; const previousAttendance = arr[index - 1];
const previousDate = previousAttendance const previousDate = previousAttendance
? moment( ? moment(
previousAttendance.checkInTime || previousAttendance.checkInTime ||
previousAttendance.checkOutTime previousAttendance.checkOutTime
).format("YYYY-MM-DD") ).format("YYYY-MM-DD")
: null; : null;
if (!previousDate || currentDate !== previousDate) { if (!previousDate || currentDate !== previousDate) {
@ -260,7 +308,12 @@ useEffect(() => {
lastName={attendance.lastName} lastName={attendance.lastName}
/> />
<div className="d-flex flex-column"> <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"> <span className="fw-normal">
{attendance.firstName} {attendance.lastName} {attendance.firstName} {attendance.lastName}
</span> </span>
@ -273,7 +326,7 @@ useEffect(() => {
attendance.checkInTime || attendance.checkOutTime attendance.checkInTime || attendance.checkOutTime
).format("DD-MMM-YYYY")} ).format("DD-MMM-YYYY")}
</td> </td>
<td>{attendance.organizationName || "--"}</td> {/* <td>{attendance.organizationName || "--"}</td> */}
<td>{convertShortTime(attendance.checkInTime)}</td> <td>{convertShortTime(attendance.checkInTime)}</td>
<td> <td>
{attendance.checkOutTime {attendance.checkOutTime
@ -295,12 +348,7 @@ useEffect(() => {
</tbody> </tbody>
</table> </table>
) : ( ) : (
<div className="my-12"> <div className="my-12"><span className="text-secondary">No data for this date range. Please choose another.</span></div>
<span className="text-secondary">
No data available for the selected date range. Please Select
another date.
</span>
</div>
)} )}
</div> </div>
{paginatedAttendances?.length == 0 && filteredSearchData?.length > 0 && ( {paginatedAttendances?.length == 0 && filteredSearchData?.length > 0 && (
@ -312,47 +360,11 @@ useEffect(() => {
</div> </div>
)} )}
{filteredSearchData.length > ITEMS_PER_PAGE && ( {filteredSearchData.length > ITEMS_PER_PAGE && (
<nav aria-label="Page "> <Pagination
<ul className="pagination pagination-sm justify-content-end py-1"> currentPage={currentPage}
<li className={`page-item ${currentPage === 1 ? "disabled" : ""}`}> totalPages={totalPages}
<button onPageChange={paginate}
className="page-link btn-xs" />
onClick={() => paginate(currentPage - 1)}
>
&laquo;
</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)}
>
&raquo;
</button>
</li>
</ul>
</nav>
)} )}
</> </>
); );

View File

@ -1,4 +1,4 @@
import React, { useState } from "react"; import React, { useEffect, useState } from "react";
import { useForm } from "react-hook-form"; import { useForm } from "react-hook-form";
import { z } from "zod"; import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
@ -9,6 +9,7 @@ import showToast from "../../services/toastService";
import { checkIfCurrentDate } from "../../utils/dateUtils"; import { checkIfCurrentDate } from "../../utils/dateUtils";
import { useMarkAttendance } from "../../hooks/useAttendance"; import { useMarkAttendance } from "../../hooks/useAttendance";
import { useSelectedProject } from "../../slices/apiDataManager"; import { useSelectedProject } from "../../slices/apiDataManager";
import { useProjectName } from "../../hooks/useProjects";
const createSchema = (modeldata) => { const createSchema = (modeldata) => {
return z return z
@ -19,31 +20,36 @@ const createSchema = (modeldata) => {
.max(200, "Description should be less than 200 characters") .max(200, "Description should be less than 200 characters")
.optional(), .optional(),
}) })
.refine((data) => { .refine(
if (modeldata?.checkInTime && !modeldata?.checkOutTime) { (data) => {
const checkIn = new Date(modeldata.checkInTime); if (modeldata?.checkInTime && !modeldata?.checkOutTime) {
const [time, modifier] = data.markTime.split(" "); const checkIn = new Date(modeldata.checkInTime);
const [hourStr, minuteStr] = time.split(":"); const [time, modifier] = data.markTime.split(" ");
let hour = parseInt(hourStr, 10); const [hourStr, minuteStr] = time.split(":");
const minute = parseInt(minuteStr, 10); let hour = parseInt(hourStr, 10);
const minute = parseInt(minuteStr, 10);
if (modifier === "PM" && hour !== 12) hour += 12; if (modifier === "PM" && hour !== 12) hour += 12;
if (modifier === "AM" && hour === 12) hour = 0; if (modifier === "AM" && hour === 12) hour = 0;
const checkOut = new Date(checkIn); const checkOut = new Date(checkIn);
checkOut.setHours(hour, minute, 0, 0); checkOut.setHours(hour, minute, 0, 0);
return checkOut >= checkIn; return checkOut >= checkIn;
}
return true;
},
{
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 CheckInCheckOut = ({ modeldata, closeModal, handleSubmitForm }) => {
const [currentProject, setCurrentProject] = useState(null);
const projectId = useSelectedProject(); const projectId = useSelectedProject();
const { projectNames, loading } = useProjectName();
const { mutate: MarkAttendance } = useMarkAttendance(); const { mutate: MarkAttendance } = useMarkAttendance();
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const coords = usePositionTracker(); const coords = usePositionTracker();
@ -95,17 +101,24 @@ const CheckInCheckOut = ({ modeldata, closeModal, handleSubmitForm }) => {
closeModal(); closeModal();
}; };
useEffect(() => {
if (projectId && projectNames) {
setCurrentProject(
projectNames?.find((project) => project.id === projectId)
);
}
}, [projectNames, projectId, loading]);
return ( return (
<form className="row p-2" onSubmit={handleSubmit(onSubmit)}> <form className="row p-2" onSubmit={handleSubmit(onSubmit)}>
<div className="col-12 d-flex justify-content-center mb-4"> <div className="col-12 d-flex justify-content-center mt-2">
<label className="fs-5 tex-semibold text-center"> <label className="fs-5 text-dark text-center">
{modeldata?.checkInTime && !modeldata?.checkOutTime {modeldata?.checkInTime && !modeldata?.checkOutTime
? "Check-Out " ? `Check out for ${currentProject?.name}`
: "Check-In "} : `Check In for ${currentProject?.name}`}
</label> </label>
</div> </div>
<div className="col-6 col-md-6 text-start"> <div className="col-6 col-md-6 text-start">
<label className="form-label" htmlFor="checkInDate"> <label className="form-label" htmlFor="checkInDate">
{modeldata?.checkInTime && !modeldata?.checkOutTime {modeldata?.checkInTime && !modeldata?.checkOutTime
@ -120,7 +133,7 @@ const CheckInCheckOut = ({ modeldata, closeModal, handleSubmitForm }) => {
modeldata?.checkInTime && !modeldata?.checkOutTime modeldata?.checkInTime && !modeldata?.checkOutTime
? formatDate(modeldata?.checkInTime?.split("T")[0]) || "" ? formatDate(modeldata?.checkInTime?.split("T")[0]) || ""
: formatDate(today) : formatDate(today)
} }
disabled disabled
/> />
</div> </div>
@ -207,7 +220,7 @@ export const Regularization = ({ modeldata, closeModal, handleSubmitForm }) => {
}; };
return ( return (
<form className="row g-2" onSubmit={handleSubmit(onSubmit)}> <form className="row " onSubmit={handleSubmit(onSubmit)}>
<div className="col-12 col-md-12"> <div className="col-12 col-md-12">
<p>Regularize Attendance</p> <p>Regularize Attendance</p>
<label className="form-label" htmlFor="description"> <label className="form-label" htmlFor="description">

View File

@ -1,44 +1,40 @@
import React, { useCallback, useEffect, useState, useMemo } from "react"; import React, { useCallback, useEffect, useState, useMemo } from "react";
import Avatar from "../common/Avatar"; import Avatar from "../common/Avatar";
import { convertShortTime, formatUTCToLocalTime } from "../../utils/dateUtils"; import { convertShortTime } from "../../utils/dateUtils";
import RegularizationActions from "./RegularizationActions"; import RegularizationActions from "./RegularizationActions";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
import { useRegularizationRequests } from "../../hooks/useAttendance"; import { useRegularizationRequests } from "../../hooks/useAttendance";
import moment from "moment"; import moment from "moment";
import usePagination from "../../hooks/usePagination"; import usePagination from "../../hooks/usePagination";
import eventBus from "../../services/eventBus"; import eventBus from "../../services/eventBus";
import { import { cacheData, clearCacheKey, useSelectedProject } from "../../slices/apiDataManager";
cacheData,
clearCacheKey,
useSelectedProject,
} from "../../slices/apiDataManager";
import { useQueryClient } from "@tanstack/react-query"; import { useQueryClient } from "@tanstack/react-query";
import Pagination from "../../components/common/Pagination"; import Pagination from "../common/Pagination";
import { useNavigate } from "react-router-dom";
import { employee } from "../../data/masters";
const Regularization = ({ const Regularization = ({ handleRequest, searchTerm, projectId, organizationId, IncludeInActive }) => {
handleRequest,
searchTerm,
projectId,
organizationId,
IncludeInActive,
}) => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
// var selectedProject = useSelector((store) => store.localVariables.projectId); // var selectedProject = useSelector((store) => store.localVariables.projectId);
const selectedProject = useSelectedProject(); const selectedProject = useSelectedProject();
const [regularizesList, setregularizedList] = useState([]); const [regularizesList, setregularizedList] = useState([]);
const { regularizes, loading, error, refetch } = useRegularizationRequests( const navigate = useNavigate();
selectedProject, const { regularizes, loading, error, refetch } =
organizationId, useRegularizationRequests(selectedProject, organizationId, IncludeInActive);
IncludeInActive
);
useEffect(() => { useEffect(() => {
if(!regularizes) return if (regularizes && regularizes.length) {
if(regularizes?.length) { setregularizedList((prev) => {
setregularizedList(regularizes); const prevIds = prev.map((i) => i.id).join(",");
const newIds = regularizes.map((i) => i.id).join(",");
if (prevIds !== newIds) {
return regularizes;
}
return prev;
});
}
}, [regularizes]);
}
}, [regularizes]);
const sortByName = (a, b) => { const sortByName = (a, b) => {
const nameA = a.firstName.toLowerCase() + a.lastName.toLowerCase(); const nameA = a.firstName.toLowerCase() + a.lastName.toLowerCase();
@ -72,15 +68,48 @@ const Regularization = ({
} }
const lowercasedSearchTerm = searchTerm.toLowerCase(); const lowercasedSearchTerm = searchTerm.toLowerCase();
return sortedList.filter((item) => { return sortedList.filter((item) => {
const fullName = `${item?.firstName} ${item?.lastName}`.toLowerCase(); const fullName = `${item.firstName} ${item.lastName}`.toLowerCase();
return fullName.includes(lowercasedSearchTerm); return fullName.includes(lowercasedSearchTerm);
}); });
}, [regularizesList, searchTerm]); }, [regularizesList, searchTerm]);
const { currentPage, totalPages, currentItems, paginate } = usePagination( // const filteredSearchData = useMemo(() => {
filteredSearchData, // let sortedList = [...regularizesList].sort(sortByName);
20
); // // Search filter
// if (searchTerm) {
// const lowercasedSearchTerm = searchTerm.toLowerCase();
// sortedList = sortedList.filter((item) => {
// const fullName = `${item.firstName} ${item.lastName}`.toLowerCase();
// return fullName.includes(lowercasedSearchTerm);
// });
// }
// // Organization filter
// if (filters?.selectedOrganization) {
// sortedList = sortedList.filter(
// (item) => item.organization?.name === filters.selectedOrganization
// );
// }
// // Services filter
// if (filters?.selectedServices?.length > 0) {
// sortedList = sortedList.filter((item) =>
// filters.selectedServices.includes(item.service?.name)
// );
// }
// return sortedList;
// }, [regularizesList, searchTerm, filters]);
const { currentPage, totalPages, currentItems, paginate } =
usePagination(filteredSearchData, 20);
// Reset pagination when the search term or data changes
useEffect(() => {
}, [filteredSearchData]);
useEffect(() => { useEffect(() => {
eventBus.on("regularization", handler); eventBus.on("regularization", handler);
@ -101,16 +130,11 @@ const Regularization = ({
return () => eventBus.off("employee", employeeHandler); return () => eventBus.off("employee", employeeHandler);
}, [employeeHandler]); }, [employeeHandler]);
return ( return (
<div <div className="table-responsive text-nowrap pb-4" style={{ minHeight: "200px" }}>
className="table-responsive text-nowrap pb-4"
style={{ minHeight: "200px" }}
>
{loading ? ( {loading ? (
<div <div className="d-flex justify-content-center align-items-center" style={{ height: "200px" }}>
className="d-flex justify-content-center align-items-center"
style={{ height: "200px" }}
>
<p className="text-secondary">Loading...</p> <p className="text-secondary">Loading...</p>
</div> </div>
) : currentItems?.length > 0 ? ( ) : currentItems?.length > 0 ? (
@ -119,30 +143,40 @@ const Regularization = ({
<tr> <tr>
<th colSpan={2}>Name</th> <th colSpan={2}>Name</th>
<th>Date</th> <th>Date</th>
<th>Organization</th> {/* <th>Organization</th> */}
<th> <th>
<i className="bx bxs-down-arrow-alt text-success"></i>Check-In <i className="bx bxs-down-arrow-alt text-success"></i>Check-In
</th> </th>
<th> <th>
<i className="bx bxs-up-arrow-alt text-danger"></i>Check-Out <i className="bx bxs-up-arrow-alt text-danger"></i>Check-Out
</th> </th>
<th colSpan={2}>
Requested By <th>Request By</th>
</th> <th>Requested At</th>
<th >
Requested At
</th>
<th>Action</th> <th>Action</th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
{currentItems?.map((att, index) => ( {currentItems?.map((att, index) => (
<tr key={index}> <tr key={index}>
<td colSpan={2}> <td colSpan={2}>
<div className="d-flex justify-content-start align-items-center"> <div className="d-flex justify-content-start align-items-center">
<Avatar firstName={att.firstName} lastName={att.lastName} /> <Avatar
firstName={att.firstName}
lastName={att.lastName}
/>
<div className="d-flex flex-column"> <div className="d-flex flex-column">
<a href="#" className="text-heading text-truncate"> {/* <a href="#" className="text-heading text-truncate">
<span className="fw-normal">
{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"> <span className="fw-normal">
{att.firstName} {att.lastName} {att.firstName} {att.lastName}
</span> </span>
@ -150,29 +184,24 @@ const Regularization = ({
</div> </div>
</div> </div>
</td> </td>
<td>{moment(att.checkOutTime).format("DD-MMM-YYYY")}</td> <td>{moment(att.checkOutTime).format("DD-MMM-YYYY")}</td>
<td>{att.organizationName || "--"}</td> {/* <td>{att.organizationName || "--"}</td> */}
<td>{convertShortTime(att.checkInTime)}</td> <td>{convertShortTime(att.checkInTime)}</td>
<td> <td>
{att.requestedAt ? convertShortTime(att.checkOutTime) : "--"} {att.checkOutTime ? convertShortTime(att.checkOutTime) : "--"}
</td> </td>
<td>
<td colSpan={2}> {att.requestedBy
{att.requestedBy ? ( <div className="d-flex justify-content-start align-items-center"> ? `${att.requestedBy?.firstName} ${att.requestedBy?.lastName}`
<Avatar firstName={att?.requestedBy?.firstName} lastName={att?.requestedBy?.lastName} /> : "--"}
<div className="d-flex flex-column">
<a href="#" className="text-heading text-truncate">
<span className="fw-normal">
{att?.requestedBy?.firstName} {att?.requestedBy?.lastName}
</span>
</a>
</div>
</div>):(<small>--</small>)}
</td> </td>
<td> <td>
{att?.requestedAt ? formatUTCToLocalTime(att.requestedAt,true) : "--"} {att.requestedAt
? moment(att.requestedAt).format("DD-MMM-YYYY")
: "--"}
</td> </td>
<td className="text-center "> <td className="text-center ">
<RegularizationActions <RegularizationActions
@ -185,6 +214,7 @@ const Regularization = ({
))} ))}
</tbody> </tbody>
</table> </table>
) : ( ) : (
<div <div
className="d-flex justify-content-center align-items-center" className="d-flex justify-content-center align-items-center"
@ -197,47 +227,7 @@ const Regularization = ({
</span> </span>
</div> </div>
)} )}
{/* {!loading && totalPages > 1 && ( {!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)}
>
&laquo;
</button>
</li>
{[...Array(totalPages)].map((_, index) => (
<li
key={index}
className={`page-item ${currentPage === index + 1 ? "active" : ""
}`}
>
<button
className="page-link "
onClick={() => paginate(index + 1)}
>
{index + 1}
</button>
</li>
))}
<li
className={`page-item ${currentPage === totalPages ? "disabled" : ""
}`}
>
<button
className="page-link "
onClick={() => paginate(currentPage + 1)}
>
&raquo;
</button>
</li>
</ul>
</nav>
)} */}
{totalPages > 0 && (
<Pagination <Pagination
currentPage={currentPage} currentPage={currentPage}
totalPages={totalPages} totalPages={totalPages}

View File

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

View File

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

View File

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

View File

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

View File

@ -2,7 +2,7 @@ import React, { useState, useMemo } from "react";
import ApexChart from "../Charts/Circle"; import ApexChart from "../Charts/Circle";
import { useProjects } from "../../hooks/useProjects"; import { useProjects } from "../../hooks/useProjects";
import { useDashboard_AttendanceData } from "../../hooks/useDashboard_Data"; import { useDashboard_AttendanceData } from "../../hooks/useDashboard_Data";
import { useSelectedProject } from "../../hooks/useSelectedProject"; // your custom hook import { useSelectedProject } from "../../hooks/useSelectedProject";
const Attendance = () => { const Attendance = () => {
const { projects } = useProjects(); const { projects } = useProjects();
@ -31,7 +31,7 @@ const selectedProjectId = useSelectedProject()
<div className="card-header mb-1 pb-0"> <div className="card-header mb-1 pb-0">
<div className="d-flex flex-wrap justify-content-between align-items-center"> <div className="d-flex flex-wrap justify-content-between align-items-center">
<div className="card-title mb-0 text-start"> <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> <p className="card-subtitle">Daily Attendance Data</p>
</div> </div>

View File

@ -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;

View 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;

View File

@ -1,69 +1,63 @@
import React from "react"; import React, { useEffect, useState } from "react";
import { useSelector } from "react-redux"; import { useDispatch, useSelector } from "react-redux";
import { // import {
useDashboardProjectsCardData, // useDashboardProjectsCardData,
useDashboardTeamsCardData, // useDashboardTeamsCardData,
useDashboardTasksCardData, // useDashboardTasksCardData,
useAttendanceOverviewData // useAttendanceOverviewData
} from "../../hooks/useDashboard_Data"; // } from "../../hooks/useDashboard_Data";
import Projects from "./Projects"; // import Projects from "./Projects";
import Teams from "./Teams"; // import Teams from "./Teams";
import TasksCard from "./Tasks"; // import TasksCard from "./Tasks";
import ProjectCompletionChart from "./ProjectCompletionChart"; // import ProjectCompletionChart from "./ProjectCompletionChart";
import ProjectProgressChart from "./ProjectProgressChart"; // import ProjectProgressChart from "./ProjectProgressChart";
import ProjectOverview from "../Project/ProjectOverview"; // import ProjectOverview from "../Project/ProjectOverview";
import AttendanceOverview from "./AttendanceChart"; 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 Dashboard = () => {
const { projectsCardData } = useDashboardProjectsCardData(); // const { projectsCardData } = useDashboardProjectsCardData();
const { teamsCardData } = useDashboardTeamsCardData(); // const { teamsCardData } = useDashboardTeamsCardData();
const { tasksCardData } = useDashboardTasksCardData(); // const { tasksCardData } = useDashboardTasksCardData();
// Get the selected project ID from Redux store // Get the selected project ID from Redux store
const projectId = useSelector((store) => store.localVariables.projectId); const projectId = useSelector((store) => store.localVariables.projectId);
const isAllProjectsSelected = projectId === null; const isAllProjectsSelected = projectId === null;
return ( return (
<div className="container-fluid mt-5"> <div className="container-fluid py-5">
<div className="row gy-4"> <div className="row mb-6 g-6">
{isAllProjectsSelected && ( <div className="col-12 col-xl-8">
<div className="col-sm-6 col-lg-4"> <div className="card h-100">
<Projects projectsCardData={projectsCardData} /> <ExpenseAnalysis />
</div> </div>
)} </div>
<div className={`${!isAllProjectsSelected ? "col-sm-6 col-lg-6" : "col-sm-6 col-lg-4"}`}> <div className="col-12 col-xl-4 col-md-6">
<Teams teamsCardData={teamsCardData} /> <div className="card ">
</div> <ExpenseStatus />
</div>
</div>
</div>
<div className={`${!isAllProjectsSelected ? "col-sm-6 col-lg-6" : "col-sm-6 col-lg-4"}`}> <div className="row ">
<TasksCard tasksCardData={tasksCardData} /> {!isAllProjectsSelected && (
</div> <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;

View 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;

View 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;

View 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;

View File

@ -19,8 +19,11 @@ const AssignedBucket = ({ selectedBucket, handleClose }) => {
} }
}, [selectedBucket, employeesList]); }, [selectedBucket, employeesList]);
const { mutate: AssignEmployee, isPending } = useAssignEmpToBucket(() => const { mutate: AssignEmployee, isPending } = useAssignEmpToBucket(() =>{
setSelectedEmployees([])
handleClose() handleClose()
}
); );
const handleSubmit = async (e) => { const handleSubmit = async (e) => {

View File

@ -0,0 +1,56 @@
import React, { useMemo } from "react";
const ContactFilterChips = ({ filters, filterData, removeFilterChip, clearFilter }) => {
const data = filterData?.data || filterData || {};
const filterChips = useMemo(() => {
const chips = [];
const addGroup = (ids, list, label, key) => {
if (!ids?.length) return;
const items = ids.map((id) => ({
id,
name: list?.find((i) => i.id === id)?.name || id,
}));
chips.push({ key, label, items });
};
addGroup(filters.bucketIds, data.buckets, "Buckets", "bucketIds");
addGroup(filters.categoryIds, data.contactCategories, "Category", "categoryIds");
return chips;
}, [filters, filterData]);
if (!filterChips.length) return null;
return (
<div className="d-flex flex-wrap align-items-center gap-2">
{filterChips.map((chipGroup) => (
<div key={chipGroup.key} className="d-flex align-items-center flex-wrap">
<span className="fw-semibold me-2">{chipGroup.label}:</span>
{chipGroup.items.map((item) => (
<span
key={item.id}
className="d-flex align-items-center bg-light rounded px-2 py-1 me-1"
>
<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(chipGroup.key, item.id)}
/>
</span>
))}
</div>
))}
</div>
);
};
export default ContactFilterChips;

View File

@ -4,8 +4,9 @@ import Pagination from "../common/Pagination";
import { useDirectoryContext } from "../../pages/Directory/DirectoryPage"; import { useDirectoryContext } from "../../pages/Directory/DirectoryPage";
import { useActiveInActiveContact } from "../../hooks/useDirectory"; import { useActiveInActiveContact } from "../../hooks/useDirectory";
import ConfirmModal from "../common/ConfirmModal"; import ConfirmModal from "../common/ConfirmModal";
import Loader from "../common/Loader";
const ListViewContact = ({ data, Pagination }) => { const ListViewContact = ({ data, Pagination, isLoading }) => {
const { showActive, setManageContact, setContactOpen } = const { showActive, setManageContact, setContactOpen } =
useDirectoryContext(); useDirectoryContext();
const [deleteContact, setDeleteContact] = useState({ const [deleteContact, setDeleteContact] = useState({
@ -85,6 +86,8 @@ const ListViewContact = ({ data, Pagination }) => {
ActiveInActive({ contactId: contactId, contactStatus: !showActive }); 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 ( return (
<> <>
<ConfirmModal <ConfirmModal
@ -97,103 +100,97 @@ const ListViewContact = ({ data, Pagination }) => {
paramData={deleteContact.contactId} paramData={deleteContact.contactId}
isOpen={deleteContact.Open} isOpen={deleteContact.Open}
/> />
<div className="card "> <div className="card page-min-h">
<div <div
className="card-datatable table-responsive" className="card-datatable table-responsive"
id="horizontal-example" id="horizontal-example"
> >
<div className="dataTables_wrapper no-footer mx-5 pb-2">
<table className="table dataTable text-nowrap"> {data && (
<thead> <div className="dataTables_wrapper no-footer mx-5 pb-2">
<tr className="table_header_border"> <table className="table dataTable text-nowrap">
{contactList?.map((col) => ( <thead>
<th key={col.key} className={col.align}> <tr className="table_header_border">
{col.label} {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>
))}
<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 border-0 align-middle"
>
No contacts found
</td>
</tr> </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
</tbody> className="bx bx-edit text-secondary cursor-pointer"
</table> onClick={() =>
{Pagination && ( setManageContact({
<div className="d-flex justify-content-start"> isOpen: true,
{Pagination} contactId: row.id,
</div> })
)} }
</div> ></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>
</div> </div>
</> </>

View File

@ -23,7 +23,7 @@ import Label from "../common/Label";
const ManageContact = ({ contactId, closeModal }) => { const ManageContact = ({ contactId, closeModal }) => {
// fetch master data // fetch master data
const { buckets, loading: bucketsLoaging } = useBuckets(); const { buckets, loading: bucketsLoaging } = useBuckets();
const { data:projects, loading: projectLoading } = useProjects(); const { data: projects, loading: projectLoading } = useProjects();
const { contactCategory, loading: contactCategoryLoading } = const { contactCategory, loading: contactCategoryLoading } =
useContactCategory(); useContactCategory();
const { organizationList } = useOrganization(); const { organizationList } = useOrganization();
@ -205,13 +205,14 @@ const ManageContact = ({ contactId, closeModal }) => {
<Label htmlFor={"organization"} required> <Label htmlFor={"organization"} required>
Organization Organization
</Label> </Label>
<InputSuggestions <InputSuggestions
organizationList={organizationList} organizationList={organizationList}
value={watch("organization") || ""} value={watch("organization") || ""}
onChange={(val) => setValue("organization", val, { shouldValidate: true })} onChange={(val) =>
error={errors.organization?.message} setValue("organization", val, { shouldValidate: true })
/> }
error={errors.organization?.message}
/>
</div> </div>
</div> </div>
@ -394,6 +395,7 @@ const ManageContact = ({ contactId, closeModal }) => {
labelKey="name" labelKey="name"
valueKey="id" valueKey="id"
IsLoading={projectLoading} IsLoading={projectLoading}
/> />
{errors.projectIds && ( {errors.projectIds && (
<small className="danger-text">{errors.projectIds.message}</small> <small className="danger-text">{errors.projectIds.message}</small>
@ -408,6 +410,7 @@ const ManageContact = ({ contactId, closeModal }) => {
label="Tags" label="Tags"
options={contactTags} options={contactTags}
isRequired={true} isRequired={true}
require
/> />
{errors.tags && ( {errors.tags && (
<small className="danger-text">{errors.tags.message}</small> <small className="danger-text">{errors.tags.message}</small>
@ -417,7 +420,7 @@ const ManageContact = ({ contactId, closeModal }) => {
{/* Buckets */} {/* Buckets */}
<div className="row"> <div className="row">
<div className="col-md-12 mt-1 text-start"> <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"> <ul className="d-flex flex-wrap px-1 list-unstyled mb-0">
{bucketsLoaging && <p>Loading...</p>} {bucketsLoaging && <p>Loading...</p>}
{buckets?.map((item) => ( {buckets?.map((item) => (
@ -450,7 +453,7 @@ const ManageContact = ({ contactId, closeModal }) => {
</div> </div>
{/* Address + Description */} {/* Address + Description */}
<div className="col-12 text-start"> <div className="col-12 text-start mb-2">
<label className="form-label">Address</label> <label className="form-label">Address</label>
<textarea <textarea
className="form-control form-control-sm" className="form-control form-control-sm"
@ -459,7 +462,7 @@ const ManageContact = ({ contactId, closeModal }) => {
/> />
</div> </div>
<div className="col-12 text-start"> <div className="col-12 text-start">
<label className="form-label">Description</label> <Label required>Description</Label>
<textarea <textarea
className="form-control form-control-sm" className="form-control form-control-sm"
rows="2" rows="2"
@ -479,10 +482,13 @@ const ManageContact = ({ contactId, closeModal }) => {
> >
Cancel Cancel
</button> </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"} {isPending ? "Please Wait..." : "Submit"}
</button> </button>
</div> </div>
</form> </form>
</FormProvider> </FormProvider>

View File

@ -0,0 +1,79 @@
import React, { useMemo } from "react";
import moment from "moment";
const NoteFilterChips = ({ filters, filterData, removeFilterChip }) => {
// Normalize data (in case its wrapped in .data)
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 dynamically
buildGroup(filters.createdByIds, data.createdBy, "Created By", "createdByIds");
buildGroup(filters.organizations, data.organizations, "Organization", "organizations");
// Example: Add date range if you ever add in future
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-2">
{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 NoteFilterChips;

View 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;

View File

@ -1,4 +1,4 @@
import React, { useState } from "react"; import React, { useEffect, useState, useMemo, useImperativeHandle, forwardRef } from "react";
import { useDocumentFilterEntities } from "../../hooks/useDocument"; import { useDocumentFilterEntities } from "../../hooks/useDocument";
import { FormProvider, useForm } from "react-hook-form"; import { FormProvider, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
@ -9,16 +9,34 @@ import {
import { DateRangePicker1 } from "../common/DateRangePicker"; import { DateRangePicker1 } from "../common/DateRangePicker";
import SelectMultiple from "../common/SelectMultiple"; import SelectMultiple from "../common/SelectMultiple";
import moment from "moment"; 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 [resetKey, setResetKey] = useState(0);
const { status } = useParams();
const { data, isError, isLoading, error } = const { data, isError, isLoading, error } =
useDocumentFilterEntities(entityTypeId); 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({ const methods = useForm({
resolver: zodResolver(DocumentFilterSchema), resolver: zodResolver(DocumentFilterSchema),
defaultValues: DocumentFilterDefaultValues, defaultValues: dynamicDocumentFilterDefaultValues,
}); });
const { handleSubmit, reset, setValue, watch } = methods; const { handleSubmit, reset, setValue, watch } = methods;
@ -32,6 +50,24 @@ const DocumentFilterPanel = ({ entityTypeId, onApply }) => {
document.querySelector(".offcanvas.show .btn-close")?.click(); 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) => { const onSubmit = (values) => {
onApply({ onApply({
...values, ...values,
@ -63,6 +99,8 @@ const DocumentFilterPanel = ({ entityTypeId, onApply }) => {
documentTag = [], documentTag = [],
} = data?.data || {}; } = data?.data || {};
return ( return (
<FormProvider {...methods}> <FormProvider {...methods}>
<form onSubmit={handleSubmit(onSubmit)}> <form onSubmit={handleSubmit(onSubmit)}>
@ -73,18 +111,16 @@ const DocumentFilterPanel = ({ entityTypeId, onApply }) => {
<div className="d-inline-flex border rounded-pill overflow-hidden shadow-none"> <div className="d-inline-flex border rounded-pill overflow-hidden shadow-none">
<button <button
type="button" type="button"
className={`btn px-2 py-1 rounded-0 text-tiny ${ className={`btn px-2 py-1 rounded-0 text-tiny ${isUploadedAt ? "active btn-secondary text-white" : ""
isUploadedAt ? "active btn-secondary text-white" : "" }`}
}`}
onClick={() => setValue("isUploadedAt", true)} onClick={() => setValue("isUploadedAt", true)}
> >
Uploaded On Uploaded On
</button> </button>
<button <button
type="button" type="button"
className={`btn px-2 py-1 rounded-0 text-tiny ${ className={`btn px-2 py-1 rounded-0 text-tiny ${!isUploadedAt ? "active btn-secondary text-white" : ""
!isUploadedAt ? "active btn-secondary text-white" : "" }`}
}`}
onClick={() => setValue("isUploadedAt", false)} onClick={() => setValue("isUploadedAt", false)}
> >
Updated On Updated On
@ -189,18 +225,18 @@ const DocumentFilterPanel = ({ entityTypeId, onApply }) => {
<div className="d-flex justify-content-end py-3 gap-2"> <div className="d-flex justify-content-end py-3 gap-2">
<button <button
type="button" type="button"
className="btn btn-label-secondary btn-xs" className="btn btn-label-secondary btn-sm"
onClick={onClear} onClick={onClear}
> >
Clear Clear
</button> </button>
<button type="submit" className="btn btn-primary btn-xs"> <button type="submit" className="btn btn-primary btn-sm">
Apply Apply
</button> </button>
</div> </div>
</form> </form>
</FormProvider> </FormProvider>
); );
}; });
export default DocumentFilterPanel; export default DocumentFilterPanel;

View File

@ -17,54 +17,56 @@ const SkeletonCell = ({
/> />
); );
export const DocumentTableSkeleton = ({ rows = 5 }) => { export const DocumentTableSkeleton = ({ rows = 10 }) => {
return ( 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"> <tbody>
<thead> {[...Array(rows)].map((_, idx) => (
<tr> <tr key={idx} className={idx % 2 === 0 ? "odd" : "even"}>
<th className="text-start">Name</th> {/* Name */}
<th className="text-start">Document Type</th> <td className="text-start">
<th className="text-start">Uploaded By</th> <SkeletonCell width="120px" height={16} />
<th className="text-center">Uploaded on</th> </td>
<th className="text-center">Status</th>
</tr>
</thead>
<tbody> {/* Document Type */}
{[...Array(rows)].map((_, idx) => ( <td className="text-start">
<tr key={idx} className={idx % 2 === 0 ? "odd" : "even"}> <SkeletonCell width="100px" height={16} />
{/* Name */} </td>
<td className="text-start">
<SkeletonCell width="120px" height={16} />
</td>
{/* Document Type */} {/* Uploaded By (Avatar + Name) */}
<td className="text-start"> <td className="text-start">
<SkeletonCell width="100px" height={16} /> <div className="d-flex align-items-center gap-2">
</td> <SkeletonCell
width="30px"
{/* Uploaded By (Avatar + Name) */} height={30}
<td className="text-start"> className="rounded-circle"
<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">
<SkeletonCell width="80px" height={16} /> <SkeletonCell width="80px" height={16} />
</td> </div>
</td>
{/* Status */} {/* Uploaded on */}
<td className="text-center"> <td className="text-center">
<SkeletonCell width="70px" height={20} className="rounded" /> <SkeletonCell width="80px" height={16} />
</td> </td>
</tr>
))} {/* Status */}
</tbody> <td className="text-center">
</table> <SkeletonCell width="70px" height={20} className="rounded" />
</td>
</tr>
))}
</tbody>
</table>
); );
}; };

View File

@ -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 GlobalModel from "../common/GlobalModel";
import NewDocument from "./ManageDocument"; import NewDocument from "./ManageDocument";
import { DOCUMENTS_ENTITIES, UPLOAD_DOCUMENT } from "../../utils/constants"; import { DOCUMENTS_ENTITIES, UPLOAD_DOCUMENT } from "../../utils/constants";
@ -17,6 +17,7 @@ import ViewDocument from "./ViewDocument";
import DocumentViewerModal from "./DocumentViewerModal"; import DocumentViewerModal from "./DocumentViewerModal";
import { useHasUserPermission } from "../../hooks/useHasUserPermission"; import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { useProfile } from "../../hooks/useProfile"; import { useProfile } from "../../hooks/useProfile";
import DocumentFilterChips from "./DocumentFilterChips";
// Context // Context
export const DocumentContext = createContext(); export const DocumentContext = createContext();
@ -51,12 +52,14 @@ const Documents = ({ Document_Entity, Entity }) => {
const [isSelf, setIsSelf] = useState(false); const [isSelf, setIsSelf] = useState(false);
const [searchText, setSearchText] = useState(""); const [searchText, setSearchText] = useState("");
const [isActive, setIsActive] = useState(true); const [isActive, setIsActive] = useState(true);
const [filters, setFilter] = useState(); const [filters, setFilter] = useState(DocumentFilterDefaultValues);
const [isRefetching, setIsRefetching] = useState(false); const [isRefetching, setIsRefetching] = useState(false);
const [refetchFn, setRefetchFn] = useState(null); const [refetchFn, setRefetchFn] = useState(null);
const [DocumentEntity, setDocumentEntity] = useState(Document_Entity); const [DocumentEntity, setDocumentEntity] = useState(Document_Entity);
const { employeeId } = useParams(); const { employeeId } = useParams();
const [OpenDocument, setOpenDocument] = useState(false); const [OpenDocument, setOpenDocument] = useState(false);
const [filterData, setFilterdata] = useState(DocumentFilterDefaultValues);
const updatedRef = useRef();
const [ManageDoc, setManageDoc] = useState({ const [ManageDoc, setManageDoc] = useState({
document: null, document: null,
isOpen: false, isOpen: false,
@ -92,7 +95,7 @@ const Documents = ({ Document_Entity, Entity }) => {
setShowTrigger(true); setShowTrigger(true);
setOffcanvasContent( setOffcanvasContent(
"Document Filters", "Document Filters",
<DocumentFilterPanel entityTypeId={DocumentEntity} onApply={setFilter} /> <DocumentFilterPanel entityTypeId={DocumentEntity} onApply={setFilter} setFilterdata={setFilterdata} ref={updatedRef} />
); );
return () => { return () => {
@ -115,13 +118,40 @@ const Documents = ({ Document_Entity, Entity }) => {
setDocumentEntity(Document_Entity); setDocumentEntity(Document_Entity);
} }
}, [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 ( return (
<DocumentContext.Provider value={contextValues}> <DocumentContext.Provider value={contextValues}>
<div className="mt-5"> <div className="mt-2">
<div className="card page-min-h d-flex p-2"> <div className="card page-min-h d-flex p-5">
<DocumentFilterChips filters={filters} filterData={filterData} removeFilterChip={removeFilterChip} />
<div className="row align-items-center"> <div className="row align-items-center">
{/* Search */} {/* 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"> <div className="d-flex">
{" "} {" "}
<input <input
@ -149,7 +179,7 @@ const Documents = ({ Document_Entity, Entity }) => {
</label> </label>
</div> </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) && ( {(isSelf || canUploadDocument) && (
<button <button
className="btn btn-sm btn-primary me-3" className="btn btn-sm btn-primary me-3"
@ -231,4 +261,4 @@ const Documents = ({ Document_Entity, Entity }) => {
); );
}; };
export default Documents; export default Documents;

View File

@ -65,7 +65,7 @@ const DocumentsList = ({
setIsRefetching(isFetching); setIsRefetching(isFetching);
}, [isFetching, setIsRefetching]); }, [isFetching, setIsRefetching]);
const { setManageDoc, setViewDoc } = useDocumentContext(); const { setManageDoc, setViewDoc,removeFilterChip } = useDocumentContext();
const { mutate: ActiveInActive, isPending } = useActiveInActiveDocument(); const { mutate: ActiveInActive, isPending } = useActiveInActiveDocument();
const paginate = (page) => { const paginate = (page) => {
@ -82,9 +82,9 @@ const DocumentsList = ({
if (isLoading || isFetching) return <DocumentTableSkeleton />; if (isLoading || isFetching) return <DocumentTableSkeleton />;
if (isError) if (isError)
return <div>Error: {error?.message || "Something went wrong"}</div>; return <div>Error: {error?.message || "Something went wrong"}</div>;
if (isInitialEmpty) return <div>No documents found yet.</div>; if (isInitialEmpty) return <div className="py-12 my-12">No documents found yet.</div>;
if (isSearchEmpty) return <div>No results found for "{debouncedSearch}"</div>; if (isSearchEmpty) return <div className="py-12 my-12">No results found for "{debouncedSearch}"</div>;
if (isFilterEmpty) return <div>No documents match your filter.</div>; if (isFilterEmpty) return <div className="py-12 my-12">No documents match your filter.</div>;
const handleDelete = () => { const handleDelete = () => {
ActiveInActive( 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"> <table className="table border-top dataTable text-nowrap">
<thead> <thead className="">
<tr className="shadow-sm"> <tr className="py-2 ">
{DocumentColumns.map((col) => ( {DocumentColumns.map((col) => (
<th key={col.key} className={`sorting ${col.align}`}> <th key={col.key} className={`sorting ${col.align}`}>
{col.label} {col.label}

View File

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

View File

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

View File

@ -12,11 +12,11 @@ const EmpDashboard = ({ profile }) => {
return ( return (
<> <>
<div className="row"> <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> <EmpOverview profile={profile}></EmpOverview>
</div> </div>
<div className="col col-sm-6 pt-5"> {/* <div className="col col-sm-6 pt-5">
<div className="card "> <div className="card ">
<div className="card-body"> <div className="card-body">
<small className="card-text text-uppercase text-body-secondary small text-start d-block"> <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" className="d-flex mb-4 align-items-start flex-wrap"
key={project.id} key={project.id}
> >
{/* Project Info */}
<div className="flex-grow-1"> <div className="flex-grow-1">
<div className="d-flex flex-wrap align-items-center justify-content-between gap-2"> <div className="d-flex flex-wrap align-items-center justify-content-between gap-2">
<div className="d-flex"> <div className="d-flex">
@ -70,7 +69,6 @@ const EmpDashboard = ({ profile }) => {
</div> </div>
</div> </div>
{/* Dates */}
</div> </div>
</li> </li>
@ -79,7 +77,7 @@ const EmpDashboard = ({ profile }) => {
</div> </div>
</div> </div>
</div> </div> */}
</div> </div>
</> </>
); );

View File

@ -24,7 +24,7 @@ const EmployeeNav = ({ onPillClick, activePill }) => {
icon: "bx bx-file", icon: "bx bx-file",
label: "Documents", label: "Documents",
}, },
{ key: "activities", icon: "bx bx-grid-alt", label: "Activities" }, // { key: "activities", icon: "bx bx-grid-alt", label: "Activities" },
].filter(Boolean); ].filter(Boolean);
return ( return (
<div className="col-md-12"> <div className="col-md-12">

View File

@ -90,7 +90,7 @@ export const employeeSchema =
.min(1, { message: "Phone Number is required" }) .min(1, { message: "Phone Number is required" })
.regex(mobileNumberRegex, { message: "Invalid phone number " }), .regex(mobileNumberRegex, { message: "Invalid phone number " }),
jobRoleId: z.string().min(1, { message: "Role is required" }), 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), hasApplicationAccess:z.boolean().default(false),
}).refine((data) => { }).refine((data) => {
if (data.hasApplicationAccess) { if (data.hasApplicationAccess) {
@ -119,6 +119,6 @@ export const defatEmployeeObj = {
permanentAddress: "", permanentAddress: "",
phoneNumber: "", phoneNumber: "",
jobRoleId: null, jobRoleId: null,
organizationId:"", // organizationId:"",
hasApplicationAccess:false hasApplicationAccess:false
} }

View File

@ -15,18 +15,18 @@ import {
import Label from "../common/Label"; import Label from "../common/Label";
import DatePicker from "../common/DatePicker"; import DatePicker from "../common/DatePicker";
import { defatEmployeeObj, employeeSchema } from "./EmployeeSchema"; import { defatEmployeeObj, employeeSchema } from "./EmployeeSchema";
import { useOrganizationsList } from "../../hooks/useOrganization"; // import { useOrganizationsList } from "../../hooks/useOrganization";
import { ITEMS_PER_PAGE } from "../../utils/constants"; import { ITEMS_PER_PAGE } from "../../utils/constants";
const ManageEmployee = ({ employeeId, onClosed }) => { const ManageEmployee = ({ employeeId, onClosed, IsAllEmployee }) => {
const dispatch = useDispatch(); const dispatch = useDispatch();
const { mutate: updateEmployee, isPending } = useUpdateEmployee(); const { mutate: updateEmployee, isPending } = useUpdateEmployee();
const { // const {
data: organzationList, // data: organzationList,
isLoading, // isLoading,
isError, // isError,
error: EempError, // error: EempError,
} = useOrganizationsList(ITEMS_PER_PAGE, 1, true); // } = useOrganizationsList(ITEMS_PER_PAGE, 1, true);
const { const {
employee, employee,
error, error,
@ -72,7 +72,7 @@ const ManageEmployee = ({ employeeId, onClosed }) => {
data.email = null; data.email = null;
} }
const payload = { ...data }; const payload = { ...data, IsAllEmployee };
if (employeeId) { if (employeeId) {
payload.id = employeeId; payload.id = employeeId;
@ -113,7 +113,7 @@ const ManageEmployee = ({ employeeId, onClosed }) => {
permanentAddress: currentEmployee.permanentAddress || "", permanentAddress: currentEmployee.permanentAddress || "",
phoneNumber: currentEmployee.phoneNumber || "", phoneNumber: currentEmployee.phoneNumber || "",
jobRoleId: currentEmployee.jobRoleId?.toString() || "", jobRoleId: currentEmployee.jobRoleId?.toString() || "",
organizationId: currentEmployee.organizationId || "", // organizationId: currentEmployee.organizationId || "", // Hide temp. for version 1
hasApplicationAccess: currentEmployee.hasApplicationAccess || false, hasApplicationAccess: currentEmployee.hasApplicationAccess || false,
} }
: {} : {}
@ -413,9 +413,10 @@ const ManageEmployee = ({ employeeId, onClosed }) => {
</div> </div>
</div> </div>
{/* -------------- */}
<div className="row mb-3"> <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> <Label className="form-text text-start" required>
Organization Organization
</Label> </Label>
@ -446,9 +447,10 @@ const ManageEmployee = ({ employeeId, onClosed }) => {
{errors.organizationId.message} {errors.organizationId.message}
</div> </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"> <label className="form-check-label d-flex align-items-center">
<input <input
type="checkbox" type="checkbox"
@ -584,15 +586,14 @@ const ManageEmployee = ({ employeeId, onClosed }) => {
)} )}
</div> </div>
</div> </div>
<div className="row text-end"> <div className="d-flex flex-row gap-3 justify-content-end">
<div className="col-sm-12">
<button <button
aria-label="manage employee" aria-label="manage employee"
type="reset"
className="btn btn-sm btn-label-secondary me-2" className="btn btn-sm btn-label-secondary me-2"
disabled={isPending} disabled={isPending}
onClick={()=>onClosed()}
> >
Clear Close
</button> </button>
<button <button
aria-label="manage employee" aria-label="manage employee"
@ -600,9 +601,8 @@ const ManageEmployee = ({ employeeId, onClosed }) => {
className="btn btn-sm btn-primary" className="btn btn-sm btn-primary"
disabled={isPending} disabled={isPending}
> >
{isPending ? "Please Wait..." : employeeId ? "Update" : "Create"} {isPending ? "Please Wait..." : employeeId ? "Update" : "Submit"}
</button> </button>
</div>
</div> </div>
</form> </form>
</> </>

View 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;

View 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;

View File

@ -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 { FormProvider, useForm, Controller } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import { defaultFilter, SearchSchema } from "./ExpenseSchema"; import { defaultFilter, SearchSchema } from "./ExpenseSchema";
@ -13,9 +13,11 @@ import { useSelector } from "react-redux";
import moment from "moment"; import moment from "moment";
import { useExpenseFilter } from "../../hooks/useExpense"; import { useExpenseFilter } from "../../hooks/useExpense";
import { ExpenseFilterSkeleton } from "./ExpenseSkeleton"; 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( const selectedProjectId = useSelector(
(store) => store.localVariables.projectId (store) => store.localVariables.projectId
); );
@ -29,17 +31,31 @@ const ExpenseFilterPanel = ({ onApply, handleGroupBy }) => {
{ id: "submittedBy", name: "Submitted By" }, { id: "submittedBy", name: "Submitted By" },
{ id: "project", name: "Project" }, { id: "project", name: "Project" },
{ id: "paymentMode", name: "Payment Mode" }, { id: "paymentMode", name: "Payment Mode" },
{ id: "expensesType", name: "Expense Type" }, { id: "expensesType", name: "Expense Category" },
{ id: "createdAt", name: "Submitted Date" }, { id: "createdAt", name: "Submitted Date" },
].sort((a, b) => a.name.localeCompare(b.name)); ].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 [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({ const methods = useForm({
resolver: zodResolver(SearchSchema), resolver: zodResolver(SearchSchema),
defaultValues: defaultFilter, defaultValues: dynamicDefaultFilter,
}); });
const { control, handleSubmit, reset, setValue, watch } = methods; const { control, handleSubmit, reset, setValue, watch } = methods;
@ -49,11 +65,30 @@ const ExpenseFilterPanel = ({ onApply, handleGroupBy }) => {
document.querySelector(".offcanvas.show .btn-close")?.click(); document.querySelector(".offcanvas.show .btn-close")?.click();
}; };
// Change here
useEffect(() => {
if (data && setFilterdata) {
setFilterdata(data);
}
}, [data, setFilterdata]);
const handleGroupChange = (e) => { const handleGroupChange = (e) => {
const group = groupByList.find((g) => g.id === e.target.value); const group = groupByList.find((g) => g.id === e.target.value);
if (group) setSelectedGroup(group); 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) => { const onSubmit = (formData) => {
onApply({ onApply({
...formData, ...formData,
@ -71,17 +106,55 @@ const ExpenseFilterPanel = ({ onApply, handleGroupBy }) => {
onApply(defaultFilter); onApply(defaultFilter);
handleGroupBy(groupByList[0].id); handleGroupBy(groupByList[0].id);
closePanel(); closePanel();
if (status) {
navigate("/expenses", { replace: true });
}
}; };
// Close popup when navigating to another component
const location = useLocation(); const location = useLocation();
useEffect(() => { useEffect(() => {
closePanel(); closePanel();
}, [location]); }, [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 (isLoading || isFetching) return <ExpenseFilterSkeleton />;
if (isError && isFetched) if (isError && isFetched)
return <div>Something went wrong Here- {error.message} </div>; return <div>Something went wrong Here- {error.message} </div>;
return ( return (
<> <>
<FormProvider {...methods}> <FormProvider {...methods}>
@ -92,18 +165,16 @@ const ExpenseFilterPanel = ({ onApply, handleGroupBy }) => {
<div className="d-inline-flex border rounded-pill mb-1 overflow-hidden shadow-none"> <div className="d-inline-flex border rounded-pill mb-1 overflow-hidden shadow-none">
<button <button
type="button" type="button"
className={`btn px-2 py-1 rounded-0 text-tiny ${ className={`btn px-2 py-1 rounded-0 text-tiny ${isTransactionDate ? "active btn-primary text-white" : ""
isTransactionDate ? "active btn-primary text-white" : "" }`}
}`}
onClick={() => setValue("isTransactionDate", true)} onClick={() => setValue("isTransactionDate", true)}
> >
Transaction Date Transaction Date
</button> </button>
<button <button
type="button" type="button"
className={`btn px-2 py-1 rounded-0 text-tiny ${ className={`btn px-2 py-1 rounded-0 text-tiny ${!isTransactionDate ? "active btn-primary text-white" : ""
!isTransactionDate ? "active btn-primary text-white" : "" }`}
}`}
onClick={() => setValue("isTransactionDate", false)} onClick={() => setValue("isTransactionDate", false)}
> >
Submitted Date Submitted Date
@ -143,6 +214,13 @@ const ExpenseFilterPanel = ({ onApply, handleGroupBy }) => {
labelKey={(item) => item.name} labelKey={(item) => item.name}
valueKey="id" valueKey="id"
/> />
<SelectMultiple
name="ExpenseTypeIds"
label="Category :"
options={data.expensesType}
labelKey={(item) => item.name}
valueKey="id"
/>
<div className="mb-3"> <div className="mb-3">
<label className="form-label">Status :</label> <label className="form-label">Status :</label>
@ -214,6 +292,6 @@ const ExpenseFilterPanel = ({ onApply, handleGroupBy }) => {
</FormProvider> </FormProvider>
</> </>
); );
}; });
export default ExpenseFilterPanel; export default ExpenseFilterPanel;

View File

@ -10,20 +10,29 @@ import {
EXPENSE_REJECTEDBY, EXPENSE_REJECTEDBY,
ITEMS_PER_PAGE, ITEMS_PER_PAGE,
} from "../../utils/constants"; } from "../../utils/constants";
import { getColorNameFromHex, useDebounce } from "../../utils/appUtils"; import {
formatCurrency,
getColorNameFromHex,
useDebounce,
} from "../../utils/appUtils";
import { ExpenseTableSkeleton } from "./ExpenseSkeleton"; import { ExpenseTableSkeleton } from "./ExpenseSkeleton";
import ConfirmModal from "../common/ConfirmModal"; import ConfirmModal from "../common/ConfirmModal";
import { useHasUserPermission } from "../../hooks/useHasUserPermission"; import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { useSelector } from "react-redux"; 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 ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
const [deletingId, setDeletingId] = useState(null); const [deletingId, setDeletingId] = useState(null);
const [IsDeleteModalOpen, setIsDeleteModalOpen] = useState(false); const [IsDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
const { setViewExpense, setManageExpenseModal } = useExpenseContext(); const { setViewExpense, setManageExpenseModal, filterData, removeFilterChip } = useExpenseContext();
const IsExpenseEditable = useHasUserPermission(); const IsExpenseEditable = useHasUserPermission();
const IsExpesneApprpve = useHasUserPermission(APPROVE_EXPENSE); const IsExpesneApprpve = useHasUserPermission(APPROVE_EXPENSE);
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
const debouncedSearch = useDebounce(searchText, 500); const debouncedSearch = useDebounce(searchText, 500);
const navigate = useNavigate();
const { mutate: DeleteExpense, isPending } = useDeleteExpense(); const { mutate: DeleteExpense, isPending } = useDeleteExpense();
const { data, isLoading, isError, isInitialLoading, error } = useExpenseList( const { data, isLoading, isError, isInitialLoading, error } = useExpenseList(
@ -59,40 +68,60 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
const groupByField = (items, field) => { const groupByField = (items, field) => {
return items.reduce((acc, item) => { return items.reduce((acc, item) => {
let key; let key;
let displayField;
switch (field) { switch (field) {
case "transactionDate": case "transactionDate":
key = item.transactionDate?.split("T")[0]; key = item?.transactionDate?.split("T")[0];
displayField = "Transaction Date";
break; break;
case "status": case "status":
key = item.status?.displayName || "Unknown"; key = item?.status?.displayName || "Unknown";
displayField = "Status";
break; break;
case "submittedBy": case "submittedBy":
key = `${item.createdBy?.firstName ?? ""} ${ key = `${item?.createdBy?.firstName ?? ""} ${item.createdBy?.lastName ?? ""
item.createdBy?.lastName ?? "" }`.trim();
}`.trim(); displayField = "Submitted By";
break; break;
case "project": case "project":
key = item.project?.name || "Unknown Project"; key = item?.project?.name || "Unknown Project";
displayField = "Project";
break; break;
case "paymentMode": case "paymentMode":
key = item.paymentMode?.name || "Unknown Mode"; key = item?.paymentMode?.name || "Unknown Mode";
displayField = "Payment Mode";
break; break;
case "expensesType": case "expensesType":
key = item.expensesType?.name || "Unknown Type"; key = item?.expensesType?.name || "Unknown Type";
displayField = "Expense Category";
break; break;
case "createdAt": case "createdAt":
key = item.createdAt?.split("T")[0] || "Unknown Type"; key = item?.createdAt?.split("T")[0] || "Unknown Date";
displayField = "Created Date";
break; break;
default: default:
key = "Others"; 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; return acc;
}, {}); }, {});
}; };
const expenseColumns = [ const expenseColumns = [
{
key: "expenseUId",
label: "Expense Id",
getValue: (e) => e.expenseUId || "N/A",
align: "text-start mx-2",
},
{ {
key: "expensesType", key: "expensesType",
label: "Expense Type", label: "Expense Type",
@ -110,11 +139,11 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
label: "Submitted By", label: "Submitted By",
align: "text-start", align: "text-start",
getValue: (e) => getValue: (e) =>
`${e.createdBy?.firstName ?? ""} ${ `${e.createdBy?.firstName ?? ""} ${e.createdBy?.lastName ?? ""
e.createdBy?.lastName ?? "" }`.trim() || "N/A",
}`.trim() || "N/A",
customRender: (e) => ( 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 <Avatar
size="xs" size="xs"
classAvatar="m-0" classAvatar="m-0"
@ -122,9 +151,8 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
lastName={e.createdBy?.lastName} lastName={e.createdBy?.lastName}
/> />
<span className="text-truncate"> <span className="text-truncate">
{`${e.createdBy?.firstName ?? ""} ${ {`${e.createdBy?.firstName ?? ""} ${e.createdBy?.lastName ?? ""
e.createdBy?.lastName ?? "" }`.trim() || "N/A"}
}`.trim() || "N/A"}
</span> </span>
</div> </div>
), ),
@ -138,11 +166,7 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
{ {
key: "amount", key: "amount",
label: "Amount", label: "Amount",
getValue: (e) => ( getValue: (e) => <>{formatCurrency(e?.amount)}</>,
<>
<i className="bx bx-rupee b-xs"></i> {e?.amount}
</>
),
isAlwaysVisible: true, isAlwaysVisible: true,
align: "text-end", align: "text-end",
}, },
@ -152,9 +176,8 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
align: "text-center", align: "text-center",
getValue: (e) => ( getValue: (e) => (
<span <span
className={`badge bg-label-${ className={`badge bg-label-${getColorNameFromHex(e?.status?.color) || "secondary"
getColorNameFromHex(e?.status?.color) || "secondary" }`}
}`}
> >
{e.status?.name || "Unknown"} {e.status?.name || "Unknown"}
</span> </span>
@ -162,27 +185,32 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
}, },
]; ];
if (isInitialLoading) return <ExpenseTableSkeleton />; if (isInitialLoading && !data) return <ExpenseTableSkeleton />;
if (isError) return <div>{error.message}</div>; if (isError) return <div>{error?.message}</div>;
const grouped = groupBy const grouped = groupBy
? groupByField(data?.data ?? [], groupBy) ? groupByField(data?.data ?? [], groupBy)
: { All: data?.data ?? [] }; : { 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) => { const canEditExpense = (expense) => {
return ( return (
(expense.status.id === EXPENSE_DRAFT || (expense?.status?.id === EXPENSE_DRAFT ||
EXPENSE_REJECTEDBY.includes(expense.status.id)) && EXPENSE_REJECTEDBY.includes(expense?.status?.id)) &&
expense.createdBy?.id === SelfId expense?.createdBy?.id === SelfId
); );
}; };
const canDetetExpense = (expense) => { const canDetetExpense = (expense) => {
return ( return (
expense.status.id === EXPENSE_DRAFT && expense.createdBy.id === SelfId expense?.status?.id === EXPENSE_DRAFT && expense?.createdBy?.id === SelfId
); );
}; };
return ( return (
<> <>
{IsDeleteModalOpen && ( {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 <div
className="card-datatable table-responsive " className="card-datatable table-responsive "
id="horizontal-example" id="horizontal-example"
> >
<div className="dataTables_wrapper no-footer px-2 "> <div className="dataTables_wrapper no-footer px-2 ">
<table className="table border-top dataTable text-nowrap"> <table className="table border-top dataTable text-nowrap">
<thead> <thead>
@ -226,18 +264,24 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
</thead> </thead>
<tbody> <tbody>
{Object.keys(grouped).length > 0 ? ( {Object.keys(grouped).length > 0 ? (
Object.entries(grouped).map(([group, expenses]) => ( Object.values(grouped).map(({ key, displayField, items }) => (
<React.Fragment key={group}> <React.Fragment key={key}>
<tr className="tr-group text-dark"> <tr className="tr-group text-dark">
<td colSpan={8} className="text-start"> <td colSpan={8} className="text-start">
<strong> <div className="d-flex align-items-center">
{IsGroupedByDate {" "}
? formatUTCToLocalTime(group) <small className="fs-6 py-1">
: group} {displayField} :{" "}
</strong> </small>{" "}
<small className="fs-6 ms-3">
{IsGroupedByDate
? formatUTCToLocalTime(key)
: key}
</small>
</div>
</td> </td>
</tr> </tr>
{expenses.map((expense) => ( {items?.map((expense) => (
<tr key={expense.id}> <tr key={expense.id}>
{expenseColumns.map( {expenseColumns.map(
(col) => (col) =>
@ -263,27 +307,61 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
}) })
} }
></i> ></i>
{canEditExpense(expense) && ( {canDetetExpense(expense) &&
<i canEditExpense(expense) && (
className="bx bx-edit text-secondary cursor-pointer" <div className="dropdown z-2">
onClick={() => <button
setManageExpenseModal({ type="button"
IsOpen: true, className="btn btn-xs btn-icon btn-text-secondary rounded-pill dropdown-toggle hide-arrow p-0 m-0"
expenseId: expense.id, data-bs-toggle="dropdown"
}) aria-expanded="false"
} >
></i> <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) && ( {canDetetExpense(expense) && (
<i <li
className="bx bx-trash text-danger cursor-pointer" onClick={() => {
onClick={() => { setIsDeleteModalOpen(true);
setIsDeleteModalOpen(true); setDeletingId(expense.id);
setDeletingId(expense.id); }}
}} >
></i> <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> </div>
</td> </td>
</tr> </tr>
@ -292,8 +370,10 @@ const ExpenseList = ({ filters, groupBy = "transactionDate", searchText }) => {
)) ))
) : ( ) : (
<tr> <tr>
<td colSpan={8} className="text-center py-4"> <td colSpan={8} className="text-center border-0 ">
No Expense Found <div className="py-8">
<p>No Expense Found</p>
</div>
</td> </td>
</tr> </tr>
)} )}

View File

@ -1,4 +1,5 @@
import { z } from "zod"; import { z } from "zod";
import { localToUtc } from "../../utils/appUtils";
const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB
const ALLOWED_TYPES = [ const ALLOWED_TYPES = [
@ -17,15 +18,12 @@ export const ExpenseSchema = (expenseTypes) => {
.min(1, { message: "Expense type is required" }), .min(1, { message: "Expense type is required" }),
paymentModeId: z.string().min(1, { message: "Payment mode is required" }), paymentModeId: z.string().min(1, { message: "Payment mode is required" }),
paidById: z.string().min(1, { message: "Employee name is required" }), paidById: z.string().min(1, { message: "Employee name is required" }),
transactionDate: z transactionDate: z.string().min(1, { message: "Date is required" }),
.string()
.min(1, { message: "Date is required" })
,
transactionId: z.string().optional(), transactionId: z.string().optional(),
description: z.string().min(1, { message: "Description is required" }), description: z.string().min(1, { message: "Description is required" }),
location: z.string().min(1, { message: "Location is required" }), location: z.string().min(1, { message: "Location is required" }),
supplerName: z.string().min(1, { message: "Supplier name is required" }), supplerName: z.string().min(1, { message: "Supplier name is required" }),
gstNumber :z.string().optional(), gstNumber: z.string().optional(),
amount: z.coerce amount: z.coerce
.number({ .number({
invalid_type_error: "Amount is required and must be a 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" }), .nonempty({ message: "At least one file attachment is required" }),
}) })
.refine( .refine(
(data) => { (data) => {
@ -68,9 +64,14 @@ export const ExpenseSchema = (expenseTypes) => {
path: ["paidById"], path: ["paidById"],
} }
) )
.superRefine((data, ctx) => { .superRefine((data, ctx) => {
const expenseType = expenseTypes.find((et) => et.id === data.expensesTypeId); const expenseType = expenseTypes.find(
if (expenseType?.noOfPersonsRequired && (!data.noOfPersons || data.noOfPersons < 1)) { (et) => et.id === data.expensesTypeId
);
if (
expenseType?.noOfPersonsRequired &&
(!data.noOfPersons || data.noOfPersons < 1)
) {
ctx.addIssue({ ctx.addIssue({
code: z.ZodIssueCode.custom, code: z.ZodIssueCode.custom,
message: "No. of Persons is required and must be at least 1", message: "No. of Persons is required and must be at least 1",
@ -92,12 +93,14 @@ export const defaultExpense = {
supplerName: "", supplerName: "",
amount: "", amount: "",
noOfPersons: "", noOfPersons: "",
gstNumber:"", gstNumber: "",
billAttachments: [], billAttachments: [],
}; };
export const ExpenseActionScheam = (
export const ExpenseActionScheam = (isReimbursement = false) => { isReimbursement = false,
transactionDate
) => {
return z return z
.object({ .object({
comment: z.string().min(1, { message: "Please leave comment" }), comment: z.string().min(1, { message: "Please leave comment" }),
@ -122,6 +125,15 @@ export const ExpenseActionScheam = (isReimbursement = false) => {
message: "Reimburse Date is required", 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) { if (!data.reimburseById) {
ctx.addIssue({ ctx.addIssue({
code: z.ZodIssueCode.custom, code: z.ZodIssueCode.custom,
@ -133,7 +145,7 @@ export const ExpenseActionScheam = (isReimbursement = false) => {
}); });
}; };
export const defaultActionValues = { export const defaultActionValues = {
comment: "", comment: "",
statusId: "", statusId: "",
@ -142,13 +154,12 @@ export const ExpenseActionScheam = (isReimbursement = false) => {
reimburseById: null, reimburseById: null,
}; };
export const SearchSchema = z.object({ export const SearchSchema = z.object({
projectIds: z.array(z.string()).optional(), projectIds: z.array(z.string()).optional(),
statusIds: z.array(z.string()).optional(), statusIds: z.array(z.string()).optional(),
createdByIds: z.array(z.string()).optional(), createdByIds: z.array(z.string()).optional(),
paidById: z.array(z.string()).optional(), paidById: z.array(z.string()).optional(),
ExpenseTypeIds: z.array(z.string()).optional(),
startDate: z.string().optional(), startDate: z.string().optional(),
endDate: z.string().optional(), endDate: z.string().optional(),
isTransactionDate: z.boolean().default(true), isTransactionDate: z.boolean().default(true),
@ -159,8 +170,8 @@ export const defaultFilter = {
statusIds: [], statusIds: [],
createdByIds: [], createdByIds: [],
paidById: [], paidById: [],
ExpenseTypeIds: [],
isTransactionDate: true, isTransactionDate: true,
startDate: null, startDate: null,
endDate: null, endDate: null,
}; };

View File

@ -296,11 +296,11 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
)} )}
</div> </div>
<div className="col-12 col-md-6 text-start"> {/* <div className="col-md-6">
<Label htmlFor="paidById" className="form-label" required> <Label htmlFor="paidById" className="form-label" required>
Paid By Paid By
</Label> </Label>
{/* <select <select
className="form-select form-select-sm" className="form-select form-select-sm"
id="paymentModeId" id="paymentModeId"
{...register("paidById")} {...register("paidById")}
@ -321,13 +321,16 @@ const ManageExpense = ({ closeModal, expenseToEdit = null }) => {
</select> </select>
{errors.paidById && ( {errors.paidById && (
<small className="danger-text">{errors.paidById.message}</small> <small className="danger-text">{errors.paidById.message}</small>
)} */} )}
</div> */}
<div className="col-12 col-md-6 text-start">
<label className="form-label">Paid By </label>
<EmployeeSearchInput <EmployeeSearchInput
control={control} control={control}
name="paidById" name="paidById"
projectId={null} projectId={null}
forAll={expenseToEdit ? true : false} forAll={expenseToEdit ? true :false}
/> />
</div> </div>
</div> </div>

View File

@ -38,7 +38,7 @@ const ViewExpense = ({ ExpenseId }) => {
const IsReview = useHasUserPermission(REVIEW_EXPENSE); const IsReview = useHasUserPermission(REVIEW_EXPENSE);
const [imageLoaded, setImageLoaded] = useState({}); const [imageLoaded, setImageLoaded] = useState({});
const { setDocumentView } = useExpenseContext(); const { setDocumentView } = useExpenseContext();
const ActionSchema = ExpenseActionScheam(IsPaymentProcess) ?? z.object({}); const ActionSchema = ExpenseActionScheam(IsPaymentProcess,data?.createdAt) ?? z.object({});
const navigate = useNavigate(); const navigate = useNavigate();
const { const {
register, register,
@ -91,7 +91,7 @@ const ViewExpense = ({ ExpenseId }) => {
const onSubmit = (formData) => { const onSubmit = (formData) => {
const Payload = { const Payload = {
...formData, ...formData,
reimburseDate: localToUtc(formData.reimburseDate), reimburseDate:localToUtc(formData.reimburseDate),
expenseId: ExpenseId, expenseId: ExpenseId,
comment: formData.comment, comment: formData.comment,
}; };
@ -106,14 +106,12 @@ const ViewExpense = ({ ExpenseId }) => {
return ( return (
<form className="container px-3" onSubmit={handleSubmit(onSubmit)}> <form className="container px-3" onSubmit={handleSubmit(onSubmit)}>
<div className="row mb-3"> <div className="row mb-1">
<div className="col-12 mb-3"> <div className="col-12 mb-1">
<h5 className="fw-semibold">Expense Details</h5> <h5 className="fw-semibold m-0">Expense Details</h5>
<hr /> <hr />
</div> </div>
<div className="text-start mb-2"> <div className="col-12 text-start fw-semibold my-2">{data?.expenseUId}</div>
<div className="text-muted">{data?.description}</div>
</div>
{/* Row 1 */} {/* Row 1 */}
<div className="col-md-6 mb-3"> <div className="col-md-6 mb-3">
<div className="d-flex"> <div className="d-flex">
@ -277,7 +275,7 @@ const ViewExpense = ({ ExpenseId }) => {
className="form-label me-2 mb-0 fw-semibold" className="form-label me-2 mb-0 fw-semibold"
style={{ minWidth: "130px" }} style={{ minWidth: "130px" }}
> >
Paid By: Paid By :
</label> </label>
<div className="d-flex align-items-center "> <div className="d-flex align-items-center ">
<Avatar <Avatar
@ -294,6 +292,11 @@ const ViewExpense = ({ ExpenseId }) => {
</div> </div>
</div> </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>
<div className="col-12 text-start"> <div className="col-12 text-start">
@ -395,7 +398,7 @@ const ViewExpense = ({ ExpenseId }) => {
<DatePicker <DatePicker
name="reimburseDate" name="reimburseDate"
control={control} control={control}
minDate={data?.transactionDate} minDate={data?.createdAt}
maxDate={new Date()} maxDate={new Date()}
/> />
{errors.reimburseDate && ( {errors.reimburseDate && (
@ -409,7 +412,7 @@ const ViewExpense = ({ ExpenseId }) => {
<EmployeeSearchInput <EmployeeSearchInput
control={control} control={control}
name="reimburseById" name="reimburseById"
projectId={null} projectId={null}
/> />
</div> </div>
</div> </div>

View File

@ -1,3 +1,4 @@
import { useCallback, useEffect, useState, useMemo } from "react";
import getGreetingMessage from "../../utils/greetingHandler"; import getGreetingMessage from "../../utils/greetingHandler";
import { import {
cacheData, cacheData,
@ -12,123 +13,105 @@ import useMaster from "../../hooks/masterHook/useMaster";
import { useProfile } from "../../hooks/useProfile"; import { useProfile } from "../../hooks/useProfile";
import { useLocation, useNavigate, useParams } from "react-router-dom"; import { useLocation, useNavigate, useParams } from "react-router-dom";
import Avatar from "../../components/common/Avatar"; import Avatar from "../../components/common/Avatar";
import { useChangePassword } from "../Context/ChangePasswordContext";
import { useProjects } from "../../hooks/useProjects"; import { useProjects } from "../../hooks/useProjects";
import { useCallback, useEffect, useState } from "react";
import { useProjectName } from "../../hooks/useProjects"; import { useProjectName } from "../../hooks/useProjects";
import eventBus from "../../services/eventBus"; import eventBus from "../../services/eventBus";
import { useHasUserPermission } from "../../hooks/useHasUserPermission"; import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { MANAGE_PROJECT } from "../../utils/constants"; import { ALLOW_PROJECTSTATUS_ID, MANAGE_PROJECT, UUID_REGEX } from "../../utils/constants";
import { useAuthModal, useLogout, useModal } from "../../hooks/useAuth"; import { useAuthModal, useLogout } from "../../hooks/useAuth";
const Header = () => { const Header = () => {
const { profile } = useProfile(); const { profile } = useProfile();
const { data: masterData } = useMaster();
const location = useLocation(); const location = useLocation();
const dispatch = useDispatch(); const dispatch = useDispatch();
const { data, loading } = useMaster();
const navigate = useNavigate(); const navigate = useNavigate();
const {onOpen} = useAuthModal()
const { onOpen:changePass } = useModal("ChangePassword"); const { mutate: logout, isPending: logouting } = useLogout();
const { onOpen } = useAuthModal();
const { openChangePassword } = useChangePassword();
const HasManageProjectPermission = useHasUserPermission(MANAGE_PROJECT); const HasManageProjectPermission = useHasUserPermission(MANAGE_PROJECT);
const { mutate : logout,isPending:logouting} = useLogout()
const isDashboardPath = const pathname = location.pathname;
/^\/dashboard$/.test(location.pathname) || /^\/$/.test(location.pathname);
const isProjectPath = /^\/projects$/.test(location.pathname);
const showProjectDropdown = (pathname) => { // ======= MEMO CHECKS =======
const isDirectoryPath = /^\/directory$/.test(pathname); 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 hideDropPaths =
const isProfilePage = isDirectory || isEmployeeList || isMasters || isEmployeeProfile;
/^\/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);
return !(isDirectoryPath || isProfilePage || isExpensePage); const showProjectDropdown = !hideDropPaths;
};
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}`);
};
// ===== Project Names & Selected Project =====
const { projectNames, loading: projectLoading, fetchData } = useProjectName(); const { projectNames, loading: projectLoading, fetchData } = useProjectName();
const selectedProject = useSelectedProject(); const selectedProject = useSelectedProject();
const projectsForDropdown = isDashboardPath const projectsForDropdown = useMemo(
? projectNames () =>
: projectNames?.filter((project) => isDashboardPath
allowedProjectStatusIds.includes(project.projectStatusId) ? projectNames
); : projectNames?.filter((project) =>
ALLOW_PROJECTSTATUS_ID.includes(project.projectStatusId)
),
[projectNames, isDashboardPath]
);
let currentProjectDisplayName; const currentProjectDisplayName = useMemo(() => {
if (projectLoading) { if (projectLoading) return "Loading...";
currentProjectDisplayName = "Loading..."; if (!projectNames?.length) return "No Projects Assigned";
} else if (!projectNames || projectNames.length === 0) { if (projectNames.length === 1) return projectNames[0].name;
currentProjectDisplayName = "No Projects Assigned"; if (selectedProject === null) return "All Projects";
} else if (projectNames.length === 1) { const selectedObj = projectNames.find((p) => p.id === selectedProject);
currentProjectDisplayName = projectNames[0].name; return selectedObj
} else { ? selectedObj.name
if (selectedProject === null) { : projectNames[0]?.name || "No Projects Assigned";
currentProjectDisplayName = "All Projects"; }, [projectLoading, projectNames, selectedProject]);
} else {
const selectedProjectObj = projectNames.find(
(p) => p?.id === selectedProject
);
currentProjectDisplayName = selectedProjectObj
? selectedProjectObj.name
: "All Projects";
}
}
// ===== 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(() => { useEffect(() => {
if ( if (
projectNames && projectNames?.length &&
projectNames.length > 0 &&
selectedProject === undefined && selectedProject === undefined &&
!getCachedData("hasReceived") !getCachedData("hasReceived")
) { ) {
if (projectNames.length === 1) { if (projectNames.length === 1) {
dispatch(setProjectId(projectNames[0]?.id || null)); dispatch(setProjectId(projectNames[0].id || null));
} else { } else {
if (isDashboardPath) { if (isDashboardPath) {
dispatch(setProjectId(null)); dispatch(setProjectId(null));
} else { } else {
const firstAllowedProject = projectNames.find((project) => const firstAllowed = projectNames.find((project) =>
allowedProjectStatusIds.includes(project.projectStatusId) ALLOW_PROJECTSTATUS_ID.includes(project.projectStatusId)
); );
dispatch(setProjectId(firstAllowedProject?.id || null)); dispatch(setProjectId(firstAllowed?.id || null));
} }
} }
} }
}, [projectNames, selectedProject, dispatch, isDashboardPath]); }, [projectNames, selectedProject, dispatch, isDashboardPath]);
// ===== Event Handlers =====
const handler = useCallback( const handler = useCallback(
async (data) => { async (data) => {
if (!HasManageProjectPermission) { if (!HasManageProjectPermission) {
await fetchData(); await fetchData();
const projectExist = data.projectIds.some( if (data.projectIds?.includes(selectedProject)) {
(item) => item === selectedProject
);
if (projectExist) {
cacheData("hasReceived", false); cacheData("hasReceived", false);
} }
} }
@ -138,14 +121,15 @@ const Header = () => {
const newProjectHandler = useCallback( const newProjectHandler = useCallback(
async (msg) => { async (msg) => {
if (HasManageProjectPermission && msg.keyword === "Create_Project") { if (
await fetchData(); msg.keyword === "Create_Project" ||
} else if (projectNames?.some((item) => item.id === msg.response.id)) { projectNames?.some((p) => p.id === msg.response?.id)
) {
await fetchData(); await fetchData();
cacheData("hasReceived", false);
} }
cacheData("hasReceived", false);
}, },
[HasManageProjectPermission, projectNames, fetchData] [projectNames, fetchData]
); );
useEffect(() => { useEffect(() => {
@ -162,10 +146,10 @@ const Header = () => {
}; };
}, [handler, newProjectHandler]); }, [handler, newProjectHandler]);
const handleProjectChange = (project) => { // ===== Project Change =====
dispatch(setProjectId(project)); const handleProjectChange = (projectId) => {
dispatch(setProjectId(projectId));
if (isProjectPath && project !== null) { if (isProjectPath && projectId !== null) {
navigate("/projects/details"); navigate("/projects/details");
} }
}; };
@ -189,8 +173,7 @@ const Header = () => {
className="navbar-nav-right d-flex align-items-center justify-content-between" className="navbar-nav-right d-flex align-items-center justify-content-between"
id="navbar-collapse" id="navbar-collapse"
> >
<div className="d-flex align-items-center"> {showProjectDropdown && (
{showProjectDropdown(location.pathname) && (
<div className="align-items-center"> <div className="align-items-center">
<i className="rounded-circle bx bx-building-house bx-sm-lg bx-md me-2"></i> <i className="rounded-circle bx bx-building-house bx-sm-lg bx-md me-2"></i>
<div className="btn-group"> <div className="btn-group">
@ -216,16 +199,14 @@ const Header = () => {
className="dropdown-menu" className="dropdown-menu"
style={{ overflow: "auto", maxHeight: "300px" }} style={{ overflow: "auto", maxHeight: "300px" }}
> >
{isDashboardPath && (
<li> <li>
<button <button
className="dropdown-item" className="dropdown-item"
onClick={() => handleProjectChange(null)} onClick={() => handleProjectChange(null)}
> >All Project</button>
All Projects </li>
</button>
</li>
)}
{[...projectsForDropdown] {[...projectsForDropdown]
.sort((a, b) => a?.name?.localeCompare(b.name)) .sort((a, b) => a?.name?.localeCompare(b.name))
.map((project) => ( .map((project) => (
@ -248,115 +229,11 @@ const Header = () => {
</div> </div>
</div> </div>
)} )}
</div>
<ul className="navbar-nav flex-row align-items-center ms-md-auto"> <ul className="navbar-nav flex-row align-items-center ms-md-auto">
<li className="nav-item dropdown-shortcuts navbar-dropdown dropdown me-2 me-xl-0"> {/* {HasManageProjectPermission && ( */}
<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>
<li className="nav-item navbar-dropdown dropdown-user dropdown"> <li className="nav-item navbar-dropdown dropdown-user dropdown">
<a <a
aria-label="dropdown profile avatar" aria-label="dropdown profile avatar"
@ -388,7 +265,7 @@ const Header = () => {
{profile?.employeeInfo?.firstName} {profile?.employeeInfo?.firstName}
</span> </span>
<small className="text-muted"> <small className="text-muted">
{getRole(data, profile?.employeeInfo?.joRoleId)} {getRole(masterData, profile?.employeeInfo?.joRoleId)}
</small> </small>
</div> </div>
</div> </div>
@ -397,15 +274,13 @@ const Header = () => {
<li> <li>
<div className="dropdown-divider"></div> <div className="dropdown-divider"></div>
</li> </li>
<li onClick={()=>onOpen()}> {/* <li onClick={() => onOpen()}>
{" "} {" "}
<a <a className="dropdown-item cusor-pointer">
className="dropdown-item cusor-pointer"
>
<i className="bx bx-transfer-alt me-2"></i> <i className="bx bx-transfer-alt me-2"></i>
<span className="align-middle">Switch Workspace</span> <span className="align-middle">Switch Workspace</span>
</a> </a>
</li> </li> */}
<li onClick={handleProfilePage}> <li onClick={handleProfilePage}>
<a <a
aria-label="go to profile" aria-label="go to profile"
@ -424,7 +299,7 @@ const Header = () => {
<span className="align-middle">Settings</span> <span className="align-middle">Settings</span>
</a> </a>
</li> </li>
<li onClick={changePass}> <li onClick={openChangePassword}>
{" "} {" "}
<a <a
aria-label="go to profile" aria-label="go to profile"
@ -435,7 +310,6 @@ const Header = () => {
</a> </a>
</li> </li>
<li> <li>
<div className="dropdown-divider"></div> <div className="dropdown-divider"></div>
</li> </li>
@ -443,10 +317,17 @@ const Header = () => {
<a <a
aria-label="click to log out" aria-label="click to log out"
className="dropdown-item cusor-pointer" className="dropdown-item cusor-pointer"
onClick={()=>logout()} onClick={() => logout()}
> >
{logouting ? "Please Wait":<> <i className="bx bx-log-out me-2"></i> {logouting ? (
<span className="align-middle">SignOut</span></>} "Please Wait"
) : (
<>
{" "}
<i className="bx bx-log-out me-2"></i>
<span className="align-middle">SignOut</span>
</>
)}
</a> </a>
</li> </li>
</ul> </ul>
@ -456,4 +337,4 @@ const Header = () => {
</nav> </nav>
); );
}; };
export default Header; export default Header;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -5,7 +5,11 @@ import { zodResolver } from "@hookform/resolvers/zod";
import Label from "../common/Label"; import Label from "../common/Label";
import DatePicker from "../common/DatePicker"; import DatePicker from "../common/DatePicker";
import { useCreateProject, useProjectDetails, useUpdateProject } from "../../hooks/useProjects"; import {
useCreateProject,
useProjectDetails,
useUpdateProject,
} from "../../hooks/useProjects";
import { import {
DEFAULT_EMPTY_STATUS_ID, DEFAULT_EMPTY_STATUS_ID,
@ -17,6 +21,8 @@ import {
useOrganizationsList, useOrganizationsList,
} from "../../hooks/useOrganization"; } from "../../hooks/useOrganization";
import { localToUtc } from "../../utils/appUtils"; import { localToUtc } from "../../utils/appUtils";
import Modal from "../common/Modal";
import { useModal } from "../../hooks/useAuth";
const currentDate = new Date().toLocaleDateString("en-CA"); const currentDate = new Date().toLocaleDateString("en-CA");
const formatDate = (date) => { const formatDate = (date) => {
@ -32,18 +38,24 @@ const formatDate = (date) => {
const ManageProjectInfo = ({ project, onClose }) => { const ManageProjectInfo = ({ project, onClose }) => {
const [addressLength, setAddressLength] = useState(0); const [addressLength, setAddressLength] = useState(0);
const maxAddressLength = 500; const maxAddressLength = 500;
const { onOpen, startStep, flowType } = useOrganizationModal(); const { onOpen, startStep, flowType } = useModal("ManageProject");
const ACTIVE_STATUS_ID = "b74da4c2-d07e-46f2-9919-e75e49b12731"; const ACTIVE_STATUS_ID = "b74da4c2-d07e-46f2-9919-e75e49b12731";
const { projects_Details, loading } = useProjectDetails(project); const { projects_Details, loading } = useProjectDetails(project);
const { data, isLoading, isError, error } = useOrganizationsList( // const { data, isLoading, isError, error } = useOrganizationsList(
ITEMS_PER_PAGE, // ITEMS_PER_PAGE,
1, // 1,
true // 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 { const {
register, register,
@ -70,11 +82,11 @@ const ManageProjectInfo = ({ project, onClose }) => {
projectStatusId: projectStatusId:
String(projects_Details?.projectStatus?.id) || String(projects_Details?.projectStatus?.id) ||
DEFAULT_EMPTY_STATUS_IDF, DEFAULT_EMPTY_STATUS_IDF,
promoterId: projects_Details?.promoter?.id || "", // promoterId: projects_Details?.promoter?.id || "", // hide temp. for version 1
pmcId: projects_Details?.pmc?.id || "", // pmcId: projects_Details?.pmc?.id || "",
}); });
setAddressLength(projects_Details?.projectAddress?.length || 0); setAddressLength(projects_Details?.projectAddress?.length || 0);
}, [project, projects_Details, reset,data]); }, [project, projects_Details, reset]);
const onSubmitForm = (formData) => { const onSubmitForm = (formData) => {
if (project) { if (project) {
@ -85,13 +97,13 @@ const ManageProjectInfo = ({ project, onClose }) => {
id: project, id: project,
}; };
UpdateProject({ projectId: project, payload: payload }); UpdateProject({ projectId: project, payload: payload });
}else{ } else {
let payload = { let payload = {
...formData, ...formData,
startDate: localToUtc(formData.startDate), startDate: localToUtc(formData.startDate),
endDate: localToUtc(formData.endDate), endDate: localToUtc(formData.endDate),
}; };
CeateProject(payload) CeateProject(payload);
} }
}; };
@ -104,7 +116,6 @@ const ManageProjectInfo = ({ project, onClose }) => {
onOpen({ startStep: 2, flowType: "default" }); onOpen({ startStep: 2, flowType: "default" });
}; };
return ( return (
<div className="p-sm-2 p-2"> <div className="p-sm-2 p-2">
<div className="text-center mb-2"> <div className="text-center mb-2">
@ -254,7 +265,7 @@ const ManageProjectInfo = ({ project, onClose }) => {
</div> </div>
)} )}
</div> </div>
<div className="col-12 "> {/* <div className="col-12 ">
<label className="form-label" htmlFor="modalEditUserStatus"> <label className="form-label" htmlFor="modalEditUserStatus">
Promoter Promoter
</label> </label>
@ -327,10 +338,10 @@ const ManageProjectInfo = ({ project, onClose }) => {
<i className="bx bx-sm bx-info-circle"></i> Not found PMC and <i className="bx bx-sm bx-info-circle"></i> Not found PMC and
Pomoter, find through SPRID or create new Pomoter, find through SPRID or create new
</span> </span>
<small className="cursor-pointer" onClick={handleOrganizaioFinder} > <small className="cursor-pointer" onClick={handleOrganizaioFinder}>
<i className="bx bx-plus-circle text-primary"></i> <i className="bx bx-plus-circle text-primary"></i>
</small> </small>
</div> </div> */}
<div className="col-12 col-md-12"> <div className="col-12 col-md-12">
<Label htmlFor="projectAddress" required> <Label htmlFor="projectAddress" required>
@ -367,16 +378,20 @@ const ManageProjectInfo = ({ project, onClose }) => {
className="btn btn-label-secondary btn-sm me-2" className="btn btn-label-secondary btn-sm me-2"
onClick={handleCancel} onClick={handleCancel}
aria-label="Close" aria-label="Close"
disabled={isPending || isCreating || loading} disabled={isPending || isCreating}
> >
Cancel Cancel
</button> </button>
<button <button
type="submit" type="submit"
className="btn btn-primary btn-sm" className="btn btn-primary btn-sm"
disabled={isPending || isCreating || loading} disabled={isPending || isCreating}
> >
{isPending||isCreating ? "Please Wait..." : project ? "Update" : "Submit"} {isPending || isCreating
? "Please Wait..."
: project
? "Update"
: "Submit"}
</button> </button>
</div> </div>
</form> </form>
@ -385,3 +400,15 @@ const ManageProjectInfo = ({ project, onClose }) => {
}; };
export default ManageProjectInfo; export default ManageProjectInfo;
export const ProjectModal = () => {
const { isOpen, data, closeModal } = useProjectModal();
return (
<Modal
isOpen={isOpen}
body={<ManageProjectInfo project={data} onClose={closeModal} />}
onClose={closeModal}
/>
);
};

View File

@ -35,6 +35,7 @@ const ProjectCard = ({ project }) => {
const handleViewProject = () => { const handleViewProject = () => {
dispatch(setProjectId(project.id)); dispatch(setProjectId(project.id));
localStorage.setItem("lastActiveProjectTab","profile")
navigate(`/projects/details`); navigate(`/projects/details`);
}; };
const handleViewActivities = () => { const handleViewActivities = () => {
@ -54,7 +55,7 @@ const ProjectCard = ({ project }) => {
style={{ fontSize: "xx-large" }} style={{ fontSize: "xx-large" }}
></i> ></i>
</div> </div>
<div className="me-2"> <div className="me-2 text-start">
<h5 <h5
className="mb-0 stretched-link text-heading text-start" className="mb-0 stretched-link text-heading text-start"
onClick={handleViewProject} onClick={handleViewProject}
@ -66,7 +67,7 @@ const ProjectCard = ({ project }) => {
</div> </div>
</div> </div>
</div> </div>
<div className={`ms-auto ${!ManageProject && "d-none"}`}> <div className={`ms-auto `}>
<div className="dropdown z-2"> <div className="dropdown z-2">
<button <button
type="button" type="button"
@ -106,12 +107,6 @@ const ProjectCard = ({ project }) => {
<span className="align-left">Modify</span> <span className="align-left">Modify</span>
</a> </a>
</li> </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> </ul>
</div> </div>
</div> </div>

View File

@ -1,70 +1,62 @@
import React from 'react' import React from "react";
import { useProjects } from '../../hooks/useProjects' import { useProjects } from "../../hooks/useProjects";
import Loader from '../common/Loader' import Loader from "../common/Loader";
import ProjectCard from './ProjectCard' import ProjectCard from "./ProjectCard";
const ProjectCardView = ({currentItems,setCurrentPage,totalPages }) => {
const ProjectCardView = ({ currentItems, setCurrentPage, totalPages }) => {
return ( 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 && ( {totalPages > 1 && (
<p className="text-center text-muted">No projects found.</p> <nav>
)} <ul className="pagination pagination-sm justify-content-end py-2">
<li className={`page-item ${currentPage === 1 && "disabled"}`}>
{currentItems.map((project) => ( <button
<ProjectCard className="page-link"
key={project.id} onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
project={project} >
/> &laquo;
))} </button>
</li>
{[...Array(totalPages)].map((_, i) => (
{ 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))}
>
&laquo;
</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 <li
className={`page-item ${currentPage === totalPages && "disabled" key={i}
}`} className={`page-item ${currentPage === i + 1 && "active"}`}
> >
<button <button
className="page-link" className="page-link"
onClick={() => onClick={() => setCurrentPage(i + 1)}
setCurrentPage((p) => Math.min(totalPages, p + 1))
}
> >
&raquo; {i + 1}
</button> </button>
</li> </li>
</ul> ))}
</nav> <li
)} className={`page-item ${
</div> currentPage === totalPages && "disabled"
}`}
) >
} <button
className="page-link"
onClick={() =>
setCurrentPage((p) => Math.min(totalPages, p + 1))
}
>
&raquo;
</button>
</li>
</ul>
</nav>
)}
</div>
);
};
export default ProjectCardView export default ProjectCardView;

View File

@ -26,9 +26,8 @@ const ProjectListView = ({
const navigate = useNavigate(); const navigate = useNavigate();
const { setMangeProject } = useProjectContext(); const { setMangeProject } = useProjectContext();
// const { data, isLoading, isError, error } = useProjects(); // const { data, isLoading, isError, error } = useProjects();
// check Permissions // check Permissions
const canManageProject = useHasUserPermission(MANAGE_PROJECT); // const canManageProject = useHasUserPermission(MANAGE_PROJECT);
const projectColumns = [ const projectColumns = [
{ {
@ -125,159 +124,156 @@ const ProjectListView = ({
}, },
]; ];
const handleViewActivities = (project) => { // const handleViewActivities = (project) => {
dispatch(setProjectId(project)); // dispatch(setProjectId(project));
navigate(`/activities/records?project=${project}`); // navigate(`/activities/records?project=${project}`);
}; // };
const handleMoveDetails = (project) => {
dispatch(setProjectId(project));
localStorage.setItem("lastActiveProjectTab", "profile")
navigate("/projects/details");
};
return ( return (
<div className="card page-min-h py-4 px-6 shadow-sm"> <div className="card page-min-h py-4 px-6 shadow-sm">
<div className="table-responsive text-nowrap">
<div <table className="table table-hover align-middle m-0">
className="table-responsive text-nowrap page-min-h" <thead className="border-bottom">
> <tr>
<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} table_header_border`}>
{col.label}
</th>
))}
<th className="text-center py-3">Action</th>
</tr>
</thead>
<tbody>
{currentItems?.map((project) => (
<tr key={project.id}>
{projectColumns.map((col) => ( {projectColumns.map((col) => (
<td <th key={col.key} colSpan={col.colSpan} className={col.className}>
key={col.key} {col.label}
colSpan={col.colSpan} </th>
className={`${col.className} py-5`}
style={{ paddingTop: "20px", paddingBottom: "20px" }}
>
{col.getValue
? col.getValue(project)
: project[col.key] || "N/A"}
</td>
))} ))}
<td <th className="text-center py-3">Action</th>
className={`mx-2 ${ </tr>
canManageProject ? "d-sm-table-cell" : "d-none" </thead>
}`} <tbody>
> {currentItems?.map((project) => (
<div className="dropdown z-2"> <tr key={project.id}>
<button {projectColumns.map((col) => (
type="button" <td
className="btn btn-icon btn-text-secondary rounded-pill dropdown-toggle hide-arrow p-0" key={col.key}
data-bs-toggle="dropdown" colSpan={col.colSpan}
aria-expanded="false" className={`${col.className} py-5`}
style={{ paddingTop: "20px", paddingBottom: "20px" }}
> >
<i {col.getValue
className="bx bx-dots-vertical-rounded bx-sm text-muted" ? col.getValue(project)
data-bs-toggle="tooltip" : project[col.key] || "N/A"}
data-bs-offset="0,8" </td>
data-bs-placement="top" ))}
data-bs-custom-class="tooltip-dark" <td className={`mx-2 ${"d-sm-table-cell"}`}>
title="More Action" <div className="dropdown z-2">
></i> <button
</button> type="button"
<ul className="dropdown-menu dropdown-menu-end"> className="btn btn-icon btn-text-secondary rounded-pill dropdown-toggle hide-arrow p-0"
<li> data-bs-toggle="dropdown"
<a aria-expanded="false"
aria-label="click to View details" >
className="dropdown-item cursor-pointer" <i
> className="bx bx-dots-vertical-rounded bx-sm text-muted"
<i className="bx bx-detail me-2"></i> data-bs-toggle="tooltip"
<span className="align-left">View details</span> data-bs-offset="0,8"
</a> data-bs-placement="top"
</li> 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> <li>
<a <a
className="dropdown-item cursor-pointer" className="dropdown-item cursor-pointer"
onClick={() => onClick={() =>
setMangeProject({ setMangeProject({
isOpen: true, isOpen: true,
Project: project.id, Project: project.id,
}) })
} }
> >
<i className="bx bx-pencil me-2"></i> <i className="bx bx-pencil me-2"></i>
<span className="align-left">Modify</span> <span className="align-left">Modify</span>
</a> </a>
</li> </li>
<li onClick={() => handleViewActivities(project.id)}> {/* <li onClick={() => handleViewActivities(project.id)}>
<a className="dropdown-item cursor-pointer"> <a className="dropdown-item cursor-pointer">
<i className="bx bx-task me-2"></i> <i className="bx bx-task me-2"></i>
<span className="align-left">Activities</span> <span className="align-left">Activities</span>
</a> </a>
</li> </li> */}
</ul> </ul>
</div> </div>
</td> </td>
</tr> </tr>
))} ))}
</tbody> </tbody>
</table> </table>
</div>
{isLoading && ( {isLoading && (
<div className="py-4"> <div className="py-4">
{" "} {" "}
{isLoading && <p className="text-center">Loading...</p>} {isLoading && <p className="text-center">Loading...</p>}
{!isLoading && filteredProjects.length === 0 && ( {!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> <p className="text-center text-muted">No projects found.</p>
)} </div>
</div> )}
)} {!isLoading && totalPages > 1 && (
{!isLoading && currentItems.length === 0 && ( <nav>
<div className="py-6"> <ul className="pagination pagination-sm justify-content-end py-2">
<p className="text-center text-muted">No projects found.</p> <li className={`page-item ${currentPage === 1 && "disabled"}`}>
</div> <button
)} className="page-link"
{!isLoading && totalPages > 1 && ( onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
<nav> >
<ul className="pagination pagination-sm justify-content-end py-2"> &laquo;
<li className={`page-item ${currentPage === 1 && "disabled"}`}> </button>
<button </li>
className="page-link" {[...Array(totalPages)].map((_, i) => (
onClick={() => setCurrentPage((p) => Math.max(1, p - 1))} <li
> key={i}
&laquo; className={`page-item ${currentPage === i + 1 && "active"}`}
</button> >
</li> <button
{[...Array(totalPages)].map((_, i) => ( className="page-link"
onClick={() => setCurrentPage(i + 1)}
>
{i + 1}
</button>
</li>
))}
<li <li
key={i} className={`page-item ${currentPage === totalPages && "disabled"
className={`page-item ${currentPage === i + 1 && "active"}`} }`}
> >
<button <button
className="page-link" className="page-link"
onClick={() => setCurrentPage(i + 1)} onClick={() =>
setCurrentPage((p) => Math.min(totalPages, p + 1))
}
> >
{i + 1} &raquo;
</button> </button>
</li> </li>
))} </ul>
<li </nav>
className={`page-item ${ )}
currentPage === totalPages && "disabled" </div>
}`}
>
<button
className="page-link"
onClick={() =>
setCurrentPage((p) => Math.min(totalPages, p + 1))
}
>
&raquo;
</button>
</li>
</ul>
</nav>
)}
</div> </div>
); );
}; };

View File

@ -27,13 +27,13 @@ const ProjectNav = ({ onPillClick, activePill }) => {
const ProjectTab = [ const ProjectTab = [
{ key: "profile", icon: "bx bx-user", label: "Profile" }, { key: "profile", icon: "bx bx-user", label: "Profile" },
{ key: "teams", icon: "bx bx-group", label: "Teams" }, // { key: "teams", icon: "bx bx-group", label: "Teams" },
{ // {
key: "infra", // key: "infra",
icon: "bx bx-grid-alt", // icon: "bx bx-grid-alt",
label: "Infrastructure", // label: "Infrastructure",
hidden: !(HasViewInfraStructure || HasManageInfra || HasManageTask), // hidden: !(HasViewInfraStructure || HasManageInfra || HasManageTask),
}, // },
{ {
key: "directory", key: "directory",
icon: "bx bxs-contact", icon: "bx bxs-contact",
@ -41,8 +41,8 @@ const ProjectNav = ({ onPillClick, activePill }) => {
hidden: !(DirAdmin || DireManager || DirUser), hidden: !(DirAdmin || DireManager || DirUser),
}, },
{ key: "documents", icon: "bx bx-folder-open", label: "Documents",hidden:!(isViewDocuments || isModifyDocument || isUploadDocument) }, { key: "documents", icon: "bx bx-folder-open", label: "Documents",hidden:!(isViewDocuments || isModifyDocument || isUploadDocument) },
{ key: "organization", icon: "bx bx-buildings", label: "Organization"}, // { key: "organization", icon: "bx bx-buildings", label: "Organization"},
{ key: "setting", icon: "bx bxs-cog", label: "Setting",hidden:!isManageTeam }, // { key: "setting", icon: "bx bxs-cog", label: "Setting",hidden:!isManageTeam },
]; ];
return ( return (
<div className="nav-align-top"> <div className="nav-align-top">

View File

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

View File

@ -11,8 +11,8 @@ export const projectDefault = {
startDate: currentDate.toISOString().split("T")[0], startDate: currentDate.toISOString().split("T")[0],
endDate: currentDate.toISOString().split("T")[0], endDate: currentDate.toISOString().split("T")[0],
projectStatusId: DEFAULT_EMPTY_STATUS_ID, projectStatusId: DEFAULT_EMPTY_STATUS_ID,
promoterId: "", // promoterId: "",
pmcId: "", // pmcId: "",
}; };
@ -39,8 +39,8 @@ export const projectSchema = z
.min(1, { message: "End Date is required" }) .min(1, { message: "End Date is required" })
.default(projectDefault), .default(projectDefault),
projectStatusId: z.string().min(1, { message: "Status is required" }), projectStatusId: z.string().min(1, { message: "Status is required" }),
promoterId: z.string().min(1, { message: "Promoter is required" }), // promoterId: z.string().min(1, { message: "Promoter is required" }),
pmcId: z.string().min(1, { message: "PMC is required" }), // pmcId: z.string().min(1, { message: "PMC is required" }),
}) })
.refine( .refine(
(data) => { (data) => {

View File

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

View File

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

View File

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

View File

@ -8,12 +8,14 @@ import { orgSize, reference } from "../../utils/constants";
import moment from "moment"; import moment from "moment";
import { useGlobalServices } from "../../hooks/masterHook/useMaster"; import { useGlobalServices } from "../../hooks/masterHook/useMaster";
import SelectMultiple from "../common/SelectMultiple"; import SelectMultiple from "../common/SelectMultiple";
import { useNavigate } from "react-router-dom";
const OrganizationInfo = ({ onNext, onPrev, onSubmitTenant }) => { const OrganizationInfo = ({ onNext, onPrev, onSubmitTenant }) => {
const { data, isError, isLoading: industryLoading } = useIndustries(); const { data, isError, isLoading: industryLoading } = useIndustries();
const [logoPreview, setLogoPreview] = useState(null); const [logoPreview, setLogoPreview] = useState(null);
const [logoName, setLogoName] = useState(""); const [logoName, setLogoName] = useState("");
const { data: services, isLoading: serviceLoading } = useGlobalServices(); const { data: services, isLoading: serviceLoading } = useGlobalServices();
const navigate = useNavigate()
const { const {
register, register,
control, control,
@ -29,8 +31,8 @@ const OrganizationInfo = ({ onNext, onPrev, onSubmitTenant }) => {
error, error,
isPending, isPending,
} = useCreateTenant(() => { } = useCreateTenant(() => {
debugger // onNext()
onNext() navigate("/tenants");
}); });
const handleNext = async () => { const handleNext = async () => {
@ -134,7 +136,6 @@ const OrganizationInfo = ({ onNext, onPrev, onSubmitTenant }) => {
control={control} control={control}
placeholder="DD-MM-YYYY" placeholder="DD-MM-YYYY"
maxDate={new Date()} maxDate={new Date()}
className={errors.onBoardingDate ? "is-invalid" : ""}
/> />
{errors.onBoardingDate && ( {errors.onBoardingDate && (
<div className="invalid-feedback"> <div className="invalid-feedback">

View File

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

View File

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

View File

@ -3,8 +3,8 @@ import { useController, useFormContext, useWatch } from "react-hook-form";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
const DateRangePicker = ({ const DateRangePicker = ({
md=12, md,
sm=6, sm,
onRangeChange, onRangeChange,
DateDifference = 7, DateDifference = 7,
endDateMode = "yesterday", endDateMode = "yesterday",
@ -33,7 +33,7 @@ const DateRangePicker = ({
startDate.setHours(0, 0, 0, 0); startDate.setHours(0, 0, 0, 0);
} }
const fp = flatpickr(inputRef.current, { const fp = flatpickr(inputRef.current, {
mode: "range", mode: "range",
dateFormat: "Y-m-d", dateFormat: "Y-m-d",
altInput: true, altInput: true,
@ -63,22 +63,20 @@ const DateRangePicker = ({
}; };
return ( return (
<div className={`position-relative w-auto justify-content-center`}> <div className={`position-relative w-auto justify-content-center`}>
<input <input
type="text" type="text"
className="form-control form-control-sm w-100 pe-8 " className="form-control form-control-sm w-100 pe-8 "
placeholder="From to End" placeholder="From to End"
id="flatpickr-range" id="flatpickr-range"
ref={inputRef} ref={inputRef}
/> />
<i
className="bx bx-calendar calendar-icon cursor-pointer position-absolute top-50 end-0 translate-middle-y me-2 "
onClick={handleIconClick}
/>
</div>
<i
className="bx bx-calendar calendar-icon cursor-pointer position-absolute top-50 end-0 translate-middle-y me-2 "
onClick={handleIconClick}
/>
</div>
); );
}; };
@ -131,7 +129,7 @@ export const DateRangePicker1 = ({
mode: "range", mode: "range",
dateFormat: "d-m-Y", dateFormat: "d-m-Y",
allowInput: allowText, allowInput: allowText,
maxDate , maxDate,
onChange: (selectedDates) => { onChange: (selectedDates) => {
if (selectedDates.length === 2) { if (selectedDates.length === 2) {
const [start, end] = selectedDates; const [start, end] = selectedDates;
@ -161,19 +159,19 @@ export const DateRangePicker1 = ({
}, []); }, []);
useEffect(() => { useEffect(() => {
if (resetSignal !== undefined) { if (resetSignal !== undefined) {
if (defaultRange) { if (defaultRange) {
applyDefaultDates(); applyDefaultDates();
} else { } else {
setValue(startField, "", { shouldValidate: true }); setValue(startField, "", { shouldValidate: true });
setValue(endField, "", { shouldValidate: true }); setValue(endField, "", { shouldValidate: true });
if (inputRef.current?._flatpickr) { if (inputRef.current?._flatpickr) {
inputRef.current._flatpickr.clear(); inputRef.current._flatpickr.clear();
}
} }
} }
} }, [resetSignal, defaultRange, setValue, startField, endField]);
}, [resetSignal, defaultRange, setValue, startField, endField]);
const start = getValues(startField); const start = getValues(startField);
@ -184,7 +182,7 @@ export const DateRangePicker1 = ({
<div className={`position-relative ${className}`}> <div className={`position-relative ${className}`}>
<input <input
type="text" type="text"
className="form-control form-control-sm" className="form-control form-control-sm ps-2 pe-5 me-4 cursor-pointer"
placeholder={placeholder} placeholder={placeholder}
defaultValue={formattedValue} defaultValue={formattedValue}
ref={(el) => { ref={(el) => {

View File

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

View File

@ -4,21 +4,26 @@ import { createPortal } from "react-dom";
import "./MultiSelectDropdown.css"; import "./MultiSelectDropdown.css";
import Label from "./Label"; import Label from "./Label";
const SelectMultiple = ({ const SelectMultiple = ({
name, name,
options = [], options = [],
label = "Select options", label = "Select options",
labelKey = "name", labelKey = "name",
valueKey = "id", valueKey = "id",
placeholder = "Please select...", placeholder = "Please select...",
IsLoading = false,required = false IsLoading = false,
required = false,
}) => { }) => {
const { setValue, watch,register } = useFormContext(); const { setValue, watch, register } = useFormContext();
useEffect(() => {
register(name, { value: [] });
}, [register, name]);
const selectedValues = watch(name) || []; useEffect(() => {
register(name, { value: [] });
}, [register, name]);
const selectedValues = watch(name) || [];
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
const [searchText, setSearchText] = useState(""); const [searchText, setSearchText] = useState("");
@ -60,18 +65,20 @@ const selectedValues = watch(name) || [];
const updated = selectedValues.includes(value) const updated = selectedValues.includes(value)
? selectedValues.filter((v) => v !== value) ? selectedValues.filter((v) => v !== value)
: [...selectedValues, value]; : [...selectedValues, value];
setValue(name, updated, { shouldValidate: true }); setValue(name, updated, { shouldValidate: true });
}; };
const filteredOptions = (options || []).filter((item) => { const filteredOptions = (options || []).filter((item) => {
const label = getLabel(item); const label = getLabel(item);
return ( return typeof label === "string" && label.toLowerCase().includes(searchText.toLowerCase());
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 = ( const dropdownElement = (
<div <div
@ -101,7 +108,7 @@ const selectedValues = watch(name) || [];
/> />
</div> </div>
{filteredOptions.map((item) => { {sortedOptions.map((item) => {
const labelVal = getLabel(item); const labelVal = getLabel(item);
const valueVal = item[valueKey]; const valueVal = item[valueKey];
const isChecked = selectedValues.includes(valueVal); 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 }}> <div className="multi-select-dropdown-Not-found" style={{ padding: 8 }}>
<label className="text-muted">Not Found {`'${searchText}'`}</label> <label className="text-muted">Not Found {`'${searchText}'`}</label>
</div> </div>
)} )}
{IsLoading && filteredOptions.length === 0 && ( {IsLoading && sortedOptions.length === 0 && (
<div className="multi-select-dropdown-Not-found" style={{ padding: 8 }}> <div className="multi-select-dropdown-Not-found" style={{ padding: 8 }}>
<label className="text-muted">Loading...</label> <label className="text-muted">Loading...</label>
</div> </div>
@ -140,19 +147,14 @@ const selectedValues = watch(name) || [];
return ( return (
<> <>
<div ref={containerRef} className="multi-select-dropdown-container" style={{ position: "relative" }}> <div ref={containerRef} className="multi-select-dropdown-container" style={{ position: "relative" }}>
<label className="form-label mb-1">{label}</label> <Label required={required}>{label}</Label>
<Label className={name} required={required}></Label>
<div <div
className="multi-select-dropdown-header" className="multi-select-dropdown-header"
onClick={() => setIsOpen((prev) => !prev)} onClick={() => setIsOpen((prev) => !prev)}
style={{ cursor: "pointer" }} style={{ cursor: "pointer" }}
> >
<span <span className={selectedValues.length > 0 ? "placeholder-style-selected" : "placeholder-style"}>
className={
selectedValues.length > 0 ? "placeholder-style-selected" : "placeholder-style"
}
>
<div className="selected-badges-container"> <div className="selected-badges-container">
{selectedValues.length > 0 ? ( {selectedValues.length > 0 ? (
selectedValues.map((val) => { selectedValues.map((val) => {

View File

@ -2,7 +2,7 @@ import { useFormContext, useWatch } from "react-hook-form";
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import Label from "./Label"; 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 { setValue, watch } = useFormContext();
const tags = watch(name) || []; const tags = watch(name) || [];
const [input, setInput] = useState(""); const [input, setInput] = useState("");
@ -65,9 +65,9 @@ const handleChange = (e) => {
return ( return (
<> <>
<label htmlFor={name} className="form-label"> <Label required={require}>
{label} {label}
</label> </Label>
<div <div
className="form-control form-control-sm p-1" className="form-control form-control-sm p-1"

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -81,8 +81,8 @@ const ServiceGroups = ({ service }) => {
) : ( ) : (
<div className="accordion-body text-start m-0 p-0"> <div className="accordion-body text-start m-0 p-0">
<div className="dropdown-divider border"></div> <div className="dropdown-divider border"></div>
{!isLoading && groups?.data?.length === 0 && (<div className="text-center py-2"><p>No Group available.</p></div>)}
{groups && groups?.data?.map((group) => { {groups?.data?.map((group) => {
const isOpen = activeGroupId === group.id; const isOpen = activeGroupId === group.id;
return ( return (

View File

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

View File

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

View File

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

View File

@ -155,32 +155,32 @@ export const useDashboard_Data = ({ days, FromDate, projectId }) => {
// }; // };
export const useAttendanceOverviewData = (projectId, days) => { // export const useAttendanceOverviewData = (projectId, days) => {
const [attendanceOverviewData, setAttendanceOverviewData] = useState([]); // const [attendanceOverviewData, setAttendanceOverviewData] = useState([]);
const [loading, setLoading] = useState(false); // const [loading, setLoading] = useState(false);
const [error, setError] = useState(""); // const [error, setError] = useState("");
useEffect(() => { // useEffect(() => {
if (!projectId || !days) return; // if (!projectId || !days) return;
const fetchAttendanceOverview = async () => { // const fetchAttendanceOverview = async () => {
setLoading(true); // setLoading(true);
setError(""); // setError("");
try { // try {
const response = await GlobalRepository.getAttendanceOverview(projectId, days); // const response = await GlobalRepository.getAttendanceOverview(projectId, days);
setAttendanceOverviewData(response.data); // setAttendanceOverviewData(response.data);
} catch (err) { // } catch (err) {
setError("Failed to fetch attendance overview data."); // setError("Failed to fetch attendance overview data.");
} finally { // } finally {
setLoading(false); // setLoading(false);
} // }
}; // };
fetchAttendanceOverview(); // fetchAttendanceOverview();
}, [projectId, days]); // }, [projectId, days]);
return { attendanceOverviewData, loading, error }; // return { attendanceOverviewData, loading, error };
}; // };
// -------------------Query---------------------------- // -------------------Query----------------------------
@ -232,16 +232,17 @@ export const useDashboardTasksCardData = (projectId) => {
} }
}) })
} }
// export const useAttendanceOverviewData = (projectId, days) => { export const useAttendanceOverviewData = (projectId, days) => {
// return useQuery({ return useQuery({
// queryKey:["dashboardAttendanceOverView",projectId], queryKey:["dashboardAttendanceOverView",projectId,days],
// queryFn:async()=> { queryFn:async()=> {
// const resp = await GlobalRepository.getAttendanceOverview(projectId, days); const resp = await GlobalRepository.getAttendanceOverview(projectId, days);
// return resp.data; return resp.data;
// } },
// }) enabled:!!projectId
// } })
}
export const useDashboardProjectsCardData = () => { export const useDashboardProjectsCardData = () => {
return useQuery({ return useQuery({
@ -252,4 +253,44 @@ export const useDashboardProjectsCardData = () => {
return resp.data; 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;
},
});
};

View File

@ -399,7 +399,6 @@ export const useUpdateBucket = (onSuccessCallBack) => {
mutationFn: async ({ bucketId, BucketPayload }) => mutationFn: async ({ bucketId, BucketPayload }) =>
await DirectoryRepository.UpdateBuckets(bucketId, BucketPayload), await DirectoryRepository.UpdateBuckets(bucketId, BucketPayload),
onSuccess: (_, variables) => { onSuccess: (_, variables) => {
debugger;
queryClient.invalidateQueries({ queryKey: ["bucketList"] }); queryClient.invalidateQueries({ queryKey: ["bucketList"] });
showToast("Bucket updated successfully", "success"); showToast("Bucket updated successfully", "success");
if (onSuccessCallBack) onSuccessCallBack(); if (onSuccessCallBack) onSuccessCallBack();
@ -415,7 +414,7 @@ export const useUpdateBucket = (onSuccessCallBack) => {
}); });
}; };
export const useAssignEmpToBucket = () => { export const useAssignEmpToBucket = (onSuccessCallBack) => {
return useMutation({ return useMutation({
mutationFn: async ({ bucketId, EmployeePayload }) => mutationFn: async ({ bucketId, EmployeePayload }) =>
await DirectoryRepository.AssignedBuckets(bucketId, EmployeePayload), await DirectoryRepository.AssignedBuckets(bucketId, EmployeePayload),
@ -464,6 +463,7 @@ export const useCreateContact = (onSuccessCallBack) => {
await DirectoryRepository.CreateContact(contactPayload), await DirectoryRepository.CreateContact(contactPayload),
onSuccess: (_, variables) => { onSuccess: (_, variables) => {
queryClient.invalidateQueries({ queryKey: ["contacts"] }); queryClient.invalidateQueries({ queryKey: ["contacts"] });
queryClient.invalidateQueries({ queryKey: ["bucketList"] });
showToast("Contact created Successfully", "success"); showToast("Contact created Successfully", "success");
if (onSuccessCallBack) onSuccessCallBack(); if (onSuccessCallBack) onSuccessCallBack();
}, },
@ -483,6 +483,7 @@ export const useUpdateContact = (onSuccessCallBack) => {
mutationFn: async ({ contactId, contactPayload }) => mutationFn: async ({ contactId, contactPayload }) =>
await DirectoryRepository.UpdateContact(contactId, contactPayload), await DirectoryRepository.UpdateContact(contactId, contactPayload),
onSuccess: (_, variables) => { onSuccess: (_, variables) => {
queryClient.invalidateQueries({ queryKey: ["Contact"] });
queryClient.invalidateQueries({ queryKey: ["contacts"] }); queryClient.invalidateQueries({ queryKey: ["contacts"] });
showToast("Contact updated Successfully", "success"); showToast("Contact updated Successfully", "success");
if (onSuccessCallBack) onSuccessCallBack(); if (onSuccessCallBack) onSuccessCallBack();
@ -548,7 +549,6 @@ export const useUpdateNote = (onSuccessCallBack) => {
mutationFn: async ({ noteId, notePayload }) => mutationFn: async ({ noteId, notePayload }) =>
await DirectoryRepository.UpdateNote(noteId, notePayload), await DirectoryRepository.UpdateNote(noteId, notePayload),
onSuccess: (_, variables) => { onSuccess: (_, variables) => {
queryClient.invalidateQueries({ queryKey: ["Contact"] });
queryClient.invalidateQueries({ queryKey: ["Notes"] }); queryClient.invalidateQueries({ queryKey: ["Notes"] });
queryClient.invalidateQueries({ queryKey: ["ContactNotes"] }); queryClient.invalidateQueries({ queryKey: ["ContactNotes"] });
showToast("Note updated Successfully", "success"); showToast("Note updated Successfully", "success");

View File

@ -120,7 +120,7 @@ export const useUploadDocument = (onSuccessCallBack) => {
DocumentRepository.uploadDocument(DocumentPayload), DocumentRepository.uploadDocument(DocumentPayload),
onSuccess: (data, variables) => { onSuccess: (data, variables) => {
queryClient.invalidateQueries({ queryKey: ["DocumentList"] }); queryClient.invalidateQueries({ queryKey: ["DocumentList"] });
queryClient.invalidateQueries({ queryKey: ["Document"] });
if (onSuccessCallBack) onSuccessCallBack(); if (onSuccessCallBack) onSuccessCallBack();
}, },
onError: (error) => { onError: (error) => {
@ -141,7 +141,7 @@ export const useUpdateDocument = (onSuccessCallBack) => {
onSuccess: (data, variables) => { onSuccess: (data, variables) => {
const { documentId } = variables; const { documentId } = variables;
queryClient.invalidateQueries({ queryKey: ["DocumentList"] }); queryClient.invalidateQueries({ queryKey: ["DocumentList"] });
queryClient.invalidateQueries({ queryKey: ["Document", documentId] }); queryClient.invalidateQueries({ queryKey: ["Document"] });
if (onSuccessCallBack) onSuccessCallBack(); if (onSuccessCallBack) onSuccessCallBack();
}, },
onError: (error) => { onError: (error) => {
@ -187,6 +187,7 @@ export const useActiveInActiveDocument = ()=>{
onSuccess: (data, variables) => { onSuccess: (data, variables) => {
const {isActive} = variables; const {isActive} = variables;
queryClient.invalidateQueries({ queryKey: ["DocumentList"] }); queryClient.invalidateQueries({ queryKey: ["DocumentList"] });
queryClient.invalidateQueries({ queryKey: ["Document"] });
showToast(`Document ${isActive ? "restored":"Deleted"} successfully`,"success") showToast(`Document ${isActive ? "restored":"Deleted"} successfully`,"success")
}, },
onError: (error) => { onError: (error) => {

View File

@ -137,6 +137,7 @@ export const useEmployeesAllOrByProjectId = (
return res.data; return res.data;
} }
}; };
const { const {
data: employees = [], data: employees = [],
isLoading, isLoading,
@ -157,18 +158,6 @@ export const useEmployeesAllOrByProjectId = (
}; };
}; };
// New Employee get list by CureentOrganization
export const useEmployeesByOrganization = (showInactive) => {
return useQuery({
queryKey: ["employeesByOrganization", showInactive],
queryFn: async () => {
const res = await EmployeeRepository.getAllEmployeeList(showInactive);
return res.data;
},
});
};
// ManageEmployee.jsx // ManageEmployee.jsx
export const useEmployeeProfile = (employeeId) => { export const useEmployeeProfile = (employeeId) => {
const isEnabled = !!employeeId; const isEnabled = !!employeeId;
@ -195,11 +184,11 @@ export const useEmployeeProfile = (employeeId) => {
}; };
}; };
export const useEmployeesName = (projectId, search, allEmployee) => { export const useEmployeesName = (projectId, search,forAll) => {
return useQuery({ return useQuery({
queryKey: ["employees", projectId, search, allEmployee], queryKey: ["employees", projectId, search,forAll],
queryFn: async () => queryFn: async () =>
await EmployeeRepository.getEmployeeName(projectId, search, allEmployee), await EmployeeRepository.getEmployeeName(projectId, search,forAll),
staleTime: 5 * 60 * 1000, // Optional: cache for 5 minutes staleTime: 5 * 60 * 1000, // Optional: cache for 5 minutes
}); });
@ -226,14 +215,15 @@ export const useUpdateEmployee = () => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: (employeeData) => mutationFn: async (employeeData) =>
EmployeeRepository.manageEmployee(employeeData), await EmployeeRepository.manageEmployee(employeeData),
onSuccess: (_, variables) => { onSuccess: (_, variables) => {
debugger;
const id = variables?.id || variables?.employeeId; const id = variables?.id || variables?.employeeId;
const isAllEmployee = variables.IsAllEmployee; const isAllEmployee = variables.IsAllEmployee;
// Cache invalidation // Cache invalidation
queryClient.invalidateQueries({ queryKey: ["employeeProfile", id] }); queryClient.invalidateQueries({ queryKey: ["employeeProfile"] });
queryClient.invalidateQueries({ queryKey: ["allEmployees"] }); queryClient.invalidateQueries({ queryKey: ["allEmployees"] });
// queryClient.invalidateQueries(['employeeProfile', id]); // queryClient.invalidateQueries(['employeeProfile', id]);
queryClient.invalidateQueries({ queryKey: ["projectEmployees"] }); queryClient.invalidateQueries({ queryKey: ["projectEmployees"] });

View File

@ -10,7 +10,7 @@ import moment from "moment";
const cleanFilter = (filter) => { const cleanFilter = (filter) => {
const cleaned = { ...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) { if (Array.isArray(cleaned[key]) && cleaned[key].length === 0) {
delete cleaned[key]; delete cleaned[key];
} }

View File

@ -8,19 +8,20 @@ export const useHasUserPermission = (permission) => {
data: projectPermissions = [], data: projectPermissions = [],
isLoading, isLoading,
isError, isError,
} = useAllProjectLevelPermissions(selectedProject); } = useAllProjectLevelPermissions();
// set selectedProject to call api- selectedProject
if (isLoading || !permission) return false; if (isLoading || !permission) return false;
const globalPerms = profile?.featurePermissions ?? []; const globalPerms = profile?.featurePermissions ?? [];
const projectPerms = projectPermissions ?? []; // const projectPerms = projectPermissions ?? [];
if (selectedProject) { // if (selectedProject) {
if (projectPerms.length === 0) { // if (projectPerms.length === 0) {
return projectPerms.includes(permission); // return projectPerms.includes(permission);
} else { // } else {
return projectPerms.includes(permission); // return projectPerms.includes(permission);
} // }
} else { // } else {
return globalPerms.includes(permission); // return globalPerms.includes(permission);
} // }
return globalPerms.includes(permission);
}; };

View File

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

View File

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

View File

@ -3,7 +3,7 @@ import { cacheData, getCachedData } from "../slices/apiDataManager";
import ProjectRepository from "../repositories/ProjectRepository"; import ProjectRepository from "../repositories/ProjectRepository";
import { useProfile } from "./useProfile"; import { useProfile } from "./useProfile";
import { useDispatch, useSelector } from "react-redux"; import { useDispatch, useSelector } from "react-redux";
import { setProjectId } from "../slices/localVariablesSlice"; import { setProjectId } from "../slices/localVariablesSlice";
import EmployeeList from "../components/Directory/EmployeeList"; import EmployeeList from "../components/Directory/EmployeeList";
import eventBus from "../services/eventBus"; import eventBus from "../services/eventBus";
import { import {
@ -12,12 +12,26 @@ import {
useQuery, useQuery,
useQueryClient, useQueryClient,
} from "@tanstack/react-query"; } from "@tanstack/react-query";
import showToast from "../services/toastService"; import showToast from "../services/toastService";
export const useCurrentService = () => { export const useCurrentService = () => {
return useSelector((store) => store.globalVariables.selectedServiceId); 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------------------- // ------------------------------Query-------------------
export const useProjects = () => { export const useProjects = () => {
@ -294,21 +308,9 @@ export const useProjectAssignedOrganizations = (projectId) => {
enabled: !!projectId, enabled: !!projectId,
}); });
}; };
export const useProjectAssignedOrganizationsName = (projectId) => {
return useQuery({
queryKey: ["projectAssignedOrganiztionsName", projectId],
queryFn: async () => {
const resp = await ProjectRepository.getProjectAssignedOrganizationsName(
projectId
);
return resp.data;
},
enabled: !!projectId,
});
};
export const useProjectAssignedServices = (projectId) => { export const useProjectAssignedServices = (projectId) => {
return useQuery({ return useQuery({
queryKey: ["projectAssignedServices", projectId], queryKey: ["projectAssignedOrganization", projectId],
queryFn: async () => { queryFn: async () => {
const resp = await ProjectRepository.getProjectAssignedServices( const resp = await ProjectRepository.getProjectAssignedServices(
projectId projectId

View File

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

View File

@ -6,6 +6,7 @@ import { useDispatch } from "react-redux";
import { setCurrentTenant } from "../slices/globalVariablesSlice"; import { setCurrentTenant } from "../slices/globalVariablesSlice";
import { ITEMS_PER_PAGE } from "../utils/constants"; import { ITEMS_PER_PAGE } from "../utils/constants";
import moment from "moment"; import moment from "moment";
import { queryClient } from "../layouts/AuthLayout";
const cleanFilter = (filter) => { const cleanFilter = (filter) => {
const cleaned = { ...filter }; const cleaned = { ...filter };
@ -71,6 +72,7 @@ export const useSubscriptionPlan = (freq) => {
// ------------Mutation--------------------- // ------------Mutation---------------------
export const useCreateTenant = (onSuccessCallback) => { export const useCreateTenant = (onSuccessCallback) => {
const clinet = queryClient()
const dispatch = useDispatch(); const dispatch = useDispatch();
return useMutation({ return useMutation({
mutationFn: async (tenantPayload) => { mutationFn: async (tenantPayload) => {
@ -87,6 +89,9 @@ export const useCreateTenant = (onSuccessCallback) => {
operationMode = 2; // tenant exists but subscription not added yet operationMode = 2; // tenant exists but subscription not added yet
} }
clinet.invalidateQueries({queryKey:["Tenants"]})
dispatch(setCurrentTenant({ operationMode, data })); dispatch(setCurrentTenant({ operationMode, data }));
if (onSuccessCallback) onSuccessCallback(); if (onSuccessCallback) onSuccessCallback();

View File

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

View File

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

View File

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

View File

@ -1,5 +1,10 @@
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import React from "react"; import React, {
useEffect,
useImperativeHandle,
forwardRef,
useMemo,
} from "react";
import { FormProvider, useForm } from "react-hook-form"; import { FormProvider, useForm } from "react-hook-form";
import { import {
contactsFilter, contactsFilter,
@ -8,70 +13,101 @@ import {
import { useContactFilter } from "../../hooks/useDirectory"; import { useContactFilter } from "../../hooks/useDirectory";
import { ExpenseFilterSkeleton } from "../../components/Expenses/ExpenseSkeleton"; import { ExpenseFilterSkeleton } from "../../components/Expenses/ExpenseSkeleton";
import SelectMultiple from "../../components/common/SelectMultiple"; import SelectMultiple from "../../components/common/SelectMultiple";
import { useParams } from "react-router-dom";
const ContactFilterPanel = ({ onApply, clearFilter }) => { const ContactFilterPanel = forwardRef(
const { data, isError, isLoading, error, isFetched, isFetching } = ({ onApply, clearFilter, setFilterdata }, ref) => {
useContactFilter(); const { data, isError, isLoading, error, isFetched, isFetching } =
useContactFilter();
const { status } = useParams();
const methods = useForm({ const dynamicdefaultContactFilter = useMemo(() => {
resolver: zodResolver(contactsFilter), return {
defaultValues: defaultContactFilter, ...defaultContactFilter,
}); bucketIds: defaultContactFilter.bucketIds || [],
categoryIds: defaultContactFilter.categoryIds || [],
};
}, [status]);
const closePanel = () => { const methods = useForm({
document.querySelector(".offcanvas.show .btn-close")?.click(); resolver: zodResolver(contactsFilter),
}; defaultValues: dynamicdefaultContactFilter,
});
const { register, handleSubmit, reset, watch } = methods; const { handleSubmit, reset, setValue, getValues } = methods;
const onSubmit = (formData) => { useImperativeHandle(ref, () => ({
onApply(formData); resetFieldValue: (name, value) => {
closePanel(); if (value !== undefined) {
}; setValue(name, value);
} else {
reset({ ...getValues(), [name]: defaultContactFilter[name] });
}
},
getValues, // optional: allows parent to read current form values
}));
const handleClose = () => { useEffect(() => {
reset(defaultContactFilter); if (data && setFilterdata) {
onApply(defaultContactFilter); setFilterdata(data);
closePanel(); }
}; }, [data, setFilterdata]);
if (isLoading || isFetching) return <ExpenseFilterSkeleton />; const closePanel = () => {
if (isError && isFetched) document.querySelector(".offcanvas.show .btn-close")?.click();
return <div>Something went wrong Here- {error.message} </div>; };
return (
<FormProvider {...methods}>
<form onSubmit={handleSubmit(onSubmit)} className="p-2 text-start">
<div className="row g-2">
<SelectMultiple
name="bucketIds"
label="Buckets :"
options={data.buckets}
labelKey="name"
valueKey="id"
/>
<SelectMultiple
name="categoryIds"
label="Contact Category :"
options={data.contactCategories}
labelKey={(item) => item.name}
valueKey="id"
/>
</div>
<div className="d-flex justify-content-end py-3 gap-2">
<button
type="button"
className="btn btn-label-secondary btn-sm"
onClick={handleClose}
>
Clear
</button>
<button type="submit" className="btn btn-primary btn-sm">
Apply
</button>
</div>
</form>
</FormProvider>
);
};
export default ContactFilterPanel; const onSubmit = (formData) => {
onApply(formData);
closePanel();
};
const handleClose = () => {
reset(defaultContactFilter);
onApply(defaultContactFilter);
closePanel();
};
if (isLoading || isFetching) return <ExpenseFilterSkeleton />;
if (isError && isFetched)
return <div>Something went wrong {error?.message}</div>;
return (
<FormProvider {...methods}>
<form onSubmit={handleSubmit(onSubmit)} className="p-2 text-start">
<div className="row g-2">
<SelectMultiple
name="bucketIds"
label="Buckets:"
options={data?.buckets || []}
labelKey="name"
valueKey="id"
/>
<SelectMultiple
name="categoryIds"
label="Contact Category:"
options={data?.contactCategories || []}
labelKey={(item) => item.name}
valueKey="id"
/>
</div>
<div className="d-flex justify-content-end py-3 gap-2">
<button
type="button"
className="btn btn-label-secondary btn-xs"
onClick={handleClose}
>
Clear
</button>
<button type="submit" className="btn btn-primary btn-xs">
Apply
</button>
</div>
</form>
</FormProvider>
);
}
);
export default ContactFilterPanel;

View File

@ -1,26 +1,30 @@
import React, { useEffect, useState } from "react";
import React, { useEffect, useRef, useState } from "react";
import { useFab } from "../../Context/FabContext"; import { useFab } from "../../Context/FabContext";
import { useContactList } from "../../hooks/useDirectory"; import { useContactList } from "../../hooks/useDirectory";
import { useDirectoryContext } from "./DirectoryPage"; import { useDirectoryContext } from "./DirectoryPage";
import CardViewContact from "../../components/Directory/CardViewContact"; import CardViewContact from "../../components/Directory/CardViewContact";
import { ITEMS_PER_PAGE } from "../../utils/constants"; import { ITEMS_PER_PAGE } from "../../utils/constants";
import ContactFilterPanel from "./ContactFilterPanel"; import ContactFilterPanel from "./ContactFilterPanel";
import ContactFilterChips from "../../components/Directory/ContactFilterChips";
import { defaultContactFilter } from "../../components/Directory/DirectorySchema"; import { defaultContactFilter } from "../../components/Directory/DirectorySchema";
import { useDebounce } from "../../utils/appUtils"; import { useDebounce } from "../../utils/appUtils";
import Pagination from "../../components/common/Pagination"; import Pagination from "../../components/common/Pagination";
import ListViewContact from "../../components/Directory/ListViewContact"; import ListViewContact from "../../components/Directory/ListViewContact";
import { CardViewContactSkeleton, ListViewContactSkeleton } from "../../components/Directory/DirectoryPageSkeleton"; import Loader from "../../components/common/Loader";
// Utility function to format contacts for CSV export // Utility for CSV export
const formatExportData = (contacts) => { const formatExportData = (contacts) => {
return contacts.map(contact => ({ return contacts.map((contact) => ({
Email: contact.contactEmails?.map(e => e.emailAddress).join(", ") || "", Email: contact.contactEmails?.map((e) => e.emailAddress).join(", ") || "",
Phone: contact.contactPhones?.map(p => p.phoneNumber).join(", ") || "", Phone: contact.contactPhones?.map((p) => p.phoneNumber).join(", ") || "",
Created: contact.createdAt ? new Date(contact.createdAt).toLocaleString() : "", Created: contact.createdAt
? new Date(contact.createdAt).toLocaleString()
: "",
Location: contact.address || "", Location: contact.address || "",
Organization: contact.organization || "", Organization: contact.organization || "",
Category: contact.contactCategory?.name || "", Category: contact.contactCategory?.name || "",
Tags: contact.tags?.map(t => t.name).join(", ") || "", Tags: contact.tags?.map((t) => t.name).join(", ") || "",
Buckets: contact.bucketIds?.join(", ") || "", Buckets: contact.bucketIds?.join(", ") || "",
})); }));
}; };
@ -28,8 +32,10 @@ const formatExportData = (contacts) => {
const ContactsPage = ({ projectId, searchText, onExport }) => { const ContactsPage = ({ projectId, searchText, onExport }) => {
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
const [filters, setFilter] = useState(defaultContactFilter); const [filters, setFilter] = useState(defaultContactFilter);
const [filterData, setFilterdata] = useState(null);
const debouncedSearch = useDebounce(searchText, 500); const debouncedSearch = useDebounce(searchText, 500);
const { showActive, gridView } = useDirectoryContext(); const { showActive, gridView } = useDirectoryContext();
const updatedRef = useRef();
const { data, isError, isLoading, error } = useContactList( const { data, isError, isLoading, error } = useContactList(
showActive, showActive,
projectId, projectId,
@ -40,13 +46,19 @@ const ContactsPage = ({ projectId, searchText, onExport }) => {
); );
const { setOffcanvasContent, setShowTrigger } = useFab(); const { setOffcanvasContent, setShowTrigger } = useFab();
// clear filters
const clearFilter = () => setFilter(defaultContactFilter); const clearFilter = () => setFilter(defaultContactFilter);
useEffect(() => { useEffect(() => {
setShowTrigger(true); setShowTrigger(true);
setOffcanvasContent( setOffcanvasContent(
"Contacts Filters", "Contacts Filters",
<ContactFilterPanel onApply={setFilter} clearFilter={clearFilter} /> <ContactFilterPanel
ref={updatedRef}
onApply={setFilter}
clearFilter={clearFilter}
setFilterdata={setFilterdata}
/>
); );
return () => { return () => {
@ -55,7 +67,7 @@ const ContactsPage = ({ projectId, searchText, onExport }) => {
}; };
}, []); }, []);
// 🔹 Format contacts for export // export data
useEffect(() => { useEffect(() => {
if (data?.data && onExport) { if (data?.data && onExport) {
onExport(formatExportData(data.data)); onExport(formatExportData(data.data));
@ -68,15 +80,54 @@ const ContactsPage = ({ projectId, searchText, onExport }) => {
} }
}; };
const handleRemoveChip = (key, id) => {
setFilter((prev) => {
const updated = { ...prev };
if (Array.isArray(updated[key])) {
updated[key] = updated[key].filter((v) => v !== id);
updatedRef.current?.resetFieldValue(key, updated[key]);
} else {
updated[key] = null;
updatedRef.current?.resetFieldValue(key, null);
}
return updated;
});
};
if (isError) return <div>{error.message}</div>; if (isError) return <div>{error.message}</div>;
// if (isLoading) return gridView ? <CardViewContactSkeleton /> : <ListViewContactSkeleton />;
return ( return (
<div className="row mt-5"> <div className="row mt-4">
{/* Chips Section */}
<div className="col-12 mb-2">
<ContactFilterChips
filters={filters}
filterData={filterData}
removeFilterChip={handleRemoveChip}
clearFilter={clearFilter}
/>
</div>
{/* Grid / List View */}
{gridView ? ( {gridView ? (
<> <>
{isLoading && <Loader />}
{data?.data?.length === 0 && (
<div className="py-4 text-center">
{searchText
? `No contact found for "${searchText}"`
: "No contacts found"}
</div>
)}
{data?.data?.map((contact) => ( {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} /> <CardViewContact IsActive={showActive} contact={contact} />
</div> </div>
))} ))}
@ -95,6 +146,7 @@ const ContactsPage = ({ projectId, searchText, onExport }) => {
<div className="col-12"> <div className="col-12">
<ListViewContact <ListViewContact
data={data?.data} data={data?.data}
isLoading={isLoading}
Pagination={ Pagination={
<Pagination <Pagination
currentPage={currentPage} currentPage={currentPage}
@ -109,4 +161,4 @@ const ContactsPage = ({ projectId, searchText, onExport }) => {
); );
}; };
export default ContactsPage; export default ContactsPage;

View File

@ -19,9 +19,15 @@ import BucketList from "../../components/Directory/BucketList";
import { MainDirectoryPageSkeleton } from "../../components/Directory/DirectoryPageSkeleton"; import { MainDirectoryPageSkeleton } from "../../components/Directory/DirectoryPageSkeleton";
import ContactProfile from "../../components/Directory/ContactProfile"; import ContactProfile from "../../components/Directory/ContactProfile";
import GlobalModel from "../../components/common/GlobalModel"; import GlobalModel from "../../components/common/GlobalModel";
import { exportToCSV } from "../../utils/exportUtils";
import ConfirmModal from "../../components/common/ConfirmModal"; import ConfirmModal from "../../components/common/ConfirmModal";
import { useSelectedProject } from "../../slices/apiDataManager"; import { useSelectedProject } from "../../slices/apiDataManager";
import {
exportToCSV,
exportToExcel,
exportToPDF,
exportToPDF1,
printTable,
} from "../../utils/tableExportUtils";
const NotesPage = lazy(() => import("./NotesPage")); const NotesPage = lazy(() => import("./NotesPage"));
const ContactsPage = lazy(() => import("./ContactsPage")); const ContactsPage = lazy(() => import("./ContactsPage"));
@ -44,7 +50,7 @@ export default function DirectoryPage({ IsPage = true, projectId = null }) {
const [searchNote, setSearchNote] = useState(""); const [searchNote, setSearchNote] = useState("");
const [activeTab, setActiveTab] = useState("notes"); const [activeTab, setActiveTab] = useState("notes");
const { setActions } = useFab(); const { setActions } = useFab();
const [gridView, setGridView] = useState(false); const [gridView, setGridView] = useState(true);
const [isOpenBucket, setOpenBucket] = useState(false); const [isOpenBucket, setOpenBucket] = useState(false);
const [isManageContact, setManageContact] = useState({ const [isManageContact, setManageContact] = useState({
isOpen: false, isOpen: false,
@ -64,11 +70,49 @@ export default function DirectoryPage({ IsPage = true, projectId = null }) {
const [ContactData, setContactData] = useState([]); const [ContactData, setContactData] = useState([]);
const handleExport = (type) => { const handleExport = (type) => {
if (activeTab === "notes" && type === "csv") { let exportData = activeTab === "notes" ? notesData : ContactData;
exportToCSV(notesData, "notes.csv"); if (!exportData?.length) return;
}
if (activeTab === "contacts" && type === "csv") { switch (type) {
exportToCSV(ContactData, "contact.csv"); 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> ></Breadcrumb>
)} )}
<div className="card"> <div className="card ">
<div className="d-flex-row px-2"> <div className="d-flex-row px-2">
<div className="d-flex justify-content-between align-items-center mb-1"> <div className="d-flex justify-content-between align-items-center mb-1">
<ul className="nav nav-tabs"> <ul className="nav nav-tabs">
@ -160,118 +204,152 @@ export default function DirectoryPage({ IsPage = true, projectId = null }) {
</a> </a>
</li> </li>
</ul> </ul>
</div>
<div className="mb-1 px-md-2 px-0 py-3"> <div className="mb-1 px-2 py-3">
<div className="row"> <div className="d-flex align-items-center justify-content-between">
<div className="col-12 col-md-10 mb-2"> <div className="d-flex align-items-center gap-3">
{activeTab === "notes" && ( {activeTab === "notes" && (
<div className="col-8 col-md-3">
<input <input
type="search" type="search"
className="form-control form-control-sm" className="form-control form-control-sm"
placeholder="Search notes..." placeholder="Search notes..."
value={searchNote} value={searchNote}
onChange={(e) => setSearchNote(e.target.value)} onChange={(e) => setSearchNote(e.target.value)}
/> />
</div> )}
)}
{activeTab === "contacts" && ( {activeTab === "contacts" && (
<div className="d-flex align-items-center gap-3"> <div className="d-flex align-items-center gap-3">
<div className="col-12 col-md-8 d-flex flex-row gap-2"> <div className="d-flex gap-2 align-items-center">
<div className="col-7 col-md-4"> <input
<input type="search"
type="search" className="form-control form-control-sm"
className="form-control form-control-sm" placeholder="Search contacts..."
placeholder="Search contacts..." value={searchContact}
value={searchContact} onChange={(e) => setsearchContact(e.target.value)}
onChange={(e) => setsearchContact(e.target.value)} />
/> <div className="d-none d-md-flex gap-2">
</div> {" "}
<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 <button
className={`btn btn-sm p-1 ${ className="dropdown-item d-flex align-items-center gap-2"
!gridView ? "btn-primary" : "btn-outline-primary" onClick={() => handleExport("csv")}
}`}
onClick={() => setGridView(false)}
> >
<i className="bx bx-list-ul"></i> <i className="bx bx-file"></i>
<span>Export to CSV</span>
</button> </button>
</li>
<li>
<button <button
className={`btn btn-sm p-1 ${ className="dropdown-item d-flex align-items-center gap-2"
gridView ? " btn-primary" : " btn-outline-primary" 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)} onClick={() => setGridView(true)}
> >
<i className="bx bx-grid-alt"></i> <i className="bx bx-grid-alt"></i> Card View
</button> </span>
<div className="form-check form-switch d-flex align-items-center d-none d-md-flex"> </li>
<input
type="checkbox"
className="form-check-input"
role="switch"
id="inactiveEmployeesCheckbox"
checked={showActive}
onChange={(e) => setShowActive(e.target.checked)}
/>
<label
className="form-check-label ms-2"
htmlFor="inactiveEmployeesCheckbox"
>
{showActive ? "Active" : "Inactive"} Contacts
</label>
</div>
</div>
<li className={` d-block d-md-none ${activeTab === "contacts" ? "d-block":"d-none"}`}>
</div> <span
)} className={`dropdown-item ${
</div> !gridView ? "text-primary" : ""
<div className="col-12 col-md-2 d-flex justify-content-end align-items-center gap-2"> }`}
<div className={`form-check form-switch d-flex align-items-center ${activeTab === "contacts" ? " d-flex d-md-none m-0":"d-none" }`}> onClick={() => setGridView(false)}
<input
type="checkbox"
className="form-check-input"
role="switch"
id="inactiveEmployeesCheckbox"
checked={showActive}
onChange={(e) => setShowActive(e.target.checked)}
/>
<label
className="form-check-label ms-2"
htmlFor="inactiveEmployeesCheckbox"
> >
{showActive ? "Active" : "Inactive"} Contacts <i className="bx bx-list-ul"></i> List View
</label> </span>
</div> </li>
<div className=" btn-group">
<button {/* Divider */}
className="btn btn-sm btn-label-secondary dropdown-toggle" {activeTab === "contacts" && (
type="button" <li>
data-bs-toggle="dropdown" <hr className="dropdown-divider" />
aria-expanded="false" </li>
> )}
<i className="bx bx-export me-2 bx-sm"></i>Export </ul>
</button> </div>
<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>
</div> </div>
</div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<div> <div>
<Suspense fallback={<MainDirectoryPageSkeleton />}> <Suspense fallback={<MainDirectoryPageSkeleton />}>
{activeTab === "notes" && ( {activeTab === "notes" && (

View File

@ -1,29 +1,38 @@
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import React from "react"; import React, { useEffect, useImperativeHandle, forwardRef, useMemo } from "react";
import { FormProvider, useForm } from "react-hook-form"; import { FormProvider, useForm } from "react-hook-form";
import { import {
defaultNotesFilter, defaultNotesFilter,
notesFilter, notesFilter,
} from "../../components/Directory/DirectorySchema"; } from "../../components/Directory/DirectorySchema";
import { useContactFilter, useNoteFilter } from "../../hooks/useDirectory"; import { useNoteFilter } from "../../hooks/useDirectory";
import { ExpenseFilterSkeleton } from "../../components/Expenses/ExpenseSkeleton"; import { ExpenseFilterSkeleton } from "../../components/Expenses/ExpenseSkeleton";
import SelectMultiple from "../../components/common/SelectMultiple"; import SelectMultiple from "../../components/common/SelectMultiple";
const NoteFilterPanel = ({ onApply, clearFilter }) => { const NoteFilterPanel = forwardRef(({ onApply, clearFilter, setFilterdata }, ref) => {
const { data, isError, isLoading, error, isFetched, isFetching } = const { data, isError, isLoading, error, isFetched, isFetching } = useNoteFilter();
useNoteFilter();
//Add this for Filter chip remover
const dynamicdefaultNotesFilter = useMemo(() => {
return {
...defaultNotesFilter,
bucketIds: defaultNotesFilter.bucketIds || [],
categoryIds: defaultNotesFilter.categoryIds || [],
};
}, [status]);
const methods = useForm({ const methods = useForm({
resolver: zodResolver(notesFilter), resolver: zodResolver(notesFilter),
defaultValues: defaultNotesFilter, defaultValues: dynamicdefaultNotesFilter,
}); });
const { handleSubmit, reset, setValue, getValues } = methods;
const closePanel = () => { const closePanel = () => {
document.querySelector(".offcanvas.show .btn-close")?.click(); document.querySelector(".offcanvas.show .btn-close")?.click();
}; };
const { register, handleSubmit, reset, watch } = methods;
const onSubmit = (formData) => { const onSubmit = (formData) => {
onApply(formData); onApply(formData);
closePanel(); closePanel();
@ -31,47 +40,72 @@ const NoteFilterPanel = ({ onApply, clearFilter }) => {
const handleClose = () => { const handleClose = () => {
reset(defaultNotesFilter); reset(defaultNotesFilter);
onApply(defaultNotesFilter); onApply(defaultNotesFilter);
closePanel(); closePanel();
}; };
//Add this for Filter chip remover
useImperativeHandle(ref, () => ({
resetFieldValue: (name, value) => {
if (value !== undefined) {
setValue(name, value);
} else {
reset({ ...getValues(), [name]: defaultNotesFilter[name] });
}
},
getValues,
}));
useEffect(() => {
if (data && setFilterdata) {
setFilterdata(data);
}
}, [data, setFilterdata]);
if (isLoading || isFetching) return <ExpenseFilterSkeleton />;
if (isError && isFetched)
return <div>Something went wrong Here- {error.message} </div>;
return ( return (
<FormProvider {...methods}> <FormProvider {...methods}>
<form onSubmit={handleSubmit(onSubmit)} className="p-2 text-start"> <form onSubmit={handleSubmit(onSubmit)} className="p-2 text-start">
<div className="row g-2"> {isLoading || isFetching ? (
<SelectMultiple <ExpenseFilterSkeleton />
name="createdByIds" ) : isError && isFetched ? (
label="Created By :" <div>Something went wrong here: {error?.message}</div>
options={data.createdBy} ) : (
labelKey="name" <>
valueKey="id" <div className="row g-2">
/> <SelectMultiple
<SelectMultiple name="createdByIds"
name="organizations" label="Created By :"
label="Organization:" options={data?.createdBy || []}
options={data.organizations} labelKey="name"
labelKey={(item) => item.name} valueKey="id"
valueKey="id" />
/> <SelectMultiple
</div> name="organizations"
<div className="d-flex justify-content-end py-3 gap-2"> label="Organization:"
<button options={data?.organizations || []}
type="button" labelKey={(item) => item.name}
className="btn btn-label-secondary btn-sm" valueKey="id"
onClick={handleClose} />
> </div>
Clear
</button> <div className="d-flex justify-content-end py-3 gap-2">
<button type="submit" className="btn btn-primary btn-sm"> <button
Apply type="button"
</button> className="btn btn-label-secondary btn-sm"
</div> onClick={handleClose}
>
Clear
</button>
<button type="submit" className="btn btn-primary btn-sm">
Apply
</button>
</div>
</>
)}
</form> </form>
</FormProvider> </FormProvider>
); );
}; });
export default NoteFilterPanel; export default NoteFilterPanel;

View File

@ -1,5 +1,4 @@
// NotesPage.jsx import React, { useEffect, useRef, useState } from "react";
import React, { useEffect, useState } from "react";
import { useFab } from "../../Context/FabContext"; import { useFab } from "../../Context/FabContext";
import { useNotes } from "../../hooks/useDirectory"; import { useNotes } from "../../hooks/useDirectory";
import NoteFilterPanel from "./NoteFilterPanel"; import NoteFilterPanel from "./NoteFilterPanel";
@ -9,11 +8,14 @@ import { useDebounce } from "../../utils/appUtils";
import NoteCardDirectoryEditable from "../../components/Directory/NoteCardDirectoryEditable"; import NoteCardDirectoryEditable from "../../components/Directory/NoteCardDirectoryEditable";
import Pagination from "../../components/common/Pagination"; import Pagination from "../../components/common/Pagination";
import { NoteCardSkeleton } from "../../components/Directory/DirectoryPageSkeleton"; import { NoteCardSkeleton } from "../../components/Directory/DirectoryPageSkeleton";
import NoteFilterChips from "../../components/Directory/NoteFilterChips";
const NotesPage = ({ projectId, searchText, onExport }) => { const NotesPage = ({ projectId, searchText, onExport }) => {
const [filters, setFilter] = useState(defaultNotesFilter); const [filters, setFilter] = useState(defaultNotesFilter);
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
const debouncedSearch = useDebounce(searchText, 500); const debouncedSearch = useDebounce(searchText, 500);
const [filterData, setFilterdata] = useState(null);
const updatedRef = useRef();
const { data, isLoading, isError, error } = useNotes( const { data, isLoading, isError, error } = useNotes(
projectId, projectId,
@ -33,7 +35,12 @@ const NotesPage = ({ projectId, searchText, onExport }) => {
setShowTrigger(true); setShowTrigger(true);
setOffcanvasContent( setOffcanvasContent(
"Notes Filters", "Notes Filters",
<NoteFilterPanel onApply={setFilter} clearFilter={clearFilter} /> <NoteFilterPanel
ref={updatedRef} //Call here
onApply={setFilter}
clearFilter={clearFilter}
setFilterdata={setFilterdata}
/>
); );
return () => { return () => {
@ -42,11 +49,27 @@ const NotesPage = ({ projectId, searchText, onExport }) => {
}; };
}, []); }, []);
// 🔹 Format data for export const handleRemoveChip = (key, id) => {
setFilter((prev) => {
const updated = { ...prev };
if (Array.isArray(updated[key])) {
updated[key] = updated[key].filter((v) => v !== id);
updatedRef.current?.resetFieldValue(key, updated[key]); //IMP
} else {
updated[key] = null;
updatedRef.current?.resetFieldValue(key, null);
}
return updated;
});
};
// Format data for export
const formatExportData = (notes) => { const formatExportData = (notes) => {
return notes.map((n) => ({ return notes.map((n) => ({
ContactName: n.contactName || "", ContactName: n.contactName || "",
Note: n.note ? n.note.replace(/<[^>]+>/g, "") : "", // strip HTML tags Note: n.note ? n.note.replace(/<[^>]+>/g, "") : "",
Organization: n.organizationName || "", Organization: n.organizationName || "",
CreatedBy: n.createdBy CreatedBy: n.createdBy
? `${n.createdBy.firstName || ""} ${n.createdBy.lastName || ""}`.trim() ? `${n.createdBy.firstName || ""} ${n.createdBy.lastName || ""}`.trim()
@ -59,7 +82,6 @@ const NotesPage = ({ projectId, searchText, onExport }) => {
})); }));
}; };
// 🔹 Pass formatted notes to parent for export
useEffect(() => { useEffect(() => {
if (data?.data && onExport) { if (data?.data && onExport) {
onExport(formatExportData(data.data)); onExport(formatExportData(data.data));
@ -77,6 +99,12 @@ const NotesPage = ({ projectId, searchText, onExport }) => {
return ( return (
<div className="d-flex flex-column text-start mt-3"> <div className="d-flex flex-column text-start mt-3">
<NoteFilterChips
filters={filters}
filterData={filterData}
removeFilterChip={handleRemoveChip}
/>
{data?.data?.length > 0 ? ( {data?.data?.length > 0 ? (
<> <>
{data.data.map((noteItem) => ( {data.data.map((noteItem) => (
@ -96,7 +124,6 @@ const NotesPage = ({ projectId, searchText, onExport }) => {
</div> </div>
</> </>
) : ( ) : (
// Card for "No notes available"
<div <div
className="card text-center d-flex align-items-center justify-content-center" className="card text-center d-flex align-items-center justify-content-center"
style={{ height: "200px" }} style={{ height: "200px" }}
@ -104,9 +131,9 @@ const NotesPage = ({ projectId, searchText, onExport }) => {
<p className="text-muted mb-0"> <p className="text-muted mb-0">
{debouncedSearch {debouncedSearch
? `No notes found matching "${searchText}"` ? `No notes found matching "${searchText}"`
: Object.keys(filters).some((k) => filters[k] && filters[k].length) : Object.keys(filters).some((k) => filters[k]?.length)
? "No notes found for the applied filters." ? "No notes found for the applied filters."
: "No notes available."} : "No notes available."}
</p> </p>
</div> </div>
)} )}
@ -114,4 +141,4 @@ const NotesPage = ({ projectId, searchText, onExport }) => {
); );
}; };
export default NotesPage; export default NotesPage;

View File

@ -1,17 +1,16 @@
import React, { createContext, useContext, useState, useEffect } from "react"; import React, { createContext, useContext, useState, useEffect, useRef } from "react";
import { useForm } from "react-hook-form"; import { useForm, useFormContext } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import { useSelector } from "react-redux"; import { useSelector } from "react-redux";
import ExpenseList from "../../components/Expenses/ExpenseList";
import ViewExpense from "../../components/Expenses/ViewExpense";
import Breadcrumb from "../../components/common/Breadcrumb"; import Breadcrumb from "../../components/common/Breadcrumb";
import GlobalModel from "../../components/common/GlobalModel"; 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 ManageExpense from "../../components/Expenses/ManageExpense";
import ExpenseFilterPanel from "../../components/Expenses/ExpenseFilterPanel"; import ExpenseFilterPanel from "../../components/Expenses/ExpenseFilterPanel";
import ExpenseFilterChips from "../../components/Expenses/ExpenseFilterChips";
// Context & Hooks
import { useFab } from "../../Context/FabContext"; import { useFab } from "../../Context/FabContext";
import { useHasUserPermission } from "../../hooks/useHasUserPermission"; import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { import {
@ -20,11 +19,7 @@ import {
VIEW_SELF_EXPENSE, VIEW_SELF_EXPENSE,
} from "../../utils/constants"; } from "../../utils/constants";
// Schema & Defaults import { defaultFilter, SearchSchema } from "../../components/Expenses/ExpenseSchema";
import {
defaultFilter,
SearchSchema,
} from "../../components/Expenses/ExpenseSchema";
// Context // Context
export const ExpenseContext = createContext(); export const ExpenseContext = createContext();
@ -41,10 +36,10 @@ const ExpensePage = () => {
(store) => store.localVariables.projectId (store) => store.localVariables.projectId
); );
const [filters, setFilter] = useState(); const [filters, setFilters] = useState(defaultFilter);
const [groupBy, setGroupBy] = useState("transactionDate"); const [groupBy, setGroupBy] = useState("transactionDate");
const [searchText, setSearchText] = useState(""); const [searchText, setSearchText] = useState("");
const filterPanelRef = useRef();
const [ManageExpenseModal, setManageExpenseModal] = useState({ const [ManageExpenseModal, setManageExpenseModal] = useState({
IsOpen: null, IsOpen: null,
expenseId: null, expenseId: null,
@ -64,18 +59,31 @@ const ExpensePage = () => {
const IsViewAll = useHasUserPermission(VIEW_ALL_EXPNESE); const IsViewAll = useHasUserPermission(VIEW_ALL_EXPNESE);
const IsViewSelf = useHasUserPermission(VIEW_SELF_EXPENSE); const IsViewSelf = useHasUserPermission(VIEW_SELF_EXPENSE);
const { setOffcanvasContent, setShowTrigger } = useFab(); const { setOffcanvasContent, setShowTrigger } = useFab();
const methods = useForm({
resolver: zodResolver(SearchSchema),
defaultValues: defaultFilter,
});
const { reset } = methods;
const clearFilter = () => { const [filterData, setFilterdata] = useState(defaultFilter);
setFilter(defaultFilter);
reset();
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(() => { useEffect(() => {
@ -84,9 +92,10 @@ const ExpensePage = () => {
setOffcanvasContent( setOffcanvasContent(
"Expense Filters", "Expense Filters",
<ExpenseFilterPanel <ExpenseFilterPanel
onApply={setFilter} ref={filterPanelRef}
onApply={setFilters}
handleGroupBy={setGroupBy} handleGroupBy={setGroupBy}
clearFilter={clearFilter} setFilterdata={setFilterdata}
/> />
); );
} }
@ -101,6 +110,8 @@ const ExpensePage = () => {
setViewExpense, setViewExpense,
setManageExpenseModal, setManageExpenseModal,
setDocumentView, setDocumentView,
filterData,
removeFilterChip
}; };
return ( return (
@ -115,20 +126,18 @@ const ExpensePage = () => {
<div className="card my-3 px-sm-4 px-0"> <div className="card my-3 px-sm-4 px-0">
<div className="card-body py-2 px-3"> <div className="card-body py-2 px-3">
<div className="row align-items-center"> <div className="row align-items-center">
<div className="col-6 "> <div className="col-6">
<div className="d-flex align-items-center"> <input
<input type="search"
type="search" className="form-control form-control-sm w-auto"
className="form-control form-control-sm w-auto" placeholder="Search Expense"
placeholder="Search Expense" value={searchText}
aria-describedby="search-label" onChange={(e) => setSearchText(e.target.value)}
value={searchText} />
onChange={(e) => setSearchText(e.target.value)}
/>
</div>
</div> </div>
<div className="col-6 text-end mt-2 mt-sm-0"> <div className="col-6 text-end mt-2 mt-sm-0">
{IsCreatedAble && ( {IsCreatedAble && (
<button <button
className="btn btn-sm btn-primary" className="btn btn-sm btn-primary"
@ -151,6 +160,8 @@ const ExpensePage = () => {
</div> </div>
</div> </div>
<ExpenseList <ExpenseList
filters={filters} filters={filters}
groupBy={groupBy} groupBy={groupBy}
@ -161,7 +172,7 @@ const ExpensePage = () => {
<div className="card text-center py-1"> <div className="card text-center py-1">
<i className="fa-solid fa-triangle-exclamation fs-5" /> <i className="fa-solid fa-triangle-exclamation fs-5" />
<p> <p>
Access Denied: You don't have permission to perform this action ! Access Denied: You don't have permission to perform this action!
</p> </p>
</div> </div>
)} )}

View File

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

View File

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

Some files were not shown because too many files have changed in this diff Show More