Compare commits

..

49 Commits

Author SHA1 Message Date
12b632f087 added new api for list of org 2025-10-11 18:06:51 +05:30
6ee4fb6d04 Updated TeamEmployeeList to fetch employees using useOrganizationEmployees during search. 2025-10-11 17:48:25 +05:30
67bb685d4b added new api for orgaization dropdown 2025-10-11 16:55:22 +05:30
8fd4e7f3f1 added space between first and last name 2025-10-11 16:30:27 +05:30
aca2decb00 clear fully cache after remove session 2025-10-11 16:26:04 +05:30
f7f4b68997 changed reimburse data during transaction to current date 2025-10-11 15:09:04 +05:30
f839613066 Merge pull request 'Fix: Ensure orgData can be cleared when opening Organization Modal' (#474) from HotChanges_11_10_25 into main
Reviewed-on: #474
Merged
2025-10-11 08:42:26 +00:00
b58bd33774 added requested b and requested at column inside rgularization 2025-10-11 14:08:27 +05:30
136bc94c5b removed dbugger and add new classes 2025-10-11 13:12:23 +05:30
281a956ac8 fixed directory header layout 2025-10-11 12:43:37 +05:30
31882c3d12 REMOVED UNNEEDED CARD CLASS 2025-10-11 11:13:38 +05:30
a64635cd37 Fix: Ensure orgData can be cleared when opening Organization Modal 2025-10-11 10:29:40 +05:30
9b8c8c34ab Merge pull request 'HotChanges_10_10_25' (#472) from HotChanges_10_10_25 into main
Reviewed-on: #472
Merged
2025-10-10 14:50:04 +00:00
704ba79289 prevent to select future date 2025-10-10 20:17:06 +05:30
3440467107 wapped header content into separated div 2025-10-10 18:25:19 +05:30
f4edcfd2f3 changed prod url 2025-10-10 18:18:20 +05:30
62e5c6899a profile icon should display always at end 2025-10-10 18:17:24 +05:30
00a23b3de9 changed class for table responsive 2025-10-10 18:11:43 +05:30
79161a8ede prevent to pick future date 2025-10-10 18:09:35 +05:30
860779d096 fixed service list show in Dialy Task 2025-10-10 18:08:21 +05:30
a2067e150d fixed service list show 2025-10-10 17:51:12 +05:30
edce5ef614 added newhook that return only organization employee for employee list (Active or Inactive) 2025-10-10 16:48:22 +05:30
dd944b3414 datepicker should not take future date 2025-10-10 16:46:34 +05:30
13d3572cf6 fixed datepicke ui 2025-10-10 16:45:43 +05:30
0dd7c19457 added navigation hook to replace path 2025-10-10 15:37:59 +05:30
3cc4f0b416 mismatch service api fixed 2025-10-10 14:15:30 +05:30
f8095ac9bf upgraded progress 2025-10-10 10:55:51 +05:30
6280abf95e added marging between fltes input box 2025-10-09 17:32:39 +05:30
1200937097 Merge pull request 'HotChanges_09_10_25 : Added Daily Task Filter' (#467) from HotChanges_09_10_25 into main
Reviewed-on: #467
Merged
2025-10-09 12:00:21 +00:00
5d1ccb9572 changed buttons size 2025-10-09 17:25:03 +05:30
91ffc5a0e0 added filter for DailyTask Report 2025-10-09 17:23:04 +05:30
1c4804fed2 added for serviceI dropdown list 2025-10-09 16:48:15 +05:30
0e5e716df2 removed debuggger 2025-10-09 16:20:43 +05:30
aecaee7116 addded project when project goin to update state 2025-10-09 15:38:59 +05:30
97dca1a10b removed unused code 2025-10-07 14:53:48 +05:30
c35eacca5a addded filter added inside api 2025-10-07 14:02:25 +05:30
5e27ed36fa Merge pull request 'HotChanges_06-10-25 : Image Gallery and Attendanc CheckIn check-Out' (#459) from HotChanges_06-10-25 into main
Reviewed-on: #459
Merged
2025-10-07 07:12:49 +00:00
8bcfcc5718 fixed attendance - check In -out and persisted date range from Redux store for attendance logs 2025-10-07 07:12:49 +00:00
ad1bef4f7b added gallery and gallery filter 2025-10-07 07:12:49 +00:00
9886fac03e employee attendance display sorted by date, 2025-10-06 17:20:36 +05:30
a28a7fb444 checked-Out Time should be greather than or equal to checked In time 2025-10-06 16:07:31 +05:30
470421b730 added two date and service-name column inside ProjectAssignedOrgslist and fixed inactive fn in project team 2025-10-06 10:58:07 +05:30
7505b790a7 added trim fn to avoid extra spacing 2025-10-06 10:06:31 +05:30
8fd13247c7 Merge pull request 'HotChanges_04_10_25' (#450) from HotChanges_04_10_25 into main
Reviewed-on: #450
Merged
2025-10-05 04:28:55 +00:00
0fec257354 make removeSession flexible to clear local, session, or both 2025-10-05 00:21:19 +05:30
638c033705 fixed employee name show whenever update expense - for paid by 2025-10-05 00:14:39 +05:30
7872e21477 changed date utils and added search employee inside manage expense 2025-10-04 19:50:26 +05:30
6928bbd309 Changes in ProjectRepository api for getProjectInfraByProject 2025-10-04 17:50:54 +05:30
3693af3d00 added missing projects at ManageContact (Edit&Crate) 2025-10-04 16:36:11 +05:30
179 changed files with 5771 additions and 10542 deletions

View File

@ -9,8 +9,6 @@
<meta name="description" content="" />
<!-- <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" /> -->
<!-- Favicon -->
<link rel="icon" type="image/svg+xml" href="/img/favicon.ico" />
@ -107,9 +105,6 @@
<!-- <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.min.js"></script> -->
<!-- <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script> -->
<!-- Flatpickr JS -->
</body>

View File

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

View File

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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 500 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 614 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 364 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 127 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 94 KiB

View File

Before

Width:  |  Height:  |  Size: 860 KiB

After

Width:  |  Height:  |  Size: 860 KiB

View File

Before

Width:  |  Height:  |  Size: 58 KiB

After

Width:  |  Height:  |  Size: 58 KiB

View File

Before

Width:  |  Height:  |  Size: 59 KiB

After

Width:  |  Height:  |  Size: 59 KiB

View File

Before

Width:  |  Height:  |  Size: 50 KiB

After

Width:  |  Height:  |  Size: 50 KiB

View File

Before

Width:  |  Height:  |  Size: 54 KiB

After

Width:  |  Height:  |  Size: 54 KiB

View File

@ -6,12 +6,7 @@ import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import { queryClient } from "./layouts/AuthLayout";
import ModalProvider from "./ModalProvider";
window.addEventListener("unhandledrejection", (event) => {
if (event.reason?.message?.includes("Failed to fetch")) {
event.preventDefault();
console.debug("Network issue (fetch failed) - suppressed");
}
});
const App = () => {
return (

View File

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

View File

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

View File

@ -11,9 +11,8 @@ import { useSelector } from "react-redux";
import { useQueryClient } from "@tanstack/react-query";
import eventBus from "../../services/eventBus";
import { useSelectedProject } from "../../slices/apiDataManager";
import Pagination from "../common/Pagination";
const Attendance = ({ getRole, handleModalData, searchTerm, projectId, organizationId, includeInactive, date }) => {
const Attendance = ({ getRole, handleModalData, searchTerm, projectId, organizationId, }) => {
const queryClient = useQueryClient();
const [loading, setLoading] = useState(false);
const navigate = useNavigate();
@ -25,7 +24,7 @@ const Attendance = ({ getRole, handleModalData, searchTerm, projectId, organizat
loading: attLoading,
recall: attrecall,
isFetching
} = useAttendance(selectedProject, organizationId, includeInactive, date);
} = useAttendance(selectedProject, organizationId);
const filteredAttendance = ShowPending
? attendance?.filter(
(att) => att?.checkInTime !== null && att?.checkOutTime === null
@ -109,144 +108,177 @@ const Attendance = ({ getRole, handleModalData, searchTerm, projectId, organizat
return () => eventBus.off("employee", employeeHandler);
}, [employeeHandler]);
return (
<>
<div>
<div
className="table-responsive text-nowrap h-100"
style={{ minHeight: "200px" }} // Ensures fixed height
>
<div className="d-flex text-start align-items-center py-2">
<strong>Date : {formatUTCToLocalTime(todayDate)}</strong>
<div className="form-check form-switch text-start m-0 ms-5">
<input
type="checkbox"
className="form-check-input"
role="switch"
id="inactiveEmployeesCheckbox"
disabled={isFetching}
checked={ShowPending}
onChange={(e) => setShowPending(e.target.checked)}
/>
<label className="form-check-label ms-0">Show Pending</label>
</div>
<div
className="table-responsive text-nowrap h-100"
style={{ minHeight: "200px" }} // Ensures fixed height
>
<div className="d-flex text-start align-items-center py-2">
<strong>Date : {formatUTCToLocalTime(todayDate)}</strong>
<div className="form-check form-switch text-start m-0 ms-5">
<input
type="checkbox"
className="form-check-input"
role="switch"
id="inactiveEmployeesCheckbox"
disabled={isFetching}
checked={ShowPending}
onChange={(e) => setShowPending(e.target.checked)}
/>
<label className="form-check-label ms-0">Show Pending</label>
</div>
{attLoading ? (
<div>Loading...</div>
) : currentItems?.length > 0 ? (
<>
<table className="table ">
<thead>
<tr className="border-top-1">
<th colSpan={2}>Name</th>
<th>Role</th>
{/* <th>Organization</th> */}
<th>
<i className="bx bxs-down-arrow-alt text-success"></i>
Check-In
</th>
<th>
<i className="bx bxs-up-arrow-alt text-danger"></i>Check-Out
</th>
<th>Actions</th>
</tr>
</thead>
<tbody className="table-border-bottom-0 ">
{currentItems &&
currentItems
.sort((a, b) => {
const checkInA = a?.checkInTime
? new Date(a.checkInTime)
: new Date(0);
const checkInB = b?.checkInTime
? new Date(b.checkInTime)
: new Date(0);
return checkInB - checkInA;
})
.map((item) => (
<tr key={item.employeeId}>
<td colSpan={2}>
<div className="d-flex justify-content-start align-items-center">
<Avatar
firstName={item.firstName}
lastName={item.lastName}
></Avatar>
<div className="d-flex flex-column">
<a
onClick={(e) =>
navigate(
`/employee/${item.employeeId}?for=attendance`
)
}
className="text-heading text-truncate cursor-pointer"
>
<span className="fw-normal">
{item.firstName} {item.lastName}
</span>
</a>
</div>
</div>
</td>
<td>{item.jobRoleName}</td>
{/* <td>{item.organizationName || "--"}</td> */}
<td>
{item.checkInTime
? convertShortTime(item.checkInTime)
: "--"}
</td>
<td>
{item.checkOutTime
? convertShortTime(item.checkOutTime)
: "--"}
</td>
<td className="text-center">
<RenderAttendanceStatus
attendanceData={item}
handleModalData={handleModalData}
Tab={1}
currentDate={null}
/>
</td>
</tr>
))}
{!attendance && (
<tr>
<td
colSpan={7}
className="text-center text-secondary"
style={{ height: "200px" }}
>
No employees assigned to the project!
</td>
</tr>
)}
</tbody>
</table>
</>
) : (
<div
className="d-flex justify-content-center align-items-center text-muted"
style={{ height: "200px" }}
>
{searchTerm
? "No results found for your search."
: attendanceList.length === 0
? "No employees assigned to the project."
: "No pending records available."}
</div>
)}
</div>
{!loading && finalFilteredData.length > ITEMS_PER_PAGE && (
<Pagination
currentPage={currentPage}
totalPages={totalPages}
onPageChange={paginate}
/>
{attLoading ? (
<div>Loading...</div>
) : currentItems?.length > 0 ? (
<>
<table className="table ">
<thead>
<tr className="border-top-1">
<th colSpan={2}>Name</th>
<th>Role</th>
<th>Organization</th>
<th>
<i className="bx bxs-down-arrow-alt text-success"></i>
Check-In
</th>
<th>
<i className="bx bxs-up-arrow-alt text-danger"></i>Check-Out
</th>
<th>Actions</th>
</tr>
</thead>
<tbody className="table-border-bottom-0 ">
{currentItems &&
currentItems
.sort((a, b) => {
const checkInA = a?.checkInTime
? new Date(a.checkInTime)
: new Date(0);
const checkInB = b?.checkInTime
? new Date(b.checkInTime)
: new Date(0);
return checkInB - checkInA;
})
.map((item) => (
<tr key={item.employeeId}>
<td colSpan={2}>
<div className="d-flex justify-content-start align-items-center">
<Avatar
firstName={item.firstName}
lastName={item.lastName}
></Avatar>
<div className="d-flex flex-column">
<a
onClick={(e) =>
navigate(
`/employee/${item.employeeId}?for=attendance`
)
}
className="text-heading text-truncate cursor-pointer"
>
<span className="fw-normal">
{item.firstName} {item.lastName}
</span>
</a>
</div>
</div>
</td>
<td>{item.jobRoleName}</td>
<td>{item.organizationName || "--"}</td>
<td>
{item.checkInTime
? convertShortTime(item.checkInTime)
: "--"}
</td>
<td>
{item.checkOutTime
? convertShortTime(item.checkOutTime)
: "--"}
</td>
<td className="text-center">
<RenderAttendanceStatus
attendanceData={item}
handleModalData={handleModalData}
Tab={1}
currentDate={null}
/>
</td>
</tr>
))}
{!attendance && (
<tr>
<td
colSpan={7}
className="text-center text-secondary"
style={{ height: "200px" }}
>
No employees assigned to the project!
</td>
</tr>
)}
</tbody>
</table>
{!loading && finalFilteredData.length > ITEMS_PER_PAGE && (
<nav aria-label="Page ">
<ul className="pagination pagination-sm justify-content-end py-1">
<li
className={`page-item ${currentPage === 1 ? "disabled" : ""
}`}
>
<button
className="page-link btn-xs"
onClick={() => paginate(currentPage - 1)}
>
&laquo;
</button>
</li>
{[...Array(totalPages)].map((_, index) => (
<li
key={index}
className={`page-item ${currentPage === index + 1 ? "active" : ""
}`}
>
<button
className="page-link "
onClick={() => paginate(index + 1)}
>
{index + 1}
</button>
</li>
))}
<li
className={`page-item ${currentPage === totalPages ? "disabled" : ""
}`}
>
<button
className="page-link "
onClick={() => paginate(currentPage + 1)}
>
&raquo;
</button>
</li>
</ul>
</nav>
)}
</>
) : (
<div
className="d-flex justify-content-center align-items-center text-muted"
style={{ height: "200px" }}
>
{searchTerm
? "No results found for your search."
: attendanceList.length === 0
? "No employees assigned to the project."
: "No pending records available."}
</div>
)}
</div>
</>

View File

@ -5,14 +5,16 @@ import { convertShortTime } from "../../utils/dateUtils";
import RenderAttendanceStatus from "./RenderAttendanceStatus";
import { useSelector, useDispatch } from "react-redux";
import DateRangePicker from "../common/DateRangePicker";
import { clearCacheKey, getCachedData, useSelectedProject } from "../../slices/apiDataManager";
import {
clearCacheKey,
getCachedData,
useSelectedProject,
} from "../../slices/apiDataManager";
import eventBus from "../../services/eventBus";
import AttendanceRepository from "../../repositories/AttendanceRepository";
import { useAttendancesLogs } from "../../hooks/useAttendance";
import { queryClient } from "../../layouts/AuthLayout";
import { ITEMS_PER_PAGE } from "../../utils/constants";
import Pagination from "../common/Pagination";
import { useNavigate } from "react-router-dom";
const usePagination = (data, itemsPerPage) => {
const [currentPage, setCurrentPage] = useState(1);
@ -36,204 +38,149 @@ const usePagination = (data, itemsPerPage) => {
};
const AttendanceLog = ({ handleModalData, searchTerm, organizationId }) => {
// const selectedProject = useSelector(
// (store) => store.localVariables.projectId
// );
const selectedProject = useSelectedProject();
const [dateRange, setDateRange] = useState({ startDate: "", endDate: "" });
const dispatch = useDispatch();
const [loading, setLoading] = useState(false);
const [showPending, setShowPending] = useState(false)
const selectedProject = useSelectedProject();
const [dateRange, setDateRange] = useState({ startDate: "", endDate: "" });
const dispatch = useDispatch();
const [loading, setLoading] = useState(false);
const [showPending, setShowPending] = useState(false);
const [isRefreshing, setIsRefreshing] = useState(false);
const [isRefreshing, setIsRefreshing] = useState(false);
const [processedData, setProcessedData] = useState([]);
const navigate = useNavigate();
const today = new Date();
today.setHours(0, 0, 0, 0);
const today = new Date();
today.setHours(0, 0, 0, 0);
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
const isSameDay = (dateStr) => {
if (!dateStr) return false;
const d = new Date(dateStr);
d.setHours(0, 0, 0, 0);
return d.getTime() === today.getTime();
};
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 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 + a.lastName).toLowerCase();
const nameB = (b.firstName + b.lastName).toLowerCase();
return nameA.localeCompare(nameB);
};
const sortByName = (a, b) => {
const nameA = a.firstName.toLowerCase() + a.lastName.toLowerCase();
const nameB = b.firstName.toLowerCase() + b.lastName.toLowerCase();
return nameA?.localeCompare(nameB);
};
const { data = [], isLoading, error, refetch, isFetching } = useAttendancesLogs(
selectedProject,
dateRange.startDate,
dateRange.endDate,
organizationId
);
const {
data = [],
isLoading,
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 processedData = useMemo(() => {
const filteredData = showPending
? data.filter((item) => item.checkOutTime === null)
: data;
const group1 = filteredData
.filter((d) => d.activity === 1 && isSameDay(d.checkInTime))
.sort(sortByName);
const group2 = filteredData
.filter((d) => d.activity === 4 && isSameDay(d.checkOutTime))
.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 group1 = filteredData.filter((d) => d.activity === 1 && isSameDay(d.checkInTime)).sort(sortByName);
const group2 = filteredData.filter((d) => d.activity === 4 && isSameDay(d.checkOutTime)).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];
// Group by date
const groupedByDate = sortedList.reduce((acc, item) => {
const date = (item.checkInTime || item.checkOutTime)?.split("T")[0];
if (date) {
acc[date] = acc[date] || [];
acc[date].push(item);
}
return acc;
}, {});
const groupedByDate = sortedList.reduce((acc, item) => {
const date = (item.checkInTime || item.checkOutTime)?.split("T")[0];
if (date) {
acc[date] = acc[date] || [];
acc[date].push(item);
}
return acc;
}, {});
const sortedDates = Object.keys(groupedByDate).sort(
(a, b) => new Date(b) - new Date(a)
);
const finalData = sortedDates.flatMap((date) => groupedByDate[date]);
setProcessedData(finalData);
}, [showPending]);
useEffect(() => {
if (data?.length) {
filtering(data);
}
const sortedDates = Object.keys(groupedByDate).sort((a, b) => new Date(b) - new Date(a));
return sortedDates.flatMap((date) => groupedByDate[date]);
}, [data, showPending]);
const filteredSearchData = useMemo(() => {
if (!searchTerm) return processedData;
// New useEffect to handle search filtering
const filteredSearchData = useMemo(() => {
if (!searchTerm) {
return processedData;
const lowercased = searchTerm.toLowerCase();
return processedData.filter((item) =>
`${item.firstName} ${item.lastName}`.toLowerCase().includes(lowercased)
);
}, [processedData, searchTerm]);
const {
currentPage,
totalPages,
currentItems: paginatedAttendances,
paginate,
resetPage,
} = usePagination(filteredSearchData, 20);
useEffect(() => {
resetPage();
}, [filteredSearchData]);
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;
}
return oldData.map((record) =>
record.id === msg.response.id ? { ...record, ...msg.response } : record
);
});
resetPage();
}
const lowercasedSearchTerm = searchTerm.toLowerCase();
return processedData.filter((item) => {
const fullName = `${item.firstName} ${item.lastName}`.toLowerCase();
return fullName.includes(lowercasedSearchTerm);
});
}, [processedData, searchTerm]);
},
[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]
);
const {
currentPage,
totalPages,
currentItems: paginatedAttendances,
paginate,
resetPage,
} = usePagination(filteredSearchData, 20);
useEffect(() => {
eventBus.on("employee", employeeHandler);
return () => eventBus.off("employee", employeeHandler);
}, [employeeHandler]);
useEffect(() => {
resetPage();
}, [filteredSearchData, resetPage]);
const handler = useCallback(
(msg) => {
const { startDate, endDate } = dateRange;
const checkIn = msg.response.checkInTime.substring(0, 10);
if (
selectedProject === msg.projectId &&
startDate <= checkIn &&
checkIn <= endDate
) {
queryClient.setQueriesData(["attendanceLogs"], (oldData) => {
if (!oldData) {
queryClient.invalidateQueries({ queryKey: ["attendanceLogs"] });
return;
}
const updatedAttendance = oldData.map((record) =>
record.id === msg.response.id
? { ...record, ...msg.response }
: record
);
filtering(updatedAttendance);
return updatedAttendance;
});
resetPage();
}
},
[selectedProject, dateRange, filtering, resetPage]
);
useEffect(() => {
eventBus.on("attendance_log", handler);
return () => eventBus.off("attendance_log", handler);
}, [handler]);
const employeeHandler = useCallback(
(msg) => {
const { startDate, endDate } = dateRange;
if (data.some((item) => item.employeeId == msg.employeeId)) {
// dispatch(
// fetchAttendanceData({
// ,
// fromDate: startDate,
// toDate: endDate,
// })
// );
refetch()
}
},
[selectedProject, dateRange, data, refetch]
);
useEffect(() => {
eventBus.on("employee", employeeHandler);
return () => eventBus.off("employee", employeeHandler);
}, [employeeHandler]);
return (
<>
<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"
>
<div className="d-flex align-items-center my-0 ms-sm-8 ">
<div className="d-flex align-items-center my-0 ">
<DateRangePicker
onRangeChange={setDateRange}
defaultStartDate={yesterday}
/>
<div className="form-check form-switch text-start ms-1 ms-md-5 align-items-center mb-0">
<div className="form-check form-switch text-start ms-1 ms-md-2 align-items-center mb-0">
<input
type="checkbox"
className="form-check-input"
@ -246,11 +193,16 @@ const AttendanceLog = ({ handleModalData, searchTerm, organizationId }) => {
<label className="form-check-label ms-0">Show Pending</label>
</div>
</div>
</div>
<div className="table-responsive text-nowrap " >
<div
className="table-responsive text-nowrap"
style={{ minHeight: "200px" }}
>
{isLoading ? (
<div className="d-flex justify-content-center align-items-center">
<div
className="d-flex justify-content-center align-items-center"
style={{ height: "200px" }}
>
<p className="text-secondary">Loading...</p>
</div>
) : filteredSearchData?.length > 0 ? (
@ -261,10 +213,10 @@ const AttendanceLog = ({ handleModalData, searchTerm, organizationId }) => {
Name
</th>
<th className="border-top-1">Date</th>
{/* <th>Organization</th> */}
<th>Organization</th>
<th>
<i className="bx bxs-down-arrow-alt text-success"></i> Check-In
<i className="bx bxs-down-arrow-alt text-success"></i>{" "}
Check-In
</th>
<th>
<i className="bx bxs-up-arrow-alt text-danger"></i> Check-Out
@ -280,9 +232,9 @@ const AttendanceLog = ({ handleModalData, searchTerm, organizationId }) => {
const previousAttendance = arr[index - 1];
const previousDate = previousAttendance
? moment(
previousAttendance.checkInTime ||
previousAttendance.checkOutTime
).format("YYYY-MM-DD")
previousAttendance.checkInTime ||
previousAttendance.checkOutTime
).format("YYYY-MM-DD")
: null;
if (!previousDate || currentDate !== previousDate) {
@ -308,12 +260,7 @@ const AttendanceLog = ({ handleModalData, searchTerm, organizationId }) => {
lastName={attendance.lastName}
/>
<div className="d-flex flex-column">
<a
onClick={() =>
navigate(`/employee/${attendance.employeeId}?for=attendance`)
}
className="text-heading text-truncate cursor-pointer"
>
<a href="#" className="text-heading text-truncate">
<span className="fw-normal">
{attendance.firstName} {attendance.lastName}
</span>
@ -326,7 +273,7 @@ const AttendanceLog = ({ handleModalData, searchTerm, organizationId }) => {
attendance.checkInTime || attendance.checkOutTime
).format("DD-MMM-YYYY")}
</td>
{/* <td>{attendance.organizationName || "--"}</td> */}
<td>{attendance.organizationName || "--"}</td>
<td>{convertShortTime(attendance.checkInTime)}</td>
<td>
{attendance.checkOutTime
@ -348,7 +295,12 @@ const AttendanceLog = ({ handleModalData, searchTerm, organizationId }) => {
</tbody>
</table>
) : (
<div className="my-12"><span className="text-secondary">No data for this date range. Please choose another.</span></div>
<div className="my-12">
<span className="text-secondary">
No data available for the selected date range. Please Select
another date.
</span>
</div>
)}
</div>
{paginatedAttendances?.length == 0 && filteredSearchData?.length > 0 && (
@ -360,11 +312,47 @@ const AttendanceLog = ({ handleModalData, searchTerm, organizationId }) => {
</div>
)}
{filteredSearchData.length > ITEMS_PER_PAGE && (
<Pagination
currentPage={currentPage}
totalPages={totalPages}
onPageChange={paginate}
/>
<nav aria-label="Page ">
<ul className="pagination pagination-sm justify-content-end py-1">
<li className={`page-item ${currentPage === 1 ? "disabled" : ""}`}>
<button
className="page-link btn-xs"
onClick={() => paginate(currentPage - 1)}
>
&laquo;
</button>
</li>
{Array.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, { useEffect, useState } from "react";
import React, { useState } from "react";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
@ -9,7 +9,6 @@ import showToast from "../../services/toastService";
import { checkIfCurrentDate } from "../../utils/dateUtils";
import { useMarkAttendance } from "../../hooks/useAttendance";
import { useSelectedProject } from "../../slices/apiDataManager";
import { useProjectName } from "../../hooks/useProjects";
const createSchema = (modeldata) => {
return z
@ -20,36 +19,31 @@ const createSchema = (modeldata) => {
.max(200, "Description should be less than 200 characters")
.optional(),
})
.refine(
(data) => {
if (modeldata?.checkInTime && !modeldata?.checkOutTime) {
const checkIn = new Date(modeldata.checkInTime);
const [time, modifier] = data.markTime.split(" ");
const [hourStr, minuteStr] = time.split(":");
let hour = parseInt(hourStr, 10);
const minute = parseInt(minuteStr, 10);
.refine((data) => {
if (modeldata?.checkInTime && !modeldata?.checkOutTime) {
const checkIn = new Date(modeldata.checkInTime);
const [time, modifier] = data.markTime.split(" ");
const [hourStr, minuteStr] = time.split(":");
let hour = parseInt(hourStr, 10);
const minute = parseInt(minuteStr, 10);
if (modifier === "PM" && hour !== 12) hour += 12;
if (modifier === "AM" && hour === 12) hour = 0;
if (modifier === "PM" && hour !== 12) hour += 12;
if (modifier === "AM" && hour === 12) hour = 0;
const checkOut = new Date(checkIn);
checkOut.setHours(hour, minute, 0, 0);
const checkOut = new Date(checkIn);
checkOut.setHours(hour, minute, 0, 0);
return checkOut >= checkIn;
}
return true;
},
{
message: "Checkout time must be later than check-in time",
path: ["markTime"],
return checkOut >= checkIn;
}
);
return true;
}, {
message: "Checkout time must be later than check-in time",
path: ["markTime"],
});
};
const CheckInCheckOut = ({ modeldata, closeModal, handleSubmitForm }) => {
const [currentProject, setCurrentProject] = useState(null);
const projectId = useSelectedProject();
const { projectNames, loading } = useProjectName();
const { mutate: MarkAttendance } = useMarkAttendance();
const [isLoading, setIsLoading] = useState(false);
const coords = usePositionTracker();
@ -101,24 +95,17 @@ const CheckInCheckOut = ({ modeldata, closeModal, handleSubmitForm }) => {
closeModal();
};
useEffect(() => {
if (projectId && projectNames) {
setCurrentProject(
projectNames?.find((project) => project.id === projectId)
);
}
}, [projectNames, projectId, loading]);
return (
<form className="row p-2" onSubmit={handleSubmit(onSubmit)}>
<div className="col-12 d-flex justify-content-center mt-2">
<label className="fs-5 text-dark text-center">
<div className="col-12 d-flex justify-content-center mb-4">
<label className="fs-5 tex-semibold text-center">
{modeldata?.checkInTime && !modeldata?.checkOutTime
? `Check out for ${currentProject?.name}`
: `Check In for ${currentProject?.name}`}
? "Check-Out "
: "Check-In "}
</label>
</div>
<div className="col-6 col-md-6 text-start">
<label className="form-label" htmlFor="checkInDate">
{modeldata?.checkInTime && !modeldata?.checkOutTime
@ -133,7 +120,7 @@ const CheckInCheckOut = ({ modeldata, closeModal, handleSubmitForm }) => {
modeldata?.checkInTime && !modeldata?.checkOutTime
? formatDate(modeldata?.checkInTime?.split("T")[0]) || ""
: formatDate(today)
}
}
disabled
/>
</div>
@ -220,7 +207,7 @@ export const Regularization = ({ modeldata, closeModal, handleSubmitForm }) => {
};
return (
<form className="row " onSubmit={handleSubmit(onSubmit)}>
<form className="row g-2" onSubmit={handleSubmit(onSubmit)}>
<div className="col-12 col-md-12">
<p>Regularize Attendance</p>
<label className="form-label" htmlFor="description">

View File

@ -1,41 +1,45 @@
import React, { useCallback, useEffect, useState, useMemo } from "react";
import Avatar from "../common/Avatar";
import { convertShortTime } from "../../utils/dateUtils";
import { convertShortTime, formatUTCToLocalTime } from "../../utils/dateUtils";
import RegularizationActions from "./RegularizationActions";
import { useSelector } from "react-redux";
import { useRegularizationRequests } from "../../hooks/useAttendance";
import moment from "moment";
import usePagination from "../../hooks/usePagination";
import eventBus from "../../services/eventBus";
import { cacheData, clearCacheKey, useSelectedProject } from "../../slices/apiDataManager";
import {
cacheData,
clearCacheKey,
useSelectedProject,
} from "../../slices/apiDataManager";
import { useQueryClient } from "@tanstack/react-query";
import Pagination from "../common/Pagination";
import { useNavigate } from "react-router-dom";
import { employee } from "../../data/masters";
import Pagination from "../../components/common/Pagination";
const Regularization = ({ handleRequest, searchTerm, projectId, organizationId, IncludeInActive }) => {
const Regularization = ({
handleRequest,
searchTerm,
projectId,
organizationId,
IncludeInActive,
}) => {
const queryClient = useQueryClient();
// var selectedProject = useSelector((store) => store.localVariables.projectId);
const selectedProject = useSelectedProject();
const [regularizesList, setregularizedList] = useState([]);
const navigate = useNavigate();
const { regularizes, loading, error, refetch } =
useRegularizationRequests(selectedProject, organizationId, IncludeInActive);
const { regularizes, loading, error, refetch } = useRegularizationRequests(
selectedProject,
organizationId,
IncludeInActive
);
useEffect(() => {
if (regularizes && regularizes.length) {
setregularizedList((prev) => {
const prevIds = prev.map((i) => i.id).join(",");
const newIds = regularizes.map((i) => i.id).join(",");
if (prevIds !== newIds) {
return regularizes;
}
return prev;
});
if(!regularizes) return
if(regularizes?.length) {
setregularizedList(regularizes);
}
}, [regularizes]);
const sortByName = (a, b) => {
const nameA = a.firstName.toLowerCase() + a.lastName.toLowerCase();
const nameB = b.firstName.toLowerCase() + b.lastName.toLowerCase();
@ -68,48 +72,15 @@ const Regularization = ({ handleRequest, searchTerm, projectId, organizationId,
}
const lowercasedSearchTerm = searchTerm.toLowerCase();
return sortedList.filter((item) => {
const fullName = `${item.firstName} ${item.lastName}`.toLowerCase();
const fullName = `${item?.firstName} ${item?.lastName}`.toLowerCase();
return fullName.includes(lowercasedSearchTerm);
});
}, [regularizesList, searchTerm]);
// const filteredSearchData = useMemo(() => {
// let sortedList = [...regularizesList].sort(sortByName);
// // 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]);
const { currentPage, totalPages, currentItems, paginate } = usePagination(
filteredSearchData,
20
);
useEffect(() => {
eventBus.on("regularization", handler);
@ -130,112 +101,149 @@ const Regularization = ({ handleRequest, searchTerm, projectId, organizationId,
return () => eventBus.off("employee", employeeHandler);
}, [employeeHandler]);
return (
<div>
<div className="table-responsive text-nowrap pb-4" style={{ minHeight: "200px" }}>
{loading ? (
<div className="d-flex justify-content-center align-items-center" style={{ height: "200px" }}>
<p className="text-secondary">Loading...</p>
</div>
) : currentItems?.length > 0 ? (
<table className="table mb-0">
<thead>
<tr>
<th colSpan={2}>Name</th>
<th>Date</th>
{/* <th>Organization</th> */}
<th>
<i className="bx bxs-down-arrow-alt text-success"></i>Check-In
</th>
<th>
<i className="bx bxs-up-arrow-alt text-danger"></i>Check-Out
</th>
<th>Request By</th>
<th>Requested At</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{currentItems?.map((att, index) => (
<tr key={index}>
<td colSpan={2}>
<div className="d-flex justify-content-start align-items-center">
<Avatar
firstName={att.firstName}
lastName={att.lastName}
/>
<div className="d-flex flex-column">
{/* <a href="#" className="text-heading text-truncate">
<div
className="table-responsive text-nowrap pb-4"
style={{ minHeight: "200px" }}
>
{loading ? (
<div
className="d-flex justify-content-center align-items-center"
style={{ height: "200px" }}
>
<p className="text-secondary">Loading...</p>
</div>
) : currentItems?.length > 0 ? (
<table className="table mb-0">
<thead>
<tr>
<th colSpan={2}>Name</th>
<th>Date</th>
<th>Organization</th>
<th>
<i className="bx bxs-down-arrow-alt text-success"></i>Check-In
</th>
<th>
<i className="bx bxs-up-arrow-alt text-danger"></i>Check-Out
</th>
<th colSpan={2}>
Requested By
</th>
<th >
Requested At
</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{currentItems?.map((att, index) => (
<tr key={index}>
<td colSpan={2}>
<div className="d-flex justify-content-start align-items-center">
<Avatar firstName={att.firstName} lastName={att.lastName} />
<div className="d-flex flex-column">
<a href="#" className="text-heading text-truncate">
<span className="fw-normal">
{att.firstName} {att.lastName}
</span>
</a> */}
<a
onClick={() =>
navigate(`/employee/${att.employeeId}?for=attendance`)
}
className="text-heading text-truncate cursor-pointer"
>
<span className="fw-normal">
{att.firstName} {att.lastName}
</span>
</a>
</div>
</a>
</div>
</td>
</div>
</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>
{att.requestedAt ? convertShortTime(att.checkOutTime) : "--"}
</td>
<td colSpan={2}>
{att.requestedBy ? ( <div className="d-flex justify-content-start align-items-center">
<Avatar firstName={att?.requestedBy?.firstName} lastName={att?.requestedBy?.lastName} />
<div className="d-flex flex-column">
<a href="#" className="text-heading text-truncate">
<span className="fw-normal">
{att?.requestedBy?.firstName} {att?.requestedBy?.lastName}
</span>
</a>
</div>
</div>):(<small>--</small>)}
</td>
<td>
{att.checkOutTime ? convertShortTime(att.checkOutTime) : "--"}
</td>
<td>
{att.requestedBy
? `${att.requestedBy?.firstName} ${att.requestedBy?.lastName}`
: "--"}
</td>
<td>
{att.requestedAt
? moment(att.requestedAt).format("DD-MMM-YYYY")
: "--"}
</td>
<td className="text-center ">
<RegularizationActions
attendanceData={att}
handleRequest={handleRequest}
refresh={refetch}
/>
</td>
</tr>
))}
</tbody>
</table>
{att?.requestedAt ? formatUTCToLocalTime(att.requestedAt,true) : "--"}
</td>
<td className="text-center ">
<RegularizationActions
attendanceData={att}
handleRequest={handleRequest}
refresh={refetch}
/>
</td>
</tr>
))}
</tbody>
</table>
) : (
<div
className="d-flex justify-content-center align-items-center"
style={{ height: "200px" }}
>
<span className="text-secondary">
{searchTerm
? "No results found for your search."
: "No Requests Found !"}
</span>
</div>
)}
{/* {!loading && totalPages > 1 && (
<nav aria-label="Page ">
<ul className="pagination pagination-sm justify-content-end py-1 mt-3">
<li className={`page-item ${currentPage === 1 ? "disabled" : ""}`}>
<button
className="page-link btn-xs"
onClick={() => paginate(currentPage - 1)}
>
&laquo;
</button>
</li>
{[...Array(totalPages)].map((_, index) => (
<li
key={index}
className={`page-item ${currentPage === index + 1 ? "active" : ""
}`}
>
<button
className="page-link "
onClick={() => paginate(index + 1)}
>
{index + 1}
</button>
</li>
))}
<li
className={`page-item ${currentPage === totalPages ? "disabled" : ""
}`}
>
<button
className="page-link "
onClick={() => paginate(currentPage + 1)}
>
&raquo;
</button>
</li>
</ul>
</nav>
)} */}
) : (
<div
className="d-flex justify-content-center align-items-center"
style={{ height: "200px" }}
>
<span className="text-secondary">
{searchTerm
? "No results found for your search."
: "No Requests Found !"}
</span>
</div>
)}
</div>
{!loading && totalPages > 1 && (
<Pagination
currentPage={currentPage}
totalPages={totalPages}
onPageChange={paginate}
/>
)}
{totalPages > 0 && (
<Pagination
currentPage={currentPage}
totalPages={totalPages}
onPageChange={paginate}
/>
)}
</div>
);
};

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,205 @@
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

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

@ -1,151 +0,0 @@
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

@ -1,164 +0,0 @@
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

@ -1,156 +0,0 @@
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,11 +19,8 @@ const AssignedBucket = ({ selectedBucket, handleClose }) => {
}
}, [selectedBucket, employeesList]);
const { mutate: AssignEmployee, isPending } = useAssignEmpToBucket(() =>{
setSelectedEmployees([])
const { mutate: AssignEmployee, isPending } = useAssignEmpToBucket(() =>
handleClose()
}
);
const handleSubmit = async (e) => {

View File

@ -1,56 +0,0 @@
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,9 +4,8 @@ import Pagination from "../common/Pagination";
import { useDirectoryContext } from "../../pages/Directory/DirectoryPage";
import { useActiveInActiveContact } from "../../hooks/useDirectory";
import ConfirmModal from "../common/ConfirmModal";
import Loader from "../common/Loader";
const ListViewContact = ({ data, Pagination, isLoading }) => {
const ListViewContact = ({ data, Pagination }) => {
const { showActive, setManageContact, setContactOpen } =
useDirectoryContext();
const [deleteContact, setDeleteContact] = useState({
@ -86,8 +85,6 @@ const ListViewContact = ({ data, Pagination, isLoading }) => {
ActiveInActive({ contactId: contactId, contactStatus: !showActive });
};
if (isLoading) return <Loader />
if (!data || data.length === 0) return <div className="text-center py-12">No Contact Found</div>
return (
<>
<ConfirmModal
@ -100,96 +97,104 @@ const ListViewContact = ({ data, Pagination, isLoading }) => {
paramData={deleteContact.contactId}
isOpen={deleteContact.Open}
/>
<div className="card page-min-h">
<div className="card ">
<div
className="card-datatable table-responsive"
id="horizontal-example"
>
{data && (
<div className="dataTables_wrapper no-footer mx-5 pb-2">
<table className="table dataTable text-nowrap">
<thead>
<tr className="table_header_border">
{contactList?.map((col) => (
<th key={col.key} className={col.align}>
{col.label}
</th>
))}
<th className="sticky-action-column bg-white text-center">
Action
<div className="dataTables_wrapper no-footer mx-5 pb-2">
<table className="table dataTable text-nowrap">
<thead>
<tr className="table_header_border">
{contactList?.map((col) => (
<th key={col.key} className={col.align}>
{col.label}
</th>
</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>
) : (
))}
<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 ${isPending && activeContact === row.id
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>
))
)}
</tbody>
</table>
</div>
)}
} 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>
)}
</tbody>
</table>
{Pagination && (
<div className="d-flex justify-content-start">
{Pagination}
</div>
)}
</div>
</div>
{Pagination && (
<div className="d-flex justify-content-start">{Pagination}</div>
)}
</div>
</>
);

View File

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

View File

@ -1,79 +0,0 @@
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

@ -1,94 +0,0 @@
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, { useEffect, useState, useMemo, useImperativeHandle, forwardRef } from "react";
import React, { useState } from "react";
import { useDocumentFilterEntities } from "../../hooks/useDocument";
import { FormProvider, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
@ -9,34 +9,16 @@ import {
import { DateRangePicker1 } from "../common/DateRangePicker";
import SelectMultiple from "../common/SelectMultiple";
import moment from "moment";
import { useParams } from "react-router-dom";
const DocumentFilterPanel = forwardRef(
({ entityTypeId, onApply, setFilterdata }, ref) => {
const DocumentFilterPanel = ({ entityTypeId, onApply }) => {
const [resetKey, setResetKey] = useState(0);
const { status } = useParams();
const { data, isError, isLoading, error } =
useDocumentFilterEntities(entityTypeId);
//changes
const dynamicDocumentFilterDefaultValues = useMemo(() => {
return {
...DocumentFilterDefaultValues,
uploadedByIds: DocumentFilterDefaultValues.uploadedByIds || [],
documentCategoryIds: DocumentFilterDefaultValues.documentCategoryIds || [],
documentTypeIds: DocumentFilterDefaultValues.documentTypeIds || [],
documentTagIds: DocumentFilterDefaultValues.documentTagIds || [],
startDate: DocumentFilterDefaultValues.startDate,
endDate: DocumentFilterDefaultValues.endDate,
};
}, [status]);
const methods = useForm({
resolver: zodResolver(DocumentFilterSchema),
defaultValues: dynamicDocumentFilterDefaultValues,
defaultValues: DocumentFilterDefaultValues,
});
const { handleSubmit, reset, setValue, watch } = methods;
@ -50,24 +32,6 @@ const DocumentFilterPanel = forwardRef(
document.querySelector(".offcanvas.show .btn-close")?.click();
};
useImperativeHandle(ref, () => ({
resetFieldValue: (name, value) => {
if (value !== undefined) {
setValue(name, value);
} else {
reset({ ...methods.getValues(), [name]: DocumentFilterDefaultValues[name] });
}
},
getValues: methods.getValues, // optional, to read current filter state
}));
//changes
useEffect(() => {
if (data && setFilterdata) {
setFilterdata(data);
}
}, [data, setFilterdata]);
const onSubmit = (values) => {
onApply({
...values,
@ -78,14 +42,14 @@ const DocumentFilterPanel = forwardRef(
? moment.utc(values.endDate, "DD-MM-YYYY").toISOString()
: null,
});
// closePanel();
closePanel();
};
const onClear = () => {
reset(DocumentFilterDefaultValues);
setResetKey((prev) => prev + 1);
onApply(DocumentFilterDefaultValues);
// closePanel();
closePanel();
};
if (isLoading) return <div>Loading...</div>;
@ -99,8 +63,6 @@ const DocumentFilterPanel = forwardRef(
documentTag = [],
} = data?.data || {};
return (
<FormProvider {...methods}>
<form onSubmit={handleSubmit(onSubmit)}>
@ -111,16 +73,18 @@ const DocumentFilterPanel = forwardRef(
<div className="d-inline-flex border rounded-pill overflow-hidden shadow-none">
<button
type="button"
className={`btn px-2 py-1 rounded-0 text-tiny ${isUploadedAt ? "active btn-secondary text-white" : ""
}`}
className={`btn px-2 py-1 rounded-0 text-tiny ${
isUploadedAt ? "active btn-secondary text-white" : ""
}`}
onClick={() => setValue("isUploadedAt", true)}
>
Uploaded On
</button>
<button
type="button"
className={`btn px-2 py-1 rounded-0 text-tiny ${!isUploadedAt ? "active btn-secondary text-white" : ""
}`}
className={`btn px-2 py-1 rounded-0 text-tiny ${
!isUploadedAt ? "active btn-secondary text-white" : ""
}`}
onClick={() => setValue("isUploadedAt", false)}
>
Updated On
@ -225,18 +189,18 @@ const DocumentFilterPanel = forwardRef(
<div className="d-flex justify-content-end py-3 gap-2">
<button
type="button"
className="btn btn-label-secondary btn-sm"
className="btn btn-label-secondary btn-xs"
onClick={onClear}
>
Clear
</button>
<button type="submit" className="btn btn-primary btn-sm">
<button type="submit" className="btn btn-primary btn-xs">
Apply
</button>
</div>
</form>
</FormProvider>
);
});
};
export default DocumentFilterPanel;

View File

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

View File

@ -1,4 +1,4 @@
import React, { createContext, useContext, useEffect, useRef, useState } from "react";
import React, { createContext, useContext, useEffect, useState } from "react";
import GlobalModel from "../common/GlobalModel";
import NewDocument from "./ManageDocument";
import { DOCUMENTS_ENTITIES, UPLOAD_DOCUMENT } from "../../utils/constants";
@ -17,7 +17,6 @@ import ViewDocument from "./ViewDocument";
import DocumentViewerModal from "./DocumentViewerModal";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { useProfile } from "../../hooks/useProfile";
import DocumentFilterChips from "./DocumentFilterChips";
// Context
export const DocumentContext = createContext();
@ -52,14 +51,12 @@ const Documents = ({ Document_Entity, Entity }) => {
const [isSelf, setIsSelf] = useState(false);
const [searchText, setSearchText] = useState("");
const [isActive, setIsActive] = useState(true);
const [filters, setFilter] = useState(DocumentFilterDefaultValues);
const [filters, setFilter] = useState();
const [isRefetching, setIsRefetching] = useState(false);
const [refetchFn, setRefetchFn] = useState(null);
const [DocumentEntity, setDocumentEntity] = useState(Document_Entity);
const { employeeId } = useParams();
const [OpenDocument, setOpenDocument] = useState(false);
const [filterData, setFilterdata] = useState(DocumentFilterDefaultValues);
const updatedRef = useRef();
const [ManageDoc, setManageDoc] = useState({
document: null,
isOpen: false,
@ -95,7 +92,7 @@ const Documents = ({ Document_Entity, Entity }) => {
setShowTrigger(true);
setOffcanvasContent(
"Document Filters",
<DocumentFilterPanel entityTypeId={DocumentEntity} onApply={setFilter} setFilterdata={setFilterdata} ref={updatedRef} />
<DocumentFilterPanel entityTypeId={DocumentEntity} onApply={setFilter} />
);
return () => {
@ -118,35 +115,13 @@ const Documents = ({ Document_Entity, Entity }) => {
setDocumentEntity(Document_Entity);
}
}, [Document_Entity]);
const removeFilterChip = (key, id) => {
const updatedFilters = { ...filters };
if (Array.isArray(updatedFilters[key])) {
updatedFilters[key] = updatedFilters[key].filter((v) => v !== id);
updatedRef.current?.resetFieldValue(key,updatedFilters[key]);
}
else if (key === "dateRange") {
updatedFilters.startDate = null;
updatedFilters.endDate = null;
updatedRef.current?.resetFieldValue("startDate",null);
updatedRef.current?.resetFieldValue("endDate",null);
}
else {
updatedFilters[key] = null;
}
setFilter(updatedFilters);
return updatedFilters;
};
return (
<DocumentContext.Provider value={contextValues}>
<div className="mt-2">
<div className="card page-min-h d-flex p-5">
<DocumentFilterChips filters={filters} filterData={filterData} removeFilterChip={removeFilterChip} />
<div className="mt-5">
<div className="card page-min-h d-flex p-2">
<div className="row align-items-center">
{/* Search */}
<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 col-8 col-md-8 col-lg-4 mb-md-0 align-items-center">
<div className="d-flex">
{" "}
<input
@ -174,7 +149,7 @@ const Documents = ({ Document_Entity, Entity }) => {
</label>
</div>
<div className="col-12 col-md-6 col-lg-8 text-end">
<div className="col-6 col-md-6 col-lg-8 text-end">
{(isSelf || canUploadDocument) && (
<button
className="btn btn-sm btn-primary me-3"
@ -256,4 +231,4 @@ const Documents = ({ Document_Entity, Entity }) => {
);
};
export default Documents;
export default Documents;

View File

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

View File

@ -14,28 +14,24 @@ import { FormProvider, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { localToUtc } from "../../utils/appUtils";
import { useParams } from "react-router-dom";
const EmpAttendance = ({ employee }) => {
const EmpAttendance = () => {
const { employeeId } = useParams();
const [attendances, setAttendnaces] = useState([]);
const [selectedDate, setSelectedDate] = useState("");
const [isModalOpen, setIsModalOpen] = useState(false);
const [attendanceId, setAttendanecId] = useState();
const methods = useForm({
resolver: zodResolver(
z.object({
startDate: z.string(),
endDate: z.string(),
})
),
defaultValues: {
startDate: "",
endDate: "",
startDate: moment().subtract(6, "days").format("DD-MM-YYYY"),
endDate: moment().format("DD-MM-YYYY"),
},
});
const { control, register, handleSubmit, reset, watch } = methods;
const startDate = watch("startDate");
const endDate = watch("endDate");
const { watch } = methods;
const [startDate, endDate] = watch(["startDate", "endDate"]);
const {
data = [],
isLoading: loading,
@ -44,76 +40,21 @@ const EmpAttendance = ({ employee }) => {
error,
refetch,
} = useAttendanceByEmployee(
employee,
localToUtc(startDate),
localToUtc(endDate)
employeeId,
startDate ? localToUtc(startDate) : null,
endDate ? localToUtc(endDate) : null
);
const dispatch = useDispatch();
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(
const sorted = [...data].sort(
(a, b) =>
new Date(b.checkInTime || b.checkOutTime) -
new Date(a.checkInTime || a.checkOutTime)
new Date(b?.checkInTime).getTime() - new Date(a?.checkInTime).getTime()
);
const currentDate = new Date().toLocaleDateString("en-CA");
console.log(sorted);
const { currentPage, totalPages, currentItems, paginate } = usePagination(
sortedFinalList,
sorted,
ITEMS_PER_PAGE
);
@ -123,7 +64,6 @@ const EmpAttendance = ({ employee }) => {
};
const closeModal = () => setIsModalOpen(false);
const onSubmit = (formData) => { };
return (
<>
{isModalOpen && (
@ -131,35 +71,31 @@ const EmpAttendance = ({ employee }) => {
<AttendLogs Id={attendanceId} />
</GlobalModel>
)}
<div className="card px-4 mt-2 py-2 page-min-h ">
<div className="card px-4 mt-5 py-2 " style={{ minHeight: "500px" }}>
<div
className="dataTables_length text-start py-2 d-flex justify-content-between "
id="DataTables_Table_0_length"
>
<div className="col-3 my-0 ">
<div className="col-4 col-md-3 my-0 ">
<>
<FormProvider {...methods}>
<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>
<DateRangePicker1 />
</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 className="table-responsive text-nowrap">
{!loading && data.length === 0 && (
<span style={{ fontSize: "0.9rem" }}>
No attendance record found in selected date range
</span>
)}
{!loading && data.length === 0 && <span>No employee logs</span>}
{isError && <div className="text-center">{error.message}</div>}
{loading && !data && <div className="text-center">Loading...</div>}
{data && data.length > 0 && (
@ -228,7 +164,7 @@ const EmpAttendance = ({ employee }) => {
</table>
)}
</div>
{!loading && sortedFinalList.length > 20 && (
{!loading && data.length > 20 && (
<nav aria-label="Page ">
<ul className="pagination pagination-sm justify-content-end py-1">
<li
@ -244,8 +180,9 @@ const EmpAttendance = ({ employee }) => {
{[...Array(totalPages)].map((_, index) => (
<li
key={index}
className={`page-item ${currentPage === index + 1 ? "active" : ""
}`}
className={`page-item ${
currentPage === index + 1 ? "active" : ""
}`}
>
<button
className="page-link "
@ -256,8 +193,9 @@ const EmpAttendance = ({ employee }) => {
</li>
))}
<li
className={`page-item ${currentPage === totalPages ? "disabled" : ""
}`}
className={`page-item ${
currentPage === totalPages ? "disabled" : ""
}`}
>
<button
className="page-link "

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,50 +0,0 @@
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

@ -1,89 +0,0 @@
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, { forwardRef, useEffect, useImperativeHandle, useState, useMemo } from "react";
import React, { useEffect, useState, useMemo } from "react";
import { FormProvider, useForm, Controller } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { defaultFilter, SearchSchema } from "./ExpenseSchema";
@ -13,11 +13,9 @@ import { useSelector } from "react-redux";
import moment from "moment";
import { useExpenseFilter } from "../../hooks/useExpense";
import { ExpenseFilterSkeleton } from "./ExpenseSkeleton";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import { useLocation } from "react-router-dom";
const ExpenseFilterPanel = forwardRef(({ onApply, handleGroupBy, setFilterdata }, ref) => {
const { status } = useParams();
const navigate = useNavigate();
const ExpenseFilterPanel = ({ onApply, handleGroupBy }) => {
const selectedProjectId = useSelector(
(store) => store.localVariables.projectId
);
@ -31,31 +29,17 @@ const ExpenseFilterPanel = forwardRef(({ onApply, handleGroupBy, setFilterdata }
{ id: "submittedBy", name: "Submitted By" },
{ id: "project", name: "Project" },
{ id: "paymentMode", name: "Payment Mode" },
{ id: "expensesType", name: "Expense Category" },
{ id: "expensesType", name: "Expense Type" },
{ id: "createdAt", name: "Submitted Date" },
].sort((a, b) => a.name.localeCompare(b.name));
}, []);
const [selectedGroup, setSelectedGroup] = useState(groupByList[6]);
const [selectedGroup, setSelectedGroup] = useState(groupByList[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, selectedProjectId]);
const methods = useForm({
resolver: zodResolver(SearchSchema),
defaultValues: dynamicDefaultFilter,
defaultValues: defaultFilter,
});
const { control, handleSubmit, reset, setValue, watch } = methods;
@ -65,30 +49,11 @@ const ExpenseFilterPanel = forwardRef(({ onApply, handleGroupBy, setFilterdata }
document.querySelector(".offcanvas.show .btn-close")?.click();
};
// Change here
useEffect(() => {
if (data && setFilterdata) {
setFilterdata(data);
}
}, [data, setFilterdata]);
const handleGroupChange = (e) => {
const group = groupByList.find((g) => g.id === e.target.value);
if (group) setSelectedGroup(group);
};
useImperativeHandle(ref, () => ({
resetFieldValue: (name, value) => {
// Reset specific field
if (value !== undefined) {
setValue(name, value);
} else {
reset({ ...methods.getValues(), [name]: defaultFilter[name] });
}
},
getValues: methods.getValues, // optional, to read current filter state
}));
const onSubmit = (formData) => {
onApply({
...formData,
@ -96,7 +61,7 @@ const ExpenseFilterPanel = forwardRef(({ onApply, handleGroupBy, setFilterdata }
endDate: moment.utc(formData.endDate, "DD-MM-YYYY").toISOString(),
});
handleGroupBy(selectedGroup.id);
// closePanel();
closePanel();
};
const onClear = () => {
@ -105,55 +70,18 @@ const ExpenseFilterPanel = forwardRef(({ onApply, handleGroupBy, setFilterdata }
setSelectedGroup(groupByList[0]);
onApply(defaultFilter);
handleGroupBy(groupByList[0].id);
// closePanel();
if (status) {
navigate("/expenses", { replace: true });
}
closePanel();
};
// Close popup when navigating to another component
const location = useLocation();
useEffect(() => {
closePanel();
}, [location]);
const [appliedStatusId, setAppliedStatusId] = useState(null);
useEffect(() => {
if (!status || !data) return;
if (status !== appliedStatusId) {
const filterWithStatus = {
...dynamicDefaultFilter,
projectIds: selectedProjectId ? [selectedProjectId] : dynamicDefaultFilter.projectIds || [],
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,
selectedProjectId, // Added dependency
]);
if (isLoading || isFetching) return <ExpenseFilterSkeleton />;
if (isError && isFetched)
return <div>Something went wrong Here- {error.message} </div>;
return (
<>
<FormProvider {...methods}>
@ -164,16 +92,18 @@ const ExpenseFilterPanel = forwardRef(({ onApply, handleGroupBy, setFilterdata }
<div className="d-inline-flex border rounded-pill mb-1 overflow-hidden shadow-none">
<button
type="button"
className={`btn px-2 py-1 rounded-0 text-tiny ${isTransactionDate ? "active btn-primary text-white" : ""
}`}
className={`btn px-2 py-1 rounded-0 text-tiny ${
isTransactionDate ? "active btn-primary text-white" : ""
}`}
onClick={() => setValue("isTransactionDate", true)}
>
Transaction Date
</button>
<button
type="button"
className={`btn px-2 py-1 rounded-0 text-tiny ${!isTransactionDate ? "active btn-primary text-white" : ""
}`}
className={`btn px-2 py-1 rounded-0 text-tiny ${
!isTransactionDate ? "active btn-primary text-white" : ""
}`}
onClick={() => setValue("isTransactionDate", false)}
>
Submitted Date
@ -213,13 +143,6 @@ const ExpenseFilterPanel = forwardRef(({ onApply, handleGroupBy, setFilterdata }
labelKey={(item) => item.name}
valueKey="id"
/>
<SelectMultiple
name="ExpenseTypeIds"
label="Category :"
options={data.expensesType}
labelKey={(item) => item.name}
valueKey="id"
/>
<div className="mb-3">
<label className="form-label">Status :</label>
@ -291,6 +214,6 @@ const ExpenseFilterPanel = forwardRef(({ onApply, handleGroupBy, setFilterdata }
</FormProvider>
</>
);
});
};
export default ExpenseFilterPanel;
export default ExpenseFilterPanel;

View File

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

View File

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

View File

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

View File

@ -1,53 +1,27 @@
import { useState } from "react";
import { useState } from 'react';
const PreviewDocument = ({ imageUrl }) => {
const [loading, setLoading] = useState(true);
const [rotation, setRotation] = useState(0);
return (
<>
<div className="d-flex justify-content-start">
<i
className="bx bx-rotate-right cursor-pointer"
onClick={() => setRotation((prev) => prev + 90)}
></i>
</div>
<div
className="position-relative d-flex flex-column justify-content-center align-items-center"
style={{ minHeight: "80vh" }}
>
<div className="d-flex justify-content-center align-items-center" style={{ minHeight: "50vh" }}>
{loading && (
<div className="text-secondary text-center mb-2">Loading...</div>
<div className="text-secondary text-center mb-2">
Loading...
</div>
)}
<div className="mb-3 d-flex justify-content-center align-items-center">
<img
src={imageUrl}
alt="Full View"
className="img-fluid"
style={{
maxHeight: "80vh",
objectFit: "contain",
display: loading ? "none" : "block",
transform: `rotate(${rotation}deg)`,
transition: "transform 0.3s ease",
}}
onLoad={() => setLoading(false)}
/>
</div>
<div className="position-absolute bottom-0 start-0 justify-content-center gap-2">
<button
className="btn btn-outline-secondary"
onClick={() => setRotation(0)}
title="Reset Rotation"
>
<i className="bx bx-reset"></i> Reset
</button>
</div>
<img
src={imageUrl}
alt="Full View"
className="img-fluid"
style={{
maxHeight: "100vh",
objectFit: "contain",
display: loading ? "none" : "block",
}}
onLoad={() => setLoading(false)}
/>
</div>
</>
);
};

View File

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

View File

@ -1,4 +1,3 @@
import { useCallback, useEffect, useState, useMemo } from "react";
import getGreetingMessage from "../../utils/greetingHandler";
import {
cacheData,
@ -13,106 +12,123 @@ import useMaster from "../../hooks/masterHook/useMaster";
import { useProfile } from "../../hooks/useProfile";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import Avatar from "../../components/common/Avatar";
import { useChangePassword } from "../Context/ChangePasswordContext";
import { useProjects } from "../../hooks/useProjects";
import { useCallback, useEffect, useState } from "react";
import { useProjectName } from "../../hooks/useProjects";
import eventBus from "../../services/eventBus";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { ALLOW_PROJECTSTATUS_ID, MANAGE_PROJECT, UUID_REGEX } from "../../utils/constants";
import { useAuthModal, useLogout } from "../../hooks/useAuth";
import { MANAGE_PROJECT } from "../../utils/constants";
import { useAuthModal, useLogout, useModal } from "../../hooks/useAuth";
const Header = () => {
const { profile } = useProfile();
const { data: masterData } = useMaster();
const location = useLocation();
const dispatch = useDispatch();
const { data, loading } = useMaster();
const navigate = useNavigate();
const { mutate: logout, isPending: logouting } = useLogout();
const { onOpen } = useAuthModal();
const { openChangePassword } = useChangePassword();
const {onOpen} = useAuthModal()
const { onOpen:changePass } = useModal("ChangePassword");
const HasManageProjectPermission = useHasUserPermission(MANAGE_PROJECT);
const { mutate : logout,isPending:logouting} = useLogout()
const pathname = location.pathname;
const isDashboardPath =
/^\/dashboard$/.test(location.pathname) || /^\/$/.test(location.pathname);
const isProjectPath = /^\/projects$/.test(location.pathname);
// ======= MEMO CHECKS =======
const showProjectDropdown = (pathname) => {
const isDirectoryPath = /^\/directory$/.test(pathname);
const isDashboardPath = pathname === "/" || pathname === "/dashboard";
const isProjectPath = pathname === "/projects";
const isDirectory = pathname === "/directory";
const isEmployeeList = pathname === "/employees";
const isEmployeeProfile = UUID_REGEX.test(pathname);
const isMasters = pathname === "/masters";
const isExpensePath = pathname.startsWith("/expenses");
// const isProfilePage = /^\/employee$/.test(location.pathname);
const isProfilePage =
/^\/employee\/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(
pathname
);
const isExpensePage = /^\/expenses$/.test(pathname);
const hideDropPaths =
isDirectory || isEmployeeList || isMasters || isEmployeeProfile || isExpensePath;
return !(isDirectoryPath || isProfilePage || isExpensePage);
};
const allowedProjectStatusIds = [
"603e994b-a27f-4e5d-a251-f3d69b0498ba",
"cdad86aa-8a56-4ff4-b633-9c629057dfef",
"b74da4c2-d07e-46f2-9919-e75e49b12731",
];
const showProjectDropdown = !hideDropPaths;
// ===== Project Names & Selected Project =====
const { projectNames, loading: projectLoading, fetchData } = useProjectName();
const selectedProject = useSelectedProject();
const projectsForDropdown = useMemo(
() =>
isDashboardPath
? projectNames
: projectNames?.filter((project) =>
ALLOW_PROJECTSTATUS_ID.includes(project.projectStatusId)
),
[projectNames, isDashboardPath]
);
const currentProjectDisplayName = useMemo(() => {
if (projectLoading) return "Loading...";
if (!projectNames?.length) return "No Projects Assigned";
if (projectNames.length === 1) return projectNames[0].name;
if (selectedProject === null) return "All Projects";
const selectedObj = projectNames.find((p) => p.id === selectedProject);
return selectedObj
? selectedObj.name
: projectNames[0]?.name || "No Projects Assigned";
}, [projectLoading, projectNames, selectedProject]);
// ===== Role Helper =====
const getRole = (roles, joRoleId) => {
if (!Array.isArray(roles)) return "User";
return roles.find((r) => r.id === joRoleId)?.name || "User";
let role = roles.find((role) => role.id === joRoleId);
return role ? role.name : "User";
};
// ===== Navigate to Profile =====
const handleProfilePage = () =>
navigate(`/employee/${profile?.employeeInfo?.id}`);
const handleProfilePage = () => {
navigate(`/employee/${profile?.employeeInfo?.id}`);
};
const { projectNames, loading: projectLoading, fetchData } = useProjectName();
const selectedProject = useSelectedProject();
const projectsForDropdown = isDashboardPath
? projectNames
: projectNames?.filter((project) =>
allowedProjectStatusIds.includes(project.projectStatusId)
);
let currentProjectDisplayName;
if (projectLoading) {
currentProjectDisplayName = "Loading...";
} else if (!projectNames || projectNames.length === 0) {
currentProjectDisplayName = "No Projects Assigned";
} else if (projectNames.length === 1) {
currentProjectDisplayName = projectNames[0].name;
} else {
if (selectedProject === null) {
currentProjectDisplayName = "All Projects";
} else {
const selectedProjectObj = projectNames.find(
(p) => p?.id === selectedProject
);
currentProjectDisplayName = selectedProjectObj
? selectedProjectObj.name
: "All Projects";
}
}
// ===== Set default project on load =====
useEffect(() => {
if (
projectNames?.length &&
projectNames &&
projectNames.length > 0 &&
selectedProject === undefined &&
!getCachedData("hasReceived")
) {
if (projectNames.length === 1) {
dispatch(setProjectId(projectNames[0].id || null));
dispatch(setProjectId(projectNames[0]?.id || null));
} else {
if (isDashboardPath) {
dispatch(setProjectId(null));
} else {
const firstAllowed = projectNames.find((project) =>
ALLOW_PROJECTSTATUS_ID.includes(project.projectStatusId)
const firstAllowedProject = projectNames.find((project) =>
allowedProjectStatusIds.includes(project.projectStatusId)
);
dispatch(setProjectId(firstAllowed?.id || null));
dispatch(setProjectId(firstAllowedProject?.id || null));
}
}
}
}, [projectNames, selectedProject, dispatch, isDashboardPath]);
// ===== Event Handlers =====
const handler = useCallback(
async (data) => {
if (!HasManageProjectPermission) {
await fetchData();
if (data.projectIds?.includes(selectedProject)) {
const projectExist = data.projectIds.some(
(item) => item === selectedProject
);
if (projectExist) {
cacheData("hasReceived", false);
}
}
@ -122,15 +138,14 @@ const Header = () => {
const newProjectHandler = useCallback(
async (msg) => {
if (
msg.keyword === "Create_Project" ||
projectNames?.some((p) => p.id === msg.response?.id)
) {
if (HasManageProjectPermission && msg.keyword === "Create_Project") {
await fetchData();
} else if (projectNames?.some((item) => item.id === msg.response.id)) {
await fetchData();
cacheData("hasReceived", false);
}
cacheData("hasReceived", false);
},
[projectNames, fetchData]
[HasManageProjectPermission, projectNames, fetchData]
);
useEffect(() => {
@ -147,10 +162,10 @@ const Header = () => {
};
}, [handler, newProjectHandler]);
// ===== Project Change =====
const handleProjectChange = (projectId) => {
dispatch(setProjectId(projectId));
if (isProjectPath && projectId !== null) {
const handleProjectChange = (project) => {
dispatch(setProjectId(project));
if (isProjectPath && project !== null) {
navigate("/projects/details");
}
};
@ -174,7 +189,8 @@ const Header = () => {
className="navbar-nav-right d-flex align-items-center justify-content-between"
id="navbar-collapse"
>
{showProjectDropdown && (
<div className="d-flex align-items-center">
{showProjectDropdown(location.pathname) && (
<div className="align-items-center">
<i className="rounded-circle bx bx-building-house bx-sm-lg bx-md me-2"></i>
<div className="btn-group">
@ -200,14 +216,16 @@ const Header = () => {
className="dropdown-menu"
style={{ overflow: "auto", maxHeight: "300px" }}
>
<li>
<button
className="dropdown-item"
onClick={() => handleProjectChange(null)}
>All Project</button>
</li>
{isDashboardPath && (
<li>
<button
className="dropdown-item"
onClick={() => handleProjectChange(null)}
>
All Projects
</button>
</li>
)}
{[...projectsForDropdown]
.sort((a, b) => a?.name?.localeCompare(b.name))
.map((project) => (
@ -230,11 +248,115 @@ const Header = () => {
</div>
</div>
)}
</div>
<ul className="navbar-nav flex-row align-items-center ms-md-auto">
{/* {HasManageProjectPermission && ( */}
{/* )} */}
<li className="nav-item dropdown-shortcuts navbar-dropdown dropdown me-2 me-xl-0">
<a
className="nav-link dropdown-toggle hide-arrow"
data-bs-toggle="dropdown"
data-bs-auto-close="true"
aria-expanded="false"
>
<i className="icon-base bx bx-grid-alt icon-md"></i>
</a>
<div className="dropdown-menu dropdown-menu-end p-0">
<div className="dropdown-menu-header border-bottom">
<div className="dropdown-header d-flex align-items-center py-3">
<h6 className="mb-0 me-auto">Shortcuts</h6>
<a
className="dropdown-shortcuts-add py-2 cusror-pointer"
data-bs-toggle="tooltip"
data-bs-placement="top"
aria-label="Add shortcuts"
data-bs-original-title="Add shortcuts"
>
<i className="icon-base bx bx-plus-circle text-heading"></i>
</a>
</div>
</div>
<div className="dropdown-shortcuts-list scrollable-container ps">
<div className="row row-bordered overflow-visible g-0">
<div className="dropdown-shortcuts-item col">
<a
onClick={() => navigate(`/dashboard`)}
className="text-heading text-truncate cursor-pointer"
>
<span className="dropdown-shortcuts-icon rounded-circle mb-3">
<i className="icon-base bx bx-home icon-26px text-heading"></i>
</span>
Dashboard
</a>
<small>User Dashboard</small>
</div>
<div className="dropdown-shortcuts-item col">
<a
onClick={() => navigate(`/projects`)}
className="text-heading text-truncate cursor-pointer"
>
<span className="dropdown-shortcuts-icon rounded-circle mb-3">
<i className="icon-base bx bx-building-house icon-26px text-heading"></i>
</span>
Projects
</a>
<small>Projects List</small>
</div>
</div>
<div className="row row-bordered overflow-visible g-0">
<div className="dropdown-shortcuts-item col">
<a
onClick={() => navigate(`/employees`)}
className="text-heading text-truncate cursor-pointer"
>
<span className="dropdown-shortcuts-icon rounded-circle mb-3">
<i className="icon-base bx bxs-user-account icon-26px text-heading"></i>
</span>
Employees
</a>
<small>Manage Employees</small>
</div>
<div className="dropdown-shortcuts-item col">
<a
onClick={() => navigate(`/activities/attendance`)}
className="text-heading text-truncate cursor-pointer"
>
<span className="dropdown-shortcuts-icon rounded-circle mb-3">
<i className="icon-base bx bx-user-check icon-26px text-heading"></i>
</span>
Attendance
</a>
<small>Manage Attendance</small>
</div>
</div>
<div className="row row-bordered overflow-visible g-0">
<div className="dropdown-shortcuts-item col">
<a
onClick={() => navigate(`/activities/task`)}
className="text-heading text-truncate cursor-pointer"
>
<span className="dropdown-shortcuts-icon rounded-circle mb-3">
<i className="icon-base bx bxs-wrench icon-26px text-heading"></i>
</span>
Allocate Work
</a>
<small>Work Allocations</small>
</div>
<div className="dropdown-shortcuts-item col">
<a
onClick={() => navigate(`/activities/records`)}
className="text-heading text-truncate cursor-pointer"
>
<span className="dropdown-shortcuts-icon rounded-circle mb-3">
<i className="icon-base bx bx-list-ul icon-26px text-heading"></i>
</span>
Daily Work Log
</a>
<small>Daily Work Allocations</small>
</div>
</div>
</div>
</div>
</li>
<li className="nav-item navbar-dropdown dropdown-user dropdown">
<a
aria-label="dropdown profile avatar"
@ -266,7 +388,7 @@ const Header = () => {
{profile?.employeeInfo?.firstName}
</span>
<small className="text-muted">
{getRole(masterData, profile?.employeeInfo?.joRoleId)}
{getRole(data, profile?.employeeInfo?.joRoleId)}
</small>
</div>
</div>
@ -275,13 +397,15 @@ const Header = () => {
<li>
<div className="dropdown-divider"></div>
</li>
{/* <li onClick={() => onOpen()}>
<li onClick={()=>onOpen()}>
{" "}
<a className="dropdown-item cusor-pointer">
<a
className="dropdown-item cusor-pointer"
>
<i className="bx bx-transfer-alt me-2"></i>
<span className="align-middle">Switch Workspace</span>
</a>
</li> */}
</li>
<li onClick={handleProfilePage}>
<a
aria-label="go to profile"
@ -300,7 +424,7 @@ const Header = () => {
<span className="align-middle">Settings</span>
</a>
</li>
<li onClick={openChangePassword}>
<li onClick={changePass}>
{" "}
<a
aria-label="go to profile"
@ -311,6 +435,7 @@ const Header = () => {
</a>
</li>
<li>
<div className="dropdown-divider"></div>
</li>
@ -318,17 +443,10 @@ const Header = () => {
<a
aria-label="click to log out"
className="dropdown-item cusor-pointer"
onClick={() => logout()}
onClick={()=>logout()}
>
{logouting ? (
"Please Wait"
) : (
<>
{" "}
<i className="bx bx-log-out me-2"></i>
<span className="align-middle">SignOut</span>
</>
)}
{logouting ? "Please Wait":<> <i className="bx bx-log-out me-2"></i>
<span className="align-middle">SignOut</span></>}
</a>
</li>
</ul>
@ -338,4 +456,4 @@ const Header = () => {
</nav>
);
};
export default Header;
export default Header;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,6 +1,7 @@
import React from "react";
import { useProjectAssignedOrganizations } from "../../../hooks/useProjects";
import { useSelectedProject } from "../../../slices/apiDataManager";
import { formatUTCToLocalTime } from "../../../utils/dateUtils";
const ProjectAssignedOrgs = () => {
const selectedProject = useSelectedProject();
@ -47,18 +48,33 @@ const ProjectAssignedOrgs = () => {
),
align: "text-center",
},
{
key: "isActive",
label: "Status",
{
key: "organizationType",
label: "Organization Type",
getValue: (org) => (
<span
className={`text-truncate d-inline-block badge bg-label-${org.isActive ? "primary" :"secondary"}`}
style={{ maxWidth: "80px" }}
className="text-truncate d-inline-block"
style={{ maxWidth: "200px" }}
>
{org?.isActive ? "Active" : "Inactive"}
{org?.organizationType || "N/A"}
</span>
),
align: "text-start",
align: "text-center",
},
{
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],
endDate: currentDate.toISOString().split("T")[0],
projectStatusId: DEFAULT_EMPTY_STATUS_ID,
// promoterId: "",
// pmcId: "",
promoterId: "",
pmcId: "",
};
@ -39,8 +39,8 @@ export const projectSchema = z
.min(1, { message: "End Date is required" })
.default(projectDefault),
projectStatusId: z.string().min(1, { message: "Status is required" }),
// promoterId: z.string().min(1, { message: "Promoter is required" }),
// pmcId: z.string().min(1, { message: "PMC is required" }),
promoterId: z.string().min(1, { message: "Promoter is required" }),
pmcId: z.string().min(1, { message: "PMC is required" }),
})
.refine(
(data) => {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,266 +0,0 @@
import { zodResolver } from "@hookform/resolvers/zod";
import React, { useState } from "react";
import { FormProvider, useForm } from "react-hook-form";
import { defaultPayment, paymentSchema } from "./collectionSchema";
import Label from "../common/Label";
import DatePicker from "../common/DatePicker";
import { formatDate } from "date-fns";
import { useCollectionContext } from "../../pages/collections/CollectionPage";
import { useAddPayment, useCollection } from "../../hooks/useCollections";
import { formatFigure, localToUtc } from "../../utils/appUtils";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
import Avatar from "../common/Avatar";
import { PaymentHistorySkeleton } from "./CollectionSkeleton";
import { usePaymentAjustmentHead } from "../../hooks/masterHook/useMaster";
const AddPayment = ({ onClose }) => {
const { addPayment } = useCollectionContext();
const { data, isLoading, isError, error } = useCollection(
addPayment?.invoiceId
);
const {
data: paymentTypes,
isLoading: isPaymentTypeLoading,
isError: isPaymentTypeError,
error: paymentError,
} = usePaymentAjustmentHead(true);
const methods = useForm({
resolver: zodResolver(paymentSchema),
defaultValues: defaultPayment,
});
const {
control,
register,
handleSubmit,
reset,
formState: { errors },
} = methods;
const { mutate: AddPayment, isPending } = useAddPayment(() => {
handleClose();
});
const onSubmit = (formData) => {
const payload = {
...formData,
paymentReceivedDate: localToUtc(formData.paymentReceivedDate),
invoiceId: addPayment.invoiceId,
};
AddPayment(payload);
};
const handleClose = (formData) => {
reset(defaultPayment);
};
return (
<div className="container pb-3">
<div className="text-black fs-5 mb-2">Add Payment</div>
<FormProvider {...methods}>
<form onSubmit={handleSubmit(onSubmit)} className="p-0 text-start">
<div className="row px-md-1 px-0">
<div className="col-12 col-md-6 mb-2">
<Label required>TransanctionId</Label>
<input
type="text"
className="form-control form-control-sm"
{...register("transactionId")}
/>
{errors.transactionId && (
<small className="danger-text">
{errors.transactionId.message}
</small>
)}
</div>
<div className="col-12 col-md-6 mb-2">
<Label required>Transaction Date </Label>
<DatePicker
name="paymentReceivedDate"
control={control}
minDate={
data?.clientSubmitedDate
? new Date(
new Date(data?.clientSubmitedDate).setDate(
new Date(data?.clientSubmitedDate).getDate() + 1
)
)
: null
}
maxDate={new Date()}
/>
{errors.paymentReceivedDate && (
<small className="danger-text">
{errors.paymentReceivedDate.message}
</small>
)}
</div>
<div className="col-12 col-md-6 mb-2">
<Label
htmlFor="paymentAdjustmentHeadId"
className="form-label"
required
>
Payment Adjustment Head
</Label>
<select
className="form-select form-select-sm "
{...register("paymentAdjustmentHeadId")}
>
{isPaymentTypeLoading ? (
<option>Loading..</option>
) : (
<>
<option value="">Select Payment Head</option>
{paymentTypes?.data
?.sort((a, b) => a.name.localeCompare(b.name))
?.map((type) => (
<option key={type.id} value={type.id}>
{type.name}
</option>
))}
</>
)}
</select>
{errors.paymentAdjustmentHeadId && (
<small className="danger-text">
{errors.paymentAdjustmentHeadId.message}
</small>
)}
</div>
<div className="col-12 col-md-6 mb-2">
<Label htmlFor="amount" className="form-label" required>
Amount
</Label>
<input
type="number"
id="amount"
className="form-control form-control-sm"
min="1"
step="0.01"
inputMode="decimal"
{...register("amount", { valueAsNumber: true })}
/>
{errors.amount && (
<small className="danger-text">{errors.amount.message}</small>
)}
</div>
<div className="col-12 mb-2">
<Label htmlFor="comment" className="form-label" required>
Comment
</Label>
<textarea
id="comment"
className="form-control form-control-sm"
{...register("comment")}
/>
{errors.comment && (
<small className="danger-text">{errors.comment.message}</small>
)}
</div>
<div className="d-flex justify-content-end gap-3">
{" "}
<button
type="reset"
className="btn btn-label-secondary btn-sm mt-3"
onClick={() => {
handleClose();
onClose();
}}
disabled={isPending}
>
Cancel
</button>
<button
type="submit"
className="btn btn-primary btn-sm mt-3"
disabled={isPending}
>
{isPending ? "Please Wait..." : "Submit"}
</button>
</div>
</div>
</form>
</FormProvider>
{isLoading ? (
<PaymentHistorySkeleton />
) : (
data?.receivedInvoicePayments?.length > 0 && (
<div className="mt-1 text-start">
<div className="mb-2 text-secondry fs-6">
<i className="bx bx-history bx-sm me-1"></i>History
</div>
<div className="row text-start mx-2">
{data.receivedInvoicePayments
.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
.map((payment, index) => (
<div className="col-12 mb-2" key={payment.id}>
<div className=" p-2 border-start border-warning">
<div className="row">
<div className="col-12 col-md-6 d-flex justify-content-between align-items-center ">
<div>
<small className="fw-semibold me-1">
Transaction Date:
</small>{" "}
{formatUTCToLocalTime(payment.paymentReceivedDate)}
</div>
<span className="fs-semibold d-block d-md-none">
{formatFigure(payment.amount, {
type: "currency",
currency: "INR",
})}
</span>
</div>
<div className="col-12 col-md-6 mb-0 d-flex align-items-center m-0">
<small className="fw-semibold me-2">
Updated By:
</small>{" "}
<Avatar
size="xs"
firstName={payment?.createdBy?.firstName}
lastName={payment?.createdBy?.lastName}
/>{" "}
{payment?.createdBy?.firstName}{" "}
{payment.createdBy?.lastName}
</div>
</div>
<div className="row">
<div className="col-12 col-md-6">
<p className="mb-1">
<small className="fw-semibold">
Transaction ID:
</small>{" "}
{payment.transactionId}
</p>
</div>
<div className="col-12 ">
<div className="d-flex justify-content-between">
<span>{payment?.paymentAdjustmentHead?.name}</span>
<span className="fs-semibold d-none d-md-block">
{formatFigure(payment.amount, {
type: "currency",
currency: "INR",
})}
</span>
</div>
<p className="text-tiny m-0 mt-1">
{payment?.comment}
</p>
</div>
</div>
</div>
</div>
))}
</div>
</div>
)
)}
</div>
);
};
export default AddPayment;

View File

@ -1,296 +0,0 @@
import React, { useState } from "react";
import { useCollections } from "../../hooks/useCollections";
import {
ADDPAYMENT_COLLECTION,
ADMIN_COLLECTION,
CREATE_COLLECTION,
EDIT_COLLECTION,
ITEMS_PER_PAGE,
VIEW_COLLECTION,
} from "../../utils/constants";
import { formatFigure, localToUtc, useDebounce } from "../../utils/appUtils";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
import Pagination from "../common/Pagination";
import { useCollectionContext } from "../../pages/collections/CollectionPage";
import { CollectionTableSkeleton } from "./CollectionSkeleton";
import { useSelectedProject } from "../../slices/apiDataManager";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
const CollectionList = ({ fromDate, toDate, isPending, searchString }) => {
const [currentPage, setCurrentPage] = useState(1);
const isAdmin = useHasUserPermission(ADMIN_COLLECTION);
const canAddPayment = useHasUserPermission(ADDPAYMENT_COLLECTION);
const canViewCollection = useHasUserPermission(VIEW_COLLECTION);
const canEditCollection = useHasUserPermission(EDIT_COLLECTION);
const canCreate = useHasUserPermission(CREATE_COLLECTION);
const selectedProject = useSelectedProject();
const searchDebounce = useDebounce(searchString, 500);
const { data, isLoading, isError, error } = useCollections(
ITEMS_PER_PAGE,
currentPage,
localToUtc(fromDate),
localToUtc(toDate),
isPending,
true,
selectedProject,
searchDebounce
);
const { setProcessedPayment, setAddPayment, setViewCollection } =
useCollectionContext();
const paginate = (page) => {
if (page >= 1 && page <= (data?.totalPages ?? 1)) {
setCurrentPage(page);
}
};
const collectionColumns = [
{
key: "invoiceDate",
label: "Invoice Date",
getValue: (col) => (
<span
className="text-truncate d-inline-block"
style={{ maxWidth: "200px" }}
>
{formatUTCToLocalTime(col.invoiceDate)}
</span>
),
align: "text-start",
},
{
key: "invoiceId",
label: "Invoice No",
getValue: (col) => (
<span
className="text-truncate d-inline-block"
style={{ maxWidth: "200px" }}
>
{col?.invoiceNumber ?? "-"}
</span>
),
align: "text-start",
},
{
key: "project",
label: "Project",
getValue: (col) => (
<span
className="text-truncate d-inline-block"
style={{ maxWidth: "200px" }}
>
{col?.project?.name ?? "-"}
</span>
),
align: "text-start",
},
{
key: "submittedDate",
label: "Submission Date",
getValue: (col) => (
<span
className="text-truncate d-inline-block"
style={{ maxWidth: "200px" }}
>
{formatUTCToLocalTime(col.createdAt)}
</span>
),
align: "text-center",
},
{
key: "expectedSubmittedDate",
label: "Expected Payment Date",
getValue: (col) => (
<span
className="text-truncate d-inline-block"
style={{ maxWidth: "200px" }}
>
{formatUTCToLocalTime(col.exceptedPaymentDate) ?? "-"}
</span>
),
align: "text-center",
},
{
key: "amount",
label: "Total Amount",
getValue: (col) => (
<span
className="text-truncate d-inline-block"
style={{ maxWidth: "200px" }}
>
{formatFigure(col?.basicAmount + col?.taxAmount, {
type: "currency",
currency: "INR",
}) ?? 0}
</span>
),
align: "text-end",
},
{
key: "balance",
label: "Balance",
getValue: (col) => (
<span
className="text-truncate d-inline-block py-3"
style={{ maxWidth: "200px" }}
>
{formatFigure(col?.balanceAmount, {
type: "currency",
currency: "INR",
}) ?? 0}
</span>
),
align: "text-end",
},
];
if (isLoading) return <CollectionTableSkeleton />;
if (isError) return <p>{error.message}</p>;
return (
<div className="card ">
<div
className="card-datatable table-responsive page-min-h"
id="horizontal-example"
>
<div className="dataTables_wrapper no-footer mx-5 pb-2">
<table className="table dataTable text-nowrap">
<thead>
<tr className="table_header_border">
{collectionColumns.map((col) => (
<th key={col.key} className={col.align}>
{col.label}
</th>
))}
{(isAdmin ||
canAddPayment ||
canViewCollection ||
canEditCollection ||
canCreate) && <th>Action</th>}
</tr>
</thead>
<tbody>
{Array.isArray(data?.data) && data.data.length > 0 ? (
data.data.map((row, i) => (
<tr key={i}>
{collectionColumns.map((col) => (
<td key={col.key} className={col.align}>
{col.getValue(row)}
</td>
))}
{(isAdmin ||
canAddPayment ||
canViewCollection ||
canEditCollection ||
canCreate) && (
<td
className="sticky-action-column text-center"
style={{ padding: "12px 8px" }}
>
<div className="dropdown z-2">
<button
type="button"
className="btn btn-icon btn-text-secondary rounded-pill dropdown-toggle hide-arrow p-0"
data-bs-toggle="dropdown"
aria-expanded="false"
>
<i
className="bx bx-dots-vertical-rounded bx-sm text-muted"
data-bs-toggle="tooltip"
data-bs-offset="0,8"
data-bs-placement="top"
data-bs-custom-class="tooltip-dark"
title="More Action"
></i>
</button>
<ul className="dropdown-menu dropdown-menu-end">
{/* View */}
<li>
<a
className="dropdown-item cursor-pointer"
onClick={() => setViewCollection(row.id)}
>
<i className="bx bx-show me-2 text-primary"></i>
<span>View</span>
</a>
</li>
{/* Only if not completed */}
{!row?.markAsCompleted && (
<>
{/* Add Payment */}
{(isAdmin || canAddPayment) && (
<li>
<a
className="dropdown-item cursor-pointer"
onClick={() =>
setAddPayment({
isOpen: true,
invoiceId: row.id,
})
}
>
<i className="bx bx-wallet me-2 text-warning"></i>
<span>Add Payment</span>
</a>
</li>
)}
{/* Mark Payment */}
{isAdmin && (
<li>
<a
className="dropdown-item cursor-pointer"
onClick={() =>
setProcessedPayment({
isOpen: true,
invoiceId: row.id,
})
}
>
<i className="bx bx-check-circle me-2 text-success"></i>
<span>Mark Payment</span>
</a>
</li>
)}
</>
)}
</ul>
</div>
</td>
)}
</tr>
))
) : (
<tr style={{ height: "200px" }}>
<td
colSpan={collectionColumns.length + 1}
className="text-center border-0 align-middle"
>
No Collections Found
</td>
</tr>
)}
</tbody>
</table>
{data?.data?.length > 0 && (
<div className="d-flex justify-content-start mt-2">
<Pagination
currentPage={currentPage}
totalPages={data?.totalPages}
onPageChange={paginate}
/>
</div>
)}
</div>
</div>
</div>
);
};
export default CollectionList;

View File

@ -1,211 +0,0 @@
import React from "react";
const SkeletonLine = ({ height = 20, width = "100%", className = "" }) => (
<div
className={`skeleton mb-2 ${className}`}
style={{
height,
width,
}}
></div>
);
export const PaymentHistorySkeleton = ({ count = 2 }) => {
return (
<div className="row text-start">
{[...Array(count)].map((_, idx) => (
<div className="col-12 mb-2" key={idx}>
<div className="p-2 border-start border-warning">
{/* Top Row: Date + Amount */}
<div className="d-flex justify-content-between align-items-center">
<SkeletonLine width="150px" height={18} /> {/* Date */}
<SkeletonLine width="100px" height={18} /> {/* Amount */}
</div>
<div className="row mt-1">
{/* Transaction ID */}
<div className="col-12 col-md-6">
<SkeletonLine width="80%" height={16} />
</div>
{/* Received By (Avatar + Name) */}
<div className="col-12 col-md-6 d-flex align-items-center gap-2">
<SkeletonLine
width="30px"
height={30}
className="rounded-circle"
/>{" "}
{/* Avatar */}
<SkeletonLine width="120px" height={16} /> {/* Name */}
</div>
</div>
</div>
</div>
))}
</div>
);
};
export const CollectionDetailsSkeleton = () => {
return (
<div className="container p-3">
{/* Title */}
<SkeletonLine height={24} width="200px" className="mx-auto" />
{/* Header Row */}
<div className="row mb-3 px-1">
<div className="col-10">
<SkeletonLine height={20} />
</div>
<div className="col-2 d-flex justify-content-end">
<SkeletonLine height={20} width="60px" />
</div>
</div>
{/* Project */}
<div className="row mb-3">
<div className="col-md-6">
<SkeletonLine width="60%" />
</div>
</div>
{/* Invoice & E-Invoice */}
<div className="row mb-3">
<div className="col-md-6">
<SkeletonLine />
</div>
<div className="col-md-6">
<SkeletonLine />
</div>
</div>
{/* Invoice Date & Client Submitted */}
<div className="row mb-3">
<div className="col-md-6">
<SkeletonLine />
</div>
<div className="col-md-6">
<SkeletonLine />
</div>
</div>
{/* Expected Payment & Mark as Completed */}
<div className="row mb-3">
<div className="col-md-6">
<SkeletonLine />
</div>
<div className="col-md-6">
<SkeletonLine width="40%" />
</div>
</div>
{/* Basic & Tax Amount */}
<div className="row mb-3">
<div className="col-md-6">
<SkeletonLine />
</div>
<div className="col-md-6">
<SkeletonLine />
</div>
</div>
{/* Balance & Created At */}
<div className="row mb-3">
<div className="col-md-6">
<SkeletonLine />
</div>
<div className="col-md-6">
<SkeletonLine />
</div>
</div>
{/* Created By */}
<div className="row mb-3">
<div className="col-md-6 d-flex align-items-center">
<SkeletonLine
width="40px"
height={40}
className="me-2 rounded-circle"
/>
<SkeletonLine width="100px" />
</div>
</div>
{/* Description */}
<div className="row mb-3">
<div className="col-12">
<SkeletonLine height={50} />
</div>
</div>
{/* Attachments */}
<div className="row mb-3">
<div className="col-12 d-flex gap-2 flex-wrap">
{[...Array(3)].map((_, idx) => (
<SkeletonLine key={idx} height={60} width="80px" />
))}
</div>
</div>
{/* Tabs */}
<div className="row mb-2">
<div className="col-12 d-flex gap-2">
<SkeletonLine height={35} width="120px" />
<SkeletonLine height={35} width="150px" />
</div>
</div>
{/* Tab Content (Comments / Payments) */}
<SkeletonLine height={200} />
</div>
);
};
export const CollectionTableSkeleton = () => {
const columnCount = 8;
return (
<div className="card ">
<div
className="card-datatable table-responsive page-min-h"
id="horizontal-example"
>
<div className="dataTables_wrapper no-footer mx-5 pb-2">
<table className="table dataTable text-nowrap">
<thead>
<tr >
{[...Array(columnCount - 1)].map((_, i) => (
<th key={i}>
<SkeletonLine height={15} width="80px" />
</th>
))}
<th className="d-flex justify-content-center">
<SkeletonLine height={16} width="40px" />
</th>
</tr>
</thead>
<tbody>
{[...Array(8)].map((_, rowIdx) => (
<tr key={rowIdx}>
{[...Array(columnCount - 1)].map((_, colIdx) => (
<td key={colIdx}>
<SkeletonLine height={33} />
</td>
))}
<td className="d-flex justify-content-center">
<SkeletonLine height={16} width="20px" />
</td>
</tr>
))}
</tbody>
</table>
{/* Pagination Skeleton */}
<div className="d-flex justify-content-end mt-2">
<SkeletonLine height={30} width="200px" />
</div>
</div>
</div>
</div>
);
};

View File

@ -1,85 +0,0 @@
import { zodResolver } from "@hookform/resolvers/zod";
import React from "react";
import { useForm } from "react-hook-form";
import { CommentSchema } from "./collectionSchema";
import { useAddComment } from "../../hooks/useCollections";
import Avatar from "../common/Avatar";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
import moment from "moment";
const Comment = ({ invoice }) => {
const {
register,
reset,
handleSubmit,
formState: { errors },
} = useForm({
resolver: zodResolver(CommentSchema),
defaultValues: { comment: "" },
});
const { mutate: AddComment, isPending } = useAddComment(() => {
reset();
});
const onSubmit = (formData) => {
const payload = { ...formData, invoiceId: invoice?.id };
AddComment(payload);
};
return (
<div className="row pt-1 px-2">
<form onSubmit={handleSubmit(onSubmit)}>
<div className="col-12">
<textarea
className="form-control "
rows={3}
{...register("comment")}
/>
{errors.comment && (
<small className="danger-text">{errors.comment.message}</small>
)}
</div>
<div className="d-flex justify-content-end p-2">
<button
className="btn btn-sm btn-primary"
type="submit"
disabled={isPending}
>
{isPending ? "Please wait..." : "Submit"}
</button>
</div>
</form>
{invoice?.comments?.length > 0 ? (
invoice.comments.map((comment, index) => (
<div
className="border-start border-primary ps-1 py-2 mb-3"
key={comment.id || index}
>
<div className="d-flex justify-content-between align-items-center mb-1">
<div className="d-flex align-items-center">
<Avatar
size="xs"
firstName={comment?.createdBy?.firstName}
lastName={comment?.createdBy?.lastName}
/>
<span className="ms-1 fw-semibold">
{comment?.createdBy?.firstName} {comment?.createdBy?.lastName}
</span>
</div>
<small className="text-secondary">
{moment.utc(comment?.createdAt).local().fromNow()}
</small>
</div>
<div className="ms-9"> <p className="mb-1">{comment?.comment}</p></div>
</div>
))
) : (
<div className="text-center py-2"> <p className="text-muted">No comments yet.</p></div>
)}
</div>
);
};
export default Comment;

View File

@ -1,445 +0,0 @@
import React, { useEffect } from "react";
import { useModal } from "../../hooks/useAuth";
import Modal from "../common/Modal";
import { FormProvider, useForm } from "react-hook-form";
import Label from "../common/Label";
import { zodResolver } from "@hookform/resolvers/zod";
import { defaultCollection, newCollection } from "./collectionSchema";
import SelectMultiple from "../common/SelectMultiple";
import { useProjectName } from "../../hooks/useProjects";
import DatePicker from "../common/DatePicker";
import {
useCollection,
useCreateCollection,
useUpdateCollection,
} from "../../hooks/useCollections";
import { formatFileSize, localToUtc } from "../../utils/appUtils";
import { useCollectionContext } from "../../pages/collections/CollectionPage";
import { formatDate } from "../../utils/dateUtils";
const ManageCollection = ({ collectionId, onClose }) => {
const { data, isError, isLoading, error } = useCollection(collectionId);
const { projectNames, projectLoading } = useProjectName(true);
const methods = useForm({
resolver: zodResolver(newCollection),
defaultValues: defaultCollection,
});
const {
control,
watch,
register,
setValue,
handleSubmit,
reset,
formState: { errors },
} = methods;
const { mutate: createNewCollection, isPending } = useCreateCollection(() => {
handleClose();
});
const { mutate: UpdateCollection } = useUpdateCollection(() => {
handleClose();
});
const files = watch("attachments");
const onFileChange = async (e) => {
const newFiles = Array.from(e.target.files);
if (newFiles.length === 0) return;
const existingFiles = watch("attachments") || [];
const parsedFiles = await Promise.all(
newFiles.map(async (file) => {
const base64Data = await toBase64(file);
return {
fileName: file.name,
base64Data,
contentType: file.type,
fileSize: file.size,
description: "",
isActive: true,
};
})
);
const combinedFiles = [
...existingFiles,
...parsedFiles.filter(
(newFile) =>
!existingFiles.some(
(f) =>
f.fileName === newFile.fileName && f.fileSize === newFile.fileSize
)
),
];
setValue("attachments", combinedFiles, {
shouldDirty: true,
shouldValidate: true,
});
};
const toBase64 = (file) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result.split(",")[1]);
reader.onerror = (error) => reject(error);
});
const removeFile = (index) => {
if (collectionId) {
const newFiles = files.map((file, i) => {
if (file.documentId !== index) return file;
return {
...file,
isActive: false,
};
});
setValue("attachments", newFiles, { shouldValidate: true });
} else {
const newFiles = files.filter((_, i) => i !== index);
setValue("attachments", newFiles, { shouldValidate: true });
}
};
const onSubmit = (formData) => {
const payload = {
...formData,
clientSubmitedDate: localToUtc(formData.clientSubmitedDate),
invoiceDate: localToUtc(formData.invoiceDate),
exceptedPaymentDate: localToUtc(formData.exceptedPaymentDate),
};
if (collectionId) {
UpdateCollection({
collectionId,
payload: { ...payload, id: collectionId },
});
} else {
createNewCollection(payload);
}
};
const handleClose = () => {
reset(defaultCollection);
onClose();
};
useEffect(() => {
if (data && collectionId) {
reset({
projectId: data?.project?.id,
invoiceNumber: data?.invoiceNumber,
eInvoiceNumber: data?.eInvoiceNumber,
title: data?.title,
clientSubmitedDate: formatDate(data?.clientSubmitedDate),
invoiceDate: formatDate(data?.invoiceDate),
exceptedPaymentDate: formatDate(data?.exceptedPaymentDate),
taxAmount: data?.taxAmount,
basicAmount: data?.basicAmount,
description: data?.description,
attachments: data.attachments
? data.attachments.map((doc) => ({
fileName: doc.fileName,
base64Data: null,
contentType: doc.contentType,
documentId: doc.documentId,
fileSize: 0,
description: "",
preSignedUrl: doc.preSignedUrl,
isActive: doc.isActive ?? true,
}))
: [],
});
}
}, [data]);
if (isLoading) return <div>Loading....</div>;
if (isError) return <div>{error.message}</div>;
return (
<div className="container pb-3">
<div className="text-black fs-5 mb-2">
{collectionId ? "Update" : "New"} Collection
</div>
<FormProvider {...methods}>
<form onSubmit={handleSubmit(onSubmit)} className="p-0 text-start">
<div className="row px-md-1 px-0">
<div className="col-12 col-md-6 mb-2">
<Label className="form-label" required>
Select Project
</Label>
<select
className="form-select form-select-sm"
{...register("projectId")}
>
<option value="">Select Project</option>
{projectLoading ? (
<option>Loading...</option>
) : (
projectNames?.map((project) => (
<option key={project.id} value={project.id}>
{project.name}
</option>
))
)}
</select>
{errors.projectId && (
<small className="danger-text">
{errors.projectId.message}
</small>
)}
</div>
<div className="col-12 col-md-6 mb-2">
<Label required>Title</Label>
<input
type="text"
className="form-control form-control-sm"
{...register("title")}
/>
{errors.title && (
<small className="danger-text">{errors.title.message}</small>
)}
</div>
<div className="col-12 col-md-6 mb-2">
<Label required>Invoice Number</Label>
<input
type="text"
className="form-control form-control-sm"
{...register("invoiceNumber")}
/>
{errors.invoiceId && (
<small className="danger-text">
{errors.invoiceId.message}
</small>
)}
</div>
<div className="col-12 col-md-6 mb-2">
<Label required>E-Invoice Number</Label>
<input
type="text"
className="form-control form-control-sm"
{...register("eInvoiceNumber")}
/>
{errors.invoiceId && (
<small className="danger-text">
{errors.invoiceId.message}
</small>
)}
</div>
<div className="col-12 col-md-6 mb-2">
<Label required>Invoice Date</Label>
<DatePicker
name="invoiceDate"
control={control}
maxDate={new Date()}
/>
{errors.invoiceDate && (
<small className="danger-text">
{errors.invoiceDate.message}
</small>
)}
</div>
<div className="col-12 col-md-6 mb-2">
<Label required>Expected Payment Date</Label>
<DatePicker
name="exceptedPaymentDate"
control={control}
minDate={watch("invoiceDate")}
/>
{errors.exceptedPaymentDate && (
<small className="danger-text">
{errors.exceptedPaymentDate.message}
</small>
)}
</div>
<div className="col-12 col-md-6 mb-2">
<Label required>Submission Date (Client)</Label>
<DatePicker
name="clientSubmitedDate"
control={control}
maxDate={new Date()}
/>
{errors.exceptedPaymentDate && (
<small className="danger-text">
{errors.exceptedPaymentDate.message}
</small>
)}
</div>
<div className="col-12 col-md-6 mb-2">
<Label htmlFor="basicAmount" className="form-label" required>
Basic Amount
</Label>
<input
type="number"
id="basicAmount"
className="form-control form-control-sm"
min="1"
step="0.01"
inputMode="decimal"
{...register("basicAmount", { valueAsNumber: true })}
/>
{errors.basicAmount && (
<small className="danger-text">
{errors.basicAmount.message}
</small>
)}
</div>
<div className="col-12 col-md-6 mb-2">
<Label htmlFor="taxAmount" className="form-label" required>
Tax Amount
</Label>
<input
type="number"
id="taxAmount"
className="form-control form-control-sm"
min="1"
step="0.01"
inputMode="decimal"
{...register("taxAmount", { valueAsNumber: true })}
/>
{errors.taxAmount && (
<small className="danger-text">
{errors.taxAmount.message}
</small>
)}
</div>
<div className="col-12 my-2 text-start mb-2">
<div className="col-md-12">
<Label htmlFor="description" className="form-label" required>
Description
</Label>
<textarea
id="description"
className="form-control form-control-sm"
{...register("description")}
rows="2"
></textarea>
{errors.description && (
<small className="danger-text">
{errors.description.message}
</small>
)}
</div>
</div>
<div className="col-12">
<Label className="form-label" required>
Upload Bill{" "}
</Label>
<div
className="border border-secondary border-dashed rounded p-4 text-center bg-textMuted position-relative text-black"
style={{ cursor: "pointer" }}
onClick={() => document.getElementById("attachments").click()}
>
<i className="bx bx-cloud-upload d-block bx-lg "> </i>
<span className="text-muted d-block">
Click to select or click here to browse
</span>
<small className="text-muted">
(PDF, JPG, PNG,Doc,docx,xls,xlsx max 5MB)
</small>
<input
type="file"
id="attachments"
accept="
.pdf,
.doc,
.docx,
.xls,
.xlsx,
.jpg,
.jpeg,
.png
"
multiple
style={{ display: "none" }}
{...register("attachments")}
onChange={(e) => {
onFileChange(e);
e.target.value = "";
}}
/>
</div>
{errors.attachments && (
<small className="danger-text">
{errors.attachments.message}
</small>
)}
{files.length > 0 && (
<div className="d-block">
{files
.filter((file) => {
if (collectionId) {
return file.isActive;
}
return true;
})
.map((file, idx) => (
<a
key={idx}
className="d-flex justify-content-between text-start p-1"
href={file.preSignedUrl || "#"}
target="_blank"
rel="noopener noreferrer"
>
<div>
<span className="mb-0 text-secondary small d-block">
{file.fileName}
</span>
<span className="text-body-secondary small d-block">
{file.fileSize ? formatFileSize(file.fileSize) : ""}
</span>
</div>
<i
className="bx bx-trash bx-sm cursor-pointer text-danger"
onClick={(e) => {
e.preventDefault();
removeFile(collectionId ? file.documentId : idx);
}}
></i>
</a>
))}
</div>
)}
{Array.isArray(errors.attachments) &&
errors.attachments.map((fileError, index) => (
<div key={index} className="danger-text small mt-1">
{
(fileError?.fileSize?.message ||
fileError?.contentType?.message ||
fileError?.base64Data?.message,
fileError?.documentId?.message)
}
</div>
))}
</div>
<div className="d-flex justify-content-end gap-3">
{" "}
<button
type="reset"
className="btn btn-label-secondary btn-sm mt-3"
onClick={handleClose}
disabled={isPending}
>
Cancel
</button>
<button
type="submit"
className="btn btn-primary btn-sm mt-3"
disabled={isPending}
>
{isPending ? "Please Wait..." : "Submit"}
</button>
</div>
</div>
</form>
</FormProvider>
</div>
);
};
export default ManageCollection;

View File

@ -1,53 +0,0 @@
import React from 'react'
import { formatUTCToLocalTime } from '../../utils/dateUtils'
import { formatFigure } from '../../utils/appUtils'
import Avatar from '../common/Avatar'
const PaymentHistoryTable = ({data}) => {
return (
<div>
{data?.receivedInvoicePayments?.length > 0 ? (
<div className="pt-1 data-tabe table-responsive">
<table className="table table-bordered table-responsive mt-2">
<thead className="table-light">
<tr>
<th className="text-center">Sr.No</th>
<th className="text-center">Transaction ID</th>
<th className="text-center"> Received Date</th>
<th className="text-center"> Payment Adjustment-Head</th>
<th className="text-center">Amount</th>
<th className="text-center">Updated By</th>
</tr>
</thead>
<tbody>
{data.receivedInvoicePayments.map((payment, index) => (
<tr key={payment.id}>
<td className="text-center">{index + 1}</td>
<td ><span className="mx-2">{payment.transactionId}</span></td>
<td className="text-center">{formatUTCToLocalTime(payment.paymentReceivedDate)}</td>
<td className="text-start">{payment?.paymentAdjustmentHead?.name ?? "--"}</td>
<td className="text-end">
<span className="px-1">{formatFigure(payment.amount, {
type: "currency",
currency: "INR",
})}</span>
</td>
<td>
<div className="d-flex align-items-center mx-2 py-1">
{payment.createdBy?.firstName}{" "}
{payment.createdBy?.lastName}
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
):(<div className='text-center py-2'><p>No History</p></div>)}
</div>
)
}
export default PaymentHistoryTable

View File

@ -1,258 +0,0 @@
import React, { useState } from "react";
import { useCollectionContext } from "../../pages/collections/CollectionPage";
import { useCollection } from "../../hooks/useCollections";
import { formatUTCToLocalTime } from "../../utils/dateUtils";
import { formatFigure, getIconByFileType } from "../../utils/appUtils";
import Avatar from "../common/Avatar";
import PaymentHistoryTable from "./PaymentHistoryTable";
import Comment from "./Comment";
import { CollectionDetailsSkeleton } from "./CollectionSkeleton";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { ADMIN_COLLECTION, EDIT_COLLECTION } from "../../utils/constants";
const ViewCollection = ({ onClose }) => {
const [activeTab, setActiveTab] = useState("payments");
const isAdmin = useHasUserPermission(ADMIN_COLLECTION);
const canEditCollection = useHasUserPermission(EDIT_COLLECTION);
const { viewCollection, setCollection, setDocumentView } =
useCollectionContext();
const { data, isLoading, isError, error } = useCollection(viewCollection);
const handleEdit = () => {
setCollection({ isOpen: true, invoiceId: viewCollection });
onClose();
};
if (isLoading) return <CollectionDetailsSkeleton />;
if (isError) return <div>{error.message}</div>;
return (
<div className="container p-3">
<p className="fs-5 fw-semibold">Collection Details</p>
<div className="row text-start ">
<div className="col-12 mb-3 d-flex justify-content-between">
<div className="d-flex">
<label
className=" me-2 mb-0 fw-semibold"
style={{ minWidth: "130px" }}
>
Project :
</label>
<div className="text-muted">{data?.project?.name}</div>
</div>
<div>
{" "}
<span
className={`badge bg-label-${
data?.isActive ? "primary" : "danger"
}`}
>
{data?.isActive ? "Active" : "Inactive"}
</span>
{(isAdmin || canEditCollection) &&
!data?.receivedInvoicePayments && (
<span onClick={handleEdit} className="ms-2 cursor-pointer">
<i className="bx bx-edit text-primary bx-sm"></i>
</span>
)}
</div>
</div>
<div className="col-md-6">
<div className="row mb-2 text-wrap">
<div className="col-4 fw-semibold">Title :</div>
<div className="col-8 text-wrap">{data?.title}</div>
</div>
</div>
<div className="col-md-6">
<div className="row mb-4 align-items-end">
<div className="col-4 fw-semibold">Invoice Number:</div>
<div className="col-8">{data?.invoiceNumber}</div>
</div>
</div>
{/* Row 2: E-Invoice Number + Project */}
<div className="col-md-6">
<div className="row mb-4 align-items-end">
<div className="col-4 fw-semibold">E-Invoice Number:</div>
<div className="col-8">{data?.eInvoiceNumber}</div>
</div>
</div>
{/* Row 3: Invoice Date + Client Submitted Date */}
<div className="col-md-6">
<div className="row mb-4 align-items-end">
<div className="col-4 fw-semibold">Invoice Date:</div>
<div className="col-8">
{formatUTCToLocalTime(data?.invoiceDate)}
</div>
</div>
</div>
<div className="col-md-6">
<div className="row mb-4 align-items-end">
<div className="col-4 fw-semibold">Client Submission Date:</div>
<div className="col-8">
{formatUTCToLocalTime(data?.clientSubmitedDate)}
</div>
</div>
</div>
{/* Row 4: Expected Payment Date + Mark as Completed */}
<div className="col-md-6">
<div className="row mb-4 align-items-end">
<div className="col-4 fw-semibold">Expected Payment Date:</div>
<div className="col-8">
{formatUTCToLocalTime(data?.exceptedPaymentDate)}
</div>
</div>
</div>
{/* Row 5: Basic Amount + Tax Amount */}
<div className="col-md-6">
<div className="row mb-4 align-items-end">
<div className="col-4 fw-semibold">Basic Amount :</div>
<div className="col-8">
{formatFigure(data?.basicAmount, {
type: "currency",
currency: "INR",
})}
</div>
</div>
</div>
<div className="col-md-6">
<div className="row mb-4 align-items-end">
<div className="col-4 fw-semibold">Tax Amount :</div>
<div className="col-8">
{formatFigure(data?.taxAmount, {
type: "currency",
currency: "INR",
})}
</div>
</div>
</div>
{/* Row 6: Balance Amount + Created At */}
<div className="col-md-6">
<div className="row mb-4 align-items-end">
<div className="col-4 fw-semibold">Balance Amount :</div>
<div className="col-8">
{formatFigure(data?.balanceAmount, {
type: "currency",
currency: "INR",
})}
</div>
</div>
</div>
<div className="col-md-6">
<div className="row mb-4 align-items-end">
<div className="col-4 fw-semibold">Created At :</div>
<div className="col-8">{formatUTCToLocalTime(data?.createdAt)}</div>
</div>
</div>
{/* Row 7: Created By */}
<div className="col-md-6">
<div className="row mb-4 align-items-center">
<div className="col-4 fw-semibold">Created By :</div>
<div className="col-8 d-flex align-items-center">
<Avatar
size="xs"
firstName={data.createdBy?.firstName}
lastName={data.createdBy?.lastName}
/>
<span className="ms-1 text-muted">
{data?.createdBy?.firstName} {data?.createdBy?.lastName}
</span>
</div>
</div>
</div>
{/* Description */}
<div className="col-12 my-1 mb-2">
<div className=" me-2 mb-0 fw-semibold">Description :</div>
<div className="text-muted">{data?.description}</div>
</div>
<div className="col-12 text-start">
<label className=" me-2 mb-2 fw-semibold">Attachment :</label>
<div className="d-flex flex-wrap gap-2">
{data?.attachments?.map((doc) => {
const isImage = doc.contentType?.includes("image");
return (
<div
key={doc.documentId}
className="border rounded hover-scale p-2 d-flex flex-column align-items-center"
style={{
width: "80px",
cursor: isImage ? "pointer" : "default",
}}
onClick={() => {
if (isImage) {
setDocumentView({
IsOpen: true,
Image: doc.preSignedUrl,
});
}
}}
>
<i
className={`bx ${getIconByFileType(doc.contentType)}`}
style={{ fontSize: "30px" }}
></i>
<small
className="text-center text-tiny text-truncate w-100"
title={doc.fileName}
>
{doc.fileName}
</small>
</div>
);
}) ?? "No Attachment"}
</div>
</div>
<div className="container px-1">
{/* Tabs Navigation */}
<ul className="nav nav-tabs" role="tablist">
<li className="nav-item">
<button
className={`nav-link ${
activeTab === "payments" ? "active" : ""
}`}
onClick={() => setActiveTab("payments")}
type="button"
>
<i className="bx bx-history bx-sm me-1"></i> Payments History
</button>
</li>
<li className="nav-item">
<button
className={`nav-link ${
activeTab === "details" ? "active" : ""
}`}
onClick={() => setActiveTab("details")}
type="button"
>
<i className="bx bx-message-dots bx-sm me-2"></i> Comments (
{data?.comments?.length ?? "0"})
</button>
</li>
</ul>
{/* Tab Content */}
<div className="tab-content px-1 py-0 border-top-0">
{activeTab === "payments" && (
<div className="tab-pane fade show active">
<PaymentHistoryTable data={data} />
</div>
)}
{activeTab === "details" && (
<div className="tab-pane fade show active">
<Comment invoice={data} />
</div>
)}
</div>
</div>
</div>
</div>
);
};
export default ViewCollection;

View File

@ -1,101 +0,0 @@
import { z } from "zod";
const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB
const ALLOWED_TYPES = [
"application/pdf",
"application/doc",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"image/png",
"image/jpg",
"image/jpeg",
"application/vnd.ms-excel",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
];
export const newCollection = z.object({
title: z.string().trim().min(1, { message: "Title is required" }),
projectId: z.string().trim().min(1, { message: "Project is required" }),
invoiceDate: z.string().min(1, { message: "Date is required" }),
description: z.string().trim().optional(),
clientSubmitedDate: z.string().min(1, { message: "Date is required" }),
exceptedPaymentDate: z.string().min(1, { message: "Date is required" }),
invoiceNumber: z
.string()
.trim()
.min(1, { message: "Invoice is required" })
.max(17, { message: "Invalid Number" }),
eInvoiceNumber: z
.string()
.trim()
.min(1, { message: "E-Invoice No is required" }),
taxAmount: z.coerce
.number({
invalid_type_error: "Amount is required and must be a number",
})
.min(1, "Amount must be Enter")
.refine((val) => /^\d+(\.\d{1,2})?$/.test(val.toString()), {
message: "Amount must have at most 2 decimal places",
}),
basicAmount: z.coerce
.number({
invalid_type_error: "Amount is required and must be a number",
})
.min(1, "Amount must be Enter")
.refine((val) => /^\d+(\.\d{1,2})?$/.test(val.toString()), {
message: "Amount must have at most 2 decimal places",
}),
attachments: z
.array(
z.object({
fileName: z.string().min(1, { message: "Filename is required" }),
base64Data: z.string().nullable(),
contentType: z.string().refine((val) => ALLOWED_TYPES.includes(val), {
message: "Only PDF, PNG, JPG, or JPEG files are allowed",
}),
documentId: z.string().optional(),
fileSize: z.number().max(MAX_FILE_SIZE, {
message: "File size must be less than or equal to 5MB",
}),
description: z.string().optional(),
isActive: z.boolean().default(true),
})
)
.nonempty({ message: "At least one file attachment is required" }),
});
export const defaultCollection = {
projectId: "",
invoiceNumber: " ",
eInvoiceNumber: "",
title: "",
clientSubmitedDate: null,
invoiceDate: null,
exceptedPaymentDate: null,
taxAmount: "",
basicAmount: "",
description: "",
attachments: [],
};
export const paymentSchema = z.object({
paymentReceivedDate: z.string().min(1, { message: "Date is required" }),
transactionId: z.string().min(1, "Transaction ID is required"),
amount: z.number().min(1, "Amount must be greater than zero"),
comment:z.string().min(1,{message:"Comment required"}),
paymentAdjustmentHeadId:z.string().min(1,{message:"Payment Type required"})
});
// Default Value
export const defaultPayment = {
paymentReceivedDate: null,
transactionId: "",
amount: 0,
comment:"",
paymentAdjustmentHeadId:""
};
export const CommentSchema = z.object({
comment:z.string().min(1,{message:"Comment required"})
})

View File

@ -1,22 +0,0 @@
import React from "react";
import Breadcrumb from "./Breadcrumb";
const AccessDenied = ({data}) => {
return (
<div className="container-fluid">
<Breadcrumb
data={data}
/>
<div className="card text-center py-1">
<i className="fa-solid fa-triangle-exclamation fs-5" />
<p>
Access Denied: You don't have permission to perform this action !
</p>
</div>
</div>
);
};
export default AccessDenied;

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