Compare commits

..

84 Commits

Author SHA1 Message Date
a2f105dd41 Merge pull request 'Expense_Weidget_main' (#489) from Expense_Weidget_main into main
Reviewed-on: #489
merged
2025-10-25 10:18:16 +00:00
247bda1be4 format figure in at dashboard 2025-10-25 12:16:22 +05:30
fc2d115f40 fixed move figure out f card - using type= compact 2025-10-25 12:12:36 +05:30
7f848eeb38 fixed figure moved out of card 2025-10-25 11:40:34 +05:30
b38eb1bc4b handle view documents inside expense 2025-10-25 11:37:23 +05:30
9cd9e0fbbe added document files properly handling inside 2025-10-25 11:20:57 +05:30
4238157fd4 prevent error occurering due to zoom in -out 2025-10-25 11:02:57 +05:30
d7caf47498 added zoom functionality inside prevw documents 2025-10-25 10:45:52 +05:30
b4f1c48293 removed debugger 2025-10-25 10:27:21 +05:30
a070d23304 added skeleton for dashboard card figures cards 2025-10-25 10:26:41 +05:30
32f16092db changed ui for org 2025-10-24 17:29:38 +05:30
1372f9870a updated - add org. ui 2025-10-24 16:01:35 +05:30
d130ede851 changed button size of resetbutton inside preview-document component 2025-10-24 13:19:09 +05:30
9355efa4af fixed search position of master search bar 2025-10-24 13:12:41 +05:30
c438b51ef1 Merge branch 'main' of https://git.marcoaiot.com/admin/marco.pms.web into Expense_Weidget_main 2025-10-24 13:04:39 +05:30
5b3f002772 Merge branch 'Collection_Management' 2025-10-24 12:33:58 +05:30
0d9037dbdc Merge branch 'main' of https://git.marcoaiot.com/admin/marco.pms.web into Collection_Management 2025-10-24 12:32:42 +05:30
55d455bb10 Merge pull request 'Collection_Management' (#487) from Collection_Management into main
Reviewed-on: #487
Merged
2025-10-24 06:41:58 +00:00
767e218987 changed useCollection file extension syntax js to jsx 2025-10-24 06:41:58 +00:00
e0eec8ff69 added ratoted image inside preview documents 2025-10-24 06:41:58 +00:00
c38efe9934 added mismatch permission 2025-10-24 06:41:58 +00:00
9e5555ff9d added properly permissions 2025-10-24 06:41:58 +00:00
8a18c0860e added collection permission 2025-10-24 06:41:58 +00:00
e5b01e9e0f added xl, and doc file allow to upload and getSubscription plan api properly 2025-10-24 06:41:58 +00:00
b7268f9294 removed console 2025-10-24 06:41:58 +00:00
43ecdadfa9 added paymentadjustment head crud operation 2025-10-24 06:41:58 +00:00
005261abab adjust history table whenever select comment tab 2025-10-24 06:41:58 +00:00
9527427f47 added provideAll is flag inside basic projctname api 2025-10-24 06:41:58 +00:00
10fc88c022 added mark as completd api operation 2025-10-24 06:41:58 +00:00
3b0097f46b integrated editcollection and vew douments 2025-10-24 06:41:58 +00:00
ecd726bbb1 integrated comment api added comment and payments history inside view collection 2025-10-24 06:41:58 +00:00
d14fb130c6 updated payhistory after add payment 2025-10-24 06:41:58 +00:00
b6ef3e0d22 added skeleton for payment history at add payment form 2025-10-24 06:41:58 +00:00
b3f489fe9f rmoved console 2025-10-24 06:41:58 +00:00
edae70f8af integrated collection details api 2025-10-24 06:41:58 +00:00
4563e328a5 changed useCollection file extension syntax js to jsx 2025-10-24 12:01:24 +05:30
8f0ca4a9ca added ratoted image inside preview documents 2025-10-17 12:26:57 +05:30
dec959c495 added mismatch permission 2025-10-17 11:55:55 +05:30
cb7e044b27 added properly permissions 2025-10-17 11:19:44 +05:30
4c059afb72 added collection permission 2025-10-17 10:18:11 +05:30
97525e3cb2 Correction in Expense compoent at name column. 2025-10-16 12:51:03 +05:30
2a0f7794b5 Changes in filter panel. 2025-10-16 10:17:12 +05:30
798ea24088 Merge branch 'Issues_Oct_main_2W' of https://git.marcoaiot.com/admin/marco.pms.web into Expense_Weidget_main 2025-10-16 10:03:02 +05:30
8460460caf Merge pull request 'Excessive space between Organization dropdown and Search bar in Attendance menu.' (#484) from Kartik_Bug#1499 into Issues_Oct_main_2W
Reviewed-on: #484
Merged
2025-10-15 12:37:16 +00:00
c8273070ac Changes in Attendance and Expenselist. 2025-10-15 12:37:16 +00:00
dc4e48ad3b Changes in Employee list at pagination and at mobile view then scrollbar is shown. 2025-10-15 12:37:16 +00:00
20b508bebc Changes in Regularization tab. 2025-10-15 12:37:16 +00:00
05c01d1d34 Changes in Attendance page. 2025-10-15 12:37:16 +00:00
073897156e Excessive space between Organization dropdown and Search bar in Attendance menu. 2025-10-15 12:37:16 +00:00
3a2fcf71ee Merge pull request 'Export to PDF button not functioning' (#479) from Kartik_Bug#1434 into Issues_Oct_main_2W
Reviewed-on: #479
Merged
2025-10-15 12:33:55 +00:00
f0c6aea55d Create a seprate file for export functionality in employee. 2025-10-15 12:33:55 +00:00
278a5651fe Changes in excel import. 2025-10-15 12:33:55 +00:00
6fc3e674e5 Export to PDF button not functioning 2025-10-15 12:33:55 +00:00
9f4d82eb06 Merge pull request '“No images match the selected filters.” message should be displayed at the center of the page.' (#481) from Kartik_Bug#1497 into Issues_Oct_main_2W
Reviewed-on: #481
Merged
2025-10-15 12:26:25 +00:00
4ba0c823c0 “No images match the selected filters.” message should be displayed at the center of the page. 2025-10-15 12:26:25 +00:00
acf6a28191 Merge pull request 'Attendance "No record" message improvement' (#480) from Kartik_Bug#1437 into Issues_Oct_main_2W
Reviewed-on: #480
merged
2025-10-15 12:24:37 +00:00
98c90f2a9b Attendance "No record" message improvement 2025-10-15 12:24:37 +00:00
6e89fbd680 added xl, and doc file allow to upload and getSubscription plan api properly 2025-10-15 17:31:58 +05:30
cc2a82e3f0 Removing error in Contact Filter panel. 2025-10-15 16:56:18 +05:30
b23518f796 Changes in expense filter panel. 2025-10-15 15:58:59 +05:30
9648d1a98b removed console 2025-10-15 15:55:46 +05:30
aa947b791b added paymentadjustment head crud operation 2025-10-15 15:42:30 +05:30
bd6332fa61 Changes in Filter panel. 2025-10-15 14:10:03 +05:30
51cca64dd5 adjust history table whenever select comment tab 2025-10-15 12:55:07 +05:30
57d65a5fe7 Adding Chips in Document, Directory and Expense Page. 2025-10-15 12:46:47 +05:30
ca88928850 added provideAll is flag inside basic projctname api 2025-10-15 12:45:11 +05:30
962286a4da added mark as completd api operation 2025-10-15 12:35:07 +05:30
0b02531909 Adding Table-respnsive in projectNav. 2025-10-15 11:33:09 +05:30
dec15278fa Changes in Emp Attendance and DateRange picker. 2025-10-15 11:00:18 +05:30
76df08e921 integrated editcollection and vew douments 2025-10-14 20:17:48 +05:30
0052fed1e6 integrated comment api added comment and payments history inside view collection 2025-10-14 18:20:36 +05:30
da56c59ac9 Merge branch 'Issues_Oct_main_2W' of https://git.marcoaiot.com/admin/marco.pms.web into Expense_Weidget_main 2025-10-14 17:40:42 +05:30
d9392c244e Changes in UI of Weigets and show selected project on 2 heading. 2025-10-14 17:29:20 +05:30
a7f1ba97c3 Creating new weidgets in Dashboard in main. 2025-10-14 17:14:06 +05:30
b80af5467c Changes in Infrastructure. 2025-10-14 15:07:07 +05:30
e2035e1fd8 updated payhistory after add payment 2025-10-14 14:28:49 +05:30
7176a86913 Merge pull request 'integrated collection details api' (#485) from collection_dev into Collection_Management
Reviewed-on: #485
Merged
2025-10-14 08:54:29 +00:00
a26e4d1dc2 added skeleton for payment history at add payment form 2025-10-14 08:54:29 +00:00
f91c7d6da1 rmoved console 2025-10-14 08:54:29 +00:00
272645f0b4 integrated collection details api 2025-10-14 08:54:29 +00:00
301684a12b Merge pull request 'collection_dev' (#482) from collection_dev into Collection_Management
Reviewed-on: #482
merged
2025-10-14 04:55:41 +00:00
9288ac1fbc successfuuly fetch data and create collection 2025-10-14 10:24:45 +05:30
376a2a397f intergrated get list and create collection 2025-10-14 00:21:19 +05:30
58c2fbdf1b initiallly setup 2025-10-13 17:15:59 +05:30
87 changed files with 5416 additions and 1333 deletions

View File

@ -10,7 +10,27 @@
.table_header_border { .table_header_border {
border-bottom:2px solid var(--bs-table-border-color) ; border-bottom:2px solid var(--bs-table-border-color) ;
} }
.text-gary-80 {
color:var(--bs-gray-500)
}
.text-royalblue{
color: #1796e3;
}
.text-md {
font-size: 2rem;
}
.text-md-b {
font-weight: normal;
}
.cursor-wait{
cursor:wait;
}
.cursor-notallowed {
cursor: not-allowed;
}
.text-xxs { font-size: 0.55rem; } /* 8px */ .text-xxs { font-size: 0.55rem; } /* 8px */
.text-xs { font-size: 0.75rem; } /* 12px */ .text-xs { font-size: 0.75rem; } /* 12px */

View File

@ -4,17 +4,20 @@ import OrganizationModal from "./components/Organization/OrganizationModal";
import { useAuthModal, useModal } from "./hooks/useAuth"; import { useAuthModal, useModal } from "./hooks/useAuth";
import SwitchTenant from "./pages/authentication/SwitchTenant"; import SwitchTenant from "./pages/authentication/SwitchTenant";
import ChangePasswordPage from "./pages/authentication/ChangePassword"; import ChangePasswordPage from "./pages/authentication/ChangePassword";
import NewCollection from "./components/collections/ManageCollection";
const ModalProvider = () => { const ModalProvider = () => {
const { isOpen, onClose } = useOrganizationModal(); const { isOpen, onClose } = useOrganizationModal();
const { isOpen: isAuthOpen } = useAuthModal(); const { isOpen: isAuthOpen } = useAuthModal();
const {isOpen:isChangePass} = useModal("ChangePassword") const {isOpen:isChangePass} = useModal("ChangePassword")
const {isOpen:isCollectionNew} = useModal("newCollection");
return ( return (
<> <>
{isOpen && <OrganizationModal />} {isOpen && <OrganizationModal />}
{isAuthOpen && <SwitchTenant />} {isAuthOpen && <SwitchTenant />}
{isChangePass && <ChangePasswordPage /> } {isChangePass && <ChangePasswordPage /> }
{isCollectionNew && <NewCollection/>}
</> </>
); );
}; };

View File

@ -223,50 +223,6 @@ const Attendance = ({ getRole, handleModalData, searchTerm, projectId, organizat
)} )}
</tbody> </tbody>
</table> </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 <div
@ -281,6 +237,48 @@ const Attendance = ({ getRole, handleModalData, searchTerm, projectId, organizat
</div> </div>
)} )}
</div> </div>
{!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>
)}
</> </>
); );
}; };

View File

@ -15,6 +15,7 @@ import AttendanceRepository from "../../repositories/AttendanceRepository";
import { useAttendancesLogs } from "../../hooks/useAttendance"; import { useAttendancesLogs } from "../../hooks/useAttendance";
import { queryClient } from "../../layouts/AuthLayout"; import { queryClient } from "../../layouts/AuthLayout";
import { ITEMS_PER_PAGE } from "../../utils/constants"; import { ITEMS_PER_PAGE } from "../../utils/constants";
import { useNavigate } from "react-router-dom";
const usePagination = (data, itemsPerPage) => { const usePagination = (data, itemsPerPage) => {
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
@ -38,162 +39,172 @@ const usePagination = (data, itemsPerPage) => {
}; };
const AttendanceLog = ({ handleModalData, searchTerm, organizationId }) => { const AttendanceLog = ({ handleModalData, searchTerm, organizationId }) => {
const selectedProject = useSelectedProject(); const selectedProject = useSelectedProject();
const [dateRange, setDateRange] = useState({ startDate: "", endDate: "" }); const [dateRange, setDateRange] = useState({ startDate: "", endDate: "" });
const dispatch = useDispatch(); const dispatch = useDispatch();
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [showPending, setShowPending] = useState(false); const [showPending, setShowPending] = useState(false);
const [isRefreshing, setIsRefreshing] = useState(false); const [isRefreshing, setIsRefreshing] = useState(false);
const navigate = useNavigate();
const today = new Date(); const today = new Date();
today.setHours(0, 0, 0, 0); today.setHours(0, 0, 0, 0);
const yesterday = new Date(); const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1); yesterday.setDate(yesterday.getDate() - 1);
const isSameDay = (dateStr) => { const isSameDay = (dateStr) => {
if (!dateStr) return false; if (!dateStr) return false;
const d = new Date(dateStr); const d = new Date(dateStr);
d.setHours(0, 0, 0, 0); d.setHours(0, 0, 0, 0);
return d.getTime() === today.getTime(); return d.getTime() === today.getTime();
}; };
const isBeforeToday = (dateStr) => { const isBeforeToday = (dateStr) => {
if (!dateStr) return false; if (!dateStr) return false;
const d = new Date(dateStr); const d = new Date(dateStr);
d.setHours(0, 0, 0, 0); d.setHours(0, 0, 0, 0);
return d.getTime() < today.getTime(); return d.getTime() < today.getTime();
}; };
const sortByName = (a, b) => { const sortByName = (a, b) => {
const nameA = (a.firstName + a.lastName).toLowerCase(); const nameA = (a.firstName + a.lastName).toLowerCase();
const nameB = (b.firstName + b.lastName).toLowerCase(); const nameB = (b.firstName + b.lastName).toLowerCase();
return nameA.localeCompare(nameB); return nameA.localeCompare(nameB);
}; };
const { data = [], isLoading, error, refetch, isFetching } = useAttendancesLogs( const { data = [], isLoading, error, refetch, isFetching } = useAttendancesLogs(
selectedProject, selectedProject,
dateRange.startDate, dateRange.startDate,
dateRange.endDate, dateRange.endDate,
organizationId organizationId
);
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 sortedList = [...group1, ...group2, ...group3, ...group4, ...group5, ...group6];
const groupedByDate = sortedList.reduce((acc, item) => {
const date = (item.checkInTime || item.checkOutTime)?.split("T")[0];
if (date) {
acc[date] = acc[date] || [];
acc[date].push(item);
}
return acc;
}, {});
const sortedDates = Object.keys(groupedByDate).sort((a, b) => new Date(b) - new Date(a));
return sortedDates.flatMap((date) => groupedByDate[date]);
}, [data, showPending]);
const filteredSearchData = useMemo(() => {
if (!searchTerm) return processedData;
const lowercased = searchTerm.toLowerCase();
return processedData.filter((item) =>
`${item.firstName} ${item.lastName}`.toLowerCase().includes(lowercased)
); );
}, [processedData, searchTerm]);
const { const processedData = useMemo(() => {
currentPage, const filteredData = showPending
totalPages, ? data.filter((item) => item.checkOutTime === null)
currentItems: paginatedAttendances, : data;
paginate,
resetPage,
} = usePagination(filteredSearchData, 20);
useEffect(() => { const group1 = filteredData.filter((d) => d.activity === 1 && isSameDay(d.checkInTime)).sort(sortByName);
resetPage(); const group2 = filteredData.filter((d) => d.activity === 4 && isSameDay(d.checkOutTime)).sort(sortByName);
}, [filteredSearchData]); 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 handler = useCallback( const sortedList = [...group1, ...group2, ...group3, ...group4, ...group5, ...group6];
(msg) => {
const { startDate, endDate } = dateRange;
const checkIn = msg.response.checkInTime.substring(0, 10);
if (selectedProject === msg.projectId && startDate <= checkIn && checkIn <= endDate) { const groupedByDate = sortedList.reduce((acc, item) => {
queryClient.setQueriesData(["attendanceLogs"], (oldData) => { const date = (item.checkInTime || item.checkOutTime)?.split("T")[0];
if (!oldData) { if (date) {
queryClient.invalidateQueries({ queryKey: ["attendanceLogs"] }); acc[date] = acc[date] || [];
return; acc[date].push(item);
} }
return oldData.map((record) => return acc;
record.id === msg.response.id ? { ...record, ...msg.response } : record }, {});
);
});
resetPage();
}
},
[selectedProject, dateRange, resetPage]
);
useEffect(() => { const sortedDates = Object.keys(groupedByDate).sort((a, b) => new Date(b) - new Date(a));
eventBus.on("attendance_log", handler); return sortedDates.flatMap((date) => groupedByDate[date]);
return () => eventBus.off("attendance_log", handler); }, [data, showPending]);
}, [handler]);
const employeeHandler = useCallback( const filteredSearchData = useMemo(() => {
(msg) => { if (!searchTerm) return processedData;
const { startDate, endDate } = dateRange;
if (data.some((item) => item.employeeId == msg.employeeId)) {
refetch();
}
},
[data, refetch]
);
useEffect(() => { const lowercased = searchTerm.toLowerCase();
eventBus.on("employee", employeeHandler); return processedData.filter((item) =>
return () => eventBus.off("employee", employeeHandler); `${item.firstName} ${item.lastName}`.toLowerCase().includes(lowercased)
}, [employeeHandler]); );
}, [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();
}
},
[selectedProject, dateRange, resetPage]
);
useEffect(() => {
eventBus.on("attendance_log", handler);
return () => eventBus.off("attendance_log", handler);
}, [handler]);
const employeeHandler = useCallback(
(msg) => {
const { startDate, endDate } = dateRange;
if (data.some((item) => item.employeeId == msg.employeeId)) {
refetch();
}
},
[data, refetch]
);
useEffect(() => {
eventBus.on("employee", employeeHandler);
return () => eventBus.off("employee", employeeHandler);
}, [employeeHandler]);
return ( return (
<> <>
<div <div
className="dataTables_length text-start py-2 d-flex justify-content-between " className="dataTables_length text-start py-2 d-flex flex-wrap justify-content-between"
id="DataTables_Table_0_length" id="DataTables_Table_0_length"
> >
<div className="d-flex align-items-center my-0 "> <div className="d-flex flex-wrap align-items-center gap-2 gap-md-3 my-0">
<DateRangePicker {/* Date Range Picker */}
onRangeChange={setDateRange} <div className="flex-grow-1 flex-md-grow-0">
defaultStartDate={yesterday} <DateRangePicker
/> onRangeChange={setDateRange}
<div className="form-check form-switch text-start ms-1 ms-md-2 align-items-center mb-0"> defaultStartDate={yesterday}
/>
</div>
{/* Pending Attendance Switch */}
<div className="form-check form-switch text-start mb-0">
<input <input
type="checkbox" type="checkbox"
className="form-check-input" className="form-check-input"
role="switch" role="switch"
disabled={isFetching}
id="inactiveEmployeesCheckbox" id="inactiveEmployeesCheckbox"
disabled={isFetching}
checked={showPending} checked={showPending}
onChange={(e) => setShowPending(e.target.checked)} onChange={(e) => setShowPending(e.target.checked)}
/> />
<label className="form-check-label ms-0">Pending Attendance</label> <label className="form-check-label ms-0 ms-md-0">
Pending Attendance
</label>
</div> </div>
</div> </div>
</div> </div>
<div <div
className="table-responsive text-nowrap" className="table-responsive text-nowrap"
style={{ minHeight: "200px" }} style={{ minHeight: "200px" }}
@ -232,9 +243,9 @@ useEffect(() => {
const previousAttendance = arr[index - 1]; const previousAttendance = arr[index - 1];
const previousDate = previousAttendance const previousDate = previousAttendance
? moment( ? moment(
previousAttendance.checkInTime || previousAttendance.checkInTime ||
previousAttendance.checkOutTime previousAttendance.checkOutTime
).format("YYYY-MM-DD") ).format("YYYY-MM-DD")
: null; : null;
if (!previousDate || currentDate !== previousDate) { if (!previousDate || currentDate !== previousDate) {
@ -260,7 +271,12 @@ useEffect(() => {
lastName={attendance.lastName} lastName={attendance.lastName}
/> />
<div className="d-flex flex-column"> <div className="d-flex flex-column">
<a href="#" className="text-heading text-truncate"> <a
onClick={() =>
navigate(`/employee/${attendance.employeeId}?for=attendance`)
}
className="text-heading text-truncate cursor-pointer"
>
<span className="fw-normal"> <span className="fw-normal">
{attendance.firstName} {attendance.lastName} {attendance.firstName} {attendance.lastName}
</span> </span>
@ -297,8 +313,7 @@ useEffect(() => {
) : ( ) : (
<div className="my-12"> <div className="my-12">
<span className="text-secondary"> <span className="text-secondary">
No data available for the selected date range. Please Select No attendance record found in selected date range.
another date.
</span> </span>
</div> </div>
)} )}
@ -326,9 +341,8 @@ useEffect(() => {
(pageNumber) => ( (pageNumber) => (
<li <li
key={pageNumber} key={pageNumber}
className={`page-item ${ className={`page-item ${currentPage === pageNumber ? "active" : ""
currentPage === pageNumber ? "active" : "" }`}
}`}
> >
<button <button
className="page-link" className="page-link"
@ -340,9 +354,8 @@ useEffect(() => {
) )
)} )}
<li <li
className={`page-item ${ className={`page-item ${currentPage === totalPages ? "disabled" : ""
currentPage === totalPages ? "disabled" : "" }`}
}`}
> >
<button <button
className="page-link" className="page-link"

View File

@ -33,7 +33,7 @@ const InfraPlanning = () => {
const selectedService = useCurrentService(); const selectedService = useCurrentService();
const { projectInfra, isLoading, isError, error, isFetched } = const { projectInfra, isLoading, isError, error, isFetched } =
useProjectInfra(selectedProject, selectedService || "" ); useProjectInfra(selectedProject, selectedService || "");
const canManageInfra = useHasUserPermission(MANAGE_PROJECT_INFRA); const canManageInfra = useHasUserPermission(MANAGE_PROJECT_INFRA);
const canApproveTask = useHasUserPermission(APPROVE_TASK); const canApproveTask = useHasUserPermission(APPROVE_TASK);
@ -62,9 +62,13 @@ const InfraPlanning = () => {
if (isFetched && (!projectInfra || projectInfra.length === 0)) { if (isFetched && (!projectInfra || projectInfra.length === 0)) {
return ( return (
<div className="text-center"> <div
<p className="my-3">No Result Found</p> className="text-center d-flex justify-content-center align-items-center text-muted"
style={{ minHeight: "40vh", fontSize: "0.9rem" }}
>
<p className="my-3 m-0">No Result Found</p>
</div> </div>
); );
} }

View File

@ -14,6 +14,7 @@ import {
} from "../../slices/apiDataManager"; } from "../../slices/apiDataManager";
import { useQueryClient } from "@tanstack/react-query"; import { useQueryClient } from "@tanstack/react-query";
import Pagination from "../../components/common/Pagination"; import Pagination from "../../components/common/Pagination";
import { useNavigate } from "react-router-dom";
const Regularization = ({ const Regularization = ({
handleRequest, handleRequest,
@ -26,6 +27,7 @@ const Regularization = ({
// var selectedProject = useSelector((store) => store.localVariables.projectId); // var selectedProject = useSelector((store) => store.localVariables.projectId);
const selectedProject = useSelectedProject(); const selectedProject = useSelectedProject();
const [regularizesList, setregularizedList] = useState([]); const [regularizesList, setregularizedList] = useState([]);
const navigate = useNavigate();
const { regularizes, loading, error, refetch } = useRegularizationRequests( const { regularizes, loading, error, refetch } = useRegularizationRequests(
selectedProject, selectedProject,
organizationId, organizationId,
@ -33,9 +35,9 @@ const Regularization = ({
); );
useEffect(() => { useEffect(() => {
if(!regularizes) return if (!regularizes) return
if(regularizes?.length) { if (regularizes?.length) {
setregularizedList(regularizes); setregularizedList(regularizes);
} }
}, [regularizes]); }, [regularizes]);
@ -102,141 +104,106 @@ const Regularization = ({
}, [employeeHandler]); }, [employeeHandler]);
return ( return (
<div <div>
className="table-responsive text-nowrap pb-4" <div
style={{ minHeight: "200px" }} className="table-responsive pt-3 text-nowrap pb-4"
> style={{ minHeight: "200px" }}
{loading ? ( >
<div {loading ? (
className="d-flex justify-content-center align-items-center" <div
style={{ height: "200px" }} className="d-flex justify-content-center align-items-center"
> style={{ height: "200px" }}
<p className="text-secondary">Loading...</p> >
</div> <p className="text-secondary">Loading...</p>
) : currentItems?.length > 0 ? ( </div>
<table className="table mb-0"> ) : currentItems?.length > 0 ? (
<thead> <table className="table mb-0">
<tr> <thead>
<th colSpan={2}>Name</th> <tr>
<th>Date</th> <th colSpan={2}>Name</th>
<th>Organization</th> <th>Date</th>
<th> <th>Organization</th>
<i className="bx bxs-down-arrow-alt text-success"></i>Check-In <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> <i className="bx bxs-up-arrow-alt text-danger"></i>Check-Out
<th colSpan={2}> </th>
Requested By <th colSpan={2}>
</th> Requested By
<th > </th>
Requested At <th >
</th> Requested At
<th>Action</th> </th>
</tr> <th>Action</th>
</thead> </tr>
<tbody> </thead>
{currentItems?.map((att, index) => ( <tbody>
<tr key={index}> {currentItems?.map((att, index) => (
<td colSpan={2}> <tr key={index}>
<div className="d-flex justify-content-start align-items-center"> <td colSpan={2}>
<Avatar firstName={att.firstName} lastName={att.lastName} /> <div className="d-flex justify-content-start align-items-center">
<div className="d-flex flex-column"> <Avatar firstName={att.firstName} lastName={att.lastName} />
<a href="#" className="text-heading text-truncate"> <div className="d-flex flex-column"> <a
onClick={() =>
navigate(`/employee/${att.employeeId}?for=attendance`)
}
className="text-heading text-truncate cursor-pointer" >
<span className="fw-normal"> <span className="fw-normal">
{att.firstName} {att.lastName} {att.firstName} {att.lastName}
</span> </span>
</a> </a>
</div>
</div> </div>
</div> </td>
</td> <td>{moment(att.checkOutTime).format("DD-MMM-YYYY")}</td>
<td>{moment(att.checkOutTime).format("DD-MMM-YYYY")}</td>
<td>{att.organizationName || "--"}</td> <td>{att.organizationName || "--"}</td>
<td>{convertShortTime(att.checkInTime)}</td> <td>{convertShortTime(att.checkInTime)}</td>
<td>
{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> <td>
{att?.requestedAt ? formatUTCToLocalTime(att.requestedAt,true) : "--"} {att.requestedAt ? convertShortTime(att.checkOutTime) : "--"}
</td> </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>
)} */}
<td colSpan={2}>
{att.requestedBy ? (<div className="d-flex justify-content-start align-items-center">
<Avatar firstName={att?.requestedBy?.firstName} lastName={att?.requestedBy?.lastName} />
<div className="d-flex flex-column">
<a href="#" className="text-heading text-truncate">
<span className="fw-normal">
{att?.requestedBy?.firstName} {att?.requestedBy?.lastName}
</span>
</a>
</div>
</div>) : (<small>--</small>)}
</td>
<td>
{att?.requestedAt ? formatUTCToLocalTime(att.requestedAt, true) : "--"}
</td>
<td 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>
)}
</div>
{totalPages > 0 && ( {totalPages > 0 && (
<Pagination <Pagination
currentPage={currentPage} currentPage={currentPage}
@ -244,6 +211,7 @@ const Regularization = ({
onPageChange={paginate} onPageChange={paginate}
/> />
)} )}
</div> </div>
); );
}; };

View File

@ -29,7 +29,9 @@ const TaskReportFilterPanel = ({ handleFilter }) => {
handleSubmit, handleSubmit,
formState: { errors }, formState: { errors },
} = methods; } = methods;
const closePanel = () => {
document.querySelector(".offcanvas.show .btn-close")?.click();
};
const onSubmit = (formData) => { const onSubmit = (formData) => {
const filterPayload = { const filterPayload = {
...formData, ...formData,
@ -37,12 +39,14 @@ const TaskReportFilterPanel = ({ handleFilter }) => {
dateTo: localToUtc(formData.dateTo), dateTo: localToUtc(formData.dateTo),
}; };
handleFilter(filterPayload); handleFilter(filterPayload);
closePanel();
}; };
const onClear = () => { const onClear = () => {
setResetKey((prev) => prev + 1); setResetKey((prev) => prev + 1);
handleFilter(TaskReportDefaultValue); handleFilter(TaskReportDefaultValue);
reset(TaskReportDefaultValue); reset(TaskReportDefaultValue);
closePanel();
}; };
return ( return (
<FormProvider {...methods}> <FormProvider {...methods}>

View File

@ -29,7 +29,7 @@ const TaskReportList = () => {
const ApprovedTaskRights = useHasUserPermission(APPROVE_TASK); const ApprovedTaskRights = useHasUserPermission(APPROVE_TASK);
const ReportTaskRights = useHasUserPermission(ASSIGN_REPORT_TASK); const ReportTaskRights = useHasUserPermission(ASSIGN_REPORT_TASK);
const { service, openModal, closeModal,filter } = useDailyProgrssContext(); const { service, openModal, closeModal, filter } = useDailyProgrssContext();
const selectedProject = useSelectedProject(); const selectedProject = useSelectedProject();
const { projectNames } = useProjectName(); const { projectNames } = useProjectName();
@ -37,7 +37,7 @@ const TaskReportList = () => {
selectedProject, selectedProject,
ITEMS_PER_PAGE, ITEMS_PER_PAGE,
currentPage, currentPage,
service,filter service, filter
); );
const ProgrssReportColumn = [ const ProgrssReportColumn = [
@ -192,109 +192,114 @@ const TaskReportList = () => {
if (isLoading) return <TaskReportListSkeleton />; if (isLoading) return <TaskReportListSkeleton />;
if (isError) return <div>Loading....</div>; if (isError) return <div>Loading....</div>;
return ( return (
<div className="mt-2 table-responsive text-nowrap"> <div>
<table className="table"> <div className="mt-2 table-responsive text-nowrap">
<thead> <table className="table">
<tr> <thead>
<th className="text-start">Activity</th>
<th>
<span>
Total Pending{" "}
<HoverPopup
title="Total Pending Task"
content={<p>This shows the total pending tasks for each activity on that date.</p>}
>
<i className="bx bx-xs ms-1 bx-info-circle cursor-pointer"></i>
</HoverPopup>
</span>
</th>
<th>
<span>
Reported/Planned{" "}
<HoverPopup
title="Reported and Planned Task"
content={<p>This shows the reported versus planned tasks for each activity on that date.</p>}
>
<i className="bx bx-xs ms-1 bx-info-circle cursor-pointer"></i>
</HoverPopup>
</span>
</th>
<th>Assign Date</th>
<th>Team</th>
<th className="text-center">Actions</th>
</tr>
</thead>
<tbody>
{groupedTasks.length === 0 && (
<tr> <tr>
<td colSpan={6} className="text-center align-middle" style={{ height: "200px", borderBottom: "none" }}> <th className="text-start">Activity</th>
No reports available <th>
</td> <span>
Total Pending{" "}
<HoverPopup
title="Total Pending Task"
content={<p>This shows the total pending tasks for each activity on that date.</p>}
>
<i className="bx bx-xs ms-1 bx-info-circle cursor-pointer"></i>
</HoverPopup>
</span>
</th>
<th>
<span>
Reported/Planned{" "}
<HoverPopup
title="Reported and Planned Task"
content={<p>This shows the reported versus planned tasks for each activity on that date.</p>}
>
<i className="bx bx-xs ms-1 bx-info-circle cursor-pointer"></i>
</HoverPopup>
</span>
</th>
<th>Assign Date</th>
<th>Team</th>
<th className="text-center">Actions</th>
</tr> </tr>
)} </thead>
<tbody>
{groupedTasks.map(({ date, tasks }) => ( {groupedTasks.length === 0 && (
<React.Fragment key={date}> <tr>
<tr className="table-row-header text-start"> <td colSpan={6} className="text-center align-middle" style={{ height: "200px", borderBottom: "none" }}>
<td colSpan={6}> No reports available
<strong>{formatUTCToLocalTime(date)}</strong>
</td> </td>
</tr> </tr>
{tasks.map((task, idx) => ( )}
<tr key={task.id || idx}>
<td className="flex-wrap text-start"> {groupedTasks.map(({ date, tasks }) => (
<div> <React.Fragment key={date}>
{task.workItem.activityMaster?.activityName || "No Activity Name"} <tr className="table-row-header text-start">
</div> <td colSpan={6}>
<div className="text-sm py-2"> <strong>{formatUTCToLocalTime(date)}</strong>
{task.workItem.workArea?.floor?.building?.name} {" "}
{task.workItem.workArea?.floor?.floorName} {" "}
{task.workItem.workArea?.areaName}
</div>
</td>
<td>
{formatNumber(task.workItem.plannedWork)}
</td>
<td>{`${formatNumber(task.completedTask)} / ${formatNumber(task.plannedTask)}`}</td>
<td>{formatUTCToLocalTime(task.assignmentDate)}</td>
<td className="text-center">{renderTeamMembers(task, idx)}</td>
<td className="text-center">
<div className="d-flex justify-content-end gap-2">
{ReportTaskRights && !task.reportedDate && (
<button className="btn btn-xs btn-primary" onClick={() => openModal("report", task)}>
Report
</button>
)}
{ApprovedTaskRights && task.reportedDate && !task.approvedBy && (
<button
className="btn btn-xs btn-warning"
onClick={() => openModal("comments", { task, isActionAllow: true })}
>
QC
</button>
)}
<button
className="btn btn-xs btn-primary"
onClick={() => openModal("comments", { task, isActionAllow: false })}
>
Comment
</button>
</div>
</td> </td>
</tr> </tr>
))} {tasks.map((task, idx) => (
</React.Fragment> <tr key={task.id || idx}>
))} <td className="flex-wrap text-start">
</tbody> <div>
</table> {task.workItem.activityMaster?.activityName || "No Activity Name"}
{data?.data?.length > 0 && ( </div>
<Pagination <div className="text-sm py-2">
currentPage={currentPage} {task.workItem.workArea?.floor?.building?.name} {" "}
totalPages={data.totalPages} {task.workItem.workArea?.floor?.floorName} {" "}
onPageChange={paginate} {task.workItem.workArea?.areaName}
/> </div>
)} </td>
</div> <td>
{formatNumber(task.workItem.plannedWork)}
</td>
<td>{`${formatNumber(task.completedTask)} / ${formatNumber(task.plannedTask)}`}</td>
<td>{formatUTCToLocalTime(task.assignmentDate)}</td>
<td className="text-center">{renderTeamMembers(task, idx)}</td>
<td className="text-center">
<div className="d-flex justify-content-end gap-2">
{ReportTaskRights && !task.reportedDate && (
<button className="btn btn-xs btn-primary" onClick={() => openModal("report", task)}>
Report
</button>
)}
{ApprovedTaskRights && task.reportedDate && !task.approvedBy && (
<button
className="btn btn-xs btn-warning"
onClick={() => openModal("comments", { task, isActionAllow: true })}
>
QC
</button>
)}
<button
className="btn btn-xs btn-primary"
onClick={() => openModal("comments", { task, isActionAllow: false })}
>
Comment
</button>
</div>
</td>
</tr>
))}
</React.Fragment>
))}
</tbody>
</table>
</div>
{
data?.data?.length > 0 && (
<Pagination
currentPage={currentPage}
totalPages={data.totalPages}
onPageChange={paginate}
/>
)
}
</div >
); );
}; };

View File

@ -14,11 +14,11 @@ import ProjectCompletionChart from "./ProjectCompletionChart";
import ProjectProgressChart from "./ProjectProgressChart"; import ProjectProgressChart from "./ProjectProgressChart";
import ProjectOverview from "../Project/ProjectOverview"; import ProjectOverview from "../Project/ProjectOverview";
import AttendanceOverview from "./AttendanceChart"; import AttendanceOverview from "./AttendanceChart";
import ExpenseAnalysis from "./ExpenseAnalysis";
import ExpenseStatus from "./ExpenseStatus";
import ExpenseByProject from "./ExpenseByProject";
const Dashboard = () => { const Dashboard = () => {
const { projectsCardData } = useDashboardProjectsCardData();
const { teamsCardData } = useDashboardTeamsCardData();
const { tasksCardData } = useDashboardTasksCardData();
// Get the selected project ID from Redux store // Get the selected project ID from Redux store
const projectId = useSelector((store) => store.localVariables.projectId); const projectId = useSelector((store) => store.localVariables.projectId);
@ -29,16 +29,16 @@ const Dashboard = () => {
<div className="row gy-4"> <div className="row gy-4">
{isAllProjectsSelected && ( {isAllProjectsSelected && (
<div className="col-sm-6 col-lg-4"> <div className="col-sm-6 col-lg-4">
<Projects projectsCardData={projectsCardData} /> <Projects />
</div> </div>
)} )}
<div className={`${!isAllProjectsSelected ? "col-sm-6 col-lg-6" : "col-sm-6 col-lg-4"}`}> <div className={`${!isAllProjectsSelected ? "col-sm-6 col-lg-6" : "col-sm-6 col-lg-4"}`}>
<Teams teamsCardData={teamsCardData} /> <Teams />
</div> </div>
<div className={`${!isAllProjectsSelected ? "col-sm-6 col-lg-6" : "col-sm-6 col-lg-4"}`}> <div className={`${!isAllProjectsSelected ? "col-sm-6 col-lg-6" : "col-sm-6 col-lg-4"}`}>
<TasksCard tasksCardData={tasksCardData} /> <TasksCard/>
</div> </div>
{isAllProjectsSelected && ( {isAllProjectsSelected && (
@ -56,11 +56,25 @@ const Dashboard = () => {
<div className="col-xxl-6 col-lg-6"> <div className="col-xxl-6 col-lg-6">
<ProjectProgressChart /> <ProjectProgressChart />
</div> </div>
<div className="col-12 col-xl-8">
<div className="card h-100">
<ExpenseAnalysis />
</div>
</div>
<div className="col-12 col-xl-4 col-md-6">
<div className="card ">
<ExpenseStatus />
</div>
</div>
{!isAllProjectsSelected && ( {!isAllProjectsSelected && (
<div className="col-xxl-6 col-lg-6"> <div className="col-12 col-md-6 mb-sm-0 mb-4 ">
<AttendanceOverview /> {/* ✅ Removed unnecessary projectId prop */} <AttendanceOverview />
</div> </div>
)} )}
<div className="col-12 col-md-6">
<ExpenseByProject />
</div>
</div> </div>
</div> </div>
); );

View File

@ -0,0 +1,110 @@
import React from "react";
const SkeletonLine = ({ height = 20, width = "100%", className = "" }) => (
<div
className={`skeleton ${className}`}
style={{
height,
width,
borderRadius: "4px",
background: "linear-gradient(90deg, #eee, #f5f5f5, #eee)",
backgroundSize: "200% 100%",
animation: "skeleton-loading 1.5s infinite",
}}
></div>
);
const skeletonStyle = `
@keyframes skeleton-loading {
0% { background-position: 200% 0; }
100% { background-position: -200% 0; }
}
`;
export const ProjectCardSkeleton = () => {
return (
<>
{/* Inject animation CSS once */}
<style>{skeletonStyle}</style>
<div className="card p-3 h-100 text-center d-flex justify-content-between">
{/* Header */}
<div className="d-flex justify-content-start align-items-center mb-3">
<h5 className="fw-bold mb-0 ms-2">
<i className="rounded-circle bx bx-building-house text-primary"></i>{" "}
Projects
</h5>
</div>
{/* Skeleton body */}
<div className="d-flex justify-content-around align-items-start mt-n2 w-100">
<div className="text-center">
<SkeletonLine height={28} width="60px" className="mx-auto mb-2" />
<SkeletonLine height={14} width="40px" className="mx-auto" />
</div>
<div className="text-center">
<SkeletonLine height={28} width="60px" className="mx-auto mb-2" />
<SkeletonLine height={14} width="40px" className="mx-auto" />
</div>
</div>
</div>
</>
);
};
export const TeamsSkeleton = () => {
return (
<>
<style>{skeletonStyle}</style>
<div className="card p-3 h-100 text-center d-flex justify-content-between">
{/* Header */}
<div className="d-flex justify-content-start align-items-center mb-3">
<h5 className="fw-bold mb-0 ms-2">
<i className="bx bx-group text-warning"></i> Teams
</h5>
</div>
{/* Skeleton Body */}
<div className="d-flex justify-content-around align-items-start mt-n2 w-100">
<div className="text-center">
<SkeletonLine height={28} width="60px" className="mx-auto mb-2" />
<SkeletonLine height={14} width="90px" className="mx-auto" />
</div>
<div className="text-center">
<SkeletonLine height={28} width="60px" className="mx-auto mb-2" />
<SkeletonLine height={14} width="70px" className="mx-auto" />
</div>
</div>
</div>
</>
);
};
export const TasksSkeleton = () => {
return (
<>
<style>{skeletonStyle}</style>
<div className="card p-3 h-100 text-center d-flex justify-content-between">
{/* Header */}
<div className="d-flex justify-content-start align-items-center mb-3">
<h5 className="fw-bold mb-0 ms-2">
<i className="bx bx-task text-success"></i> Tasks
</h5>
</div>
{/* Skeleton Body */}
<div className="d-flex justify-content-around align-items-start mt-n2 w-100">
<div className="text-center">
<SkeletonLine height={28} width="60px" className="mx-auto mb-2" />
<SkeletonLine height={14} width="70px" className="mx-auto" />
</div>
<div className="text-center">
<SkeletonLine height={28} width="60px" className="mx-auto mb-2" />
<SkeletonLine height={14} width="90px" className="mx-auto" />
</div>
</div>
</div>
</>
);
};

View File

@ -0,0 +1,167 @@
import React, { useEffect, useMemo, useState } 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";
import { useProjectName } from "../../hooks/useProjects";
const ExpenseAnalysis = () => {
const projectId = useSelectedProject();
const [projectName, setProjectName] = useState("All Project");
const { projectNames, loading } = useProjectName();
const methods = useForm({
defaultValues: { startDate: "", endDate: "" },
});
useEffect(() => {
if (projectId && projectNames?.length) {
const project = projectNames.find((p) => p.id === projectId);
setProjectName(project?.name || "All Project");
} else {
setProjectName("All Project");
}
}, [projectNames, projectId]);
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 (
<>
<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> */}
<p className="card-subtitle m-0">{projectName}</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>
{/* Header */}
</>
);
};
export default ExpenseAnalysis;

View File

@ -0,0 +1,178 @@
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";
import { useProjectName } from "../../hooks/useProjects";
import { useSelectedProject } from "../../slices/apiDataManager";
const ExpenseByProject = () => {
const projectId = useSelector((store) => store.localVariables.projectId);
const [projectName, setProjectName] = useState("All Project");
const [range, setRange] = useState("12M");
const { projectNames, loading } = useProjectName();
const [selectedType, setSelectedType] = useState("");
const [viewMode, setViewMode] = useState("Category");
const [chartData, setChartData] = useState({ categories: [], data: [] });
const selectedProject = useSelectedProject();
const { ExpenseTypes, loading: typeLoading } = useExpenseType();
const { data: expenseApiData, isLoading } = useExpenseDataByProject(
projectId,
selectedType,
range === "All" ? null : parseInt(range)
);
useEffect(() => {
if (selectedProject && projectNames?.length) {
const project = projectNames.find((p) => p.id === selectedProject);
setProjectName(project?.name || "All Project");
} else {
setProjectName("All Project");
}
}, [projectNames, selectedProject]);
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 className="text-start">
<h5 className="mb-1 me-6 card-title">Monthly Expense -</h5>
<p className="card-subtitle m-0">{projectName}</p>
</div>
<div className="btn-group mb-4 ms-n8">
<button
className="btn btn-sm dropdown-toggle fs-5"
type="button"
data-bs-toggle="dropdown"
aria-expanded="false"
>
{viewMode}
</button>
<ul className="dropdown-menu dropdown-menu-end ">
<li>
<button
className="dropdown-item"
onClick={() => {
setViewMode("Category");
setSelectedType("");
}}
>
Category
</button>
</li>
<li>
<button
className="dropdown-item"
onClick={() => {
setViewMode("Project");
setSelectedType("");
}}
>
Project
</button>
</li>
</ul>
</div>
</div>
{/* Range Buttons + Expense Dropdown */}
<div className="d-flex align-items-center flex-wrap ">
{["1M", "3M", "6M", "12M", "All"].map((item) => (
<button
key={item}
className={`border-0 px-2 py-1 text-sm rounded ${range === item
? "text-white bg-primary"
: "text-body bg-transparent"
}`}
style={{ cursor: "pointer", transition: "all 0.2s ease" }}
onClick={() => setRange(item)}
>
{item}
</button>
))}
{viewMode === "Category" && (
<select
className="form-select form-select-sm ms-auto mb-3 mt-1 mt-sm-0"
value={selectedType}
onChange={(e) => setSelectedType(e.target.value)}
disabled={typeLoading}
style={{ maxWidth: "200px" }}
>
<option value="">All Types</option>
{ExpenseTypes.map((type) => (
<option key={type.id} value={type.id}>
{type.name}
</option>
))}
</select>
)}
</div>
</div>
{/* Chart */}
<div className="card-body bg-white text-dark p-3 rounded" style={{ minHeight: "210px" }}>
{isLoading ? (
<p>Loading chart...</p>
) : !expenseApiData || expenseApiData.length === 0 ? (
<div className="text-center text-muted py-5">No data found</div>
) : (
<Chart options={options} series={series} type="bar" height={235} />
)}
</div>
</div>
);
};
export default ExpenseByProject;

View File

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

@ -1,6 +1,9 @@
import React, { useEffect } from "react"; import React, { useEffect } from "react";
import { useDashboardProjectsCardData } from "../../hooks/useDashboard_Data"; import { useDashboardProjectsCardData } from "../../hooks/useDashboard_Data";
import eventBus from "../../services/eventBus"; import eventBus from "../../services/eventBus";
import ProjectInfra from "../Project/ProjectInfra";
import { ProjectCardSkeleton } from "./DashboardSkeleton";
import { formatFigure } from "../../utils/appUtils";
const Projects = () => { const Projects = () => {
const { const {
@ -8,6 +11,7 @@ const Projects = () => {
isLoading, isLoading,
isError, isError,
error, error,
isFetching,
refetch, refetch,
} = useDashboardProjectsCardData(); } = useDashboardProjectsCardData();
@ -23,7 +27,7 @@ const Projects = () => {
const totalProjects = projectsCardData?.totalProjects ?? 0; const totalProjects = projectsCardData?.totalProjects ?? 0;
const ongoingProjects = projectsCardData?.ongoingProjects ?? 0; const ongoingProjects = projectsCardData?.ongoingProjects ?? 0;
if (isLoading) return <ProjectCardSkeleton />;
return ( return (
<div className="card p-3 h-100 text-center d-flex justify-content-between"> <div className="card p-3 h-100 text-center d-flex justify-content-between">
<div className="d-flex justify-content-start align-items-center mb-3"> <div className="d-flex justify-content-start align-items-center mb-3">
@ -33,24 +37,41 @@ const Projects = () => {
</h5> </h5>
</div> </div>
{isLoading ? ( {isError ? (
<div className="d-flex justify-content-center align-items-center flex-grow-1"> <div className="d-flex flex-column justify-content-center align-items-center p-1">
<div className="spinner-border text-primary" role="status"> <i className="bx bx-error-circle bx-sm fs-2 "></i>
<span className="visually-hidden">Loading...</span> <small className="text-muted mb-2">
</div> {error?.message || "Unable to load data at the moment."}
</div> </small>
) : isError ? ( <span
<div className="text-danger flex-grow-1 d-flex justify-content-center align-items-center"> className={`text-muted ${
{error?.message || "Error loading data"} isFetching ? "cursor-wait" : "cursor-pointer"
}`}
onClick={refetch}
>
<i
className={`bx bx-refresh me-1 ${isFetching ? "bx-spin" : ""}`}
></i>{" "}
Retry
</span>
</div> </div>
) : ( ) : (
<div className="d-flex justify-content-around align-items-start mt-n2"> <div className="d-flex justify-content-around align-items-start mt-n2">
<div> <div>
<h4 className="mb-0 fw-bold">{totalProjects.toLocaleString()}</h4> <h4 className="mb-0 fw-bold">
{formatFigure(totalProjects ?? 0, {
notation: "compact",
})}
</h4>
<small className="text-muted">Total</small> <small className="text-muted">Total</small>
</div> </div>
<div> <div>
<h4 className="mb-0 fw-bold">{ongoingProjects.toLocaleString()}</h4> <h4 className="mb-0 fw-bold">
{formatFigure(ongoingProjects ?? 0, {
notation: "compact",
})}
</h4>
<small className="text-muted">Ongoing</small> <small className="text-muted">Ongoing</small>
</div> </div>
</div> </div>

View File

@ -1,6 +1,8 @@
import React from "react"; import React from "react";
import { useSelectedProject } from "../../slices/apiDataManager"; import { useSelectedProject } from "../../slices/apiDataManager";
import { useDashboardTasksCardData } from "../../hooks/useDashboard_Data"; import { useDashboardTasksCardData } from "../../hooks/useDashboard_Data";
import { TasksSkeleton } from "./DashboardSkeleton";
import { formatCurrency, formatFigure } from "../../utils/appUtils";
const TasksCard = () => { const TasksCard = () => {
const projectId = useSelectedProject(); const projectId = useSelectedProject();
@ -10,42 +12,57 @@ const TasksCard = () => {
isLoading, isLoading,
isError, isError,
error, error,
isFetching,
refetch,
} = useDashboardTasksCardData(projectId); } = useDashboardTasksCardData(projectId);
if (isLoading) return <TasksSkeleton />;
return ( return (
<div className="card p-3 h-100 text-center d-flex justify-content-between"> <div className="card p-3 h-100 text-center d-flex flex-column justify-content-between">
{/* Header */}
<div className="d-flex justify-content-start align-items-center mb-3"> <div className="d-flex justify-content-start align-items-center mb-3">
<h5 className="fw-bold mb-0 ms-2"> <h5 className="fw-bold mb-0 ms-2">
<i className="bx bx-task text-success"></i> Tasks <i className="bx bx-task text-success"></i> Tasks
</h5> </h5>
</div> </div>
{isLoading ? ( {isError ? (
// Loader while fetching <div className="d-flex flex-column justify-content-center align-items-center p-3">
<div className="d-flex justify-content-center align-items-center flex-grow-1"> <i className="bx bx-error-circle bx-sm fs-2 mb-2"></i>
<div className="spinner-border text-primary" role="status"> <small className="text-muted mb-2">
<span className="visually-hidden">Loading...</span> {error?.message || "Unable to load data at the moment."}
</div> </small>
</div> <span
) : isError ? ( className={`text-muted ${
// Show error isFetching ? "cursor-wait" : "cursor-pointer"
<div className="text-danger flex-grow-1 d-flex justify-content-center align-items-center"> }`}
{error?.message || "Error loading data"} onClick={refetch}
>
<i
className={`bx bx-refresh me-1 ${isFetching ? "bx-spin" : ""}`}
></i>
Retry
</span>
</div> </div>
) : ( ) : (
// Show data <div className="d-flex justify-content-around align-items-start flex-wrap mt-n2">
<div className="d-flex justify-content-around align-items-start mt-n2"> {/* Total Tasks */}
<div> <div className="text-center flex-fill p-2">
<h4 className="mb-0 fw-bold"> <h4 className="mb-0 fw-bold text-truncate">
{tasksCardData?.totalTasks?.toLocaleString() ?? 0} {formatFigure(tasksCardData?.totalTasks ?? 0, {
notation: "compact",
})}
</h4> </h4>
<small className="text-muted">Total</small> <small className="text-muted d-block">Total</small>
</div> </div>
<div>
<h4 className="mb-0 fw-bold"> {/* Completed Tasks */}
{tasksCardData?.completedTasks?.toLocaleString() ?? 0} <div className="text-center flex-fill p-2">
<h4 className="mb-0 fw-bold text-truncate">
{formatFigure(tasksCardData?.completedTasks ?? 0, {
notation: "compact",
})}
</h4> </h4>
<small className="text-muted">Completed</small> <small className="text-muted d-block">Completed</small>
</div> </div>
</div> </div>
)} )}

View File

@ -4,16 +4,20 @@ import { useDashboardTeamsCardData } from "../../hooks/useDashboard_Data";
import eventBus from "../../services/eventBus"; import eventBus from "../../services/eventBus";
import { useQueryClient } from "@tanstack/react-query"; import { useQueryClient } from "@tanstack/react-query";
import { useSelectedProject } from "../../slices/apiDataManager"; import { useSelectedProject } from "../../slices/apiDataManager";
import { TeamsSkeleton } from "./DashboardSkeleton";
import { formatFigure } from "../../utils/appUtils";
const Teams = () => { const Teams = () => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const projectId = useSelectedProject() const projectId = useSelectedProject();
const { const {
data: teamsCardData, data: teamsCardData,
isLoading, isLoading,
isError, isError,
error, error,
isFetching,
refetch,
} = useDashboardTeamsCardData(projectId); } = useDashboardTeamsCardData(projectId);
// Handle real-time updates via eventBus // Handle real-time updates via eventBus
@ -40,6 +44,7 @@ const Teams = () => {
const inToday = teamsCardData?.inToday ?? 0; const inToday = teamsCardData?.inToday ?? 0;
const totalEmployees = teamsCardData?.totalEmployees ?? 0; const totalEmployees = teamsCardData?.totalEmployees ?? 0;
if (isLoading) return <TeamsSkeleton />;
return ( return (
<div className="card p-3 h-100 text-center d-flex justify-content-between"> <div className="card p-3 h-100 text-center d-flex justify-content-between">
<div className="d-flex justify-content-start align-items-center mb-3"> <div className="d-flex justify-content-start align-items-center mb-3">
@ -48,24 +53,41 @@ const Teams = () => {
</h5> </h5>
</div> </div>
{isLoading ? ( {isError ? (
<div className="d-flex justify-content-center align-items-center flex-grow-1"> <div className="d-flex flex-column justify-content-center align-items-center p-1">
<div className="spinner-border text-primary" role="status"> <i className="bx bx-error-circle bx-sm fs-2 "></i>
<span className="visually-hidden">Loading...</span>
</div> <small className="text-muted mb-2">
</div> {error?.message || "Unable to load data at the moment."}
) : isError ? ( </small>
<div className="text-danger flex-grow-1 d-flex justify-content-center align-items-center"> <span
{error?.message || "Error loading data"} className={`text-muted ${
isFetching ? "cursor-wait" : "cursor-pointer"
}`}
onClick={refetch}
>
<i
className={`bx bx-refresh me-1 ${isFetching ? "bx-spin" : ""}`}
></i>{" "}
Retry
</span>
</div> </div>
) : ( ) : (
<div className="d-flex justify-content-around align-items-start mt-n2"> <div className="d-flex justify-content-around align-items-start mt-n2">
<div> <div>
<h4 className="mb-0 fw-bold">{totalEmployees.toLocaleString()}</h4> <h4 className="mb-0 fw-bold">
{formatFigure(totalEmployees ?? 0, {
notation: "compact",
})}
</h4>
<small className="text-muted">Total Employees</small> <small className="text-muted">Total Employees</small>
</div> </div>
<div> <div>
<h4 className="mb-0 fw-bold">{inToday.toLocaleString()}</h4> <h4 className="mb-0 fw-bold">
{formatFigure(inToday ?? 0, {
notation: "compact",
})}
</h4>
<small className="text-muted">In Today</small> <small className="text-muted">In Today</small>
</div> </div>
</div> </div>

View File

@ -0,0 +1,56 @@
import React, { useMemo } from "react";
const ContactFilterChips = ({ filters, filterData, removeFilterChip, clearFilter }) => {
const data = filterData?.data || filterData || {};
const filterChips = useMemo(() => {
const chips = [];
const addGroup = (ids, list, label, key) => {
if (!ids?.length) return;
const items = ids.map((id) => ({
id,
name: list?.find((i) => i.id === id)?.name || id,
}));
chips.push({ key, label, items });
};
addGroup(filters.bucketIds, data.buckets, "Buckets", "bucketIds");
addGroup(filters.categoryIds, data.contactCategories, "Category", "categoryIds");
return chips;
}, [filters, filterData]);
if (!filterChips.length) return null;
return (
<div className="d-flex flex-wrap align-items-center gap-2">
{filterChips.map((chipGroup) => (
<div key={chipGroup.key} className="d-flex align-items-center flex-wrap">
<span className="fw-semibold me-2">{chipGroup.label}:</span>
{chipGroup.items.map((item) => (
<span
key={item.id}
className="d-flex align-items-center bg-light rounded px-2 py-1 me-1"
>
<span>{item.name}</span>
<button
type="button"
className="btn-close btn-close-white btn-sm ms-2"
style={{
filter: "invert(1) grayscale(1)",
opacity: 0.7,
fontSize: "0.6rem",
}}
onClick={() => removeFilterChip(chipGroup.key, item.id)}
/>
</span>
))}
</div>
))}
</div>
);
};
export default ContactFilterChips;

View File

@ -160,8 +160,7 @@ const ListViewContact = ({ data, Pagination }) => {
</div> </div>
) : ( ) : (
<i <i
className={`bx ${ className={`bx ${isPending && activeContact === row.id
isPending && activeContact === row.id
? "bx-loader-alt bx-spin" ? "bx-loader-alt bx-spin"
: "bx-recycle" : "bx-recycle"
} me-1 text-primary cursor-pointer`} } me-1 text-primary cursor-pointer`}
@ -188,13 +187,13 @@ const ListViewContact = ({ data, Pagination }) => {
)} )}
</tbody> </tbody>
</table> </table>
{Pagination && (
<div className="d-flex justify-content-start">
{Pagination}
</div>
)}
</div> </div>
</div> </div>
{Pagination && (
<div className="d-flex justify-content-start">
{Pagination}
</div>
)}
</div> </div>
</> </>
); );

View File

@ -0,0 +1,79 @@
import React, { useMemo } from "react";
import moment from "moment";
const NoteFilterChips = ({ filters, filterData, removeFilterChip }) => {
// Normalize data (in case its wrapped in .data)
const data = filterData?.data || filterData || {};
const filterChips = useMemo(() => {
const chips = [];
const buildGroup = (ids, list, label, key) => {
if (!ids?.length) return;
const items = ids.map((id) => ({
id,
name: list?.find((item) => item.id === id)?.name || id,
}));
chips.push({ key, label, items });
};
// Build chips dynamically
buildGroup(filters.createdByIds, data.createdBy, "Created By", "createdByIds");
buildGroup(filters.organizations, data.organizations, "Organization", "organizations");
// Example: Add date range if you ever add in future
if (filters.startDate || filters.endDate) {
const start = filters.startDate ? moment(filters.startDate).format("DD-MM-YYYY") : "";
const end = filters.endDate ? moment(filters.endDate).format("DD-MM-YYYY") : "";
chips.push({
key: "dateRange",
label: "Date Range",
items: [{ id: "dateRange", name: `${start} - ${end}` }],
});
}
return chips;
}, [filters, filterData]);
if (!filterChips.length) return null;
return (
<div className="row my-2">
<div className="col-12">
<div className="d-flex flex-wrap align-items-start gap-2">
{filterChips.map((chip) => (
<div
key={chip.key}
className="d-flex align-items-center flex-wrap px-2 py-1"
style={{ fontSize: "0.9rem" }}
>
<span className="fw-semibold me-2">{chip.label}:</span>
<div className="d-flex flex-wrap align-items-center gap-1">
{chip.items.map((item) => (
<span
key={item.id}
className="d-flex align-items-center bg-light rounded px-2 py-1 text-xs"
>
<span>{item.name}</span>
<button
type="button"
className="btn-close btn-close-white btn-sm ms-2"
style={{
filter: "invert(1) grayscale(1)",
opacity: 0.7,
fontSize: "0.6rem",
}}
onClick={() => removeFilterChip(chip.key, item.id)}
/>
</span>
))}
</div>
</div>
))}
</div>
</div>
</div>
);
};
export default NoteFilterChips;

View File

@ -0,0 +1,94 @@
import React, { useMemo } from "react";
import moment from "moment";
const DocumentFilterChips = ({ filters, filterData, removeFilterChip }) => {
// Normalize structure: handle both "filterData.data" and plain "filterData"
const data = filterData?.data || filterData || {};
const filterChips = useMemo(() => {
const chips = [];
const buildGroup = (ids, list, label, key) => {
if (!ids?.length) return;
const items = ids.map((id) => ({
id,
name: list?.find((item) => item.id === id)?.name || id,
}));
chips.push({ key, label, items });
};
// Build chips using normalized data
buildGroup(filters.uploadedByIds, data.uploadedBy || [], "Uploaded By", "uploadedByIds");
buildGroup(filters.documentCategoryIds, data.documentCategory || [], "Category", "documentCategoryIds");
buildGroup(filters.documentTypeIds, data.documentType || [], "Type", "documentTypeIds");
buildGroup(filters.documentTagIds, data.documentTag || [], "Tags", "documentTagIds");
if (filters.statusIds?.length) {
const items = filters.statusIds.map((status) => ({
id: status,
name:
status === true
? "Verified"
: status === false
? "Rejected"
: "Pending",
}));
chips.push({ key: "statusIds", label: "Status", items });
}
if (filters.startDate || filters.endDate) {
const start = filters.startDate ? moment(filters.startDate).format("DD-MM-YYYY") : "";
const end = filters.endDate ? moment(filters.endDate).format("DD-MM-YYYY") : "";
chips.push({
key: "dateRange",
label: "Date Range",
items: [{ id: "dateRange", name: `${start} - ${end}` }],
});
}
return chips;
}, [filters, filterData]);
if (!filterChips.length) return null;
return (
<div className="row my-2">
<div className="col-12">
<div className="d-flex flex-wrap align-items-start gap-1">
{filterChips.map((chip) => (
<div
key={chip.key}
className="d-flex align-items-center flex-wrap px-2 py-1"
style={{ fontSize: "0.9rem" }}
>
<span className="fw-semibold me-2">{chip.label}:</span>
<div className="d-flex flex-wrap align-items-center gap-1">
{chip.items.map((item) => (
<span
key={item.id}
className="d-flex align-items-center bg-light rounded px-2 py-1 text-xs"
>
<span>{item.name}</span>
<button
type="button"
className="btn-close btn-close-white btn-sm ms-2"
style={{
filter: "invert(1) grayscale(1)",
opacity: 0.7,
fontSize: "0.6rem",
}}
onClick={() => removeFilterChip(chip.key, item.id)}
/>
</span>
))}
</div>
</div>
))}
</div>
</div>
</div>
);
};
export default DocumentFilterChips;

View File

@ -1,4 +1,4 @@
import React, { useEffect, useState } from "react"; import React, { useEffect, useState, useMemo, useImperativeHandle, forwardRef } from "react";
import { useDocumentFilterEntities } from "../../hooks/useDocument"; import { useDocumentFilterEntities } from "../../hooks/useDocument";
import { FormProvider, useForm } from "react-hook-form"; import { FormProvider, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
@ -9,18 +9,34 @@ import {
import { DateRangePicker1 } from "../common/DateRangePicker"; import { DateRangePicker1 } from "../common/DateRangePicker";
import SelectMultiple from "../common/SelectMultiple"; import SelectMultiple from "../common/SelectMultiple";
import moment from "moment"; import moment from "moment";
import { useLocation } from "react-router-dom"; import { useParams } from "react-router-dom";
const DocumentFilterPanel = ({ entityTypeId, onApply }) => { const DocumentFilterPanel = forwardRef(
({ entityTypeId, onApply, setFilterdata }, ref) => {
const [resetKey, setResetKey] = useState(0); const [resetKey, setResetKey] = useState(0);
const location = useLocation(); const { status } = useParams();
const { data, isError, isLoading, error } = const { data, isError, isLoading, error } =
useDocumentFilterEntities(entityTypeId); useDocumentFilterEntities(entityTypeId);
//changes
const dynamicDocumentFilterDefaultValues = useMemo(() => {
return {
...DocumentFilterDefaultValues,
uploadedByIds: DocumentFilterDefaultValues.uploadedByIds || [],
documentCategoryIds: DocumentFilterDefaultValues.documentCategoryIds || [],
documentTypeIds: DocumentFilterDefaultValues.documentTypeIds || [],
documentTagIds: DocumentFilterDefaultValues.documentTagIds || [],
startDate: DocumentFilterDefaultValues.startDate,
endDate: DocumentFilterDefaultValues.endDate,
};
}, [status]);
const methods = useForm({ const methods = useForm({
resolver: zodResolver(DocumentFilterSchema), resolver: zodResolver(DocumentFilterSchema),
defaultValues: DocumentFilterDefaultValues, defaultValues: dynamicDocumentFilterDefaultValues,
}); });
const { handleSubmit, reset, setValue, watch } = methods; const { handleSubmit, reset, setValue, watch } = methods;
@ -34,6 +50,24 @@ const DocumentFilterPanel = ({ entityTypeId, onApply }) => {
document.querySelector(".offcanvas.show .btn-close")?.click(); document.querySelector(".offcanvas.show .btn-close")?.click();
}; };
useImperativeHandle(ref, () => ({
resetFieldValue: (name, value) => {
if (value !== undefined) {
setValue(name, value);
} else {
reset({ ...methods.getValues(), [name]: DocumentFilterDefaultValues[name] });
}
},
getValues: methods.getValues, // optional, to read current filter state
}));
//changes
useEffect(() => {
if (data && setFilterdata) {
setFilterdata(data);
}
}, [data, setFilterdata]);
const onSubmit = (values) => { const onSubmit = (values) => {
onApply({ onApply({
...values, ...values,
@ -44,23 +78,16 @@ const DocumentFilterPanel = ({ entityTypeId, onApply }) => {
? moment.utc(values.endDate, "DD-MM-YYYY").toISOString() ? moment.utc(values.endDate, "DD-MM-YYYY").toISOString()
: null, : null,
}); });
closePanel(); // closePanel();
}; };
const onClear = () => { const onClear = () => {
reset(DocumentFilterDefaultValues); reset(DocumentFilterDefaultValues);
setResetKey((prev) => prev + 1); setResetKey((prev) => prev + 1);
onApply(DocumentFilterDefaultValues); onApply(DocumentFilterDefaultValues);
closePanel(); // closePanel();
}; };
// Close popup when navigating to another component
useEffect(() => {
return () => {
closePanel();
};
}, []);
if (isLoading) return <div>Loading...</div>; if (isLoading) return <div>Loading...</div>;
if (isError) if (isError)
return <div>Error: {error?.message || "Something went wrong!"}</div>; return <div>Error: {error?.message || "Something went wrong!"}</div>;
@ -198,18 +225,18 @@ const DocumentFilterPanel = ({ entityTypeId, onApply }) => {
<div className="d-flex justify-content-end py-3 gap-2"> <div className="d-flex justify-content-end py-3 gap-2">
<button <button
type="button" type="button"
className="btn btn-label-secondary btn-xs" className="btn btn-label-secondary btn-sm"
onClick={onClear} onClick={onClear}
> >
Clear Clear
</button> </button>
<button type="submit" className="btn btn-primary btn-xs"> <button type="submit" className="btn btn-primary btn-sm">
Apply Apply
</button> </button>
</div> </div>
</form> </form>
</FormProvider> </FormProvider>
); );
}; });
export default DocumentFilterPanel; export default DocumentFilterPanel;

View File

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

View File

@ -82,9 +82,9 @@ const DocumentsList = ({
if (isLoading || isFetching) return <DocumentTableSkeleton />; if (isLoading || isFetching) return <DocumentTableSkeleton />;
if (isError) if (isError)
return <div>Error: {error?.message || "Something went wrong"}</div>; return <div>Error: {error?.message || "Something went wrong"}</div>;
if (isInitialEmpty) return <div>No documents found yet.</div>; if (isInitialEmpty) return <div className="py-12 my-12">No documents found yet.</div>;
if (isSearchEmpty) return <div>No results found for "{debouncedSearch}"</div>; if (isSearchEmpty) return <div className="py-12 my-12">No results found for "{debouncedSearch}"</div>;
if (isFilterEmpty) return <div>No documents match your filter.</div>; if (isFilterEmpty) return <div className="py-12 my-12">No documents match your filter.</div>;
const handleDelete = () => { const handleDelete = () => {
ActiveInActive( ActiveInActive(
@ -138,16 +138,14 @@ const DocumentsList = ({
lastName={e.uploadedBy?.lastName} lastName={e.uploadedBy?.lastName}
/> />
<span className="text-truncate ms-1"> <span className="text-truncate ms-1">
{`${e.uploadedBy?.firstName ?? ""} ${ {`${e.uploadedBy?.firstName ?? ""} ${e.uploadedBy?.lastName ?? ""
e.uploadedBy?.lastName ?? "" }`.trim() || "N/A"}
}`.trim() || "N/A"}
</span> </span>
</div> </div>
), ),
getValue: (e) => getValue: (e) =>
`${e.uploadedBy?.firstName ?? ""} ${ `${e.uploadedBy?.firstName ?? ""} ${e.uploadedBy?.lastName ?? ""
e.uploadedBy?.lastName ?? "" }`.trim() || "N/A",
}`.trim() || "N/A",
}, },
{ {
key: "uploadedAt", key: "uploadedAt",
@ -217,7 +215,7 @@ const DocumentsList = ({
} }
></i> ></i>
{(isSelf || canModifyDocument) && ( {(isSelf || canModifyDocument) && (
<i <i
className="bx bx-edit text-secondary cursor-pointer" className="bx bx-edit text-secondary cursor-pointer"
onClick={() => onClick={() =>
@ -226,7 +224,7 @@ const DocumentsList = ({
></i> ></i>
)} )}
{(isSelf || canDeleteDocument) && ( {(isSelf || canDeleteDocument) && (
<i <i
className="bx bx-trash text-danger cursor-pointer" className="bx bx-trash text-danger cursor-pointer"
onClick={() => { onClick={() => {

View File

@ -0,0 +1,84 @@
import moment from "moment";
import { exportToExcel, exportToCSV, exportToPDF, printTable } from "../../utils/tableExportUtils";
/**
* Handles export operations for employee data.
* @param {string} type - Export type: 'csv', 'excel', 'pdf', or 'print'
* @param {Array} employeeList - Full employee data array
* @param {Array} filteredData - Filtered employee data (if search applied)
* @param {string} searchText - Current search text (used to decide dataset)
* @param {RefObject} tableRef - Table reference (used for print)
*/
const handleEmployeeExport = (type, employeeList, filteredData, searchText, tableRef) => {
// Export full list (filtered if search applied)
const dataToExport = searchText ? filteredData : employeeList;
if (!dataToExport || dataToExport.length === 0) return;
// Map and format employee data for export
const exportData = dataToExport.map((item) => ({
"First Name": item.firstName || "",
"Middle Name": item.middleName || "",
"Last Name": item.lastName || "",
"Email": item.email || "",
"Gender": item.gender || "",
"Birth Date": item.birthdate
? moment(item.birthdate).format("DD-MMM-YYYY")
: "",
"Joining Date": item.joiningDate
? moment(item.joiningDate).format("DD-MMM-YYYY")
: "",
"Permanent Address": item.permanentAddress || "",
"Current Address": item.currentAddress || "",
"Phone Number": item.phoneNumber || "",
"Emergency Phone Number": item.emergencyPhoneNumber || "",
"Emergency Contact Person": item.emergencyContactPerson || "",
"Is Active": item.isActive ? "Active" : "Inactive",
"Job Role": item.jobRole || "",
}));
switch (type) {
case "csv":
exportToCSV(exportData, "employees");
break;
case "excel":
exportToExcel(exportData, "employees");
break;
case "pdf":
exportToPDF(
dataToExport.map((item) => ({
Name: `${item.firstName || ""} ${item.lastName || ""}`.trim(),
Email: item.email || "",
"Phone Number": item.phoneNumber || "",
"Job Role": item.jobRole || "",
"Joining Date": item.joiningDate
? moment(item.joiningDate).format("DD-MMM-YYYY")
: "",
Gender: item.gender || "",
Status: item.isActive ? "Active" : "Inactive",
})),
"employees",
[
"Name",
"Email",
"Phone Number",
"Job Role",
"Joining Date",
"Gender",
"Status",
]
);
break;
case "print":
printTable(tableRef.current);
break;
default:
break;
}
};
export default handleEmployeeExport;

View File

@ -0,0 +1,86 @@
import React, { useMemo } from "react";
const ExpenseFilterChips = ({ filters, filterData, removeFilterChip }) => {
// Build chips from filters
const filterChips = useMemo(() => {
const chips = [];
const buildGroup = (ids, list, label, key) => {
if (!ids?.length) return;
const items = ids.map((id) => ({
id,
name: list.find((item) => item.id === id)?.name || id,
}));
chips.push({ key, label, items });
};
buildGroup(filters.projectIds, filterData.projects, "Project", "projectIds");
buildGroup(filters.createdByIds, filterData.createdBy, "Submitted By", "createdByIds");
buildGroup(filters.paidById, filterData.paidBy, "Paid By", "paidById");
buildGroup(filters.statusIds, filterData.status, "Status", "statusIds");
buildGroup(filters.ExpenseTypeIds, filterData.expensesType, "Category", "ExpenseTypeIds");
if (filters.startDate || filters.endDate) {
const start = filters.startDate
? new Date(filters.startDate).toLocaleDateString()
: "";
const end = filters.endDate
? new Date(filters.endDate).toLocaleDateString()
: "";
chips.push({
key: "dateRange",
label: "Date Range",
items: [{ id: "dateRange", name: `${start} - ${end}` }],
});
}
return chips;
}, [filters, filterData]);
if (!filterChips.length) return null;
return (
<div className="row">
<div className="col-12">
<div className="d-flex flex-wrap align-items-start gap-1 text-start">
{filterChips.map((chip) => (
<div
key={chip.key}
className="d-flex align-items-center flex-wrap px-2 py-1 "
style={{ fontSize: "0.9rem", maxWidth: "100%" }}
>
{/* Chip Label */}
<span className="fw-semibold me-2">{chip.label}:</span>
{/* Chip Items */}
<div className="d-flex flex-wrap align-items-center gap-1">
{chip.items.map((item) => (
<span
key={item.id}
className="d-flex align-items-center bg-light rounded px-2 py-1 text-xs"
>
<span>{item.name}</span>
<button
type="button"
className="btn-close btn-close-white btn-sm ms-2"
style={{
filter: "invert(1) grayscale(1)",
opacity: 0.7,
fontSize: "0.6rem",
}}
onClick={() => removeFilterChip(chip.key, item.id)}
/>
</span>
))}
</div>
</div>
))}
</div>
</div>
</div>
);
};
export default ExpenseFilterChips;

View File

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

View File

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

View File

@ -1,28 +1,137 @@
import { useState } from 'react'; import { useState, useRef ,useEffect} from "react";
const PreviewDocument = ({ imageUrl }) => { const PreviewDocument = ({ imageUrl }) => {
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [rotation, setRotation] = useState(0);
const [zoom, setZoom] = useState(1);
const [position, setPosition] = useState({ x: 0, y: 0 });
const [isDragging, setIsDragging] = useState(false);
const [startPos, setStartPos] = useState({ x: 0, y: 0 });
const containerRef = useRef(null);
// Zoom handlers
const handleZoomIn = () => setZoom((prev) => Math.min(prev + 0.2, 3));
const handleZoomOut = () => setZoom((prev) => Math.max(prev - 0.2, 0.5));
// Mouse wheel zoom
const handleWheel = (e) => {
e.preventDefault();
const delta = e.deltaY > 0 ? -0.1 : 0.1;
setZoom((prev) => Math.min(Math.max(prev + delta, 0.5), 3));
};
useEffect(() => {
const container = containerRef.current;
if (!container) return;
container.addEventListener("wheel", handleWheel, { passive: false });
return () => {
container.removeEventListener("wheel", handleWheel);
};
}, []);
const handleMouseDown = (e) => {
if (zoom <= 1) return;
setIsDragging(true);
setStartPos({
x: e.clientX - position.x,
y: e.clientY - position.y,
});
};
const handleMouseMove = (e) => {
if (!isDragging) return;
setPosition({
x: e.clientX - startPos.x,
y: e.clientY - startPos.y,
});
};
const handleMouseUp = () => setIsDragging(false);
const handleMouseLeave = () => setIsDragging(false);
const handleReset = () => {
setRotation(0);
setZoom(1);
setPosition({ x: 0, y: 0 });
};
return ( return (
<div className="d-flex justify-content-center align-items-center" style={{ minHeight: "50vh" }}> <>
{loading && ( <div className="d-flex justify-content-start align-items-center gap-3 mb-2 px-3 py-2 px-md-0 py-md-0">
<div className="text-secondary text-center mb-2"> <i
Loading... className="bx bx-rotate-right fs-4 cursor-pointer"
</div> title="Rotate Right"
)} onClick={() => setRotation((prev) => prev + 90)}
<img ></i>
src={imageUrl} <i
alt="Full View" className="bx bx-zoom-in fs-4 cursor-pointer"
className="img-fluid" title="Zoom In"
onClick={handleZoomIn}
></i>
<i
className="bx bx-zoom-out fs-4 cursor-pointer"
title="Zoom Out"
onClick={handleZoomOut}
></i>
<i
className="bx bx-reset fs-4 cursor-pointer"
title="Reset"
onClick={handleReset}
></i>
</div>
<div
ref={containerRef}
onMouseDown={handleMouseDown}
onMouseMove={handleMouseMove}
onMouseUp={handleMouseUp}
onMouseLeave={handleMouseLeave}
className="d-flex justify-content-center align-items-center overflow-hidden border rounded "
style={{ style={{
maxHeight: "100vh", width: "100%",
objectFit: "contain", height: "80vh",
display: loading ? "none" : "block", background: "#f8f9fa",
cursor: zoom > 1 ? (isDragging ? "grabbing" : "grab") : "default",
userSelect: "none",
position: "relative",
}} }}
onLoad={() => setLoading(false)} >
/> {loading && (
</div> <div className="text-secondary text-center position-absolute">
Loading...
</div>
)}
<img
src={imageUrl}
alt="Preview"
onLoad={() => setLoading(false)}
style={{
transform: `translate(${position.x}px, ${position.y}px) rotate(${rotation}deg) scale(${zoom})`,
transition: isDragging ? "none" : "transform 0.3s ease",
objectFit: "contain",
maxWidth: "100%",
maxHeight: "100%",
display: loading ? "none" : "block",
pointerEvents: "none",
}}
/>
</div>
{/* <div className="d-flex justify-content-center gap-2 mt-2">
<button
className="btn btn-sm btn-outline-secondary"
onClick={handleReset}
title="Reset View"
>
<i className="bx bx-reset"></i> Reset View
</button>
</div> */}
</>
); );
}; };
export default PreviewDocument; export default PreviewDocument;

View File

@ -9,7 +9,11 @@ import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import { defaultActionValues, ExpenseActionScheam } from "./ExpenseSchema"; import { defaultActionValues, ExpenseActionScheam } from "./ExpenseSchema";
import { useExpenseContext } from "../../pages/Expense/ExpensePage"; import { useExpenseContext } from "../../pages/Expense/ExpensePage";
import { getColorNameFromHex, getIconByFileType, localToUtc } from "../../utils/appUtils"; import {
getColorNameFromHex,
getIconByFileType,
localToUtc,
} from "../../utils/appUtils";
import { ExpenseDetailsSkeleton } from "./ExpenseSkeleton"; import { ExpenseDetailsSkeleton } from "./ExpenseSkeleton";
import { useHasUserPermission } from "../../hooks/useHasUserPermission"; import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { import {
@ -301,15 +305,15 @@ const ViewExpense = ({ ExpenseId }) => {
<div className="d-flex flex-wrap gap-2"> <div className="d-flex flex-wrap gap-2">
{data?.documents?.map((doc) => { {data?.documents?.map((doc) => {
const isImage = doc.contentType?.includes("image"); const isImage = doc.contentType?.startsWith("image");
return ( return (
<div <div
key={doc.documentId} key={doc.documentId}
className="border rounded hover-scale p-2 d-flex flex-column align-items-center" className="border rounded hover-scale p-2 d-flex flex-column align-items-center"
style={{ style={{
width: "80px", width: "80px",
cursor: isImage ? "pointer" : "default", cursor: "pointer",
}} }}
onClick={() => { onClick={() => {
if (isImage) { if (isImage) {
@ -317,6 +321,8 @@ const ViewExpense = ({ ExpenseId }) => {
IsOpen: true, IsOpen: true,
Image: doc.preSignedUrl, Image: doc.preSignedUrl,
}); });
} else {
window.open(doc.preSignedUrl, "_blank");
} }
}} }}
> >
@ -332,7 +338,7 @@ const ViewExpense = ({ ExpenseId }) => {
</small> </small>
</div> </div>
); );
})} }) ?? "No Attachment"}
</div> </div>
</div> </div>
@ -418,7 +424,9 @@ const ViewExpense = ({ ExpenseId }) => {
{((nextStatusWithPermission.length > 0 && !IsRejectedExpense) || {((nextStatusWithPermission.length > 0 && !IsRejectedExpense) ||
(IsRejectedExpense && isCreatedBy)) && ( (IsRejectedExpense && isCreatedBy)) && (
<> <>
<Label className="form-label me-2 mb-0" required>Comment</Label> <Label className="form-label me-2 mb-0" required>
Comment
</Label>
<textarea <textarea
className="form-control form-control-sm" className="form-control form-control-sm"
{...register("comment")} {...register("comment")}
@ -440,7 +448,7 @@ const ViewExpense = ({ ExpenseId }) => {
key={status.id || index} key={status.id || index}
type="button" type="button"
onClick={() => { onClick={() => {
setClickedStatusId(status.id); setClickedStatusId(status.id);
setValue("statusId", status.id); setValue("statusId", status.id);
handleSubmit(onSubmit)(); handleSubmit(onSubmit)();
}} }}

View File

@ -34,6 +34,8 @@ const Header = () => {
const isDashboardPath = const isDashboardPath =
/^\/dashboard$/.test(location.pathname) || /^\/$/.test(location.pathname); /^\/dashboard$/.test(location.pathname) || /^\/$/.test(location.pathname);
const isProjectPath = /^\/projects$/.test(location.pathname); const isProjectPath = /^\/projects$/.test(location.pathname);
const isCollectionPath =
/^\/collection$/.test(location.pathname) || /^\/$/.test(location.pathname);
const showProjectDropdown = (pathname) => { const showProjectDropdown = (pathname) => {
const isDirectoryPath = /^\/directory$/.test(pathname); const isDirectoryPath = /^\/directory$/.test(pathname);
@ -216,7 +218,7 @@ const Header = () => {
className="dropdown-menu" className="dropdown-menu"
style={{ overflow: "auto", maxHeight: "300px" }} style={{ overflow: "auto", maxHeight: "300px" }}
> >
{isDashboardPath && ( {(isDashboardPath|| isCollectionPath) &&(
<li> <li>
<button <button
className="dropdown-item" className="dropdown-item"

View File

@ -1,4 +1,4 @@
import React, { useEffect, useState } from "react"; import React, { useEffect } from "react";
import { FormProvider, useForm } from "react-hook-form"; import { FormProvider, useForm } from "react-hook-form";
import { import {
useCreateOrganization, useCreateOrganization,
@ -14,7 +14,6 @@ import Label from "../common/Label";
import { useGlobalServices } from "../../hooks/masterHook/useMaster"; import { useGlobalServices } from "../../hooks/masterHook/useMaster";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import SelectMultiple from "../common/SelectMultiple"; import SelectMultiple from "../common/SelectMultiple";
import { LogoUpload } from "../Tenant/LogoUpload";
const ManagOrg = () => { const ManagOrg = () => {
const { data: service, isLoading } = useGlobalServices(); const { data: service, isLoading } = useGlobalServices();
@ -32,14 +31,10 @@ const ManagOrg = () => {
defaultValues: defaultOrganizationValues, defaultValues: defaultOrganizationValues,
}); });
const [logoPreview, setLogoPreview] = useState(null);
const [logoName, setLogoName] = useState("");
const { const {
handleSubmit, handleSubmit,
register, register,
reset, reset,
getValues,
formState: { errors }, formState: { errors },
} = method; } = method;
@ -67,7 +62,6 @@ const ManagOrg = () => {
email: organization.email || "", email: organization.email || "",
serviceIds: organization.services?.map((s) => s.id) || [], serviceIds: organization.services?.map((s) => s.id) || [],
address: organization.address || "", address: organization.address || "",
logoImage: organization.logoImage || "",
}); });
} }
}, [organization, reset, service?.data]); }, [organization, reset, service?.data]);
@ -99,14 +93,6 @@ const ManagOrg = () => {
} }
onOpen({ startStep: 2 }); onOpen({ startStep: 2 });
}; };
useEffect(() => {
const logoImage = getValues("logoImage");
if (logoImage) {
setLogoPreview(logoImage);
setLogoName("Uploaded Logo");
}
}, [getValues]);
return ( return (
<FormProvider {...method}> <FormProvider {...method}>
<form className="form" onSubmit={handleSubmit(onSubmit)}> <form className="form" onSubmit={handleSubmit(onSubmit)}>
@ -190,17 +176,6 @@ const ManagOrg = () => {
)} )}
</div> </div>
<div className="col-sm-12 text-start mt-2">
<Label htmlFor="logoImage" required>Logo Image</Label>
<LogoUpload
preview={logoPreview}
setPreview={setLogoPreview}
fileName={logoName}
setFileName={setLogoName}
/>
</div>
<div className="d-flex justify-content-between gap-2 my-2"> <div className="d-flex justify-content-between gap-2 my-2">
<button <button
type="button" type="button"
@ -224,8 +199,8 @@ const ManagOrg = () => {
{isCreating || isUpdating {isCreating || isUpdating
? "Please Wait..." ? "Please Wait..."
: orgData : orgData
? "Update" ? "Update"
: "Submit"} : "Submit"}
</button> </button>
</div> </div>
</div> </div>

View File

@ -12,13 +12,12 @@ import { spridSchema } from "./OrganizationSchema";
import { OrgCardSkeleton } from "./OrganizationSkeleton"; import { OrgCardSkeleton } from "./OrganizationSkeleton";
import { useQueryClient } from "@tanstack/react-query"; import { useQueryClient } from "@tanstack/react-query";
// Zod schema: only allow exactly 4 digits // Zod schema: only allow exactly 4 digits
const OrgPickerFromSPId = ({ title, placeholder }) => { const OrgPickerFromSPId = ({ title, placeholder }) => {
const { onClose, startStep, flowType, onOpen, prevStep,orgData } = const { onClose, startStep, flowType, onOpen, prevStep, orgData } =
useOrganizationModal(); useOrganizationModal();
const clientQuery = useQueryClient() const clientQuery = useQueryClient();
const { const {
register, register,
handleSubmit, handleSubmit,
@ -37,33 +36,42 @@ const OrgPickerFromSPId = ({ title, placeholder }) => {
const onSubmit = (formdata) => { const onSubmit = (formdata) => {
setSPRID(formdata.spridSearchText); setSPRID(formdata.spridSearchText);
}; };
const handleCrateOrg = () => { const handleCrateOrg = () => {
clientQuery.removeQueries({queryKey:["organization"]}) clientQuery.removeQueries({ queryKey: ["organization"] });
onOpen({ startStep: 4,orgData:null }) onOpen({ startStep: 4, orgData: null });
}; };
const SP = watch("spridSearchText"); const SP = watch("spridSearchText");
return ( return (
<div className="d-block"> <div className="d-block mt-4">
<form <form onSubmit={handleSubmit(onSubmit)}>
className="d-flex flex-row gap-6 text-start align-items-center" <div className="row align-items-center g-2">
onSubmit={handleSubmit(onSubmit)} {/* Input Section */}
> <div className="col-12 col-md-8 d-block d-md-flex align-items-center gap-2 m-0 text-start">
<div className="d-flex flex-row align-items-center gap-2"> <Label className="text-nowrap mb-1 mb-md-0" required>
<Label className="text-secondary">Search by SPRID</Label> Search by SPRID
<input </Label>
type="search" <input
{...register("spridSearchText")} type="search"
className="form-control form-control-sm w-auto" {...register("spridSearchText")}
placeholder="Enter SPRID" className="form-control form-control-sm flex-grow-1"
maxLength={4} placeholder="Enter SPRID"
/> maxLength={4}
</div> />
</div>
<button type="submit" className="btn btn-sm btn-primary"> {/* Button Section */}
<i className="bx bx-sm bx-search-alt-2"></i> Search <div className="col-12 col-md-4 text-md-start text-center mt-2 mt-md-0">
</button> <button
type="submit"
className="btn btn-sm btn-primary w-100 w-md-auto"
>
<i className="bx bx-sm bx-search-alt-2"></i> Search
</button>
</div>
</div>
</form> </form>
<div className="text-start danger-text"> <div className="text-start danger-text">
{" "} {" "}
{errors.spridSearchText && ( {errors.spridSearchText && (
@ -124,7 +132,7 @@ const OrgPickerFromSPId = ({ title, placeholder }) => {
No organization found for "{SPRID}" No organization found for "{SPRID}"
</div> </div>
) : null} ) : null}
<div className="py-12 text-center text-tiny text-black"> <div className="py-2 text-center text-tiny text-black">
<small className="d-block text-secondary"> <small className="d-block text-secondary">
Do not have SPRID or could not find organization ? Do not have SPRID or could not find organization ?
</small> </small>

View File

@ -13,7 +13,6 @@ export const organizationSchema = z.object({
.regex(phoneRegex, { message: "Invalid phone number" }), .regex(phoneRegex, { message: "Invalid phone number" }),
contactPerson: z.string().min(1, { message: "Person name required" }), contactPerson: z.string().min(1, { message: "Person name required" }),
address: z.string().min(1, { message: "Address is required!" }), address: z.string().min(1, { message: "Address is required!" }),
logoImage: z.string().min(1, { message: "Logo is required!" }),
email: z email: z
.string().trim() .string().trim()
.min(1, { message: "Email is required" }) .min(1, { message: "Email is required" })
@ -29,7 +28,6 @@ export const defaultOrganizationValues = {
contactPerson: "", contactPerson: "",
address: "", address: "",
email: "", email: "",
logoImage:"",
serviceIds: [], serviceIds: [],
}; };
@ -56,4 +54,4 @@ export const spridSchema = z.object({
spridSearchText: z spridSearchText: z
.string() .string()
.regex(/^\d{4}$/, { message: "SPRID must be exactly 4 digits" }), .regex(/^\d{4}$/, { message: "SPRID must be exactly 4 digits" }),
}); });

View File

@ -93,10 +93,12 @@ const OrganizationsList = ({searchText}) => {
if (isError) return <div>{error?.message || "Something went wrong"}</div>; if (isError) return <div>{error?.message || "Something went wrong"}</div>;
return ( return (
<div className="card px-0 px-sm-4 pb-12 pt-5"> <div
<div className="card-datatable table-responsive" id="horizontal-example"> className="card-datatable table-responsive overflow-auto"
<div className="dataTables_wrapper no-footer px-2"> id="horizontal-example"
<table className="table border-top dataTable text-nowrap"> >
<div className="dataTables_wrapper no-footer px-2 ">
<table className="table border-top dataTable text-nowrap">
<thead> <thead>
<tr className="table_header_border"> <tr className="table_header_border">
{organizationsColumns.map((col) => ( {organizationsColumns.map((col) => (
@ -157,7 +159,6 @@ const OrganizationsList = ({searchText}) => {
)} )}
</div> </div>
</div> </div>
</div>
); );
}; };

View File

@ -104,7 +104,7 @@ const WorkArea = ({ workArea, floor, forBuilding }) => {
</span> </span>
</div> </div>
<div className="col-2"> <div className="col-6 col-md-2">
<ProgressBar <ProgressBar
completedWork={formatNumber(workArea?.completedWork)} completedWork={formatNumber(workArea?.completedWork)}
plannedWork={formatNumber(workArea?.plannedWork)} plannedWork={formatNumber(workArea?.plannedWork)}

View File

@ -40,31 +40,32 @@ const ProjectNav = ({ onPillClick, activePill }) => {
label: "Directory", label: "Directory",
hidden: !(DirAdmin || DireManager || DirUser), hidden: !(DirAdmin || DireManager || DirUser),
}, },
{ key: "documents", icon: "bx bx-folder-open", label: "Documents",hidden:!(isViewDocuments || isModifyDocument || isUploadDocument) }, { key: "documents", icon: "bx bx-folder-open", label: "Documents", hidden: !(isViewDocuments || isModifyDocument || isUploadDocument) },
{ key: "organization", icon: "bx bx-buildings", label: "Organization"}, { key: "organization", icon: "bx bx-buildings", label: "Organization" },
{ key: "setting", icon: "bx bxs-cog", label: "Setting",hidden:!isManageTeam }, { key: "setting", icon: "bx bxs-cog", label: "Setting", hidden: !isManageTeam },
]; ];
return ( return (
<div className="nav-align-top"> <div className="table-responsive">
<ul className="nav nav-tabs"> <div className="nav-align-top">
{ProjectTab?.filter((tab) => !tab.hidden)?.map((tab) => ( <ul className="nav nav-tabs">
<li key={tab.key} className="nav-item cursor-pointer"> {ProjectTab?.filter((tab) => !tab.hidden)?.map((tab) => (
<a <li key={tab.key} className="nav-item cursor-pointer">
<a
className={`nav-link ${
activePill === tab.key ? "active cursor-pointer" : "" className={`nav-link ${activePill === tab.key ? "active cursor-pointer" : ""
} fs-6`} } fs-6`}
onClick={(e) => { onClick={(e) => {
e.preventDefault(); e.preventDefault();
onPillClick(tab.key); onPillClick(tab.key);
}} }}
> >
<i className={`${tab.icon} bx-sm me-1_5`}></i> <i className={`${tab.icon} bx-sm me-1_5`}></i>
<span className="d-none d-md-inline ">{tab.label}</span> <span className="d-none d-md-inline ">{tab.label}</span>
</a> </a>
</li> </li>
))} ))}
</ul> </ul>
</div>
</div> </div>
); );
}; };

View File

@ -45,7 +45,7 @@ export const LogoUpload = ({ preview, setPreview, fileName, setFileName }) => {
return ( return (
<div className="col-sm-12 mb-3"> <div className="col-sm-12 mb-3">
<div <div
className="border border-secondary text-black border-dashed rounded p-2 text-center position-relative" className="border border-secondary border-dashed rounded p-2 text-center position-relative"
style={{ cursor: "pointer" }} style={{ cursor: "pointer" }}
onClick={() => document.getElementById("logoImageInput")?.click()} onClick={() => document.getElementById("logoImageInput")?.click()}
> >

View File

@ -136,7 +136,7 @@ const TenantsList = ({
); );
return ( return (
<> <>
<div className="p-2 mt-3"> <div className=" mt-3">
<div className=" text-nowrap table-responsive"> <div className=" text-nowrap table-responsive">
<table className="table border-top dataTable text-nowrap"> <table className="table border-top dataTable text-nowrap">
<thead> <thead>

View File

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

@ -0,0 +1,296 @@
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 px-sm-4 px-0">
<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

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

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

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

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

@ -0,0 +1,260 @@
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?.startsWith("image");
return (
<div
key={doc.documentId}
className="border rounded hover-scale p-2 d-flex flex-column align-items-center"
style={{
width: "80px",
cursor: "pointer",
}}
onClick={() => {
if (isImage) {
setDocumentView({
IsOpen: true,
Image: doc.preSignedUrl,
});
} else {
window.open(doc.preSignedUrl, "_blank");
}
}}
>
<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

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

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

View File

@ -51,7 +51,7 @@ const Avatar = ({ firstName, lastName, size = "sm", classAvatar }) => {
return ( return (
<div className="avatar-wrapper p-1"> <div className="avatar-wrapper p-1">
<div className={`avatar avatar-${size} me-2 ${classAvatar}`}> <div className={`avatar avatar-${size} ${classAvatar}`}>
<span className={`avatar-initial rounded-circle ${bgClass}`}> <span className={`avatar-initial rounded-circle ${bgClass}`}>
{generateAvatarText(firstName, lastName)} {generateAvatarText(firstName, lastName)}
</span> </span>

View File

@ -13,19 +13,18 @@ const ConfirmModal = ({
if (!isOpen) return null; if (!isOpen) return null;
const TypeofIcon = () => { const TypeofIcon = () => {
if (type === "delete") { switch (type) {
return ( case "delete":
<i return <i className="bx bx-x-circle text-danger" style={{ fontSize: "60px" }}></i>;
className="bx bx-x-circle text-danger" case "success":
style={{ fontSize: "60px" }} return <i className="bx bx-check-circle text-success" style={{ fontSize: "60px" }}></i>;
></i> case "warning":
); return <i className="bx bx-error-circle text-warning" style={{ fontSize: "60px" }}></i>;
default:
return null;
} }
return null;
}; };
const modalSize = type === "delete" ? "sm" : "md";
return ( return (
<div <div
className="modal fade show" className="modal fade show"
@ -33,22 +32,24 @@ const ConfirmModal = ({
role="dialog" role="dialog"
aria-modal="true" aria-modal="true"
> >
<div className={`modal-dialog modal-${modalSize} modal-dialog-top`}> <div className="modal-dialog modal-sm modal-dialog-top">
<div className="modal-content"> <div className="modal-content">
<div className="modal-body py-1 px-2"> <div className="modal-body py-1 px-2">
<div className="d-flex justify-content-between mb-4 pt-2"> <div className="d-flex justify-content-between mb-4 pt-2">
{header && <strong className="mb-0">{header}</strong>} {header && <strong className="mb-0">{header}</strong>}
<button <button
type="button" type="button"
className="btn-close " className="btn-close"
aria-label="Close" aria-label="Close"
onClick={onClose} onClick={onClose}
/> />
</div> </div>
<div className="row"> <div className="row">
<div className="col-4 col-sm-2">{TypeofIcon()}</div> <div className="col-4 col-sm-3 d-flex justify-content-center align-items-start">
<div className="col-8 col-sm-10 py-sm-2 py-1 text-sm-start"> {TypeofIcon()}
</div>
<div className="col-8 col-sm-9 py-sm-2 py-1 text-sm-start">
<span className="fs-6">{message}</span> <span className="fs-6">{message}</span>
<div className="d-flex justify-content-end mt-4"> <div className="d-flex justify-content-end mt-4">
<button <button
@ -59,7 +60,7 @@ const ConfirmModal = ({
{loading ? "Please Wait..." : "Yes"} {loading ? "Please Wait..." : "Yes"}
</button> </button>
<button <button
className="btn btn-secondary ms-4 btn-sm" className="btn btn-secondary ms-3 btn-sm"
onClick={onClose} onClick={onClose}
disabled={loading} disabled={loading}
> >
@ -68,6 +69,7 @@ const ConfirmModal = ({
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>

View File

@ -73,7 +73,7 @@ const DateRangePicker = ({
/> />
<i <i
className="bx bx-calendar calendar-icon cursor-pointer position-absolute top-50 end-0 translate-middle-y me-2 " className="bx bx-calendar calendar-icon cursor-pointer position-absolute ms-n6 top-50 end-30 translate-middle-y me-2 "
onClick={handleIconClick} onClick={handleIconClick}
/> />
</div> </div>
@ -88,7 +88,6 @@ export default DateRangePicker;
export const DateRangePicker1 = ({ export const DateRangePicker1 = ({
startField = "startDate", startField = "startDate",
endField = "endDate", endField = "endDate",
@ -98,6 +97,7 @@ export const DateRangePicker1 = ({
resetSignal, resetSignal,
defaultRange = true, defaultRange = true,
maxDate = null, maxDate = null,
howManyDay = 6,
...rest ...rest
}) => { }) => {
const inputRef = useRef(null); const inputRef = useRef(null);
@ -107,12 +107,13 @@ export const DateRangePicker1 = ({
field: { ref }, field: { ref },
} = useController({ name: startField, control }); } = useController({ name: startField, control });
// Apply default range
const applyDefaultDates = () => { const applyDefaultDates = () => {
const today = new Date(); const today = new Date();
const past = new Date(); const past = new Date(today.getTime());
past.setDate(today.getDate() - 6); past.setDate(today.getDate() - howManyDay);
const format = (d) => flatpickr.formatDate(d, "d-m-Y"); const format = (d) => window.flatpickr.formatDate(d, "d-m-Y");
const formattedStart = format(past); const formattedStart = format(past);
const formattedEnd = format(today); const formattedEnd = format(today);
@ -127,15 +128,19 @@ export const DateRangePicker1 = ({
useEffect(() => { useEffect(() => {
if (!inputRef.current || inputRef.current._flatpickr) return; if (!inputRef.current || inputRef.current._flatpickr) return;
const instance = flatpickr(inputRef.current, { if (defaultRange && !getValues(startField) && !getValues(endField)) {
applyDefaultDates();
}
const instance = window.flatpickr(inputRef.current, {
mode: "range", mode: "range",
dateFormat: "d-m-Y", dateFormat: "d-m-Y",
allowInput: allowText, allowInput: allowText,
maxDate , maxDate,
onChange: (selectedDates) => { onChange: (selectedDates) => {
if (selectedDates.length === 2) { if (selectedDates.length === 2) {
const [start, end] = selectedDates; const [start, end] = selectedDates;
const format = (d) => flatpickr.formatDate(d, "d-m-Y"); const format = (d) => window.flatpickr.formatDate(d, "d-m-Y");
setValue(startField, format(start), { shouldValidate: true }); setValue(startField, format(start), { shouldValidate: true });
setValue(endField, format(end), { shouldValidate: true }); setValue(endField, format(end), { shouldValidate: true });
} else { } else {
@ -148,12 +153,10 @@ export const DateRangePicker1 = ({
const currentStart = getValues(startField); const currentStart = getValues(startField);
const currentEnd = getValues(endField); const currentEnd = getValues(endField);
if (defaultRange && !currentStart && !currentEnd) { if (currentStart && currentEnd) {
applyDefaultDates();
} else if (currentStart && currentEnd) {
instance.setDate([ instance.setDate([
flatpickr.parseDate(currentStart, "d-m-Y"), window.flatpickr.parseDate(currentStart, "d-m-Y"),
flatpickr.parseDate(currentEnd, "d-m-Y"), window.flatpickr.parseDate(currentEnd, "d-m-Y"),
]); ]);
} }
@ -161,20 +164,19 @@ export const DateRangePicker1 = ({
}, []); }, []);
useEffect(() => { useEffect(() => {
if (resetSignal !== undefined) { if (resetSignal !== undefined) {
if (defaultRange) { if (defaultRange) {
applyDefaultDates(); applyDefaultDates();
} else { } else {
setValue(startField, "", { shouldValidate: true }); setValue(startField, "", { shouldValidate: true });
setValue(endField, "", { shouldValidate: true }); setValue(endField, "", { shouldValidate: true });
if (inputRef.current?._flatpickr) { if (inputRef.current?._flatpickr) {
inputRef.current._flatpickr.clear(); inputRef.current._flatpickr.clear();
}
} }
} }
} }, [resetSignal, defaultRange, setValue, startField, endField]);
}, [resetSignal, defaultRange, setValue, startField, endField]);
const start = getValues(startField); const start = getValues(startField);
const end = getValues(endField); const end = getValues(endField);
@ -186,7 +188,7 @@ export const DateRangePicker1 = ({
type="text" type="text"
className="form-control form-control-sm" className="form-control form-control-sm"
placeholder={placeholder} placeholder={placeholder}
defaultValue={formattedValue} value={formattedValue}
ref={(el) => { ref={(el) => {
inputRef.current = el; inputRef.current = el;
ref(el); ref(el);

View File

@ -37,13 +37,13 @@ const GalleryFilterPanel = ({ onApply }) => {
startDate: localToUtc(formData.startDate), startDate: localToUtc(formData.startDate),
endDate: localToUtc(formData.endDate), endDate: localToUtc(formData.endDate),
}); });
closePanel() // closePanel()
}; };
const onClear=()=>{ const onClear=()=>{
reset(defaultGalleryFilterValue); reset(defaultGalleryFilterValue);
setResetKey((prev) => prev + 1); setResetKey((prev) => prev + 1);
closePanel() // closePanel()
} }
if (isLoading) return <div>Loading....</div>; if (isLoading) return <div>Loading....</div>;

View File

@ -28,13 +28,21 @@ const ImageGalleryListView = ({filter}) => {
} }
}; };
if (!data?.data?.length && !isLoading) { if (!data?.data?.length && !isLoading) {
return ( return (
<p className="text-center text-muted mt-5"> <div
{selectedProject ? " No images match the selected filters.":"Please Select Project!"} className="d-flex justify-content-center align-items-center text-muted"
</p> style={{ minHeight: "50vh" }}
); >
} <span style={{ fontSize: "0.9rem" }}>
{selectedProject
? "No images match the selected filters."
: "Please Select Project!"}
</span>
</div>
);
}
if (isLoading) { if (isLoading) {
return ( return (

View File

@ -4,7 +4,6 @@ import { formatUTCToLocalTime } from "../../utils/dateUtils";
const ViewGallery = ({ batch, index }) => { const ViewGallery = ({ batch, index }) => {
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [currentIndex, setCurrentIndex] = useState(index); const [currentIndex, setCurrentIndex] = useState(index);
console.log(batch);
useEffect(() => { useEffect(() => {
setCurrentIndex(index); setCurrentIndex(index);
}, [index, batch]); }, [index, batch]);

View File

@ -16,10 +16,10 @@ import ManageDocumentCategory from "./ManageDocumentCategory";
import ManageDocumentType from "./ManageDocumentType"; import ManageDocumentType from "./ManageDocumentType";
import ManageServices from "./Services/ManageServices"; import ManageServices from "./Services/ManageServices";
import ServiceGroups from "./Services/ServicesGroups"; import ServiceGroups from "./Services/ServicesGroups";
import ManagePaymentHead from "./paymentAdjustmentHead/ManagePaymentHead";
const MasterModal = ({ modaldata, closeModal }) => { const MasterModal = ({ modaldata, closeModal }) => {
if (!modaldata?.modalType || modaldata.modalType === "delete") { if (!modaldata?.modalType || modaldata.modalType === "delete") {
return null; return null;
} }
@ -33,7 +33,7 @@ const MasterModal = ({ modaldata, closeModal }) => {
<EditRole master={modaldata} onClose={closeModal} /> <EditRole master={modaldata} onClose={closeModal} />
), ),
"Job Role": <CreateJobRole onClose={closeModal} />, "Job Role": <CreateJobRole onClose={closeModal} />,
"Edit-Job Role": <EditJobRole data={item} onClose={closeModal} />, "Edit-Job Role": <EditJobRole data={item} onClose={closeModal} />,
"Work Category": <CreateWorkCategory onClose={closeModal} />, "Work Category": <CreateWorkCategory onClose={closeModal} />,
"Edit-Work Category": <EditWorkCategory data={item} onClose={closeModal} />, "Edit-Work Category": <EditWorkCategory data={item} onClose={closeModal} />,
"Contact Category": <CreateCategory data={item} onClose={closeModal} />, "Contact Category": <CreateCategory data={item} onClose={closeModal} />,
@ -58,24 +58,20 @@ const MasterModal = ({ modaldata, closeModal }) => {
"Edit-Document Type": ( "Edit-Document Type": (
<ManageDocumentType data={item} onClose={closeModal} /> <ManageDocumentType data={item} onClose={closeModal} />
), ),
"Services": ( Services: <ManageServices onClose={closeModal} />,
<ManageServices onClose={closeModal} /> "Edit-Services": <ManageServices data={item} onClose={closeModal} />,
), "Manage-Services": <ServiceGroups service={item} onClose={closeModal} />,
"Edit-Services": ( "Payment Adjustment Head": <ManagePaymentHead onClose={closeModal} />,
<ManageServices data={item} onClose={closeModal} /> "Edit-Payment Adjustment Head": <ManagePaymentHead data={item} onClose={closeModal} />
),
"Manage-Services": (
<ServiceGroups service={item} onClose={closeModal}/>
),
}; };
return ( return (
<div className="p-2 p-md-1"> <div className="p-2 p-md-1">
<div className="text-center"> <div className="text-center">
<p className="fs-5 fw-semibold" >{`${masterType, " ", modalType}`}</p> <p className="fs-5 fw-semibold">{`${(masterType, " ", modalType)}`}</p>
</div>
{modalComponents[modalType] || null}
</div> </div>
{ modalComponents[modalType] || null}
</div>
); );
}; };

View File

@ -0,0 +1,107 @@
import React, { useEffect } from "react";
import { z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import Label from "../../common/Label";
import { useCreatePaymentAjustmentHead, useUpdatePaymentAjustmentHead } from "../../../hooks/masterHook/useMaster";
export const simpleFormSchema = z.object({
name: z.string().min(1, "Name is required"),
description: z.string().min(1, "Description is required"),
});
const ManagePaymentHead = ({ data, onClose }) => {
const {
register,
handleSubmit,
reset,
formState: { errors },
} = useForm({
resolver: zodResolver(simpleFormSchema),
defaultValues: {
name: "",
description: "",
},
});
const {mutate:CreateAjustmentHead,isPending} = useCreatePaymentAjustmentHead(()=>{
handleClose?.()
});
const {mutate:UpdateAjustmentHead,isPending:isUpdating} = useUpdatePaymentAjustmentHead(()=>{
handleClose?.()
})
const onSubmit = (formData) => {
if(data){
let id = data?.id;
const payload = {
...formData,
id:id,
}
UpdateAjustmentHead({id:id,payload:payload})
}else{
let payload={
...formData
}
CreateAjustmentHead(payload)
}
};
useEffect(() => {
if (data) {
reset({
name: data.name,
description: data.description,
});
}
}, [data]);
const handleClose = () => {
reset();
onClose();
};
return (
<div className="row text-start">
<form onSubmit={handleSubmit(onSubmit)} className="p-4">
<div className="mb-3">
<Label htmlFor="name" required>
Name
</Label>
<input
type="text"
{...register("name")}
className={`form-control ${errors.name ? "is-invalid" : ""}`}
/>
{errors.name && (
<div className="invalid-feedback">{errors.name.message}</div>
)}
</div>
<div className="mb-3">
<Label htmlFor="description" required>
Description
</Label>
<textarea
{...register("description")}
className={`form-control ${errors.description ? "is-invalid" : ""}`}
/>
{errors.description && (
<div className="invalid-feedback">{errors.description.message}</div>
)}
</div>
<div className="d-flex flex-row justify-content-end gap-2">
<button
className="btn btn-sm btn-label-secondary"
onClick={handleClose} disabled={isUpdating || isPending}
>
Cancel
</button>
<button type="submit" className="btn btn-sm btn-primary" disabled={isUpdating || isPending}>
{isPending || isUpdating ? "Please Wait" :data ? "Update":"Submit"}
</button>
</div>
</form>
</div>
);
};
export default ManagePaymentHead;

View File

@ -10,6 +10,14 @@ import {
} from "@tanstack/react-query"; } from "@tanstack/react-query";
import showToast from "../../services/toastService"; import showToast from "../../services/toastService";
export const usePaymentAjustmentHead = (isActive) => {
return useQuery({
queryKey: ["paymentType",isActive],
queryFn: async () => await MasterRespository.getPaymentAdjustmentHead(isActive),
});
};
export const useServices = () => { export const useServices = () => {
return useQuery({ return useQuery({
queryKey: ["services"], queryKey: ["services"],
@ -28,9 +36,8 @@ export const useActivitiesByGroups = (groupId) => {
return useQuery({ return useQuery({
queryKey: ["activties", groupId], queryKey: ["activties", groupId],
queryFn: async () => await MasterRespository.getActivitesByGroup(groupId), queryFn: async () => await MasterRespository.getActivitesByGroup(groupId),
enabled: !!groupId, enabled: !!groupId,
}); });
}; };
export const useGlobalServices = () => { export const useGlobalServices = () => {
@ -296,6 +303,8 @@ const fetchMasterData = async (masterType) => {
return (await MasterRespository.getDocumentTypes()).data; return (await MasterRespository.getDocumentTypes()).data;
case "Document Category": case "Document Category":
return (await MasterRespository.getDocumentCategories()).data; return (await MasterRespository.getDocumentCategories()).data;
case "Payment Adjustment Head":
return (await MasterRespository.getPaymentAdjustmentHead(true)).data;
case "Status": case "Status":
return [ return [
{ {
@ -448,8 +457,6 @@ export const useUpdateApplicationRole = (onSuccessCallback) => {
}); });
}; };
//-----Create work Category------------------------------- //-----Create work Category-------------------------------
export const useCreateWorkCategory = (onSuccessCallback) => { export const useCreateWorkCategory = (onSuccessCallback) => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
@ -703,13 +710,11 @@ export const useCreateService = (onSuccessCallback) => {
return useMutation({ return useMutation({
mutationFn: async (payload) => { mutationFn: async (payload) => {
const resp = await MasterRespository.createService(payload); const resp = await MasterRespository.createService(payload);
return resp.data; return resp.data;
}, },
onSuccess: (data) => { onSuccess: (data) => {
queryClient.invalidateQueries({ queryKey: ["masterData", "Services"] }); queryClient.invalidateQueries({ queryKey: ["masterData", "Services"] });
showToast(data?.message || "Service added successfully", "success"); showToast(data?.message || "Service added successfully", "success");
@ -717,8 +722,12 @@ export const useCreateService = (onSuccessCallback) => {
if (onSuccessCallback) onSuccessCallback(data?.data); if (onSuccessCallback) onSuccessCallback(data?.data);
}, },
onError: (error) => { onError: (error) => {
showToast(
showToast( error?.response?.data?.message || error?.message || "Something went wrong", "error"); error?.response?.data?.message ||
error?.message ||
"Something went wrong",
"error"
);
}, },
}); });
}; };
@ -741,7 +750,12 @@ export const useUpdateService = (onSuccessCallback) => {
if (onSuccessCallback) onSuccessCallback(data); if (onSuccessCallback) onSuccessCallback(data);
}, },
onError: (error) => { onError: (error) => {
showToast(error?.response?.data?.message || error?.message || "Something went wrong", "error"); showToast(
error?.response?.data?.message ||
error?.message ||
"Something went wrong",
"error"
);
}, },
}); });
}; };
@ -759,15 +773,22 @@ export const useCreateActivityGroup = (onSuccessCallback) => {
queryKey: ["groups"], queryKey: ["groups"],
}); });
showToast( data?.message || showToast(
data?.response?.data?.message || "Activity Group created successfully.", data?.message ||
data?.response?.data?.message ||
"Activity Group created successfully.",
"success" "success"
); );
if (onSuccessCallback) onSuccessCallback(data); if (onSuccessCallback) onSuccessCallback(data);
}, },
onError: (error) => { onError: (error) => {
showToast(error?.response?.data?.message || error?.message || "Something went wrong", "error"); showToast(
error?.response?.data?.message ||
error?.message ||
"Something went wrong",
"error"
);
}, },
}); });
}; };
@ -775,8 +796,8 @@ export const useUpdateActivityGroup = (onSuccessCallback) => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: async ({id,payload}) => { mutationFn: async ({ id, payload }) => {
const response = await MasterRespository.updateActivityGrop(id,payload); const response = await MasterRespository.updateActivityGrop(id, payload);
return response; return response;
}, },
onSuccess: (data, variables) => { onSuccess: (data, variables) => {
@ -786,7 +807,8 @@ export const useUpdateActivityGroup = (onSuccessCallback) => {
showToast( showToast(
data?.message || data?.message ||
data?.response?.data?.message|| "Activity Group Updated successfully.", data?.response?.data?.message ||
"Activity Group Updated successfully.",
"success" "success"
); );
@ -812,7 +834,12 @@ export const useCreateActivity = (onSuccessCallback) => {
if (onSuccessCallback) onSuccessCallback(data); if (onSuccessCallback) onSuccessCallback(data);
}, },
onError: (error) => { onError: (error) => {
showToast(error?.response?.data?.message || error?.message || "Something went wrong", "error"); showToast(
error?.response?.data?.message ||
error?.message ||
"Something went wrong",
"error"
);
}, },
}); });
}; };
@ -834,7 +861,12 @@ export const useUpdateActivity = (onSuccessCallback) => {
if (onSuccessCallback) onSuccessCallback(data); if (onSuccessCallback) onSuccessCallback(data);
}, },
onError: (error) => { onError: (error) => {
showToast(error?.response?.data?.message || error?.message || "Something went wrong", "error"); showToast(
error?.response?.data?.message ||
error?.message ||
"Something went wrong",
"error"
);
}, },
}); });
}; };
@ -968,7 +1000,52 @@ export const useUpdateDocumentType = (onSuccessCallback) => {
}, },
}); });
}; };
// -Delete Master -------- // ------------------------------x-x--------x-x------------------------------------
// ==============================Payment Adjustment Head =============================
export const useCreatePaymentAjustmentHead = (onSuccessCallback) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (payload) => {
const resp = await MasterRespository.createPaymentAjustmentHead(payload);
return resp.data;
},
onSuccess: (data) => {
queryClient.invalidateQueries({
queryKey: ["masterData", "Payment Adjustment Head"],
});
showToast("Payment Ajustment Head successfully", "success");
if (onSuccessCallback) onSuccessCallback(data);
},
onError: (error) => {
showToast(error.message || "Something went wrong", "error");
},
});
};
export const useUpdatePaymentAjustmentHead = (onSuccessCallback) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({ id, payload }) => {
const resp = await MasterRespository.updatePaymentAjustmentHead(id, payload);
return resp.data;
},
onSuccess: (data) => {
queryClient.invalidateQueries({
queryKey: ["masterData", "Payment Adjustment Head"],
});
showToast("Payment Ajustment Head Updated successfully", "success");
if (onSuccessCallback) onSuccessCallback(data);
},
onError: (error) => {
showToast(error.message || "Something went wrong", "error");
},
});
};
// ====================x=x====================x=x==================================
// --------Delete Master --------
export const useDeleteMasterItem = () => { export const useDeleteMasterItem = () => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
@ -1001,14 +1078,12 @@ export const useDeleteMasterItem = () => {
}); });
}; };
export const useDeleteServiceGroup = () => {
export const useDeleteServiceGroup =()=>{ const queryClient = useQueryClient();
const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: async (id)=>await MasterRespository.deleteActivityGroup(id), mutationFn: async (id) => await MasterRespository.deleteActivityGroup(id),
onSuccess: ({_,variable}) => { onSuccess: ({ _, variable }) => {
queryClient.invalidateQueries({ queryKey: ["groups"] }); queryClient.invalidateQueries({ queryKey: ["groups"] });
showToast(`Group deleted successfully.`, "success"); showToast(`Group deleted successfully.`, "success");
@ -1022,15 +1097,13 @@ export const useDeleteServiceGroup =()=>{
showToast(message, "error"); showToast(message, "error");
}, },
}); });
} };
export const useDeleteActivity =()=>{ export const useDeleteActivity = () => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
return useMutation({ return useMutation({
mutationFn: async (id)=>await MasterRespository.deleteActivity(id), mutationFn: async (id) => await MasterRespository.deleteActivity(id),
onSuccess: ({_,variable}) => { onSuccess: ({ _, variable }) => {
queryClient.invalidateQueries({ queryKey: ["activties"] }); queryClient.invalidateQueries({ queryKey: ["activties"] });
showToast(`Acivity deleted successfully.`, "success"); showToast(`Acivity deleted successfully.`, "success");
@ -1044,4 +1117,4 @@ export const useDeleteActivity =()=>{
showToast(message, "error"); showToast(message, "error");
}, },
}); });
} };

View File

@ -32,6 +32,15 @@ export const useModal = (modalType) => {
return { isOpen, onOpen, onClose, onToggle }; return { isOpen, onOpen, onClose, onToggle };
}; };
export const useSubscription = (frequency) => {
return useQuery({
queryKey: ["subscriptionPlans", frequency],
queryFn: async () => {
const resp = await AuthRepository.getSubscription(frequency);
return resp.data;
},
});
};
// -------------------APIHook------------------------------------- // -------------------APIHook-------------------------------------
@ -85,8 +94,8 @@ export const useAuthModal = () => {
export const useLogout = () => { export const useLogout = () => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const naviget = useNavigate() const naviget = useNavigate();
const dispatch = useDispatch() const dispatch = useDispatch();
return useMutation({ return useMutation({
mutationFn: async () => { mutationFn: async () => {
@ -99,12 +108,12 @@ export const useLogout = () => {
}, },
onSuccess: (data) => { onSuccess: (data) => {
queryClient.clear() queryClient.clear();
removeSession(); removeSession();
dispatch(cacheProfileData(null)) dispatch(cacheProfileData(null));
// window.location.href = "/auth/login"; // window.location.href = "/auth/login";
naviget("/auth/login",{replace:true}) naviget("/auth/login", { replace: true });
if (onSuccessCallBack) onSuccessCallBack(); if (onSuccessCallBack) onSuccessCallBack();
}, },

View File

@ -0,0 +1,152 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { CollectionRepository } from "../repositories/ColllectionRepository";
import showToast from "../services/toastService";
export const useCollections = (
pageSize,
pageNumber,
fromDate,
toDate,
isPending,
isActive,
projectId,
searchString
) => {
return useQuery({
queryKey: [
"collections",
pageSize,
pageNumber,
fromDate,
toDate,
isPending,
isActive,
projectId,
searchString,
],
queryFn: async () => {
const response = await CollectionRepository.getCollections(
pageSize,
pageNumber,
fromDate,
toDate,
isPending,
isActive,
projectId,
searchString
);
return response.data;
},
keepPreviousData: true,
staleTime: 1000 * 60 * 1,
});
};
export const useCollection =(collectionId)=>{
return useQuery({
queryKey:["collection",collectionId],
queryFn:async()=> {
const resp = await CollectionRepository.getCollection(collectionId);
return resp.data
},
enabled:!!collectionId
})
}
// =========================Mutation======================
export const useCreateCollection = (onSuccessCallBack) => {
const clinent = useQueryClient();
return useMutation({
mutationFn: async (payload) =>
await CollectionRepository.createNewCollection(payload),
onSuccess: (_, variables) => {
showToast("New Collection created Successfully", "success");
clinent.invalidateQueries({ queryKey: ["collections"] });
if (onSuccessCallBack) onSuccessCallBack();
},
onError: (error) => {
showToast(
error.response.data.message || error.message || "Something Went wrong"
);
},
});
};
export const useMarkedPaymentReceived = (onSuccessCallBack) => {
const client = useQueryClient();
return useMutation({
mutationFn: async (payload) =>
await CollectionRepository.markPaymentReceived(payload),
onSuccess: async () => {
client.invalidateQueries({ queryKey: ["collections"] });
showToast("Payment Received marked Successfully", "success");
if (onSuccessCallBack) onSuccessCallBack();
},
onError: (error) => {
showToast(
error.response.data.message || error.message || "Something Went wrong"
);
},
});
};
export const useAddPayment = (onSuccessCallBack) => {
const client = useQueryClient();
return useMutation({
mutationFn: (payload) => CollectionRepository.makeReceivePayment(payload),
onSuccess: () => {
client.invalidateQueries({ queryKey: ["collections"] });
client.invalidateQueries({ queryKey: ["collection"] });
showToast("Payment Received marked Successfully", "success");
if (onSuccessCallBack) onSuccessCallBack();
},
onError: (error) => {
showToast(
error?.response?.data?.message || error.message || "Something Went wrong"
);
},
});
};
export const useAddComment = (onSuccessCallBack) => {
const client = useQueryClient();
return useMutation({
mutationFn: (payload) => CollectionRepository.addComment(payload),
onSuccess: () => {
client.invalidateQueries({ queryKey: ["collections"] });
client.invalidateQueries({ queryKey: ["collection"] });
showToast("Comment Successfully", "success");
if (onSuccessCallBack) onSuccessCallBack();
},
onError: (error) => {
showToast(
error?.response?.data?.message || error.message || "Something Went wrong"
);
},
});
};
export const useUpdateCollection =(onSuccessCallBack)=>{
const client = useQueryClient();
return useMutation({
mutationFn:async({collectionId,payload})=> await CollectionRepository.updateCollection(collectionId,payload),
onSuccess: () => {
client.invalidateQueries({ queryKey: ["collections"] });
client.invalidateQueries({ queryKey: ["collection"] });
showToast("Collection Updated Successfully", "success");
if (onSuccessCallBack) onSuccessCallBack();
},
onError: (error) => {
showToast(
error?.response?.data?.message || error.message || "Something Went wrong"
);
},
})
}

View File

@ -200,35 +200,35 @@ export const useAttendanceOverviewData = (projectId, days) => {
// }) // })
// } // }
export const useDashboard_AttendanceData = (date,projectId)=>{ export const useDashboard_AttendanceData = (date, projectId) => {
return useQuery({ return useQuery({
queryKey:["dashboardAttendances",date,projectId], queryKey: ["dashboardAttendances", date, projectId],
queryFn:async()=> { queryFn: async () => {
const resp = await await GlobalRepository.getDashboardAttendanceData(date, projectId) const resp = await await GlobalRepository.getDashboardAttendanceData(date, projectId)
return resp.data; return resp.data;
} }
}) })
} }
export const useDashboardTeamsCardData =(projectId)=>{ export const useDashboardTeamsCardData = (projectId) => {
return useQuery({ return useQuery({
queryKey:["dashboardTeams",projectId], queryKey: ["dashboardTeams", projectId],
queryFn:async()=> { queryFn: async () => {
const resp = await GlobalRepository.getDashboardTeamsCardData(projectId) const resp = await GlobalRepository.getDashboardTeamsCardData(projectId)
return resp.data; return resp.data;
} }
}) })
} }
export const useDashboardTasksCardData = (projectId) => { export const useDashboardTasksCardData = (projectId) => {
return useQuery({ return useQuery({
queryKey:["dashboardTasks",projectId], queryKey: ["dashboardTasks", projectId],
queryFn:async()=> { queryFn: async () => {
const resp = await GlobalRepository.getDashboardTasksCardData(projectId) const resp = await GlobalRepository.getDashboardTasksCardData(projectId)
return resp.data; return resp.data;
} }
}) })
} }
@ -236,7 +236,7 @@ export const useDashboardTasksCardData = (projectId) => {
// return useQuery({ // return useQuery({
// queryKey:["dashboardAttendanceOverView",projectId], // queryKey:["dashboardAttendanceOverView",projectId],
// queryFn:async()=> { // queryFn:async()=> {
// const resp = await GlobalRepository.getAttendanceOverview(projectId, days); // const resp = await GlobalRepository.getAttendanceOverview(projectId, days);
// return resp.data; // return resp.data;
// } // }
@ -244,12 +244,53 @@ export const useDashboardTasksCardData = (projectId) => {
// } // }
export const useDashboardProjectsCardData = () => { export const useDashboardProjectsCardData = () => {
return useQuery({ return useQuery({
queryKey:["dashboardProjects"], queryKey: ["dashboardProjects"],
queryFn:async()=> { queryFn: async () => {
const resp = await GlobalRepository.getDashboardProjectsCardData(); const resp = await GlobalRepository.getDashboardProjectsCardData();
return resp.data; return resp.data;
} }
}) })
} }
export const useExpenseAnalysis = (projectId, startDate, endDate) => {
const hasBothDates = !!startDate && !!endDate;
const noDatesSelected = !startDate && !endDate;
const shouldFetch =
noDatesSelected ||
hasBothDates;
return useQuery({
queryKey: ["expenseAnalysis", projectId, startDate, endDate],
queryFn: async () => {
const resp = await GlobalRepository.getExpenseData(projectId, startDate, endDate);
return resp.data;
},
enabled: shouldFetch,
refetchOnWindowFocus: true, // refetch when you come back
refetchOnMount: "always", // always refetch on remount
staleTime: 0,
});
};
export const useExpenseStatus = (projectId) => {
return useQuery({
queryKey: ["expense_stauts", projectId],
queryFn: async () => {
const resp = await GlobalRepository.getExpenseStatus(projectId);
return resp.data;
}
})
}
export const useExpenseDataByProject = (projectId, categoryId, months) => {
return useQuery({
queryKey: ["expenseByProject", projectId, categoryId, months],
queryFn: async () => {
const resp = await GlobalRepository.getExpenseDataByProject(projectId, categoryId, months);
return resp.data;
},
});
};

View File

@ -153,7 +153,7 @@ export const useProjectsAllocationByEmployee = (employeeId) => {
return { projectList, loading: isLoading, error, refetch }; return { projectList, loading: isLoading, error, refetch };
}; };
export const useProjectName = () => { export const useProjectName = (provideAll=false) => {
const { const {
data = [], data = [],
isLoading, isLoading,
@ -161,9 +161,9 @@ export const useProjectName = () => {
refetch, refetch,
isError, isError,
} = useQuery({ } = useQuery({
queryKey: ["basicProjectNameList"], queryKey: ["basicProjectNameList",provideAll],
queryFn: async () => { queryFn: async () => {
const res = await ProjectRepository.projectNameList(); const res = await ProjectRepository.projectNameList(provideAll);
return res.data || res; return res.data || res;
}, },
onError: (error) => { onError: (error) => {

View File

@ -179,44 +179,40 @@ const AttendancePage = () => {
</div> </div>
{/* Search + Organization filter */} {/* Search + Organization filter */}
<div className="col-12 col-md-auto mt-2 mt-md-0 ms-md-auto d-flex gap-2 align-items-center"> <div className="col-12 col-md-auto mt-2 mt-md-0 ms-md-auto">
{/* Organization Dropdown */} <div className="row g-2">
<div className="row"> <div className="col-12 col-sm-6">
<div className="col-12 col-sm-6 mb-2 mb-sm-0"> <select
<select className="form-select form-select-sm"
className="form-select form-select-sm" value={appliedFilters.selectedOrganization}
value={appliedFilters.selectedOrganization} onChange={(e) =>
onChange={(e) => setAppliedFilters((prev) => ({
setAppliedFilters((prev) => ({ ...prev,
...prev, selectedOrganization: e.target.value,
selectedOrganization: e.target.value, }))
})) }
} disabled={orgLoading}
disabled={orgLoading} >
> <option value="">All Organizations</option>
<option value="">All Organizations</option> {organizations?.map((org, ind) => (
{organizations?.map((org, ind) => ( <option key={`${org.id}-${ind}`} value={org.id}>
<option key={`${org.id}-${ind}`} value={org.id}> {org.name}
{org.name} </option>
</option> ))}
))} </select>
</select>
</div> </div>
<div className="col-12 col-sm-6"> <div className="col-12 col-sm-6">
{/* Search Input */} <input
<input type="text"
type="text" className="form-control form-control-sm"
className="form-control form-control-sm" placeholder="Search Employee..."
placeholder="Search Employee..." value={searchTerm}
value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)}
onChange={(e) => setSearchTerm(e.target.value)} />
/>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
@ -224,7 +220,7 @@ const AttendancePage = () => {
{selectedProject ? ( {selectedProject ? (
<> <>
{activeTab === "all" && ( {activeTab === "all" && (
<div className="tab-pane fade show active py-0 mx-5"> <div className="tab-pane fade show active py-0 mx-2">
<Attendance <Attendance
handleModalData={handleModalData} handleModalData={handleModalData}
getRole={getRole} getRole={getRole}
@ -234,7 +230,7 @@ const AttendancePage = () => {
</div> </div>
)} )}
{activeTab === "logs" && ( {activeTab === "logs" && (
<div className="tab-pane fade show active py-0"> <div className="tab-pane fade p-3 show active py-0">
<AttendanceLog <AttendanceLog
handleModalData={handleModalData} handleModalData={handleModalData}
searchTerm={searchTerm} searchTerm={searchTerm}
@ -243,7 +239,7 @@ const AttendancePage = () => {
</div> </div>
)} )}
{activeTab === "regularization" && DoRegularized && ( {activeTab === "regularization" && DoRegularized && (
<div className="tab-pane fade show active py-0"> <div className="tab-pane fade p-3 show active py-0">
<Regularization <Regularization
searchTerm={searchTerm} searchTerm={searchTerm}
organizationId={appliedFilters.selectedOrganization} organizationId={appliedFilters.selectedOrganization}

View File

@ -38,7 +38,7 @@ const TaskPlanning = () => {
]} ]}
/> />
<div className="card py-2 "> <div className="card py-2 page-min-h">
<div className="col-sm-4 col-md-3 col-12 px-4 py-2 text-start"> <div className="col-sm-4 col-md-3 col-12 px-4 py-2 text-start">
{data?.length === 0 ? ( {data?.length === 0 ? (
<p className="badge bg-label-secondary m-0">Service not assigned</p> <p className="badge bg-label-secondary m-0">Service not assigned</p>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -206,8 +206,8 @@ const LandingPage = () => {
navigation={false} navigation={false}
modules={[EffectFlip, Autoplay, Pagination, Navigation]} modules={[EffectFlip, Autoplay, Pagination, Navigation]}
className="mySwiper" className="mySwiper"
onSlideChange={() => console.log("slide change")} onSlideChange={() => {}}
onSwiper={(swiper) => console.log(swiper)} onSwiper={(swiper) => {}}
> >
<SwiperSlide> <SwiperSlide>
<SwaperSlideContent <SwaperSlideContent

View File

@ -2,37 +2,28 @@ import React, { useState, useEffect } from "react";
import axios from "axios"; import axios from "axios";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import PlanCardSkeleton from "./PlanCardSkeleton"; import PlanCardSkeleton from "./PlanCardSkeleton";
import { useSubscription } from "../../hooks/useAuth";
const SubscriptionPlans = () => { const SubscriptionPlans = () => {
const [plans, setPlans] = useState([]); const [plans, setPlans] = useState([]);
const [frequency, setFrequency] = useState(1); const [frequency, setFrequency] = useState(1);
const { data, isLoading, isError, error } = useSubscription(frequency);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
useEffect(() => {
const fetchPlans = async () => {
try {
setLoading(true);
const res = await axios.get(
`http://localhost:5032/api/market/list/subscription-plan?frequency=${frequency}`,
{ headers: { "Content-Type": "application/json" } }
);
setPlans(res.data?.data || []);
} catch (err) {
console.error("Error fetching plans:", err);
} finally {
setLoading(false);
}
};
fetchPlans();
}, [frequency]);
const frequencyLabel = (freq) => { const frequencyLabel = (freq) => {
switch (freq) { switch (freq) {
case 0: return "1 mo"; case 0:
case 1: return "3 mo"; return "1 mo";
case 2: return "6 mo"; case 1:
case 3: return "1 yr"; return "3 mo";
default: return "mo"; case 2:
return "6 mo";
case 3:
return "1 yr";
default:
return "mo";
} }
}; };
@ -41,38 +32,49 @@ const SubscriptionPlans = () => {
{/* Frequency Switcher */} {/* Frequency Switcher */}
<div className="text-center mb-4"> <div className="text-center mb-4">
<div className="btn-group" role="group" aria-label="Plan frequency"> <div className="btn-group" role="group" aria-label="Plan frequency">
{["Monthly", "Quarterly", "Half-Yearly", "Yearly"].map((label, idx) => ( {["Monthly", "Quarterly", "Half-Yearly", "Yearly"].map(
<button (label, idx) => (
key={idx} <button
type="button" key={idx}
className={`btn btn-${frequency === idx ? "primary" : "outline-secondary"}`} type="button"
onClick={() => setFrequency(idx)} className={`btn btn-${
> frequency === idx ? "primary" : "outline-secondary"
{label} }`}
</button> onClick={() => setFrequency(idx)}
))} >
{label}
</button>
)
)}
</div> </div>
</div> </div>
{/* Cards */} {/* Cards */}
<div className="row g-4 mt-10"> <div className="row g-4 mt-10">
{loading ? ( {isLoading ? (
// Show 3 skeletons // Show 3 skeletons
<> <>
<PlanCardSkeleton /> <PlanCardSkeleton />
<PlanCardSkeleton /> <PlanCardSkeleton />
<PlanCardSkeleton /> <PlanCardSkeleton />
</> </>
) : plans.length === 0 ? ( ) : data.length === 0 ? (
<div className="text-center">No plans found</div> <div className="text-center">No plans found</div>
) : isError ? (
<div className="text-start bg-light">
<p>{error.message}</p>
<p>{error.name}</p>
</div>
) : ( ) : (
plans.map((plan) => ( data.map((plan) => (
<div key={plan.id} className="col-xl-4 col-lg-6 col-md-6"> <div key={plan.id} className="col-xl-4 col-lg-6 col-md-6">
<div className="card h-100 shadow-lg border-0 p-3 text-center p-10"> <div className="card h-100 shadow-lg border-0 p-3 text-center p-10">
{/* Header */} {/* Header */}
<div className="mb-3"> <div className="mb-3">
<i className="bx bxs-package text-primary fs-1 mb-2"></i> <i className="bx bxs-package text-primary fs-1 mb-2"></i>
<p className="card-title fs-3 fw-bold mb-1">{plan.planName}</p> <p className="card-title fs-3 fw-bold mb-1">
{plan.planName}
</p>
<p className="text-muted mb-0 fs-5">{plan.description}</p> <p className="text-muted mb-0 fs-5">{plan.description}</p>
</div> </div>
@ -80,7 +82,9 @@ const SubscriptionPlans = () => {
<div className="mb-3"> <div className="mb-3">
<h4 className="fw-semibold mt-auto mb-0 fs-3"> <h4 className="fw-semibold mt-auto mb-0 fs-3">
{plan.currency?.symbol} {plan.price} {plan.currency?.symbol} {plan.price}
<small className="text-muted ms-1">/ {frequencyLabel(frequency)}</small> <small className="text-muted ms-1">
/ {frequencyLabel(frequency)}
</small>
</h4> </h4>
</div> </div>
@ -133,7 +137,6 @@ const SubscriptionPlans = () => {
)) ))
)} )}
</div> </div>
</div> </div>
); );
}; };

View File

@ -13,7 +13,7 @@ const OrganizationPage = () => {
<Breadcrumb <Breadcrumb
data={[{ label: "Home", link: "/" }, { label: "Organizations" }]} data={[{ label: "Home", link: "/" }, { label: "Organizations" }]}
/> />
<div className="card my-3 px-sm-2 px-0"> <div className="card my-3 px-sm-4 px-0">
<div className="card-body py-2 px-3"> <div className="card-body py-2 px-3">
<div className="row align-items-center"> <div className="row align-items-center">
<div className="col-6 d-flex "> <div className="col-6 d-flex ">
@ -42,9 +42,13 @@ const OrganizationPage = () => {
</button> </button>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<OrganizationsList searchText={searchText} /> <div className="card page-min-h px-sm-4">
<OrganizationsList searchText={searchText} />
</div>
</div> </div>
); );

View File

@ -121,7 +121,7 @@ const TenantPage = () => {
{ label: "Tenant", link: null }, { label: "Tenant", link: null },
]} ]}
/> />
<div className="card text-center my-4 p-5 pb-10"> <div className="card text-center my-4 p-md-5 px-1 py-3 pb-10">
{/* Super Tenant Actions */} {/* Super Tenant Actions */}
{isSuperTenant && ( {isSuperTenant && (
<div className="p-0"> <div className="p-0">

View File

@ -8,35 +8,43 @@ const TenantSelectionPage = () => {
const [pendingTenant, setPendingTenant] = useState(null); const [pendingTenant, setPendingTenant] = useState(null);
const navigate = useNavigate(); const navigate = useNavigate();
const { data, isLoading, isError, error } = useTenants(); const { data, isLoading, isError } = useTenants();
const { mutate: chooseTenant, isPending } = useSelectTenant(() => { const { mutate: chooseTenant, isPending } = useSelectTenant(() => {
navigate("/dashboard"); navigate("/dashboard");
}); });
const handleTenantselection = (tenantId) => { const { mutate: handleLogout, isPending: isLogouting } = useLogout();
const handleTenantSelection = (tenantId) => {
setPendingTenant(tenantId); setPendingTenant(tenantId);
localStorage.setItem("ctnt", tenantId); localStorage.setItem("ctnt", tenantId);
chooseTenant(tenantId); chooseTenant(tenantId);
}; };
const {mutate:handleLogout,isPending:isLogouting} = useLogout()
// Auto-select if already stored
useEffect(() => { useEffect(() => {
if (localStorage.getItem("ctnt")) { const storedTenant = localStorage.getItem("ctnt");
chooseTenant(localStorage.getItem("ctnt")) if (storedTenant) {
chooseTenant(storedTenant);
} }
}, [navigate]); }, []);
// Auto-select if only one tenant
useEffect(() => { useEffect(() => {
if (!isLoading && data?.data?.length === 1) { if (!isLoading && data?.data?.length === 1) {
const tenant = data.data[0]; const tenant = data.data[0];
handleTenantselection(tenant.id); handleTenantSelection(tenant.id);
} }
}, [isLoading, data]); }, [isLoading, data]);
if (isLoading) return <Loader />; // Show loader if:
// - initial loading
if (isLoading) { // - only one tenant (auto-selecting)
// - user manually selecting
if (
isLoading ||
isPending ||
(data?.data?.length === 1 && pendingTenant !== null)
) {
return <Loader />; return <Loader />;
} }
@ -48,7 +56,6 @@ const TenantSelectionPage = () => {
); );
} }
return ( return (
<div className="container-fluid"> <div className="container-fluid">
{/* Logo */} {/* Logo */}
@ -65,20 +72,24 @@ const TenantSelectionPage = () => {
<div className="text-center mb-4"> <div className="text-center mb-4">
<p className="fs-4 fw-bold mb-1">Welcome</p> <p className="fs-4 fw-bold mb-1">Welcome</p>
<p className="fs-6 fs-md-5"> <p className="fs-6 fs-md-5">
Please select which dashboard you want to explore!!! Please select which dashboard you want to explore!
</p> </p>
<div onClick={()=>handleLogout()}> <div onClick={() => handleLogout()}>
{isLogouting ? "Please Wait...":<span className="fs-6 fw-semibold cursor-pointer text-decoration-underline"><i className='bx bx-log-out'></i>SignOut</span>} {isLogouting ? (
"Please Wait..."
) : (
<span className="fs-6 fw-semibold cursor-pointer text-decoration-underline">
<i className="bx bx-log-out"></i> Sign Out
</span>
)}
</div> </div>
</div> </div>
{/* Card Section */} {/* Tenant Cards */}
<div className="row justify-content-center g-4 "> <div className="row justify-content-center g-4">
{data?.data.map((tenant) => ( {data?.data.map((tenant) => (
<div key={tenant.id} className="col-12 col-md-10 col-lg-8"> <div key={tenant.id} className="col-12 col-md-10 col-lg-8">
<div className="d-flex flex-column flex-md-row gap-4 align-items-center align-items-md-start p-3 border rounded shadow-sm bg-white h-100"> <div className="d-flex flex-column flex-md-row gap-4 align-items-center align-items-md-start p-3 border rounded shadow-sm bg-white h-100">
{/* Image */} {/* Image */}
<div className="flex-shrink-0 text-center"> <div className="flex-shrink-0 text-center">
<img <img
@ -95,12 +106,10 @@ const TenantSelectionPage = () => {
{/* Content */} {/* Content */}
<div className="d-flex flex-column text-start gap-2 w-100"> <div className="d-flex flex-column text-start gap-2 w-100">
{/* Title */}
<p className="fs-5 fs-md-4 text-dark fw-semibold mb-1"> <p className="fs-5 fs-md-4 text-dark fw-semibold mb-1">
{tenant?.name} {tenant?.name}
</p> </p>
{/* Industry */}
<div className="d-flex flex-wrap gap-2 align-items-center"> <div className="d-flex flex-wrap gap-2 align-items-center">
<p className="fw-semibold m-0">Industry:</p> <p className="fw-semibold m-0">Industry:</p>
<p className="m-0 text-muted"> <p className="m-0 text-muted">
@ -108,21 +117,19 @@ const TenantSelectionPage = () => {
</p> </p>
</div> </div>
{/* Description */}
{tenant?.description && ( {tenant?.description && (
<p className="text-start text-wrap text-muted small m-0"> <p className="text-start text-wrap text-muted small m-0">
{tenant?.description} {tenant?.description}
</p> </p>
)} )}
{/* Button */}
<button <button
className="btn btn-primary btn-sm mt-2 align-self-start" className="btn btn-primary btn-sm mt-2 align-self-start"
onClick={() => handleTenantselection(tenant?.id)} onClick={() => handleTenantSelection(tenant?.id)}
disabled={pendingTenant === tenant.id && isPending} disabled={pendingTenant === tenant.id && isPending}
> >
{isPending && pendingTenant === tenant.id {pendingTenant === tenant.id && isPending
? "Please Wait.." ? "Please Wait..."
: "Go To Dashboard"} : "Go To Dashboard"}
</button> </button>
</div> </div>
@ -131,8 +138,8 @@ const TenantSelectionPage = () => {
))} ))}
</div> </div>
</div> </div>
); );
}; };
export default TenantSelectionPage; export default TenantSelectionPage;

View File

@ -0,0 +1,237 @@
import React, { createContext, useContext, useState } from "react";
import moment from "moment";
import Breadcrumb from "../../components/common/Breadcrumb";
import CollectionList from "../../components/collections/CollectionList";
import { useModal } from "../../hooks/useAuth";
import { FormProvider, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { DateRangePicker1 } from "../../components/common/DateRangePicker";
import { isPending } from "@reduxjs/toolkit";
import ConfirmModal from "../../components/common/ConfirmModal";
import showToast from "../../services/toastService";
import { useMarkedPaymentReceived } from "../../hooks/useCollections";
import GlobalModel from "../../components/common/GlobalModel";
import AddPayment from "../../components/collections/AddPayment";
import ViewCollection from "../../components/collections/ViewCollection";
import ManageCollection from "../../components/collections/ManageCollection";
import PreviewDocument from "../../components/Expenses/PreviewDocument";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import {
ADDPAYMENT_COLLECTION,
ADMIN_COLLECTION,
CREATE_COLLECTION,
EDIT_COLLECTION,
VIEW_COLLECTION,
} from "../../utils/constants";
import AccessDenied from "../../components/common/AccessDenied";
const CollectionContext = createContext();
export const useCollectionContext = () => {
const context = useContext(CollectionContext);
if (!context) {
window.location = "/dashboard";
showToast("Out of Context Happend inside Collection Context", "warning");
}
return context;
};
const CollectionPage = () => {
const [viewCollection, setViewCollection] = useState(null);
const [makeCollection, setCollection] = useState({
isOpen: false,
invoiceId: null,
});
const [ViewDocument, setDocumentView] = useState({
IsOpen: false,
Image: null,
});
const [processedPayment, setProcessedPayment] = useState(null);
const [addPayment, setAddPayment] = useState({
isOpen: false,
invoiceId: null,
});
const [showPending, setShowPending] = useState(false);
const [searchText, setSearchText] = useState("");
const isAdmin = useHasUserPermission(ADMIN_COLLECTION);
const canViewCollection = useHasUserPermission(VIEW_COLLECTION);
const canCreate = useHasUserPermission(CREATE_COLLECTION);
const canEditCollection = useHasUserPermission(EDIT_COLLECTION);
const canAddPayment = useHasUserPermission(ADDPAYMENT_COLLECTION);
const methods = useForm({
defaultValues: {
fromDate: moment().subtract(180, "days").format("DD-MM-YYYY"),
toDate: moment().format("DD-MM-YYYY"),
},
});
const { watch } = methods;
const [fromDate, toDate] = watch(["fromDate", "toDate"]);
const handleToggleActive = (e) => setShowPending(e.target.checked);
const contextMassager = {
setProcessedPayment,
setCollection,
setAddPayment,
addPayment,
setViewCollection,
viewCollection,
setDocumentView,
};
const { mutate: MarkedReceived, isPending } = useMarkedPaymentReceived(() => {
setProcessedPayment(null);
});
const handleMarkedPayment = (payload) => {
MarkedReceived(payload);
};
if (
isAdmin === undefined ||
canAddPayment === undefined ||
canEditCollection === undefined ||
canViewCollection === undefined ||
canCreate === undefined
) {
return <div className="text-center py-5">Checking access...</div>;
}
if (
!isAdmin &&
!canAddPayment &&
!canEditCollection &&
!canViewCollection &&
!canCreate
) {
return (
<AccessDenied
data={[{ label: "Home", link: "/" }, { label: "Collection" }]}
/>
);
}
return (
<CollectionContext.Provider value={contextMassager}>
<div className="container-fluid">
<Breadcrumb
data={[{ label: "Home", link: "/" }, { label: "Collection" }]}
/>
<div className="card my-3 py-2 px-sm-4 px-0">
<div className="row px-3">
<div className="col-12 col-md-3 mb-1">
<FormProvider {...methods}>
<DateRangePicker1 howManyDay={180} />
</FormProvider>
</div>
<div className="col-12 col-md-3 d-flex align-items-center gap-2 ">
<div className="form-check form-switch text-start align-items-center">
<input
type="checkbox"
className="form-check-input"
role="switch"
id="inactiveEmployeesCheckbox"
checked={showPending}
onChange={(e) => setShowPending(e.target.checked)}
/>
<label
className="form-check-label ms-0"
htmlFor="inactiveEmployeesCheckbox"
>
Show Pending
</label>
</div>
</div>
<div className="col-12 col-md-6 d-flex justify-content-between justify-content-md-end gap-4">
<div className="w-md-auto">
{" "}
<input
type="search"
value={searchText}
onChange={(e) => setSearchText(e.target.value)}
placeholder="Search Collection"
className="form-control form-control-sm"
/>
</div>
{(canCreate || isAdmin) && (
<button
className="btn btn-sm btn-primary"
type="button"
onClick={() =>
setCollection({ isOpen: true, invoiceId: null })
}
>
<i className="bx bx-plus-circle me-2"></i>
<span className="d-none d-md-inline-block">
Add New Collection
</span>
</button>
)}
</div>
</div>
</div>
<CollectionList
fromDate={fromDate}
toDate={toDate}
isPending={showPending}
searchString={searchText}
/>
{makeCollection.isOpen && (
<GlobalModel
isOpen={makeCollection.isOpen}
size="lg"
closeModal={() => setCollection({ isOpen: false, invoiceId: null })}
>
<ManageCollection
collectionId={makeCollection?.invoiceId ?? null}
onClose={() => setCollection({ isOpen: false, invoiceId: null })}
/>
</GlobalModel>
)}
{addPayment.isOpen && (
<GlobalModel
size="lg"
isOpen={addPayment.isOpen}
closeModal={() => setAddPayment({ isOpen: false, invoiceId: null })}
>
<AddPayment
onClose={() => setAddPayment({ isOpen: false, invoiceId: null })}
/>
</GlobalModel>
)}
{viewCollection && (
<GlobalModel
size="lg"
isOpen={viewCollection}
closeModal={() => setViewCollection(null)}
>
<ViewCollection onClose={() => setViewCollection(null)} />
</GlobalModel>
)}
{ViewDocument.IsOpen && (
<GlobalModel
isOpen
size="md"
key={ViewDocument.Image ?? "doc"}
closeModal={() => setDocumentView({ IsOpen: false, Image: null })}
>
<PreviewDocument imageUrl={ViewDocument.Image} />
</GlobalModel>
)}
<ConfirmModal
type="success"
header="Payment Successful Received"
message="Payment has been recored successfully."
isOpen={processedPayment?.isOpen}
loading={isPending}
onSubmit={() => handleMarkedPayment(processedPayment?.invoiceId)}
onClose={() => setProcessedPayment(null)}
/>
</div>
</CollectionContext.Provider>
);
};
export default CollectionPage;

View File

@ -38,6 +38,7 @@ import usePagination from "../../hooks/usePagination";
import { setProjectId } from "../../slices/localVariablesSlice"; import { setProjectId } from "../../slices/localVariablesSlice";
import { useHasUserPermission } from "../../hooks/useHasUserPermission"; import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import Pagination from "../../components/common/Pagination"; import Pagination from "../../components/common/Pagination";
import handleEmployeeExport from "../../components/Employee/handleEmployeeExport";
const EmployeeList = () => { const EmployeeList = () => {
const selectedProjectId = useSelector( const selectedProjectId = useSelector(
@ -134,26 +135,11 @@ const EmployeeList = () => {
const tableRef = useRef(null); const tableRef = useRef(null);
const handleExport = (type) => { const handleExport = (type) => {
if (!currentItems || currentItems.length === 0) return; handleEmployeeExport(type, employeeList, filteredData, searchText, tableRef);
switch (type) {
case "csv":
exportToCSV(currentItems, "employees");
break;
case "excel":
exportToExcel(currentItems, "employees");
break;
case "pdf":
exportToPDF(currentItems, "employees");
break;
case "print":
printTable(tableRef.current);
break;
default:
break;
}
}; };
const handleAllEmployeesToggle = (e) => { const handleAllEmployeesToggle = (e) => {
const isChecked = e.target.checked; const isChecked = e.target.checked;
setShowInactive(false); setShowInactive(false);
@ -663,17 +649,16 @@ const EmployeeList = () => {
</tr> </tr>
))} ))}
</tbody> </tbody>
</table> </table>
</div>
{displayData?.length > 0 && ( </div>
{displayData?.length > 0 && (
<Pagination <Pagination
currentPage={currentPage} currentPage={currentPage}
totalPages={totalPages} totalPages={totalPages}
onPageChange={paginate} onPageChange={paginate}
/> />
)} )}
</div>
</div>
</div> </div>
) : ( ) : (
<div className="card"> <div className="card">

View File

@ -186,8 +186,8 @@ const MasterPage = () => {
)} )}
</select> </select>
</div> </div>
<div className="col-12 col-md-9 d-flex justify-content-end align-items-center gap-2 mt-2 mt-md-0"> <div className="col-12 col-md-9 d-flex justify-content-between justify-content-md-end align-items-center gap-2 mt-2 mt-md-0">
<div className="col-6 col-md-3"> <div className="col-8 col-md-3">
<input <input
type="search" type="search"
className="form-control form-control-sm" className="form-control form-control-sm"

View File

@ -96,8 +96,8 @@ const ProjectPage = () => {
}, [data, isLoading, selectedStatuses]); }, [data, isLoading, selectedStatuses]);
if(isLoading) return <div className="page-min-h"><Loader/></div> if (isLoading) return <div className="page-min-h"><Loader /></div>
if(isError) return <div className="page-min-h d-flex justify-content-center align-items-center"><p>{error.message}</p></div> if (isError) return <div className="page-min-h d-flex justify-content-center align-items-center"><p>{error.message}</p></div>
return ( return (
<ProjectContext.Provider value={contextDispatcher}> <ProjectContext.Provider value={contextDispatcher}>
<div className="container-fluid"> <div className="container-fluid">
@ -128,9 +128,8 @@ const ProjectPage = () => {
<div className="d-flex gap-2 mb-2"> <div className="d-flex gap-2 mb-2">
<button <button
type="button" type="button"
className={`btn btn-sm p-1 ${ className={`btn btn-sm p-1 ${!listView ? "btn-primary" : "btn-outline-primary"
!listView ? "btn-primary" : "btn-outline-primary" }`}
}`}
onClick={() => setListView(false)} onClick={() => setListView(false)}
data-bs-toggle="tooltip" data-bs-toggle="tooltip"
data-bs-custom-class="tooltip" data-bs-custom-class="tooltip"
@ -140,9 +139,8 @@ const ProjectPage = () => {
</button> </button>
<button <button
type="button" type="button"
className={`btn btn-sm p-1 ${ className={`btn btn-sm p-1 ${listView ? "btn-primary" : "btn-outline-primary"
listView ? "btn-primary" : "btn-outline-primary" }`}
}`}
onClick={() => setListView(true)} onClick={() => setListView(true)}
data-bs-toggle="tooltip" data-bs-toggle="tooltip"
data-bs-custom-class="tooltip" data-bs-custom-class="tooltip"
@ -180,20 +178,22 @@ const ProjectPage = () => {
</div> </div>
</div> </div>
<div> {HasManageProject && (
{HasManageProject && ( <button <div className="ms-auto">
className="btn btn-sm btn-primary" <button
type="button" className="btn btn-sm btn-primary"
onClick={() => type="button"
setMangeProject({ isOpen: true, Project: null }) onClick={() =>
} setMangeProject({ isOpen: true, Project: null })
> }
<i className="bx bx-plus-circle me-2"></i> >
<span className="d-none d-md-inline-block"> <i className="bx bx-plus-circle me-2"></i>
Add New Project <span className="d-none d-md-inline-block">
</span> Add New Project
</button>)} </span>
</div> </button>
</div>
)}
</div> </div>
</div> </div>
</div> </div>

View File

@ -10,6 +10,7 @@ const AuthRepository = {
verifyOTP: (data) => api.postPublic("/api/auth/login-otp", data), verifyOTP: (data) => api.postPublic("/api/auth/login-otp", data),
register: (data) => api.postPublic("/api/auth/register", data), register: (data) => api.postPublic("/api/auth/register", data),
sendMail: (data) => api.postPublic("/api/auth/sendmail", data), sendMail: (data) => api.postPublic("/api/auth/sendmail", data),
getSubscription:(frequency)=> api.getPublic(`/api/market/list/subscription-plan?frequency=${frequency}`),
// Protected routes (require auth token) // Protected routes (require auth token)
logout: (data) => api.post("/api/auth/logout", data), logout: (data) => api.post("/api/auth/logout", data),
@ -17,7 +18,9 @@ const AuthRepository = {
changepassword: (data) => api.post("/api/auth/change-password", data), changepassword: (data) => api.post("/api/auth/change-password", data),
appmenu: () => api.get('/api/appmenu/get/menu'), appmenu: () => api.get('/api/appmenu/get/menu'),
selectTenant: (tenantId) => api.post(`/api/Auth/select-tenant/${tenantId}`), selectTenant: (tenantId) => api.post(`/api/Auth/select-tenant/${tenantId}`),
getTenantList: () => api.get("/api/Auth/get/user/tenants"), getTenantList: () => api.get("/api/Auth/get/user/tenants"),
//
}; };

View File

@ -0,0 +1,29 @@
import { api } from "../utils/axiosClient";
import { DirectoryRepository } from "./DirectoryRepository";
export const CollectionRepository = {
createNewCollection: (data) =>
api.post(`/api/Collection/invoice/create`, data),
updateCollection:(id,data)=>{
api.put(`/api/Collection/invoice/edit/${id}`,data)
},
getCollections: (pageSize, pageNumber,fromDate,toDate, isPending,isActive,projectId, searchString) => {
let url = `/api/Collection/invoice/list?pageSize=${pageSize}&pageNumber=${pageNumber}&isPending=${isPending}&isActive=${isActive}&searchString=${searchString}`;
const params = [];
if (fromDate) params.push(`fromDate=${fromDate}`);
if (toDate) params.push(`toDate=${toDate}`);
if(projectId) params.push(`projectId=${projectId}`)
if (params.length > 0) {
url += `&${params.join("&")}`;
}
return api.get(url);
},
makeReceivePayment:(data)=> api.post(`/api/Collection/invoice/payment/received`,data),
markPaymentReceived:(invoiceId)=>api.put(`/api/Collection/invoice/marked/completed/${invoiceId}`),
getCollection:(id)=>api.get(`/api/Collection/invoice/details/${id}`),
addComment:(data)=>api.post(`/api/Collection/invoice/add/comment`,data)
};

View File

@ -3,12 +3,12 @@ import { api } from "../utils/axiosClient";
const GlobalRepository = { const GlobalRepository = {
getDashboardProgressionData: ({ days = '', FromDate = '', projectId = '' }) => { getDashboardProgressionData: ({ days = '', FromDate = '', projectId = '' }) => {
let params; let params;
if(projectId == null){ if (projectId == null) {
params = new URLSearchParams({ params = new URLSearchParams({
days: days.toString(), days: days.toString(),
FromDate, FromDate,
}); });
}else{ } else {
params = new URLSearchParams({ params = new URLSearchParams({
days: days.toString(), days: days.toString(),
FromDate, FromDate,
@ -19,30 +19,72 @@ const GlobalRepository = {
return api.get(`/api/Dashboard/Progression?${params.toString()}`); return api.get(`/api/Dashboard/Progression?${params.toString()}`);
}, },
getDashboardAttendanceData: ( date,projectId ) => { getDashboardAttendanceData: (date, projectId) => {
return api.get(`/api/Dashboard/project-attendance/${projectId}?date=${date}`); return api.get(`/api/Dashboard/project-attendance/${projectId}?date=${date}`);
}, },
getDashboardProjectsCardData: () => { getDashboardProjectsCardData: () => {
return api.get(`/api/Dashboard/projects`); return api.get(`/api/Dashboard/projects`);
}, },
getDashboardTeamsCardData: (projectId) => { getDashboardTeamsCardData: (projectId) => {
const url = projectId const url = projectId
? `/api/Dashboard/teams?projectId=${projectId}` ? `/api/Dashboard/teams?projectId=${projectId}`
: `/api/Dashboard/teams`; : `/api/Dashboard/teams`;
return api.get(url); return api.get(url);
}, },
getDashboardTasksCardData: (projectId) => { getDashboardTasksCardData: (projectId) => {
const url = projectId const url = projectId
? `/api/Dashboard/tasks?projectId=${projectId}` ? `/api/Dashboard/tasks?projectId=${projectId}`
: `/api/Dashboard/tasks`; : `/api/Dashboard/tasks`;
return api.get(url); return api.get(url);
}, },
getExpenseData: (projectId, startDate, endDate) => {
let url = `api/Dashboard/expense/type`
const queryParams = [];
if (projectId) {
queryParams.push(`projectId=${projectId}`);
}
if (startDate) {
queryParams.push(`startDate=${startDate}`);
}
if (endDate) {
queryParams.push(`endDate=${endDate}`);
}
if (queryParams.length > 0) {
url += `?${queryParams.join("&")}`;
}
return api.get(url);
},
getExpenseStatus: (projectId) => api.get(`/api/Dashboard/expense/pendings${projectId ? `?projectId=${projectId}` : ""}`),
getExpenseDataByProject: (projectId, categoryId, months) => {
let url = `api/Dashboard/expense/monthly`
const queryParams = [];
if (projectId) {
queryParams.push(`projectId=${projectId}`);
}
if (categoryId) {
queryParams.push(`categoryId=${categoryId}`);
}
if (months) {
queryParams.push(`months=${months}`);
}
if (queryParams.length > 0) {
url += `?${queryParams.join("&")}`;
}
return api.get(url);
},
getAttendanceOverview: (projectId, days) => api.get(`/api/dashboard/attendance-overview/${projectId}?days=${days}`)
getAttendanceOverview:(projectId,days)=>api.get(`/api/dashboard/attendance-overview/${projectId}?days=${days}`)
}; };
export default GlobalRepository; export default GlobalRepository;

View File

@ -58,6 +58,7 @@ export const MasterRespository = {
"Document Type": (id) => api.delete(`/api/Master/document-type/delete/${id}`), "Document Type": (id) => api.delete(`/api/Master/document-type/delete/${id}`),
"Document Category": (id) => "Document Category": (id) =>
api.delete(`/api/Master/document-category/delete/${id}`), api.delete(`/api/Master/document-category/delete/${id}`),
"Payment Adjustment Head":(id,isActive)=>api.delete(`/api/Master/payment-adjustment-head/delete/${id}`,(isActive=false)),
getWorkCategory: () => api.get(`/api/master/work-categories`), getWorkCategory: () => api.get(`/api/master/work-categories`),
createWorkCategory: (data) => api.post(`/api/master/work-category`, data), createWorkCategory: (data) => api.post(`/api/master/work-category`, data),
@ -124,10 +125,15 @@ export const MasterRespository = {
api.put(`/api/Master/activity-group/edit/${serviceId}`, data), api.put(`/api/Master/activity-group/edit/${serviceId}`, data),
getActivitesByGroup: (activityGroupId) => getActivitesByGroup: (activityGroupId) =>
api.get(`api/master/activities?activityGroupId=${activityGroupId}`), api.get(`api/master/activities?activityGroupId=${activityGroupId}`),
deleteActivityGroup:(id)=>api.delete(`/api/Master/activity-group/delete/${id}`), deleteActivityGroup: (id) =>
api.delete(`/api/Master/activity-group/delete/${id}`),
deleteActivity: (id) => api.delete(`/api/Master/activity/delete/${id}`),
deleteActivity:(id)=>api.delete(`/api/Master/activity/delete/${id}`),
getOrganizationType: () => api.get("/api/Master/organization-type/list"), getOrganizationType: () => api.get("/api/Master/organization-type/list"),
getPaymentAdjustmentHead: (isActive) =>
api.get(`/api/Master/payment-adjustment-head/list?isActive=${isActive}`),
createPaymentAjustmentHead:(data)=>api.post(`/api/Master/payment-adjustment-head`, data),
updatePaymentAjustmentHead:(id,data)=>api.put(`/api/Master/payment-adjustment-head/edit/${id}`, data)
}; };

View File

@ -40,7 +40,7 @@ const ProjectRepository = {
api.get(`/api/project/allocation-histery/${id}`), api.get(`/api/project/allocation-histery/${id}`),
updateProjectsByEmployee: (id, data) => updateProjectsByEmployee: (id, data) =>
api.post(`/api/project/assign-projects/${id}`, data), api.post(`/api/project/assign-projects/${id}`, data),
projectNameList: () => api.get("/api/project/list/basic"), projectNameList: (provideAll) => api.get(`/api/project/list/basic?provideAll=${provideAll}`),
getProjectDetails: (id) => api.get(`/api/project/details/${id}`), getProjectDetails: (id) => api.get(`/api/project/details/${id}`),

View File

@ -53,6 +53,7 @@ import DailyProgrssReport from "../pages/DailyProgressReport/DailyProgrssReport"
import ProjectPage from "../pages/project/ProjectPage"; import ProjectPage from "../pages/project/ProjectPage";
import { ComingSoonPage } from "../pages/Misc/ComingSoonPage"; import { ComingSoonPage } from "../pages/Misc/ComingSoonPage";
import ImageGalleryPage from "../pages/Gallary/ImageGallaryPage"; import ImageGalleryPage from "../pages/Gallary/ImageGallaryPage";
import CollectionPage from "../pages/collections/CollectionPage";
const router = createBrowserRouter( const router = createBrowserRouter(
[ [
{ {
@ -94,7 +95,9 @@ const router = createBrowserRouter(
{ path: "/activities/task", element: <TaskPlannng /> }, { path: "/activities/task", element: <TaskPlannng /> },
{ path: "/activities/reports", element: <Reports /> }, { path: "/activities/reports", element: <Reports /> },
{ path: "/gallary", element: <ImageGalleryPage /> }, { path: "/gallary", element: <ImageGalleryPage /> },
{ path: "/expenses/:status?/:project?", element: <ExpensePage /> },
{ path: "/expenses", element: <ExpensePage /> }, { path: "/expenses", element: <ExpensePage /> },
{ path: "/collection", element: <CollectionPage /> },
{ path: "/masters", element: <MasterPage /> }, { path: "/masters", element: <MasterPage /> },
{ path: "/tenants", element: <TenantPage /> }, { path: "/tenants", element: <TenantPage /> },
{ path: "/tenants/new-tenant", element: <CreateTenant /> }, { path: "/tenants/new-tenant", element: <CreateTenant /> },

View File

@ -69,30 +69,6 @@ export const normalizeAllowedContentTypes = (allowedContentType) => {
return allowedContentType.split(","); return allowedContentType.split(",");
return []; return [];
}; };
export function localToUtc(dateString) {
if (!dateString || typeof dateString !== "string") return null;
const parts = dateString.trim().split("-");
if (parts.length !== 3) return null;
let day, month, year;
if (parts[0].length === 4) {
// Format: yyyy-mm-dd
[year, month, day] = parts;
} else {
// Format: dd-mm-yyyy
[day, month, year] = parts;
}
if (!day || !month || !year) return null;
const date = new Date(
Date.UTC(Number(year), Number(month) - 1, Number(day), 0, 0, 0)
);
return isNaN(date.getTime()) ? null : date.toISOString();
}
/** /**
* Flexible number formatter for currency, numbers, or percentages. * Flexible number formatter for currency, numbers, or percentages.
@ -113,7 +89,7 @@ export const formatFigure = (
type = "number", type = "number",
currency = "INR", currency = "INR",
locale = "en-US", locale = "en-US",
notation = "compact", notation = "standard", // standard or compact
compactDisplay = "short", compactDisplay = "short",
minimumFractionDigits = 0, minimumFractionDigits = 0,
maximumFractionDigits = 2, maximumFractionDigits = 2,
@ -135,3 +111,42 @@ export const formatFigure = (
return new Intl.NumberFormat(locale, formatterOptions).format(amount); return new Intl.NumberFormat(locale, formatterOptions).format(amount);
}; };
export function localToUtc(dateString) {
if (!dateString || typeof dateString !== "string") return null;
const parts = dateString.trim().split("-");
if (parts.length !== 3) return null;
let day, month, year;
if (parts[0].length === 4) {
// Format: yyyy-mm-dd
[year, month, day] = parts;
} else {
// Format: dd-mm-yyyy
[day, month, year] = parts;
}
if (!day || !month || !year) return null;
const date = new Date(
Date.UTC(Number(year), Number(month) - 1, Number(day), 0, 0, 0)
);
return isNaN(date.getTime()) ? null : date.toISOString();
}
export const formatCurrency = (amount, currency = "INR", locale = "en-US") => {
return new Intl.NumberFormat(locale, {
style: "currency",
notation: "compact",
compactDisplay: "short",
currency: currency,
minimumFractionDigits: 0,
maximumFractionDigits: 2,
}).format(amount);
};
export const countDigit = (num) => {
return Math.abs(num).toString().length;
};

View File

@ -72,7 +72,9 @@ axiosClient.interceptors.response.use(
if (status === 401 && !isRefreshRequest) { if (status === 401 && !isRefreshRequest) {
originalRequest._retry = true; originalRequest._retry = true;
const refreshToken = localStorage.getItem("refreshToken") || sessionStorage.getItem("refreshToken"); const refreshToken =
localStorage.getItem("refreshToken") ||
sessionStorage.getItem("refreshToken");
if ( if (
!refreshToken || !refreshToken ||
@ -87,7 +89,9 @@ axiosClient.interceptors.response.use(
try { try {
// Refresh token call // Refresh token call
const res = await axiosClient.post("/api/Auth/refresh-token", { const res = await axiosClient.post("/api/Auth/refresh-token", {
token: localStorage.getItem("jwtToken") || sessionStorage.getItem("jwtToken"), token:
localStorage.getItem("jwtToken") ||
sessionStorage.getItem("jwtToken"),
refreshToken, refreshToken,
}); });
@ -144,6 +148,11 @@ export const api = {
headers: { ...customHeaders }, headers: { ...customHeaders },
authRequired: false, authRequired: false,
}), }),
getPublic: (url, data = {}, customHeaders = {}) =>
apiRequest("get", url, data, {
headers: { ...customHeaders },
authRequired: false,
}),
// Authenticated routes // Authenticated routes
get: (url, params = {}, customHeaders = {}) => get: (url, params = {}, customHeaders = {}) =>

View File

@ -3,7 +3,6 @@ export const DURATION_TIME = 10; // minutes
export const ITEMS_PER_PAGE = 20; export const ITEMS_PER_PAGE = 20;
export const OTP_EXPIRY_SECONDS = 300; // OTP time export const OTP_EXPIRY_SECONDS = 300; // OTP time
export const BASE_URL = process.env.VITE_BASE_URL; export const BASE_URL = process.env.VITE_BASE_URL;
// export const BASE_URL = "https://api.marcoaiot.com"; // export const BASE_URL = "https://api.marcoaiot.com";
@ -50,7 +49,7 @@ export const DIRECTORY_ADMIN = "4286a13b-bb40-4879-8c6d-18e9e393beda";
export const DIRECTORY_MANAGER = "62668630-13ce-4f52-a0f0-db38af2230c5"; export const DIRECTORY_MANAGER = "62668630-13ce-4f52-a0f0-db38af2230c5";
export const DIRECTORY_USER = "0f919170-92d4-4337-abd3-49b66fc871bb"; export const DIRECTORY_USER = "0f919170-92d4-4337-abd3-49b66fc871bb";
// ========================Finance=========================================================
// -----------------------Expense---------------------------------------- // -----------------------Expense----------------------------------------
export const VIEW_SELF_EXPENSE = "385be49f-8fde-440e-bdbc-3dffeb8dd116"; export const VIEW_SELF_EXPENSE = "385be49f-8fde-440e-bdbc-3dffeb8dd116";
@ -66,6 +65,16 @@ export const PROCESS_EXPENSE = "ea5a1529-4ee8-4828-80ea-0e23c9d4dd11";
export const EXPENSE_MANAGE = "ea5a1529-4ee8-4828-80ea-0e23c9d4dd11"; export const EXPENSE_MANAGE = "ea5a1529-4ee8-4828-80ea-0e23c9d4dd11";
// --------------------------------Collection----------------------------
export const ADMIN_COLLECTION = "dbf17591-09fe-4c93-9e1a-12db8f5cc5de";
export const VIEW_COLLECTION = "c8d7eea5-4033-4aad-9ebe-76de49896830";
export const CREATE_COLLECTION = "b93141fd-dbd3-4051-8f57-bf25d18e3555";
export const EDIT_COLLECTION = "455187b4-fef1-41f9-b3d0-025d0b6302c3";
export const ADDPAYMENT_COLLECTION = "061d9ccd-85b4-4cb0-be06-2f9f32cebb72";
// ==========================================================================================
export const EXPENSE_REJECTEDBY = [ export const EXPENSE_REJECTEDBY = [
"d1ee5eec-24b6-4364-8673-a8f859c60729", "d1ee5eec-24b6-4364-8673-a8f859c60729",
"965eda62-7907-4963-b4a1-657fb0b2724b", "965eda62-7907-4963-b4a1-657fb0b2724b",
@ -145,5 +154,13 @@ export const PROJECT_STATUS = [
label: "Completed", label: "Completed",
}, },
]; ];
export const DEFAULT_EMPTY_STATUS_ID = "00000000-0000-0000-0000-000000000000";
export const EXPENSE_STATUS = {
daft:"297e0d8f-f668-41b5-bfea-e03b354251c8",
review_pending:"6537018f-f4e9-4cb3-a210-6c3b2da999d7",
payment_pending:"f18c5cfd-7815-4341-8da2-2c2d65778e27",
approve_pending:"4068007f-c92f-4f37-a907-bc15fe57d4d8",
process_pending:"61578360-3a49-4c34-8604-7b35a3787b95"
}
export const DEFAULT_EMPTY_STATUS_ID = "00000000-0000-0000-0000-000000000000";

View File

@ -51,7 +51,7 @@ export const convertShortTime = (dateString) => {
}; };
export const timeElapsed = (checkInTime, timeElapsedInHours) => { export const timeElapsed = (checkInTime, timeElapsedInHours) => {
const checkInDate = new Date( checkInTime.split( "T" )[ 0 ] ); const checkInDate = new Date(checkInTime.split("T")[0]);
const currentTime = new Date(); const currentTime = new Date();
@ -72,7 +72,7 @@ export const checkIfCurrentDate = (dateString) => {
return currentDate?.getTime() === inputDate?.getTime(); return currentDate?.getTime() === inputDate?.getTime();
}; };
export const formatNumber = (num) => { export const formatNumber = (num) => {
if (num == null || isNaN(num)) return "NA"; if (num == null || isNaN(num)) return "NA";
return Number.isInteger(num) ? num : num.toFixed(2); return Number.isInteger(num) ? num : num.toFixed(2);
}; };
@ -84,15 +84,25 @@ export const formatUTCToLocalTime = (datetime, timeRequired = false) => {
: moment.utc(datetime).local().format("DD MMM YYYY"); : moment.utc(datetime).local().format("DD MMM YYYY");
}; };
export const getCompletionPercentage = (completedWork, plannedWork)=> { export const getCompletionPercentage = (completedWork, plannedWork) => {
if (!plannedWork || plannedWork === 0) return 0; if (!plannedWork || plannedWork === 0) return 0;
const percentage = (completedWork / plannedWork) * 100; const percentage = (completedWork / plannedWork) * 100;
const clamped = Math.min(Math.max(percentage, 0), 100); const clamped = Math.min(Math.max(percentage, 0), 100);
return clamped.toFixed(2); return clamped.toFixed(2);
} }
export const getTenantStatus =(statusId)=>{ export const formatDate_DayMonth = (monthName, year) => {
return ActiveTenant === statusId ? " bg-label-success":"bg-label-secondary" if (!monthName || !year) return "";
try {
const shortMonth = monthName.substring(0, 3);
return `${shortMonth} ${year}`;
} catch {
return "";
}
};
export const getTenantStatus = (statusId) => {
return ActiveTenant === statusId ? " bg-label-success" : "bg-label-secondary"
} }

View File

@ -40,112 +40,57 @@ export const exportToExcel = (data, fileName = "data") => {
* @param {Array} data - Array of objects to export * @param {Array} data - Array of objects to export
* @param {string} fileName - File name for the PDF (optional) * @param {string} fileName - File name for the PDF (optional)
*/ */
export const exportToPDF = async (data, fileName = "data") => { const sanitizeText = (text) => {
if (!text) return "";
// Replace all non-ASCII characters with "?" or remove them
return text.replace(/[^\x00-\x7F]/g, "?");
};
export const exportToPDF = async (data, fileName = "data", columns = null, options = {}) => {
if (!data || data.length === 0) return; if (!data || data.length === 0) return;
// Create a new PDF document
const pdfDoc = await PDFDocument.create(); const pdfDoc = await PDFDocument.create();
const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
// Set up the font // Default options
const font = await pdfDoc.embedFont(StandardFonts.Helvetica); // Use Helvetica font const {
columnWidths = [], // array of widths per column
// Calculate column widths dynamically based on data content fontSizeHeader = 12,
const headers = Object.keys(data[0]); fontSizeRow = 10,
const rows = data.map(item => headers.map(header => item[header] || '')); rowHeight = 25,
} = options;
const getMaxColumnWidth = (columnIndex) => { const pageWidth = 1000;
let maxWidth = font.widthOfTextAtSize(headers[columnIndex], 12); const pageHeight = 600;
rows.forEach(row => { let page = pdfDoc.addPage([pageWidth, pageHeight]);
const cellText = row[columnIndex].toString(); const margin = 30;
maxWidth = Math.max(maxWidth, font.widthOfTextAtSize(cellText, 10)); let y = pageHeight - margin;
const headers = columns || Object.keys(data[0]);
// Draw headers
headers.forEach((header, i) => {
const x = margin + (columnWidths[i] ? columnWidths.slice(0, i).reduce((a, b) => a + b, 0) : i * 150);
page.drawText(header, { x, y, font, size: fontSizeHeader });
});
y -= rowHeight;
// Draw rows
data.forEach(row => {
headers.forEach((header, i) => {
const x = margin + (columnWidths[i] ? columnWidths.slice(0, i).reduce((a, b) => a + b, 0) : i * 150);
const text = row[header] || '';
page.drawText(text, { x, y, font, size: fontSizeRow });
}); });
return maxWidth + 10; // Padding for better spacing y -= rowHeight;
};
const columnWidths = headers.map((_, index) => getMaxColumnWidth(index)); if (y < margin) {
const tableX = 30; // X-coordinate for the table start page = pdfDoc.addPage([pageWidth, pageHeight]);
const rowHeight = 20; // Height of each row (can be adjusted) y = pageHeight - margin;
const maxPageHeight = 750; // Max available height for content (before a new page is added)
const pageMargin = 30; // Margin from the top of the page
let tableY = maxPageHeight; // Start Y position for the table
const maxPageWidth = 600; // Max available width for content (before a new page is added)
// Add the headers and rows to the page
const addHeadersToPage = (page, scaleFactor) => {
let xPosition = tableX;
headers.forEach((header, index) => {
page.drawText(header, {
x: xPosition,
y: tableY,
font,
size: 12 * scaleFactor, // Scale the header font size
color: rgb(0, 0, 0),
});
xPosition += columnWidths[index] * scaleFactor; // Adjust X position based on scaling
});
tableY -= rowHeight; // Move down after adding headers
};
// Add a new page and reset the table position
const addNewPage = (scaleFactor) => {
const page = pdfDoc.addPage([600, 800]);
tableY = maxPageHeight; // Reset Y position for the new page
addHeadersToPage(page, scaleFactor); // Re-add headers to the new page
return page;
};
// Create the first page and add headers
let page = pdfDoc.addPage([600, 800]);
// Check if the content fits within the page width, scale if necessary
const checkPageWidth = (row) => {
let totalWidth = columnWidths.reduce((acc, width) => acc + width, 0);
let scaleFactor = 1;
if (totalWidth > maxPageWidth) {
scaleFactor = maxPageWidth / totalWidth; // Scale down if necessary
} }
return scaleFactor;
};
// Function to check for page breaks when adding a new row
const checkPageBreak = () => {
if (tableY - rowHeight < pageMargin) {
page = addNewPage(scaleFactor); // Add a new page if there is no space for the next row
}
};
// Add rows to the PDF with pagination and horizontal scaling
rows.forEach(row => {
checkPageBreak(); // Check for page break before adding each row
const scaleFactor = checkPageWidth(row); // Get the scaling factor for the row
// Add headers to the first page and each new page with the same scale factor
if (tableY === maxPageHeight) {
addHeadersToPage(page, scaleFactor); // Add headers only on the first page
}
let xPosition = tableX;
row.forEach((value, index) => {
page.drawText(value.toString(), {
x: xPosition,
y: tableY,
font,
size: 10 * scaleFactor, // Scale the font size
color: rgb(0, 0, 0),
});
xPosition += columnWidths[index] * scaleFactor; // Adjust X position based on scaling
});
tableY -= rowHeight; // Move down to the next row position
}); });
// Serialize the document to bytes
const pdfBytes = await pdfDoc.save(); const pdfBytes = await pdfDoc.save();
// Trigger a download of the PDF
const blob = new Blob([pdfBytes], { type: 'application/pdf' }); const blob = new Blob([pdfBytes], { type: 'application/pdf' });
const link = document.createElement('a'); const link = document.createElement('a');
link.href = URL.createObjectURL(blob); link.href = URL.createObjectURL(blob);
@ -153,15 +98,110 @@ export const exportToPDF = async (data, fileName = "data") => {
link.click(); link.click();
}; };
/**
* Export JSON data to PDF in a card-style format
* @param {Array} data - Array of objects to export
* @param {string} fileName - File name for the PDF (optional)
*/
export const exportToPDF1 = async (data, fileName = "data") => {
if (!data || data.length === 0) return;
const pdfDoc = await PDFDocument.create();
const font = await pdfDoc.embedFont(StandardFonts.Helvetica);
const boldFont = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
const pageWidth = 600;
const pageHeight = 800;
const margin = 30;
const cardSpacing = 20;
const cardPadding = 10;
let page = pdfDoc.addPage([pageWidth, pageHeight]);
let y = pageHeight - margin;
for (const item of data) {
const title = item.ContactName || "";
const subtitle = `by ${item.CreatedBy || ""} on ${item.CreatedAt || ""}`;
const body = item.Note || "";
const cardHeight = 80 + (body.length / 60) * 14; // approximate height for body text
if (y - cardHeight < margin) {
page = pdfDoc.addPage([pageWidth, pageHeight]);
y = pageHeight - margin;
}
// Draw card border
page.drawRectangle({
x: margin,
y: y - cardHeight,
width: pageWidth - 2 * margin,
height: cardHeight,
borderColor: rgb(0.7, 0.7, 0.7),
borderWidth: 1,
color: rgb(1, 1, 1),
});
// Draw title
page.drawText(title, {
x: margin + cardPadding,
y: y - 20,
font: boldFont,
size: 12,
color: rgb(0.1, 0.1, 0.1),
});
// Draw subtitle
page.drawText(subtitle, {
x: margin + cardPadding,
y: y - 35,
font,
size: 10,
color: rgb(0.4, 0.4, 0.4),
});
// Draw body text (wrap manually)
const lines = body.match(/(.|[\r\n]){1,80}/g) || [];
lines.forEach((line, i) => {
page.drawText(line, {
x: margin + cardPadding,
y: y - 50 - i * 12,
font,
size: 10,
color: rgb(0.2, 0.2, 0.2),
});
});
y -= cardHeight + cardSpacing;
}
const pdfBytes = await pdfDoc.save();
const blob = new Blob([pdfBytes], { type: 'application/pdf' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = `${fileName}.pdf`;
link.click();
};
/** /**
* Print the HTML table by accepting the table element or a reference. * Print the HTML table by accepting the table element or a reference.
* @param {HTMLElement} table - The table element (or ref) to print * @param {HTMLElement} table - The table element (or ref) to print
*/ */
export const printTable = (table) => { export const printTable = (table) => {
if (table) { if (table) {
const newWindow = window.open("", "", "width=600,height=600"); // Open a new window const clone = table.cloneNode(true);
// Remove last column (Actions) from all rows
clone.querySelectorAll("tr").forEach((row) => {
row.removeChild(row.lastElementChild);
});
// Inject styles for the table and body const newWindow = window.open("", "", "width=600,height=600");
newWindow.document.write("<html><head><title>Print Table</title>"); newWindow.document.write("<html><head><title>Print Table</title>");
const style = document.createElement('style'); const style = document.createElement('style');
style.innerHTML = ` style.innerHTML = `
@ -171,16 +211,14 @@ export const printTable = (table) => {
th { background-color: #f2f2f2; } th { background-color: #f2f2f2; }
`; `;
newWindow.document.head.appendChild(style); newWindow.document.head.appendChild(style);
newWindow.document.write("</head><body>"); newWindow.document.write("</head><body>");
newWindow.document.write(table.outerHTML); // Write the table HTML to the new window newWindow.document.write(clone.outerHTML);
newWindow.document.write("</body></html>"); newWindow.document.write("</body></html>");
newWindow.document.close();
newWindow.document.close(); // Close the document stream
// Wait for the document to load before triggering print
newWindow.onload = () => { newWindow.onload = () => {
newWindow.print(); // Trigger the print dialog after the content is loaded newWindow.print();
}; };
} }
}; };